diff --git "a/609.jsonl" "b/609.jsonl" new file mode 100644--- /dev/null +++ "b/609.jsonl" @@ -0,0 +1,708 @@ +{"seq_id":"528359149","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n#import roslib\n#roslib.load_manifest('lancer_test')\nimport sys\nimport rospy\nimport time\nfrom sensor_msgs.msg import Joy\nfrom std_msgs.msg import Int8MultiArray\nimport cv2\nimport numpy as np\nfrom std_msgs.msg import String\nfrom sensor_msgs.msg import Image\nfrom cv_bridge import CvBridge, CvBridgeError\nfrom matplotlib import pyplot as plt\n\nstealing = 50\nthrottle = 40\n\nclass image_converter:\n def __init__(self):\n self.image_pub = rospy.Publisher(\"/contl_data\",Int8MultiArray, queue_size=1)\n self.bridge = CvBridge()\n #self.image_sub = rospy.Subscriber(\"/camera/rgb/image_raw\",Image,self.callback)\n self.image_sub = rospy.Subscriber(\"/usb_cam/image_raw\",Image,self.callback)\n\n def callback(self,data):\n global stealing\n global throttle\n data_list = Int8MultiArray()\n try:\n cv_image = self.bridge.imgmsg_to_cv2(data, \"bgr8\")\n except CvBridgeError as e:\n print(e)\n\n #RGB表色系からHSV表色系に変換\n #hsv_image = cv2.cvtColor(cv_image, cv2.COLOR_BGR2HSV)\n #hsv_image = cv2.cvtColor(cv_image, cv2.COLOR_BGR2HSV)\n #color_min = np.array([150,100,150])\n #color_max = np.array([180,255,255])\n #color_mask = cv2.inRange(hsv_image, color_min, color_max)\n #cv_image2 = cv2.bitwise_and(cv_image, cv_image, mask = color_mask)\n\n gray_image = cv2.cvtColor(cv_image[105:119,0:159] ,cv2.COLOR_BGR2GRAY)\n #histr = cv2.calcHist([gray_image],[0],None,[256],[0,256])\n #plt.plot(histr,color = 'k')\n #plt.show()\n ret, cv_image2 = cv2.threshold(gray_image, 150, 255, cv2.THRESH_BINARY_INV)\n thresh = 210\n max_pixel = 255\n ret, img_dst = cv2.threshold(gray_image, thresh, max_pixel, cv2.THRESH_BINARY)\n img_binary = img_dst /255\n line_data = np.sum(img_binary, axis=0)\n line_data_left = line_data[0:((line_data.shape[0]/2)-1)].sum()\n line_data_right = line_data[(line_data.shape[0]/2):(line_data.shape[0]-1)].sum()\n #print(\"left :{} right:{}\".format(line_data_left,line_data_right))\n cont_data = [float(line_data_left) - float(line_data_right)]\n #print(cont_data)\n cont_data = np.clip(cont_data, -50, 50)[0]\n cont_data = (cont_data -50) * -1\n print(cont_data)\n stealing = cont_data\n data_list.data = [int(throttle),int(stealing)]\n self.image_pub.publish(data_list)\n cv2.imshow(\"img_dst\",img_dst)\n cv2.waitKey(2)\n\n\ndef main():\n ic = image_converter()\n rospy.init_node('image_converter', anonymous=True)\n try:\n rospy.spin()\n except KeyboardInterrupt:\n print(\"shutting down\")\n cv2.destroyAllWindows()\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"lancer_ros_src/backup/line_trace.py","file_name":"line_trace.py","file_ext":"py","file_size_in_byte":2801,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"528345555","text":"def loadResults():\r\n ReadMarathon = open(\"marathon.csv\")\r\n runners = []\r\n for eachLine in ReadMarathon:\r\n info = eachLine.split(\",\")\r\n s = {}\r\n s['number'] = info[0]\r\n s['time'] = info[1]\r\n s['name'] = info[2]\r\n s['surname'] = info[3]\r\n runners.append(s)\r\n return runners\r\n\r\ndef displayTime(runnerList,RunnerNum):\r\n found = False\r\n for J in runnerList:\r\n if int(J['number']) == RunnerNum: \r\n print(J['name'])\r\n print(J['surname'])\r\n print(J['time'])\r\n found = True\r\n \r\n if found == False:\r\n print(\"This competitor does not exist\")\r\n \r\n \r\n \r\n \r\nsearch = \"yes\"\r\nwhile search == \"yes\": \r\n marathonR=loadResults()\r\n NumRunner = int(input(\"Enter the number of the runner: \"))\r\n displayTime(marathonR,NumRunner) \r\n search = input(\"Would you like to search another player? \") \r\n","sub_path":"Ex2.py","file_name":"Ex2.py","file_ext":"py","file_size_in_byte":951,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"159142184","text":"#!env/bin/python\n\"\"\"Lift JS\n\nUsage:\n main.py [-o ]\n\nOptions:\n -o , --output Specifies output file [default: a.out].\n\n\"\"\"\nimport Parser\nimport Optimizer\nimport sys\nfrom Generator import Generator\nfrom docopt import docopt\n\nif __name__ == '__main__':\n args = docopt(__doc__)\n input_file = args['']\n output_file = args['--output']\n ast = None\n try:\n with open(input_file, 'r') as f:\n Parser.build(\"Program\")\n source = f.read()\n ast = Parser.parse(source)\n except IOError:\n print('Error opening file %s. Please check the file or '\n 'the directory.' % input_file)\n sys.exit(1)\n\n if ast is None:\n error_list = list(Parser.error_list.keys())\n error_list.sort()\n for key in error_list:\n sys.stdout.write(Parser.error_list[key])\n sys.stdout.flush()\n sys.exit(-1)\n\n ast = Optimizer.optimize(ast)\n\n try:\n with open(output_file, 'w') as f:\n f.write(Generator.generate(ast))\n except IOError:\n print('Error writing to file %s. Please check the file or '\n 'the directory.' % output_file)\n sys.exit(1)\n","sub_path":"lift/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1218,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"586365282","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Dec 4 18:47:08 2017\n\n@author: danberenberg\n\"\"\"\n\nfrom subprocess import Popen, PIPE\nimport tensorflow as tf\nimport tensorflow.contrib.slim as slim # library to remove boilerplate code\nimport numpy as np\nimport random\nimport glob\nimport sys, os\nimport controller_utils as ut\nimport datetime\nimport warnings\nimport pickle\n\ndef save(data,filename):\n with open(filename,'wb') as f:\n pickle.dump(data,f)\n\ndef play_game_randomly(process,nsteps):\n \"\"\"\n Play the game randomly\n \"\"\"\n \n steps = 0\n \n left,right,space,up = random.randint(0,1),random.randint(0,1),random.randint(0,1),0\n \n while steps < nsteps:\n value = str(left) + str(right) + str(up) + str(space) + '\\n'\n ut.write_to_game(process,value)\n \n if steps % 2 == 0:\n left = random.randint(0, 1)\n right = random.randint(0, 1)\n #up = random.randint(0, 1)\n up = 0\n space = random.randint(0, 1)\n \n steps+=1\n \n print('Game ended.')\n value = str('d') + str('d') + str('d') + str('d') + '\\n'\n ut.write_to_game(process,value)\n wait_time = 0\n response = \"\"\n while (response != 'd'):\n ut.write_to_game(process,'k\\n')\n response = str(ut.read_from_game(process))\n wait_time+=1\n \n process.kill()\n\ndef random_action():\n # choose a random action index\n action_ind = random.randint(0,2)\n \n # initialize actions\n actions = np.zeros(3)\n \n actions[action_ind] = 1\n \n left = actions[0]\n right = actions[1]\n up = 0 # ship stays in middle of board\n space = actions[2]\n\n \n return left,right,up,space,action_ind\n\ndef verify_screenshot_directory(screenshot_dir):\n \"\"\"\n Find the next directory that is unoccupied to place screen shots into\n \"\"\"\n screenshot_dir = screenshot_dir.strip('/')\n if not os.path.isdir(screenshot_dir):\n print (\"[!] making a screenshot dir: {}\".format(screenshot_dir))\n os.makedirs(screenshot_dir)\n return screenshot_dir\n \n \n num = 1\n screenshot_dir_ = screenshot_dir\n \n while os.path.isdir(screenshot_dir_):\n #print (ut.BUFFER_LINE + \"trying {}\".format(screenshot_dir_))\n if glob.glob(screenshot_dir_+ '/*' ) == []:\n return screenshot_dir_\n \n screenshot_dir_ = screenshot_dir + str(num)\n num +=1\n \n if screenshot_dir_ != screenshot_dir:\n print (\"[!] making a screenshot dir: {}\".format(screenshot_dir_))\n os.makedirs(screenshot_dir_)\n return screenshot_dir_\n\n\ndef updateTargetNet(tfVars,tau):\n \"\"\"\n Update the target network's graph using the expriences of the behavior network\n \"\"\"\n \n nvars = len(tfVars)\n op_holder = []\n \n for ind,var in enumerate(tfVars[0:nvars//2]): # extracting only the behavior net's values\n \n # update the parallel target net parameter\n op_holder.append(tfVars[ind+nvars//2].assign((var.value()*tau) + ((1-tau)*tfVars[ind+nvars//2].value())))\n \n return op_holder\n\ndef updateTarget(op_holder,sess):\n \"\"\"\n Update the target network using the operations collected and updated in updateTargetNet\n \"\"\"\n for op in op_holder:\n sess.run(op)\n \nclass QNetwork():\n \"\"\"\n QNetwork Class code adapted from Arthur Juliani \n ----------------------------------------------\n [https://medium.com/@awjuliani/]\n \n QNetwork Architecture implemented from Mnih,Kavukcuoglu, Silver, et al\n ---------------------------------------------------------------------\n 'Human-level control through deep reinforcement learning'\n \n \"\"\"\n \n def __init__(self,h_size,name=''):\n \"\"\"\n Network recieves a flattened frame array from the game\n - The frame array is resized to an 84x84x1 image\n \n - The image is processed through 4 convolutional layers, ending\n with a one hot encoded action vector\n \"\"\"\n self.name = name\n \n print(\"[+] Initializing {}\".format(self.name))\n self.std = 0.1\n ###################### Input ####################\n\n self.frame_array = tf.placeholder(shape=[None,ut.X_SIZE*ut.Y_SIZE*ut.N_CHANNELS],dtype=tf.float32)\n \n self.in_image = tf.reshape(self.frame_array,shape=[-1,ut.X_SIZE,ut.Y_SIZE,ut.N_CHANNELS])\n \n ###################### ConvLayer1: 8x8x4x32 stride 4 ##################\n print (\"[+] Building ConvLayer1: 8x8x4x32 stride 4..\")\n self.w_conv1 = self.weights([8,8,4,32])\n \n # no biases .. ?\n #self.b_conv1 = self.biases([32])\n self.conv1 = self.cnv_lyr(self.in_image,self.w_conv1,[1,4,4,1])\n self.h_conv1 = tf.nn.relu(self.conv1)\n print(ut.BUFFER_LINE + \"[+] Built ConvLayer1: 8x8x4x32 stride 4\")\n \n ###################### ConvLayer2: 4x4x64 stride 2 ####################\n print (\"[+] Building ConvLayer2: 4x4x32x64 stride 4.. \")\n self.w_conv2 = self.weights([4,4,32,64])\n \n # no biases .. ?\n #self.b_conv2 = self.biases([64])\n self.conv2 = self.cnv_lyr(self.h_conv1,self.w_conv2,[1,2,2,1])\n self.h_conv2 = tf.nn.relu(self.conv2)\n print(ut.BUFFER_LINE + \"[+] Built ConvLayer2: 4x4x32x64 stride 2\")\n \n ###################### ConvLayer3: 3x3x64 stride 1 ####################\n print(\"[+] Building ConvLayer3: 3x3x64x64 stride 1.. \")\n self.w_conv3 = self.weights([3,3,64,64])\n \n # no biases .. ?\n #self.b_conv2 = self.biases([64])\n self.conv3 = self.cnv_lyr(self.h_conv2,self.w_conv3,[1,1,1,1])\n self.h_conv3 = tf.nn.relu(self.conv3)\n\n # take output of Conv3 and separate into Advantage and Value streams\n #self.streamAC,self.streamVC = tf.split(self.conv4,2,3)\n print(ut.BUFFER_LINE + \"[+] Built ConvLayer3: 3x3x64x64 stride 1\")\n \n ###################### ConvLayer4: 7x7x3 stride 1 ####################\n print(\"[+] Building ConvLayer4: 7x7x512x1 stride 1\")\n self.w_conv4 = self.weights([7,7,64,h_size])\n self.conv4 = self.cnv_lyr(self.h_conv3,self.w_conv4,[1,1,1,1])\n self.h_conv4 = tf.nn.relu(self.conv4)\n print(ut.BUFFER_LINE + \"[+] Built ConvLayer4: 7x7x512x1 stride 1\")\n \n ###################### Fully Connected (FC1): (3x3x64)x512 ############\n print(\"[+] Building Dual Layer: Separate Advantage and Value streams\")\n \n self.streamAC, self.streamVC = tf.split(self.h_conv4,2,3)\n \n self.streamA = slim.flatten(self.streamAC)\n self.streamV = slim.flatten(self.streamVC)\n \n xavier_init = tf.contrib.layers.xavier_initializer()\n \n self.AW = tf.Variable(xavier_init([h_size//2,3]))\n self.VW = tf.Variable(xavier_init([h_size//2,1]))\n \n self.Advantage = tf.matmul(self.streamA,self.AW)\n self.Value = tf.matmul(self.streamV,self.VW)\n \n print(ut.BUFFER_LINE + \"[+] Built Dual Layer: Separate Advantage and Value streams\")\n \n ###################### Q values and Initial weights ################### \n print(\"[+] Initializing parameters\")\n \n self.Qout = self.Value + tf.subtract(self.Advantage,tf.reduce_mean(self.Advantage,axis=1,keep_dims=True))\n self.predict = tf.argmax(self.Qout,1)\n \n self.targetQ = tf.placeholder(shape=[None],dtype=tf.float32)\n\n self.actions = tf.placeholder(shape=[None],dtype=tf.int32)\n\n self.actions_onehot = tf.one_hot(self.actions,3,dtype=tf.float32)\n \n self.Q = tf.reduce_sum(tf.multiply(self.Qout,self.actions_onehot),axis=1)\n\n self.TD_error = tf.square(self.targetQ-self.Q)\n self.loss = tf.reduce_mean(self.TD_error)\n \n self.trainer = tf.train.AdamOptimizer(learning_rate=0.0001)\n self.optimizer = self.trainer.minimize(self.loss)\n print()\n def weights(self,dims):\n \"\"\"\n Initialize a set of weights with dimensions\n \"\"\"\n initial_wts = tf.truncated_normal(dims,stddev=self.std)\n return tf.Variable(initial_wts)\n \n def biases(self,dims):\n \"\"\"\n Initialize a set of biases with dimensions\n \"\"\"\n initial_biases = tf.constant(0.1,shape=dims)\n return tf.Variable(initial_biases)\n \n def cnv_lyr(self,in_lyr,weight_vec,strides):\n return tf.nn.conv2d(in_lyr,weight_vec,strides=strides,padding=\"VALID\")\n \nclass ExperienceBuffer():\n \"\"\"\n Implementation of the Experience Replay buffer described in:\n \n QNetwork Architecture implemented from Mnih,Kavukcuoglu, Silver, et al\n ---------------------------------------------------------------------\n 'Human-level control through deep reinforcement learning'\n \n Adapted from Arthur Juliani\n ---------------------------------------------------------------------\n [https://medium.com/@awjuliani/]\n \"\"\"\n \n def __init__(self,buffer_size=10000):\n \"\"\"\n Initialize the empty buffer with size buffer_size and \n \"\"\"\n self.buffer = []\n self.buffer_size = buffer_size\n \n def add(self,experience):\n \"\"\"\n Add an experience to the buffer\n \"\"\"\n \n # determine whether the buffer is full - if it is,\n # remove the first k elements of the buffer where \n # current_buf_size = k + buffer_size_limit\n if len(self.buffer) + len(experience) >= self.buffer_size:\n self.buffer[0:(len(experience)+len(self.buffer))-self.buffer_size] = [] \n \n # add the experience\n self.buffer.extend(experience)\n \n def sample(self,size):\n \"\"\"\n Sample out size experiences from the buffer\n \"\"\"\n return np.reshape(np.array(random.sample(self.buffer,size)),[size,4])\n \n\n# parameter intialization\nBATCH_SIZE = 32\nUPDATE_FREQ = 2\nPLAY_FREQ = 3 # take action every 3 frames which is comprable to human speeds\nN_STEPS = 400\nN_EPISODES = 800\n\ngamma = 0.99\nstarting_epsilon = 1 # starting epsilon\nending_epsilon = 0.05 # decreases on some schedule until it reaches this epsilon\nannealing_steps = 5000 # number of steps to reduce starting_epsilon to ending_epsilon\npretraining_steps = 10000 # numbear of steps to play randomly and gather state information\n\ntau = 0.001 # rate at which target network is updated toward primary network\n\nh_size = 512\n\n# variable initialization\ntf.reset_default_graph()\nmainQN = QNetwork(h_size,name=\"DQN behavior\") # the behavior network\ntargetQN = QNetwork(h_size,name=\"DQN optimal\") # the target network\n\ninit = tf.global_variables_initializer()\nsaver = tf.train.Saver()\n\ntrainable_vars = tf.trainable_variables()\ntarget_ops = updateTargetNet(trainable_vars,tau)\n\n# initialize Experience Buffer\nbuff = ExperienceBuffer()\n\nepsilon = starting_epsilon\nstep_drop = (starting_epsilon - ending_epsilon)/annealing_steps\n\n# reward list over each episode\nrwrds = []\nsteps_ctr = []\ntotal_steps = 0\n\nleft,right,up,down = 0,0,0,0\n\n\nparams = [BATCH_SIZE,UPDATE_FREQ,PLAY_FREQ,N_STEPS,N_EPISODES,gamma,\n starting_epsilon,annealing_steps,pretraining_steps,tau,h_size,\n step_drop]\n\nparam_names = \"BATCH_SIZE,UPDATE_FREQ,PLAY_FREQ,N_STEPS,N_EPISODES,gamma,starting_epsilon,annealing_steps,pretraining_steps,tau,h_size,step_drop\".split(\",\")\n \nif __name__ == '__main__':\n with warnings.catch_warnings():\n warnings.simplefilter(\"ignore\")\n ########################### simulation setup ###############################\n ###########################################################################\n args = ut.setup_args()\n \n asteroids_location = args.ast_path\n out_dir = args.out_dir\n screenshot_location = args.picture_path\n screenshot_location = verify_screenshot_directory(screenshot_location)\n load_model = args.model_path\n # not output directory specified, create one inside \n # of this directory\n \n if load_model != None and not os.path.exists(load_model):\n sys.exit(\"[!] Could not locate {}\".format(load_model))\n \n \n if not out_dir:\n # make a rsz ( resize ) directory if necessary\n if not os.path.isdir(screenshot_location + \"/rsz\"):\n print (\"[!] making a resize photos dir: {}\".format(screenshot_location + \"/rsz\"))\n os.makedirs(screenshot_location + \"/rsz\")\n \n out_dir = screenshot_location + \"/rsz/\"\n \n #process = Popen([asteroids_location,screenshot_location + '/'],stdout=PIPE, stdin=PIPE)\n game_args = {\"screenshot_location\":screenshot_location,\n \"output_directory\":out_dir,\n 'load_pth':load_model,\n 'load':type(load_model) == str}\n \n \n ########################## simulation #####################################\n ###########################################################################\n left,right,space,up = random.randint(0,1),random.randint(0,1),random.randint(0,1),0\n \n #img_location = game_args['screenshot_location']\n #out_dir = game_args['output_directory']\n load_model = game_args['load']\n load_pth = game_args['load_pth']\n \n img_pth = screenshot_location.strip(\"/\") + \"/\" + \"*pgm\" # search string\n buffer_string = \"\"\n \n print()\n print(\"=\"*50)\n for p,n in zip(params,param_names):\n print(\"[*] {:<22}: {}\".format(n,p))\n print(\"=\"*50)\n print()\n #process = None\n begin = datetime.datetime.now().strftime(\"%m/%d/%Y - %H:%M:%S\")\n print (\"[!] Starting session at {}\".format(begin))\n with tf.Session() as sess:\n sess.run(init)\n \n if load_model == True:\n #print (\"[+] loading model: {}\".format(load_pth))\n checkpt = tf.train.get_checkpont_state(load_pth)\n saver.restore(sess,checkpt.model_checkpoint_path)\n \n dead = False\n for i in range(N_EPISODES):\n ########################### simulation setup ###############################\n ###########################################################################\n \n ep_buff = ExperienceBuffer() # new experience buffer\n \n if not os.path.isdir(screenshot_location + \"/rsz\"):\n print (\"[!] making a resize photos dir: {}\".format(screenshot_location + \"/rsz\"))\n os.makedirs(screenshot_location + \"/rsz\")\n \n # new regular expression\n img_pth = screenshot_location.strip(\"/\") + \"/\" + \"*pgm\"\n \n out_dir = screenshot_location + \"/rsz/\"\n dead = False\n # start up a game\n process = Popen([asteroids_location,screenshot_location + '/'],stdout=PIPE, stdin=PIPE) \n \n steps = 0 # reset steps\n \n ########################## simulation #####################################\n ###########################################################################\n state = None\n state_p1 = None\n score_t = None\n score_t1 = None\n buffer_string = \"\"\n running_reward = 0\n frame_buffer = ut.FrameBuffer()\n # do gradient step for nsteps\n while steps < N_STEPS and not dead:\n \n old_photos = set()\n curr_photos = set()\n steps+=1\n total_steps+=1\n \n if steps < 60:\n value = str(0) + str(0) + str(0) + str(0) + '\\n'\n ut.write_to_game(process,value)\n \n continue # lots of black screen before anythign happens\n else: \n if steps == 60:\n state,score_t,buffer_string,curr_photos,old_photos = ut.next_state_and_reward(old_photos,curr_photos,\n img_pth,screenshot_location,\n out_dir,buffer_string,epsilon,\n total_steps,-1) \n else:\n if steps % PLAY_FREQ == 0:\n \n # with probability epsilon or if training hasn't begun yet ... \n if total_steps < pretraining_steps or np.random.rand(1) < epsilon:\n left,right,up,space,act = random_action()\n value = str(left) + str(right) + str(up) + str(space) + '\\n'\n ut.write_to_game(process,value)\n action = act\n actions = np.zeros(3)\n actions[action] = 1\n \n else:\n # select an action\n if state != None:\n #print('getting an action')\n \n print(frame_buffer.stack)\n fb = np.vstack(frame_buffer.stack)\n while fb.shape[0] < 4:\n fb = np.vstack([fb,fb[-1]])\n print(fb)\n \n action = sess.run(mainQN.predict,\n feed_dict={mainQN.frame_array:np.reshape(fb,[1,\n 7056*ut.N_CHANNELS]\n )\n }\n )\n \n else:\n action = [-1] \n \n action = action[0]\n \n actions = np.zeros(3)\n actions[action] = 1\n \n if action == -1:\n actions[action] = 0\n \n \n # left right up down\n value = str(actions[0]) + str(actions[1]) + str(0) + str(actions[2]) + '\\n'\n ut.write_to_game(process,value)\n \n # get the next photo and resize it\n state_p1, score_t1, buffer_string,curr_photos,old_photos = ut.next_state_and_reward(old_photos,curr_photos,\n img_pth,screenshot_location,\n out_dir,buffer_string,epsilon,\n total_steps,action)\n terminal = 0\n #print(score_t1,score_t)\n if score_t1 == score_t:\n score_t1 -= 1000\n #print(\"[-] foul play {}\".format(steps))\n terminal = 0\n dead = True\n \n old_buff = frame_buffer.deep_copy()\n frame_buffer.add(state_p1)\n transition = [old_buff.stack,action,score_t1,frame_buffer.stack]\n #transition = [state,action,score_t1,state_p1]\n if state_p1 != None and state != None:\n ep_buff.add(np.reshape(transition,[1,4]))\n \n if total_steps > pretraining_steps:\n #print ('[!] here: steps --> {} total --> {}'.format(steps,total_steps))\n \n if epsilon > ending_epsilon:\n epsilon -= step_drop\n \n if steps % UPDATE_FREQ == 0 and steps != 0 and action != -1:\n #print('updating...')\n # sample out a random batch\n trainBatch = buff.sample(BATCH_SIZE)\n print (trainBatch[:,3].shape)\n stp1 = np.vstack(trainBatch[:,3])\n print(stp1.shape)\n stp1 = np.reshape(stp1,[32,7056*4])\n print(stp1)\n \n #stp1 = np.reshape(stp1,[32,4])\n # belief of the optimal action value of next state\n #print(\"maxQ\")\n #or exp in stp1:\n #print(exp)\n maxQ = sess.run(mainQN.predict,feed_dict={mainQN.frame_array:stp1})\n #,[-1,ut.N_CHANNELS*ut.X_SIZE*ut.Y_SIZE]))})\n \n # action value of previous state\n print(\"Q1\")\n Q1 = sess.run(mainQN.predict,feed_dict={mainQN.frame_array:stp1})\n print(\"Q2\")\n Q2 = sess.run(targetQN.Qout,feed_dict={targetQN.frame_array:stp1})\n \n #print(\"doubleQ\")\n doubleQ = Q2[range(BATCH_SIZE),Q1]\n \n #print(\"targetQ\")\n targetQ = trainBatch[:,2] + (gamma*doubleQ * terminal)\n \n #print(\"frame_arr\")\n frame_arr = np.vstack(trainBatch[:,0])\n print (trainBatch[:,0].shape)\n st = np.vstack(trainBatch[:,0])\n print(st.shape)\n print(st)\n if st.shape[0] != 128:\n while st.shape[0] < 128:\n st = np.vstack([st,st[-1]])\n \n print(st)\n print(st.shape)\n st = np.reshape(st,[32,7056*4])\n print(st)\n \n #print(\"myactions\")\n myactions = np.vstack(trainBatch[:,1])\n \n print(\"_\")\n _ = sess.run(mainQN.optimizer,feed_dict={mainQN.frame_array:st,\n mainQN.targetQ:targetQ,\n mainQN.actions:trainBatch[:,1]})\n updateTarget(target_ops,sess)\n print (\"[*] Updated model!\")\n else:\n \n value = str(0) + str(0) + str(0) + str(0) + '\\n'\n ut.write_to_game(process,value)\n frame = ut.next_frame_thats_it(curr_photos,old_photos,img_pth,screenshot_location,out_dir)\n #print(\"adding a frame\")\n frame_buffer.add(frame)\n \n # end update sequence \n if state_p1 != None:\n state = state_p1 \n score_t = score_t1\n \n if score_t != None:\n running_reward += score_t\n # finish the game\n buff.add(ep_buff.buffer)\n # process killed\n screenshot_location = verify_screenshot_directory(args.picture_path) # new shots directory\n process.kill()\n \n rwrds.append(running_reward/steps)\n steps_ctr.append(steps)\n #print (\"here we go again {} {}\".format(dead,screenshot_location))\n saver.save(sess,\"./model/model-\"+str(i)+\".ckpt\")\n save(rwrds,\"./pickles/avg_rwd_m{}\".format(str(i))+\".pkl\")\n save(steps_ctr,\"./pickles/step_ct_m{}\".format(str(i)+\".pkl\"))\n print(\"Saved model\")\n \n # make the new screen shot directory \n # reset the resized photo directory to trigger creation\n out_dir = None\n \n saver.save(sess,\"./model-\"+str(i)+\".ckpt\")\n\nend = datetime.datetime.now().strftime(\"%m/%d/%Y - %H:%M:%S\")\nprint (\"[!] Started at {}, ended at {}\".format(begin,end))\n \n","sub_path":"Controller/DQNcontroller.py","file_name":"DQNcontroller.py","file_ext":"py","file_size_in_byte":27031,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"244367048","text":"#!/usr/bin/python3\n\nfrom keras.applications import InceptionV3, ResNet50, Xception\nfrom keras.layers import Flatten, Dense, Input, Dropout\nfrom keras.models import Model\nfrom keras.optimizers import Adam, RMSprop, Adadelta, Adagrad\nfrom six.moves import cPickle\nimport keras\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport os\n\n__location__ = os.path.realpath(os.path.join(os.getcwd(), os.path.dirname(__file__)))\n\n# network and training\nEPOCHS = 30\nBATCH_SIZE = 35\nVERBOSE = 1\n# https://keras.io/optimizers\nOPTIMIZER = Adam(lr=0.001)\n# OPTIMIZER = RMSprop()\n# OPTIMIZER = Adadelta(lr=1.0, rho=0.95, epsilon=None, decay=0.0)\n# OPTIMIZER = Adagrad(lr=0.05)\n\n# Image processing layer\n# CNN = 'Xception'\n# CNN = 'IV3'\nCNN = \"RN50\"\n\n# Load data\nprint(\"...loading training data\")\nf = open((os.path.join(__location__, \"data.pkl\")), \"rb\")\nimg = cPickle.load(f)\nf.close()\n\nf = open((os.path.join(__location__, \"data_age.pkl\")), \"rb\")\nage = cPickle.load(f)\nf.close()\n\n\nimg = np.asarray(img, dtype=np.float32)\nage = np.asarray(age)\n\n# this is to normalize x since RGB scale is [0,255]\nimg /= 255.\n\nimg_final = []\nage_final = []\n\n# Shuffle images and split into train, validation and test sets\nrandom_no = np.random.choice(img.shape[0], size=img.shape[0], replace=False)\nfor i in random_no:\n img_final.append(img[i, :, :, :])\n age_final.append(age[i])\n\nimg_final = np.asarray(img_final)\nage_final = np.asarray(age_final)\n\n# Split images dataset\nk = int(len(img_final) / 6) # Decides split count\n\nimg_test = img_final[:k, :, :, :]\nage_test = age_final[:k]\n\nimg_valid = img_final[k: 2 * k, :, :, :]\nage_valid = age_final[k: 2 * k]\n\nimg_train = img_final[2 * k:, :, :, :]\nage_train = age_final[2 * k:]\n\nprint(\"img_train shape:\" + str(img_train.shape))\nprint(\"age_train shape:\" + str(age_train.shape))\nprint(\"img_valid shape:\" + str(img_valid.shape))\nprint(\"age_valid shape:\" + str(age_valid.shape))\nprint(\"img_test shape:\" + str(img_test.shape))\nprint(\"age_test shape:\" + str(age_test.shape))\n\n# First we need to create a model structure\n# input layer\nimage_input = Input(shape=img_train.shape[1:], name=\"image_input\")\n\nif CNN == \"IV3\":\n # Inception V3 layer with pre-trained weights from ImageNet\n # base_iv3_model = InceptionV3(include_top=False, weights=\"imagenet\")\n base_iv3_model = InceptionV3(weights=\"imagenet\")\n # Inception V3 output from input layer\n x = base_iv3_model(image_input)\n # flattening it #why?\n # flat_iv3 = Flatten()(output_vgg16)\nelif CNN == \"RN50\":\n # ResNet50 layer with pre-trained weights from ImageNet\n base_rn50_model = ResNet50(weights=\"imagenet\")\n # ResNet50 output from input layer\n x = base_rn50_model(image_input)\nelif CNN == \"Xception\":\n # Xception layer with pre-trained weights from ImageNet\n base_xp_model = Xception(weights=\"imagenet\")\n # Xception output from input layer\n x = base_xp_model(image_input)\n\n\n# We stack dense layers and dropout layers to avoid overfitting after that\nx = Dense(1000, activation=\"relu\")(x)\nx = Dropout(0.2)(x)\nx = Dense(1000, activation=\"relu\")(x)\nx = Dropout(0.2)(x)\n# x = Dense(240, activation=\"relu\")(x)\n# x = Dropout(0.1)(x)\n\n# and the final prediction layer as output (should be the main logistic regression layer)\n# predictions = Dense(1, activation='sigmoid', name='predictions')(x)\npredictions = Dense(1)(x)\n\n# Now that we have created a model structure we can define it\n# this defines the model with one input and one output\nmodel = Model(inputs=[image_input], outputs=predictions)\n\n# printing a model summary to check what we constructed\nprint(model.summary())\n\nmodel.compile(optimizer=OPTIMIZER, loss=\"mean_squared_error\", metrics=[\"MAE\", \"accuracy\"])\n\n# Save weights after every epoch\nif not os.path.exists(os.path.join(__location__, \"weights\")):\n os.makedirs(os.path.join(__location__, \"weights\"))\n\ncheckpoint = keras.callbacks.ModelCheckpoint(\n filepath=\"weights/weights.{epoch:02d}-{val_loss:.2f}.hdf5\",\n save_weights_only=True,\n period=1,\n)\n\n# Reduce learning rate\nreduceLROnPlat = keras.callbacks.ReduceLROnPlateau(\n monitor=\"val_loss\", factor=0.8, patience=3, verbose=1, min_lr=0.0001\n)\n\n# TensorBoard\n# how to use: $ tensorboard --logdir path_to_current_dir/Graph\n# Save log for tensorboard\nLOG_DIR_TENSORBOARD = os.path.join(__location__, \"tensorboard\")\nif not os.path.exists(LOG_DIR_TENSORBOARD):\n os.makedirs(LOG_DIR_TENSORBOARD)\n\ntbCallBack = keras.callbacks.TensorBoard(\n log_dir=LOG_DIR_TENSORBOARD,\n batch_size=BATCH_SIZE,\n histogram_freq=0,\n write_graph=True,\n write_images=True,\n)\nprint(\"tensorboard --logdir\", LOG_DIR_TENSORBOARD)\n\nhistory = model.fit(\n [img_train],\n [age_train],\n batch_size=BATCH_SIZE,\n epochs=EPOCHS,\n verbose=VERBOSE,\n validation_data=([img_valid], [age_valid]),\n callbacks=[tbCallBack, checkpoint, reduceLROnPlat],\n # callbacks=[tbCallBack, checkpoint],\n)\n\n# Path to save model\nPATHE_SAVE_MODEL = os.path.join(__location__, \"model-backup\")\n\n# Save weights after every epoch\nif not os.path.exists(PATHE_SAVE_MODEL):\n os.makedirs(PATHE_SAVE_MODEL)\n\n# serialize model to YAML\nmodel_yaml = model.to_yaml()\nwith open(os.path.join(PATHE_SAVE_MODEL, \"model.yaml\"), \"w\") as yaml_file:\n yaml_file.write(model_yaml)\n# serialize weights to HDF5\nmodel.save_weights(os.path.join(PATHE_SAVE_MODEL, \"model.h5\"))\nprint(\"Saved model to disk\")\n\nscore = model.evaluate([img_test], age_test, batch_size=BATCH_SIZE, verbose=VERBOSE)\n\nprint(\"\\nTest loss:\", score[0])\nprint(\"Test MAE:\", score[1])\nprint(\"Test accuracy:\", score[2])\n\n# Save all data in history\nwith open(os.path.join(PATHE_SAVE_MODEL, \"history.pkl\"), \"wb\") as f:\n cPickle.dump(history.history, f)\nf.close()\n\n# list all data in history\nprint(history.history.keys())\n# summarize history for accuracy\nplt.plot(history.history[\"acc\"])\nplt.plot(history.history[\"val_acc\"])\nplt.title(\"model accuracy\")\nplt.ylabel(\"accuracy\")\nplt.xlabel(\"epoch\")\nplt.legend([\"train\", \"test\"], loc=\"upper left\")\nplt.show()\n# summarize history for loss\nplt.plot(history.history[\"loss\"])\nplt.plot(history.history[\"val_loss\"])\nplt.title(\"model loss\")\nplt.ylabel(\"loss\")\nplt.xlabel(\"epoch\")\nplt.legend([\"train\", \"test\"], loc=\"upper left\")\nplt.show()\n","sub_path":"main_no_gender.py","file_name":"main_no_gender.py","file_ext":"py","file_size_in_byte":6199,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"419704621","text":"#============= enthought library imports =======================\n\n#============= standard library imports ========================\n\n#============= local library imports ==========================\n\nimport os\nfrom src.helpers import paths\nfrom src.graph.time_series_graph import TimeSeriesGraph\n\n\ndef extract_data(p):\n '''\n '''\n import csv\n reader = csv.reader(open(p, 'U'), delimiter = '\\t')\n x = []\n y = []\n\n max = 40000\n for i, row in enumerate(reader):\n if i == 0:\n continue\n\n if i == 1:\n t_zero = float(row[0])\n t = 0\n else:\n t = float(row[0]) - t_zero\n\n if i == max:\n break\n x.append(t)\n y.append(float(row[2]))\n\n return x, y\ndef plot_data(x, y, x1, y1):\n '''\n @type y: C{str}\n @param y:\n\n @type x1: C{str}\n @param x1:\n\n @type y1: C{str}\n @param y1:\n '''\n g = TimeSeriesGraph()\n\n g.new_plot(show_legend = True, zoom = True, pan = True)\n g.new_series(x = x, y = y)\n g.new_series(x = x1, y = y1)\n\n g.set_series_label('Inside')\n\n g.set_series_label('Outside', series = 1)\n\n g.configure_traits()\nif __name__ == '__main__':\n p1 = os.path.join(paths.data_dir, 'furnace_calibration', 'DPi32TemperatureMonitor002.txt')\n p2 = os.path.join(paths.data_dir, 'furnace_calibration', 'Eurotherm002.txt')\n\n x, y = extract_data(p1)\n x1, y1 = extract_data(p2)\n\n plot_data(x, y, x1, y1)\n\n#============= EOF ====================================\n","sub_path":"furnace_cal.py","file_name":"furnace_cal.py","file_ext":"py","file_size_in_byte":1538,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"96281115","text":"from astropy.table import Table\n\nfrom collections import OrderedDict\nfrom warnings import warn\n\n\nclass UndefinedCut(Exception):\n pass\n\n\nclass PureCountingCut(Exception):\n pass\n\n\nclass CutFlow:\n \"\"\"\n a class that keeps track of e.g. events/images that passed cuts or other\n events that could reject them \"\"\"\n\n def __init__(self, name=\"CutFlow\"):\n \"\"\"\n Parameters\n ----------\n name : string (default: \"CutFlow\")\n name for the specific instance\n \"\"\"\n self.cuts = OrderedDict()\n self.name = name\n warn(\n \"CutFlow is deprecated. Use ctapipe.core.Selector for similar \"\n \"functionality\",\n FutureWarning,\n )\n\n def count(self, cut, weight=1):\n \"\"\"\n counts an event/image at a given stage of the analysis\n\n Parameters\n ----------\n cut : string\n name of the cut/stage where you want to count\n weight : int or float, optional (default: 1)\n weight of the current element\n\n Notes\n -----\n If `cut` is not yet being tracked, it will simply be added\n Will be an alias to __getitem__\n \"\"\"\n if cut not in self.cuts:\n self.cuts[cut] = [None, weight]\n else:\n self.cuts[cut][1] += weight\n\n def set_cut(self, cut, function):\n \"\"\"\n sets a function that selects on whatever you want to count\n sets the counter corresponding to the selection criterion to 0\n that means: it overwrites whatever you counted before under this\n name\n\n Parameters\n ----------\n cut : string\n name of the cut/stage where you want to count\n function : function\n a function that is your selection criterion\n\n Notes\n -----\n add_cut and set_cut are aliases\n \"\"\"\n self.cuts[cut] = [function, 0]\n\n def set_cuts(self, cut_dict, clear=False):\n \"\"\"\n sets functions that select on whatever you want to count\n sets the counter corresponding to the selection criterion to 0\n that means: it overwrites whatever you counted before under this\n name\n\n Parameters\n ----------\n cut_dict : {string: functor} dictionary\n dictionary of {name: function} of cuts to add as your selection criteria\n clear : bool, optional (default: False)\n if set to `True`, clear the cut-dictionary before adding the new cuts\n\n Notes\n -----\n add_cuts and set_cuts are aliases\n \"\"\"\n\n if clear:\n self.cuts = OrderedDict()\n\n for cut, function in cut_dict.items():\n self.cuts[cut] = [function, 0]\n\n def _check_cut(self, cut):\n \"\"\"\n checks if `cut` is a valid name for a function to select on\n\n Parameters\n ----------\n cut : string\n name of the selection criterion\n\n Raises\n ------\n UndefinedCut if `cut` is not known\n PureCountingCut if `cut` has no associated function\n (i.e. manual counting mode)\n \"\"\"\n\n if cut not in self.cuts:\n raise UndefinedCut(\n \"unknown cut '{}' -- only know: {}\".format(\n cut, [a for a in self.cuts.keys()]\n )\n )\n elif self.cuts[cut][0] is None:\n raise PureCountingCut(f\"'{cut}' has no function associated\")\n\n def cut(self, cut, *args, weight=1, **kwargs):\n \"\"\"\n selects the function associated with `cut` and hands it all\n additional arguments provided. if the function returns `False`,\n the event counter is incremented.\n\n Parameters\n ----------\n cut : string\n name of the selection criterion\n args, kwargs: additional arguments\n anything you want to hand to the associated function\n weight : int or float, optional (default: 1)\n weight of the current element\n\n Returns\n -------\n True if the function evaluats to True\n False otherwise\n\n Raises\n ------\n UndefinedCut if `cut` is not known\n PureCountingCut if `cut` has no associated function\n (i.e. manual counting mode)\n \"\"\"\n\n self._check_cut(cut)\n\n if self.cuts[cut][0](*args, **kwargs):\n return True\n else:\n self.cuts[cut][1] += weight\n return False\n\n def keep(self, cut, *args, weight=1, **kwargs):\n \"\"\"\n selects the function associated with `cut` and hands it all\n additional arguments provided. if the function returns True,\n the event counter is incremented.\n\n Parameters\n ----------\n cut : string\n name of the selection criterion\n args, kwargs: additional arguments\n anything you want to hand to the associated function\n weight : int or float, optional (default: 1)\n weight of the current element\n\n Returns\n -------\n True if the function evaluats to True\n False otherwise\n\n Raises\n ------\n UndefinedCut if `cut` is not known\n PureCountingCut if `cut` has no associated function\n (i.e. manual counting mode)\n \"\"\"\n\n self._check_cut(cut)\n\n if self.cuts[cut][0](*args, **kwargs):\n self.cuts[cut][1] += weight\n return True\n else:\n return False\n\n def __call__(self, *args, **kwargs):\n \"\"\"\n creates an astropy table of the cut names, counted events and\n selection efficiencies\n prints the instance name and the astropy table\n\n Parameters\n ----------\n kwargs : keyword arguments\n arguments to be passed to the `get_table` function; see there\n\n Returns\n -------\n t : `astropy.table.Table`\n the table containing the cut names, counted events and\n efficiencies -- sorted in the order the cuts were added if not\n specified otherwise\n \"\"\"\n print(self.name)\n t = self.get_table(*args, **kwargs)\n print(t)\n return t\n\n def get_table(\n self, base_cut=None, sort_column=None, sort_reverse=False, value_format=\"5.3f\"\n ):\n \"\"\"\n creates an astropy table of the cut names, counted events and\n selection efficiencies\n\n Parameters\n ----------\n base_cut : string, optional (default: None)\n name of the selection criterion that should be taken as 100 %\n in efficiency calculation\n if not given, the criterion with the highest count is used\n sort_column : integer, optional (default: None)\n the index of the column that should be used for sorting the entries\n by default the table is sorted in the order the cuts were added\n (index 0: cut name, index 1: number of passed events, index 2: efficiency)\n sort_reverse : bool, optional (default: False)\n if true, revert the order of the entries\n value_format : string, optional (default: '5.3f')\n formatting string for the efficiency column\n\n Returns\n -------\n t : `astropy.table.Table`\n the table containing the cut names, counted events and\n efficiencies -- sorted in the order the cuts were added if not\n specified otherwise\n \"\"\"\n\n if base_cut is None:\n base_value = max([a[1] for a in self.cuts.values()])\n elif base_cut not in self.cuts:\n raise UndefinedCut(\n \"unknown cut '{}' -- only know: {}\".format(\n base_cut, [a for a in self.cuts.keys()]\n )\n )\n else:\n base_value = self.cuts[base_cut][1]\n\n t = Table(\n [\n [cut for cut in self.cuts.keys()],\n [self.cuts[cut][1] for cut in self.cuts.keys()],\n [self.cuts[cut][1] / base_value for cut in self.cuts.keys()],\n ],\n names=[\"Cut Name\", \"selected Events\", \"Efficiency\"],\n )\n t[\"Efficiency\"].format = value_format\n\n if sort_column is not None:\n t.sort(t.colnames[sort_column])\n # if sorted by column 0 (i.e. the cut name) default sorting (alphabetically) is\n # fine. if sorted by column 1 or 2 or `sort_reverse` is True,\n # revert the order of the table\n if (sort_column is not None and sort_column > 0) != sort_reverse:\n t.reverse()\n return t\n\n add_cut = set_cut\n add_cuts = set_cuts\n __getitem__ = count\n","sub_path":"ctapipe/utils/CutFlow.py","file_name":"CutFlow.py","file_ext":"py","file_size_in_byte":8701,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"569681378","text":"import cv2\nfrom recognize_server.face_recognizer import FaceRecognizer\nimport time\n\n\nif __name__ == '__main__':\n\n max_cost = 0\n first_max_cost = 0\n\n f = 0\n\n recognizer = FaceRecognizer()\n\n camera = cv2.VideoCapture('./xdemo_src_video/src.mp4') # 0 -> first camera\n\n fourcc = cv2.VideoWriter_fourcc(*'MP4V')\n out = cv2.VideoWriter('./xdemo_out_video/out.mp4', fourcc, 20.0, (640, 480))\n\n while True:\n\n ret, frame = camera.read() # get frame\n\n frame = cv2.resize(frame, (640, 480))\n\n print(frame.shape)\n\n t1 = time.clock()\n\n frame, face_ids = recognizer.recognize(frame) # recognize frame\n\n frame = cv2.resize(frame, (640, 480))\n\n t2 = time.clock()\n\n cost = t2-t1\n if max_cost < cost:\n if f == 0 and cost > 1:\n f = 1\n first_max_cost = cost\n else:\n max_cost = cost\n\n print(\"\\ncost: {} sec\".format(cost))\n print(\"first max cost: {} sec\".format(first_max_cost))\n print(\"max cost: {} sec\".format(max_cost))\n\n out.write(frame)\n\n cv2.imshow('frame', frame) # show frame in window\n\n # press 'q' to stop\n if cv2.waitKey(1) & 0xFF == ord('q'):\n break\n\n camera.release() # camera release\n out.release() # writer release\n cv2.destroyAllWindows() # close windows\n\n","sub_path":"xdemo/demo_recognize.py","file_name":"demo_recognize.py","file_ext":"py","file_size_in_byte":1383,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"313863646","text":"# import necessary packages\nimport numpy as np\nimport cv2\nimport os\nfrom imutils.paths import list_files\nimport argparse\nimport ffmpeg\n\n# check out the my stackoverflow answer below for this\n# https://stackoverflow.com/a/55747773/4699994\ndef check_rotation(path_video_file):\n # this returns meta-data of the video file in form of a dictionary\n meta_dict = ffmpeg.probe(path_video_file)\n\n # from the dictionary, meta_dict['streams'][0]['tags']['rotate'] is the key\n # we are looking for\n rotateCode = None\n if int(meta_dict['streams'][0]['tags']['rotate']) == 90:\n rotateCode = cv2.ROTATE_90_CLOCKWISE\n elif int(meta_dict['streams'][0]['tags']['rotate']) == 180:\n rotateCode = cv2.ROTATE_180\n elif int(meta_dict['streams'][0]['tags']['rotate']) == 270:\n rotateCode = cv2.ROTATE_90_COUNTERCLOCKWISE\n\n return rotateCode\n\n\ndef correct_rotation(frame, rotateCode):\n return cv2.rotate(frame, rotateCode)\n\n\n# construct argument parser\nap = argparse.ArgumentParser()\nap.add_argument(\"-i\", \"--input\", type=str, required=True,\n help='path to directory containing videos')\nap.add_argument(\"-o\", \"--output\", type=str, required=True,\n help=\"path to output directory\")\nap.add_argument(\"-c\", \"--confidence\", type=float, default=0.5,\n help=\"minimum probability to filter out weak predictions\")\n\n# --skip : We don’t need to detect and store every image because\n# adjacent frames will be similar. Instead, we’ll skip N frames\n# between detections. You can alter the default of 16 using this argument.\nap.add_argument(\"-s\", \"--skip\", type=int, default=16,\n help=\"# of frame to skip before applying face detection\")\n\nargs = vars(ap.parse_args())\n\n# path to caffe model\npath_caffemdel = \"..//DNN_MODELS//opencv_face_detector.caffemodel\"\npath_model_architecture = \"..//DNN_MODELS//opencv_face_detector.prototxt\"\n\n\n# load model\nprint(\"[INFO] loading model...\")\nnet = cv2.dnn.readNetFromCaffe(path_model_architecture, path_caffemdel)\n\n# store the total number of faces saved from all videos here\ntotal_faces_saved = 0\n\nvs = None # defined in to loop\n\n\n# loop over all videos in the directory\nfor vid_num, video_path in enumerate(list_files(args[\"input\"])):\n print(\"[INFO] extracting faces from video #{} ...\".format(vid_num))\n\n # open a pointer to the video file stream and initialize\n # the total number of frame read and save thus far\n vs = cv2.VideoCapture(video_path)\n read = 0\n\n # check if video requires rotation\n rotateCode = check_rotation(video_path)\n\n # loop over frames from the video file stream\n while True:\n # grab the frame from the file\n grabbed, frame = vs.read()\n\n # if frame not grabbed -> end of video\n if not grabbed:\n break\n\n # check if frame needs to be rotated\n if rotateCode is not None:\n frame = correct_rotation(frame, rotateCode)\n\n\n # increment total number of frames read thus far\n read +=1\n\n # check to see if we should skip this frame\n if read % args[\"skip\"] != 0:\n continue\n\n # grab the frame dims and construct blob\n h, w = frame.shape[:2]\n blob = cv2.dnn.blobFromImage(cv2.resize(frame, (300, 300)), 1.0,\n (300, 300), (104.0, 177.0, 123.0))\n\n # pass the blob through the network and obtain detections\n # and predictions\n net.setInput(blob)\n detections = net.forward()\n\n # ensure at least oe face was found\n if len(detections) > 0:\n # we're making assumption that each image has only ONE\n # face, so find bounding box with the largest confidence\n i = np.argmax(detections[0, 0, :, 2])\n confidence = detections[0, 0, i, 2]\n\n # ensure that the detections with the largest confidence also\n # meets our min_confidence test (i.e. filter out weak\n # detections)\n if confidence > args[\"confidence\"]:\n # compute (x, y) - coordinates of the bounding box for\n # the face and extract face ROI\n box = detections[0, 0, i, 3:7] * np.array([w, h, w, h])\n (startX, startY, endX, endY) = box.astype('int')\n face = frame[startY:endY, startX:endX]\n\n\n\n # save the cropped face\n p = os.path.sep.join([args['output'],\n \"{}.png\".format(str(total_faces_saved))])\n cv2.imwrite(p, face)\n total_faces_saved += 1\n print(\"[INFO] save {} to directory\".format(total_faces_saved))\n\n\n# do some clean up\nvs.release()\ncv2.destroyAllWindows()","sub_path":"Liveness_detection/get_example_from_videos.py","file_name":"get_example_from_videos.py","file_ext":"py","file_size_in_byte":4736,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"239028889","text":"\"\"\" Default urlconf for fitoera \"\"\"\n\nfrom django.conf import settings\nfrom django.conf.urls import include, patterns, url\nfrom django.views.generic import RedirectView\nfrom django.contrib import admin\n\n\nadmin.autodiscover()\n\n\ndef bad(request):\n \"\"\" Simulates a server error \"\"\"\n 1 / 0\n\nurlpatterns = patterns(\n '',\n\n url(r'^admin/', include(admin.site.urls)),\n url(r'^bad/$', bad),\n (r'^favicon\\.ico$', RedirectView.as_view(url='/static/favicon.ico')),\n\n url(r'', include('apps.base.urls')),\n url(r'^api/', include('apps.snippets.urls')),\n\n url(r'^api-auth/', include(\n 'rest_framework.urls', namespace='rest_framework'))\n)\n\n## In DEBUG mode, serve media files through Django.\nif settings.DEBUG:\n from django.contrib.staticfiles.urls import staticfiles_urlpatterns\n urlpatterns += staticfiles_urlpatterns()\n # Remove leading and trailing slashes so the regex matches.\n media_url = settings.MEDIA_URL.lstrip('/').rstrip('/')\n urlpatterns += patterns(\n '',\n (r'^%s/(?P.*)$' % media_url, 'django.views.static.serve',\n {'document_root': settings.MEDIA_ROOT}),\n )\n","sub_path":"fitoera/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1139,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"291653764","text":"#!/usr/bin/env python\n#\nimport pytest\nfrom functools import reduce\n# pytestmark = pytest.mark.skipif(False, reason=\"only run mannually\")\n# pytestmark = pytest.mark.needs_mantid\n\ninteractive = False\n\nimport os\nhere = os.path.dirname(__file__)\ndatadir = os.path.join(here, \"data\")\n\nimport numpy as np, histogram.hdf as hh\n\nimport unittest\nclass TestCase(unittest.TestCase):\n\n def test1(self):\n \"multiphonon.flutils\"\n from multiphonon.flutils import MDH2Histo\n h1 = MDH2Histo(os.path.join(datadir,'Al_md.h5'))\n assert np.abs(h1.getAttribute('Ei')-49.6743)<0.0001\n return\n \n def test2(self):\n \"multiphonon.flutils\"\n from multiphonon.flutils import MDH2Histo\n h1 = MDH2Histo(os.path.join(datadir,'Al_md.h5'), Ei = 50.0)\n assert np.abs(h1.getAttribute('Ei')-50.0)<0.0001\n return\n pass # end of TestCase\n\n\nif __name__ == \"__main__\":\n interactive = True\n unittest.main()\n \n# End of file \n","sub_path":"tests/flutils_TestCase.py","file_name":"flutils_TestCase.py","file_ext":"py","file_size_in_byte":971,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"493148046","text":"from selenium import webdriver\nfrom datetime import datetime\nimport time\n\nclass Babyoye:\n def __init__(self):\n self.name = 'babyoye'\n\n def Driver(self):\n self.driver = webdriver.Firefox()\n\n def closeDriver(self):\n self.driver.close()\n\n def scrapeData(self, url, df):\n self.driver.get(url)\n driver = self.driver\n\n try:\n PID = url.split('/')[-1]\n except:\n PID = ''\n URL_raw = url\n try:\n Title = driver.find_element_by_css_selector('.quickview-inner-rgt').find_element_by_tag_name('h1').text\n except:\n Title = ''\n try:\n Brand = driver.find_element_by_css_selector('.orange-hd.txt_transform_UPC.font_size13').text\n except:\n Brand = ''\n try:\n Seller = driver.find_element_by_css_selector('.seller_details').find_elements_by_tag_name('span')[1].text\n except:\n Seller = ''\n try:\n IMG_medium = driver.find_element_by_css_selector('#Zoomer').find_element_by_tag_name('img').get_attribute('src')\n except:\n IMG_medium = ''\n try:\n IMG_large = driver.find_element_by_css_selector('#Zoomer').get_attribute('href')\n except:\n IMG_large = ''\n try:\n Price_mrp = driver.find_element_by_css_selector('#oldPriceAmntMainProd').text.strip()[1:].strip().replace(\",\",'')\n except:\n Price_mrp = ''\n try:\n Price_selling = driver.find_element_by_css_selector('#current_product_price').text.strip().replace(\",\",'')\n except:\n if Price_mrp !='':\n Price_selling = Price_mrp\n else:\n Price_selling = ''\n\n if Price_mrp == '' and Price_selling != '':\n Price_mrp = Price_selling\n\n try:\n color = driver.find_element_by_css_selector('.selection_color').find_elements_by_tag_name('img')\n color[0].click()\n except:\n pass\n try:\n pincode = driver.find_element_by_css_selector('#pincode')\n pincode.send_keys('110001')\n driver.find_element_by_id('deliveryAndCodDetailCheck').click()\n time.sleep(2)\n except:\n pass\n try:\n if int(float(Price_mrp))>499:\n Price_shipping = 0\n else:\n Price_shipping = 50\n except:\n Price_shipping = ''\n try:\n Delivery = driver.find_element_by_css_selector('.product-page-border-bottom.stockDaysDetail').text.replace('Delivers in','').replace('days','').strip()\n except:\n Delivery = ''\n try:\n COD = driver.find_element_by_css_selector('.stockDetailRow.stockCodDEtail').text.replace('Cash On Delivery','').strip()\n except:\n COD = ''\n try:\n EMI = ''\n except:\n EMI = ''\n try:\n breadcrums = driver.find_element_by_css_selector('.breadcrums').find_elements_by_tag_name('li')\n b = ''\n for bread in breadcrums:\n b = b + '|' + bread.text.strip()\n Category_path = b.replace('|||','|')[1:]\n except:\n Category_path = ''\n try:\n Description = str({'Description': driver.find_element_by_css_selector('.contents').text, \\\n 'Features':driver.find_element_by_id('tab6').find_element_by_css_selector('.contents').text})\n except:\n Description = ''\n try:\n Offers = ''\n except:\n Offers = ''\n try:\n Average_rating = driver.find_element_by_css_selector('.product-page-review-rating').find_elements_by_tag_name('h2')[1].find_element_by_tag_name('span').text\n except:\n Average_rating = ''\n try:\n Reviews = ''\n review_elem = driver.find_elements_by_css_selector('.reviews-count')[:10]\n for review in review_elem:\n try:\n rating = review.find_element_by_css_selector('.starRating').find_elements_by_tag_name('meta')[1].get_attribute('content')\n except:\n rating = ''\n try:\n author_date = review.find_element_by_css_selector('.starcol').text\n author = author_date.split(',')[0].strip()\n date = author_date.split(',')[1].strip()\n except:\n author = ''\n date = ''\n try:\n headline = review.find_element_by_tag_name('h2').text\n except:\n headline = ''\n try:\n description = review.find_element_by_tag_name('p').text\n except:\n description = ''\n Reviews = Reviews + str({'rating': str(rating), 'author':author, 'date':date, 'headline':headline,\\\n 'description':description}) + '||'\n Reviews = Reviews[:-2]\n except:\n Reviews = ''\n try:\n if 'out of stock' in driver.page_source.lower():\n Status = 'OUT OF STOCK'\n else:\n Status = 'IN STOCK' \n except:\n Status = 'IN STOCK'\n Condition = 'NEW'\n TimeStamp = str(datetime.now())\n\n nrow = df.shape[0]\n df.loc[nrow+1] = [PID, URL_raw, Title, Brand,Seller, IMG_medium, IMG_large, Price_mrp, Price_selling, Price_shipping, Delivery,\\\n COD,EMI, Category_path,Description,Offers,Average_rating,Reviews,Status,Condition,TimeStamp]\n\n return df\n","sub_path":"e-commerce-scraper3/20 April/babyoye.py","file_name":"babyoye.py","file_ext":"py","file_size_in_byte":5738,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"193971730","text":"#!/usr/bin/python\n\nimport random\nimport pdb\nimport time\nfrom math import cos, sin, pi, sqrt\n\nX_COORD=0\nY_COORD=1\nZ_COORD=2\n\nclass Mesh(object): \n \n def __init__(self): \n self.vertex_dict = dict() # Takes a vertex, returns the index of it. \n self.face_list = [] # faces are lists. These lists contain vertex indices.\n self.vertex_count=0\n \n def add_vertex(self, *args):\n if len(args)==1:\n x = round(args[0][X_COORD],10)\n y = round(args[0][Y_COORD],10)\n z = round(args[0][Z_COORD],10)\n elif len(args)==3:\n x = round(args[X_COORD],10)\n y = round(args[Y_COORD],10)\n z = round(args[Z_COORD],10)\n else: \n assert False\n if (x,y,z) not in self.vertex_dict:\n self.vertex_dict[(x,y,z)]= self.vertex_count+1 \n self.vertex_count += 1\n return (x,y,z)\n \n def add_face(self, v_list):\n v_list = map(self.add_vertex, v_list)\n self.face_list.append([self.vertex_dict[v] for v in v_list])\n \n def save_to_obj_file(self, output_file):\n with open(output_file,'w') as f:\n f.write(\"# Vertices\\n\")\n for i,(coordinate,index) in enumerate(sorted(self.vertex_dict.items(),key=lambda x:x[1])):\n assert i+1 == index\n f.write(\"v \"+str(coordinate[X_COORD])+\" \"+str(coordinate[Y_COORD])+\" \"+str(coordinate[Z_COORD])+\"\\n\") \n f.write(\"\\n\\n\")\n f.write(\"# Faces\\n\")\n for face in self.face_list:\n f.write(\"f \"+\"\".join([str(v_index)+\" \" for v_index in face])+\"\\n\")\n\ndef mean(l):\n return sum(l)/float(len(l))\n\ndef square(x):\n return x*x\n\ndef euclidean_distance(vector):\n return sqrt(sum([square(e) for e in vector]))\n\ndef tuple_subtraction(A,B):\n return tuple(map(lambda e:e[0]-e[1],zip(A,B)))\n\ndef tuple_addition(A,B):\n return tuple(map(lambda e:e[0]+e[1],zip(A,B)))\n\ndef dot_product(A,B):\n return tuple(map(lambda e:e[0]*e[1],zip(A,B)))\n\ndef normalize_vector(v):\n return tuple(map(lambda x:x/euclidean_distance(v),v))\n\ndef cross_product(*args): \n if len(args)==2:\n ax = args[0][X_COORD]\n ay = args[0][Y_COORD]\n az = args[0][Z_COORD]\n bx = args[1][X_COORD]\n by = args[1][Y_COORD]\n bz = args[1][Z_COORD]\n elif len(args)==6:\n ax = args[0]\n ay = args[1]\n az = args[2]\n bx = args[3]\n by = args[4]\n bz = args[5]\n else: \n assert False\n return (ay*bz-az*by,az*bx-ax*bz,ax*by-ay*bx)\n\ndef rotate_about_x_axis(angle_radians, *args):\n if len(args)==1:\n x0 = args[0][X_COORD]\n y0 = args[0][Y_COORD]\n z0 = args[0][Z_COORD]\n elif len(args)==3:\n x0 = args[X_COORD]\n y0 = args[Y_COORD]\n z0 = args[Z_COORD]\n else: \n assert False\n x = x0 \n y = cos(angle_radians)*y0-sin(angle_radians)*z0\n z = sin(angle_radians)*y0+cos(angle_radians)*z0\n return (x,y,z)\n\ndef rotate_about_y_axis(angle_radians, *args):\n if len(args)==1:\n x0 = args[0][X_COORD]\n y0 = args[0][Y_COORD]\n z0 = args[0][Z_COORD]\n elif len(args)==3:\n x0 = args[X_COORD]\n y0 = args[Y_COORD]\n z0 = args[Z_COORD]\n else: \n assert False\n x = cos(angle_radians)*x0+sin(angle_radians)*z0 \n y = y0\n z = -sin(angle_radians)*x0+cos(angle_radians)*z0\n return (x,y,z)\n\ndef rotate_about_z_axis(angle_radians, *args):\n if len(args)==1:\n x0 = args[0][X_COORD]\n y0 = args[0][Y_COORD]\n z0 = args[0][Z_COORD]\n elif len(args)==3:\n x0 = args[X_COORD]\n y0 = args[Y_COORD]\n z0 = args[Z_COORD]\n else: \n assert False\n x = cos(angle_radians)*x0-sin(angle_radians)*y0\n y = sin(angle_radians)*x0+cos(angle_radians)*y0\n z = z0\n return (x,y,z)\n\ndef get_equation_of_bisecting_circle(p1,p2,p3,radius):\n # https://math.stackexchange.com/questions/73237/parametric-equation-of-a-circle-in-3d-space \n p1_to_p2 = tuple_subtraction(p2,p1)\n p3_to_p2 = tuple_subtraction(p2,p3)\n cp = cross_product(p1_to_p2,p3_to_p2)\n if cp != (0,0,0): # i.e. if the 3 points do not form a line\n mean_vector = normalize_vector(tuple_addition(p1,p3)) # Note that this is not the bisecting coplanar vector (that's the variable \"a\" as we define it below)\n v = mean_vector # axis of rotation for the circle\n a = normalize_vector(cp) # unit vector perpendicular to axis\n else:\n v = p1_to_p2 # since the 3 points form a line, that line is the axis of rotation, so we can just choose either of the two vectors we calculated above\n arbitrary_vector = tuple_addition(v,(1,0,0)) # an arbitrary vector\n a = normalize_vector(cross_product(v,arbitrary_vector)) # we just want the variable a to be perpendicular to v, since the cross product of v and any arbitrary vector is perpendicular to both v and that arbitrary vector, this value works for a.\n b = normalize_vector(cross_product(a,v)) # unit vector perpendicular to axis\n c = p2 # point on axis\n \n ans_func = lambda theta: (\n c[X_COORD]+radius*cos(theta)*a[X_COORD]+radius*sin(theta)*b[X_COORD],\n c[Y_COORD]+radius*cos(theta)*a[Y_COORD]+radius*sin(theta)*b[Y_COORD],\n c[Z_COORD]+radius*cos(theta)*a[Z_COORD]+radius*sin(theta)*b[Z_COORD],\n )\n return ans_func\n\ndef cube(length=1):\n m=Mesh()\n m.add_face([\n (0,length,0),\n (length,length,0),\n (length,0,0),\n (0,0,0),\n ]) \n m.add_face([\n (0,0,length),\n (length,0,length),\n (length,length,length),\n (0,length,length),\n ]) \n m.add_face([\n (0,0,0),\n (length,0,0),\n (length,0,length),\n (0,0,length),\n ]) \n m.add_face([\n (0,length,length),\n (length,length,length),\n (length,length,0),\n (0,length,0),\n ]) \n m.add_face([\n (0,0,length),\n (0,length,length),\n (0,length,0),\n (0,0,0),\n ])\n m.add_face([\n (length,0,0),\n (length,length,0),\n (length,length,length),\n (length,0,length),\n ])\n return m\n\ndef cone(height=10, radius=5, num_triangles=360):\n # num_triangles is the number of triangles used for the part of the cone that isn't the base \n m=Mesh()\n for triangle_index in range(num_triangles):\n start_angle = 2*pi/float(num_triangles)*triangle_index\n end_angle = 2*pi/float(num_triangles)*(triangle_index+1)\n m.add_face([\n (0,0,height),\n (radius*sin(end_angle),radius*cos(end_angle),0),\n (radius*sin(start_angle),radius*cos(start_angle),0),\n ])\n m.add_face(\n [(radius*sin(2*pi/float(num_triangles)*triangle_index),radius*cos(2*pi/float(num_triangles)*triangle_index),0) for triangle_index in range(num_triangles)]\n )\n for triangle_index in range(num_triangles):\n start_angle = 2*pi/float(num_triangles)*triangle_index\n return m\n\ndef torus(inner_radius=5, outer_radius=10, num_segments=36, segment_precision=36):\n # num_segments refers to the number of segments we split the donut/torus into (we cut from the center outward)\n # segment_precision refers to the number of rectangles used per segment (this is precision along the other dimension)\n m=Mesh()\n assert inner_radius < outer_radius\n tube_radius = (outer_radius-inner_radius)/2.0\n for segment_index in range(num_segments): # index along the length of the tube (the long part if we're thinking about a regular donut)\n lengthwise_start_angle = 2*pi/float(num_segments)*segment_index\n lengthwise_end_angle = 2*pi/float(num_segments)*(segment_index+1)\n lengthwise_tube_start_center_x = (inner_radius+tube_radius)*cos(lengthwise_start_angle)\n lengthwise_tube_start_center_y = (inner_radius+tube_radius)*sin(lengthwise_start_angle)\n lengthwise_tube_start_center_z = 0\n lengthwise_tube_end_center_x = (inner_radius+tube_radius)*cos(lengthwise_end_angle)\n lengthwise_tube_end_center_y = (inner_radius+tube_radius)*sin(lengthwise_end_angle)\n lengthwise_tube_end_center_z = 0\n for rect_index in range(segment_precision): # index along the tube's circumference\n slicewise_tube_start_angle = 2*pi/float(segment_precision)*rect_index\n slicewise_tube_end_angle = 2*pi/float(segment_precision)*(rect_index+1)\n # innertube coordinates\n start_circle_coords = rotate_about_z_axis(lengthwise_start_angle, tube_radius*cos(slicewise_tube_start_angle),0,tube_radius*sin(slicewise_tube_start_angle))\n start_circle_coords_further_along_slice = rotate_about_z_axis(lengthwise_start_angle, tube_radius*cos(slicewise_tube_end_angle),0,tube_radius*sin(slicewise_tube_end_angle))\n end_circle_coords = rotate_about_z_axis(lengthwise_end_angle, tube_radius*cos(slicewise_tube_start_angle),0,tube_radius*sin(slicewise_tube_start_angle))\n end_circle_coords_further_along_slice = rotate_about_z_axis(lengthwise_end_angle, tube_radius*cos(slicewise_tube_end_angle),0,tube_radius*sin(slicewise_tube_end_angle))\n m.add_face([\n (lengthwise_tube_end_center_x+end_circle_coords[X_COORD],lengthwise_tube_end_center_y+end_circle_coords[Y_COORD],lengthwise_tube_end_center_z+end_circle_coords[Z_COORD]),\n (lengthwise_tube_end_center_x+end_circle_coords_further_along_slice[X_COORD],lengthwise_tube_end_center_y+end_circle_coords_further_along_slice[Y_COORD],lengthwise_tube_end_center_z+end_circle_coords_further_along_slice[Z_COORD]),\n (lengthwise_tube_start_center_x+start_circle_coords_further_along_slice[X_COORD],lengthwise_tube_start_center_y+start_circle_coords_further_along_slice[Y_COORD],lengthwise_tube_start_center_z+start_circle_coords_further_along_slice[Z_COORD]),\n (lengthwise_tube_start_center_x+start_circle_coords[X_COORD],lengthwise_tube_start_center_y+start_circle_coords[Y_COORD],lengthwise_tube_start_center_z+start_circle_coords[Z_COORD]),\n ])\n return m\n\ndef horn(precision=36):\n m = Mesh()\n '''\n points = [\n(0,0,0.0),\n(0,10,5.877852522924732),\n(0,20,9.510565162951535),\n(0,30,9.510565162951536),\n(0,40,5.877852522924733),\n(0,50,1.2246467991473533e-15),\n(0,60,-5.87785252292473),\n(0,70,-9.510565162951535),\n(0,80,-9.510565162951536),\n(0,90,-5.877852522924734),\n ]\n #'''\n #points = [(0,x*10,10*sin(2*pi*x/10.0)) for x in range(100)]\n num_points=1000\n def f(x):\n return sin(x)\n start_x = 0\n end_x = 10\n input_values = map(lambda x:(x/float(num_points-1))*(end_x-start_x)+start_x,range(num_points))\n points = [(10*x,10*f(x),0) for x in input_values]\n radii = [1 for i in range(num_points)]\n # first element of radii is None since the first point is the tip of the horn\n # last element is also None since we don't actually draw it, we just use it to determine the angle of the last circle\n radii[0]=None\n radii[-1]=None\n #assert (len(points)==len(radii))\n def get_circle_equation_for_point_index(point_index):\n assert point_index > 0 # can't be the first point\n assert point_index < len(points)-1 # can't be the last point\n return get_equation_of_bisecting_circle(points[point_index-1],points[point_index],points[point_index+1],radii[point_index])\n circle_equations = [None]+[get_circle_equation_for_point_index(i) for i in range(1,len(points)-1)]+[None]\n # we want our circles to connect and look like cylinders\n # thus, we should make the faces that connect in such a way that makes them look like \"straight\" cylinders rather than one that's been twisted and thus kind of look like twisted towels\n # we do this by making the triangles that go between the two circles as \"flat\" and \"straight\" as possible. \n # we aim to do this heuristically (which means we're too lazy to do it properly and bc we want it to be fast, but this also means that we still may get some twisted cylinders in there)\n # the heuristic that we're using is to make the triangles as much like right triangles as possible (in terms of angle)\n cirlce_point_lists_by_point_index = []\n current_focus_point = points[0]\n current_focus_point_neighbor = tuple_addition(points[0],(0,0,1)) # any point will work here since it doesn't matter who the neighbor is since the first tube is a cone\n for i,equation in enumerate(circle_equations):\n if equation is None:\n cirlce_point_lists_by_point_index.append(None)\n continue\n points_in_circle = [equation(2*pi*precision_index/float(precision)) for precision_index in range(precision)]\n nearest_point = None\n nearest_point_index = None\n closest_dist=float(\"inf\")\n for i,p in enumerate(points_in_circle): \n #dist = sum(tuple_addition(tuple(map(abs,p)),tuple(map(abs,current_focus_point)))) # we'll use the manhattan distance for speed\n #dist = sum(map(square,tuple_subtraction(p,current_focus_point))) # SSD\n dist = sum(cross_product(tuple_subtraction(current_focus_point_neighbor,current_focus_point),tuple_subtraction(p,current_focus_point)))\n if dist None:\n \"\"\"\n Do not return anything, modify nums in-place instead.\n \"\"\"\n n=len(nums)\n i, start, end=0, 0, n-1\n while i<=end:\n if nums[i]==0:\n if start!=i:\n nums[start], nums[i]=nums[i], nums[start]\n start+=1\n i+=1\n elif nums[i]==1:\n i+=1\n else:\n nums[i], nums[end]=nums[end], nums[i]\n end-=1\n\n","sub_path":"python/sort-colors.py","file_name":"sort-colors.py","file_ext":"py","file_size_in_byte":537,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"329551097","text":"from datetime import datetime\nimport re\nimport csv\nimport os\nimport io\nfrom bs4 import BeautifulSoup\nfrom time import sleep\nimport requests\nimport itertools\nfrom flask import request, make_response, session\nimport flask\nimport flask.views\n\napp = flask.Flask(__name__)\napp.secret_key = os.urandom(32)\n\nfirms_cities = open('gitignore/firms_cities.csv').read().split('\\r')\nfirms_cities_split = [i.split(',') for i in firms_cities]\n\n\nclass View(flask.views.MethodView):\n\n def get(self):\n return flask.render_template('index.html')\n\n @app.route('/download')\n def post(self):\n\n session.permanent = True\n # app.permanent_session_lifetime = timedelta(minutes=5)\n\n def append_weather_data():\n # appends \"weatherdata\"\n weatherdata.append([firm, printcity, alert, from_date, until_date,\n current_date, current_time, sky, feelslike, wind,\n barometer, visibility, humidity, dew, today, tmrw,\n two, three, four, five, six, seven, eight, nine])\n \n region = flask.request.form['reg']\n\n if region == 'midwest':\n midwest = [i for i in firms_cities_split if re.search('IL|IN|MI|OH|WI|IA|KS|MN|MO|NE|ND|SD|WV|KY', i[1])]\n midwest_cities = [i[0]+\", \"+i[1] for i in midwest]\n midwest_firms = [i[2:] for i in midwest]\n midwest_firms = [','.join(x) for x in midwest_firms]\n mwdict = dict(zip(midwest_firms, midwest_cities))\n my_dict = mwdict\n cities = midwest_cities\n elif region == 'dirty south':\n southeast = [i for i in firms_cities_split if re.search('FL|GA|NC|SC|AL|TN|MS', i[1])]\n southeast_cities = [i[0]+\", \"+i[1] for i in southeast]\n southeast_firms = [i[2:] for i in southeast]\n southeast_firms = [','.join(x) for x in southeast_firms]\n sedict = dict(zip(southeast_firms, southeast_cities))\n my_dict = sedict\n cities = southeast_cities\n elif region == 'southwest':\n southwest = [i for i in firms_cities_split if re.search('AR|OK|LA|TX', i[1])]\n southwest_cities = [i[0]+\", \"+i[1] for i in southwest]\n southwest_firms = [i[2:] for i in southwest]\n southwest_firms = [','.join(x) for x in southwest_firms]\n swdict = dict(zip(southwest_firms, southwest_cities))\n my_dict = swdict\n cities = southwest_cities\n elif region == 'northeast':\n northeast = [i for i in firms_cities_split if re.search('CT|ME|MA|NH|RI|VT|NJ|NY|PA|VA|DE|DC|MD', i[1])]\n northeast_cities = [i[0]+\", \"+i[1] for i in northeast]\n northeast_firms = [i[2:] for i in northeast]\n northeast_firms = [','.join(x) for x in northeast_firms]\n nedict = dict(zip(northeast_firms, northeast_cities))\n my_dict = nedict\n cities = northeast_cities\n elif region == 'west':\n west = [i for i in firms_cities_split if re.search('AZ|CO|ID|MT|NV|WY|UT|NM|AK|CA|HI|OR|WA|ON|AB', i[1])] \n west_cities = [i[0]+\", \"+i[1] for i in west]\n west_firms = [i[2:] for i in west]\n west_firms = [','.join(x) for x in west_firms]\n wdict = dict(zip(west_firms, west_cities))\n my_dict = wdict\n cities = west_cities\n \n weatherdata = []\n\n try:\n for firm, city in my_dict.iteritems():\n\n current_date = datetime.now().strftime('%m/%d/%y')\n current_time = datetime.now().strftime('%I:%M:%S')\n\n printcity = city.upper()\n city = re.sub(' ','',str(city))\n url = 'http://www.msn.com/en-us/weather/today/'+city+',United%20States/we-city?weadegreetype=F&ocid=INSWEPL10'\n r = requests.get(url)\n soup = BeautifulSoup(r.content)\n gdata = soup.find_all(\"div\",{\"class\":\"outer\"})\n\n for data in gdata:\n current = data.find_all('span',{'class':'current'})[0].text\n df = data.find_all('div',{'class':'type'})[0].text.encode('utf-8')\n conditions = data.find_all('div',{'class':'weather-info'})[0].text.encode('utf-8')\n forecast = data.find_all('ul',{'class':'forecast-list'})\n forecast_cond = re.findall('img.*title=\\\"(.*)\\\"', str(forecast))\n\n dates_temps = []\n for cast in forecast:\n cast = cast.text\n dates_temps.append([cast])\n\n forecast = [re.sub(r'\\\\n|\\\\|xb0|[\\[\\]\\']',' ',str(f)).strip() for f in dates_temps]\n forecast = str(forecast).split('%')\n dates_temps = [re.sub('^\\[\\'u|%$| ','',str(f)).strip()+'%' for f in forecast][:-1]\n Z = zip(dates_temps, forecast_cond)\n dates_temps_conds = [x for item in Z for x in item]\n dates_temps_conds = zip(dates_temps_conds[0::2], dates_temps_conds[1::2])\n dates_temps_conds = [re.sub('\\'|\\(|\\)', '', str(i)) for i in dates_temps_conds]\n\n today, tmrw, two, three, four, five, six, seven, eight, nine = dates_temps_conds[:]\n\n alert = data.find_all('span',{'id':'alertTime'})\n alert = data.find_all('span',{'id':'alertTime'})[0].text if alert else None\n alertexpl = data.find_all('p')[0].text\n # alertexpl2 = re.sub(\"(.{64})\", \"\\\\1\\n\", alertexpl, 0, re.DOTALL)\n\n conditions = conditions.strip().split('\\n')\n conditions = filter(None, conditions)\n conditions = [re.sub(r'[^\\x00-\\x7F]+',' ', i) for i in conditions] \n\n sky, feelslike, wind, barometer, visibility, humidity, dew = conditions[:]\n feelslike = re.sub('Feels Like', '', feelslike).strip()+' degrees'\n wind = re.sub('Wind', '', wind).strip()\n barometer = re.sub('Barometer', '', barometer).strip()\n visibility = re.sub('Visibility', '', visibility).strip()\n humidity = re.sub('Humidity', '', humidity).strip()\n dew = re.sub('Dew Point', '', dew).strip()+' degress'\n\n if alert is not None:\n try:\n alert = str(re.findall('^\\.\\.\\.[\\w /]+\\.\\.\\.', alertexpl)[0])+'\\n'+alert\n except Exception as ex:\n alert = alertexpl[0:len(alertexpl)/4]+'\\n'+alert\n # sys.stdout.flush()\n # errorlog.write(\"\\n'{0}' '{1}'\\nFirst try/catch block at '{2}'%:\\nError: '{3}'\\n'{4}'\\n\\n\".format(current_date, current_time, round(percentage, 2), ex, firm))\n\n if re.search('[0-9]{1,2}/[0-9]{1,2}/[0-9]{4}', alert):\n until_date = re.search('to ?[0-9]{1,2}/[0-9]{1,2}/[0-9]{4}', alert, flags=re.IGNORECASE)\n from_date = re.search('from ?[0-9]{1,2}/[0-9]{1,2}/[0-9]{4}', alert, flags=re.IGNORECASE)\n until_date = until_date.group()\n from_date = from_date.group()\n until_date = re.sub('to', '', until_date).strip()\n from_date = re.sub('from', '', from_date).strip()\n else:\n until_date = 'n/a'\n from_date = 'n/a'\n\n append_weather_data()\n\n except:\n pass\n\n if weatherdata:\n si = io.BytesIO()\n cw = csv.writer(si)\n [cw.writerow(row) for row in weatherdata]\n output = make_response(\"FIRM,CITY,ALERT,FROM,UNTIL,CURRENT DATE,CURRENT TIME,SKY CONDITIONS,FEELS LIKE,WIND,BAROMOTER,VISIBILITY,HUMIDITY,DEW,TODAY,TOMORROW,TWO DAYS OUT,THREE DAYS OUT,FOUR DAYS OUT,FIVE DAYS OUT,SIX DAYS OUT,SEVEN DAYS OUT,EIGHT DAYS OUT,NINE DAYS OUT\"+'\\n'+si.getvalue())\n output.headers[\"Content-Disposition\"] = \"attachment; filename=LIP_WEATHER_REPORT_\"+region.upper()+\".csv\"\n output.headers[\"Content-type\"] = \"text/csv\"\n return output\n\n else:\n flask.flash('No alerts for '+region+'.')\n return self.get()\n\napp.add_url_rule('/',\n view_func=View.as_view('main'), \n methods=['GET','POST'])\n\n\n# app.run(debug=True, use_reloader=False)","sub_path":"weatheralerts.py","file_name":"weatheralerts.py","file_ext":"py","file_size_in_byte":8642,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"634559396","text":"import cython_elipse as c\nimport numpy as np\n\n\ndef cythonized(x, y):\n array = np.zeros(shape=[x, y])\n a = 0.5 * 10\n b = 0.5 * 10\n a2 = a * a\n b2 = b * b\n c2 = 255 * 255\n cx = 0.5 * 10\n cy = 0.5 * 10\n a = c.calc(array, 5.0, 5.0, 255.0, 5.0, 5.0, x, y)\n return np.asarray(a)\n\n\ndef canvas(x, y):\n width, height = (x, y)\n y = np.linspace(0, height - 1, height)\n x = np.linspace(0, width - 1, width)\n xv, yv = np.meshgrid(x, y)\n return np.meshgrid(y, x), (int(height / 2), int(width / 2)), (height, width)\n\n\ndef function(x, y):\n (Y, X), (cx, cy), (height, width) = canvas(x, y)\n a = 0.5 * 10\n b = 0.5 * 10\n a2 = a * a\n b2 = b * b\n c2 = 255 * 255\n cx = 0.5 * 10\n cy = 0.5 * 10\n definition = \"np.sqrt(c2-(c2/b2)*((X-cy)**2)-(c2/a2)*((Y-cx)**2))\"\n # print(eval(definition))\n # Z = np.zeros(shape=[x,y])\n # for X in range(x):\n # for Y in range(y):\n # Z[X,Y]=eval(definition)\n # return Z\n return np.nan_to_num(np.clip(eval(definition), 0, 255))\n\n\nimport time\n\nix = 100\ns = time.time()\nx = 20\ny = 200\nfor i in range(ix):\n function(x, y)\nprint((time.time() - s) / ix)\nprint(function(x, y).astype(np.uint8))\n\ns = time.time()\nfor i in range(ix):\n cythonized(x, y)\nprint((time.time() - s) / ix)\nprint(cythonized(x, y).astype(np.uint8))\n","sub_path":"garbage/speed.py","file_name":"speed.py","file_ext":"py","file_size_in_byte":1330,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"176125115","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# In[1]:\n\n\nimport collections\nimport logging\nimport os\nimport pathlib\nimport re\nimport string\nimport sys\nimport time\n\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n\nimport tensorflow as tf\n\n\n# ## Download the Dataset\n\n# In[2]:\n\n\nimport numpy as np\nimport cv2\nimport xml.etree.ElementTree as ET\nimport argparse\nimport os\nimport re\nimport nltk\nnltk.download('punkt')\n\n\n# In[3]:\n\n\nfile_list = os.listdir('./IUXR_report')\nfile_list.sort()\n\n\n# In[4]:\n\n\nimage_path = []\ncaption_list = []\nfor file in file_list:\n caption_string = ''\n tree = ET.parse('./IUXR_report/' + file)\n root = tree.getroot()\n if root.find('parentImage') == None:\n continue;\n else:\n image_path.append('IUXR_png/'+root.find('parentImage').attrib['id']+'.png')\n for data in root.iter('AbstractText'):\n label = data.attrib['Label']\n if label == 'FINDINGS' and data.text != None:\n caption_string+=data.text\n if label == 'IMPRESSION' and data.text != None:\n caption_string+=data.text\n caption_list.append(caption_string)\n\n\n# In[5]:\n\n\nnew_report_list = []\nnew_image_name_list = []\n\ndef hasNumbers(inputString):\n return any(char.isdigit() for char in inputString)\n\nfor idx, report in enumerate(caption_list):\n new_report = report.lower().replace(\"..\", \".\")\n new_report = new_report.replace(\"'\", \"\")\n new_sentences = []\n # print(nltk.tokenize.sent_tokenize(new_report))\n for sentence in nltk.tokenize.sent_tokenize(new_report):\n new_sentence = sentence.replace(\"/\", \" / \")\n if \"xxxx\" not in sentence and not hasNumbers(sentence):\n new_sentences.append(sentence)\n new_report = ' ' + \" \".join(new_sentences) + ' '\n if len(new_report) > 0:\n new_report_list.append(new_report)\n new_image_name_list.append(image_path[idx])\n# print(image_path[idx])\n\n\n# In[6]:\n\n\ntop_k = 1000\ntokenizer = tf.keras.preprocessing.text.Tokenizer(num_words=top_k,\n oov_token=\"\",\n filters='!\"#$%&()*+-/:;=?@[\\]^_`{|}~')\ntokenizer.fit_on_texts(new_report_list)\n\ntokenizer.word_index[''] = 0\ntokenizer.index_word[0] = ''\ntrain_seqs = tokenizer.texts_to_sequences(new_report_list)\n\ncap_vector = tf.keras.preprocessing.sequence.pad_sequences(train_seqs, padding='post')\n\n\n# In[7]:\n\n\nBUFFER_SIZE = 500\nBATCH_SIZE = 32\n\ndef mapping(image_path, train_captions):\n img = tf.io.read_file(image_path)\n img = tf.image.decode_png(img, channels=3)\n img = tf.image.resize(img, (128, 128))\n img = tf.image.flip_up_down(img)\n img = tf.image.flip_left_right(img)\n img = img / 255.0 - 0.5\n train_captions = tf.dtypes.cast(train_captions, tf.float32)\n return img, train_captions\n\ndef mapping_origin(image_path, train_captions):\n img = tf.io.read_file(image_path)\n img = tf.image.decode_png(img, channels=3)\n img = tf.image.resize(img, (128, 128))\n img = img / 255.0 - 0.5\n train_captions = tf.dtypes.cast(train_captions, tf.float32)\n return img, train_captions\n\noriginal_image_name_list = new_image_name_list\noriginal_cap_vector = cap_vector\n\nnew_image_name_list = new_image_name_list[0:3500] \ncap_vector = cap_vector[0:3500] \n\nprint(original_image_name_list[3501:3700])\n\n# val_img_name_list = original_image_name_list[3500:3600]\n# cap_val_vector = original_cap_vector[3500:3600]\n\ndataset_train = tf.data.Dataset.from_tensor_slices((new_image_name_list, cap_vector)).map(mapping_origin)\ndataset_train_flip_picture = tf.data.Dataset.from_tensor_slices((new_image_name_list, cap_vector)).map(mapping)\n\ndataset_train = dataset_train.concatenate(dataset_train_flip_picture)\ndataset_train = dataset_train.shuffle(BUFFER_SIZE).batch(BATCH_SIZE)\ndataset_train = dataset_train.prefetch(buffer_size=tf.data.experimental.AUTOTUNE)\n\ndataset_val = tf.data.Dataset.from_tensor_slices((original_image_name_list[3501:3700], original_cap_vector[3501:3700])).map(mapping_origin)\ndataset_val = dataset_val.shuffle(BUFFER_SIZE).batch(BATCH_SIZE)\ndataset_val = dataset_val.prefetch(buffer_size=tf.data.experimental.AUTOTUNE)\nprint(dataset_train)\n\n\n# In[8]:\n\n\nprint(dataset_train)\n\n\n# In[9]:\n\n\nget_ipython().system('nvidia-smi')\n\n\n# ## Positional encoding\n# \n\n# In[13]:\n\n\ndef get_angles(pos, i, d_model):\n angle_rates = 1 / np.power(10000, (2 * (i//2)) / np.float32(d_model))\n return pos * angle_rates\n\n\n# In[14]:\n\n\ndef positional_encoding(position, d_model):\n angle_rads = get_angles(np.arange(position)[:, np.newaxis],\n np.arange(d_model)[np.newaxis, :],\n d_model)\n\n # apply sin to even indices in the array; 2i\n angle_rads[:, 0::2] = np.sin(angle_rads[:, 0::2])\n\n # apply cos to odd indices in the array; 2i+1\n angle_rads[:, 1::2] = np.cos(angle_rads[:, 1::2])\n\n pos_encoding = angle_rads[np.newaxis, ...]\n\n return tf.cast(pos_encoding, dtype=tf.float32)\n\n\n# In[15]:\n\n\nn, d = 2048, 512\npos_encoding = positional_encoding(n, d)\nprint(pos_encoding.shape)\npos_encoding = pos_encoding[0]\n\n# Juggle the dimensions for the plot\npos_encoding = tf.reshape(pos_encoding, (n, d//2, 2))\npos_encoding = tf.transpose(pos_encoding, (2, 1, 0))\npos_encoding = tf.reshape(pos_encoding, (d, n))\n\nplt.pcolormesh(pos_encoding, cmap='RdBu')\nplt.ylabel('Depth')\nplt.xlabel('Position')\nplt.colorbar()\nplt.show()\n\n\n# ## Masking\n\n# In[16]:\n\n\ndef create_padding_mask(seq):\n seq = tf.cast(tf.math.equal(seq, 0), tf.float32)\n\n # add extra dimensions to add the padding\n # to the attention logits.\n return seq[:, tf.newaxis, tf.newaxis, :] # (batch_size, 1, 1, seq_len)\n\n\n# In[17]:\n\n\ndef create_look_ahead_mask(size):\n mask = 1 - tf.linalg.band_part(tf.ones((size, size)), -1, 0)\n return mask # (seq_len, seq_len)\n\n\n# ## Scaled dot product attention\n\n# In[18]:\n\n\ndef scaled_dot_product_attention(q, k, v, mask):\n \"\"\"Calculate the attention weights.\n q, k, v must have matching leading dimensions.\n k, v must have matching penultimate dimension, i.e.: seq_len_k = seq_len_v.\n The mask has different shapes depending on its type(padding or look ahead)\n but it must be broadcastable for addition.\n\n Args:\n q: query shape == (..., seq_len_q, depth)\n k: key shape == (..., seq_len_k, depth)\n v: value shape == (..., seq_len_v, depth_v)\n mask: Float tensor with shape broadcastable\n to (..., seq_len_q, seq_len_k). Defaults to None.\n\n Returns:\n output, attention_weights\n \"\"\"\n\n matmul_qk = tf.matmul(q, k, transpose_b=True) # (..., seq_len_q, seq_len_k)\n\n # scale matmul_qk\n dk = tf.cast(tf.shape(k)[-1], tf.float32)\n scaled_attention_logits = matmul_qk / tf.math.sqrt(dk)\n\n # add the mask to the scaled tensor.\n if mask is not None:\n scaled_attention_logits += (mask * -1e9)\n\n # softmax is normalized on the last axis (seq_len_k) so that the scores\n # add up to 1.\n attention_weights = tf.nn.softmax(scaled_attention_logits, axis=-1) # (..., seq_len_q, seq_len_k)\n\n output = tf.matmul(attention_weights, v) # (..., seq_len_q, depth_v)\n\n return output, attention_weights\n\n\n# ## Multi-head attention\n\n# In[19]:\n\n\nclass MultiHeadAttention(tf.keras.layers.Layer):\n def __init__(self, d_model, num_heads):\n super(MultiHeadAttention, self).__init__()\n self.num_heads = num_heads\n self.d_model = d_model\n\n assert d_model % self.num_heads == 0\n\n self.depth = d_model // self.num_heads\n\n self.wq = tf.keras.layers.Dense(d_model)\n self.wk = tf.keras.layers.Dense(d_model)\n self.wv = tf.keras.layers.Dense(d_model)\n\n self.dense = tf.keras.layers.Dense(d_model)\n\n def split_heads(self, x, batch_size):\n \"\"\"Split the last dimension into (num_heads, depth).\n Transpose the result such that the shape is (batch_size, num_heads, seq_len, depth)\n \"\"\"\n x = tf.reshape(x, (batch_size, -1, self.num_heads, self.depth))\n return tf.transpose(x, perm=[0, 2, 1, 3])\n\n def call(self, v, k, q, mask):\n batch_size = tf.shape(q)[0]\n\n q = self.wq(q) # (batch_size, seq_len, d_model)\n k = self.wk(k) # (batch_size, seq_len, d_model)\n v = self.wv(v) # (batch_size, seq_len, d_model)\n\n q = self.split_heads(q, batch_size) # (batch_size, num_heads, seq_len_q, depth)\n k = self.split_heads(k, batch_size) # (batch_size, num_heads, seq_len_k, depth)\n v = self.split_heads(v, batch_size) # (batch_size, num_heads, seq_len_v, depth)\n \n\n\n # scaled_attention.shape == (batch_size, num_heads, seq_len_q, depth)\n # attention_weights.shape == (batch_size, num_heads, seq_len_q, seq_len_k)\n scaled_attention, attention_weights = scaled_dot_product_attention(\n q, k, v, mask)\n \n\n\n scaled_attention = tf.transpose(scaled_attention, perm=[0, 2, 1, 3]) # (batch_size, seq_len_q, num_heads, depth)\n\n\n concat_attention = tf.reshape(scaled_attention,\n (batch_size, -1, self.d_model)) # (batch_size, seq_len_q, d_model)\n\n output = self.dense(concat_attention) # (batch_size, seq_len_q, d_model)\n\n\n return output, attention_weights\n\n\n# In[20]:\n\n\ntemp_mha = MultiHeadAttention(d_model=512, num_heads=8)\ny = tf.random.uniform((1, 60, 512)) # (batch_size, encoder_sequence, d_model)\nout, attn = temp_mha(y, k=y, q=y, mask=None)\nout.shape, attn.shape\n\n\n# ## Point wise feed forward network\n\n# In[21]:\n\n\ndef point_wise_feed_forward_network(d_model, dff):\n return tf.keras.Sequential([\n tf.keras.layers.Dense(dff, activation='relu'), # (batch_size, seq_len, dff)\n tf.keras.layers.Dense(d_model) # (batch_size, seq_len, d_model)\n ])\n\n\n# ## Encoder and decoder\n\n# \"transformer\"\n\n# In[22]:\n\n\nclass DecoderLayer(tf.keras.layers.Layer):\n def __init__(self, d_model, num_heads, dff, rate=0.1):\n super(DecoderLayer, self).__init__()\n\n self.mha1 = MultiHeadAttention(d_model, num_heads)\n self.mha2 = MultiHeadAttention(d_model, num_heads)\n\n self.ffn = point_wise_feed_forward_network(d_model, dff)\n\n self.layernorm1 = tf.keras.layers.LayerNormalization(epsilon=1e-6)\n self.layernorm2 = tf.keras.layers.LayerNormalization(epsilon=1e-6)\n self.layernorm3 = tf.keras.layers.LayerNormalization(epsilon=1e-6)\n\n self.dropout1 = tf.keras.layers.Dropout(rate)\n self.dropout2 = tf.keras.layers.Dropout(rate)\n self.dropout3 = tf.keras.layers.Dropout(rate)\n\n def call(self, x, enc_output, training,\n look_ahead_mask, padding_mask):\n # enc_output.shape == (batch_size, input_seq_len, d_model)\n\n attn1, attn_weights_block1 = self.mha1(x, x, x, look_ahead_mask) # (batch_size, target_seq_len, d_model)\n attn1 = self.dropout1(attn1, training=training)\n out1 = self.layernorm1(attn1 + x)\n \n attn2, attn_weights_block2 = self.mha2(\n enc_output, enc_output, out1, padding_mask) # (batch_size, target_seq_len, d_model)\n attn2 = self.dropout2(attn2, training=training)\n out2 = self.layernorm2(attn2 + out1) # (batch_size, target_seq_len, d_model)\n\n ffn_output = self.ffn(out2) # (batch_size, target_seq_len, d_model)\n ffn_output = self.dropout3(ffn_output, training=training)\n out3 = self.layernorm3(ffn_output + out2) # (batch_size, target_seq_len, d_model)\n\n return out3, attn_weights_block1, attn_weights_block2\n\n\n# In[23]:\n\n\nclass Residual(tf.keras.Model):\n \"\"\"The Residual block of ResNet.\"\"\"\n def __init__(self, num_channels, use_1x1conv=False, strides=1):\n super().__init__()\n self.conv1 = tf.keras.layers.Conv2D(num_channels, padding='same',\n kernel_size=3, strides=strides)\n self.conv2 = tf.keras.layers.Conv2D(num_channels, kernel_size=3,\n padding='same')\n self.conv3 = None\n if use_1x1conv:\n self.conv3 = tf.keras.layers.Conv2D(num_channels, kernel_size=1,\n strides=strides)\n self.bn1 = tf.keras.layers.BatchNormalization()\n self.bn2 = tf.keras.layers.BatchNormalization()\n\n def call(self, X):\n Y = tf.keras.activations.relu(self.bn1(self.conv1(X)))\n Y = self.bn2(self.conv2(Y))\n if self.conv3 is not None:\n X = self.conv3(X)\n Y += X\n return tf.keras.activations.relu(Y)\n\n\n# In[24]:\n\n\nclass ResnetBlock(tf.keras.layers.Layer):\n def __init__(self, num_channels, num_residuals, first_block=False,\n **kwargs):\n super(ResnetBlock, self).__init__(**kwargs)\n self.residual_layers = []\n for i in range(num_residuals):\n if i == 0 and not first_block:\n self.residual_layers.append(\n Residual(num_channels, use_1x1conv=True, strides=2))\n else:\n self.residual_layers.append(Residual(num_channels))\n\n def call(self, X):\n for layer in self.residual_layers.layers:\n X = layer(X)\n return X\n\n\n# In[25]:\n\n\nclass Encoder(tf.keras.layers.Layer): # ResNet\n def __init__(self):\n super(Encoder, self).__init__()\n self.cov1 = tf.keras.layers.Conv2D(64, kernel_size=7, strides=2, padding='same')\n self.batch_norm = tf.keras.layers.BatchNormalization()\n self.max_pool = tf.keras.layers.MaxPool2D(pool_size=3, strides=2, padding='same')\n self.res_1 = ResnetBlock(64, 2, first_block=True)\n self.res_2 = ResnetBlock(128, 2)\n self.res_3 = ResnetBlock(256, 2)\n self.res_4 = ResnetBlock(512, 2)\n self.glob_pool = tf.keras.layers.GlobalAvgPool2D()\n self.fc = tf.keras.layers.Dense(1024)\n \n def call(self, x):\n x = self.cov1(x)\n x = self.batch_norm(x)\n x = tf.nn.relu(x)\n x = self.max_pool(x)\n x = self.res_1(x)\n x = self.res_2(x)\n x = self.res_4(x)\n x = self.glob_pool(x)\n x = self.fc(x)\n \n return x # (batch_size, input_seq_len, d_model)\n\n\n# In[26]:\n\n\ntemp_embedding = tf.random.uniform((64, 7), dtype=tf.float64, minval=0, maxval=28)\ntemp_img = tf.random.uniform((64, 128), dtype=tf.float64, minval=-1, maxval=1)\n\n\nsample_encoder = Encoder()\n\n\ntemp_input = tf.random.uniform((64, 128, 128, 3), dtype=tf.float64, minval=-1, maxval=1)\n\nsample_encoder_output = sample_encoder(temp_input)\n\nsample_encoder_output.shape\n\n\n# ### Decoder\n\n# In[27]:\n\n\nclass Decoder(tf.keras.layers.Layer):\n def __init__(self, num_layers, d_model, num_heads, dff, target_vocab_size,\n maximum_position_encoding, rate=0.1):\n super(Decoder, self).__init__()\n\n self.d_model = d_model\n self.num_layers = num_layers\n\n self.embedding = tf.keras.layers.Embedding(target_vocab_size, d_model)\n self.pos_encoding = positional_encoding(maximum_position_encoding, d_model)\n\n self.dec_layers = [DecoderLayer(d_model, num_heads, dff, rate)\n for _ in range(num_layers)]\n self.dropout = tf.keras.layers.Dropout(rate)\n\n def call(self, x, enc_output, training,\n look_ahead_mask, padding_mask):\n\n seq_len = tf.shape(x)[1]\n attention_weights = {}\n\n x = self.embedding(x) # (batch_size, target_seq_len, d_model)\n x *= tf.math.sqrt(tf.cast(self.d_model, tf.float32))\n x += self.pos_encoding[:, :seq_len, :]\n x = self.dropout(x, training=training)\n\n for i in range(self.num_layers):\n x, block1, block2 = self.dec_layers[i](x, enc_output, training,\n look_ahead_mask, padding_mask)\n attention_weights[f'decoder_layer{i+1}_block1'] = block1\n attention_weights[f'decoder_layer{i+1}_block2'] = block2\n\n return x, attention_weights\n\n\n# In[28]:\n\n\nsample_decoder = Decoder(num_layers=2, d_model=512, num_heads=8,\n dff=2048, target_vocab_size=29,\n maximum_position_encoding=141)\n\ntemp_input = tf.random.uniform((1, 7), dtype=tf.float64, minval=0, maxval=28)\n\nsample_encoder_output = tf.random.uniform((1, 128), dtype=tf.float64, minval=0, maxval=28)\n\noutput, attn = sample_decoder(temp_input,\n enc_output=sample_encoder_output,\n training=False,\n look_ahead_mask=None,\n padding_mask=None)\n\n\n# ## Create the Transformer\n\n# Transformer consists of the encoder, decoder and a final linear layer. The output of the decoder is the input to the linear layer and its output is returned.\n\n# In[29]:\n\n\nclass Transformer(tf.keras.Model):\n def __init__(self, num_layers, d_model, num_heads, dff, input_vocab_size,\n target_vocab_size, pe_input, pe_target, rate=0.1):\n super(Transformer, self).__init__()\n \n self.encoder = Encoder()\n\n self.decoder = Decoder(num_layers, d_model, num_heads, dff,\n target_vocab_size, pe_target, rate)\n\n self.final_layer = tf.keras.layers.Dense(target_vocab_size)\n\n def call(self, x, tar, training, enc_padding_mask, look_ahead_mask, dec_padding_mask):\n\n x = self.encoder(x)\n \n dec_output, attention_weights = self.decoder(\n tar, x, training, look_ahead_mask, dec_padding_mask)\n\n final_output = self.final_layer(dec_output) # (batch_size, tar_seq_len, target_vocab_size)\n\n return final_output, attention_weights\n\n\n# In[30]:\n\n\nsample_transformer = Transformer(\n num_layers=2, d_model=1024, num_heads=64, dff=2048,\n input_vocab_size=1000, target_vocab_size=1000,\n pe_input=10000, pe_target=6000)\n\ntemp_input = tf.random.uniform((64, 128, 128, 3), dtype=tf.float64, minval=-1, maxval=1)\n\ntemp_target = tf.random.uniform((64, 7), dtype=tf.int32, minval=0, maxval=28)\n\nfn_out, _ = sample_transformer(temp_input, temp_target, training=False,enc_padding_mask=None,look_ahead_mask=None,dec_padding_mask=None)\n\nfn_out.shape # (batch_size, tar_seq_len, target_vocab_size)\n\n\n# ## Set hyperparameters\n\n# In[31]:\n\n\nnum_layers = 8\nd_model = 512\ndff = 512\nnum_heads = 8\ndropout_rate = 0.3\n\n\n# ## Optimizer\n\n# Use the Adam optimizer with a custom learning rate scheduler according to the formula in the [paper](https://arxiv.org/abs/1706.03762).\n# \n# $$\\Large{lrate = d_{model}^{-0.5} * \\min(step{\\_}num^{-0.5}, step{\\_}num \\cdot warmup{\\_}steps^{-1.5})}$$\n# \n\n# In[32]:\n\n\nclass CustomSchedule(tf.keras.optimizers.schedules.LearningRateSchedule):\n def __init__(self, d_model, warmup_steps=4000):\n super(CustomSchedule, self).__init__()\n\n self.d_model = d_model\n self.d_model = tf.cast(self.d_model, tf.float32)\n\n self.warmup_steps = warmup_steps\n\n def __call__(self, step):\n arg1 = tf.math.rsqrt(step)\n arg2 = step * (self.warmup_steps ** -1.5)\n\n return tf.math.rsqrt(self.d_model) * tf.math.minimum(arg1, arg2)\n\n\n# In[33]:\n\n\nlearning_rate = CustomSchedule(d_model)\n\noptimizer = tf.keras.optimizers.Adam(learning_rate, beta_1=0.9, beta_2=0.98,\n epsilon=1e-9)\n\n\n# ## Loss and metrics\n\n# Since the target sequences are padded, it is important to apply a padding mask when calculating the loss.\n\n# In[34]:\n\n\nloss_object = tf.keras.losses.SparseCategoricalCrossentropy(\n from_logits=True, reduction='none')\n\n\n# In[35]:\n\n\ndef loss_function(real, pred):\n mask = tf.math.logical_not(tf.math.equal(real, 0))\n loss_ = loss_object(real, pred)\n\n mask = tf.cast(mask, dtype=loss_.dtype)\n loss_ *= mask\n\n return tf.reduce_sum(loss_)/tf.reduce_sum(mask)\n\n\ndef accuracy_function(real, pred):\n not_paddings = (real != 0)\n logics = (real == tf.dtypes.cast(pred, tf.float32))\n logics = logics & not_paddings\n summation = tf.reduce_sum(tf.cast(logics, tf.float32))\n total = tf.reduce_sum(tf.cast(not_paddings, tf.float32))\n return summation/total\n\n\n# In[36]:\n\n\ntrain_loss = tf.keras.metrics.Mean(name='train_loss')\ntrain_accuracy = tf.keras.metrics.Mean(name='train_accuracy')\n\nval_loss = tf.keras.metrics.Mean(name='val_loss')\nval_accuracy = tf.keras.metrics.Mean(name='val_accuracy')\n\n\n# ## Training and checkpointing\n\n# In[37]:\n\n\ntransformer = Transformer(\n num_layers=num_layers,\n d_model=d_model,\n num_heads=num_heads,\n dff=dff,\n input_vocab_size=1000,\n target_vocab_size=1000,\n pe_input=1000,\n pe_target=1000,\n rate=dropout_rate)\n\n\n# In[38]:\n\n\ndef create_masks(inp, tar):\n # Encoder padding mask\n enc_padding_mask = create_padding_mask(inp)\n\n # Used in the 2nd attention block in the decoder.\n # This padding mask is used to mask the encoder outputs.\n dec_padding_mask = create_padding_mask(inp)\n\n # Used in the 1st attention block in the decoder.\n # It is used to pad and mask future tokens in the input received by\n # the decoder.\n look_ahead_mask = create_look_ahead_mask(tf.shape(tar)[1])\n dec_target_padding_mask = create_padding_mask(tar)\n combined_mask = tf.maximum(dec_target_padding_mask, look_ahead_mask)\n\n return enc_padding_mask, combined_mask, dec_padding_mask\n\n\ntemp_embedding = tf.random.uniform((64, 142), dtype=tf.float64, minval=0, maxval=28)\ntemp_img = tf.random.uniform((64, 128), dtype=tf.float64, minval=-1, maxval=1)\n\nenc_padding_mask, combined_mask, dec_padding_mask = create_masks(temp_img, temp_embedding)\n\n\n# In[39]:\n\n\nEPOCHS = 100\n\n\n# In[40]:\n\n\ndef train_step(inp, tar):\n tar_inp = tar[:, :-1]\n# print(tar_inp)\n tar_real = tar[:, 1:]\n# print(tar_real)\n\n enc_padding_mask, combined_mask, dec_padding_mask = create_masks(inp, tar_inp)\n\n with tf.GradientTape() as tape:\n predictions, _ = transformer(inp, tar_inp,\n True,\n None,\n combined_mask,\n None)\n loss = loss_function(tar_real, predictions)\n\n gradients = tape.gradient(loss, transformer.trainable_variables)\n optimizer.apply_gradients(zip(gradients, transformer.trainable_variables))\n prediction = tf.argmax(predictions, axis=-1)\n\n train_loss(loss)\n train_accuracy(accuracy_function(tar_real, prediction))\n\n\n# In[41]:\n\n\ndef val_step(inp, tar):\n tar_inp = tar[:, :-1]\n tar_real = tar[:, 1:]\n\n enc_padding_mask, combined_mask, dec_padding_mask = create_masks(inp, tar_inp)\n\n predictions, _ = transformer(inp, tar_inp,\n True,\n None,\n combined_mask,\n None)\n loss = loss_function(tar_real, predictions)\n\n prediction = tf.argmax(predictions, axis=-1)\n\n val_loss(loss)\n val_accuracy(accuracy_function(tar_real, prediction))\n\n\n# In[42]:\n\n\ncheckpoint_path = \"./checkpoints/term_project_jinghao_transformer\"\n\nckpt = tf.train.Checkpoint(transformer=transformer,\n optimizer=optimizer)\n\nckpt_manager = tf.train.CheckpointManager(ckpt, checkpoint_path, max_to_keep=5)\n\n# if a checkpoint exists, restore the latest checkpoint.\nif ckpt_manager.latest_checkpoint:\n ckpt.restore(ckpt_manager.latest_checkpoint)\n print('Latest checkpoint restored!!')\n\n\n# In[43]:\n\n\nget_ipython().system('nvidia-smi')\n\n\n# In[60]:\n\n\nearly_stop = np.zeros(EPOCHS)\ncount = 1\nmaximum = 0.0\nprev_maximum = 0.0\nbreak_flag = 0\ncheck_counter = 0\nfor epoch in range(EPOCHS):\n start = time.time()\n train_loss.reset_states()\n train_accuracy.reset_states()\n val_loss.reset_states()\n val_accuracy.reset_states()\n ckpt_save_path = ckpt_manager.save()\n print(f'Saving checkpoint for epoch {epoch+1} at {ckpt_save_path}')\n\n # inp -> img, tar -> captioning\n for (batch, (inp, tar)) in enumerate(dataset_train):\n train_step(inp, tar)\n\n if batch % 50 == 0:\n print(f'Epoch {epoch + 1} Batch {batch} Loss {train_loss.result():.4f} Accuracy {train_accuracy.result():.4f}')\n \n for (batch, (inp, tar)) in enumerate(dataset_val):\n val_step(inp, tar)\n\n if batch % 50 == 0:\n print(f'Epoch {epoch + 1} Batch {batch} Loss {val_loss.result():.4f} Accuracy {val_accuracy.result():.4f}')\n\n print(f'Epoch {epoch + 1} Loss {train_loss.result():.4f} Accuracy {train_accuracy.result():.4f} VAL_Loss {val_loss.result():.4f} VAL_Accuracy {val_accuracy.result():.4f}')\n print(tf.keras.backend.get_value(val_accuracy.result()))\n early_stop[count] = tf.keras.backend.get_value(val_accuracy.result())\n ## if the val_accuracy can't improve in 10 epoochs, break the loop\n maximum = np.max(early_stop)\n \n if(maximum > prev_maximum):\n prev_maximum = maximum\n check_counter = 0\n else:\n check_counter+=1\n if(check_counter == 7):\n break_flag = 1\n print(f'Time taken for 1 epoch: {time.time() - start:.2f} secs\\n')\n if(break_flag == 1):\n break\n\n\n# In[44]:\n\n\ndef evaluate(img):\n output = tf.expand_dims([tokenizer.word_index['']], 0)\n result = []\n \n result.append('')\n\n for i in range(141):\n temp_img = tf.random.uniform((1, 128), dtype=tf.float64, minval=-1, maxval=1)\n\n enc_padding_mask, combined_mask, dec_padding_mask = create_masks(temp_img, output)\n \n predictions, attention_weights = transformer(img,\n output,\n False,\n None,\n combined_mask,\n None)\n \n predictions = predictions[:, -1:, :] \n predicted_id = tf.argmax(predictions.numpy(), axis=-1)\n result.append(tokenizer.index_word[predicted_id.numpy()[0][0]])\n to_append = tf.cast(predicted_id, tf.int32)\n # as its input.\n output = tf.concat([output, to_append], axis=-1)\n \n\n if tokenizer.index_word[predicted_id.numpy()[0][0]] == '':\n return result\n\n\n return result\n\n\n# In[45]:\n\n\ndef calc_max_length(tensor):\n return max(len(t) for t in tensor)\n\n\n\n\nfor x, y in dataset_train:\n result = []\n token = y.numpy()[2]\n img_ = x[2]\n img_ = tf.expand_dims(img_, axis=0)\n for j in token:\n if j != 0:\n result.append(tokenizer.index_word[j])\n predict = evaluate(img_)\n print('Predict Caption:', ' '.join(predict))\n plt.imshow(x[2].numpy()+ 0.5)\n break\n\n\n\nprint('Real Caption:', ' '.join(result))\n\n\n# In[46]:\n\n\nfrom nltk.translate.bleu_score import sentence_bleu\n\nidx = 3771\n\nfor idx in range(3701,3740):\n image_path = original_image_name_list[idx]\n\n img = tf.io.read_file(image_path)\n img = tf.image.decode_png(img, channels=3)\n img = tf.image.resize(img, (128, 128))\n img = img / 255.0 - 0.5\n\n img_ = tf.expand_dims(img, axis=0)\n predict = evaluate(img_)\n# print(predict)\n predict_bleu = predict.remove('')\n predict_bleu = predict.remove('')\n print('Predict Caption:', ' '.join(predict))\n predict = ' '.join(predict)\n\n result = []\n for j in original_cap_vector[idx]:\n if j != 0:\n result.append(tokenizer.index_word[j])\n# print(result)\n result_bleu = result.remove('')\n result_bleu = result.remove('')\n print(' Real Caption:', ' '.join(result))\n score = sentence_bleu(predict, result, weights=(1, 0, 0, 0))\n print(score)\n print('--------------------------------------------------------------------------------------------------------')\n tar_real = ' '.join(result)\n plt.imshow(img + 0.5)\n\n\n# In[49]:\n\n\nidx = 3771\nBLEU_1 = 0\nBLEU_2 = 0\nBLEU_3 = 0\nBLEU_4 = 0\nfor idx in range(3701,3825):\n image_path = original_image_name_list[idx]\n\n img = tf.io.read_file(image_path)\n img = tf.image.decode_png(img, channels=3)\n img = tf.image.resize(img, (224, 224))\n img = img / 255.0 - 0.5\n\n img_ = tf.expand_dims(img, axis=0)\n predict = evaluate(img_)\n print('Predict Caption:', ' '.join(predict))\n\n result = []\n for j in original_cap_vector[idx]:\n if j != 0:\n result.append(tokenizer.index_word[j])\n print('Real Caption:', ' '.join(result))\n print('<------------------------------------------------>')\n BLEUscore_1 = nltk.translate.bleu_score.sentence_bleu([result], predict, weights=(1, 0, 0, 0))\n BLEUscore_2 = nltk.translate.bleu_score.sentence_bleu([result], predict, weights=(0, 1, 0, 0))\n BLEUscore_3 = nltk.translate.bleu_score.sentence_bleu([result], predict, weights=(0, 0, 1, 0))\n BLEUscore_4 = nltk.translate.bleu_score.sentence_bleu([result], predict, weights=(0, 0, 0, 1))\n print('1:', BLEUscore_1)\n print('2:', BLEUscore_2)\n print('3:', BLEUscore_3)\n print('4:', BLEUscore_4)\n BLEU_1 += BLEUscore_1\n BLEU_2 += BLEUscore_2\n BLEU_3 += BLEUscore_3\n BLEU_4 += BLEUscore_4\n# result = ' '.join(result)\n# predict = ' '.join(predict)\n# print(result)\n# print(predict)\n# print(accuracy_function(result, predict))\nprint('average 1-gram', BLEU_1/125)\nprint('average 2-gram', BLEU_2/125)\nprint('average 3-gram', BLEU_3/125)\nprint('average 4-gram', BLEU_4/125)\n\n\n# In[ ]:\n\n\n\n\n","sub_path":"medical-image-final/transformer-data-splitting.py","file_name":"transformer-data-splitting.py","file_ext":"py","file_size_in_byte":29519,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"442325800","text":"import time\nimport numpy as np\nfrom sklearn import preprocessing\nfrom numpy import random\nfrom scipy import linalg as LA\nfrom keras.models import Model, load_model\n\n# from scipy import stats\n# import matplotlib.pyplot as plt\n\n'''\n#输出训练/测试准确率\n'''\n\nL = 5 # # of incremental steps\nM = 50 # # of adding enhance nodes\ns = 0.8 # shrink coefficient\nc = 2 ** -30 # Regularization coefficient\nBLS_Epoch = 10\n\n\ndef show_accuracy(predictLabel, Label):\n count = 0\n label_1 = np.zeros(Label.shape[0])\n predlabel = []\n label_1 = Label.argmax(axis=1)\n predlabel = predictLabel.argmax(axis=1)\n for j in list(range(Label.shape[0])):\n if label_1[j] == predlabel[j]:\n count += 1\n return round(count / len(Label), 5)\n\n\n'''\n激活函数\n'''\n\n\ndef tansig(x):\n return (2 / (1 + np.exp(-2 * x))) - 1\n\n\ndef sigmoid(data):\n return 1.0 / (1 + np.exp(-data))\n\n\ndef linear(data):\n return data\n\n\ndef tanh(data):\n return (np.exp(data) - np.exp(-data)) / (np.exp(data) + np.exp(-data))\n\n\ndef relu(data):\n return np.maximum(data, 0)\n\n\ndef pinv(A, reg):\n return np.mat(reg * np.eye(A.shape[1]) + A.T.dot(A)).I.dot(A.T)\n\n\n'''\n参数压缩\n'''\n\n\ndef shrinkage(a, b):\n z = np.maximum(a - b, 0) - np.maximum(-a - b, 0)\n return z\n\n\n'''\n参数稀疏化\n'''\n\n\ndef sparse_bls(A, b):\n lam = 0.001\n itrs = 50\n AA = A.T.dot(A)\n m = A.shape[1]\n n = b.shape[1]\n x1 = np.zeros([m, n])\n wk = x1\n ok = x1\n uk = x1\n L1 = np.mat(AA + np.eye(m)).I\n L2 = (L1.dot(A.T)).dot(b)\n for i in range(itrs):\n ck = L2 + np.dot(L1, (ok - uk))\n ok = shrinkage(ck + uk, lam)\n uk = uk + ck - ok\n wk = ok\n return wk\n\n\ndef bls_deep_train(model, model_path, middle_model_save_path, get_layer_name, train_x, train_y, N2, N3):\n # 生成映射层\n model.load_weights(model_path)\n model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])\n feature_layer = Model(inputs=model.input, outputs=model.get_layer(get_layer_name).output)\n feature_layer.save(middle_model_save_path)\n\n time_start = time.time() # 计时开始\n\n OutputOfFeatureMappingLayer = []\n for i in range(N2):\n FeatureOfEachWindow = feature_layer.predict(train_x)\n scaler1 = preprocessing.MinMaxScaler(feature_range=(0, 1)).fit(FeatureOfEachWindow)\n FeatureOfEachWindowAfterPreprocess = scaler1.transform(FeatureOfEachWindow)\n # 通过稀疏化计算映射层每个窗口内的最终权重\n outputOfEachWindow = FeatureOfEachWindowAfterPreprocess\n # distOfMaxAndMin.append(np.max(outputOfEachWindow, axis=0) - np.min(outputOfEachWindow, axis=0))\n # minOfEachWindow.append(np.min(outputOfEachWindow, axis=0))\n OutputOfFeatureMappingLayer.append(outputOfEachWindow)\n del FeatureOfEachWindow\n N1 = OutputOfFeatureMappingLayer[0].shape[1]\n OutputOfFeatureMappingLayer = np.array(OutputOfFeatureMappingLayer)\n OutputOfFeatureMappingLayer = np.reshape(OutputOfFeatureMappingLayer,\n newshape=[-1, OutputOfFeatureMappingLayer[0].shape[1] * N2])\n # 生成强化层\n # 以下为映射层输出加偏置(强化层输入)\n InputOfEnhanceLayerWithBias = np.hstack(\n [OutputOfFeatureMappingLayer, 0.1 * np.ones((OutputOfFeatureMappingLayer.shape[0], 1))])\n # 生成强化层权重\n if N1 * N2 >= N3:\n random.seed(67797325)\n weightOfEnhanceLayer = LA.orth(2 * random.randn(InputOfEnhanceLayerWithBias.shape[1], N3) - 1)\n else:\n random.seed(67797325)\n weightOfEnhanceLayer = LA.orth(2 * random.randn(InputOfEnhanceLayerWithBias.shape[1], N3).T - 1).T\n\n tempOfOutputOfEnhanceLayer = np.dot(InputOfEnhanceLayerWithBias, weightOfEnhanceLayer)\n parameterOfShrink = s / np.max(tempOfOutputOfEnhanceLayer)\n OutputOfEnhanceLayer = tansig(tempOfOutputOfEnhanceLayer * parameterOfShrink)\n\n # 生成最终输入\n InputOfOutputLayer = np.hstack([OutputOfFeatureMappingLayer, OutputOfEnhanceLayer])\n pinvOfInput = pinv(InputOfOutputLayer, c)\n OutputWeight = pinvOfInput.dot(train_y) # 全局违逆\n time_end = time.time() # 训练完成\n trainTime = time_end - time_start\n\n # 训练输出\n OutputOfTrain = np.dot(InputOfOutputLayer, OutputWeight)\n trainAcc = show_accuracy(OutputOfTrain, train_y)\n print('Training accurate is', trainAcc * 100, '%')\n print('Training time is ', trainTime, 's')\n\n return weightOfEnhanceLayer, parameterOfShrink, OutputWeight, InputOfEnhanceLayerWithBias, InputOfOutputLayer, pinvOfInput, N1\n\n\ndef bls_deep_test(middle_model_save_path, x_test, y_test, N2, weightOfEnhanceLayer, parameterOfShrink, OutputWeight):\n # 测试过程\n OutputOfFeatureMappingLayerTest = []\n feature_layer = load_model(middle_model_save_path)\n feature_layer.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])\n\n time_start = time.time() # 测试计时开始\n # 映射层\n for i in range(N2):\n outputOfEachWindowTest = feature_layer.predict(x_test)\n OutputOfFeatureMappingLayerTest.append(outputOfEachWindowTest)\n\n OutputOfFeatureMappingLayerTest = np.array(OutputOfFeatureMappingLayerTest)\n OutputOfFeatureMappingLayerTest = np.reshape(OutputOfFeatureMappingLayerTest,\n newshape=[-1,\n OutputOfFeatureMappingLayerTest[0].shape[1] * N2])\n # 强化层\n InputOfEnhanceLayerWithBiasTest = np.hstack(\n [OutputOfFeatureMappingLayerTest, 0.1 * np.ones((OutputOfFeatureMappingLayerTest.shape[0], 1))])\n tempOfOutputOfEnhanceLayerTest = np.dot(InputOfEnhanceLayerWithBiasTest, weightOfEnhanceLayer)\n # 强化层输出\n OutputOfEnhanceLayerTest = tansig(tempOfOutputOfEnhanceLayerTest * parameterOfShrink)\n # 最终层输入\n InputOfOutputLayerTest = np.hstack([OutputOfFeatureMappingLayerTest, OutputOfEnhanceLayerTest])\n # 最终测试输出\n OutputOfTest = np.dot(InputOfOutputLayerTest, OutputWeight)\n time_end = time.time() # 训练完成\n testTime = time_end - time_start\n testAcc = show_accuracy(OutputOfTest, y_test)\n print('Testing accurate is', testAcc * 100, '%')\n print('Testing time is ', testTime, 's')\n\n return InputOfEnhanceLayerWithBiasTest, InputOfOutputLayerTest\n\n\ndef bls_deep_enhance(train_y, test_y, N1, N2, InputOfEnhanceLayerWithBias, InputOfEnhanceLayerWithBiasTest, InputOfOutputLayer,\n pinvOfInput, InputOfOutputLayerTest):\n parameterOfShrinkAdd = []\n for e in list(range(L)):\n time_start = time.time()\n if N1 * N2 >= M:\n random.seed(e)\n weightOfEnhanceLayerAdd = LA.orth(2 * random.randn(InputOfEnhanceLayerWithBias.shape[1], M) - 1)\n else:\n random.seed(e)\n weightOfEnhanceLayerAdd = LA.orth(2 * random.randn(InputOfEnhanceLayerWithBias.shape[1], M).T - 1).T\n\n # WeightOfEnhanceLayerAdd[e,:,:] = weightOfEnhanceLayerAdd\n # weightOfEnhanceLayerAdd = weightOfEnhanceLayer[:,N3+e*M:N3+(e+1)*M]\n tempOfOutputOfEnhanceLayerAdd = np.dot(InputOfEnhanceLayerWithBias, weightOfEnhanceLayerAdd)\n parameterOfShrinkAdd.append(s / np.max(tempOfOutputOfEnhanceLayerAdd))\n OutputOfEnhanceLayerAdd = tansig(tempOfOutputOfEnhanceLayerAdd * parameterOfShrinkAdd[e])\n tempOfLastLayerInput = np.hstack([InputOfOutputLayer, OutputOfEnhanceLayerAdd])\n\n D = pinvOfInput.dot(OutputOfEnhanceLayerAdd)\n C = OutputOfEnhanceLayerAdd - InputOfOutputLayer.dot(D)\n if C.all() == 0:\n w = D.shape[1]\n B = np.mat(np.eye(w) - np.dot(D.T, D)).I.dot(np.dot(D.T, pinvOfInput))\n else:\n B = pinv(C, c)\n pinvOfInput = np.vstack([(pinvOfInput - D.dot(B)), B])\n OutputWeightEnd = pinvOfInput.dot(train_y)\n InputOfOutputLayer = tempOfLastLayerInput\n Training_time = time.time() - time_start\n OutputOfTrain1 = InputOfOutputLayer.dot(OutputWeightEnd)\n TrainingAccuracy = show_accuracy(OutputOfTrain1, train_y)\n print('Incremental Training Accuracy is :', TrainingAccuracy * 100, ' %')\n\n # 增量增加节点的 测试过程\n time_start = time.time()\n OutputOfEnhanceLayerAddTest = tansig(\n InputOfEnhanceLayerWithBiasTest.dot(weightOfEnhanceLayerAdd) * parameterOfShrinkAdd[e]);\n InputOfOutputLayerTest = np.hstack([InputOfOutputLayerTest, OutputOfEnhanceLayerAddTest])\n\n OutputOfTest1 = InputOfOutputLayerTest.dot(OutputWeightEnd)\n TestingAcc = show_accuracy(OutputOfTest1, test_y)\n\n Test_time = time.time() - time_start\n\n print('Incremental Testing Accuracy is : ', TestingAcc * 100, ' %');\n print('Incremental Testing Time is :', Test_time, ' s')\n\n\ndef BLS_AddEnhanceNodes(train_x, train_y, test_x, test_y, s, c, N1, N2, N3, L, M):\n # 生成映射层\n '''\n 两个参数最重要,1)y;2)Beta1OfEachWindow\n '''\n u = 0\n ymax = 1 # 数据收缩上限\n ymin = 0 # 数据收缩下限\n # train_x = preprocessing.scale(train_x, axis=1) # 处理数据\n FeatureOfInputDataWithBias = np.hstack([train_x, 0.1 * np.ones((train_x.shape[0], 1))])\n OutputOfFeatureMappingLayer = np.zeros([train_x.shape[0], N2 * N1])\n # Beta1OfEachWindow = np.zeros([N2,train_x.shape[1]+1,N1])\n # distOfMaxAndMin = []\n # minOfEachWindow = []\n train_acc = np.zeros([1, L + 1])\n test_acc = np.zeros([1, L + 1])\n train_time = np.zeros([1, L + 1])\n test_time = np.zeros([1, L + 1])\n time_start = time.time() # 计时开始\n Beta1OfEachWindow = []\n for i in range(N2):\n random.seed(i + u)\n weightOfEachWindow = 2 * random.randn(train_x.shape[1] + 1, N1) - 1 # 生成每个窗口的权重系数,最后一行为偏差\n # WeightOfEachWindow([],[],i) = weightOfEachWindow; #存储每个窗口的权重系数\n FeatureOfEachWindow = np.dot(FeatureOfInputDataWithBias, weightOfEachWindow) # 生成每个窗口的特征\n # 压缩每个窗口特征到[-1,1]\n # scaler1 = preprocessing.MinMaxScaler(feature_range=(0, 1)).fit(FeatureOfEachWindow)\n # FeatureOfEachWindowAfterPreprocess = scaler1.transform(FeatureOfEachWindow)\n FeatureOfEachWindowAfterPreprocess = FeatureOfEachWindow\n # 通过稀疏化计算映射层每个窗口内的最终权重\n betaOfEachWindow = sparse_bls(FeatureOfEachWindowAfterPreprocess, FeatureOfInputDataWithBias).T\n Beta1OfEachWindow.append(betaOfEachWindow)\n outputOfEachWindow = np.dot(FeatureOfInputDataWithBias, betaOfEachWindow)\n # distOfMaxAndMin.append(np.max(outputOfEachWindow, axis=0) - np.min(outputOfEachWindow, axis=0))\n # minOfEachWindow.append(np.min(outputOfEachWindow, axis=0))\n outputOfEachWindow = (outputOfEachWindow)\n OutputOfFeatureMappingLayer[:, N1 * i:N1 * (i + 1)] = outputOfEachWindow\n del outputOfEachWindow\n del FeatureOfEachWindow\n del weightOfEachWindow\n\n # 生成强化层\n # 以下为映射层输出加偏置(强化层输入)\n InputOfEnhanceLayerWithBias = np.hstack(\n [OutputOfFeatureMappingLayer, 0.1 * np.ones((OutputOfFeatureMappingLayer.shape[0], 1))])\n # 生成强化层权重\n if N1 * N2 >= N3:\n random.seed(67797325)\n weightOfEnhanceLayer = LA.orth(2 * random.randn(N2 * N1 + 1, N3) - 1)\n else:\n random.seed(67797325)\n weightOfEnhanceLayer = LA.orth(2 * random.randn(N2 * N1 + 1, N3).T - 1).T\n\n tempOfOutputOfEnhanceLayer = np.dot(InputOfEnhanceLayerWithBias, weightOfEnhanceLayer)\n parameterOfShrink = s / np.max(tempOfOutputOfEnhanceLayer)\n OutputOfEnhanceLayer = tansig(tempOfOutputOfEnhanceLayer * parameterOfShrink)\n\n # 生成最终输入\n InputOfOutputLayer = np.hstack([OutputOfFeatureMappingLayer, OutputOfEnhanceLayer])\n pinvOfInput = pinv(InputOfOutputLayer, c)\n OutputWeight = pinvOfInput.dot(train_y) # 全局违逆\n time_end = time.time() # 训练完成\n trainTime = time_end - time_start\n\n # 训练输出\n OutputOfTrain = np.dot(InputOfOutputLayer, OutputWeight)\n trainAcc = show_accuracy(OutputOfTrain, train_y)\n print('Training accurate is', trainAcc * 100, '%')\n print('Training time is ', trainTime, 's')\n train_acc[0][0] = trainAcc\n train_time[0][0] = trainTime\n # 测试过程\n test_x = preprocessing.scale(test_x, axis=1) # 处理数据 x = (x-mean(x))/std(x) x属于[-1,1]\n FeatureOfInputDataWithBiasTest = np.hstack([test_x, 0.1 * np.ones((test_x.shape[0], 1))])\n OutputOfFeatureMappingLayerTest = np.zeros([test_x.shape[0], N2 * N1])\n time_start = time.time() # 测试计时开始\n # 映射层\n for i in range(N2):\n outputOfEachWindowTest = np.dot(FeatureOfInputDataWithBiasTest, Beta1OfEachWindow[i])\n OutputOfFeatureMappingLayerTest[:, N1 * i:N1 * (i + 1)] = outputOfEachWindowTest\n # 强化层\n InputOfEnhanceLayerWithBiasTest = np.hstack(\n [OutputOfFeatureMappingLayerTest, 0.1 * np.ones((OutputOfFeatureMappingLayerTest.shape[0], 1))])\n tempOfOutputOfEnhanceLayerTest = np.dot(InputOfEnhanceLayerWithBiasTest, weightOfEnhanceLayer)\n # 强化层输出\n OutputOfEnhanceLayerTest = tansig(tempOfOutputOfEnhanceLayerTest * parameterOfShrink)\n # 最终层输入\n InputOfOutputLayerTest = np.hstack([OutputOfFeatureMappingLayerTest, OutputOfEnhanceLayerTest])\n # 最终测试输出\n OutputOfTest = np.dot(InputOfOutputLayerTest, OutputWeight)\n time_end = time.time() # 训练完成\n testTime = time_end - time_start\n testAcc = show_accuracy(OutputOfTest, test_y)\n print('Testing accurate is', testAcc * 100, '%')\n print('Testing time is ', testTime, 's')\n test_acc[0][0] = testAcc\n test_time[0][0] = testTime\n '''\n 增量增加强化节点\n '''\n parameterOfShrinkAdd = []\n for e in list(range(L)):\n time_start = time.time()\n if N1 * N2 >= M:\n random.seed(e)\n weightOfEnhanceLayerAdd = LA.orth(2 * random.randn(N2 * N1 + 1, M) - 1)\n else:\n random.seed(e)\n weightOfEnhanceLayerAdd = LA.orth(2 * random.randn(N2 * N1 + 1, M).T - 1).T\n\n # WeightOfEnhanceLayerAdd[e,:,:] = weightOfEnhanceLayerAdd\n # weightOfEnhanceLayerAdd = weightOfEnhanceLayer[:,N3+e*M:N3+(e+1)*M]\n tempOfOutputOfEnhanceLayerAdd = np.dot(InputOfEnhanceLayerWithBias, weightOfEnhanceLayerAdd)\n parameterOfShrinkAdd.append(s / np.max(tempOfOutputOfEnhanceLayerAdd))\n OutputOfEnhanceLayerAdd = tansig(tempOfOutputOfEnhanceLayerAdd * parameterOfShrinkAdd[e])\n tempOfLastLayerInput = np.hstack([InputOfOutputLayer, OutputOfEnhanceLayerAdd])\n\n D = pinvOfInput.dot(OutputOfEnhanceLayerAdd)\n C = OutputOfEnhanceLayerAdd - InputOfOutputLayer.dot(D)\n if C.all() == 0:\n w = D.shape[1]\n B = np.mat(np.eye(w) - np.dot(D.T, D)).I.dot(np.dot(D.T, pinvOfInput))\n else:\n B = pinv(C, c)\n pinvOfInput = np.vstack([(pinvOfInput - D.dot(B)), B])\n OutputWeightEnd = pinvOfInput.dot(train_y)\n InputOfOutputLayer = tempOfLastLayerInput\n Training_time = time.time() - time_start\n train_time[0][e + 1] = Training_time\n OutputOfTrain1 = InputOfOutputLayer.dot(OutputWeightEnd)\n TrainingAccuracy = show_accuracy(OutputOfTrain1, train_y)\n train_acc[0][e + 1] = TrainingAccuracy\n print('Incremental Training Accuracy is :', TrainingAccuracy * 100, ' %')\n\n # 增量增加节点的 测试过程\n time_start = time.time()\n OutputOfEnhanceLayerAddTest = tansig(\n InputOfEnhanceLayerWithBiasTest.dot(weightOfEnhanceLayerAdd) * parameterOfShrinkAdd[e]);\n InputOfOutputLayerTest = np.hstack([InputOfOutputLayerTest, OutputOfEnhanceLayerAddTest])\n\n OutputOfTest1 = InputOfOutputLayerTest.dot(OutputWeightEnd)\n TestingAcc = show_accuracy(OutputOfTest1, test_y)\n\n Test_time = time.time() - time_start\n test_time[0][e + 1] = Test_time\n test_acc[0][e + 1] = TestingAcc\n print('Incremental Testing Accuracy is : ', TestingAcc * 100, ' %');\n\n return test_acc, test_time, train_acc, train_time\n","sub_path":"CIFAR-10/bls_model.py","file_name":"bls_model.py","file_ext":"py","file_size_in_byte":16363,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"36311476","text":"\nimport people as ppl\nfrom twitter import usertimeline\nfrom pandas.io.json import json_normalize\nimport re\n\n\n\ndef 유저정보에_국회의원정보를_결합(dbg_on=False, return_type='all', 사전검증=False):\n \"\"\"기초 데이터 로딩\"\"\"\n #pp.pprint({'ppl.assem.ASS_TBL명':ppl.assem.ASS_TBL명})\n projection = {'_id':0, '이름':1, '정당명':1}\n df1 = mg.find(db명=DB명, tbl명=ppl.assem.ASS_TBL명, query=None, projection=projection, dbg_on=dbg_on, 컬럼순서li=[], df보고형태='df')\n #print(df1)\n\n #pp.pprint({'ppl.info.TBL명':ppl.info.TBL명})\n projection = {'_id':0, '이름':1, '직업':1}\n df2 = mg.find(db명=DB명, tbl명=ppl.info.TBL명, query=None, projection=projection, dbg_on=dbg_on, 컬럼순서li=[], df보고형태='df')\n #print(df2)\n\n query = {'user_relation':'friend'}\n df = mg.find(db명=DB명, tbl명=TBL명, query=query, projection=None, dbg_on=dbg_on, 컬럼순서li=[], df보고형태='df')\n\n\n \"\"\"트위터_유저TBL 기본청소\"\"\"\n df['json_dump'] = df['json_dump'].apply(lambda x: json.loads(x))\n df['json_dump'] = df['json_dump'].apply(lambda x: [x])\n dicli = df.to_dict('records')\n df = json_normalize(data=dicli, record_path='json_dump', meta=['수집일시', 'user_relation'], meta_prefix=None, record_prefix=None, errors='raise', sep='.')\n\n \"\"\"불필요 컬럼 제거.\"\"\"\n print(len(list(df.columns)))\n df = df.dropna(axis=1, how='any', thresh=None, subset=None, inplace=False)\n print(len(list(df.columns)))\n\n \"\"\"\n print('\\n'+'= '*30+'결합')\n 국회의원현황TBL의 이름은 3글자인데, 트위터 이름은 사족이 많다.\n 따라서 join 함수는 안 통한다.\n df = df.join(df1.set_index('이름'), on='name')\n #print(df.dtypes)\n \"\"\"\n\n \"\"\"트위터_유저 정보에 국회의원 이름이 regex 매치되면 정당명을 추가\"\"\"\n dicli_1 = df1.to_dict('records')\n dicli = df.to_dict('records')\n for d1 in dicli_1:\n for d in dicli:\n rs = re.search(pattern=d1['이름'], string=d['name'], flags=0)\n if rs is None:\n pass\n else:\n d['정당명'] = d1['정당명']\n d['직업'] = '국회의원'\n\n df = pd.DataFrame(dicli)\n #print(df.dtypes)\n #print(list(df['정당명'].unique()))\n\n \"\"\"트위터_유저 정보에 인물정보의 이름이 regex 매치되면 직업을 추가\"\"\"\n dicli_2 = df2.to_dict('records')\n dicli = df.to_dict('records')\n for d2 in dicli_2:\n for d in dicli:\n rs = re.search(pattern=d2['이름'], string=d['name'], flags=0)\n if rs is None: pass\n else: d['직업'] = d2['직업']\n\n df = pd.DataFrame(dicli)\n #print(df.dtypes)\n\n \"\"\"직업별 인원수 분포현황보고\"\"\"\n df9 = df.fillna(value={'직업':'_None'}, method=None, axis=None, inplace=False, limit=None, downcast=None)\n g = df9.groupby('직업').count().sort_values('name', ascending=False)\n g = g.loc[:,['name']]\n print(g)\n\n\n \"\"\"트위터 수집할 타겟 name | screen_name 과 추가된 정보를 저장\"\"\"\n df0 = df.loc[:,['name','screen_name','정당명','직업']]\n #df0 = df0.fillna(value='_None', method=None, axis=None, inplace=False, limit=None, downcast=None)\n df0 = df0.where((pd.notnull(df0)), None)\n #print(df0.dtypes)\n dicli_0 = df0.to_dict('records')\n mg.insert_many(db명=DB명, tbl명=usertimeline.CORE_TRGT_TBL, dicli=dicli_0, dbg_on=dbg_on, 사전검증=사전검증)\n\n\n \"\"\"국회의원 / 비국회의원 분포현황보고\"\"\"\n df9 = df.fillna(value={'정당명':'_None'}, method=None, axis=None, inplace=False, limit=None, downcast=None)\n print(list(df9['정당명'].unique()))\n df91 = df9[ df9['정당명'] != '_None' ]\n df92 = df9[ df9['정당명'] == '_None' ]\n #df1 = df.query('정당명 != \"_None\" ')\n #df2 = df.query('정당명 = \"_None\" ')\n dic = {\n '총 유저 수':len(df9),\n '국회의원 df91 수':len(df91),\n '비국회의원 df92 수':len(df92),\n }\n pp.pprint(dic)\n #print('\\n 비국회의원 이름 목록\\n')\n #print(df92)\n #pp.pprint(sorted(df92['name']))\n\n\n if return_type == 'all': return df\n else: return df1, df2\n","sub_path":"inews/twitter_bk.py","file_name":"twitter_bk.py","file_ext":"py","file_size_in_byte":4242,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"173110684","text":"import numpy as np\n\n\nclass ValueIteration(object):\n def __init__(self, world, one_step_cost_fn, discount_factor=0.9, eps=10e-4):\n \"\"\"\n Ctor for value iteration algorithm implementation.\n\n :param world: Instance of class 'World'\n :param one_step_cost_fn: Method that returns the one step cost given an instance of World, the current position.\n :param discount_factor: In range [0, 1)\n :param eps: Threshold for value function convergence\n \"\"\"\n self.world = world\n self.discount_factor = discount_factor\n self.eps = eps\n self.one_step_cost_fn = lambda current_pos, next_pos: one_step_cost_fn(self.world, current_pos, next_pos)\n\n self.value_fn = np.zeros(self.world.map.shape, np.float32)\n self.value_fn_history = list()\n\n def execute(self, max_iterations=int(10e6)):\n \"\"\"\n Starts the value iteration algorithm\n :param max_iterations: Maximum allowable number of iterations\n :return: None\n \"\"\"\n\n for k in range(max_iterations):\n prev_value_fn = np.copy(self.value_fn)\n self.value_fn_history.append(prev_value_fn)\n\n for y in range(self.world.world_height):\n for x in range(self.world.world_width):\n state = np.array([x, y], np.int32)\n if self.world.is_wall(state):\n continue\n\n min_cost = 10e6\n\n for action in self.world.actions:\n if not self.world.is_action_allowed(state, action):\n continue\n\n transitions = self.world.get_transitions(state, action)\n\n cost_fn = sum([transition_prob * (self.one_step_cost_fn(state, next_state) +\n (self.discount_factor * prev_value_fn[next_state[1], next_state[0]]))\n for next_state, transition_prob in transitions])\n\n min_cost = min(min_cost, cost_fn)\n\n if min_cost == 10e6:\n raise ValueError(\"No action could be applied on state (%d, %d). This state is probably \"\n \"surrounded by walls on all sides.\")\n\n self.value_fn[y, x] = min_cost\n\n if np.sum((np.absolute(self.value_fn - prev_value_fn) > self.eps).astype(np.int32)) == 0:\n print(\"Value iteration has converged after %d iterations\" % (k + 1))\n break\n\n self.value_fn_history.append(self.value_fn)\n\n def extract_policy(self):\n \"\"\"\n Computes the greedily induced policy from the current value function\n :return: The greedy policy for the current value function.\n \"\"\"\n\n optimal_policy = np.zeros([self.world.world_height, self.world.world_width, 2], np.float32)\n\n for y in range(self.world.world_height):\n for x in range(self.world.world_width):\n state = np.array([x, y], np.int32)\n if self.world.is_wall(state):\n continue\n\n min_cost = 10e6\n min_cost_action = None\n\n for action in self.world.actions:\n if not self.world.is_action_allowed(state, action):\n continue\n\n transitions = self.world.get_transitions(state, action)\n\n cost_fn = sum([transition_prob * (self.one_step_cost_fn(state, next_state) +\n (self.discount_factor * self.value_fn[next_state[1], next_state[0]]))\n for next_state, transition_prob in transitions])\n\n if cost_fn < min_cost:\n min_cost = cost_fn\n min_cost_action = action\n\n if min_cost_action is None:\n raise ValueError(\"No action found for state (%d, %d)\", x, y)\n else:\n optimal_policy[y, x] = min_cost_action\n\n return optimal_policy\n","sub_path":"value_iteration.py","file_name":"value_iteration.py","file_ext":"py","file_size_in_byte":4142,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"177613973","text":"from enum import Enum\nfrom tkinter import *\nfrom twenty_forty_eight_python.logic import *\nfrom random import *\n\nSIZE = 500\nGRID_LEN = 4\nGRID_PADDING = 10\n\nBACKGROUND_COLOR_GAME = \"#92877d\"\nBACKGROUND_COLOR_CELL_EMPTY = \"#9e948a\"\nBACKGROUND_COLOR_DICT = {2: \"#eee4da\", 4: \"#ede0c8\", 8: \"#f2b179\", 16: \"#f59563\",\n 32: \"#f67c5f\", 64: \"#f65e3b\", 128: \"#edcf72\", 256: \"#edcc61\",\n 512: \"#edc850\", 1024: \"#edc53f\", 2048: \"#edc22e\"}\nCELL_COLOR_DICT = {2: \"#776e65\", 4: \"#776e65\", 8: \"#f9f6f2\", 16: \"#f9f6f2\",\n 32: \"#f9f6f2\", 64: \"#f9f6f2\", 128: \"#f9f6f2\", 256: \"#f9f6f2\",\n 512: \"#f9f6f2\", 1024: \"#f9f6f2\", 2048: \"#f9f6f2\"}\nFONT = (\"Verdana\", 40, \"bold\")\n\nKEY_UP_ALT = \"\\'\\\\uf700\\'\"\nKEY_DOWN_ALT = \"\\'\\\\uf701\\'\"\nKEY_LEFT_ALT = \"\\'\\\\uf702\\'\"\nKEY_RIGHT_ALT = \"\\'\\\\uf703\\'\"\n\nKEY_UP = \"'w'\"\nKEY_DOWN = \"'s'\"\nKEY_LEFT = \"'a'\"\nKEY_RIGHT = \"'d'\"\n\n\nclass Moves(Enum):\n UP = 0\n DOWN = 1\n LEFT = 2\n RIGHT = 3\n\n\nclass TheGame:\n def __init__(self):\n self.commands = {Moves.UP: up, Moves.DOWN: down, Moves.LEFT: left, Moves.RIGHT: right}\n self.matrix = add_number(add_number(new_game(4)))\n self.score = 0\n self.sudden_death = False\n\n def make_move(self, move: Moves):\n self.matrix, done, score = self.commands[move](self.matrix, self.score)\n if done:\n self.score = score\n self.matrix = add_number(self.matrix)\n return 0\n elif self.sudden_death:\n return -1\n\n\nclass GameGrid(Frame):\n def __init__(self, game=None):\n Frame.__init__(self)\n\n self.grid()\n self.master.title('2048')\n self.master.bind(\"\", self.key_down)\n\n self.moves = {KEY_UP: Moves.UP, KEY_DOWN: Moves.DOWN,\n KEY_LEFT: Moves.LEFT, KEY_RIGHT: Moves.RIGHT}\n\n self.grid_cells = []\n self.init_grid()\n # Initialise the board\n if game:\n self.game = game\n else:\n self.game = TheGame()\n self.update_grid_cells()\n\n def init_grid(self):\n background = Frame(self, bg=BACKGROUND_COLOR_GAME, width=SIZE, height=SIZE)\n background.grid()\n for i in range(GRID_LEN):\n grid_row = []\n for j in range(GRID_LEN):\n cell = Frame(background, bg=BACKGROUND_COLOR_CELL_EMPTY, width=SIZE / GRID_LEN,\n height=SIZE / GRID_LEN)\n cell.grid(row=i, column=j, padx=GRID_PADDING, pady=GRID_PADDING)\n # font = Font(size=FONT_SIZE, family=FONT_FAMILY, weight=FONT_WEIGHT)\n t = Label(master=cell, text=\"\", bg=BACKGROUND_COLOR_CELL_EMPTY, justify=CENTER,\n font=FONT, width=4, height=2)\n t.grid()\n grid_row.append(t)\n\n self.grid_cells.append(grid_row)\n\n def update_grid_cells(self):\n for i in range(GRID_LEN):\n for j in range(GRID_LEN):\n new_number = self.matrix[i][j]\n if new_number == 0:\n self.grid_cells[i][j].configure(text=\"\", bg=BACKGROUND_COLOR_CELL_EMPTY)\n else:\n self.grid_cells[i][j].configure(text=str(new_number),\n bg=BACKGROUND_COLOR_DICT[new_number],\n fg=CELL_COLOR_DICT[new_number])\n if game_state(self.matrix) == 'win':\n self.grid_cells[1][1].configure(text=\"You\", bg=BACKGROUND_COLOR_CELL_EMPTY)\n self.grid_cells[1][2].configure(text=\"Win!\", bg=BACKGROUND_COLOR_CELL_EMPTY)\n if game_state(self.matrix) == 'lose':\n self.grid_cells[1][1].configure(text=\"You\", bg=BACKGROUND_COLOR_CELL_EMPTY)\n self.grid_cells[1][2].configure(text=\"Lose!\", bg=BACKGROUND_COLOR_CELL_EMPTY)\n self.update_idletasks()\n\n def key_down(self, event):\n key = repr(event.char)\n if key in self.moves and self.game.make_move(self.moves[key]) == 0:\n self.update_grid_cells()\n\n @property\n def matrix(self):\n return self.game.matrix\n\n\nif __name__ == '__main__':\n gamegrid = GameGrid()\n gamegrid.mainloop()\n","sub_path":"puzzle.py","file_name":"puzzle.py","file_ext":"py","file_size_in_byte":4228,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"392460948","text":"#!/usr/bin/env python\n\nimport os\nimport sys\n\ntry:\n import setuptools # noqa\nexcept ImportError:\n from ez_setup import use_setuptools\n use_setuptools()\n\ntry:\n from Cython.Build import cythonize\n CYTHON_AVAILABLE = True\nexcept ImportError:\n CYTHON_AVAILABLE = False\n\nfrom setuptools import setup, find_packages\nfrom setuptools.extension import Extension\n\n\ndef prepare_modules():\n\n modules = ['reduce', 'nonreduce', 'nonreduce_axis', 'move']\n\n # Don't attempt to import numpy until it needed; this\n # enables pip to install numpy before bottleneck\n import numpy as np\n\n # info needed to compile bottleneck\n kwargs = {}\n for module in modules:\n # `-O3` causes slow down of nanmin and nanmax; force `-O2`\n kwargs[module] = {'include_dirs': [np.get_include()],\n 'extra_compile_args': ['-O2']}\n if module == 'move':\n kwargs[module]['extra_compile_args'].insert(0, '-std=gnu89')\n\n if CYTHON_AVAILABLE:\n # create the C files\n from bottleneck.template.template import make_pyx\n make_pyx()\n return cythonize([Extension(\"bottleneck.%s\" % module,\n sources=[\"bottleneck/%s.pyx\" % module],\n **kwargs[module])\n for module in modules])\n else:\n # assume the presence of shipped C files\n return [Extension(\"bottleneck.%s\" % module,\n sources=[\"bottleneck/%s.c\" % module],\n **kwargs[module])\n for module in modules]\n\n\ndef get_long_description():\n with open('README.rst', 'r') as fid:\n long_description = fid.read()\n idx = max(0, long_description.find(\"Bottleneck is a collection\"))\n long_description = long_description[idx:]\n return long_description\n\n\ndef get_version_str():\n ver_file = os.path.join('bottleneck', 'version.py')\n with open(ver_file, 'r') as fid:\n version = fid.read()\n version = version.split(\"= \")\n version = version[1].strip()\n version = version.strip(\"\\\"\")\n return version\n\n\nCLASSIFIERS = [\"Development Status :: 4 - Beta\",\n \"Environment :: Console\",\n \"Intended Audience :: Science/Research\",\n \"License :: OSI Approved :: BSD License\",\n \"Operating System :: OS Independent\",\n \"Programming Language :: Cython\",\n \"Programming Language :: Python\",\n \"Programming Language :: Python :: 3\",\n \"Topic :: Scientific/Engineering\"]\n\n\nmetadata = dict(name='Bottleneck',\n maintainer=\"Keith Goodman\",\n maintainer_email=\"bottle-neck@googlegroups.com\",\n description=\"Fast NumPy array functions written in Cython\",\n long_description=get_long_description(),\n url=\"https://github.com/kwgoodman/bottleneck\",\n download_url=\"http://pypi.python.org/pypi/Bottleneck\",\n license=\"Simplified BSD\",\n classifiers=CLASSIFIERS,\n platforms=\"OS Independent\",\n version=get_version_str(),\n packages=find_packages(),\n package_data={'bottleneck': ['LICENSE']},\n requires=['numpy'],\n install_requires=['numpy'],\n setup_requires=['numpy'])\n\n\nif not(len(sys.argv) >= 2 and ('--help' in sys.argv[1:] or\n sys.argv[1] in ('--help-commands', 'egg_info', '--version', 'clean',\n 'build_sphinx'))):\n # build bottleneck\n metadata['ext_modules'] = prepare_modules()\nelif sys.argv[1] == 'build_sphinx':\n # create intro.rst (from readme file) for sphinx manual\n readme = 'README.rst'\n intro = os.path.join('doc', 'source', 'intro.rst')\n with open(readme, 'r') as infile, open(intro, 'w') as outfile:\n txt = infile.readlines()[2:] # skip travis build status\n outfile.write(''.join(txt))\n\nsetup(**metadata)\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":3979,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"520317478","text":"from __future__ import unicode_literals\n\nfrom django.conf import settings\nimport logging\nfrom requests import Response\n\nfrom songcritic.constant import Constant\nfrom songcritic.models import Album\nfrom songcritic.third_party.request_mixin import RequestMixin\n\n\nlogger = logging.getLogger(__name__)\n\n\nclass Metacritic(RequestMixin):\n UPDATE_THRESHOLD_DAYS = 14 # If a DB object is n days stale, fetch from API\n\n HEADERS = {'X-Mashape-Key': settings.METACRITIC_API_KEY}\n NO_MATCHING_ITEM = 'No matching item found!'\n\n class Endpoints(Constant):\n BASE = 'https://api-marcalencc-metacritic-v1.p.mashape.com'\n ALBUM = BASE + '/album/{}'\n ARTIST_ALBUM = BASE + '/person/{}/album'\n\n @classmethod\n def handle_response(cls, response):\n # type: (Response) -> dict\n result = None\n if response.status_code == 200:\n result = response.json()\n if result[0].get('Message') and result[0]['Message'].lower() == cls.NO_MATCHING_ITEM.lower():\n result = None\n elif response.status_code > 400:\n result = None\n\n if result is None:\n logger.warning('No Metacritic result for %s', response.url)\n return result\n\n @classmethod\n def get_album_rating(cls, album, year=None):\n # type: (Album, int) -> dict\n album_rating = None\n url = cls.Endpoints.BASE + album.id_mc\n\n if year:\n url += '/{}'.format(year)\n\n req_obj = cls.get_request_obj(url=url, method='get', threshold=cls.UPDATE_THRESHOLD_DAYS)\n if not req_obj:\n result = cls.get(url=url, handle_response=cls.handle_response, headers=cls.HEADERS)\n if result is None:\n logger.info('No Metacritic rating found for Album {}'.format(album.name))\n else:\n album_rating = result[0]\n else:\n logger.info('No request to %r, not past update threshold' % url)\n pass\n return album_rating\n\n @classmethod\n def get_artist_rating_and_albums(cls, artist_name, force_update=False):\n # type: (unicode, bool) -> dict\n result = None\n artist_name = cls.get_metacritic_name(artist_name)\n url = cls.Endpoints.ARTIST_ALBUM.format(artist_name)\n\n req_obj = cls.get_request_obj(url=url, method='get', threshold=cls.UPDATE_THRESHOLD_DAYS)\n if not req_obj:\n result = cls.get(url=url, handle_response=cls.handle_response, headers=cls.HEADERS)\n if result is None:\n pass\n else:\n # Retry getting the Request object. It should now exist\n req_obj = cls.get_request_obj(url=url, method='get', threshold=cls.UPDATE_THRESHOLD_DAYS)\n result = result[0]\n if result.get('Message') and result['Message'].lower() == cls.NO_MATCHING_ITEM.lower():\n result = None\n elif result.get('Exception'):\n if req_obj.attempts < 3: # Exception could be a mistake, try this again a few times\n logger.warning(\n 'Exception returned from url %r. Only attempted %r times, trying again',\n url,\n req_obj.attempts\n )\n return cls.get_artist_rating_and_albums(artist_name)\n result = None\n else:\n logger.info('No request to %r, not past update threshold' % url)\n pass\n\n return result\n\n @staticmethod\n def get_metacritic_name(s):\n # type: (unicode) -> unicode\n \"\"\"Convert api parameter to Metacritic format of dash separated\"\"\"\n\n # Remove chars that metacritic probably doesnt accept in API\n char_to_remove = '+'\n for char in char_to_remove:\n s.replace(char, '')\n\n result = None\n # If '-' is in the string its probably already converted into the right format\n if '-' in s:\n result = s\n else:\n try:\n result = s.lower().replace(' ', '-')\n except AttributeError as e:\n logger.critical(e)\n\n return result\n","sub_path":"songcritic/third_party/metacritic/metacritic.py","file_name":"metacritic.py","file_ext":"py","file_size_in_byte":4218,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"589686647","text":"from django.core.urlresolvers import reverse\nfrom seefithappen.core.tests import BaseTestCase\nfrom seefithappen.exercise.models import ExerciseVariation, ExerciseSuperCategory, ExerciseSubCategory, Exercise\nfrom seefithappen.workout.tests import WorkoutTestData\n\nclass ExerciseTestData(WorkoutTestData):\n\n def setUp(self):\n super(ExerciseTestData, self).setUp()\n\n super_category = ExerciseSuperCategory.objects.create(name='Test Super Category')\n sub_category = ExerciseSubCategory.objects.create(\n super_category=super_category,\n name='Test Sub Category',\n )\n exercise = Exercise.objects.create(\n sub_category=sub_category,\n name='Test Exercise'\n )\n\n self.exercise_variation = ExerciseVariation(\n exercise=exercise,\n name='Test Exercise Variation',\n )\n self.exercise_variation.save()\n\n def tearDown(self):\n super(ExerciseTestData, self).tearDown()\n\n\nclass ExerciseViewTests(BaseTestCase, ExerciseTestData):\n\n def test_exercise_add_view_get(self):\n response = self.client.get(reverse('exercise.add', args=[self.workout.id]))\n self.assertEquals(response.status_code, 200)\n self.assertTemplateUsed(response, 'exercise/exercise-add.html')\n\n def test_exercise_add_view_post(self):\n self.assertEquals(self.workout.exercises.count(), 0)\n post_params = {\n 'exercise_var': self.exercise_variation.id,\n }\n response = self.client.post(reverse('exercise.add', args=[self.workout.id]), post_params)\n self.assertEquals(response.status_code, 302)\n self.assertRedirects(response, reverse('workout.edit', args=[self.workout.id]))\n\n self.assertEquals(self.workout.exercises.count(), 1)\n","sub_path":"seefithappen/exercise/tests.py","file_name":"tests.py","file_ext":"py","file_size_in_byte":1798,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"145000434","text":"import curio\nimport os\nfrom . import worker\nfrom .db import JobDB\nfrom flask.config import Config\nimport sys\n\n\nINSTANCE_DIR = 'instance'\nSOCKNAME = 'workproc.sock'\n\n\nclass WorkProc:\n \"\"\"A container process for our worker threads that can receive\n notifications from a Unix domain socket.\n \"\"\"\n\n def __init__(self, basedir, db=None):\n \"\"\"Create a container using a given base directory for the\n storage and socket. Optionally, provide a database object to use\n that instead of creating a new one (to, for example, reuse its\n internal locks).\n \"\"\"\n self.basedir = os.path.abspath(basedir)\n\n # Load the configuration. We're just reusing Flask's simple\n # configuration component here.\n self.config = Config(self.basedir)\n self.config.from_object('buildbot.config_default')\n self.config.from_pyfile('buildbot.cfg', silent=True)\n\n # Create the database.\n self.db = db or JobDB(self.basedir)\n\n def start(self):\n \"\"\"Create and start the worker threads.\n \"\"\"\n threads = worker.work_threads(self.db, self.config)\n for thread in threads:\n if not thread.is_alive():\n thread.start()\n\n async def handle(self, client, addr):\n \"\"\"Handle an incoming socket connection.\n \"\"\"\n async for line in client.makefile('rb'):\n # Each line is a job name.\n job_name = line.decode('utf8').strip()\n print(job_name)\n\n # Just notify the database that something changed.\n with self.db.cv:\n self.db.cv.notify_all()\n\n def serve(self):\n \"\"\"Start listening on a Unix domain socket for incoming\n messages. Run indefinitely (until the server is interrupted).\n \"\"\"\n sockpath = os.path.join(self.basedir, SOCKNAME)\n if os.path.exists(sockpath):\n os.unlink(sockpath)\n try:\n curio.run(curio.unix_server, sockpath, self.handle)\n except KeyboardInterrupt:\n pass\n finally:\n os.unlink(sockpath)\n\n\ndef notify(basedir, jobname):\n \"\"\"Notify a running workproc that a new job has been added to the\n database (via the socket in basedir).\n \"\"\"\n curio.run(_notify, basedir, jobname)\n\n\nasync def _notify(basedir, jobname):\n sockpath = os.path.join(basedir, SOCKNAME)\n line = (jobname + '\\n').encode('utf8')\n sock = await curio.open_unix_connection(sockpath)\n await sock.makefile('wb').write(line)\n await sock.close()\n\n\nif __name__ == '__main__':\n p = WorkProc(sys.argv[1] if len(sys.argv) > 1 else INSTANCE_DIR)\n p.start()\n p.serve()\n","sub_path":"buildbot/buildbot/workproc.py","file_name":"workproc.py","file_ext":"py","file_size_in_byte":2672,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"473839692","text":"SAMPLES = 100\nCONVERGENCE = 0.1\nITERATIONS = 20\nITERATIONS_MULTI = 10000\nETA = 0.1\nALPHA = 0.9\nD_BATCH = 1\nD_SEQUENTIAL = 2\nPERCEPTRON = 3\nPLOTTING = True\nEARLY_STOP_THRESHOLD = 5\nEARLY_STOP_TOLERANCE = 1e-6 \nNOISE_SIGMA = 0.18\nLAMBDA = 0.1\n","sub_path":"Assignment1/Constants.py","file_name":"Constants.py","file_ext":"py","file_size_in_byte":241,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"611617159","text":"import pandas as pd \nimport os \nimport numpy as np \nimport matplotlib.pyplot as plt \nimport pandas as pd \n\n\ndef is_number(s):\n try:\n float(s)\n return True\n except ValueError:\n return False\n\ndef distanz(input,house): \n score = 0.0;\n for i in range(0, input.size - 1) :\n if isinstance((input[i]),str):\n if str(input[i]) == str(house[i]):\n score +=1 ; \n else:\n score += 0;\n else:\n if input[i] == house[i]:\n if input[i] == 0.0 or house[i] == 0.0:\n score+=0.3;\n else:\n score+=1;\n elif input[i] == 0.0 or house[i] == 0.0:\n score+=0;\n elif (input[i] + house[i]) == 1.0:\n score+=0;\n elif is_number(house[i]) :\n a = abs(input[i] - house[i]);\n score+=1/((abs(input[i]))/(a));\n return score; \n\ndef findsimilarhouses(inputfile,data):\n input = pd.read_csv(inputfile);\n df = data[list(input.columns.values)]\n scores = np.empty(len(df.index), dtype=float)\n for i in range(0, len(df.index)-1) : \n print(i);\n scores[i] = distanz(input.iloc[0],data.iloc[i])\n df['Score'] = scores; \n df = pd.DataFrame(df.sort_values(by=['Score'],ascending =False))\n df = pd.DataFrame(df.head())\n print(df.head())\n ## parse back to categorical! \n df.to_csv(\"test_similarhouses.csv\" )\n return df.head();\n \ndef run(inputfile):\n data = pd.read_csv(\"house_geo_binominal.csv\") \n findsimilarhouses(inputfile,data);\n ","sub_path":"similar.py","file_name":"similar.py","file_ext":"py","file_size_in_byte":1615,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"140337514","text":"import cv2\nimport os\nimport numpy as np\n\nimageformat = \".jpg\"\npath = '/home/vijesh/****PROJECT****/i-codes/error+fix'\nimfilelist = [os.path.join(path, f) for f in os.listdir(path) if f.endswith(imageformat)]\nfor el in imfilelist:\n img = cv2.imread(el)\n os.chdir('/home/vijesh') # head region\n\n resiz = cv2.resize(img, (206, 270))\n cv2.imwrite(str(el) , resiz)\n cv2.imshow('frame', resiz)\n #cv2.waitKey(30)\n\n\n# print 'staring frames=',startingframe\n# print 'ending frames=',endingframe\n\n\ncv2.destroyAllWindows()\n","sub_path":"resizing.py","file_name":"resizing.py","file_ext":"py","file_size_in_byte":530,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"129001926","text":"# -*- coding:utf-8 -*-\r\n# author:yufeixu\r\n# datetime:2019/6/27 17:14\r\n# software: PyCharm\r\nimport copy\r\n\r\n\r\nclass ListNode:\r\n def __init__(self, val):\r\n self.val = val\r\n self.next = None\r\n\r\n\r\nclass DoubleNode:\r\n def __init__(self, val):\r\n self.val = val\r\n self.last = None\r\n self.next = None\r\n\r\n\r\nclass ListNodeHelper:\r\n def __init__(self, head: ListNode):\r\n self.head_copy = copy.deepcopy(head)\r\n\r\n def traverse_list_node(self):\r\n temp = self.head_copy\r\n val_list = []\r\n while temp:\r\n val_list.append(str(temp.val))\r\n temp = temp.next\r\n return \" -> \".join(val_list) if len(val_list) > 0 else \"None\"\r\n","sub_path":"src/base/list_node.py","file_name":"list_node.py","file_ext":"py","file_size_in_byte":705,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"540960026","text":"# Escribir una función diasiguiente(…) que reciba como parámetro una fecha cualquiera\n# expresada por tres enteros (correspondientes al d��a, mes y año) y calcule y\n# devuelva tres enteros correspondientes el día siguiente al dado.\n# Utilizando esta función, desarrollar programas que permitan:\n# a. Sumar N días a una fecha.\n# b. Calcular la cantidad de días existentes entre dos fechas cualesquiera.\n\nimport funciones\nfrom Ej2b import EsFechaValida\n\ndef DiaSiguiente(dia, mes, anio):\n \"\"\"\n Determina el dia siguiente a una fecha ingresada\n \n Devuelve el dia, mes y año correspondientes al dia siguiente de la fecha ingresada\n \n Parámetros:\n dia -- numero entero positivo correspondiente al día del mes\n mes -- numero entero positivo correspondiente al mes del año\n anio -- numero entero positivo correspondiente al año calendario\n \"\"\"\n #Sumo un día\n if (EsFechaValida(dia + 1, mes, anio)):\n dia = dia + 1\n #Sino, paso al dia 1 y sumo un mes\n elif (EsFechaValida(1, mes + 1, anio)):\n dia = 1\n mes = mes + 1\n #Sino, paso el dia y el mes a 1 y sumo un año\n else:\n dia = 1\n mes = 1\n anio = anio + 1\n \n return dia, mes, anio\n\ndef main():\n #Sumar dias a una fecha\n print(\"Ejercicio 1.9 a: Sumar dias a una fecha\")\n print(\"Ingrese una fecha\")\n dia = funciones.IngresarPositivo(\"Ingrese el día: \")\n mes = funciones.IngresarPositivo(\"Ingrese el mes: \")\n anio = funciones.IngresarPositivo(\"Ingrese el año: \")\n if (EsFechaValida(dia, mes, anio)):\n dias = funciones.IngresarPositivo(\"Días a sumar: \")\n for i in range(dias):\n dia, mes, anio = DiaSiguiente(dia, mes, anio)\n print(\"La nueva fecha es:\", end=\" \")\n print(dia, mes, anio, sep=\"/\")\n else:\n print(\"La fecha ingresada no es valida\")\n \nif __name__ == \"__main__\":\n main()","sub_path":"Clase 3/Modulos/Ejemplo3/Ej9ab.py","file_name":"Ej9ab.py","file_ext":"py","file_size_in_byte":1911,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"354321339","text":"'''\n\nReceive a number between 0 and 1,000,000,000 from the user.\nUse while loop to find the number - when the number is found exit the loop and print the number to the console.\n\n'''\nuser_input = int(input(\"Enter a number: \"))\nnum = 20\n\nwhile user_input < num:\n for num in range(1,user_input):\n if user_input == num:\n print(num)\n break\n else:\n print(num)","sub_path":"labs/04_conditionals_loops/03_07_search.py","file_name":"03_07_search.py","file_ext":"py","file_size_in_byte":403,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"146648002","text":"# import\n# -*- coding:utf-8 -*-\n\nimport tensorflow as tf\nimport math\nimport argparse\n\n# 引き数処理\nparser = argparse.ArgumentParser()\nparser.add_argument('--data_dir', type=str, default='data_w2v/', help='Data set directory.')\nparser.add_argument('--log_dir', type=str, default='logs_w2v/', help='Log directory.')\nparser.add_argument('--max_vocab', type=int, default=2000, help='Max Vocablary size.')\nparser.add_argument('--skip_window', type=int, default=2, help='How many words to consider left and right.')\nparser.add_argument('--num_skips', type=int, default=4, help='How many times to reuse an input to generate a label.')\nparser.add_argument('--embedding_size', type=int, default=64, help=\"Dimension of the embedding vector.\")\nparser.add_argument('--num_sumpled', type=int, default=64, help=\"Number of negative examples to sample.\" )\nparser.add_argument('--num_step', type=int, default=10000, help=\"Train step.\" )\nparser.add_argument('--batch_size', type=int, default=64, help=\"Batch size.\" )\nparser.add_argument('--learning_rate', type=float, default=0.1, help=\"Learning rate.\" )\nparser.add_argument('--create_tsv', type=bool, default=True, help=\"Create words.tsv or not.\" )\n\nFLAGS, unparsed = parser.parse_known_args()\n\n# DataSetクラス\nimport glob\nimport re\nimport collections\nimport random\n\nimport numpy as np\nfrom janome.tokenizer import Tokenizer\n\nclass DataSet(object):\n\n def __init__(self, data_dir, max_vocab):\n\n #全データセットのファイルパスを取得\n file_pathes = []\n for file_path in glob.glob(data_dir+'*'):\n file_pathes.append(file_path)\n\n #ファイルを読み込み\n row_documents = [self._read_docment(file_path) for file_path in file_pathes]\n #必要な部分だけ抽出\n documents = [self._preprocessing(document) for document in row_documents]\n #形態素解析\n splited_documents = [self._morphological(document) for document in documents]\n\n words = []\n for word_list in splited_documents:\n words.extend(word_list)\n\n #データセット作成\n self.id_sequence, self.word_frequency, self.w_to_id, self.id_to_w = self._build_data_sets(words, max_vocab)\n print('Most common words (+UNK)', self.word_frequency[:5])\n print('Sample data.')\n print(self.id_sequence[:10])\n print([self.id_to_w[i] for i in self.id_sequence[:10]])\n self.data_index = 0\n\n #ファイルの読み込み\n def _read_docment(self, file_path):\n with open(file_path, 'r', encoding='sjis') as f:\n return f.read()\n\n #ヘッダなどの不要データを前処理。必要な部分だけを返す。\n def _preprocessing(self, document):\n\n lines = document.splitlines()\n processed_line = []\n\n horizontal_count = 0\n\n for line in lines:\n\n #ヘッダーは読み飛ばす\n if horizontal_count < 2:\n if line.startswith('-------'):\n horizontal_count += 1\n continue\n #フッターに入る行になったらそれ以降は無視\n if line.startswith('底本:'):\n break\n\n line = re.sub(r'《.*》', '', line) #ルビを除去\n line = re.sub(r'[.*]', '', line) #脚注を除去\n line =re.sub(r'[!-~]', '', line) #半角記号を除去\n line =re.sub(r'[︰-@]', '', line) #全角記号を除去\n line = re.sub('|', '', line) # 脚注の始まりを除去\n\n processed_line.append(line)\n\n return ''.join(processed_line)\n\n #形態素解析\n def _morphological(self, document):\n\n word_list = []\n t = Tokenizer()\n for token in t.tokenize(document):\n #名詞(一般)動詞(自立)、形容詞(自立)以外は除外\n if token.part_of_speech.startswith('名詞,一般') and token.base_form != '':\n word_list.append(token.base_form)\n if token.part_of_speech.startswith('動詞,自立') and token.base_form != '':\n word_list.append(token.base_form)\n if token.part_of_speech.startswith('形容詞,自立') and token.base_form != '':\n word_list.append(token.base_form)\n return word_list\n\n #辞書作成\n def _build_data_sets(self, words, max_vocab):\n\n #単語出現回数を解析。出現数が少ないたんをUnknown wordとしてひとくくりに扱う\n word_frequency = [['UNW', -1]]\n word_frequency.extend(collections.Counter(words).most_common(max_vocab - 1))\n #単語=>IDの辞書\n w_to_id = dict()\n for word, _ in word_frequency:\n w_to_id[word] = len(w_to_id)\n #形態素解析した文章を単語IDの並びに変換\n id_sequence = list()\n unw_count = 0\n for word in words:\n #UNK処理\n if word in w_to_id:\n index = w_to_id[word]\n else:\n index = 0\n unw_count += 1\n id_sequence.append(index)\n word_frequency[0][1] = unw_count\n #単語ID=>単語の辞書\n id_to_w = dict(zip(w_to_id.values(), w_to_id.keys()))\n return id_sequence, word_frequency, w_to_id, id_to_w\n\n # num_skip:1つの入力をどれだけ再利用するか\n # skip_window: 左右何語までを正解対象にするか\n def create_next_batch(self, batch_size, num_skips, skip_window):\n\n assert batch_size % num_skips == 0\n #一つの入力の再利用回数が対象範囲全件を超えてはならない\n assert num_skips <= 2 * skip_window\n inputs = np.ndarray(shape=(batch_size), dtype=np.int32)\n labels = np.ndarray(shape=(batch_size, 1), dtype=np.int32)\n\n span = 2 * skip_window + 1\n buffer = collections.deque(maxlen=span)\n #データセットが1週しそうならindexを最初にもどす\n if self.data_index + span > len(self.id_sequence):\n self.data_index = 0\n #初期のqueueを構築(window内の単語をすべて格納)\n buffer.extend(self.id_sequence[self.data_index:self.data_index+span])\n self.data_index += span\n\n for i in range(batch_size // num_skips):\n #中心は先に正解データから除外\n target = skip_window\n targets_to_avoid = [skip_window]\n for j in range(num_skips):\n #すでに選ばれている物以外から正解データのインデックスを取得\n while target in targets_to_avoid:\n target = random.randint(0, span - 1)\n #次回以降targetにならないように\n targets_to_avoid.append(target)\n #入力値になるのはbufferの中心\n inputs[i * num_skips + j] = buffer[skip_window]\n #ランダムに指定した周辺単語が正解データに\n labels[i * num_skips + j, 0] = buffer[target]\n\n #次に入れる単語がデータセットにない場合はbufferには最初の値を入力\n if self.data_index == len(self.id_sequence):\n buffer = self.id_sequence[:span]\n self.data_index = span\n else:\n #bufferに次の単語を追加してindexを1進める\n buffer.append(self.id_sequence[self.data_index])\n self.data_index += 1\n #最後の方のデータが使われないことを避けるために少しだけindexを元に戻す\n self.data_index = (self.data_index + len(self.id_sequence) - span) % len(self.id_sequence)\n\n return inputs, labels\n\n\n# データセットオブジェクトを作成\ndata = DataSet(FLAGS.data_dir, FLAGS.max_vocab)\n\n# Embeddings用に使うラベルをtsv形式で保存\nif FLAGS.create_tsv:\n sorted_dict = sorted(data.w_to_id.items(), key=lambda x: x[1])\n words = [ \"{word}\\n\".format(word=x[0]) for x in sorted_dict]\n tf.gfile.MakeDirs(FLAGS.log_dir)\n with open(FLAGS.log_dir+\"words.tsv\", 'w', encoding=\"utf-8\") as f:\n f.writelines(words)\n print(\"Embeddings metadata was saved to \"+FLAGS.log_dir+\"/words.tsv\")\nbatch_size = FLAGS.batch_size\nembedding_size = FLAGS.embedding_size\nvocab_size = len(data.w_to_id)\n\n# placeholderの定義\ntrain_inputs = tf.placeholder(tf.int32, shape=[batch_size])\ntrain_labels = tf.placeholder(tf.int32, shape=[batch_size, 1])\n\n# 中間層\nembedding = tf.Variable(tf.random_uniform([vocab_size, embedding_size], -1.0, 1.0))\nembed = tf.nn.embedding_lookup(embedding, train_inputs)\n\n# 出力層\nnce_weights = tf.Variable(tf.truncated_normal([vocab_size, embedding_size], stddev =1.0 / math.sqrt(embedding_size)))\nnce_biases = tf.Variable(tf.zeros([vocab_size]))\n\n# 損失関数\nnce_loss = tf.nn.nce_loss(nce_weights, nce_biases, train_labels, embed, FLAGS.num_sumpled, vocab_size)\nloss = tf.reduce_mean(nce_loss)\n\n# 訓練方法\nglobal_step = tf.train.get_or_create_global_step()\ntrain_op = tf.train.GradientDescentOptimizer(FLAGS.learning_rate).minimize(loss, global_step=global_step)\n\n# モデル保存用\nsaver = tf.train.Saver(max_to_keep=3)\n\n# 訓練\nsess = tf.Session()\n\n# 初期化 or モデル読み込み\nckpt_state = tf.train.get_checkpoint_state(FLAGS.log_dir)\nif ckpt_state:\n last_model = ckpt_state.model_checkpoint_path\n saver.restore(sess,last_model)\n print(\"model was loaded:\", last_model)\nelse:\n init = tf.global_variables_initializer()\n sess.run(init)\n print(\"initialized.\")\n\nlast_step = sess.run(global_step)\naverage_loss = 0\nfor i in range(FLAGS.num_step):\n\n step = last_step + i + 1\n batch_inputs, batch_labels = data.create_next_batch(batch_size, FLAGS.num_skips, FLAGS.skip_window)\n feed_dict = {train_inputs: batch_inputs, train_labels: batch_labels}\n\n _, loss_val = sess.run([train_op, loss], feed_dict=feed_dict)\n average_loss += loss_val\n\n if step % 100 == 0:\n average_loss /= 100\n print('Average loss at step ', step, ': ', average_loss)\n average_loss = 0\n saver.save(sess, FLAGS.log_dir+'my_model.ckpt', step)\n","sub_path":"code/word2vec/word2vec.py","file_name":"word2vec.py","file_ext":"py","file_size_in_byte":10174,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"9793211","text":"def absolutePermutation(n, k):\n arr = {}\n for i in range(1, n+1):\n if i - k > 0 and (i-k) not in arr:\n arr[i-k] = i-k\n elif i+k <= n and (i+k) not in arr:\n arr[i+k] = i+k\n else:\n return -1\n print([*arr])\n return arr\n\n\nabsolutePermutation(3, 2)\n","sub_path":"Algorithm-Python/hackerRank/absolutePermutation.py","file_name":"absolutePermutation.py","file_ext":"py","file_size_in_byte":310,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"163537281","text":"#11866번 요세푸스 문제\r\n#121808KB 176ms\r\n\r\nN,K = map(int,input().split())\r\narr = list(range(N,0,-1))\r\nresult = []\r\n\r\nidx = 0\r\nwhile len(arr) > 0 :\r\n if idx == K-1 : \r\n idx = 0\r\n result.append(arr[-1])\r\n arr.pop()\r\n else :\r\n arr.insert(0,arr[-1])\r\n arr.pop()\r\n idx += 1\r\n\r\nresult = list(map(str,result))\r\n\r\nprint('<'+', '.join(result)+'>')","sub_path":"Algorithm/Baekjoon/queue_11866.py","file_name":"queue_11866.py","file_ext":"py","file_size_in_byte":365,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"428783383","text":"from django.urls import path\nfrom . import views\n\napp_name = 'store'\n\nurlpatterns = [\n path('add-employee/', views.AddEmployee.as_view(), name='add-employee'),\n path('get-employees/', views.GetEmployees.as_view(), name='get-employees'),\n]\n\n","sub_path":"store/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":246,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"246104384","text":"import ssg.utils\nimport os\n\n\ndef preprocess(data, lang):\n path = data[\"path\"]\n name = ssg.utils.escape_id(os.path.basename(path))\n data[\"name\"] = name\n if lang == \"oval\":\n data[\"path\"] = path.replace(\"/\", \"\\\\/\")\n return data\n","sub_path":"shared/templates/audit_rules_usergroup_modification/template.py","file_name":"template.py","file_ext":"py","file_size_in_byte":247,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"379291713","text":"import numpy as np\nimport pandas as pd\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.metrics import roc_auc_score, confusion_matrix\nfrom lifelines import CoxPHFitter\nfrom datautils.dataset import Dataset\nfrom datautils.data import Data\nfrom datautils.helper import save_output\nfrom tqdm import tqdm\nimport argparse\n\n\n#%%\narg_parser = argparse.ArgumentParser()\n\narg_parser.add_argument('--imputation_mode', default=\"mean\")\narg_parser.add_argument('--seed', type=int, default=42)\narg_parser.add_argument('--positive_weight', type=int, default=56)\n\nARGS = arg_parser.parse_args()\n\n\n#%%\nprint(f\"Running Cox with imputation_mode = {ARGS.imputation_mode}, seed = {ARGS.seed}\")\n\nprint('Arguments:', ARGS)\n\n#%%\ndataset = Dataset(\"data/challenge_data\",\n batchSize=100,\n train_ratio=0.8,\n normalize=True,\n padding=False,\n imputeForward=(False if ARGS.imputation_mode == \"mean\" else True),\n calculateDelay=False,\n seed=ARGS.seed)\n\n\n#%%\ncolumns = list(dataset.train_data.features.keys())[:-2]\n\n# dataset.train_data.x.shape\n# dataset.val_data.x.shape\n# dataset.test_data.x.shape\n\n\n#%%\n# create windowing system here\nT = 6\n#idx = 10\ndef process_data(d: Data, T: int) -> (pd.DataFrame, np.array):\n npa = d.x\n target_npa = d.y\n \n processed = []\n labels = []\n\n print(\"* Processing data...\")\n for idx in tqdm(range(npa.shape[0])):\n if target_npa[idx].sum() == 0:\n processed.extend([[row,7,1] for row in npa[idx]])\n else:\n sepsis_count = 0\n for i in range(npa[idx].shape[0]):\n t = (T + 1) - sepsis_count\n t = t if t >= 1 else 1\n s = 1 if t > T else 0\n processed.append([npa[idx][i],t,s])\n sepsis_count += 1 if target_npa[idx][i][0] == 1 else 0\n \n labels.extend(target_npa[idx].flatten().tolist())\n \n return (pd.DataFrame(processed, columns=[\"x\",\"t\",\"s\"]), np.array(labels))\n# Naive windowing:\n# for i in range(df[idx].shape[0]):\n# window = df[idx][i:i+T]\n# matches = np.where(window[:,-1]==1)[0]\n# if matches.size > 0:\n# t = matches[0] + 1\n# s = 0\n# else:\n# t = T + 1\n# s = 1\n# processed.append([df[idx][i][:-1],t,s])\n\n\n#%%\nX_train, y_train = process_data(dataset.train_data, T)\nX_val, y_val = process_data(dataset.val_data, T)\nX_test, y_test = process_data(dataset.test_data, T)\n\n\n#%%\n# X_train.head()\n\n\n#%%\ninverse_s = 1-X_train.s\nX_train_cph = pd.DataFrame(X_train.x.values.tolist(), columns=columns)\nX_train_cph[\"s\"] = inverse_s\nX_train_cph[\"w\"] = (inverse_s * ARGS.positive_weight) + X_train.s\nX_train_cph[\"t\"] = X_train.t\n\n\n#%%\ncph = CoxPHFitter(penalizer=0.2)\ncph.fit(X_train_cph, duration_col='t', event_col='s', weights_col='w', step_size=0.070, show_progress=True, robust=False)\n\n\n#%%\n#cph.check_assumptions(X_train_cph,show_plots=False,plot_n_bootstraps=0)\n#cph.print_summary()\n\n\n#%%\ndef get_metrics(ty, py, threshold=0.5):\n print('-'*20)\n auc = roc_auc_score(ty, py)\n print(f\"AUC = {auc}\")\n lst = [1 if i >=0.5 else 0 for i in py]\n acc = ((lst == ty).sum() / ty.shape[0]) * 100\n print(f\"Accuracy = {acc}\")\n c_m = confusion_matrix(ty, np.array(py > threshold).astype(int))\n print(c_m)\n PPV = c_m[1,1] / (c_m[1,1] + c_m[0,1])\n print(f\"PPV/Precision = {PPV}\")\n TPR = c_m[1,1] / c_m[1].sum()\n print(f\"TPR/Sensitivity/Recall = {TPR}\")\n TNR = c_m[0,0] / c_m[0].sum()\n print(f\"TNR/Specificity = {TNR}\")\n print('-'*20)\n\n\n#%%\ndef get_preds(df: pd.DataFrame, columns):\n cph_df = pd.DataFrame(df.x.values.tolist(), columns=columns)\n \n preds = 1-cph.predict_survival_function(cph_df,times=[6])\n \n return preds\n\n\n#%%\nprint(\"Train:\")\ntrain_preds = get_preds(X_train, columns)\nget_metrics(y_train, train_preds, threshold=0.5)\nprint(\"Val:\")\nval_preds = get_preds(X_val, columns)\nget_metrics(y_val, val_preds, threshold=0.5)\nprint(\"Test:\")\ntest_preds = get_preds(X_test, columns)\nget_metrics(y_test, test_preds, threshold=0.5)\n\n\n#%%\ntest_preds = test_preds.values\n\n\n#%%\ngrouped_preds = []\n\ncur = 0\nfor x_length in dataset.test_data.x_lengths:\n grouped_preds.append(list(test_preds[cur:cur+x_length].reshape((-1,1))))\n cur += x_length\n\n\n#%%\nsave_output(grouped_preds, list(dataset.test_data.files), \"results\", \"COX\", ARGS.imputation_mode, seed=ARGS.seed, threshold=0.5)\n\nprint('Finished!', '='*20)\n","sub_path":"Cox.py","file_name":"Cox.py","file_ext":"py","file_size_in_byte":4647,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"426612935","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Feb 24 22:13:20 2017\n\n@author: linhb\n\"\"\"\n\nfrom keras.layers import Input, Dense\nfrom keras.models import Model\nfrom keras import backend as K\nK.set_image_dim_ordering('tf')\n\nfrom keras.datasets import mnist\nimport numpy as np\n(x_train, _), (x_test, _) = mnist.load_data()\n\n#============SIMPLE MODEL============#\n(x_train, _), (x_test, _) = mnist.load_data()\nx_train = x_train.astype('float32') / 255.\nx_test = x_test.astype('float32') / 255.\nx_train = x_train.reshape((len(x_train), np.prod(x_train.shape[1:])))\nx_test = x_test.reshape((len(x_test), np.prod(x_test.shape[1:])))\nprint(x_train.shape)\nprint(x_test.shape)\n\n# this is the size of our encoded representations\nencoding_dim = 32 # 32 floats -> compression of factor 24.5, assuming the input is 784 floats\n\n# encode\ninput_img = Input(shape=(784,))\nencoded = Dense(128, activation='relu')(input_img)\nencoded = Dense(64, activation='relu')(encoded)\nencoded = Dense(32, activation='relu')(encoded)\n\n# decode\ndecoded = Dense(64, activation='relu')(encoded)\ndecoded = Dense(128, activation='relu')(decoded)\ndecoded = Dense(784, activation='sigmoid')(decoded)\n\nautoencoder = Model(input=input_img, output=decoded)\nautoencoder.compile(optimizer='adadelta', loss='binary_crossentropy')\n\nautoencoder.fit(x_train, x_train,\n nb_epoch=100,\n batch_size=256,\n shuffle=True,\n validation_data=(x_test, x_test), verbose=2)\n\n# decode some digits\ndecoded_imgs = autoencoder.predict(x_test)\n\n# use Matplotlib (don't ask)\nimport matplotlib.pyplot as plt\n\nn = 10 # how many digits we will display\nplt.figure(figsize=(20, 4))\nfor i in range(n):\n # display original\n ax = plt.subplot(2, n, i + 1)\n plt.imshow(x_test[i].reshape(28, 28))\n plt.gray()\n ax.get_xaxis().set_visible(False)\n ax.get_yaxis().set_visible(False)\n\n # display reconstruction\n ax = plt.subplot(2, n, i + 1 + n)\n plt.imshow(decoded_imgs[i].reshape(28, 28))\n plt.gray()\n ax.get_xaxis().set_visible(False)\n ax.get_yaxis().set_visible(False)\nplt.show()\n\n#============CNN MODEL============#\n(x_train, _), (x_test, _) = mnist.load_data()\nx_train = x_train.astype('float32') / 255.\nx_test = x_test.astype('float32') / 255.\nx_train = np.reshape(x_train, (len(x_train), 1, 28, 28))\nx_test = np.reshape(x_test, (len(x_test), 1, 28, 28))\n\nfrom keras.layers import Input, Dense, Convolution2D, MaxPooling2D, UpSampling2D\nfrom keras.models import Model\n\ninput_img = Input(shape=(1, 28, 28))\n\nx = Convolution2D(16, 3, 3, activation='relu', border_mode='same')(input_img)\nx = MaxPooling2D((2, 2), border_mode='same')(x)\nx = Convolution2D(8, 3, 3, activation='relu', border_mode='same')(x)\nx = MaxPooling2D((2, 2), border_mode='same')(x)\nx = Convolution2D(8, 3, 3, activation='relu', border_mode='same')(x)\nencoded = MaxPooling2D((2, 2), border_mode='same')(x)\n\n# at this point the representation is (8, 4, 4) i.e. 128-dimensional\n\nx = Convolution2D(8, 3, 3, activation='relu', border_mode='same')(encoded)\nx = UpSampling2D((2, 2))(x)\nx = Convolution2D(8, 3, 3, activation='relu', border_mode='same')(x)\nx = UpSampling2D((2, 2))(x)\nx = Convolution2D(16, 3, 3, activation='relu')(x)\nx = UpSampling2D((2, 2))(x)\ndecoded = Convolution2D(1, 3, 3, activation='sigmoid', border_mode='same')(x)\n\nautoencoder = Model(input_img, decoded)\nautoencoder.compile(optimizer='adadelta', loss='binary_crossentropy')\n\nautoencoder.fit(x_train, x_train,\n nb_epoch=50,\n batch_size=128,\n shuffle=True,\n validation_data=(x_test, x_test), verbose=2)\n\n#============VARIATIONAL MODEL============#\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom scipy.stats import norm\n\nfrom keras.layers import Input, Dense, Lambda\nfrom keras.models import Model\nfrom keras import backend as K\nfrom keras import objectives\nfrom keras.datasets import mnist\n\nbatch_size = 100\noriginal_dim = 784\nlatent_dim = 2\nintermediate_dim = 256\nnb_epoch = 50\nepsilon_std = 1.0\n\nx = Input(batch_shape=(batch_size, original_dim))\nh = Dense(intermediate_dim, activation='relu')(x)\nz_mean = Dense(latent_dim)(h)\nz_log_var = Dense(latent_dim)(h)\n\n\ndef sampling(args):\n z_mean, z_log_var = args\n epsilon = K.random_normal(shape=(batch_size, latent_dim), mean=0.,\n std=epsilon_std)\n return z_mean + K.exp(z_log_var / 2) * epsilon\n\n# note that \"output_shape\" isn't necessary with the TensorFlow backend\nz = Lambda(sampling, output_shape=(latent_dim,))([z_mean, z_log_var])\n\n# we instantiate these layers separately so as to reuse them later\ndecoder_h = Dense(intermediate_dim, activation='relu')\ndecoder_mean = Dense(original_dim, activation='sigmoid')\nh_decoded = decoder_h(z)\nx_decoded_mean = decoder_mean(h_decoded)\n\n\ndef vae_loss(x, x_decoded_mean):\n xent_loss = original_dim * objectives.binary_crossentropy(x, x_decoded_mean)\n kl_loss = - 0.5 * K.sum(1 + z_log_var - K.square(z_mean) - K.exp(z_log_var), axis=-1)\n return xent_loss + kl_loss\n\nvae = Model(x, x_decoded_mean)\nvae.compile(optimizer='rmsprop', loss=vae_loss)\n\n# train the VAE on MNIST digits\n(x_train, y_train), (x_test, y_test) = mnist.load_data()\n\nx_train = x_train.astype('float32') / 255.\nx_test = x_test.astype('float32') / 255.\nx_train = x_train.reshape((len(x_train), np.prod(x_train.shape[1:])))\nx_test = x_test.reshape((len(x_test), np.prod(x_test.shape[1:])))\n\nvae.fit(x_train, x_train,\n shuffle=True,\n nb_epoch=nb_epoch,\n batch_size=batch_size,\n validation_data=(x_test, x_test), verbose =2)\n\n# build a model to project inputs on the latent space\nencoder = Model(x, z_mean)\n\n# display a 2D plot of the digit classes in the latent space\nx_test_encoded = encoder.predict(x_test, batch_size=batch_size)\nplt.figure(figsize=(6, 6))\nplt.scatter(x_test_encoded[:, 0], x_test_encoded[:, 1], c=y_test)\nplt.colorbar()\nplt.show()\n\n# build a digit generator that can sample from the learned distribution\ndecoder_input = Input(shape=(latent_dim,))\n_h_decoded = decoder_h(decoder_input)\n_x_decoded_mean = decoder_mean(_h_decoded)\ngenerator = Model(decoder_input, _x_decoded_mean)\n\n# display a 2D manifold of the digits\nn = 15 # figure with 15x15 digits\ndigit_size = 28\nfigure = np.zeros((digit_size * n, digit_size * n))\n# linearly spaced coordinates on the unit square were transformed through the inverse CDF (ppf) of the Gaussian\n# to produce values of the latent variables z, since the prior of the latent space is Gaussian\ngrid_x = norm.ppf(np.linspace(0.05, 0.95, n))\ngrid_y = norm.ppf(np.linspace(0.05, 0.95, n))\n\nfor i, yi in enumerate(grid_x):\n for j, xi in enumerate(grid_y):\n z_sample = np.array([[xi, yi]])\n x_decoded = generator.predict(z_sample)\n digit = x_decoded[0].reshape(digit_size, digit_size)\n figure[i * digit_size: (i + 1) * digit_size,\n j * digit_size: (j + 1) * digit_size] = digit\n\nplt.figure(figsize=(10, 10))\nplt.imshow(figure, cmap='Greys_r')\nplt.show()\n\n","sub_path":"Tutorial_Python/audocoder.py","file_name":"audocoder.py","file_ext":"py","file_size_in_byte":7002,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"359434597","text":"from . import * \nfrom app.mchat.models.user import * \n\n# Participant model (linking users to chats)\nclass Participant(Base):\n\t\n\t# Table name\n\t__tablename__ = \"participants\"\n\t\n\t# Foreign key to user \n\tuser_id = db.Column(db.Integer, db.ForeignKey('users.id'))\n\t\n\t# Foreign key to chat \n\tchat_id = db.Column(db.Integer, db.ForeignKey('chats.id'), index=True)\n\n\tdef __init__(self, user_id, chat_id):\n\n\t\tself.user_id = user_id\n\t\tself.chat_id = chat_id\n\n\tdef __repr__(self):\n\t\trep = \"\"\n\t\treturn rep\n\n\n\n# Participant schema\nclass ParticipantSchema(BaseSchema):\n\n\tuser_id = field_for(Participant, 'user_id', dump_only=False)\n\tchat_id = field_for(Participant, 'chat_id', dump_only=False)\n\n\tclass Meta(BaseSchema.Meta):\n\t\tmodel = Participant\n\n\t# Validates uniqueness of combo \n\t@validates_schema\n\tdef unique_user_chat(self, data):\n\t\tuser_id = int(data['user_id'])\n\t\tchat_id = int(data['chat_id'])\n\n\t\tparts = db.session.query(Participant).filter(Participant.user_id == user_id)\n\t\tparts = parts.filter(Participant.chat_id == chat_id)\n\t\tif len(parts.all()) > 0: \n\t\t\traise ValidationError(\"You are already part of this chat\")\n\n\n\t@post_dump \n\tdef add_user(self, item):\n\t\tuser_id = int(item['user_id'])\n\t\titem.pop('user_id', None) # Get rid of this\n\t\tuser = db.session.query(User).filter(User.id == user_id).first() \n\t\tuser_json = UserSchema(exclude=('password_digest',)).dump(user).data\n\t\titem['user'] = user_json\n\t\treturn item\n\n\n\n\n\n\n\n","sub_path":"app/mchat/models/participant.py","file_name":"participant.py","file_ext":"py","file_size_in_byte":1511,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"83365378","text":"names = ['name1', 'name2', 'name3']\nprint(isinstance(names, list))\nnum_names=len(names)\nprint(isinstance(num_names, list))\n\n\nprint(\"===================nesting array===================\")\nmovies = [\n\t\"00\", \"01\", \"02\",\n\t\t[\"10\",\t\n\t\t\t[\"20\", \"21\", \"22\", [\"30\", \"31\"]]]]\nfor each_item in movies:\n\tif isinstance(each_item, list):\n\t\tfor nested_item in each_item:\n\t\t\tif isinstance(nested_item, list):\n\t\t\t\tfor deeper_item in nested_item:\n\t\t\t\t\tprint(deeper_item)\n\t\t\telse:\n\t\t\t\tprint(nested_item)\n\telse:\n\t\tprint(each_item)\n\n","sub_path":"python/Head+First+Python/isinstance.py","file_name":"isinstance.py","file_ext":"py","file_size_in_byte":510,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"217833663","text":"\"\"\"\nThis script removes logging statements form java projects\n\"\"\"\nimport shutil\nimport tarfile\nimport threading\nfrom queue import Queue\nimport os\nimport re\nimport itertools\nimport json\nfrom numpy import True_\nimport pandas as pd\nimport ast\nimport subprocess\nimport multiprocessing\nfrom collections import defaultdict\nimport sys\n\nsys.path.insert(0, os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))\nimport src.util.utils as ut\n\nlogger = ut.setlogger(\n f_log='log/log_removal/log_removal.log',\n logger=\"log_remover\",\n)\nlock = ut.setRWLock()\n\n\nclass LogRemover:\n def __init__(self, f_removal,\n sample_dir='result/proj_sample',\n f_log_stats='conf/log_all_stats.csv',\n repeats=1,\n sample_percentage=0.1,\n sample_sizes=['small', 'medium', 'large', 'vlarge'],\n is_remove_cleaned_project=False,\n is_archive_cleaned_project=True,\n is_ignore_failed_clone_detections=True):\n\n self.f_removal = f_removal\n ut.create_folder_if_not_exist(os.path.dirname(f_removal))\n # f_removal records processed files and lines in JSON\n if os.path.isfile(f_removal):\n with open(f_removal) as r:\n self.logging_remove_json = json.load(r)\n else:\n self.logging_remove_json = defaultdict(dict)\n\n self.d_proj_size = 'result/proj_size'\n self.sample_sizes = sample_sizes\n self.repeats = repeats\n self.lu_levels = self.load_lu_levels()\n self.df_proj_lus = self.load_lu_per_project(f_log_stats)\n self.is_remove_cleaned_project = is_remove_cleaned_project\n self.is_archive_cleaned_project = is_archive_cleaned_project\n self.is_ignore_failed_clone_detections = is_ignore_failed_clone_detections\n if is_ignore_failed_clone_detections:\n self.ignore_projects = self._get_ignored_projects()\n self.archive_dir = ut.getPath('CLEAN_REPO_ARCHIVE_ROOT')\n if is_archive_cleaned_project:\n ut.create_folder_if_not_exist(self.archive_dir)\n if repeats ==0:\n sample_dirname = 'inner_proj_clone_detection'\n self.sample_dir = sample_dir\n else:\n if isinstance(sample_percentage, float):\n sample_dirname = os.path.join('projects_clean', '%d_p' % int(sample_percentage * 100))\n elif isinstance(sample_percentage, int):\n sample_dirname = os.path.join('projects_clean', '%d_n' % sample_percentage)\n self.sample_dir = os.path.join(sample_dir, sample_dirname)\n if not os.path.isdir(self.sample_dir):\n os.makedirs(self.sample_dir)\n \n # Generate sampled projects from each size\n self.project_sample(sample_percentage=sample_percentage)\n self.d_clean_project_root = os.path.join(ut.getPath('TEMP_PROJ_ROOT', ischeck=False), sample_dirname)\n ut.create_folder_if_not_exist(self.d_clean_project_root)\n\n def load_lu_per_project(self, f):\n \"\"\"\n Load log_all_stats.csv and get the LUs used in each project\n This file currently is not being tracked since its generated by Chen not us\n We do not wish to disclose too much details before we have Chen's permission\n Parameters\n ----------\n f\n\n Returns\n -------\n\n \"\"\"\n df = ut.csv_loader(f)\n df['project_id'] = df['project'].apply(lambda x: int(x.split('-')[0]))\n keep_cols = ['project_id', 'others'] + [x for x in self.lu_levels.keys() if x in df.columns]\n return df[keep_cols]\n\n def load_lu_levels(self, f='conf/lu_levels.json'):\n \"\"\"\n Load logging utilities\n Parameters\n ----------\n f\n extra\n\n Returns\n -------\n\n \"\"\"\n with open(f) as r:\n lu_levels = json.load(r)\n return lu_levels\n\n def filter_row(self, row):\n \"\"\"\n Check if a row contain general logging utilities\n If listed LU is not in recorded dataset as a separate column, will check it through the 'others' column\n Parameters\n ----------\n row\n cols\n\n Returns\n If is general LU, and the LU used\n -------\n\n \"\"\"\n general_lus = []\n for x in self.lu_levels.keys():\n if x in row.keys():\n ig = row[x]\n else:\n if isinstance(row['others'], str):\n ig = (x in row['others'])\n else:\n continue\n if ig is True:\n general_lus.append(x)\n return len(general_lus) > 0, general_lus\n\n def filter_projects_by_lus(self, df):\n \"\"\"\n Filter projects by selected logging utilities\n Parameters\n -------\n df: The dataframe to be processed\n Returns\n -------\n \"\"\"\n df = pd.merge(df, self.df_proj_lus, on='project_id')\n df[['is_general', 'general_lus']] = df.apply(func=self.filter_row, axis=1, result_type='expand')\n return df[df['is_general'] == True]\n\n def _get_ignored_projects(self):\n \"\"\"\n Filter projects that cannot be parsed in NiCad\n \"\"\"\n f_failed = 'result/clone_detection/clone_detection_check.csv'\n df_failed = pd.read_csv(f_failed)\n return list(df_failed.loc[df_failed['NiCadPassed']==False]['project_id'])\n\n def project_sample(self, sample_percentage=0.1, overwrite=False):\n \"\"\"\n Sample 10% of the projects from each size\n Parameters\n ----------\n sample_percentage: The percentage of sampling\n overwrite: if overwrite existing files\n\n Returns\n -------\n\n \"\"\"\n sloc_dir = 'result/proj_sloc'\n if 0.0 < sample_percentage < 1.0:\n ut.print_msg_box('Sample {}% projects from each size'.format(sample_percentage * 100))\n elif sample_percentage == 1.0:\n ut.print_msg_box('Iterate all selected projects from each size (filtered by LU)')\n elif sample_percentage == 0.0:\n raise ValueError('Not projects are selected at sample rate equals to 0.0')\n else:\n raise ValueError('Not a proper sample rate. Sample rate should be in range')\n \n # Concatenate all size types to be analyzed\n if self.repeats == 0:\n for size_type in self.sample_sizes:\n f_projects_inner_clone = os.path.join(self.sample_dir, 'inner_project_clone_sloc_{}.csv'.format(size_type))\n if os.path.isfile(f_projects_inner_clone):\n if overwrite:\n print('Overwrite existing project {}'.format(os.path.basename(f_projects_inner_clone)))\n else:\n print('Sample projects already exist in {}; skip'.format(os.path.basename(f_projects_inner_clone)))\n continue\n df_projects = ut.csv_loader(os.path.join(sloc_dir, 'filesize_sloc_{}.csv'.format(size_type)))\n df_projects = self.filter_projects_by_lus(df=df_projects)\n df_projects.to_csv(f_projects_inner_clone, index=False) \n else:\n # If sample dir\n for repeat in range(1, self.repeats + 1):\n for size_type in self.sample_sizes:\n f_projects_sample = os.path.join(self.sample_dir, 'sample_{}_sloc_{}.csv'.format(repeat, size_type))\n if os.path.isfile(f_projects_sample):\n if overwrite:\n print('Overwrite existing project {}'.format(os.path.basename(f_projects_sample)))\n else:\n print('Sample projects already exist in {}; skip'.format(os.path.basename(f_projects_sample)))\n continue\n df_projects = ut.csv_loader(os.path.join(sloc_dir, 'filesize_sloc_{}.csv'.format(size_type)))\n if self.is_ignore_failed_clone_detections:\n df_projects = df_projects.loc[~df_projects['project_id'].isin(self.ignore_projects)]\n df_projects = self.filter_projects_by_lus(df=df_projects)\n df_projects_sample = df_projects.sample(frac=sample_percentage, random_state=repeat)\n df_projects_sample.to_csv(f_projects_sample, index=False)\n \n\n def get_total_project_size(self, proj_id_list):\n \"\"\"\n Calculate the total size of selected projects after decompression\n Returns\n -------\n \"\"\"\n # Merge all projects from size calculation\n df_merged = pd.concat(\n [ut.csv_loader(\n os.path.join(self.d_proj_size, 'filesize_mb_{}.csv'.format(size_type))\n ) for size_type in self.sample_sizes])\n df_merged = df_merged.loc[df_merged['project_id'].isin(proj_id_list)]\n return ut.convert_size(df_merged['size_mb'].sum() * 1024 * 1024)\n\n def logger_detector(self, repeat_idx):\n \"\"\"\n Detect java files with logging statements such as logger, etc. followed by a function call.\n Returns\n -------\n \"\"\"\n # Merge all sampled projects under the same repeat index\n df_merged = pd.concat(\n [ut.csv_loader(\n os.path.join(self.sample_dir, 'sample_{}_sloc_{}.csv'.format(repeat_idx, size_type))\n ) for size_type in self.sample_sizes])\n\n total_projects_count = df_merged['project_id'].count()\n total_projects_size = self.get_total_project_size(list(df_merged['project_id']))\n total_num_java = df_merged['Count'].sum()\n total_uncompressed_java_size = ut.convert_size(df_merged['Bytes'].sum())\n ut.print_msg_box('Projects Summary\\n'\n 'Repeat ID:{rep_id}\\n'\n 'Total Projects:{proj_count}\\n'\n 'Total Projects Size:{proj_size}\\n'\n 'Total Number of Java Files:{num_f_java}\\n'\n 'Total Sizes of Java Files:{java_size}'.format(rep_id=repeat_idx,\n proj_count=total_projects_count,\n proj_size=total_projects_size,\n num_f_java=total_num_java,\n java_size=total_uncompressed_java_size))\n #self.remove_logging_single(df=df_merged, repeat_idx=repeat_idx)\n self.remove_logging_multiprocessing(df=df_merged, repeat_idx=repeat_idx)\n\n def remove_logging_single(self, df, repeat_idx):\n \"\"\"\n Remove logging without parallelism\n Parameters\n ----------\n df\n\n Returns\n -------\n\n \"\"\"\n # No Parallel\n logging_remove_json_new = defaultdict(dict)\n log_remove_lst = [self.find_and_remove_logging(row=row, repeat_idx=repeat_idx) for idx, row in df.iterrows()]\n for lrm in log_remove_lst:\n if lrm is not None:\n log_remove_repo_id, log_remove_repo_detail = lrm\n logging_remove_json_new[log_remove_repo_id] = log_remove_repo_detail\n self.dump_remove_logging_result(logging_remove_json_new)\n\n def remove_logging_multiprocessing(self, df, repeat_idx):\n # Preserve for parallelism\n jobs = []\n for d in ut.chunkify(df, ut.getWorkers()):\n jobs.append(\n multiprocessing.Process(target=self.remove_logging_multithreading, args=(d, repeat_idx,))\n )\n [j.start() for j in jobs]\n [j.join() for j in jobs]\n\n def remove_logging_multithreading(self, df, repeat_idx):\n q = Queue()\n ts = [threading.Thread(target=self.find_and_remove_logging, args=(row, repeat_idx, q,)) for idx, row in\n df.iterrows()]\n for t in ts: t.start()\n for t in ts: t.join()\n\n log_remove_lst = []\n while not q.empty():\n log_remove_lst.append(q.get())\n q.task_done()\n\n logging_remove_json_new = defaultdict(dict)\n for lrm in log_remove_lst:\n if lrm is not None:\n log_remove_repo_id, log_remove_repo_detail = lrm\n logging_remove_json_new[log_remove_repo_id] = log_remove_repo_detail\n\n self.dump_remove_logging_result(logging_remove_json_new)\n\n def dump_remove_logging_result(self, new_json):\n \"\"\"\n Save removed logging statements in JSON\n Returns\n -------\n\n \"\"\"\n # Skip writing or updating if new_json object is empty\n if not any(new_json): return\n\n # Save Json\n with lock:\n if os.path.isfile(self.f_removal):\n with open(self.f_removal, 'r+') as f_update:\n js = json.load(f_update)\n for k, v in new_json.items():\n # Update if project exists\n js[k] = v\n f_update.seek(0)\n f_update.write(json.dumps(js, indent=4))\n f_update.truncate()\n else:\n with open(self.f_removal, 'w') as f_update:\n f_update.write(json.dumps(new_json, indent=4))\n\n def find_and_remove_logging(self, row, repeat_idx=None, q=None):\n \"\"\"\n Decompress selected java projects and remove logging statements from them\n Parameters\n ----------\n row: dataframe row, records the information of a project\n repeat_idx: The repeat index of current experiment\n\n Returns\n -------\n\n \"\"\"\n repo_path = row['repo_path']\n repo_id = int(row['project_id'])\n owner_repo = row['owner_repo']\n\n # The previously removed logging recorded for this project\n stored_proj_logging_removal = None\n\n if repeat_idx:\n # Temp location to store project\n tmp_out_dir = os.path.abspath(os.path.join(\n *[self.d_clean_project_root, 'repeat_%d' % repeat_idx, str(repo_id)]\n ))\n else:\n tmp_out_dir = os.path.abspath(os.path.join(\n *[self.d_clean_project_root, str(repo_id)]\n ))\n # Archived file location\n archived_f = os.path.join(self.archive_dir, '%s.tar.gz' % str(repo_id))\n\n if str(repo_id) in self.logging_remove_json.keys():\n # Skip remove logging if this project has already been log removed\n if os.path.isdir(tmp_out_dir):\n print('Project %s has already been log removed; skip' % owner_repo)\n return\n # If cleaned project not in temp, but in archived location\n else:\n if os.path.isfile(archived_f):\n # Decompress previously cleaned project from archived file\n # The project has java only so no need to remove non-java files\n print('Cleaned project %s found. Decompressing previously archived project' % owner_repo)\n self.decompress_project(f_tar=archived_f, out_d=os.path.dirname(tmp_out_dir),\n clean_project=False, keep_java_only=False)\n return\n else:\n # If archived file does not exist, while logging removal info is on file\n # This happens when we move to a new machine\n # We will skip the logging file grepping, instead we will jump to the logging removal part\n stored_proj_logging_removal = self.logging_remove_json[str(repo_id)]\n\n if os.path.isdir(tmp_out_dir):\n # If file was not archived, which means previous logging removal failed\n # We will remove this folder and reexamine\n shutil.rmtree(tmp_out_dir)\n\n repo_path = os.path.join(ut.getPath('REPO_ZIPPED_ROOT'), os.path.basename(repo_path))\n\n if not os.path.isfile(repo_path):\n logger.error('Cannot find project %s at %s' % (owner_repo, repo_path))\n return\n print('Start decompression and logging removal from %s' % owner_repo)\n # Decompress\n self.decompress_project(f_tar=repo_path, out_d=tmp_out_dir, keep_java_only=True)\n\n general_lus = ast.literal_eval(row['general_lus'])\n function_names = set(itertools.chain.from_iterable([self.lu_levels[lu] for lu in general_lus]))\n\n try:\n proj_logging_removal = self.logging_remover_cu_line(d=tmp_out_dir,\n function_names=function_names,\n stored_proj_logging_removal=stored_proj_logging_removal)\n except Exception:\n logger.warning(\"Fail to remove logging in project %s. Either no logging or command failed.\" % owner_repo)\n proj_logging_removal = None\n\n # If remove cleaned project from temp folder\n if self.is_remove_cleaned_project:\n shutil.rmtree(tmp_out_dir)\n\n # If save cleaned project into a separate location\n if self.is_archive_cleaned_project:\n with tarfile.open(archived_f, 'w:gz') as tar:\n tar.add(tmp_out_dir, arcname=os.path.basename(tmp_out_dir))\n\n if proj_logging_removal:\n if q is not None:\n q.put([repo_id, proj_logging_removal])\n # Record result in json\n return (repo_id, proj_logging_removal)\n else:\n return None\n\n def logging_remover_cu_line(self, d, function_names, stored_proj_logging_removal=None):\n \"\"\"\n Convert java files with keyword \"log\" to Compilation Unit then perform single line grep\n Parameters\n ----------\n d: The project directory\n function_names: The function names of log level\n\n Returns\n -------\n\n \"\"\"\n self.rename_files(d=d)\n log_related_files = self.get_files_with_keyword(keyword='log', d=d, function_names=function_names)\n self.format_java(d=d, files=log_related_files)\n\n if stored_proj_logging_removal:\n proj_logging_removal = stored_proj_logging_removal\n else:\n # If logging removal for this project is not recorded\n proj_logging_removal = self.single_line_grep_logging(function_names=function_names, d=d)\n del stored_proj_logging_removal\n if proj_logging_removal:\n self.remove_logging_by_linenum(dict_removal=proj_logging_removal, d=d, function_names=function_names)\n return proj_logging_removal\n\n def rename_files(self, d):\n \"\"\"\n Certain file path contain special chars which may cause error when reading\n We replace all special chars to underline _\n However, this may not solve all the issues\n Parameters\n ----------\n d\n\n Returns\n -------\n\n \"\"\"\n # Rename all files with special characters\n cmd_rename = r\"find . -name '*.java' -exec rename 's/[?<>\\$\\\\:*|\\\"]/_/g' {} \\;\"\n subprocess.Popen(cmd_rename, shell=True, cwd=d).wait()\n\n def check_lambda(self, line):\n \"\"\"\n Check if the source code line contain lambda usage\n Parameters\n ----------\n line\n\n Returns\n -------\n\n \"\"\"\n line_cleaned = re.sub(r'\".*?\"', '', line.strip())\n if '->' in line_cleaned: return True\n return False\n\n def check_normal_logging(self, line):\n \"\"\"\n A full logging statement, start with logger and end with ;\n The parenthesis should be the same\n Parameters\n ----------\n line_content\n\n Returns\n -------\n\n \"\"\"\n # If left/right parenthesis is not the same\n if not self.check_parenthesis(line):\n # If not balanced, remove content in string then check\n # Example: Log.info(\"**************************)\"\n line_str_removed = re.sub(r'\".*?\"', '', line.strip())\n # Also check if\n if not self.check_parenthesis(line_str_removed):\n return False\n else:\n if 'log' in line.split('.')[0] and line.endswith(';'): return True\n return False\n\n def check_parenthesis(self, line):\n \"\"\"\n Check if left&right parenthesis is matching\n Parameters\n ----------\n line\n\n Returns\n -------\n\n \"\"\"\n left_parenthesis = list(line).count('(')\n right_parenthesis = list(line).count(')')\n if left_parenthesis != right_parenthesis: return False\n return True\n\n def format_java(self, d, files=None):\n \"\"\"\n Convert Java format to eliminate the syntax error by multi-line greps\n Parameters\n ----------\n d: The directory of the project\n files: log_related_files\n Returns\n -------\n\n \"\"\"\n f_javaformatter = os.path.join(*[ut.get_proj_root(), 'resources', 'javaformatter', 'JavaFormatter.jar'])\n if files is None:\n for root, dirnames, filenames in os.walk(d):\n for filename in filenames:\n if filename.endswith('.java'):\n cmd = 'java -jar {f_jf} \"{f_java}\"'.format(f_jf=f_javaformatter,\n f_java=os.path.join(root, filename))\n p = subprocess.Popen(cmd, shell=True)\n p.wait()\n else:\n for filename in files:\n if filename.endswith('.java'):\n cmd = 'java -jar {f_jf} \"{f_java}\"'.format(f_jf=f_javaformatter,\n f_java=os.path.join(d, filename))\n p = subprocess.Popen(cmd, shell=True)\n p.wait()\n\n def get_files_with_keyword(self, keyword, d, function_names):\n \"\"\"\n Grep files that contain the given keyword\n Parameters\n ----------\n keyword: The keyword(s) to be searched\n d: The directory of the project\n Returns\n -------\n\n \"\"\"\n try:\n cmd = \"\"\"grep -ril \"%s\" --include=\"*.java\" . | xargs grep -ilE \"%s\" \"\"\" % (\n keyword, ('|'.join(function_names)))\n out_raw = subprocess.check_output(cmd, shell=True, cwd=d)\n except Exception:\n logger.warning('Grepping command <-- %s -->failed at %s' % (cmd, d))\n # Redo grepping (not using recursion since we are uncertain if the unknown errors will cause an infinite loop)\n cmd = 'grep -ril \"%s\" --include=\"*.java\"' % keyword\n out_raw = subprocess.check_output(cmd, shell=True, cwd=d)\n try:\n out = out_raw.decode('utf-8')\n except UnicodeError:\n out = out_raw.decode('iso-8859-1')\n return [x for x in out.split('\\n') if x != '']\n\n def single_line_grep_logging(self, function_names, d):\n \"\"\"\n Grep logging statements of single-lined logging\n Cannot handle logging statements that are across multiple lines (unless reformatted)\n Parameters\n ----------\n function_names: logging levels function names regarding to the LU used in this project\n d: The directory of the project\n\n Returns\n -------\n \"\"\"\n proj_logging_removal = defaultdict(lambda: defaultdict(dict))\n\n cmd = 'grep -rinE \"(.*log.*)\\.({funcs})\\(.*\\)\" --include=\\*.java .'.format(\n funcs='|'.join(function_names))\n try:\n out_raw = subprocess.check_output(cmd, shell=True, cwd=d)\n except subprocess.CalledProcessError:\n logger.warning('Fail to execute command %s at %s' % (cmd, d))\n return None\n try:\n out = out_raw.decode('utf-8')\n except UnicodeError:\n out = out_raw.decode('iso-8859-1')\n # Process results\n re_match = re.compile(r'^./(.*\\.java)\\:(\\d+)\\:(.*)$')\n for line in out.split('\\n'):\n if line == \"\": continue\n f_path, line_num, line_content = re_match.match(line).groups()\n # Skip lines in comments\n if line_content.lower().strip().startswith((r'//', r'/*', r'*/')): continue\n line_type = self.check_logging_type(line=line_content.lower().strip(), functions=function_names)\n proj_logging_removal[f_path][int(line_num)] = {'line': line_content, 'linetype': line_type}\n return proj_logging_removal\n\n def check_logging_guard_type(self, line, functions, supplement_keywords=[]):\n \"\"\"\n Check if logging guard\n Parameters\n ----------\n line: source code lines\n functions: log level functions to be added\n supplement_keywords: Some other keywords you want to add other search keywords\n\n Returns\n -------\n \"\"\"\n # Grep usages such as if(log.isDebug()) or if(trace); this statement can either start with \"if\" or \"else (if)\"\n re_match = re.compile('^(if|else\\s+if)\\s+\\((.*?)\\)[\\s+{].*$')\n keywords = list(functions) + supplement_keywords\n try:\n condition = re_match.match(line).groups()[1]\n if any([x in condition for x in keywords]):\n return 'logging_guard'\n else:\n return 'condition'\n except AttributeError:\n if line.startswith('else '):\n return 'condition'\n return None\n\n def check_logging_type(self, line, functions):\n \"\"\"\n Check the type of logging\n Parameters\n ----------\n line\n\n Returns\n -------\n \"\"\"\n # Check if lambda: Do not consider lambda\n if self.check_lambda(line=line):\n return 'lambda'\n # Check if logging guard: Replace full line of logging guard\n logging_guard = self.check_logging_guard_type(line=line, functions=functions, supplement_keywords=['log'])\n if logging_guard:\n return logging_guard\n # # Check if normal logging: Replace full line of normal logging\n # if self.check_normal_logging(line=line):\n # return 'normal'\n # # Replace in full\n # return 'other'\n return 'normal'\n\n def remove_logging_by_linenum(self, dict_removal, d, function_names):\n \"\"\"\n Remove logging by line number with \"sed\" command\n\n Parameters\n ----------\n dict_removal\n d\n\n Returns\n -------\n\n \"\"\"\n # Iterate each file and remove logging statements\n for f_path, line_info in dict_removal.items():\n\n # The lines needs to replace specific logging statement\n lst_replace_logging = []\n # The lines can simply replace whole line\n lst_replace_line = []\n\n f = os.path.join(d, f_path)\n if not os.path.isfile(f):\n # In case some error caused by renaming\n logger.error('Did not find recorded filepath from folder: %s' % f)\n continue\n\n for line_id, line_content_info in line_info.items():\n if line_content_info['linetype'] == 'lambda':\n pass\n elif line_content_info['linetype'] == 'condition':\n lst_replace_logging.append(line_id)\n else:\n lst_replace_line.append(line_id)\n \n if len(lst_replace_line) > 0:\n # Remove logging statements by line number\n # Cannot write to original file directly since > has a higher priority\n cmd = \"awk '%s {gsub(/.*/,\\\"\\\")}; {print}' %s > %s_lrm_temp && mv %s_lrm_temp %s\" % \\\n (' || '.join(['NR == %d' % x for x in lst_replace_line]), f, f, f, f)\n p = subprocess.Popen(cmd, shell=True)\n\n try:\n p.communicate()\n except Exception as ex:\n logger.error('Fail to remove log for {f}; {ex}'.format(f, str(ex)))\n\n if len(lst_replace_logging) > 0:\n # Find logging statements and remove them\n with open(f, 'r+') as fw:\n f_lines = fw.readlines()\n for line_id in lst_replace_logging:\n line_content = f_lines[line_id - 1]\n try:\n line_logging = \\\n re.match('.*(.*log.*\\.({levels})\\(.*\\))'.format(levels='|'.join(function_names)),\n line_content, re.IGNORECASE).groups()[0]\n f_lines[line_id - 1] = line_content.replace(line_logging, '')\n except Exception as e:\n logger.error('Fail to replace logging statement in file: {file}, '\n 'line_num:{line_num}, line: {line}; Error: {e}'.format(\n file=f_path, line_num=line_id, line=line_content, e=e))\n # Rewrite file\n fw.seek(0)\n fw.write('\\n'.join(f_lines))\n fw.truncate()\n\n def decompress_project(self, f_tar, out_d, clean_project=True, keep_java_only=True):\n \"\"\"\n Decompress project into a temporary location\n Parameters\n ----------\n f_tar\n repo_id\n\n Returns\n -------\n\n \"\"\"\n # Clean temp project if it exists. This could happen when a previous job collapsed\n if clean_project:\n if os.path.isdir(out_d):\n shutil.rmtree(out_d)\n\n # Decompress tar to temp folder\n tar = tarfile.open(f_tar, \"r:gz\")\n tar.extractall(path=out_d)\n tar.close()\n\n # If only keep java files\n if keep_java_only:\n subprocess.Popen(\"find . -type f ! -name '*.java' -delete\", shell=True, cwd=out_d).wait()\n\n\nif __name__ == '__main__':\n f_removal = 'result/log_remove/logging_removal_lines.json'\n logremover = LogRemover(f_removal=f_removal, sample_percentage=0.1)\n for repeat_idx in range(1, 1 + logremover.repeats):\n logremover.logger_detector(repeat_idx)\n","sub_path":"src/log_remove/log_remover.py","file_name":"log_remover.py","file_ext":"py","file_size_in_byte":30442,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"265137906","text":"#!/usr/bin/python3\nimport logging\n\nimport json\nfrom datetime import timedelta\nimport urllib3\nurllib3.disable_warnings()\nimport requests\nimport re\nfrom bs4 import BeautifulSoup\n\nimport voluptuous as vol\n\nfrom homeassistant.const import CONF_HOST\nfrom homeassistant.helpers.entity import Entity\nfrom homeassistant.components.sensor import PLATFORM_SCHEMA\nimport homeassistant.helpers.config_validation as cv\nimport homeassistant.util as util\n\nPLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({\n vol.Required(CONF_HOST): cv.string,\n})\n\n_LOGGER = logging.getLogger(__name__)\n\nSCAN_INTERVAL = timedelta(seconds=3600)\nMIN_TIME_BETWEEN_SCANS = timedelta(seconds=600)\nMIN_TIME_BETWEEN_FORCED_SCANS = timedelta(seconds=120)\n\ndef setup_platform(hass, config, add_devices, discovery_info=None):\n \"\"\"Setup the sensor platform.\"\"\"\n hostip = config.get(CONF_HOST)\n add_devices([ink_M252dw(hostip)])\n\n\nclass ink_M252dw(Entity):\n \"\"\"Find the ink levels of the M252dw printer\"\"\"\n\n def __init__(self, hostip):\n \"\"\"Initialize the sensor.\"\"\"\n _LOGGER.debug('Initializing...')\n self.HOSTIP = hostip\n self.update()\n\n @property\n def name(self):\n \"\"\"Return the name of the sensor.\"\"\"\n return 'Ink levels for HP M252dw printer' \n\n @property\n def state(self):\n \"\"\"Return the state of the sensor.\"\"\"\n return self._state\n\n @property\n def unit_of_measurement(self):\n \"\"\"Return the unit of measurement.\"\"\"\n return '%'\n\n @util.Throttle(MIN_TIME_BETWEEN_SCANS, MIN_TIME_BETWEEN_FORCED_SCANS)\n def update(self):\n \"\"\"Fetch new state data for the sensor.\n\n This is the only method that should fetch new data for Home Assistant.\n \"\"\"\n _LOGGER.debug('Returning current state...')\n ink_levels = get_ink_levels(self.HOSTIP)\n self._state = json.dumps(ink_levels)\n self._attributes = ink_levels\n\n @property\n def state_attributes(self):\n \"\"\"Return the attributes of the entity.\n\n Provide the parsed JSON data (if any).\n \"\"\"\n return self._attributes\n\ndef get_ink_levels(HOSTIP):\n try:\n page = requests.get(\"https://\" + HOSTIP + \"/hp/device/info_suppliesStatus.html?tab=Home&menu=SupplyStatus\", verify=False, timeout=2)\n except requests.exceptions.Timeout:\n return {'Black' : None, 'Magenta' : None, 'Cyan' : None, 'Yellow' : None}\n soup = BeautifulSoup(page.content, 'html.parser')\n inkstatus = soup.find_all('td', class_='SupplyName')\n ink_levels={}\n Colours = ['Black','Magenta','Cyan','Yellow']\n if len(inkstatus)==8:\n for i in range(0,8,2):\n for colour in Colours:\n if colour in inkstatus[i].contents[0]:\n level = re.findall(r'[\\d-]?[\\d-]?[\\d-]%', inkstatus[i+1].contents[0])[0][0:-1]\n if level == '--':\n level = 0\n else:\n level = int(level)\n ink_levels[colour]=level\n return ink_levels\n","sub_path":"custom_components/ink_M252dw/sensor.py","file_name":"sensor.py","file_ext":"py","file_size_in_byte":3031,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"282379512","text":"import csv\nfrom datetime import datetime\n\nimport matplotlib.pyplot as plt\n\nfilename ='data/sitka_weather_2018_simple.csv'\nwith open(filename) as f:\n reader = csv.reader(f)\n header_row = next(reader)\n\n dates, prcps = [], []\n for row in reader:\n currrent_date = datetime.strptime(row[2], '%Y-%m-%d')\n try:\n prcp = int(row[3])\n except ValueError:\n print(f\"Missing data for {currrent_date}\")\n else:\n dates.append(currrent_date)\n prcps.append(prcp)\n\nplt.style.use('seaborn')\nfig, ax = plt.subplots()\nax.plot(dates, prcps, c='green')\n\ntitle = 'Daily perciptation at Sitka rain forest'\nax.set_title(title, fontsize=20)\nax.set_xlabel('', fontsize=16)\nfig.autofmt_xdate()\nax.set_ylabel(\"Percipitation \", fontsize=16)\nax.tick_params(axis='both', which='major', labelsize=16)\n\nplt.show()\n","sub_path":"Python_Projects/Data_Visualization/Chap16_downloading_data/sitka_rainfall.py","file_name":"sitka_rainfall.py","file_ext":"py","file_size_in_byte":860,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"387859779","text":"# https://oj.leetcode.com/problems/single-number/\n\nclass Solution:\n # @param A, a list of integer\n # @return an integer\n def singleNumber(self, A):\n ans = 0\n for x in A:\n ans = (ans ^ x)\n\n return ans\n","sub_path":"leetans/singlenumber.py","file_name":"singlenumber.py","file_ext":"py","file_size_in_byte":241,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"165435181","text":"# Similar script 2 but with the hybrid A2c discrete.\n\nfrom sys_simulator import general as gen\nfrom sys_simulator.q_learning.environments.completeEnvironmentA2C \\\n import CompleteEnvironmentA2C\nfrom sys_simulator.q_learning.rewards import dis_reward_tensor\nfrom sys_simulator.parameters.parameters import EnvironmentParameters\nfrom sys_simulator.a2c.agent import Agent\nfrom sys_simulator.a2c.a2c import ActorCriticDiscreteHybrid, \\\n compute_gae_returns\nfrom torch import optim, nn\nimport torch\nimport os\nimport pickle\nimport random\n# from copy import deepcopy\n\n\ndef run():\n # environment physical parameters\n n_mues = 1 # number of mues\n n_d2d = 2 # number of d2d pairs\n n_rb = n_mues # number of RBs\n bs_radius = 500 # bs radius in m\n rb_bandwidth = 180*1e3 # rb bandwidth in Hz\n d2d_pair_distance = 50 # d2d pair distance in m\n p_max = 23 # max tx power in dBm\n noise_power = -116 # noise power per RB in dBm\n bs_gain = 17 # macro bs antenna gain in dBi\n user_gain = 4 # user antenna gain in dBi\n sinr_threshold_train = 6 # mue sinr threshold in dB for training\n mue_margin = .5e4\n # conversions from dB to pow\n p_max = p_max - 30\n p_max = gen.db_to_power(p_max)\n noise_power = noise_power - 30\n noise_power = gen.db_to_power(noise_power)\n bs_gain = gen.db_to_power(bs_gain)\n user_gain = gen.db_to_power(user_gain)\n sinr_threshold_train = gen.db_to_power(sinr_threshold_train)\n # ai training parameters\n STEPS_PER_EPISODE = 20\n MAX_NUM_EPISODES = 2700 * 1\n # C = 8000 # C constant for the improved reward function\n C = 80 # C constant for the improved reward function\n MAX_NUMBER_OF_AGENTS = 10\n NUM_ACTIONS = 5\n HIDDEN_SIZE = 256\n LEARNING_RATE = 3e-2\n BETA = 1e-2\n # mu = 0.82*p_max/5/2000\n # std = mu/6\n mu = 0\n std = 0.1\n # torch device\n device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')\n # parameters classes initialization\n env_params = EnvironmentParameters(\n rb_bandwidth, d2d_pair_distance, p_max, noise_power,\n bs_gain, user_gain, sinr_threshold_train,\n n_mues, n_d2d, n_rb, bs_radius, c_param=C, mue_margin=mue_margin)\n # environment initialization\n reward_function = dis_reward_tensor\n environment = CompleteEnvironmentA2C(env_params, reward_function)\n # a2c initialization\n a2c = ActorCriticDiscreteHybrid(6, NUM_ACTIONS, HIDDEN_SIZE, mu, std)\n actor_optimizer = optim.RMSprop(a2c.actor.parameters(), lr=LEARNING_RATE)\n critic_optimizer = optim.RMSprop(a2c.critic.parameters(), lr=LEARNING_RATE)\n # training loop\n episode = 0\n d2d_spectral_effs = []\n mue_spectral_effs = []\n actions = [i*0.82*p_max/5/1000 for i in range(NUM_ACTIONS)] # best result\n while episode < MAX_NUM_EPISODES:\n # entropy = 0\n aux_range = range(MAX_NUMBER_OF_AGENTS+1)[1:]\n n_agents = random.choice(aux_range)\n agents = [Agent() for _ in range(n_agents)]\n environment.build_scenario(agents)\n obs = [environment.get_state(a) for a in agents]\n log_probs = torch.zeros((n_agents, STEPS_PER_EPISODE)).to(device)\n values = torch.zeros((n_agents, STEPS_PER_EPISODE+1)).to(device)\n rewards = torch.zeros((n_agents, STEPS_PER_EPISODE)).to(device)\n entropy = torch.zeros((n_agents, STEPS_PER_EPISODE)).to(device)\n i = 0\n done = False\n # actions = [] # used for debug purposes\n while not done and i < STEPS_PER_EPISODE:\n # agents choose their actions\n # actions_t = [] # used for debug purposes\n for j, agent in enumerate(agents):\n action_index, dist, value = agent.act_discrete(a2c, obs[j])\n agent.set_action(actions[action_index.item()])\n # actions_t.append(action) # used for debug purposes\n log_prob = dist.log_prob(action_index)\n # entropy += dist.entropy().mean()\n log_probs[j][i] = log_prob\n values[j][i] = value\n entropy[j][i] = dist.entropy()\n # perform a environment step\n next_obs_t, rewards_t, done = environment.step(agents)\n rewards[:, i] = torch.FloatTensor(rewards_t)\n # actions.append(actions_t) # used for debug purposes\n i += 1\n # last_states = deepcopy(obs) # used for debug purposes\n obs = next_obs_t\n # gae and returns\n next_obs_t = torch.cat(obs, 0).to(device)\n for j, agent in enumerate(agents):\n _, _, next_value_t = agents[0].act(a2c, next_obs_t[j])\n values[j][i] = next_value_t\n advantages, returns = compute_gae_returns(device, rewards, values)\n # update critic\n values_critic = values[:, :-1].reshape(1, -1).to(device)\n returns_critic = returns.view(1, -1).to(device)\n critic_loss = nn.functional.mse_loss(values_critic, returns_critic)\n critic_optimizer.zero_grad()\n critic_loss.backward(retain_graph=True)\n critic_optimizer.step()\n # update actor\n a2c.common.zero_grad()\n aux = torch.mul(advantages, log_probs)\n aux -= BETA * entropy\n aux = torch.sum(aux, axis=1)\n actor_loss = -torch.mean(aux)\n actor_optimizer.zero_grad()\n actor_loss.backward()\n actor_optimizer.step()\n # print training info\n episode += 1\n m_reward = torch.mean(rewards).item()\n d2d_spectral_effs.append(environment.d2d_spectral_eff)\n mue_spectral_effs.append(environment.mue_spectral_eff)\n print(\"Episode#:{} mean reward:{}\".format(\n episode, m_reward))\n # save training data into a file\n cwd = os.getcwd()\n data = {}\n data['d2d_spectral_effs'] = d2d_spectral_effs\n data['mue_spectral_effs'] = mue_spectral_effs\n filename = gen.path_leaf(__file__)\n filename = filename.split('.')[0]\n filename_model = filename\n filename = f'{cwd}/data/a2c/{filename}.pickle'\n # save the a2c models\n torch.save(\n a2c.state_dict(),\n f'{cwd}/models/a2c/{filename_model}.pt')\n with open(filename, 'wb') as f:\n pickle.dump(data, f)\n","sub_path":"scripts_a2c/script3.py","file_name":"script3.py","file_ext":"py","file_size_in_byte":6216,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"155406160","text":"# -*- coding: utf-8 -*-\nfrom unityagents import UnityEnvironment\n\ndef init_environment(executable_path): \n \n # Init the Reacher Unity Environment\n env = UnityEnvironment(file_name=executable_path)\n # Get the default brain\n brain_name = env.brain_names[0]\n brain = env.brains[brain_name]\n # Reset the environment\n env_info = env.reset(train_mode=True)[brain_name]\n # Number of agents\n n_agents = len(env_info.agents)\n # Size of each action\n action_size = brain.vector_action_space_size\n \n # Get state space \n states = env_info.vector_observations\n state_size = states.shape[1]\n \n return env, brain_name, n_agents, state_size, action_size","sub_path":"unity_env.py","file_name":"unity_env.py","file_ext":"py","file_size_in_byte":690,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"281254824","text":"# Quoretech Object\n\nimport hashlib\nimport logging\nimport numpy as np\n\nfrom ..filters.baseline import LinFilter\nfrom ..models.load import ModelLoad\nfrom ..segments.frames import GetFrames\nfrom ..segments.peaks import PeakWave\nfrom .quorerhythms import EcgCalc\nimport tensorflow as tf\n\nlogger = logging.getLogger(__name__)\ntf.logging.set_verbosity(tf.logging.ERROR)\n\n\nclass EcgClassifier(PeakWave, LinFilter, GetFrames, EcgCalc, ModelLoad):\n\n def __init__(self):\n super().__init__()\n self.document_datetime_init = None\n self.adc_gain = None\n self.nsig = None\n self.annotList = []\n self.ecg_classification = None\n self.ecg_features = None\n self.pre_contraction = []\n self.annot_symbol = []\n self.annot_proba = []\n self.higher_idx = []\n\n def variables_initializer(self, signal, adc_gain, fs, document_datetime_init, annotation_df=[]) -> None:\n \"\"\"\n Parameters\n ----------\n Returns\n -------\n Raises\n ------\n \"\"\"\n self.document_datetime_init = document_datetime_init\n if 'annotation' in annotation_df:\n self.annotation_df = annotation_df[annotation_df['annotation'].notnull()]\n self.adc_gain = adc_gain\n self.signal = np.array(signal, dtype=np.int32)\n self.signal = self.signal - np.mean(self.signal)\n self.nsig = len(self.signal)\n self.fs = fs\n\n def upload_model(self, classifier=None, uuid_physician=None, verbose=None) -> None:\n \"\"\"\n Parameters\n ----------\n Returns\n -------\n Raises\n ------\n \"\"\"\n if uuid_physician is 'golden':\n if classifier == 'DNN':\n self.ecg_classification = self.tf_load()\n self.ecg_classification.load_weights('./models/' +\n hashlib.sha256('QT-MODEL:Standard'.encode()).hexdigest())\n elif classifier == 'debug':\n self.ecg_classification = self.tf_load()\n self.ecg_classification.load_weights('./tmp/model.h5')\n else:\n logger.info('classifier was not selected!')\n\n else:\n logger.info('Physician UUID was not found.')\n\n def apply(self) -> None:\n \"\"\"\n Parameters\n ----------\n Returns\n -------\n Raises\n ------\n \"\"\"\n rr_interval = np.asarray(self.pre_contraction_calc(), dtype=np.float32)\n noise_id = np.where('Q' == np.array(self.annot_dict))[0][0]\n\n self.annot_symbol = ['Q', 'Q', 'Q', 'Q']\n init_beat = 4\n last_annot = (np.ones(init_beat, ) * noise_id).astype(np.int)\n proba_init = np.zeros((init_beat,)) * - 1\n self.annot_proba = [x.tolist() for x in proba_init]\n\n def norma(x):\n x = x - x.min()\n x = x / x.max()\n return x\n\n for beat in range(init_beat, self.npeaks):\n pos = beat\n\n rr_mem = rr_interval[pos - 4:pos + 1]\n rr_mem = rr_mem[::-1]\n\n last_beat = self.frame[pos - 1, self.qrs_left - 10:self.qrs_left + 20] - \\\n self.frame[pos - 1, self.qrs_left - 10:self.qrs_left + 20].min()\n last_beat = last_beat / last_beat.max()\n last_beat = last_beat - np.mean(last_beat)\n\n now_beat = self.frame[pos, self.qrs_left - 10:self.qrs_left + 20] - \\\n self.frame[pos, self.qrs_left - 10:self.qrs_left + 20].min()\n now_beat = now_beat / now_beat.max()\n now_beat = now_beat - np.mean(now_beat)\n\n mse_beat = (np.square(now_beat - last_beat)).mean(axis=0).astype(np.float32)\n\n ecg_data = norma(self.frame[pos])\n seq_now = np.expand_dims(rr_mem.reshape(1, -1), 2)\n\n out = self.ecg_classification.predict([ecg_data.reshape(1, -1),\n seq_now,\n mse_beat.reshape(1, -1)])\n proba = np.argmax(out[0][0])\n proba = int(out[0][0][proba] * 100)\n annot_now = np.argmax(out[0][0])\n\n self.annot_proba.append(proba)\n self.annot_symbol.append(self.annot_dict[annot_now])\n last_annot = np.roll(last_annot, 1)\n last_annot[0] = annot_now\n\n def jsonify(self):\n \"\"\"\n Parameters\n ----------\n Returns\n -------\n Raises\n ------\n \"\"\"\n self.hrv = self.hrv_calc()\n self.pre_contraction = self.pre_contraction_calc()\n\n for index, label, prob, preco, hrv, in zip(\n self.rpeaks.tolist(),\n self.annot_symbol,\n self.annot_proba,\n self.pre_contraction,\n self.hrv\n ):\n self.annotList.append({\n \"index\": index,\n \"annotation\": label,\n \"probability\": prob,\n # \"contraction\": preco,\n # \"hrv\": hrv,\n \"cluster\": None,\n \"isRegion\": False,\n \"deltaTime\": 0\n })\n\n return self.annotList\n","sub_path":"quore/core/quoreclassifier.py","file_name":"quoreclassifier.py","file_ext":"py","file_size_in_byte":5221,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"637343758","text":"from bs4 import BeautifulSoup\nimport urllib.request as req\nimport urllib.parse as rep\nimport sys\nimport io\nimport os\n\nsys.stdout = io.TextIOWrapper(sys.stdout.detach(), encoding = 'utf-8')\nsys.stderr = io.TextIOWrapper(sys.stderr.detach(), encoding = 'utf-8')\n\nbase = \"https://search.naver.com/search.naver?sm=tab_hty.top&where=image&query=\"\nquote = rep.quote_plus(\"파이썬\")\n\nurl = base + quote\n\nsavePath = \"C:\\\\python_work\\\\image_down\\\\\"\n\nres = req.urlopen(url).read()\n\ntry:\n if not (os.path.isdir(savePath)):\n os.makedirs(os.path.join(savePath))\nexcept OSError as e:\n if e.errno != errno.EEXIST:\n print(\"폴더 만들기 실패\")\n raise\n\nsoup = BeautifulSoup(res, \"html.parser\")\n\nimg_list = soup.select(\"div.img_area > a.thumb._thumb > img\")\n\n#print(img_list)\n\nfor i, element in enumerate(img_list,1):\n #print(i,':',element['data-source'])\n fullFileName = os.path.join(savePath, savePath+str(i)+'.jpg')\n #print(fullFileName)\n req.urlretrieve(element['data-source'], fullFileName)\n\nprint(\"다운로드완료\")\n","sub_path":"download2-8-1.py","file_name":"download2-8-1.py","file_ext":"py","file_size_in_byte":1053,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"634295846","text":"from t2listing import *\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\nimport csv\r\nimport os\r\n#from t2data import *\r\nfrom mpl_toolkits.mplot3d import Axes3D\r\nimport importlib\r\nimport py_compile\r\ncwd = os.getcwd()\r\n\r\n\r\n\r\n# reload t2listing and t2data in case there is update in the module \r\npytough_path=os.environ['pytough']\r\nprint(os.environ['pytough'])\r\n\r\ncurrent_path=os.getcwd()\r\ncurrent_folder_name=os.path.basename(current_path)\r\nsys.path.append(os.path.join(pytough_path,'python'))\r\n\r\npy_compile.compile(os.path.join(pytough_path,'python','t2listing.py'))\r\npy_compile.compile(os.path.join(pytough_path,'python','t2data.py'))\r\n\r\nimport t2listing\r\nimport t2data\r\nimportlib.reload(t2listing)\r\nimportlib.reload(t2data)\r\n\r\n\r\nliquid_density_kgPm3 = 1000\r\nbrine_density_kgPm3 = 1185.1\r\nwater_molecular_weight = 0.018\r\nR_value = 8.3145\r\nmPmm = 1.e-3\r\ndayPs = 1./(3600*24)\r\nT_kelven = 273.15\r\nT_initial = 25.0\r\nP_initial = 101.3e3\r\n\r\ndat = t2data.t2data()\r\ndat.title = 'flow.inp' # for toughreact, only 'flow.inp' can be used as flow input file\r\ndat.add_react(mopr=[None,2,0,0,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1])\r\n# the first 2 means only run tough2 not chemical and solute\r\n\r\n# #--- set up the model ---------------------------------\r\nlength_x = 40.\r\nnblks_x = 80\r\nlength_z = 6.\r\nnblks_z = 12\r\ndx = [length_x / nblks_x] * nblks_x\r\ndz = [length_z / nblks_z] * nblks_z\r\ndy = [0.5]\r\ngeo = t2data.mulgrid().rectangular(dx, dy, dz)\r\ngeo.write(dat.title+'.dat')\r\n\r\n# #Create TOUGH2 input data file:\r\ndat.grid = t2data.t2grid().fromgeo(geo)\r\ndat.parameter.update(\r\n {'max_timesteps' : 9.e3,\r\n 'const_timestep' : -1,\r\n 'tstop' : 200*24*3600,\r\n 'gravity' : 9.81,\r\n 'print_level' : 2,\r\n 'texp' : 1.8,\r\n 'timestep' : [1.0],\r\n 'default_incons' : [P_initial, 0, 10.99, T_initial, None]})\r\n\t \r\ndat.parameter['print_interval'] = dat.parameter['max_timesteps']/20\r\ndat.parameter['max_timestep'] = dat.parameter['tstop']/dat.parameter['max_timesteps']\r\n\r\n# #Set MOPs:\r\ndat.parameter['option'][1] = 1\r\ndat.parameter['option'][7] = 0\r\ndat.parameter['option'][11] = 0\r\ndat.parameter['option'][16] = 4\r\ndat.parameter['option'][19] = 2\r\ndat.parameter['option'][21] = 3\r\n\r\ndat.start = True\r\n#dat.diffusion=[[2.13e-5, 0.e-8], [2.13e-5, 0.e-8]]\r\ndat.multi={'num_components': 3, 'num_equations': 3, 'num_phases': 2, 'num_secondary_parameters': 6}\r\ndat.selection={'float':[None],'integer':[2]}\r\n\r\n# #Add another rocktype, with relative permeability and capillarity functions & parameters:\r\nr1 = t2data.rocktype('SAND ', nad = 2, porosity = 0.45,density = 2650.,permeability = [2.e-12, 2.e-12, 2.e-12],conductivity = 2.51,specific_heat = 920)\r\nr1.tortuosity = 0\r\nr1.relative_permeability = {'type': 7, 'parameters': [0.627, 0.045, 1., 0.054] }\r\nr1.capillarity = {'type': 7, 'parameters': [0.627, 0.045, 5.e-4, 1.e8, 1.]}\r\ndat.grid.add_rocktype(r1)\r\n\r\nr2 = t2data.rocktype('BOUND', nad = 2,porosity = 0.99,density = 2650., permeability = [2.e-12, 2.e-12, 2.e-12],conductivity = 2.51,specific_heat = 1.e5)\r\nr2.relative_permeability = {'type': 1, 'parameters': [0.1, 0., 1., 0.1]}\r\nr2.capillarity = {'type': 1, 'parameters': [0. , 0., 1.0 ]}\r\ndat.grid.add_rocktype(r2)\r\n# relative_humidity=0.1\r\n# P_bound=np.log(relative_humidity)*liquid_density_kgPm3*R_value*(T_initial+T_kelven)/water_molecular_weight\r\n# r2.relative_permeability = {'type': 1, 'parameters': [0.1,0.0,1.0,0.1,]}\r\n# r2.capillarity = {'type': 1, 'parameters': [-P_bound, 0., 1.0]}\r\n\t\r\nbvolume = 1.e50\r\nconarea = dy[0] * dz[0]\r\ncondist = 1.e-10\r\n# #assign rocktype and parameter values:\r\nfor blk in dat.grid.blocklist:\r\n blk.rocktype = r1\r\n blk.ahtx=conarea\r\n\r\n# #add boundary condition block at each end:\r\nfor i in range(nblks_z):\r\n b1 = t2data.t2block('zzz'+str(i+1), bvolume, dat.grid.rocktype['BOUND'],ahtx=conarea,centre=np.array([0,0.25,-(length_z/nblks_z+i)/2]) )\r\n dat.grid.add_block(b1)\r\n con1 = t2data.t2connection([b1, dat.grid.blocklist[i*nblks_x],b1], # why three\r\n distance = [condist,0.5*dx[0]], area = conarea, direction=1) #dirction=1 ends up with betax=0 (cos between gravity and line between link)\r\n dat.grid.add_connection(con1)\r\n\r\nfor i in range(nblks_z-4):\r\n b2 = t2data.t2block('zzz'+str(nblks_z+i+1), bvolume, dat.grid.rocktype['BOUND'],ahtx=conarea,centre=np.array([length_x,0.25,-(length_z/nblks_z+i+4)/2]))\r\n dat.grid.add_block(b2)\r\n con2 = t2data.t2connection([dat.grid.blocklist[nblks_x-1+(i+4)*nblks_x], b2],\r\n distance = [0.5*dx[nblks_x-1], condist], area = conarea, direction=1)\r\n dat.grid.add_connection(con2)\r\n\r\n\r\n#for i in range(nblks_z-4):\r\n# #print(dat.grid.blocklist[-(i+1)])\r\n# print(brine_density_kgPm3*dat.parameter['gravity']*(dat.grid.blocklist[-(i+1)].centre[2]+1.5)\r\n\r\n# #Set initial condition:\r\nfor i in range(nblks_z-4):\r\n dat.incon[str(dat.grid.blocklist[-(i+1)])] = \\\r\n [None, [P_initial-brine_density_kgPm3*dat.parameter['gravity']*(dat.grid.blocklist[-(i+1)].centre[2]+1.5), 1, 10.01, T_initial]]\r\n\r\n#[None, [144896.86625, 1, 10.01, 25.0]]\r\n\r\nfor i in range(nblks_z):\r\n dat.incon[str(dat.grid.blocklist[-(i+1+nblks_z-4)])] \\\r\n = [None, [P_initial-liquid_density_kgPm3*dat.parameter['gravity']*(dat.grid.blocklist[-(i+1+nblks_z-4)].centre[2]+1), 0, 10.01, T_initial]]\r\n\r\n# #deleted block:\r\nj=0\r\ni=(10*2-1)*(j+1)+j*10\r\nwhile i...p\", P))\n if calc_cons:\n self.cons = np.einsum(\"p...->...p\", U)\n if calc_derived or calc_cons:\n self.ucon = np.einsum(\"p...->...p\", self.ucon)\n self.ucov = np.einsum(\"p...->...p\", self.ucov)\n self.bcon = np.einsum(\"p...->...p\", self.bcon)\n self.bcov = np.einsum(\"p...->...p\", self.bcov)\n else:\n self.prims = np.ascontiguousarray(P)\n if calc_cons:\n self.cons = U\n # We no longer need the originals\n del P,G\n if calc_cons:\n del U\n \n # Associate a scale & units with this dump, for calculating variables\n # normally reserved for e.g. radiative transfer\n def set_units(self, MBH, M_unit):\n self.units = get_units(MBH, M_unit, gam=self.params['gam'])\n\n # Act like a dict when retrieving lots of different things --\n # just compute/retrieve them on the fly!\n def __getitem__(self, key):\n key = str(key)\n if key in self.header['prim_names']:\n i = self.header['prim_names'].index(key)\n if self._zones_first:\n return self.prims[:, :, :, i]\n else:\n return self.prims[i]\n elif key in self.__dict__:\n return self.__dict__[key]\n elif key in ['r', 'th', 'phi']:\n return getattr(self.grid.coords, key)(self.grid.coord_all())\n elif key in ['x', 'y', 'z']:\n return getattr(self.grid.coords, 'cart_' + key)(self.grid.coord_all())\n elif key in ['X1', 'X2', 'X3']:\n return self.grid.coord_all()[int(key[-1:])]\n elif key in self.header:\n return self.header[key]\n elif key in vars.fns_dict:\n return vars.fns_dict[key](self)\n elif key[:4] == \"abs_\":\n return np.abs(self[key[4:]])\n elif key[:4] == \"log_\":\n return np.log10(self[key[4:]])\n elif key[:3] == \"ln_\":\n return np.log(self[key[3:]])\n elif key[:4] == \"pdf_\":\n var_og = self[key[4:]]\n pdf_window=(np.min(var_og), np.max(var_og))\n return np.histogram(var_og, bins=100, range=pdf_window,\n weights=np.repeat(self.gdet, self.N3).reshape(var_og.shape), density=True)\n # TODO transformed full vectors, with e.g. 'ucon_ks'\n # Return vector components\n elif key[-2:] == \"_0\" or key[-2:] == \"_1\" or key[-2:] == \"_2\" or key[-2:] == \"_3\":\n return self[key[0]+\"cov\"][int(key[-1])]\n elif key[-2:] == \"^0\" or key[-2:] == \"^1\" or key[-2:] == \"^2\" or key[-2:] == \"^3\":\n return self[key[0]+\"con\"][int(key[-1])]\n # Return transformed vector components\n elif key[-2:] == \"_t\" or key[-2:] == \"_r\" or key[-3:] == \"_th\" or key[-4:] == \"_phi\":\n return np.einsum(\"i...,ij...->j...\",\n self[key[0]+\"cov\"],\n self.grid.coords.dxdX(self.grid.coord_all())\n )[[\"t\", \"r\", \"th\", \"phi\"].index(key.split(\"_\")[-1])]\n elif key[-2:] == \"^t\" or key[-2:] == \"^r\" or key[-3:] == \"^th\" or key[-4:] == \"^phi\":\n return np.einsum(\"i...,ij...->j...\",\n self[key[0]+\"con\"],\n self.grid.coords.dXdx(self.grid.coord_all())\n )[[\"t\", \"r\", \"th\", \"phi\"].index(key.split(\"^\")[-1])]\n elif key[-2:] == \"_x\" or key[-2:] == \"_y\" or key[-2:] == \"_z\":\n return np.einsum(\"i...,ij...->j...\",\n self[key[0]+\"cov\"],\n np.einsum(\"ij...,jk...->ik...\",\n self.grid.coords.dxdX(self.grid.coord_all()),\n self.grid.coords.dxdX(self.grid.coord_all())\n )\n )[[\"t\", \"r\", \"th\", \"phi\"].index(key.split(\"_\")[-1])]\n elif key[-2:] == \"^x\" or key[-2:] == \"^y\" or key[-2:] == \"^z\":\n return np.einsum(\"i...,ij...->j...\",\n self[key[0]+\"con\"],\n np.einsum(\"ij...,jk...->ik...\",\n self.grid.coords.dxdX(self.grid.coord_all()),\n self.grid.coords.dxdX(self.grid.coord_all())\n )\n )[[\"t\", \"r\", \"th\", \"phi\"].index(key.split(\"^\")[-1])]\n else:\n try:\n # Reshape number inputs. I swear this is useful for properly-sized constant arrays for e.g. area\n nkey = float(key)\n return nkey*np.ones_like(self['RHO'])\n except ValueError:\n raise ValueError(\"IharmDump cannot find or compute {}\".format(key))\n\n # TODO does __del__ need to do anything?\n\n\n","sub_path":"pyHARM/ana/iharm_dump.py","file_name":"iharm_dump.py","file_ext":"py","file_size_in_byte":9171,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"281746853","text":"from django.db.models import fields\nfrom django.forms import widgets\nfrom .models import (\n Escuela,Secretaria,Alumno,Docente,Jurado,Director,Asesor,Solicitud,TramiteInicioPractica,\n TramiteFinPractica,ActaAprobacion,SolicitudTesis,InscripcionTesis,SustentacionTesis,\n TesisJurado\n )\nfrom django import forms\n\nclass EscuelaForm(forms.ModelForm):\n class Meta:\n model = Escuela\n fields = '__all__'\n\nclass DirectorForm(forms.ModelForm):\n class Meta:\n model = Director\n fields = '__all__'\n exclude = ('usuario',)\n\nclass SecretariaForm(forms.ModelForm):\n class Meta:\n model = Secretaria\n fields = '__all__'\n exclude = ('usuario',)\n\nclass DocenteForm(forms.ModelForm):\n class Meta:\n model = Docente\n fields = '__all__'\n exclude = ('usuario','escuela',)\n\nclass AlumnoForm(forms.ModelForm):\n class Meta:\n model = Alumno\n fields = '__all__'\n exclude = ('usuario','estado',)\n\nclass JuradoForm(forms.ModelForm):\n docente = forms.ModelChoiceField(queryset=Docente.objects.all(),widget=forms.Select(attrs={'class':'selectpicker'}))\n class Meta:\n model = Jurado\n fields = '__all__'\n\nclass AsesorForm(forms.ModelForm):\n docente = forms.ModelChoiceField(queryset=Docente.objects.all(),widget=forms.Select(attrs={'class':'selectpicker'}))\n class Meta:\n model = Asesor\n fields = '__all__'\n\nclass SolicitudForm(forms.ModelForm):\n class Meta:\n model = Solicitud\n fields = '__all__'\n exclude = ('observacion','alumno')\n widgets = {'estado': forms.HiddenInput()}\n\nclass SolicitudFormEvaluar(forms.ModelForm):\n class Meta:\n model = Solicitud\n fields = '__all__'\n exclude = ('alumno','documento','enviar')\n\nclass TramiteInicioPracticaForm(forms.ModelForm):\n asesor = forms.ModelChoiceField(queryset=Asesor.objects.all(),widget=forms.Select(attrs={'class':'selectpicker'}))\n class Meta:\n model = TramiteInicioPractica\n fields = '__all__'\n exclude = ('solicitud','observacion',)\n widgets = {\n 'fecha_aceptacion':forms.TextInput(attrs={'type': 'date','class': 'datetimepicker-input'}), #CAMBIAR FORMATO DE IMPUT DE FECHA\n 'estado': forms.HiddenInput()\n }\n\nclass TramiteInicioPracticaFormEvaluar(forms.ModelForm):\n class Meta:\n model = TramiteInicioPractica\n fields = '__all__'\n exclude = ('solicitud','enviar','asesor','voucher','carta_aceptacion','plan_practicas','fut_inicio_practicas')\n widgets = {\n 'fecha_aceptacion':forms.TextInput(attrs={'type': 'date','readonly':'readonly','class': 'form-control datetimepicker-input'}) #CAMBIAR FORMATO DE IMPUT DE FECHA\n }\n\nclass TramiteFinPracticaForm(forms.ModelForm):\n class Meta:\n model = TramiteFinPractica\n fields = '__all__'\n exclude = ('tramiteInicioPractica','observacion')\n widgets = {'estado': forms.HiddenInput()}\n\nclass TramiteFinPracticaFormEvaluar(forms.ModelForm):\n class Meta:\n model = TramiteFinPractica\n fields = '__all__'\n exclude = ('tramiteInicioPractica','enviar','voucher','informe_final_practicas','fut_fin_practicas','certificado_practicas')\n\nclass ActaAprobacionForm(forms.ModelForm):\n class Meta:\n model = ActaAprobacion\n fields = '__all__'\n exclude = ('tramiteFinPractica','asesor')\n\nclass SolicitudTesisForm(forms.ModelForm):\n class Meta:\n model = SolicitudTesis\n fields = '__all__'\n exclude = ('observacion','alumno')\n widgets = {'estado': forms.HiddenInput()}\n\nclass SolicitudTesisFormEvaluar(forms.ModelForm):\n class Meta:\n model = SolicitudTesis\n fields = '__all__'\n exclude = ('alumno','documento','enviar')\n\nclass InscripcionTesisForm(forms.ModelForm):\n asesor = forms.ModelChoiceField(queryset=Asesor.objects.all(),widget=forms.Select(attrs={'class':'selectpicker'}))\n class Meta:\n model = InscripcionTesis\n fields = '__all__'\n exclude = ('solicitud','observacion','asignada',)\n widgets = {\n 'estado': forms.HiddenInput()\n }\n\nclass InscripcionTesisFormEvaluar(forms.ModelForm):\n class Meta:\n model = InscripcionTesis\n fields = '__all__'\n exclude = ('solicitud','enviar','asesor','voucher','fut_inscripcion_tesis','ejemplar_tesis','asignada',)\n\nclass SustentacionTesisForm(forms.ModelForm):\n \n class Meta:\n model = SustentacionTesis\n fields = '__all__'\n exclude = ('observacion','hora','enlace','inscripcionTesis','jurados','fecha_sustentacion','nota',)\n widgets = {\n 'fecha_sustentacion':forms.TextInput(attrs={'type': 'date','class': 'form-control datetimepicker-input'}), #CAMBIAR FORMATO DE IMPUT DE FECHA\n 'estado': forms.HiddenInput(),\n 'asignada': forms.HiddenInput(),\n 'hora':forms.TimeInput(attrs={'type': 'text','class': 'form-control datetimepicker-input'}),\n }\n\nclass SustentacionTesisFormAsignar(forms.ModelForm):\n # jurados = forms.ModelChoiceField(queryset=Jurado.objects.all(),widget=forms.Select(attrs={'class':'selectpicker selectmultiple ','multiple':'multiple'}))\n class Meta:\n model = SustentacionTesis\n fields = '__all__'\n exclude = ('inscripcionTesis','observacion','enviar','estado','voucher','fut_sustentacion_tesis','resumen_tesis','nota')\n widgets = {\n 'fecha_sustentacion':forms.TextInput(attrs={'type': 'date','class': 'form-control datetimepicker-input'}), #CAMBIAR FORMATO DE IMPUT DE FECHA\n 'hora':forms.TextInput(attrs={'type': 'time','class': 'form-control datetimepicker-input'}),\n }\n\nclass TesisJuradoForm(forms.ModelForm):\n class Meta:\n model = TesisJurado\n fields = '__all__'\n exclude = ('sustentacionTesis','jurado',)","sub_path":"practicas_tesisApp/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":5937,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"455755261","text":"# -*- encoding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nimport os\n\nfrom django.db import models\nfrom django import forms\nfrom django.forms import ModelForm\n# Added imports\nfrom django.contrib.auth.models import User, Group\nfrom datetime import datetime\nfrom core import views_utils as util\nfrom core import rights\nfrom django.core.exceptions import ValidationError\n# Extending the Django User's model\nfrom django.contrib.auth.models import AbstractUser\n\n# Logger class\nfrom core.views_logs import logger\n\n\nclass TimeStampedModelMixin(models.Model):\n \"\"\"\n Abstract Mixin model to add timestamp\n \"\"\"\n # Timestamp\n created = models.DateTimeField(u\"Date created\", auto_now_add=True)\n updated = models.DateTimeField(\n u\"Date updated\", auto_now=True, db_index=True)\n\n class Meta:\n abstract = True\n\n\n# => UserType (OP or simple user)\nclass UserType(TimeStampedModelMixin):\n status = models.CharField(max_length=20)\n\n def __unicode__(self):\n return self.status\n\n\n# Extending base User class\n# https://micropyramid.com/blog/how-to-create-custom-user-model-in-django/\nclass User(AbstractUser):\n status_rel = models.ForeignKey(\n UserType, on_delete=models.CASCADE, null=True, blank=True)\n avatar = models.FileField(upload_to='avatar/', null=True, blank=True)\n rssfeed = models.CharField(max_length=400, null=True, blank=True)\n collapsednavbar = models.BooleanField(default=False)\n\n # If is_superuser comes with NULL value, set it to FALSE\n # (we use a personalized form and if not checked, comes as NULL)\n def save(self, *args, **kwargs):\n if not self.is_superuser:\n self.is_superuser = False\n super(User, self).save(*args, **kwargs)\n\n\n# => Auth forms\nclass UserForm(ModelForm):\n date_joined = forms.DateField(\n widget=forms.SelectDateWidget(), input_formats=['%d/%m/%Y'],initial=util.now)\n password_first = forms.CharField(\n label='Initial Password', widget=forms.PasswordInput,\n required=False,initial='')\n password_check = forms.CharField(\n label='Password confirmation', widget=forms.PasswordInput,\n required=False,initial='')\n is_active = forms.BooleanField(required=False, initial=True)\n\n # is_superuser = forms.BooleanField(initial=False)\n # Pass request to query wich user is trying ot modify the object User\n def __init__(self, *args, **kwargs):\n self.request = kwargs.pop(\"request\")\n super(UserForm, self).__init__(*args, **kwargs)\n\n class Meta:\n model = User\n #fields = ['username', 'first_name', 'last_name', 'email', 'is_superuser', 'is_staff',\n # 'is_active', 'rssfeed', ]\n exclude = ['password']\n\n def clean_password_check(self):\n password_raw = self.cleaned_data.get('password_first')\n password_chk = self.cleaned_data.get('password_check')\n # First password but not second\n if not password_chk and password_raw:\n raise forms.ValidationError(\"You must confirm your password\")\n # First and second but differents\n elif password_raw != password_chk:\n raise forms.ValidationError(\"Your passwords do not match\")\n # Not updating password\n elif self.instance.pk and password_chk == \"\" and password_raw == \"\":\n pass\n else:\n return password_chk\n\n # Only admin can set is_superuser to TRUE or change it to normal users\n def clean_is_superuser(self):\n cleaned_superuser = self.cleaned_data.get('is_superuser')\n # If we return a simple \"HttpResponse\" and the cleaned data\n # we can raise the error for debug purpouses\n # return HttpResponse(cleaned_superuser)\n user_obj = self.request.user\n # If user exists\n if self.instance.pk:\n # If modifier is not admin\n if user_obj.username != 'admin':\n # Do nothing, return original instance\n return self.instance.is_superuser\n else:\n # If admin, get the submitted value in the form and clean_it\n self.is_superuser = cleaned_superuser\n return self.is_superuser\n\n def clean_last_login(self):\n return self.instance.last_login\n\n\nclass GroupForm(ModelForm):\n class Meta:\n model = Group\n fields = '__all__'\n\n\n# => Companys\nclass Company(TimeStampedModelMixin):\n name = models.CharField(max_length=100)\n # More fields will be needed...\n logo = models.FileField(upload_to='logo/')\n\n # phone = pending\n # address = pending\n def __unicode__(self):\n return self.name\n\n\nclass CompanyForm(ModelForm):\n class Meta:\n model = Company\n fields = '__all__'\n\n\n# => Queues (ex Departments)\nclass Queue(TimeStampedModelMixin):\n name = models.CharField(max_length=100)\n shortcode = models.CharField(max_length=10)\n description = models.CharField(max_length=30, null=True, blank=True)\n company_rel = models.ForeignKey(Company, on_delete=models.CASCADE)\n # logo = pending....\n # color = if needed....\n\n def __unicode__(self):\n return self.name\n\n\nclass QueueForm(ModelForm):\n class Meta:\n model = Queue\n fields = '__all__'\n\n\n# => Groups\n# Group's rights\nclass Rights(TimeStampedModelMixin):\n enabled = models.BooleanField(default=True)\n grp_src = models.ForeignKey(\n Group, related_name=\"src_grp\", blank=True, null=True)\n queue_dst = models.ForeignKey(\n Queue, related_name=\"dst_queue\", blank=True, null=True)\n # Permited actions\n can_view = models.BooleanField(default=False)\n can_create = models.BooleanField(default=False)\n can_delete = models.BooleanField(default=False)\n can_edit = models.BooleanField(default=False)\n can_comment = models.BooleanField(default=False)\n\n ''''\n Check at database state if registry is created or we can create it:\n If you use the admin, to mantain the non-duplicity of the rules, we make a\n secondary check at time to save the object to the DB.\n Yes, you have 2 querys but this is the unique way to avoid errors if you\n use the admin panel to insert some righths\n '''\n\n def detect_rights_exists(self, grp, queue):\n return_query = {}\n obj_query = Rights.objects.filter(grp_src=grp, queue_dst=queue)\n if obj_query:\n return_query['status'] = True\n return_query['numbers'] = [i.id for i in obj_query]\n return return_query\n else:\n return_query['status'] = False\n return return_query\n\n # Only for new records (self.pk check)\n def save(self, *args, **kwargs):\n detect_function = self.detect_rights_exists(\n self.grp_src, self.queue_dst)\n if not self.pk and detect_function['status']:\n raise ValidationError(\n \"Rule already created: model output \" + str(\n detect_function['numbers']) + \"\")\n else:\n super(Rights, self).save(*args, **kwargs)\n\n\nclass RightForm(ModelForm):\n class Meta:\n model = Rights\n fields = '__all__'\n\n # Check at form stage if registry is created or if we can create it\n def clean_queue_dst(self):\n detect_function = Rights.detect_rights_exists(\n Rights(), self.cleaned_data.get('grp_src'),\n self.cleaned_data.get('queue_dst'))\n # Check if no pk assigned and if detect_function['status'] is True\n if not self.instance.pk and detect_function['status']:\n raise forms.ValidationError(\n \"Rule already created (\" + str(detect_function['numbers'][0]) + \") src=>\" +\n str(self.cleaned_data.get('grp_src')) +\n \" dst=>\" + str(self.cleaned_data.get('queue_dst')) + \"\")\n return self.cleaned_data.get('queue_dst')\n\n\n# => States\nclass State(TimeStampedModelMixin):\n name = models.CharField(max_length=30)\n description = models.CharField(max_length=150, null=True, blank=True)\n active = models.BooleanField(default=True)\n color = models.CharField(default='008ac6', max_length=10, null=True, blank=True)\n\n def save(self, *args, **kwargs):\n if self.color.startswith(\"# \"):\n self.color = self.color[1:]\n super(State, self).save(*args, **kwargs)\n\n def __unicode__(self):\n return self.name\n\n\nclass StateForm(ModelForm):\n class Meta:\n model = State\n fields = '__all__'\n\n\n# => Prioritys\nclass Priority(TimeStampedModelMixin):\n name = models.CharField(max_length=30)\n\n def __unicode__(self):\n return self.name\n\n\nclass PriorityForm(ModelForm):\n class Meta:\n model = Priority\n fields = '__all__'\n\n\n# => Inventory Servers/PC\nclass InventoryGroup(TimeStampedModelMixin):\n name = models.CharField(max_length=100)\n company_rel = models.ForeignKey(Company, null=True)\n\n\nclass Inventory(TimeStampedModelMixin):\n name = models.CharField(max_length=100)\n ip = models.GenericIPAddressField(protocol='ipv4')\n group_rel = models.ForeignKey(InventoryGroup, null=True)\n\n\n# => Tickets\nclass Ticket(TimeStampedModelMixin):\n create_user = models.ForeignKey(\n User, related_name=\"c_user\", blank=True, null=True,)\n subject = models.CharField(max_length=40)\n body = models.TextField(null=True, blank=True)\n assigned_user = models.ForeignKey(\n User, blank=True, null=True, related_name=\"a_user\")\n assigned_queue = models.ForeignKey(Queue, blank=True, null=True)\n assigned_company = models.ForeignKey(Company, blank=True, null=True)\n assigned_state = models.ForeignKey(State)\n assigned_prio = models.ForeignKey(Priority)\n assigned_inventory = models.ForeignKey(Inventory, null=True, blank=True)\n percentage = models.IntegerField(default=0, blank=True, null=True)\n\n def __str__(self):\n return '%s' % (self.id)\n\n '''Return a empty string to avoid problems in JSON serialization'''\n def str_assigned_user_name(self):\n try:\n assigned_user_data = \"\" + str(self.assigned_user.first_name) + \\\n \" \" + str(self.assigned_user.last_name) + \"\"\n except:\n assigned_user_data = \"\"\n return assigned_user_data\n\n def str_creator_user_name(self):\n try:\n creator_user_data = \"\" + str(self.create_user.first_name) + \" \" + \\\n str(self.create_user.last_name) + \"\"\n except:\n creator_user_data = \"\"\n return creator_user_data\n\n def as_json(self):\n return dict(\n id=str(self.id),\n date=str(self.created.strftime('%d-%m-%Y %H:%M')),\n subject_data=str(self.subject.encode('utf8')),\n body_data=str(self.body.encode('utf8')),\n state_data=str(self.assigned_state.name),\n state_data_id=str(self.assigned_state.id),\n state_color_data=str(self.assigned_state.color),\n percentage_data=str(self.percentage),\n queue_shortcode=str(self.assigned_queue.shortcode),\n priority=str(self.assigned_prio),\n create_user=self.str_creator_user_name(),\n assigned_user_data=self.str_assigned_user_name(),)\n\n\nclass TicketForm(ModelForm):\n # Pass request to a form => http://stackoverflow.com/questions/6325681/\n # passing-a-user-request-to-forms\n def __init__(self, *args, **kwargs):\n self.request = kwargs.pop(\"request\")\n super(TicketForm, self).__init__(*args, **kwargs)\n\n class Meta:\n model = Ticket\n fields = '__all__'\n # exclude = ['date']\n\n '''\n We log all importante changes in fields to be tracked\n The field_checker test if both are the same and if it found changes, call \"logger\" passing data\n TODO: Maybe, \"if self.instance.pk is not None:\" can be improved to not call\n all times to make the check (and save N checks at save time)\n '''\n\n def clean_assigned_state(self):\n if self.instance.pk is not None: # new instance only\n self.field_checker(str(self.instance.assigned_state), str(\n self.cleaned_data.get('assigned_state')))\n return self.cleaned_data.get('assigned_state')\n\n '''\n Check if the new queue assigned is permited...\n '''\n def clean_assigned_queue(self):\n if self.instance.pk is not None: # new instance only\n user_object_rights = rights.get_rights_for_ticket(\n user=self.request.user,\n queue=self.cleaned_data.get('assigned_queue'), ticket_id=None)\n if not user_object_rights.can_create:\n raise forms.ValidationError(self.clean_error_cantcreate())\n else:\n self.field_checker(\n str(self.instance.assigned_queue),\n str(self.cleaned_data.get('assigned_queue')))\n return self.cleaned_data.get('assigned_queue')\n\n def clean_assigned_user(self):\n if self.instance.pk is not None: # new instance only\n self.field_checker(self.instance.assigned_user, self.cleaned_data.get('assigned_user'))\n return self.cleaned_data.get('assigned_user')\n\n def clean_subject(self):\n if self.instance.pk is not None: # new instance only\n self.field_checker(self.instance.subject, self.cleaned_data.get('subject'))\n return self.cleaned_data.get('subject')\n\n def clean_body(self):\n if self.instance.pk is not None: # new instance only\n self.field_checker(self.instance.body, self.cleaned_data.get('body'))\n return self.cleaned_data.get('body')\n\n '''\n Error codes:\n '''\n\n def clean_error_cantedit(self):\n cantedit = 'You don\\'t have permissions to edit this ticket'\n return cantedit\n\n def clean_error_cantview(self):\n cantview = 'You don\\'t have permissions to view this ticket'\n return cantview\n\n def clean_error_cantcreate(self):\n cantcreate = 'You don\\'t have permissions to create this ticket'\n return cantcreate\n\n def clean_error_cantsave(self):\n cantsave = 'You don\\'t have permissions to save this ticket'\n return cantsave\n\n '''\n Functions:\n Check source=>destiny object and if it's not the same, log clean_it\n '''\n\n def field_checker(self, source=None, destiny=None, destiny_name=None):\n if source != destiny:\n logger(self.instance, self.request.user, \"Changed\", destiny)\n pass\n\n def clean(self):\n # Some essential vars\n user_obj = self.request.user\n cleaned_data = self.cleaned_data\n queue_obj = cleaned_data.get('assigned_queue')\n\n '''Check creation'''\n if not self.instance.pk:\n user_object_rights = rights.get_rights_for_ticket(\n user=user_obj, queue=queue_obj, ticket_id=None)\n if not user_object_rights.can_create:\n raise forms.ValidationError(self.clean_error_cantcreate())\n\n '''Check edition'''\n if self.instance.pk:\n user_object_rights = rights.get_rights_for_ticket(\n user=user_obj, queue=queue_obj, ticket_id=self.instance.id)\n if not user_object_rights.can_edit:\n raise forms.ValidationError(self.clean_error_cantedit())\n\n '''Force to assign company'''\n cleaned_data['assigned_company'] = queue_obj.company_rel\n\n # '''Put percentage 100% when closed ticket is detected'''\n # if cleaned_data['assigned_state'].id == 3:\n # self.instance.percentage = int(100)\n\n\n# => Attachments\n# Method to store tickets attachments inside folders called with related ticket id\ndef get_attachment_upload_path(instance, filename):\n return os.path.join(\"ticket_files/%s\" % instance.ticket_rel.id, filename)\n\n\nclass Attachment(TimeStampedModelMixin):\n\n ticket_rel = models.ForeignKey(Ticket, null=True, blank=True)\n file_name = models.FileField(\n upload_to=get_attachment_upload_path, null=True, blank=True)\n\n\nclass AttachmentForm(ModelForm):\n class Meta:\n model = Attachment\n fields = '__all__'\n\n\n# => Comments\nclass Comments(TimeStampedModelMixin):\n ticket_rel = models.ForeignKey(Ticket, related_name='ticket_rel_comm')\n user_rel = models.ForeignKey(User, related_name='user_rel_comm')\n comment = models.TextField(null=True, blank=True)\n private = models.BooleanField(default=False)\n\n '''Return this dict to avoid the NO-NESTED objects in serialize library'''\n\n def as_json(self, request):\n if request.user.id == self.user_rel.id or request.user.is_superuser:\n delete_comment = True\n else:\n delete_comment = False\n\n return dict(\n human_name=\"\" + self.user_rel.username + \"\",\n avatar_data=str(self.user_rel.avatar),\n # UTF8 in order to avoid encoding problems\n comment_data=str(self.comment.encode('utf8')),\n id=str(self.id),\n delete_comment=str(delete_comment),\n date_data=str(self.created.strftime('%Y-%m-%d %H:%M')))\n\n\nclass Microtasks(TimeStampedModelMixin):\n ticket_rel = models.ForeignKey(Ticket, related_name='ticket_rel_mtask')\n subject = models.CharField(max_length=40)\n body = models.TextField(null=True, blank=True)\n assigned_state = models.ForeignKey(State, null=True, blank=True)\n percentage = models.IntegerField(default=0, blank=True, null=True)\n\n def as_json(self):\n return dict(\n # UTF8 in order to avoid encoding problems\n id=str(self.id),\n subject_data=str(self.subject.encode('utf8')),\n body_data=str(self.body.encode('utf8')),\n state_data=str(self.assigned_state),\n state_data_id=str(self.assigned_state.id),\n state_color_data=str(self.assigned_state.color),\n date_data=str(self.created.strftime('%d/%m/%y %H:%M:%S')),\n percentage_data=int(self.percentage))\n\n\nclass Logs(TimeStampedModelMixin):\n log_ticket = models.ForeignKey(Ticket, related_name='ticket_log')\n log_user = models.ForeignKey(User, related_name='user_log')\n log_action = models.CharField(max_length=200)\n log_destiny = models.CharField(max_length=200)\n","sub_path":"ticketatorapp/core/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":18208,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"57350776","text":"import urllib3\nimport json\nimport boto3\nimport time\nimport math\n\ndef bitbns():\n http = urllib3.PoolManager()\n res={\n \"exchangeUID\": 4,\n \"exchangeName\": \"BitBNS\",\n \"updateTimestamp\": 0,\n \"coins\":[\n ]\n }\n # coinlist array, sequentially add all required coins to this\n coinlist=[]\n response= http.request('GET', 'https://bitbns.com/order/getTickerWithVolume/')\n coindata = response.data.decode(\"utf-8\")\n coindata = json.loads(coindata)\n times= math.floor(time.time())\n #update time of updateTimestamp ( only once in whole routine)\n res[\"updateTimestamp\"]=times\n #======coin 1 BTC===\n coin = {\n \"coinUID\": 1,\n \"coinName\": \"BTC\",\n \"coinbuyprice\": coindata['BTC']['lowest_sell_bid'],\n \"coinsellprice\": coindata['BTC']['highest_buy_bid']\n }\n coinlist.append(coin)\n #=====================\n\n #======coin 2 ETH===\n coin = {\n \"coinUID\": 2,\n \"coinName\": \"ETH\",\n \"coinbuyprice\": coindata['ETH']['lowest_sell_bid'],\n \"coinsellprice\": coindata['ETH']['highest_buy_bid']\n }\n coinlist.append(coin)\n #=====================\n #======coin 3 LTC===\n coin = {\n \"coinUID\": 3,\n \"coinName\": \"LTC\",\n \"coinbuyprice\": coindata['LTC']['lowest_sell_bid'],\n \"coinsellprice\": coindata['LTC']['highest_buy_bid']\n }\n coinlist.append(coin)\n #=====================\n #======coin 4 DOGE ===\n coin = {\n \"coinUID\": 4,\n \"coinName\": \"DOGE\",\n \"coinbuyprice\": coindata['DOGE']['lowest_sell_bid'],\n \"coinsellprice\": coindata['DOGE']['highest_buy_bid']\n }\n coinlist.append(coin)\n #=====================\n #======coin 5 TRX===\n coin = {\n \"coinUID\": 5,\n \"coinName\": \"TRX\",\n \"coinbuyprice\": coindata['TRX']['lowest_sell_bid'],\n \"coinsellprice\": coindata['TRX']['highest_buy_bid']\n }\n coinlist.append(coin)\n #=====================\n #======coin 6 ADA===\n coin = {\n \"coinUID\": 6,\n \"coinName\": \"ADA\",\n \"coinbuyprice\": coindata['ADA']['lowest_sell_bid'],\n \"coinsellprice\": coindata['ADA']['highest_buy_bid']\n }\n coinlist.append(coin)\n #=====================\n res[\"coins\"]= coinlist\n s = json.dumps(res)\n\n dynamodb = boto3.resource('dynamodb', region_name='us-east-2')\n table = dynamodb.Table('coin')\n\n response = table.put_item(\n Item={\n 'exchnum': 4,\n 'data': s\n }\n )\n\n return {\n 'statusCode': 200\n }\n","sub_path":"app/bitbns.py","file_name":"bitbns.py","file_ext":"py","file_size_in_byte":2596,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"479260702","text":"import komand\nfrom .schema import ViewSavedSearchPropertiesInput, ViewSavedSearchPropertiesOutput\n# Custom imports below\n\n\nclass ViewSavedSearchProperties(komand.Action):\n\n def __init__(self):\n super(self.__class__, self).__init__(\n name='view_saved_search_properties',\n description='Returns the properties for a saved search',\n input=ViewSavedSearchPropertiesInput(),\n output=ViewSavedSearchPropertiesOutput())\n\n def run(self, params={}):\n saved_search_name = params.get(\"saved_search_name\")\n\n saved_search = self.connection.client.saved_searches[saved_search_name]\n properties = saved_search.content\n\n return {\"properties\": properties}\n\n def test(self):\n return {}\n","sub_path":"splunk/komand_splunk/actions/view_saved_search_properties/action.py","file_name":"action.py","file_ext":"py","file_size_in_byte":778,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"6895704","text":"# coding:utf-8\n\"\"\"\n Time : 2021/1/27 下午3:07\n Author : vincent\n FileName: views\n Software: PyCharm\n Last Modified by: vincent\n Last Modified time: 2021/1/27 下午3:07\n\"\"\"\nimport base64\nimport datetime\nimport json\nimport logging\nimport os\nimport random\nimport string\nimport re\nimport time\nfrom _md5 import md5\nfrom decimal import Decimal\nfrom io import BytesIO\n\nimport pandas as pd\nfrom django.conf import settings\nfrom django.core import serializers\nfrom django.core.cache import cache\nfrom django.core.paginator import Paginator\nfrom django.db.models import Q\nfrom django.http import HttpResponse\nfrom django.shortcuts import render, redirect\nfrom django.urls import reverse\nfrom django.views.decorators.csrf import csrf_exempt\n\nfrom management.models import User, Role, Goods, GoodsDetails, DecoctCenter, Institution, Menu, Permission\nfrom relies import generate_code\nfrom relies.authorityControl import get_menu_html\nfrom relies.barCode_QRcode import generateBarcode\nfrom relies.handle import DateEncoder, string_to_list, model2json, makepdf\nfrom relies.prescription_audit import reverse_18, fear_19, usage_match, poisonous_and_dose_match\nfrom services.models import Order, Prescription, PresDetails\nfrom zhyf.settings import BASE_DIR\nlogger = logging.getLogger('log')\n\n\ndef login_old(request):\n err_msg = {}\n today_str = datetime.date.today().strftime(\"%Y%m%d\")\n verify_code_img_path = os.path.join('static/verify_code_imgs', today_str)\n if not os.path.exists(verify_code_img_path):\n os.makedirs(verify_code_img_path)\n print('创建目录成功')\n print(\"session:\", request.session.session_key)\n # print(\"session:\",request.META.items())\n random_filename = \"\".join(random.sample(string.ascii_lowercase, 4))\n random_code = generate_code.gene_code(verify_code_img_path, random_filename)\n cache.set(random_filename, random_code, 30)\n # GET 请求,直接显示用户登录界面\n if request.method == 'POST':\n # POST 请求,获取用户输入的用户名和密码\n username = request.POST.get('username')\n password = request.POST.get('password')\n verify_code = request.POST.get('code')\n verify_code_key = request.POST.get('verify_code_key')\n # print('username:', username)\n # print('password:', md5(password.encode('utf-8')).hexdigest())\n # print(\"verify_code_key:\", verify_code_key)\n # print(\"verify_code:\", verify_code)\n # print('cache_code:', cache.get(verify_code_key))\n\n if cache.get(verify_code_key) == verify_code.upper():\n print(\"code verification pass!\")\n # 从数据库中查询用户名和密码是否正确\n user = User.objects.filter(username=username, password=md5(password.encode('utf-8')).hexdigest())\n print(user)\n if len(user) != 0:\n request.session['username'] = username\n print('用户名密码正确,验证通过')\n login_user = User.objects.get(username=username)\n print(login_user)\n print(type(login_user))\n login_user.login_time = datetime.datetime.now().strftime(\"%Y-%m-%d %H:%M:%S\")\n login_user.save()\n context = {'name': login_user.name}\n print(context)\n return render(request, 'backstage/index.html', context=context)\n else:\n err_msg[\"uperror\"] = '用户名或密码错误!'\n else:\n err_msg['cerror'] = \"验证码错误或已过期!\"\n return render(request, 'backstage/mg_login_old.html',\n {\"filename\": random_filename, \"today_str\": today_str, \"error\": err_msg})\n\n\ndef login(request):\n err_msg = {}\n if request.method == 'POST':\n # POST 请求,获取用户输入的用户名和密码\n username = request.POST.get('username')\n password = request.POST.get('password')\n verify_code = request.POST.get('code')\n if cache.get('verify_code') == verify_code.upper():\n if username != 'whiteadmin':\n user = User.objects.filter(username=username, password=password).first()\n if user:\n request.session[\"is_login\"] = True\n request.session['username'] = user.username\n request.session.set_expiry(0) # 关闭浏览器就清掉session\n if user.is_disabled > 0:\n return redirect(reverse('management:index'))\n else:\n err_msg['uperror'] = '该用户已停用,请联系管理员!'\n else:\n err_msg[\"uperror\"] = '用户名或密码错误!'\n else:\n if password == md5('whiteadmin'.encode('utf-8')).hexdigest():\n return render(request, 'backstage/white_admin_index.html')\n else:\n err_msg[\"uperror\"] = '用户名或密码错误!'\n else:\n err_msg['cerror'] = \"验证码错误或已过期!\"\n return render(request, 'backstage/mg_login.html', err_msg)\n\n\ndef change_verify_code(request):\n im = generate_code.gene_code()\n fp = BytesIO()\n im[0].save(fp, 'png')\n cache.set('verify_code', im[1], 60)\n return HttpResponse(fp.getvalue(), content_type='image/png')\n\n\ndef index(request):\n is_login = request.session.get('is_login')\n username = request.session.get('username')\n if not is_login:\n \"\"\"如果没有登录则跳转至登录页面\"\"\"\n return redirect(reverse('management:login'))\n user = User.objects.get(username=username)\n user.login_time = datetime.datetime.now().strftime(\"%Y-%m-%d %H:%M:%S\")\n user.save()\n permission_item_list = list(user.role.values('permissions__url',\n 'permissions__title',\n 'permissions__per_id',\n 'permissions__menu_id').distinct())\n permission_list = [] # 用户权限url列表\n permission_menu_list = [] # 用户权限url所属菜单列表\n\n for item in permission_item_list:\n if item['permissions__menu_id']:\n temp = {\"title\": item['permissions__title'],\n \"url\": item[\"permissions__url\"],\n \"menu_id\": item[\"permissions__menu_id\"],\n 'per_id': item[\"permissions__per_id\"]}\n permission_list.append(temp)\n if item['permissions__menu_id'] in permission_menu_list:\n continue\n else:\n permission_menu_list.append(item['permissions__menu_id'])\n menu_list = list(Menu.objects.filter(id__in=permission_menu_list).values('id', 'title', 'icon'))\n # 注:session在存储时,会先对数据进行序列化,因此对于Queryset对象写入session, 加list()转为可序列化对象\n # print(permission_list)\n # print(menu_list)\n menu_html = get_menu_html(menu_list, permission_data=permission_list)\n context = {'name': user.name, 'menu_html': menu_html}\n # print(context)\n return render(request, 'backstage/index.html', context)\n # return render(request, 'backstage/index.html')\n\n\ndef logout(request):\n request.session.flush()\n return redirect(reverse('management:login'))\n\n\ndef home(request):\n return render(request, 'backstage/home.html')\n\n\n@csrf_exempt\ndef table_data(request, type):\n lis = []\n data_count = 0\n if type == 'menu_table':\n menuname = request.GET.get('menuname')\n menutype = request.GET.get('menutype')\n q1 = Q()\n q1.connector = 'AND'\n if menuname:\n q1.children.append(('title', menuname))\n if menutype:\n q1.children.append(('menu_type', menutype))\n if q1.children:\n menu_datas = Menu.objects.filter(q1)\n data_count += menu_datas.count()\n lis = list(menu_datas.values())\n for i in range(len(lis)):\n if lis[i]['parent_id']:\n lis[i]['parent_id'] = menu_datas[i].parent.title\n else:\n lis[i]['parent_id'] = ''\n else:\n menu_datas = Menu.objects.all()\n data_count += menu_datas.count()\n lis = list(menu_datas.order_by('id').values())\n # print(menu_datas)\n # print(lis)\n for i in range(len(lis)):\n if lis[i]['parent_id']:\n lis[i]['parent_id'] = menu_datas[i].parent.title\n else:\n lis[i]['parent_id'] = ''\n if type == 'user_table':\n username = request.GET.get('username')\n role = request.GET.get('role')\n last_login_start = request.GET.get('lastLoginStart')\n last_login_end = request.GET.get('lastLoginEnd')\n q1 = Q()\n q1.connector = 'AND'\n if username:\n q1.children.append(('username', username))\n if role:\n q1.children.append(('role', role))\n if last_login_start and last_login_end:\n q1.children.append(('login_time__range', (last_login_start, last_login_end)))\n # print(query_dict)\n if q1.children:\n user_datas = User.objects.filter(q1)\n data_count += user_datas.count()\n lis = list(user_datas.values())\n for i in range(len(lis)):\n lis[i]['role'] = list(user_datas[i].role.all().values('role_name'))[0]['role_name']\n else:\n user_datas = User.objects.all()\n data_count += user_datas.count() # 数据总数\n lis = list(user_datas.values())\n for i in range(len(lis)): # 级联数据\n lis[i]['role'] = list(user_datas[i].role.all().values('role_name'))[0]['role_name']\n # print(lis)\n elif type == 'role_table':\n data_count += Role.objects.all().count() # 数据总数\n lis = list(Role.objects.all().order_by('id').values())\n elif type == 'goods_table':\n key_words = request.GET.get('key_words')\n goods_code = request.GET.get('goods_code')\n q2 = Q()\n q3 = Q()\n q2.connector = 'OR' # q2对象表示‘OR’关系,也就是说q2下的条件都要满足‘OR’\n q3.connector = 'AND'\n if key_words:\n keys = ['goods_name', 'short_code', 'english_name', 'chinese_name', 'alias1', 'alias2', 'alias3', 'alias4',\n 'alias5', 'alias6', 'alias7', 'alias8', 'alias9', 'alias10']\n for key in keys:\n new_key = key + '__contains'\n q2.children.append((new_key, key_words))\n if goods_code:\n q3.children.append(('goods_code', goods_code))\n if (q2 & q3).children:\n goods_datas = Goods.objects.filter(q2 & q3)\n # print(goods_datas)\n data_count += goods_datas.count()\n lis = list(goods_datas.values())\n else:\n data_count += Goods.objects.all().count()\n lis = list(Goods.objects.all().values())\n elif type == 'goodsDetails_table':\n key_words = request.GET.get('key_words')\n goods_code = request.GET.get('goods_code')\n q1 = Q()\n q1.connector = 'AND'\n if key_words:\n q1.children.append(('goods_name__contains', key_words))\n if goods_code:\n q1.children.append(('goods_code', goods_code))\n if q1.children:\n goods_details = GoodsDetails.objects.filter(q1)\n data_count += goods_details.count()\n lis = list(goods_details.values())\n else:\n data_count += GoodsDetails.objects.all().count()\n lis = list(GoodsDetails.objects.all().values())\n elif type == 'center_table':\n key_words = request.GET.get('key_words')\n q1 = Q()\n q1.connector = 'OR'\n if key_words:\n try:\n key_words = int(key_words)\n q1.children.append(('code', key_words))\n except ValueError:\n q1.children.append(('name__contains', key_words))\n if q1.children:\n center_datas = DecoctCenter.objects.filter(q1)\n data_count += center_datas.count()\n lis = list(center_datas.values())\n else:\n data_count += DecoctCenter.objects.all().count()\n lis = list(DecoctCenter.objects.all().values())\n elif type == 'company_table':\n q1 = Q()\n q1.connector = 'OR'\n q2 = Q()\n q2.connector = 'AND'\n key_words = request.GET.get('keyWords')\n storage_type = request.GET.get('storageType')\n his_grade = request.GET.get('hisGrade')\n ascription = request.GET.get('ascription')\n if key_words:\n q1.children.append(('company_num__contains', key_words))\n q1.children.append(('company_name__contains', key_words))\n q1.children.append(('short_name__contains', key_words))\n if storage_type:\n q2.children.append(('storage_type', storage_type))\n if his_grade:\n q2.children.append(('his_grade', his_grade))\n if ascription:\n q2.children.append(('ascription', ascription))\n if (q1 & q2).children:\n companydatas = Institution.objects.filter(q1 & q2)\n data_count += companydatas.count()\n lis = list(companydatas.values())\n for i in range(len(lis)):\n lis[i]['storage_type'] = companydatas[i].storage_type.name\n lis[i]['oper_id'] = companydatas[i].oper_id.name\n else:\n company_datas = Institution.objects.all()\n data_count += company_datas.count()\n lis = list(company_datas.values())\n for i in range(len(lis)):\n lis[i]['storage_type'] = company_datas[i].storage_type.name\n lis[i]['oper_id'] = company_datas[i].oper_id.name\n elif type == 'order_table':\n order_q1 = Q()\n order_q2 = Q()\n order_q3 = Q()\n order_q1.connector = 'AND'\n order_q2.connector = 'AND'\n order_q3.connector = 'OR'\n consignee = request.GET.get('consignee')\n doctor_name = request.GET.get('doctorName')\n start_date = request.GET.get('startDate')\n end_date = request.GET.get('endDate')\n is_hos = request.GET.get('isHos')\n is_hosaddr = request.GET.get('isHosAddr')\n order_status = request.GET.get('orderStatus')\n other_presnum = request.GET.get('otherPresNum')\n prescri_type = request.GET.get('prescrType')\n prescri_id = request.GET.get('prescriId')\n source_id = request.GET.get('sourceId')\n storage_type = request.GET.get('storageType')\n user_name = request.GET.get('userName')\n if start_date and end_date:\n order_q1.children.append(('order_time__range', (start_date, end_date)))\n if source_id:\n order_q1.children.append(('source_id', source_id))\n if storage_type:\n order_q1.children.append(('storage_type', storage_type))\n if consignee:\n order_q1.children.append(('consignee', consignee))\n if is_hosaddr:\n order_q1.children.append(('is_hos_addr', is_hosaddr))\n if order_status:\n order_q1.children.append(('order_status', order_status))\n if doctor_name:\n order_q2.children.append(('doctor', doctor_name))\n if is_hos:\n order_q2.children.append(('is_hos', is_hos))\n if other_presnum:\n order_q2.children.append(('other_pres_num', other_presnum))\n if prescri_type:\n order_q2.children.append(('prescri_type', prescri_type))\n if prescri_id:\n order_q2.children.append(('prescri_id', prescri_id))\n if user_name:\n order_q2.children.append(('user_name', user_name))\n # print(order_q1.children)\n # print(order_q2.children)\n if order_q1.children and order_q2.children:\n prescription_datas = Prescription.objects.filter(order_q2)\n # print(prescription_datas)\n count = prescription_datas.count()\n # print(count)\n if count:\n for num in range(count):\n order_id = prescription_datas[num].order_id.order_id\n order_q3.children.append(('order_id', order_id))\n order_datas = Order.objects.filter(order_q1 & order_q3)\n else:\n order_datas = prescription_datas\n elif order_q1.children:\n order_datas = Order.objects.filter(order_q1)\n elif order_q2.children:\n prescription_datas = Prescription.objects.filter(order_q2)\n count = prescription_datas.count()\n if count:\n for num in range(count):\n order_id = prescription_datas[num].order_id.order_id\n order_q3.children.append(('order_id', order_id))\n order_datas = Order.objects.filter(order_q3)\n else:\n order_datas = prescription_datas\n else:\n order_datas = Order.objects.all()\n data_count += order_datas.count()\n lis = list(order_datas.values())\n for i in range(len(lis)):\n # print(order_datas[i].prescription_set.all().values('other_pres_num')[0]['other_pres_num'])\n prescript = order_datas[i].prescription_set.all() # 外键反向查询\n lis[i]['other_pres_num'] = prescript.values('other_pres_num')[0]['other_pres_num']\n lis[i]['prescri_id'] = prescript.values('prescri_id')[0]['prescri_id']\n lis[i]['prescri_type'] = prescript.values('prescri_type')[0]['prescri_type']\n lis[i]['is_suffering'] = prescript.values('is_suffering')[0]['is_suffering']\n lis[i]['user_name'] = prescript.values('user_name')[0]['user_name']\n lis[i]['doctor'] = prescript.values('doctor')[0]['doctor']\n lis[i]['storage_type'] = order_datas[i].storage_type.name\n lis[i]['source_id'] = order_datas[i].source_id.company_name\n elif type == 'drugs_table':\n pres_num = request.GET.get('prescri_id')\n drugs_datas = PresDetails.objects.filter(prescri_id=pres_num)\n data_count += drugs_datas.count()\n lis = list(drugs_datas.values())\n for i in range(len(lis)):\n lis[i]['unit_sum'] = Decimal(Decimal(drugs_datas[i].dose).quantize(Decimal('0.00')) *\n Decimal(drugs_datas[i].unit_price).quantize(Decimal('0.00000'))).quantize(\n Decimal('0.00'))\n result = {\"code\": 0, \"msg\": \"\", \"count\": data_count, \"data\": lis}\n return HttpResponse(json.dumps(result, cls=DateEncoder, ensure_ascii=False), content_type=\"application/json\")\n elif type == 'orderAudit_table':\n order_q1 = Q()\n order_q2 = Q()\n order_q3 = Q()\n order_q1.connector = 'AND'\n order_q2.connector = 'AND'\n order_q3.connector = 'OR'\n is_hos = request.GET.get('isHos')\n is_hosaddr = request.GET.get('isHosAddr')\n audit_type = request.GET.get('auditType')\n other_presnum = request.GET.get('otherPresNum')\n prescri_type = request.GET.get('prescrType')\n source_id = request.GET.get('sourceId')\n user_name = request.GET.get('userName')\n if source_id:\n order_q1.children.append(('source_id', source_id))\n if is_hosaddr:\n order_q1.children.append(('is_hos_addr', is_hosaddr))\n if audit_type:\n if int(audit_type) == 0:\n order_q1.children.append(('order_status', 5))\n else:\n order_q1.children.append(('order_status__gt', 5))\n if is_hos:\n order_q2.children.append(('is_hos', is_hos))\n if other_presnum:\n order_q2.children.append(('other_pres_num', other_presnum))\n if prescri_type:\n order_q2.children.append(('prescri_type', prescri_type))\n if user_name:\n order_q2.children.append(('user_name', user_name))\n if order_q1.children or order_q2.children:\n if order_q2.children and order_q1.children:\n prescription_datas = Prescription.objects.filter(order_q2)\n count = prescription_datas.count()\n if count:\n for num in range(count):\n order_id = prescription_datas[num].order_id.order_id\n order_q3.children.append(('order_id', order_id))\n order_datas = Order.objects.filter(order_q1 & order_q3 & Q(order_status=5))\n else:\n order_datas = prescription_datas\n elif order_q1.children:\n order_datas = Order.objects.filter(order_q1)\n else:\n prescription_datas = Prescription.objects.filter(order_q2)\n count = prescription_datas.count()\n if count:\n for num in range(count):\n order_id = prescription_datas[num].order_id.order_id\n order_q3.children.append(('order_id', order_id))\n order_datas = Order.objects.filter(order_q3 & Q(order_status=5))\n else:\n order_datas = prescription_datas\n data_count += order_datas.count()\n lis = list(order_datas.values())\n else:\n order_datas = Order.objects.filter(Q(order_status=5))\n data_count += order_datas.count()\n lis = list(order_datas.values())\n for i in range(len(lis)):\n prescript = order_datas[i].prescription_set.all() # 外键反向查询\n lis[i]['prescri_id'] = prescript.values('prescri_id')[0]['prescri_id']\n lis[i]['prescri_type'] = prescript.values('prescri_type')[0]['prescri_type']\n lis[i]['is_suffering'] = prescript.values('is_suffering')[0]['is_suffering']\n lis[i]['user_name'] = prescript.values('user_name')[0]['user_name']\n lis[i]['source_id'] = order_datas[i].source_id.company_name\n elif type == 'orderInitial_table':\n order_q1 = Q()\n order_q2 = Q()\n order_q3 = Q()\n order_q1.connector = 'AND'\n order_q2.connector = 'AND'\n order_q3.connector = 'OR'\n source_id = request.GET.get('sourceId')\n key_words = request.GET.get('keyWords')\n start_date = request.GET.get('startDate')\n end_date = request.GET.get('endDate')\n if source_id:\n order_q1.children.append(('source_id', source_id))\n if key_words:\n if bool(re.search(r'\\d', key_words)):\n order_q1.children.append(('order_id', key_words))\n else:\n order_q2.children.append(('user_name', key_words))\n if start_date and end_date:\n order_q1.children.append(('order_time__range', (start_date, end_date)))\n if order_q1.children or order_q2.children:\n if order_q2.children and order_q1.children:\n prescription_datas = Prescription.objects.filter(order_q2)\n # print(prescription_datas)\n count = prescription_datas.count()\n # print(count)\n if count:\n for num in range(count):\n order_id = prescription_datas[num].order_id.order_id\n order_q3.children.append(('order_id', order_id))\n order_datas = Order.objects.filter(order_q1 & order_q3)\n else:\n order_datas = prescription_datas\n elif order_q1.children:\n order_datas = Order.objects.filter(order_q1)\n else:\n prescription_datas = Prescription.objects.filter(order_q2)\n count = prescription_datas.count()\n if count:\n for num in range(count):\n order_id = prescription_datas[num].order_id.order_id\n order_q3.children.append(('order_id', order_id))\n order_datas = Order.objects.filter(order_q3)\n else:\n order_datas = prescription_datas\n data_count += order_datas.count()\n lis = list(order_datas.values())\n else:\n order_datas = Order.objects.all()\n data_count += order_datas.count()\n lis = list(order_datas.values())\n for i in range(len(lis)):\n prescript = order_datas[i].prescription_set.all() # 外键反向查询\n lis[i]['prescri_id'] = prescript.values('prescri_id')[0]['prescri_id']\n lis[i]['user_name'] = prescript.values('user_name')[0]['user_name']\n lis[i]['source_id'] = order_datas[i].source_id.company_name\n elif type == 'prescriptionAdjust_table':\n order_q1 = Q()\n order_q2 = Q()\n order_q3 = Q()\n order_q1.connector = 'AND'\n order_q2.connector = 'AND'\n order_q3.connector = 'OR'\n source_id = request.GET.get('sourceId')\n prescri_type = request.GET.get('prescrType')\n print_status = request.GET.get('printStatus')\n batch = request.GET.get('batch')\n is_hos = request.GET.get('isHos')\n is_hosaddr = request.GET.get('isHosAddr')\n taking_method = request.GET.get('takingMethod')\n # print(taking_method)\n prescri_id = request.GET.get('prescriId')\n if source_id:\n order_q1.children.append(('source_id', source_id))\n if is_hosaddr:\n order_q1.children.append(('is_hos_addr', is_hosaddr))\n if print_status:\n order_q2.children.append(('print_type', print_status))\n if is_hos:\n order_q2.children.append(('is_hos', is_hos))\n if prescri_type:\n order_q2.children.append(('prescri_type', prescri_type))\n if batch:\n order_q1.children.append(('batch', batch))\n if taking_method:\n order_q2.children.append(('is_within', taking_method))\n if prescri_id:\n order_q2.children.append(('prescri_id', prescri_id))\n # print(order_q1.children)\n # print(order_q2.children)\n if order_q1.children or order_q2.children:\n if order_q2.children and order_q1.children:\n prescription_datas = Prescription.objects.filter(order_q2)\n count = prescription_datas.count()\n if count:\n for num in range(count):\n order_id = prescription_datas[num].order_id.order_id\n order_q3.children.append(('order_id', order_id))\n order_datas = Order.objects.filter(order_q1 & order_q3 & Q(order_status=15))\n else:\n order_datas = prescription_datas\n elif order_q1.children:\n order_datas = Order.objects.filter(order_q1 & Q(order_status=15))\n else:\n prescription_datas = Prescription.objects.filter(order_q2)\n count = prescription_datas.count()\n if count:\n for num in range(count):\n order_id = prescription_datas[num].order_id.order_id\n order_q3.children.append(('order_id', order_id))\n order_datas = Order.objects.filter(order_q3 & Q(order_status=15))\n else:\n order_datas = prescription_datas\n data_count += order_datas.count()\n lis = list(order_datas.values())\n else:\n order_datas = Order.objects.filter(Q(order_status=15))\n data_count += order_datas.count()\n lis = list(order_datas.values())\n for i in range(len(lis)):\n prescript = order_datas[i].prescription_set.all() # 外键反向查询\n lis[i]['prescri_id'] = prescript.values('prescri_id')[0]['prescri_id']\n lis[i]['prescri_type'] = prescript.values('prescri_type')[0]['prescri_type']\n lis[i]['is_suffering'] = prescript.values('is_suffering')[0]['is_suffering']\n lis[i]['user_name'] = prescript.values('user_name')[0]['user_name']\n lis[i]['is_within'] = prescript.values('is_within')[0]['is_within']\n lis[i]['print_type'] = prescript.values('print_type')[0]['print_type']\n lis[i]['adjust_num'] = prescript.values('adjust_num')[0]['adjust_num']\n lis[i]['source_id'] = order_datas[i].source_id.company_name\n page_index = request.GET.get('page') # 前台传的值,\n page_size = request.GET.get('limit') # 前台传的值\n paginator = Paginator(lis, page_size) # 导入分页模块分页操作,不写前端只展示一页数据,\n contacts = paginator.page(page_index) # 导入分页模块分页操作,不写前端只展示一页数据,\n res = []\n for contact in contacts:\n res.append(contact)\n result = {\"code\": 0, \"msg\": \"\", \"count\": data_count, \"data\": res}\n # print(result)\n return HttpResponse(json.dumps(result, cls=DateEncoder, ensure_ascii=False), content_type=\"application/json\")\n\n\n@csrf_exempt\ndef user_manage(request, type):\n if type == 'userAdd':\n context = {}\n if request.method == 'POST':\n user = User()\n user.username = request.POST.get('username')\n # user.password = md5(request.POST.get('password').encode('utf-8')).hexdigest()\n user.password = request.POST.get('password')\n user.name = request.POST.get('uname')\n user.department = request.POST.get('department')\n role = Role.objects.get(id=request.POST.get('role'))\n try:\n user.save()\n user.role.add(role)\n context['status'] = 'success'\n except Exception as e:\n context['status'] = 'fail'\n context['message'] = str(e)\n logger.error(e)\n logger.info(context)\n return HttpResponse(json.dumps(context, ensure_ascii=False), content_type=\"application/json\")\n return render(request, 'backstage/systemManage/user/user_add.html')\n if type == 'userEdit':\n context = {}\n if request.method == 'POST':\n user = User.objects.get(username=request.POST.get('username'))\n user.name = request.POST.get('uname')\n user.department = request.POST.get('department')\n user.work_num = request.POST.get('worknum')\n role = Role.objects.get(id=request.POST.get('role'))\n user.role.add(role)\n try:\n user.save()\n context['status'] = 'success'\n except Exception as e:\n logger.error(e)\n context['status'] = 'fail'\n context['message'] = str(e)\n logger.info(context)\n return HttpResponse(json.dumps(context, ensure_ascii=False), content_type=\"application/json\")\n user = User.objects.get(id=request.GET.get('userId'))\n role_id = list(user.role.all().values('id'))[0]['id']\n return render(request, 'backstage/systemManage/user/user_edit.html', locals())\n if type == 'userDelete':\n context = {}\n # print(request.POST)\n dele_datas = string_to_list(request.POST.get('delData'))\n # print(dele_datas)\n for data in dele_datas:\n try:\n User.objects.get(username=data).delete()\n context['status'] = 'success'\n context['message'] = '成功删除%s条数据' % len(dele_datas)\n except Exception as e:\n context['status'] = 'fail'\n context['message'] = str(e)\n logger.error(e)\n return HttpResponse(json.dumps(context, ensure_ascii=False), content_type=\"application/json\")\n if type == 'updateStatus':\n context = {}\n user = User.objects.get(username=request.POST.get('username'))\n status = request.POST.get('status')\n if int(status) > 0:\n user.is_disabled = 0\n else:\n user.is_disabled = 1\n try:\n user.save()\n context['status'] = 'success'\n except Exception as e:\n logger.error(e)\n context['status'] = 'fail'\n context['message'] = str(e)\n return HttpResponse(json.dumps(context, ensure_ascii=False), content_type=\"application/json\")\n if type == 'home':\n return render(request, 'backstage/systemManage/user/user_manage.html')\n\n\n@csrf_exempt\ndef update_pass(request):\n context = {}\n if request.method == 'POST':\n user = User.objects.get(name=request.POST.get('uName'))\n # print(user.password)\n # print(request.POST.get('prePassword'))\n if user.password == request.POST.get('prePassword'):\n user.password = request.POST.get('newPassword')\n try:\n user.save()\n context['status'] = 'success'\n except Exception as e:\n context['status'] = 'fail'\n context['message'] = str(e)\n else:\n context['status'] = 'fail'\n context['message'] = '原密码不正确!'\n return HttpResponse(json.dumps(context, ensure_ascii=False), content_type=\"application/json\")\n return render(request, 'backstage/systemManage/user/update_pass.html')\n\n\n@csrf_exempt\ndef role_manage(request, type):\n if type == 'roleAdd':\n context = {}\n if request.method == 'POST':\n role = Role()\n # print(request.POST.get('rolename'))\n role.role_name = request.POST.get('rolename')\n try:\n role.save()\n context['status'] = 'success'\n except Exception as e:\n context['status'] = 'fail'\n context['message'] = str(e)\n return HttpResponse(json.dumps(context, ensure_ascii=False), content_type=\"application/json\")\n return render(request, 'backstage/systemManage/user/role_add.html')\n if type == 'roleEdit':\n context = {}\n if request.method == 'POST':\n role = Role.objects.get(id=request.POST.get('roleid'))\n role.role_name = request.POST.get('rolename')\n try:\n role.save()\n context['status'] = 'success'\n except Exception as e:\n context['status'] = 'fail'\n context['message'] = str(e)\n return HttpResponse(json.dumps(context, ensure_ascii=False), content_type=\"application/json\")\n return render(request, 'backstage/systemManage/user/role_edit.html')\n if type == 'roleDelete':\n context = {}\n try:\n Role.objects.get(id=request.POST.get('delData')).delete()\n context['status'] = 'success'\n except Exception as e:\n context['status'] = 'fail'\n context['message'] = str(e)\n return HttpResponse(json.dumps(context, ensure_ascii=False), content_type=\"application/json\")\n if type == 'menuData':\n menu_datalist = list(Menu.objects.all().values())\n # print(menu_datalist)\n # print(len(menu_datalist))\n menu_data = []\n parent_id = []\n for num in range(len(menu_datalist)):\n # print(menu_datalist[num]['parent_id'])\n if menu_datalist[num]['parent_id'] == None:\n del menu_datalist[num]['icon']\n del menu_datalist[num]['parent_id']\n menu_datalist[num]['children'] = []\n menu_data.append(menu_datalist[num])\n parent_id.append(menu_datalist[num]['id'])\n # print(menu_data)\n # print(parent_id)\n else:\n for n in range(len(parent_id)):\n if menu_datalist[num]['parent_id'] == parent_id[n]:\n del menu_datalist[num]['icon']\n del menu_datalist[num]['parent_id']\n menu_data[n]['children'].append(menu_datalist[num])\n break\n else:\n continue\n context = {'menuData': menu_data}\n role = Role.objects.get(id=request.GET.get('roleId'))\n permissions = list(role.permissions.all().values())\n # print(permissions)\n menu_ids = []\n if permissions:\n for num in range(len(permissions)):\n menu_id = Menu.objects.get(title=permissions[num]['title']).id\n menu_ids.append(menu_id)\n context['checkedId'] = menu_ids\n return HttpResponse(json.dumps(context, ensure_ascii=False), content_type=\"application/json\")\n if type == 'authorize':\n context = {}\n if request.method == 'POST':\n role = Role.objects.get(id=request.POST.get('roleId'))\n role.permissions.clear()\n auth_data = json.loads(request.POST.get('data'))\n for num in range(len(auth_data)):\n for n in range(len(auth_data[num]['children'])):\n title = auth_data[num]['children'][n]['title']\n auth = Permission.objects.filter(title=title).first()\n if auth:\n role.permissions.add(auth)\n context['status'] = 'success'\n else:\n au = Permission()\n url = ''\n per_id = ''\n if title == '订单审核':\n url += \"/management/orderAudit/home\"\n per_id += 'order_audit'\n elif title == '处方查询':\n url += \"/management/prescriptionQuery/home\"\n per_id += 'prescri_query'\n elif title == '订单初始化':\n url += \"/management/orderInitial/home\"\n per_id += 'order_initial'\n elif title == '处方调剂':\n url += \"/management/Adjust/home\"\n per_id += 'prescription_adjust'\n elif title == '商品管理':\n url += \"/management/goodsManage/home\"\n per_id += 'goods_manage'\n elif title == '商品详情管理':\n url += \"/management/goodsDetailsManage/home\"\n per_id += 'goods_details_manage'\n elif title == '品牌管理':\n url += \"\"\n per_id += 'brand_manage'\n elif title == '分类管理':\n url += \"\"\n per_id += 'category_manage'\n elif title == '菜单管理':\n url += \"/management/menuManage/home/\"\n per_id += 'menu_manage'\n elif title == '用户管理':\n url += \"/management/userManage/home/\"\n per_id += 'user_manage'\n elif title == '角色管理':\n url += \"/management/roleManage/home/\"\n per_id += 'role_manage'\n elif title == '处方重打':\n url += \"/management/Adjust/rePrintPrescription/\"\n per_id += 're_print_prescription'\n elif title == '煎煮中心管理':\n url += \"/management/decoctionCenterManage/home/\"\n per_id += 'decoction_center_manage'\n elif title == '机构来源管理':\n url += \"/management/companyManage/home\"\n per_id += 'company_manage'\n au.title = title\n au.url = url\n au.per_id = per_id\n au.menu = Menu.objects.get(id=auth_data[num]['id'])\n try:\n au.save()\n role.permissions.add(au)\n context['status'] = 'success'\n except Exception as e:\n context['status'] = 'fail'\n context['message'] = str(e)\n print(context)\n return HttpResponse(json.dumps(context, ensure_ascii=False), content_type=\"application/json\")\n return render(request, 'backstage/systemManage/user/role_authorize.html')\n if type == 'home':\n return render(request, 'backstage/systemManage/user/role_manage.html')\n\n\ndef get_role(request):\n roles = Role.objects.all()\n json_roles = serializers.serialize('json', roles)\n return HttpResponse(json_roles)\n\n\n@csrf_exempt\ndef goods_manage(request, type):\n if type == 'addGoods':\n context = {}\n if request.method == 'POST':\n goods = Goods()\n keys = []\n values = []\n # print(request.POST)\n # print(request.POST.get('goodsCode'))\n alias = json.loads(request.POST.get('alias'))\n # print(alias)\n for key_value in alias.items():\n keys.append(key_value[0])\n values.append(key_value[1])\n # print(keys)\n # print(values)\n goods.goods_code = request.POST.get('goodsCode')\n goods.goods_name = request.POST.get('goodsName')\n goods.english_name = request.POST.get('englishName')\n goods.chinese_name = request.POST.get('chineseName')\n goods.unit = request.POST.get('unit')\n goods.short_code = request.POST.get('shortCode')\n goods.price = Decimal(request.POST.get('price')).quantize(Decimal('0.000'))\n if 'alias1' in keys:\n goods.alias1 = values[keys.index('alias1')]\n if 'alias2' in keys:\n goods.alias2 = values[keys.index('alias2')]\n if 'alias3' in keys:\n goods.alias3 = values[keys.index('alias3')]\n if 'alias4' in keys:\n goods.alias4 = values[keys.index('alias4')]\n if 'alias5' in keys:\n goods.alias5 = values[keys.index('alias5')]\n if 'alias6' in keys:\n goods.alias6 = values[keys.index('alias6')]\n if 'alias7' in keys:\n goods.alias7 = values[keys.index('alias7')]\n if 'alias8' in keys:\n goods.alias8 = values[keys.index('alias8')]\n if 'alias9' in keys:\n goods.alias9 = values[keys.index('alias9')]\n if 'alias10' in keys:\n goods.alias10 = values[keys.index('alias10')]\n try:\n goods.save()\n context['status'] = 'success'\n except Exception as e:\n context['status'] = 'fail'\n context['message'] = str(e)\n print(context)\n return HttpResponse(json.dumps(context, ensure_ascii=False), content_type=\"application/json\")\n return render(request, 'backstage/goods/add_goods.html')\n if type == 'goodsBatchImport':\n context = {}\n if request.method == 'POST':\n file = request.FILES['file']\n file_name = '%s/%s' % (settings.MEDIA_ROOT, file.name)\n # print(file_name)\n try:\n with open(file_name, 'wb') as f:\n for f_file in file.chunks():\n f.write(f_file)\n context['status'] = 'success'\n df = pd.read_excel(file_name)\n # print(df)\n drugs = []\n count_control = 0\n for num in range(len(df)):\n drug = Goods(goods_code=df.loc[num]['商品编号'], goods_name=df.loc[num]['药材名'],\n short_code=df.loc[num]['代码'], chinese_name=df.loc[num]['中文名'],\n price=df.loc[num]['单价'], unit=df.loc[num]['单位'],\n oper_id=User.objects.get(username=request.session['username']).id)\n if not pd.isna(df.loc[num]['英文名']):\n drug.english_name = df.loc[num]['英文名']\n if not pd.isna(df.loc[num]['库存']):\n drug.stock = df.loc[num]['库存']\n if df.loc[num]['是否停用'] != '否' or df.loc[num]['是否停用'] != '已停用':\n drug.status = 1\n else:\n drug.status = 0\n if not pd.isna(df.loc[num]['商品规格']):\n drug.goods_norms = df.loc[num]['商品规格']\n if not pd.isna(df.loc[num]['商品产地']):\n drug.goods_orgin = df.loc[num]['商品产地']\n if df.loc[num]['商品(药材)类型'] == '中药':\n drug.goods_type = 0\n else:\n drug.goods_type = 1\n if not pd.isna(df.loc[num]['别名1']):\n drug.alias1 = df.loc[num]['别名1']\n if not pd.isna(df.loc[num]['别名2']):\n drug.alias2 = df.loc[num]['别名2']\n if not pd.isna(df.loc[num]['别名3']):\n drug.alias3 = df.loc[num]['别名3']\n if not pd.isna(df.loc[num]['别名4']):\n drug.alias4 = df.loc[num]['别名4']\n if not pd.isna(df.loc[num]['别名5']):\n drug.alias5 = df.loc[num]['别名5']\n if not pd.isna(df.loc[num]['别名6']):\n drug.alias6 = df.loc[num]['别名6']\n if not pd.isna(df.loc[num]['别名7']):\n drug.alias7 = df.loc[num]['别名7']\n if not pd.isna(df.loc[num]['别名8']):\n drug.alias8 = df.loc[num]['别名8']\n if not pd.isna(df.loc[num]['别名9']):\n drug.alias9 = df.loc[num]['别名9']\n if not pd.isna(df.loc[num]['别名10']):\n drug.alias10 = df.loc[num]['别名10']\n count_control += 1\n drugs.append(drug)\n if count_control >= 100: # 每100条数据执行一次插入\n Goods.objects.bulk_create(drugs)\n count_control = 0 # 计数归0\n drugs.clear() # 清空列表\n Goods.objects.bulk_create(drugs)\n context['message'] = '导入成功'\n except Exception as e:\n context['status'] = 'false'\n context['message'] = str(e)\n print(context)\n return HttpResponse(json.dumps(context, ensure_ascii=False), content_type=\"application/json\")\n return render(request, 'backstage/goods/BatchImportGoods.html')\n if type == 'editGoods':\n context = {}\n if request.method == 'POST':\n alias = json.loads(request.POST.get('alias'))\n goods = Goods.objects.get(goods_code=request.POST.get('goodsCode'))\n goods.alias1 = alias['alias1']\n goods.alias2 = alias['alias2']\n goods.alias3 = alias['alias3']\n goods.alias4 = alias['alias4']\n goods.alias5 = alias['alias5']\n goods.alias6 = alias['alias6']\n goods.alias7 = alias['alias7']\n goods.alias8 = alias['alias8']\n goods.alias9 = alias['alias9']\n goods.alias10 = alias['alias10']\n goods.unit = request.POST.get('unit')\n goods.stock = request.POST.get('stock')\n goods.price = request.POST.get('price')\n goods.short_code = request.POST.get('shortCode')\n try:\n goods.save()\n context['status'] = 'success'\n except Exception as e:\n context['status'] = 'fail'\n context['message'] = str(e)\n print(context)\n return HttpResponse(json.dumps(context, ensure_ascii=False), content_type=\"application/json\")\n goods_code = request.GET.get('goods_code')\n # print(goods_code)\n goods = Goods.objects.get(goods_code=goods_code)\n return render(request, 'backstage/goods/edit_goods.html', locals())\n if type == 'updateStatus':\n context = {}\n status = request.GET.get('status')\n # print(status)\n if status:\n goods = Goods.objects.get(goods_code=request.GET.get('goodsCode'))\n if int(status) > 0:\n goods.status = 0\n else:\n goods.status = 1\n try:\n goods.save()\n context['status'] = 'success'\n except Exception as e:\n context['status'] = 'fail'\n context['message'] = str(e)\n print(context)\n return HttpResponse(json.dumps(context, ensure_ascii=False), content_type=\"application/json\")\n if type == 'home':\n return render(request, 'backstage/goods/goods_manage.html')\n\n\n@csrf_exempt\ndef goods_details_manage(request, type):\n if type == 'addGoodsDetails':\n context = {}\n if request.method == 'POST':\n goods_code = request.POST.get('goodsCode')\n goods_name = request.POST.get('goodsName')\n property = request.POST.get('property')\n channels = request.POST.get('channels')\n action = request.POST.get('action')\n usage_dosage = request.POST.get('usageDosage')\n precaution = request.POST.get('precaution')\n print('goodcode:%s\\ngoodsname:%s\\nproperty:%s\\nchannels:%s\\naction:%s\\nusageDosage:%s\\nprecaution:%s\\s' %\n (goods_code, goods_name, property, channels, action, usage_dosage, precaution))\n details = GoodsDetails()\n details.goods_code = goods_code\n details.goods_name = goods_name\n details.property = property\n details.channels = channels\n details.actions = action\n details.usage_dosage = usage_dosage\n details.precaution = precaution\n try:\n details.save()\n context['status'] = 'success'\n except Exception as e:\n context['status'] = 'fail'\n context['message'] = str(e)\n print(context)\n return HttpResponse(json.dumps(context, ensure_ascii=False), content_type=\"application/json\")\n return render(request, 'backstage/goods/add_goods_details.html')\n if type == 'detailBatchImport':\n return render(request, 'backstage/goods/BatchImportDetails.html')\n if type == 'home':\n return render(request, 'backstage/goods/goods_details_manage.html')\n\n\n@csrf_exempt\ndef decoction_center_manage(request, type):\n context = {}\n if type == 'add':\n if request.method == 'POST':\n # print('name:%s\\nnote:%s\\nprovince:%s\\ncity:%s\\nzone:%s\\naddress:%s' %\n # (request.POST.get('name'), request.POST.get('note'), request.POST.get('province'),\n # request.POST.get('city'), request.POST.get('zone'), request.POST.get('address')))\n exist_center = DecoctCenter.objects.all()\n center = DecoctCenter()\n center.name = request.POST.get('name')\n center.note = request.POST.get('note')\n center.province = request.POST.get('province')\n center.city = request.POST.get('city')\n center.zone = request.POST.get('zone')\n center.address = request.POST.get('address')\n if exist_center:\n pass\n else:\n center.code = '10000'\n try:\n center.save()\n context['status'] = 'success'\n except Exception as e:\n context['status'] = 'fail'\n context['message'] = str(e)\n print(context)\n return HttpResponse(json.dumps(context, ensure_ascii=False), content_type=\"application/json\")\n return render(request, 'backstage/systemManage/decoctionCenter/decoct_center_add.html')\n if type == 'updateStatus':\n status = request.GET.get('status')\n center = DecoctCenter.objects.get(code=request.GET.get('Code'))\n if int(status) > 0:\n center.status = 0\n else:\n center.status = 1\n try:\n center.save()\n context['status'] = 'success'\n except Exception as e:\n context['status'] = 'fail'\n context['message'] = str(e)\n print(context)\n return HttpResponse(json.dumps(context, ensure_ascii=False), content_type=\"application/json\")\n if type == 'home':\n return render(request, 'backstage/systemManage/decoctionCenter/decoction_center_manage.html')\n\n\n@csrf_exempt\ndef company_manage(request, type):\n context = {}\n if type == 'storagetype':\n centers = DecoctCenter.objects.all()\n json_roles = serializers.serialize('json', centers)\n return HttpResponse(json_roles)\n if type == 'add':\n if request.method == 'POST':\n exist_company = Institution.objects.all()\n company = Institution()\n company.company_name = request.POST.get('companyName')\n company.company_pass = md5(request.POST.get('companyPass').encode('utf-8')).hexdigest()\n storage_code = DecoctCenter.objects.get(code=request.POST.get('storageType'))\n company.storage_type = storage_code\n company.ascription = request.POST.get('ascription')\n company.short_name = request.POST.get('shortName')\n company.salesman = request.POST.get('salesMan')\n company.sales_tel = request.POST.get('salesTel')\n company.his_abutment = request.POST.get('hisAbutment')\n company.his_abutment_tel = request.POST.get('hisAbutmentTel')\n company.his_grade = request.POST.get('hisGrade')\n company.company_type = request.POST.get('companyType')\n company.is_doc_outh = request.POST.get('isDocOuth')\n company.is_send_msg = request.POST.get('isSendMsg')\n company.his_addr = request.POST.get('hosAddr')\n company.default_consignee = request.POST.get('defaultConsignee')\n company.distribution_description = request.POST.get('distributionDescription')\n company.default_tel = request.POST.get('defaultTel')\n company.defalut_addr = request.POST.get('defaultAddr')\n current_user = request.session['username']\n company.oper_id = User.objects.get(username=current_user)\n if exist_company:\n pass\n else:\n company.company_num = '10000'\n try:\n company.save()\n context['status'] = 'success'\n except Exception as e:\n context['status'] = 'fail'\n context['message'] = str(e)\n print(context)\n return HttpResponse(json.dumps(context, ensure_ascii=False), content_type=\"application/json\")\n return render(request, 'backstage/systemManage/company/add_company.html')\n if type == 'updateStatus':\n status = request.GET.get('status')\n company = Institution.objects.get(company_num=request.GET.get('companyNum'))\n if int(status) > 0:\n company.status = 0\n else:\n company.status = 1\n try:\n company.save()\n context['status'] = 'success'\n except Exception as e:\n context['status'] = 'fail'\n context['message'] = str(e)\n print(context)\n return HttpResponse(json.dumps(context, ensure_ascii=False), content_type=\"application/json\")\n if type == 'edit':\n if request.method == 'POST':\n company = Institution.objects.get(company_num=request.POST.get('companyNum'))\n company.company_name = request.POST.get('companyName')\n storage_code = DecoctCenter.objects.get(code=request.POST.get('storageType'))\n company.storage_type = storage_code\n company.ascription = request.POST.get('ascription')\n company.short_name = request.POST.get('shortName')\n company.salesman = request.POST.get('salesMan')\n company.sales_tel = request.POST.get('salesTel')\n company.his_abutment = request.POST.get('hisAbutment')\n company.his_abutment_tel = request.POST.get('hisAbutmentTel')\n company.his_grade = request.POST.get('hisGrade')\n company.company_type = request.POST.get('companyType')\n company.is_doc_outh = request.POST.get('isDocOuth')\n company.is_send_msg = request.POST.get('isSendMsg')\n company.his_addr = request.POST.get('hosAddr')\n company.default_consignee = request.POST.get('defaultConsignee')\n company.distribution_description = request.POST.get('distributionDescription')\n company.default_tel = request.POST.get('defaultTel')\n company.defalut_addr = request.POST.get('defaultAddr')\n current_user = request.session['username']\n company.oper_id = User.objects.get(username=current_user)\n company.defalut_djdj = request.POST.get('defalutDjdj')\n try:\n company.save()\n context['status'] = 'success'\n except Exception as e:\n context['status'] = 'fail'\n context['message'] = str(e)\n print(context)\n return HttpResponse(json.dumps(context, ensure_ascii=False), content_type=\"application/json\")\n company_num = request.GET.get('company_num')\n company = Institution.objects.get(company_num=company_num)\n return render(request, 'backstage/systemManage/company/edit_company.html', locals())\n if type == 'home':\n return render(request, 'backstage/systemManage/company/company_manage.html')\n\n\ndef prescription_query(request, type):\n if type == 'sourceId':\n sources = Institution.objects.all()\n json_sources = serializers.serialize('json', sources)\n return HttpResponse(json_sources)\n if type == 'pdDetail':\n pres_num = request.GET.get('prescri_id')\n pres_info = Prescription.objects.get(prescri_id=pres_num)\n suffering_unit_price = Decimal(pres_info.order_id.source_id.defalut_djdj).quantize(Decimal('0.00'))\n suffering_price = Decimal(int(pres_info.suffering_num) * suffering_unit_price).quantize(Decimal('0.00'))\n return render(request, 'backstage/customerServiceCenter/prescriptionDetail.html', locals())\n if type == 'home':\n return render(request, 'backstage/customerServiceCenter/prescriptionQuery.html')\n\n\n@csrf_exempt\ndef order_audit(request, type):\n if type == 'addRemark':\n context = {}\n if request.method == 'POST':\n order_id = request.POST.get('orderId')\n order_remark = request.POST.get('remark')\n order = Order.objects.get(order_id=order_id)\n order.order_remark = order_remark\n try:\n order.save()\n context['status'] = 'success'\n except Exception as e:\n context['status'] = 'fail'\n context['message'] = str(e)\n print(context)\n return HttpResponse(json.dumps(context, ensure_ascii=False), content_type=\"application/json\")\n order_id = request.GET.get('orderId')\n return render(request, 'backstage/customerServiceCenter/addRemark.html', locals())\n if type == 'auditPrescriptionInfo':\n prescri_id = request.GET.get('prescri_id')\n auto_audit_result = []\n drugs = PresDetails.objects.filter(prescri_id=prescri_id).values('medicines', 'dose', 'm_usage')\n reverse_18_and_fear_19 = reverse_18(*drugs) + fear_19(*drugs) + usage_match(*drugs) + poisonous_and_dose_match(*drugs)\n if reverse_18_and_fear_19:\n auto_audit_result = reverse_18_and_fear_19\n else:\n auto_audit_result.append('处方自动审核正常!')\n prescri_info = Prescription.objects.get(prescri_id=prescri_id)\n total_result = ''\n for result in auto_audit_result:\n total_result += result + '|'\n prescri_info.audit_result = total_result\n prescri_info.save()\n suffering_unit_price = Decimal(prescri_info.order_id.source_id.defalut_djdj).quantize(Decimal('0.00'))\n suffering_price = Decimal(int(prescri_info.suffering_num) * suffering_unit_price).quantize(Decimal('0.00'))\n return render(request, 'backstage/customerServiceCenter/audit_prescription_info.html', locals())\n if type == 'giveUpOrder':\n context = {}\n if request.method == 'POST':\n order_id = request.POST.get('orderId')\n give_up_reason = request.POST.get('giveUpReason')\n print(order_id)\n print(give_up_reason)\n order = Order.objects.get(order_id=order_id)\n order.order_status = 98\n order.reason = give_up_reason\n try:\n order.save()\n context['status'] = 'success'\n except Exception as e:\n context['status'] = 'fail'\n context['message'] = str(e)\n print(context)\n return HttpResponse(json.dumps(context, ensure_ascii=False), content_type=\"application/json\")\n return render(request, 'backstage/customerServiceCenter/give_up_order.html')\n if type == 'changeCenter':\n context = {}\n if request.method == 'POST':\n order_id = request.POST.get('orderId')\n change_reason = request.POST.get('changeReason')\n storage_type = request.POST.get('storageType')\n print(order_id)\n print(change_reason)\n print(storage_type)\n order = Order.objects.get(order_id=order_id)\n # order.storage_type = DecoctCenter.objects.get(code=storage_type)\n order.storage_type_id = storage_type\n order.reason = change_reason\n try:\n order.save()\n context['status'] = 'success'\n except Exception as e:\n context['status'] = 'fail'\n context['message'] = str(e)\n print(context)\n return HttpResponse(json.dumps(context, ensure_ascii=False), content_type=\"application/json\")\n return render(request, 'backstage/customerServiceCenter/change_center.html')\n if type == 'auditOrder':\n context = {}\n order_id = request.GET.get('orderId')\n batch_num = request.GET.get('batchNum')\n order = Order.objects.get(order_id=order_id)\n order.batch = batch_num\n order.audit_id = User.objects.get(username=request.session['username']).id\n order.order_status = 15\n try:\n order.save()\n context['status'] = 'success'\n except Exception as e:\n context['status'] = 'fail'\n context['message'] = str(e)\n print(context)\n return HttpResponse(json.dumps(context, ensure_ascii=False), content_type=\"application/json\")\n if type == 'home':\n return render(request, 'backstage/customerServiceCenter/orderAudit.html')\n\n\ndef order_initial(request, type):\n if type == 'initialStatus':\n order_id = request.GET.get('order_id')\n return render(request, 'backstage/customerServiceCenter/initial.html', locals())\n if type == 'initial':\n context = {}\n order_id = request.GET.get('orderId')\n order = Order.objects.get(order_id=order_id)\n prescription = Prescription.objects.get(order_id=order_id)\n order.order_status = 5\n order.audit_id = None\n order.batch = None\n order.order_remark = ''\n order.adjust_id = None\n order.reason = ''\n prescription.adjust_num = ''\n prescription.print_type = 0\n try:\n order.save()\n prescription.save()\n context['status'] = 'success'\n except Exception as e:\n context['status'] = 'fail'\n context['message'] = str(e)\n print(context)\n return HttpResponse(json.dumps(context, ensure_ascii=False), content_type=\"application/json\")\n if type == 'home':\n return render(request, 'backstage/customerServiceCenter/orderInitial.html')\n\n\ndef prescription_adjust(request, type):\n if type == 'print':\n if not request.GET.get('order_id'):\n context = {}\n work_num = request.GET.get('workNum')\n user = User.objects.filter(work_num=work_num).first()\n if user and user.username == request.session['username']:\n context['status'] = 'success'\n else:\n context['status'] = 'fail'\n context['message'] = '工号错误,请核对!'\n print(context)\n return HttpResponse(json.dumps(context, ensure_ascii=False), content_type=\"application/json\")\n else:\n order_id = request.GET.get('order_id')\n prescription_id = request.GET.get('prescri_id')\n work_num = request.GET.get('workNum')\n order = Order.objects.get(order_id=order_id)\n prescription = Prescription.objects.get(prescri_id=prescription_id)\n order.adjust_id = User.objects.get(work_num=work_num).id\n prescription.print_type = 1\n prescription.adjust_num = work_num\n order.save()\n prescription.save()\n return render(request, 'backstage/adjustCenter/print_model.html', locals())\n if type == 'drugs':\n prescription_id = request.GET.get('prescriId')\n prescri_detail = list(PresDetails.objects.filter(prescri_id=prescription_id).values('medicines', 'dose', 'unit',\n 'm_usage', 'prescri_id__amount'))\n # print(prescri_detail)\n return HttpResponse(json.dumps(prescri_detail, ensure_ascii=False), content_type=\"application/json\")\n if type == 'barcode':\n prescription_id = request.GET.get('prescriId')\n # print(prescription_id)\n code = generateBarcode(prescription_id)\n fp = BytesIO()\n # code.render(fp)\n code.write(fp, {'module_width': 0.5, 'module_height': 25, 'quiet_zone': 3, 'font_size': 45, 'text_distance': 3,\n 'dpi': 400})\n return HttpResponse(fp.getvalue(), content_type='image/png')\n if type == 'rePrintPrescription':\n pres_id = request.GET.get('presId')\n prescri_id = request.GET.get('prescri_id')\n if pres_id:\n context = {}\n prescription = Prescription.objects.filter(prescri_id=pres_id)\n if prescription.count() > 0:\n context['status'] = 'yes'\n else:\n context['status'] = 'no'\n return HttpResponse(json.dumps(context, ensure_ascii=False), content_type=\"application/json\")\n if prescri_id:\n print(prescri_id)\n order_id = prescri_id.split('-')[0]\n print(order_id)\n order = Order.objects.get(order_id=order_id)\n prescription = Prescription.objects.get(prescri_id=prescri_id)\n return render(request, 'backstage/adjustCenter/print_model.html', locals())\n return render(request, 'backstage/adjustCenter/re_print_prescription.html')\n if type == 'home':\n return render(request, 'backstage/adjustCenter/prescription_adjust.html')\n\n\n@csrf_exempt\ndef menu_manage(request, type):\n if type == 'menuAdd':\n context = {}\n if request.method == 'POST':\n menu = Menu()\n menu.title = request.POST.get('menuname')\n menu.icon = request.POST.get('menuicon')\n menu.menu_type = request.POST.get('menutype')\n menu.parent_id = request.POST.get('parentMenu')\n try:\n menu.save()\n context['status'] = 'success'\n except Exception as e:\n context['status'] = 'fail'\n context['message'] = str(e)\n print(context)\n return HttpResponse(json.dumps(context, ensure_ascii=False), content_type='application/json')\n return render(request, 'backstage/systemManage/menu/menu_add.html')\n if type == 'parentMenu':\n parent_menu = Menu.objects.exclude(parent_id__gt=1)\n json_menus = serializers.serialize('json', parent_menu)\n return HttpResponse(json_menus)\n if type == 'menuEdit':\n context = {}\n if request.method == 'POST':\n menu = Menu.objects.get(id=request.POST.get('menuid'))\n menu.title = request.POST.get('menuname')\n menu.icon = request.POST.get('menuicon')\n menu.menu_type = request.POST.get('menutype')\n menu.parent_id = request.POST.get('parentMenu')\n try:\n menu.save()\n context['status'] = 'success'\n except Exception as e:\n context['status'] = 'fail'\n context['message'] = str(e)\n print(context)\n return HttpResponse(json.dumps(context, ensure_ascii=False), content_type='application/json')\n return render(request, 'backstage/systemManage/menu/menu_add.html')\n if type == 'menuDelete':\n context = {}\n try:\n Menu.objects.get(id=request.POST.get('delData')).delete()\n context['status'] = 'success'\n except Exception as e:\n context['status'] = 'fail'\n context['message'] = str(e)\n return HttpResponse(json.dumps(context, ensure_ascii=False), content_type=\"application/json\")\n if type == 'home':\n return render(request, 'backstage/systemManage/menu/menu_manage.html')\n","sub_path":"zhyf/management/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":70905,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"522531200","text":"import logging\nimport urllib.parse\nfrom typing import List, Optional, Set, Tuple\n\n# FIXME: too many DB calls\nfrom fastapi import APIRouter, Depends, Header, HTTPException, status\nfrom models_library.services import (\n KEY_RE,\n VERSION_RE,\n ServiceAccessRightsAtDB,\n ServiceMetaDataAtDB,\n ServiceType,\n)\nfrom pydantic import ValidationError, constr\nfrom pydantic.types import PositiveInt\n\nfrom ...db.repositories.groups import GroupsRepository\nfrom ...db.repositories.services import ServicesRepository\nfrom ...models.schemas.services import ServiceOut, ServiceUpdate\nfrom ...services.frontend_services import get_services as get_frontend_services\nfrom ..dependencies.database import get_repository\nfrom ..dependencies.director import DirectorApi, get_director_api\n\nrouter = APIRouter()\nlogger = logging.getLogger(__name__)\n\n\n@router.get(\"\", response_model=List[ServiceOut])\nasync def list_services(\n # pylint: disable=too-many-arguments\n user_id: PositiveInt,\n details: Optional[bool] = True,\n director_client: DirectorApi = Depends(get_director_api),\n groups_repository: GroupsRepository = Depends(get_repository(GroupsRepository)),\n services_repo: ServicesRepository = Depends(get_repository(ServicesRepository)),\n x_simcore_products_name: str = Header(...),\n):\n # get user groups\n user_groups = await groups_repository.list_user_groups(user_id)\n if not user_groups:\n # deny access\n raise HTTPException(\n status_code=status.HTTP_403_FORBIDDEN,\n detail=\"You have unsufficient rights to access the services\",\n )\n # now get the executable services\n executable_services: Set[Tuple[str, str]] = {\n (service.key, service.version)\n for service in await services_repo.list_services(\n gids=[group.gid for group in user_groups],\n execute_access=True,\n product_name=x_simcore_products_name,\n )\n }\n # get the writable services\n _services = await services_repo.list_services(\n gids=[group.gid for group in user_groups],\n write_access=True,\n product_name=x_simcore_products_name,\n )\n writable_services: Set[Tuple[str, str]] = {\n (service.key, service.version) for service in _services\n }\n visible_services = executable_services | writable_services\n if not details:\n # only return a stripped down version\n services = [\n ServiceOut(\n key=key,\n version=version,\n name=\"nodetails\",\n description=\"nodetails\",\n type=ServiceType.computational,\n authors=[{\"name\": \"nodetails\", \"email\": \"nodetails@nodetails.com\"}],\n contact=\"nodetails@nodetails.com\",\n inputs={},\n outputs={},\n )\n for key, version in visible_services\n ]\n return services\n\n # get the services from the registry and filter them out\n frontend_services = [s.dict(by_alias=True) for s in get_frontend_services()]\n registry_services = await director_client.get(\"/services\")\n data = frontend_services + registry_services\n services: List[ServiceOut] = []\n for x in data:\n try:\n service = ServiceOut.parse_obj(x)\n\n if not (service.key, service.version) in visible_services:\n # no access to that service\n continue\n\n # we have write access for that service, fill in the service rights\n access_rights: List[\n ServiceAccessRightsAtDB\n ] = await services_repo.get_service_access_rights(\n service.key, service.version, product_name=x_simcore_products_name\n )\n service.access_rights = {rights.gid: rights for rights in access_rights}\n\n # access is allowed, override some of the values with what is in the db\n service_in_db: Optional[\n ServiceMetaDataAtDB\n ] = await services_repo.get_service(service.key, service.version)\n if not service_in_db:\n logger.error(\n \"The service %s:%s is not in the database\",\n service.key,\n service.version,\n )\n continue\n service = service.copy(\n update=service_in_db.dict(exclude_unset=True, exclude={\"owner\"})\n )\n # the owner shall be converted to an email address\n if service_in_db.owner:\n service.owner = await groups_repository.get_user_email_from_gid(\n service_in_db.owner\n )\n\n services.append(service)\n\n # services = parse_obj_as(List[ServiceOut], data) this does not work since if one service has an issue it fails\n except ValidationError as exc:\n logger.warning(\n \"skip service %s:%s that has invalid fields\\n%s\",\n x[\"key\"],\n x[\"version\"],\n exc,\n )\n\n return services\n\n\n@router.get(\"/{service_key:path}/{service_version}\", response_model=ServiceOut)\nasync def get_service(\n # pylint: disable=too-many-arguments\n user_id: int,\n service_key: constr(regex=KEY_RE),\n service_version: constr(regex=VERSION_RE),\n director_client: DirectorApi = Depends(get_director_api),\n groups_repository: GroupsRepository = Depends(get_repository(GroupsRepository)),\n services_repo: ServicesRepository = Depends(get_repository(ServicesRepository)),\n x_simcore_products_name: str = Header(None),\n):\n # check the service exists\n services_in_registry = await director_client.get(\n f\"/services/{urllib.parse.quote_plus(service_key)}/{service_version}\"\n )\n service = ServiceOut.parse_obj(services_in_registry[0])\n # the director client already raises an exception if not found\n\n # get the user groups\n user_groups = await groups_repository.list_user_groups(user_id)\n if not user_groups:\n # deny access\n raise HTTPException(\n status_code=status.HTTP_403_FORBIDDEN,\n detail=\"You have unsufficient rights to access the service\",\n )\n # check the user has access to this service and to which extent\n service_in_db = await services_repo.get_service(\n service_key,\n service_version,\n gids=[group.gid for group in user_groups],\n write_access=True,\n product_name=x_simcore_products_name,\n )\n if service_in_db:\n # we have full access, let's add the access to the output\n service_access_rights: List[\n ServiceAccessRightsAtDB\n ] = await services_repo.get_service_access_rights(\n service.key, service.version, product_name=x_simcore_products_name\n )\n service.access_rights = {rights.gid: rights for rights in service_access_rights}\n else:\n # check if we have executable rights\n service_in_db = await services_repo.get_service(\n service_key,\n service_version,\n gids=[group.gid for group in user_groups],\n execute_access=True,\n product_name=x_simcore_products_name,\n )\n if not service_in_db:\n # we have no access here\n raise HTTPException(\n status_code=status.HTTP_403_FORBIDDEN,\n detail=\"You have insufficient rights to access the service\",\n )\n # access is allowed, override some of the values with what is in the db\n service = service.copy(\n update=service_in_db.dict(exclude_unset=True, exclude={\"owner\"})\n )\n # the owner shall be converted to an email address\n if service_in_db.owner:\n service.owner = await groups_repository.get_user_email_from_gid(\n service_in_db.owner\n )\n\n return service\n\n\n@router.patch(\"/{service_key:path}/{service_version}\", response_model=ServiceOut)\nasync def modify_service(\n # pylint: disable=too-many-arguments\n user_id: int,\n service_key: constr(regex=KEY_RE),\n service_version: constr(regex=VERSION_RE),\n updated_service: ServiceUpdate,\n director_client: DirectorApi = Depends(get_director_api),\n groups_repository: GroupsRepository = Depends(get_repository(GroupsRepository)),\n services_repo: ServicesRepository = Depends(get_repository(ServicesRepository)),\n x_simcore_products_name: str = Header(None),\n):\n # check the service exists\n await director_client.get(\n f\"/services/{urllib.parse.quote_plus(service_key)}/{service_version}\"\n )\n # the director client already raises an exception if not found\n\n # get the user groups\n user_groups = await groups_repository.list_user_groups(user_id)\n if not user_groups:\n # deny access\n raise HTTPException(\n status_code=status.HTTP_403_FORBIDDEN,\n detail=\"You have unsufficient rights to access the service\",\n )\n # check the user has write access to this service\n writable_service = await services_repo.get_service(\n service_key,\n service_version,\n gids=[group.gid for group in user_groups],\n write_access=True,\n product_name=x_simcore_products_name,\n )\n if not writable_service:\n # deny access\n raise HTTPException(\n status_code=status.HTTP_403_FORBIDDEN,\n detail=\"You have unsufficient rights to modify the service\",\n )\n\n # let's modify the service then\n await services_repo.update_service(\n ServiceMetaDataAtDB(\n key=service_key,\n version=service_version,\n **updated_service.dict(exclude_unset=True),\n )\n )\n # let's modify the service access rights (they can be added/removed/modified)\n current_gids_in_db = [\n r.gid\n for r in await services_repo.get_service_access_rights(\n service_key, service_version, product_name=x_simcore_products_name\n )\n ]\n\n if updated_service.access_rights:\n # start by updating/inserting new entries\n new_access_rights = [\n ServiceAccessRightsAtDB(\n key=service_key,\n version=service_version,\n gid=gid,\n execute_access=rights.execute_access,\n write_access=rights.write_access,\n product_name=x_simcore_products_name,\n )\n for gid, rights in updated_service.access_rights.items()\n ]\n await services_repo.upsert_service_access_rights(new_access_rights)\n\n # then delete the ones that were removed\n removed_gids = [\n gid\n for gid in current_gids_in_db\n if gid not in updated_service.access_rights\n ]\n deleted_access_rights = [\n ServiceAccessRightsAtDB(\n key=service_key,\n version=service_version,\n gid=gid,\n product_name=x_simcore_products_name,\n )\n for gid in removed_gids\n ]\n await services_repo.delete_service_access_rights(deleted_access_rights)\n\n # now return the service\n return await get_service(\n user_id,\n service_key,\n service_version,\n director_client,\n groups_repository,\n services_repo,\n x_simcore_products_name,\n )\n","sub_path":"services/catalog/src/simcore_service_catalog/api/routes/services.py","file_name":"services.py","file_ext":"py","file_size_in_byte":11362,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"459180826","text":"from ConfigParser import RawConfigParser\nfrom StringIO import StringIO\nfrom pprint import pformat\nimport sys\nimport json\nimport subprocess\nimport logging\n\nimport bottle\n\n\nlogging.basicConfig(stream=sys.stdout, level=logging.INFO,\n format='%(asctime)-15s %(levelname)s: %(message)s')\nlog = logging.getLogger(__name__)\n\ncfg = RawConfigParser()\n# set default cfg\ncfg.readfp(StringIO(\"\"\"\n[server]\nhost = localhost\nport = 8888\nserver = wsgiref\ndebug = false\n\"\"\"))\n# read global and custom cfg files\ncfg.read(['/etc/hooked.cfg', './hooked.cfg'])\n\n\ndef checkcfg():\n errors = []\n hooks = set(cfg.sections())\n hooks.remove('server')\n for hook in hooks:\n if not cfg.has_option(hook, 'command'):\n errors.append('[%s] hook should have a \"command\" option.' % hook)\n if len(errors) > 0:\n log.error('\\n--> '.join(['Aborting... Check config failed:'] + errors))\n sys.exit(1)\n\n\n@bottle.get('/')\ndef index():\n #return bottle.redirect('https://github.com/bbinet/hooked')\n resp = {\n 'success': True,\n 'hooks': [],\n }\n hooks = set(cfg.sections())\n hooks.remove('server')\n for hook in hooks:\n items = dict(cfg.items(hook))\n resp['hooks'].append({\n 'name': hook,\n 'repository': items.get('repository'),\n 'branch': items.get('branch'),\n 'command': items['command'],\n 'cwd': items.get('cwd'),\n })\n log.debug('GET / response =>\\n%s' % pformat(resp))\n return resp\n\n\n@bottle.get('/hooks//')\ndef run_hooks(repo, branch):\n if not (repo and branch):\n return bottle.HTTPError(status=400)\n hooks = set(cfg.sections())\n hooks.remove('server')\n resp = {\n 'success': True,\n 'hooks': [],\n }\n for hook in hooks:\n hook_cfg = dict(cfg.items(hook))\n if 'repository' in hook_cfg and repo != hook_cfg['repository']:\n log.debug('\"%s\" repository don\\'t match [%s] hook' % (repo, hook))\n continue\n if 'branch' in hook_cfg and branch != hook_cfg['branch']:\n log.debug('\"%s\" branch don\\'t match [%s] hook' % (branch, hook))\n continue\n resp['hooks'].append(run_hook(hook, repo, branch))\n log.debug(resp)\n return resp\n\n\n@bottle.post('/')\ndef run_git_hooks():\n branch = None\n repo = None\n data = None\n #print('request: ' + str(bottle.request))\n if bottle.request.json:\n data = bottle.request.json\n elif bottle.request.forms.get('payload', None):\n data = json.loads(bottle.request.forms.get('payload'))\n elif bottle.request.POST.get('hook', None):\n data = json.loads(bottle.request.POST.get('hook'))\n data = data['push_data']\n log.debug('POST / request =>\\n%s' % pformat(data))\n\n if data:\n if 'slug' in data['repository']:\n repo = data['repository']['slug']\n elif 'name' in data['repository']:\n repo = data['repository']['name']\n if 'ref' in data:\n branch = data['ref'].split('/')[-1]\n elif 'commits' in data and len(data['commits']) > 0:\n branch = data['commits'][0]['branch']\n elif 'push' in data and 'changes' in data['push'] and len(data['push']['changes']) > 0:\n branch = data['push']['changes'][0]['new']['name']\n\n return run_hooks(repo, branch)\n\n\n@bottle.get('/hook/')\ndef run_hook(hook, repo='', branch=''):\n if not cfg.has_section(hook):\n return bottle.HTTPError(status=404)\n # optionally get repository/branch from query params\n repo = bottle.request.query.get('repository', repo)\n branch = bottle.request.query.get('branch', branch)\n\n hook_cfg = dict(cfg.items(hook))\n\n out, err = subprocess.Popen(\n [hook_cfg['command'], repo, branch],\n cwd=hook_cfg.get('cwd'),\n stdout=subprocess.PIPE,\n stderr=subprocess.PIPE,\n ).communicate()\n log.info('Running command: %s\\n'\n '--> STDOUT: %s\\n'\n '--> STDERR: %s'\n % (' '.join([hook_cfg['command'], repo, branch]), out, err))\n return {\n 'name': hook,\n 'repository': hook_cfg.get('repository'),\n 'branch': hook_cfg.get('branch'),\n 'command': hook_cfg['command'],\n 'cwd': hook_cfg.get('cwd'),\n 'stdout': out,\n 'stderr': err,\n }\n\n\ndef run():\n if len(sys.argv) > 1:\n cfg.read(sys.argv[1:])\n debug = cfg.getboolean('server', 'debug')\n if debug:\n log.setLevel(logging.DEBUG)\n bottle.debug(True)\n checkcfg()\n bottle.run(\n server=cfg.get('server', 'server'),\n host=cfg.get('server', 'host'),\n port=cfg.get('server', 'port'),\n reloader=debug)\n\n\nif __name__ == '__main__':\n cfg.set('server', 'debug', True)\n run()\n","sub_path":"hooked/server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":4802,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"518558129","text":"#!/usr/bin/env python\n\n\"\"\"\n This python file is a helper script for the script runAllTest.py.\n This python file will parse a test case and return all the neccessary\n information to execute the test case.\n \n Args: filename: A name of a file to test\n Output: returnList: A list containing: the test ID number, the path to the\n file of concern, the the method to test, test inputs, and the expected\n output.\n\"\"\"\n\nfrom myExceptions import ImproperTestCaseSpecificationError\n\ndef parseTestCase( filename ):\n\n try:\n testCase = open(filename, 'r')\n \n returnList = []\n \n # Parse the testCase text file. Certain keywords will result in this\n # file collecting the following information: Test ID, filepath, the\n # method in the file to be tested, the inputs, and the expected\n # outcome(s). \n #\n # It is important to note the current limitations. \n # Any deviation from the keywords in the following conditional statements\n # will cause errors no all the necessary elements will be collected.\n # It is assumed that the elements being collected here will be passed\n # to the calling method. \n # It is assumed that the filepath will be the path to the file from\n # the parent directory of this project.\n for line in testCase:\n if \"Test Case ID: \" in line:\n IDnumber = line.replace(\"\\n\", \"\").split(\"ID: \")[1]\n returnList.append(IDnumber)\n elif \"Path to file: \" in line:\n filepath = line.replace(\"\\n\", \"\").split(\"file: \")[1]\n returnList.append(filepath)\n elif \"Method being tested: \" in line:\n methodName = line.replace(\"\\n\", \"\").split(\"tested: \")[1]\n returnList.append(methodName)\n elif \"arguments: \" in line:\n inputs = line.replace(\"\\n\", \"\").split(\"arguments: \")[1]\n returnList.append(inputs)\n elif \"outcome(s): \" in line:\n outcomes = line.replace(\"\\n\", \"\").split(\"outcome(s): \")[1]\n returnList.append(outcomes)\n \n if len(returnList) != 5:\n raise ImproperTestCaseSpecificationError(\"Test case did not follow specification standards.\")\n \n testCase.close()\n \n return returnList\n \n except Exception:\n raise ImproperTestCaseSpecificationError(\"Test case did not follow specification standards.\")\n \n finally:\n testCase.close()\n","sub_path":"TestAutomation/scripts/parseTestCase.py","file_name":"parseTestCase.py","file_ext":"py","file_size_in_byte":2548,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"4373440","text":"import cv2\r\n\r\n# Face and smile classifiers\r\nface_detector = cv2.CascadeClassifier(\r\n cv2.data.haarcascades + 'haarcascade_frontalface_default.xml')\r\nsmile_detector = cv2.CascadeClassifier(\r\n cv2.data.haarcascades + 'haarcascade_smile.xml')\r\n\r\n# Grab Webcam feed\r\nwebcam = cv2.VideoCapture(0)\r\n\r\nwhile True:\r\n # Read current frame from webcam\r\n successful_frame_read, frame = webcam.read()\r\n\r\n # If there's an error, abort\r\n if not successful_frame_read:\r\n break\r\n\r\n # Change to grayscale\r\n frame_grayscale = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)\r\n\r\n # Detect faces first\r\n faces = face_detector.detectMultiScale(frame_grayscale)\r\n # smiles = smile_detector.detectMultiScale(frame_grayscale) # scaleFactor=1.7, minNeighbors=20)\r\n\r\n # Run face detection within each of these faces\r\n for (x, y, w, h) in faces:\r\n\r\n # Draw a rectangle around the face\r\n cv2.rectangle(frame, (x, y), (x+w, y+h), (0, 255, 0), 2)\r\n\r\n # Get the sub frame (using numpy N-dimensional array slicing)\r\n the_face = frame[y:y+h, x:x+w]\r\n\r\n # Change to grayscale\r\n face_grayscale = cv2.cvtColor(the_face, cv2.COLOR_BGR2GRAY)\r\n\r\n smiles = smile_detector.detectMultiScale(\r\n face_grayscale, scaleFactor=1.7, minNeighbors=20)\r\n\r\n # Find all the smiles in the face\r\n # for (x_, y_, w_, h_) in smiles:\r\n\r\n # Draw a rectangle around the smile\r\n #cv2.rectangle(the_face, (x_, y_), (x_+w_, y_+h_), (0, 255, 0), 4)\r\n\r\n # Label this face as smiling\r\n if(len(smiles) > 0):\r\n cv2.putText(frame, 'smiling', (x, y+h+40), fontScale=3,\r\n fontFace=cv2.FONT_HERSHEY_SIMPLEX, color=(255, 255, 255))\r\n\r\n cv2.imshow('Face Detector', frame)\r\n key = cv2.waitKey(1)\r\n\r\n # Stop if Q key is pressed\r\n # ASCII character for q:113 and Q:81\r\n if key == 81 or key == 113:\r\n break\r\n\r\n# Cleanup\r\nwebcam.release()\r\ncv2.destroyAllWindows()\r\nprint(\"CODE COMPLETED\")\r\n","sub_path":"Smile_Detector.py","file_name":"Smile_Detector.py","file_ext":"py","file_size_in_byte":2014,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"532090030","text":"import argparse\nimport sys\nimport os\n\n# Data preparation:\n# plink --noweb --file hm8_5 --recode12 --missing-genotype N --output-missing-genotype 0 --out hm8_5_recode12 --exclude ignoresnps.txt --geno 0.2\n# cat hm8_5_recode12.ped | grep '^SCEL' >outgroups_sus_recode12.ped\n# cat hm8_5_recode12.ped | grep '^SVSV' >>outgroups_sus_recode12.ped\n# cat hm8_5_recode12.ped | grep '^SCEB' >>outgroups_sus_recode12.ped\n# cp hm8_5_recode12.map outgroups_sus_recode12.map\n# for CHROM in `seq 1 18`; do plink --noweb --file hm8_5_recode12 --chr $CHROM --recode --missing-genotype 0 --output-missing-genotype 0 --out chr$CHROM; done\n# for CHROM in `seq 1 18`; do plink --noweb --file outgroups_sus_recode12 --chr $CHROM --freq --missing-genotype 0 --out outgroupfreq_chr$CHROM; done\n\n\nparser = argparse.ArgumentParser( description='calculate heterozygosities for individuals in a ped file')\nparser.add_argument(\"-f\", \"--pedfile_stub\", help=\"name of pedfile stub\", nargs=1)\nparser.add_argument(\"-p\", \"--population\", help=\"name of or string of names of population(s)\", nargs=1)\n\nargs = parser.parse_args()\npedfile_stub=args.pedfile_stub[0]\npops=args.population[0].split(' ')\n\ndef pedfile_to_list_of_lists(pedfile):\n flist=[]\n with open(pedfile) as pedf:\n for l in pedf.readlines():\n l=l.rstrip().split()\n flist.append(l[:])\n return flist\n\ndef calc_het(geno):\n het=0\n hom=0\n for i in range(0,len(geno),2):\n pair=geno[i:i+2]\n if pair[0] == pair[1] and pair[0] != 'N':\n hom+=1\n elif pair[0] != pair[1] and pair[0] != 'N':\n het+=1\n obshet=het/(het+hom)\n return [obshet,het,hom]\n\ndef remove_ped_if_already_present(label,pedfile_stub):\n for i in range(1,19):\n remove_file_if_exists(label+pedfile_stub+str(i)+'.ped')\n\ndef phase_with_shapeit(label,pedfile_stub):\n for i in range(1,19):\n remove_file_if_exists(label+pedfile_stub+str(i)+\".phased.haps\")\n remove_file_if_exists(label+pedfile_stub+str(i)+\".phased.sample\")\n\n shapeit_command=\"/cm/shared/apps/SHARED/shapeit/shapeit2.r769/shapeit --input-ped \"+label+pedfile_stub+str(i)+'.ped '+label+pedfile_stub+str(i)+\".map -O \"+label+pedfile_stub+str(i)+\".phased --missing-code 0 -W 5\"\n print(shapeit_command)\n os.system(shapeit_command)\n os.popen(\"rm shapeit_*\")\n\ndef create_ped(pop,pedfile_stub,label):\n for i in range(1,19):\n remove_file_if_exists(label+pedfile_stub+str(i)+'_int.ped')\n remove_file_if_exists(label+pedfile_stub+str(i)+'_int.map')\n os.system('cat '+pedfile_stub+str(i)+'.ped | grep ^'+pop+' >>'+label+pedfile_stub+str(i)+'_int.ped')\n os.system('cp '+pedfile_stub+str(i)+'.map '+label+pedfile_stub+str(i)+'_int.map')\n os.system('plink --noweb --file '+label+pedfile_stub+str(i)+'_int --chr '+str(i)+' --recode --geno 0.1 --missing-genotype 0 --output-missing-genotype 0 --out '+label+pedfile_stub+str(i))\n #os.remove(label+pedfile_stub+str(i)+'_int.ped')\n #os.remove(label+pedfile_stub+str(i)+'_int.map')\n\ndef remove_file_if_exists(file):\n try:\n if os.stat(file):\n os.remove(file)\n print(\"removed old file: \"+file)\n except OSError:\n pass\n\ndef make_snpinfo(label,pedfile_stub):\n remove_file_if_exists(label+\"snp.info\")\n for i in range(1,19):\n os.popen(\"cat \"+label+pedfile_stub+str(i)+\".phased.haps | awk '{print $2\"+'\" \"$1\" \"$3\" 1 2\"}'+\"' >>\"+label+\"snp.info\")\n\ndef make_haplotype_file(label,pedfile_stub):\n for i in range(1,19):\n command='cut -f1,2 -d\" \" '+label+pedfile_stub+str(i)+\".phased.sample | sed 's/ /_/' | awk '{print $0\"+'\"'+r'\\n'+'\"$0\"1\"}'+\"' | sed 1d | sed 1d | sed 1d | sed 1d >\"+label+pedfile_stub+str(i)+\".duplo_inds\"\n print(command)\n os.system(command)\n command=\"sed 's/ /\"+r'\\t'+\"/' \"+label+pedfile_stub+str(i)+\".phased.haps | sed 's/ /\"+r'\\t'+\"/' | sed 's/ /\"+r'\\t/'+\"' | sed 's/ /\"+r'\\t'+\"/' | sed 's/ /\"+r'\\t'+\"/' | cut -f6 | java -jar /cm/shared/apps/SHARED/beagle/beagle4.r1230/transpose.jar | sed 's/1/2/g' | sed 's/0/1/g' >\"+label+pedfile_stub+str(i)+\".haplo_inds\"\n print(command)\n os.system(command)\n command=\"paste \"+label+pedfile_stub+str(i)+\".duplo_inds \"+label+pedfile_stub+str(i)+\".haplo_inds | sed 's/\"+r'\\t'+\"/ /' >\"+label+pedfile_stub+str(i)+\".phased60K.hap\"\n print(command)\n os.system(command)\n \n\ndef do_rehh(label,pedfile_stub):\n rscriptfile=open(label+\"_rehh.R\",\"w\")\n \n rscriptfile.write(\"library(rehh)\"+\"\\n\")\n for i in range(1,19):\n rscriptfile.write(\"data<-data2haplohh(hap_file='\"+label+pedfile_stub+str(i)+\".phased60K.hap','\"+label+\"snp.info',chr.name=\"+str(i)+\")\\n\")\n if i == 1:\n rscriptfile.write(\"res<-scan_hh(data)\\nwg.res<-res\\n\")\n elif i > 1:\n rscriptfile.write(\"res<-scan_hh(data)\\nwg.res<-rbind(wg.res,res)\\n\")\n rscriptfile.write(\"wg.ihs<-ihh2ihs(wg.res)\\n\")\n rscriptfile.write(\"write.table(wg.ihs$res.ihs, file='\"+label+\"iHS_60K.txt')\\n\")\n rscriptfile.write(\"pdf('\"+label+\"full_60K_REHH.pdf')\\n\")\n rscriptfile.write(\"par(mfrow=c(2,1))\\nihsplot(wg.ihs$res.ihs,plot.pval=TRUE,ylim.scan=2,main='\"+label+\" iHS 60K')\\ndev.off()\\n\")\n rscriptfile.write(\"png('\"+label+\"full_60K_REHH.png',width=2000, height=1800)\\n\")\n rscriptfile.write(\"par(mfrow=c(2,1))\\nihsplot(wg.ihs$res.ihs,plot.pval=TRUE,ylim.scan=2,main='\"+label+\" iHS 60K')\\ndev.off()\\n\")\n rscriptfile.close()\n os.system('R CMD BATCH '+label+'_rehh.R')\n\nif __name__==\"__main__\":\n poplabel=''.join(pops)\n print(poplabel)\n remove_ped_if_already_present(poplabel,pedfile_stub)\n for pop in pops:\n print(pop)\n create_ped(pop,pedfile_stub,poplabel)\n phase_with_shapeit(poplabel,pedfile_stub) \n make_snpinfo(poplabel,pedfile_stub)\n make_haplotype_file(poplabel,pedfile_stub)\n do_rehh(poplabel,pedfile_stub)\n","sub_path":"Pig_60K_tools/rehh_pipeline.py","file_name":"rehh_pipeline.py","file_ext":"py","file_size_in_byte":5763,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"281560627","text":"\"\"\"Using Axe-core, scan the Kitchen Sink pages for accessibility violations.\"\"\"\n\nimport time\nfrom http.client import HTTPConnection\nfrom pathlib import Path\nfrom subprocess import PIPE, Popen\nfrom urllib.parse import urljoin\n\nimport pytest\n\nfrom .utils.pretty_axe_results import pretty_axe_results\n\n# Using importorskip to ensure these tests are only loaded if Playwright is installed.\nplaywright = pytest.importorskip(\"playwright\")\nfrom playwright.sync_api import Page # noqa: E402\n\n# Important note: automated accessibility scans can only find a fraction of\n# potential accessibility issues.\n#\n# This test file scans pages from the Kitchen Sink examples with a JavaScript\n# library called Axe-core, which checks the page for accessibility violations,\n# such as places on the page with poor color contrast that would be hard for\n# people with low vision to see.\n#\n# Just because a page passes the scan with no accessibility violations does\n# *not* mean that it will be generally usable by a broad range of disabled\n# people. It just means that page is free of common testable accessibility\n# pitfalls.\n\npath_repo = Path(__file__).parent.parent\npath_docs_build = path_repo / \"docs\" / \"_build\" / \"html\"\n\n\n@pytest.fixture(scope=\"module\")\ndef url_base():\n \"\"\"Start local server on built docs and return the localhost URL as the base URL.\"\"\"\n # Use a port that is not commonly used during development or else you will\n # force the developer to stop running their dev server in order to run the\n # tests.\n port = \"8213\"\n host = \"localhost\"\n url = f\"http://{host}:{port}\"\n\n # Try starting the server\n process = Popen(\n [\"python\", \"-m\", \"http.server\", port, \"--directory\", path_docs_build],\n stdout=PIPE,\n )\n\n # Try connecting to the server\n retries = 5\n while retries > 0:\n conn = HTTPConnection(host, port)\n try:\n conn.request(\"HEAD\", \"/\")\n response = conn.getresponse()\n if response is not None:\n yield url\n break\n except ConnectionRefusedError:\n time.sleep(1)\n retries -= 1\n\n # If the code above never yields a URL, then we were never able to connect\n # to the server and retries == 0.\n if not retries:\n raise RuntimeError(\"Failed to start http server in 5 seconds\")\n else:\n # Otherwise the server started and this fixture is done now and we clean\n # up by stopping the server.\n process.terminate()\n process.wait()\n\n\n@pytest.mark.a11y\n@pytest.mark.parametrize(\"theme\", [\"light\", \"dark\"])\n@pytest.mark.parametrize(\n \"url_page,selector\",\n [\n (\"admonitions.html\", \"#admonitions\"),\n (\"api.html\", \"#api-documentation\"),\n (\"blocks.html\", \"#blocks\"),\n (\"generic.html\", \"#generic-items\"),\n (\"images.html\", \"#images-figures\"),\n (\"lists.html\", \"#lists\"),\n (\"structure.html\", \"#structural-elements\"),\n (\"structure.html\", \"#structural-elements-2\"),\n (\"tables.html\", \"#tables\"),\n (\"typography.html\", \"#typography\"),\n ],\n)\ndef test_axe_core_kitchen_sink(\n theme: str, url_base: str, url_page: str, selector: str, page: Page\n):\n \"\"\"Should have no Axe-core violations at the provided theme and page section.\"\"\"\n # Load the page at the provided path\n url_base_kitchen_sink = urljoin(url_base, \"/examples/kitchen-sink/\")\n url_full = urljoin(url_base_kitchen_sink, url_page)\n page.goto(url_full)\n\n # Run a line of JavaScript that sets the light/dark theme on the page\n page.evaluate(f\"document.documentElement.dataset.theme = '{theme}'\")\n\n # Inject the Axe-core JavaScript library into the page\n page.add_script_tag(path=\"node_modules/axe-core/axe.min.js\")\n\n # Run the Axe-core library against a section of the page. (Don't run it\n # against the whole page because in this test we're not trying to find\n # accessibility violations in the nav, sidebar, footer, or other parts of\n # the PyData Sphinx Theme documentation website.)\n results = page.evaluate(f\"axe.run('{selector}')\")\n\n # Expect Axe-core to have found 0 accessibility violations\n assert len(results[\"violations\"]) == 0, pretty_axe_results(results)\n","sub_path":"tests/test_a11y.py","file_name":"test_a11y.py","file_ext":"py","file_size_in_byte":4225,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"223773771","text":"import torch\nimport os\nimport pandas as pd\nimport math\nimport numpy as np\nimport dendropy\nfrom Bio import SeqIO\n\ndef get_seq_length(args):\n backbone_seq_file = args.backbone_seq_file\n backbone_tree_file = args.backbone_tree_file\n seq = SeqIO.to_dict(SeqIO.parse(backbone_seq_file, \"fasta\"))\n args.sequence_length = len(list(seq.values())[0])\n tree = dendropy.Tree.get(path=backbone_tree_file, schema='newick')\n num_nodes = len(tree.leaf_nodes())\n if args.embedding_size == -1:\n args.embedding_size = 2**math.floor(math.log2(10*num_nodes**(1/2)))\n\ndef distance_portion(nodes1, nodes2, mode):\n if len(nodes1.shape) == 1:\n nodes1 = nodes1.unsqueeze(0)\n if len(nodes2.shape) == 1:\n nodes2 = nodes2.unsqueeze(0)\n n1 = len(nodes1)\n n2 = len(nodes2)\n nodes1 = nodes1.view(n1, 1, -1)\n nodes2 = nodes2.view(1, n2, -1)\n if mode == 'ms':\n return torch.sum((nodes1 - nodes2) ** 2, dim=-1)\n elif mode == 'L2':\n return torch.sum((nodes1 - nodes2) ** 2, dim=-1)\n elif mode == 'L1':\n return torch.sum(abs(nodes1 - nodes2), dim=-1)\n elif mode == 'cosine':\n return 1 - torch.nn.functional.cosine_similarity(nodes1, nodes2, dim=-1)\n elif mode == 'tan':\n cosine = torch.nn.functional.cosine_similarity(nodes1, nodes2, dim=-1)\n return (1 - cosine ** 2) / (cosine + 1e-9)\n\ndef distance(nodes1, nodes2, mode):\n # node1: query\n # node2: backbone\n dist = []\n for i in range(math.ceil(len(nodes1) / 1000.0)):\n dist.append(distance_portion(nodes1[i*1000: (i+1)*1000], nodes2, mode))\n return torch.cat(dist, dim=0)\n\ndef mse_loss(model_dist, true_dist, weighted_method):\n assert model_dist.shape == true_dist.shape\n if weighted_method == 'ols':\n return ((model_dist - true_dist) ** 2).mean()\n elif weighted_method == 'fm':\n weight = 1 / (true_dist + 1e-4) ** 2\n return ((model_dist - true_dist) ** 2 * weight).mean()\n elif weighted_method == 'be':\n weight = 1 / (true_dist + 1e-4)\n return ((model_dist - true_dist) ** 2 * weight).mean()\n elif weighted_method == 'square_root_fm':\n true_dist = torch.sqrt(true_dist)\n weight = 1 / (true_dist + 1e-4) ** 2\n return ((model_dist - true_dist) ** 2 * weight).mean()\n elif weighted_method == 'square_root_be':\n true_dist = torch.sqrt(true_dist)\n weight = 1 / (true_dist + 1e-4)\n return ((model_dist - true_dist) ** 2 * weight).mean()\n elif weighted_method == 'square_root_ols':\n true_dist = torch.sqrt(true_dist)\n weight = 1\n return ((model_dist - true_dist) ** 2 * weight).mean()\n elif weighted_method == 'square_root_sqrt':\n true_dist = torch.sqrt(true_dist)\n weight = 1 / (torch.sqrt(true_dist) + 1e-4)\n return ((model_dist - true_dist) ** 2 * weight).mean()\n elif weighted_method == 'square_root_four':\n true_dist = torch.sqrt(true_dist)\n weight = 1 / (true_dist + 1e-4) ** 4\n return ((model_dist - true_dist) ** 2 * weight).mean()\n\ndef process_seq(self_seq, args, isbackbone):\n L = len(list(self_seq.values())[0])\n seq_tmp = {}\n if args.replicate_seq and isbackbone:\n for k in self_seq:\n seq_tmp[k.split('_')[0]] = torch.zeros(4, L)\n for k in self_seq:\n seq = np.zeros([4, L])\n raw_seq = np.array(self_seq[k])\n seq[0][raw_seq == 'A'] = 1\n seq[1][raw_seq == 'C'] = 1\n seq[2][raw_seq == 'G'] = 1\n seq[3][raw_seq == 'T'] = 1\n if args.replicate_seq and isbackbone:\n seq_tmp[k.split('_')[0]] += torch.from_numpy(seq)\n else:\n seq_tmp[k] = torch.from_numpy(seq)\n if args.replicate_seq and isbackbone:\n for k in seq_tmp:\n seq_tmp[k] = seq_tmp[k].float() / (seq_tmp[k].sum(dim=0, keepdim=True) + 1e-8)\n names = []\n seqs = []\n for k in seq_tmp:\n names.append(k)\n seqs.append(seq_tmp[k].unsqueeze(0))\n return names, torch.cat(seqs, dim=0)\n\n\ndef save_depp_dist(model, args):\n print('processing data...')\n backbone_seq_file = args.backbone_seq_file\n query_seq_file = args.query_seq_file\n dis_file_root = os.path.join(args.outdir)\n # args.distance_ratio = float(1.0 / float(args.embedding_size) / 10 * float(args.distance_alpha))\n args.distance_ratio = model.hparams.distance_ratio\n if not os.path.exists(dis_file_root):\n os.makedirs(dis_file_root)\n\n backbone_seq = SeqIO.to_dict(SeqIO.parse(backbone_seq_file, \"fasta\"))\n query_seq = SeqIO.to_dict(SeqIO.parse(query_seq_file, \"fasta\"))\n\n backbone_seq_names, backbone_seq_tensor = process_seq(backbone_seq, args, isbackbone=True)\n query_seq_names, query_seq_tensor = process_seq(query_seq, args, isbackbone=False)\n\n for param in model.parameters():\n param.requires_grad = False\n print('finish data processing!')\n print(f'{len(backbone_seq_names)} backbone sequences')\n print(f'{len(query_seq_names)} query sequence(s)')\n print(f'calculating embeddings...')\n backbone_encodings = []\n for i in range(math.ceil(len(backbone_seq_tensor) / 2000.0)):\n encodings_tmp = model(backbone_seq_tensor[i * 2000: (i + 1) * 2000].float()).detach()\n backbone_encodings.append(encodings_tmp)\n backbone_encodings = torch.cat(backbone_encodings, dim=0)\n\n query_encodings = []\n for i in range(math.ceil(len(query_seq_tensor) / 2000.0)):\n encodings_tmp = model(query_seq_tensor[i * 2000: (i + 1) * 2000].float()).detach()\n query_encodings.append(encodings_tmp)\n query_encodings = torch.cat(query_encodings, dim=0)\n print(f'finish embedding calculation!')\n\n query_dist = distance(query_encodings, backbone_encodings, args.distance_mode) * args.distance_ratio\n query_dist = np.array(query_dist)\n query_dist[query_dist < 1e-3] = 0\n if args.weighted_method == 'square_root_fm':\n data_origin = dict(zip(query_seq_names, list(query_dist**2)))\n else:\n data_origin = dict(zip(query_seq_names, list(query_dist)))\n\n data_origin = pd.DataFrame.from_dict(data_origin, orient='index', columns=backbone_seq_names)\n\n data_origin.to_csv(os.path.join(dis_file_root, f'depp.csv'), sep='\\t')\n if not os.path.isdir(f'{args.outdir}/depp_tmp'):\n os.makedirs(f'{args.outdir}/depp_tmp')\n with open(f'{args.outdir}/depp_tmp/seq_name.txt', 'w') as f:\n f.write(\"\\n\".join(query_seq_names)+'\\n')\n print('original distanace matrix saved!')\n","sub_path":"depp/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":6471,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"454281665","text":"from tournament.utils import HACK_DICT\r\nimport numpy as np\r\nfrom numpy.linalg import norm\r\nimport oracle_agent.utils as utils\r\nimport time\r\nimport sys\r\nimport oracle_agent.models as models\r\nimport torch\r\nimport torch.nn.functional as F\r\nfrom os import path\r\n\r\n\r\nclass HockeyPlayer(object):\r\n TARGET_SPEED = 15\r\n DRIFT_ANGLE = 20\r\n BRAKE_ANGLE = 30\r\n DEFENSE_RADIUS = 40\r\n\r\n PUCK = None\r\n PUCK_T = 0\r\n\r\n def __init__(self, player_id=0, kart='wilber'):\r\n # constants\r\n self.player_id = player_id\r\n self.kart = kart\r\n self.team = player_id % 2\r\n self.own_goal = np.float32([0, -65 if self.team == 0 else 65])\r\n self.goal = np.float32([0, 64 if self.team == 0 else -64])\r\n self.model = models.Detector()\r\n self.model.load_state_dict(torch.load(path.join(path.dirname(path.abspath(__file__)), 'det.th'), map_location='cpu'))\r\n self.model.eval()\r\n # self.model = self.model.cuda()\r\n\r\n # states\r\n self.offense = (player_id == 0)\r\n self.pucklock = True\r\n\r\n # vars\r\n self.puck = np.float32([0, 0])\r\n self.t = 0\r\n\r\n # recurrent info\r\n self.last_puck = None\r\n self.last_loc = None \r\n\r\n def act(self, image, player_info, game_state=None, mask=None):\r\n \"\"\"\r\n :param image: numpy array of shape (300, 400, 3)\r\n :param player_info: pystk.Player object for the current kart.\r\n return: Dict describing the action\r\n \"\"\"\r\n # puck = np.float32(HACK_DICT['state'].soccer.ball.location)[[0, 2]]\r\n # dets, depth, is_puck = self.model.detect(torch.from_numpy(image/255.0).float().permute(2, 0, 1).cuda())\r\n start_time = time.time()\r\n with torch.no_grad():\r\n img = F.interpolate(torch.from_numpy(image/255.0).float().permute(2, 0, 1)[None], size=(75,100))[0,:,27:,:]\r\n dets, depth, is_puck = self.model.detect(img)\r\n # transform detections from small net -> big net\r\n for det in dets:\r\n for i, de in enumerate(det):\r\n new_de_1 = (de[1] + 0) * 4\r\n new_de_2 = (de[2] + 27) * 4\r\n new_de = (de[0], new_de_1, new_de_2, de[3], de[4])\r\n det[i] = new_de\r\n end_time = time.time()\r\n print(\"Network detection took\", end_time-start_time)\r\n\r\n front = np.float32(player_info.kart.front)[[0, 2]]\r\n kart = np.float32(player_info.kart.location)[[0, 2]]\r\n vel = np.float32(player_info.kart.velocity)[[0, 2]]\r\n speed = norm(vel)\r\n\r\n if self.last_loc is None or float(norm(kart - self.last_loc)) > 10:\r\n self.t = 0\r\n self.last_loc = kart\r\n\r\n coords = dets[1][0]\r\n proj = np.array(player_info.camera.projection).T @ np.array(player_info.camera.view).T\r\n if is_puck > 0 and dets[1][0][0] > 2 and len(dets[0]) > 0: # and abs(dets[1][0][1] - dets[0][0][1]) + abs(dets[1][0][2] - dets[0][0][2]) > 45: # and abs(dets[1][0][3] - dets[0][0][3]) + abs(dets[1][0][4] - dets[0][0][4]) > 10:\r\n # we can bereasonably confident the puck exists\r\n puck = utils.center_to_world(coords[1], coords[2], 400, 300, proj)\r\n else:\r\n puck = None\r\n\r\n #print(puck[1]/400)\r\n #print(puck[2]/300)\r\n\r\n # TODO: insert some confidence metric here\r\n\r\n if puck is not None:\r\n # print(puck.shape)\r\n puck = puck[[0,2]]\r\n self.pucklock = True\r\n\r\n if puck is None:\r\n otherpuck = HockeyPlayer.PUCK\r\n pt = HockeyPlayer.PUCK_T\r\n self.pucklock = True\r\n\r\n if abs(self.t - pt) < 10 and otherpuck is not None:\r\n puck = otherpuck\r\n elif self.t < 60: # change this?\r\n # assume puck is at center\r\n puck = np.float32([0,0])\r\n else:\r\n # back up until we see puck\r\n self.pucklock = False\r\n puck = np.float32([0,0])\r\n else:\r\n # set shared puck\r\n HockeyPlayer.PUCK = puck\r\n HockeyPlayer.PUCK_T = self.t\r\n # puck_updated = False\r\n # if is_puck > 0 and puck[0] > 2 and len(dets[0]) > 0 and abs(puck[1] - dets[0][0][1]) + abs(puck[2] - dets[0][0][2]) > 45: # and abs(puck[3] - dets[0][0][3]) + abs(puck[4] - dets[0][0][4]) > 10:\r\n # puck = utils.center_to_world(puck[1], puck[2], 400, 300, np.array(player_info.camera.projection).T @ np.array(player_info.camera.view).T)\r\n # if puck is not None and np.linalg.norm(puck - player_info.kart.location) > 2:\r\n # self.last_puck = puck\r\n # puck_updated = True\r\n # puck = puck[[0, 2]]\r\n # else:\r\n # puck = self.last_puck\r\n # if puck is not None:\r\n # puck = puck[[0, 2]]\r\n # else:\r\n # puck = np.array([0, 0])\r\n # else:\r\n # puck = self.last_puck\r\n # if puck is None:\r\n # puck = np.array([0, 0]) # estimate at center before known\r\n # else:\r\n # puck = puck[[0, 2]]\r\n # realpuck = np.float32(game_state.soccer.ball.location)[[0, 2]]\r\n puck_map = np.zeros((66 * 4, 66 * 4, 3))\r\n # puck_map[int(round(-66 + 66 * 2 - 1)):int(round(-66 + 66 * 2 + 133)), int(round(-50 + 66 * 2 - 1)):int(round(-50 + 66 * 2 + 1))] = [100, 0, 0]\r\n # puck_map[int(round(-66 + 66 * 2 - 1)):int(round(-66 + 66 * 2 + 133)), int(round(-50 + 66 * 2 - 1 + 100)):int(round(-50 + 66 * 2 + 101))] = [100, 0, 0]\r\n # puck_map[int(round(-66 + 66 * 2 - 1)):int(round(-66 + 66 * 2 + 1)), int(round(-50 + 66 * 2 - 1)):int(round(50 + 66 * 2 + 1))] = [100, 0, 0]\r\n # puck_map[int(round(66 + 66 * 2 - 1)):int(round(66 + 66 * 2 + 1)), int(round(-50 + 66 * 2 - 1)):int(round(50 + 66 * 2 + 1))] = [100, 0, 0]\r\n # puck_map[int(round(puck[1] + 66 * 2 - 2)):int(round(puck[1] + 66 * 2 + 2)), int(round(puck[0] + 66 * 2 - 2)):int(round(puck[0] + 66 * 2 + 2))] += [255, 0, 0]\r\n # puck_map[int(round(realpuck[1] + 66 * 2 - 2)):int(round(realpuck[1] + 66 * 2 + 2)), int(round(realpuck[0] + 66 * 2 - 2)):int(round(realpuck[0] + 66 * 2 + 2))] += [0, 255, 0]\r\n # puck_map[int(round(kart[1] + 66 * 2 - 2)):int(round(kart[1] + 66 * 2 + 2)), int(round(kart[0] + 66 * 2 - 2)):int(round(kart[0] + 66 * 2 + 2))] += [0, 0, 255]\r\n\r\n\r\n u = front - kart\r\n u /= norm(u)\r\n\r\n # find aimpoint\r\n if self.offense:\r\n puck_goal = self.goal - puck\r\n puck_goal /= norm(puck_goal)\r\n kart_puck_dist = norm(puck - kart)\r\n aim = puck - puck_goal * kart_puck_dist / 2\r\n else: # defense\r\n own_goal_puck = puck - self.own_goal\r\n own_goal_puck_dist = norm(own_goal_puck)\r\n\r\n if own_goal_puck_dist < self.DEFENSE_RADIUS:\r\n aim = puck - 1 * own_goal_puck / own_goal_puck_dist\r\n elif np.abs(kart[1]) < np.abs(self.own_goal[1]):\r\n aim = self.own_goal\r\n u = -u\r\n vel = -vel\r\n else:\r\n aim = self.goal\r\n\r\n # get steer angles\r\n v = aim - kart\r\n v /= norm(v)\r\n theta = np.degrees(np.arccos(np.dot(u, v)))\r\n signed_theta = -np.sign(np.cross(u, v)) * np.sign(np.dot(u, vel)) * theta\r\n steer = signed_theta / 8\r\n\r\n # brake or accelerate\r\n drift = False\r\n if self.offense:\r\n brake = self.BRAKE_ANGLE <= theta\r\n drift = self.DRIFT_ANGLE <= theta and not brake\r\n accel = 1 if speed < self.TARGET_SPEED and not brake else 0\r\n else: # defense\r\n if own_goal_puck_dist < self.DEFENSE_RADIUS:\r\n brake = self.BRAKE_ANGLE <= theta\r\n drift = self.DRIFT_ANGLE <= theta and not brake\r\n accel = 1 if speed < self.TARGET_SPEED and not brake else 0\r\n elif np.abs(kart[1]) < np.abs(self.own_goal[1]):\r\n brake = True\r\n accel = 0\r\n else:\r\n brake = (np.sign(np.dot(u, vel)) == 1 and speed > 2) or 5 <= theta\r\n accel = 1 if brake == 0 and np.sign(np.dot(u, vel)) == -1 and speed > 2 else 0\r\n\r\n return {\r\n 'steer': steer,\r\n 'acceleration': accel,\r\n 'brake': brake,\r\n 'drift': False,\r\n 'nitro': False,\r\n 'rescue': False,\r\n 'puck_map': puck_map\r\n }\r\n","sub_path":"oracle_agent/player.py","file_name":"player.py","file_ext":"py","file_size_in_byte":8467,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"396528905","text":"class_name = 'saml_tab'\n\n\nfrom qtpy import QtWidgets, uic\nimport os\nimport sys\nimport pathlib\nimport json\nfrom logzero import logger\nfrom datetime import datetime, timezone\nfrom modules.sumologic import SumoLogic\nfrom modules.shared import ShowTextDialog, import_saml_config\n\n\nclass saml_tab(QtWidgets.QWidget):\n\n def __init__(self, mainwindow):\n\n super(saml_tab, self).__init__()\n self.mainwindow = mainwindow\n self.tab_name = 'SAML'\n self.cred_usage = 'both'\n saml_widget_ui = os.path.join(self.mainwindow.basedir, 'data/saml.ui')\n uic.loadUi(saml_widget_ui, self)\n\n self.pushButtonUpdateSAMLLeft.clicked.connect(lambda: self.update_SAML_list(\n self.SAMLListWidgetLeft,\n self.mainwindow.loadedapiurls[str(self.mainwindow.comboBoxRegionLeft.currentText())],\n str(self.mainwindow.lineEditUserNameLeft.text()),\n str(self.mainwindow.lineEditPasswordLeft.text())\n ))\n\n self.pushButtonUpdateSAMLRight.clicked.connect(lambda: self.update_SAML_list(\n self.SAMLListWidgetRight,\n self.mainwindow.loadedapiurls[str(self.mainwindow.comboBoxRegionRight.currentText())],\n str(self.mainwindow.lineEditUserNameRight.text()),\n str(self.mainwindow.lineEditPasswordRight.text())\n ))\n\n self.pushButtonSAMLDeleteLeft.clicked.connect(lambda: self.delete_saml(\n self.SAMLListWidgetLeft,\n self.mainwindow.loadedapiurls[str(self.mainwindow.comboBoxRegionLeft.currentText())],\n str(self.mainwindow.lineEditUserNameLeft.text()),\n str(self.mainwindow.lineEditPasswordLeft.text())\n ))\n\n self.pushButtonSAMLDeleteRight.clicked.connect(lambda: self.delete_saml(\n self.SAMLListWidgetRight,\n self.mainwindow.loadedapiurls[str(self.mainwindow.comboBoxRegionRight.currentText())],\n str(self.mainwindow.lineEditUserNameRight.text()),\n str(self.mainwindow.lineEditPasswordRight.text())\n ))\n\n self.pushButtonSAMLCopyLeftToRight.clicked.connect(lambda: self.copy_saml(\n self.SAMLListWidgetLeft,\n self.SAMLListWidgetRight,\n self.mainwindow.loadedapiurls[str(self.mainwindow.comboBoxRegionLeft.currentText())],\n str(self.mainwindow.lineEditUserNameLeft.text()),\n str(self.mainwindow.lineEditPasswordLeft.text()),\n self.mainwindow.loadedapiurls[str(self.mainwindow.comboBoxRegionRight.currentText())],\n str(self.mainwindow.lineEditUserNameRight.text()),\n str(self.mainwindow.lineEditPasswordRight.text())\n ))\n\n self.pushButtonSAMLCopyRightToLeft.clicked.connect(lambda: self.copy_saml(\n self.SAMLListWidgetRight,\n self.SAMLListWidgetLeft,\n self.mainwindow.loadedapiurls[str(self.mainwindow.comboBoxRegionRight.currentText())],\n str(self.mainwindow.lineEditUserNameRight.text()),\n str(self.mainwindow.lineEditPasswordRight.text()),\n self.mainwindow.loadedapiurls[str(self.mainwindow.comboBoxRegionLeft.currentText())],\n str(self.mainwindow.lineEditUserNameLeft.text()),\n str(self.mainwindow.lineEditPasswordLeft.text())\n ))\n\n self.pushButtonSAMLBackupLeft.clicked.connect(lambda: self.backup_saml(\n self.SAMLListWidgetLeft,\n self.mainwindow.loadedapiurls[str(self.mainwindow.comboBoxRegionLeft.currentText())],\n str(self.mainwindow.lineEditUserNameLeft.text()),\n str(self.mainwindow.lineEditPasswordLeft.text())\n ))\n\n self.pushButtonSAMLBackupRight.clicked.connect(lambda: self.backup_saml(\n self.SAMLListWidgetRight,\n self.mainwindow.loadedapiurls[str(self.mainwindow.comboBoxRegionRight.currentText())],\n str(self.mainwindow.lineEditUserNameRight.text()),\n str(self.mainwindow.lineEditPasswordRight.text())\n ))\n\n self.pushButtonSAMLJSONLeft.clicked.connect(lambda: self.view_json(\n self.SAMLListWidgetLeft,\n self.mainwindow.loadedapiurls[str(self.mainwindow.comboBoxRegionLeft.currentText())],\n str(self.mainwindow.lineEditUserNameLeft.text()),\n str(self.mainwindow.lineEditPasswordLeft.text())\n ))\n\n self.pushButtonSAMLJSONRight.clicked.connect(lambda: self.view_json(\n self.SAMLListWidgetRight,\n self.mainwindow.loadedapiurls[str(self.mainwindow.comboBoxRegionRight.currentText())],\n str(self.mainwindow.lineEditUserNameRight.text()),\n str(self.mainwindow.lineEditPasswordRight.text())\n ))\n\n self.pushButtonSAMLRestoreLeft.clicked.connect(lambda: self.restore_saml(\n self.SAMLListWidgetLeft,\n self.mainwindow.loadedapiurls[str(self.mainwindow.comboBoxRegionLeft.currentText())],\n str(self.mainwindow.lineEditUserNameLeft.text()),\n str(self.mainwindow.lineEditPasswordLeft.text())\n ))\n\n self.pushButtonSAMLRestoreRight.clicked.connect(lambda: self.restore_saml(\n self.SAMLListWidgetRight,\n self.mainwindow.loadedapiurls[str(self.mainwindow.comboBoxRegionRight.currentText())],\n str(self.mainwindow.lineEditUserNameRight.text()),\n str(self.mainwindow.lineEditPasswordRight.text())\n ))\n\n def reset_stateful_objects(self, side='both'):\n\n if side == 'both':\n left = True\n right = True\n if side == 'left':\n left = True\n right = False\n if side == 'right':\n left = False\n right = True\n\n if left:\n self.SAMLListWidgetLeft.clear()\n self.SAMLListWidgetLeft.currentcontent = {}\n self.SAMLListWidgetLeft.updated = False\n\n if right:\n self.SAMLListWidgetRight.clear()\n self.SAMLListWidgetRight.currentcontent = {}\n self.SAMLListWidgetRight.updated = False\n\n def update_SAML_list(self, SAMLListWidget, url, id, key):\n sumo = SumoLogic(id, key, endpoint=url, log_level=self.mainwindow.log_level)\n try:\n logger.info(\"[SAML]Updating SAML config List\")\n SAMLListWidget.currentcontent = sumo.get_saml_configs()\n SAMLListWidget.clear()\n self.update_SAML_listwidget(SAMLListWidget)\n return\n except Exception as e:\n logger.exception(e)\n SAMLListWidget.updated = False\n self.mainwindow.errorbox('Something went wrong:\\n\\n' + str(e))\n return\n\n def update_SAML_listwidget(self, SAMLListWidget):\n try:\n SAMLListWidget.clear()\n SAMLListWidget.setSortingEnabled(True)\n for object in SAMLListWidget.currentcontent:\n item_name = object['configurationName']\n SAMLListWidget.addItem(item_name) # populate the list widget in the GUI\n SAMLListWidget.updated = True\n except Exception as e:\n logger.exception(e)\n SAMLListWidget.updated = False\n SAMLListWidget.clear()\n\n return\n\n def delete_saml(self, SAMLListWidget, url, id, key):\n logger.info(\"[SAML]Deleting SAML config(s)\")\n selecteditems = SAMLListWidget.selectedItems()\n if len(selecteditems) > 0: # make sure something was selected\n message = \"You are about to delete the following item(s):\\n\\n\"\n for selecteditem in selecteditems:\n message = message + str(selecteditem.text()) + \"\\n\"\n message = message + '''\n This is exceedingly DANGEROUS!!!! \n Please be VERY, VERY, VERY sure you want to do this!\n You could lose quite a bit of work if you delete the wrong thing(s).\n\n If you are absolutely sure, type \"DELETE\" in the box below.\n\n '''\n text, result = QtWidgets.QInputDialog.getText(self, 'Warning!!', message)\n if (result and (str(text) == 'DELETE')):\n try:\n\n sumo = SumoLogic(id, key, endpoint=url, log_level=self.mainwindow.log_level)\n for selecteditem in selecteditems:\n for object in SAMLListWidget.currentcontent:\n if object['configurationName'] == str(selecteditem.text()):\n item_id = object['id']\n\n result = sumo.delete_saml_config(item_id)\n\n self.update_SAML_list(SAMLListWidget, url, id, key)\n return\n\n\n except Exception as e:\n logger.exception(e)\n self.mainwindow.errorbox('Something went wrong:\\n\\n' + str(e))\n\n else:\n self.mainwindow.errorbox('You need to select something before you can delete it.')\n return\n\n def copy_saml(self, SAMLListWidgetFrom, SAMLListWidgetTo, fromurl, fromid, fromkey,\n tourl, toid,\n tokey):\n\n logger.info(\"[SAML]Copying SAML config(s)\")\n try:\n selecteditems = SAMLListWidgetFrom.selectedItems()\n if len(selecteditems) > 0: # make sure something was selected\n message = \"You are about to copy the following item(s):\\n\\n\"\n for selecteditem in selecteditems:\n message = message + str(selecteditem.text()) + \"\\n\"\n message = message + '''\n This is exceedingly DANGEROUS!!!! \n Please be VERY, VERY, VERY sure you want to do this!\n You could cross the streams if you copy the wrong thing(s).\n\n If you are absolutely sure, type \"COPY\" in the box below.\n\n '''\n text, result = QtWidgets.QInputDialog.getText(self, 'Warning!!', message)\n if (result and (str(text) == 'COPY')):\n fromsumo = SumoLogic(fromid, fromkey, endpoint=fromurl, log_level=self.mainwindow.log_level)\n tosumo = SumoLogic(toid, tokey, endpoint=tourl, log_level=self.mainwindow.log_level)\n for selecteditem in selecteditems:\n for object in SAMLListWidgetFrom.currentcontent:\n if object['configurationName'] == str(selecteditem.text()):\n item_id = object['id']\n saml_export = fromsumo.get_saml_config_by_id(item_id)\n import_saml_config(saml_export, tosumo)\n break\n self.update_SAML_list(SAMLListWidgetTo, tourl, toid, tokey)\n return\n\n else:\n self.mainwindow.errorbox('You have not made any selections.')\n return\n\n except Exception as e:\n logger.exception(e)\n self.mainwindow.errorbox('Something went wrong:' + str(e))\n self.update_SAML_list(SAMLListWidgetTo, tourl, toid, tokey)\n return\n\n def backup_saml(self, SAMLListWidget, url, id, key):\n logger.info(\"[SAML]Backing Up SAML config(s)\")\n selecteditems = SAMLListWidget.selectedItems()\n if len(selecteditems) > 0: # make sure something was selected\n savepath = str(QtWidgets.QFileDialog.getExistingDirectory(self, \"Select Backup Directory\"))\n if os.access(savepath, os.W_OK):\n message = ''\n sumo = SumoLogic(id, key, endpoint=url, log_level=self.mainwindow.log_level)\n for selecteditem in selecteditems:\n for object in SAMLListWidget.currentcontent:\n if object['configurationName'] == str(selecteditem.text()):\n item_id = object['id']\n try:\n\n export = sumo.get_saml_config_by_id(item_id)\n\n savefilepath = pathlib.Path(savepath + r'/' + str(selecteditem.text()) + r'.saml.json')\n if savefilepath:\n with savefilepath.open(mode='w') as filepointer:\n json.dump(export, filepointer)\n message = message + str(selecteditem.text()) + r'.json' + '\\n'\n except Exception as e:\n logger.exception(e)\n self.mainwindow.errorbox('Something went wrong:\\n\\n' + str(e))\n return\n self.mainwindow.infobox('Wrote files: \\n\\n' + message)\n else:\n self.mainwindow.errorbox(\"You don't have permissions to write to that directory\")\n\n else:\n self.mainwindow.errorbox('No content selected.')\n return\n\n def view_json(self, SAMLListWidget, url, id, key):\n logger.info(\"[SAML]Viewing SAML(s) as JSON\")\n selecteditems = SAMLListWidget.selectedItems()\n if len(selecteditems) > 0: # make sure something was selected\n try:\n sumo = SumoLogic(id, key, endpoint=url, log_level=self.mainwindow.log_level)\n json_text = ''\n for selecteditem in selecteditems:\n for object in SAMLListWidget.currentcontent:\n if object['configurationName'] == str(selecteditem.text()):\n item_id = object['id']\n fer = sumo.get_saml_config_by_id(item_id)\n json_text = json_text + json.dumps(fer, indent=4, sort_keys=True) + '\\n\\n'\n self.json_window = ShowTextDialog('JSON', json_text, self.mainwindow.basedir)\n self.json_window.show()\n\n except Exception as e:\n logger.exception(e)\n self.mainwindow.errorbox('Something went wrong:\\n\\n' + str(e))\n return\n\n else:\n self.mainwindow.errorbox('No FER selected.')\n return\n\n def restore_saml(self, SAMLListWidget, url, id, key):\n logger.info(\"[SAML]Restoring SAML config(s)\")\n if SAMLListWidget.updated == True:\n\n filter = \"JSON (*.json)\"\n filelist, status = QtWidgets.QFileDialog.getOpenFileNames(self, \"Open file(s)...\", os.getcwd(),\n filter)\n if len(filelist) > 0:\n sumo = SumoLogic(id, key, endpoint=url, log_level=self.mainwindow.log_level)\n for file in filelist:\n try:\n with open(file) as filepointer:\n saml_export = json.load(filepointer)\n except Exception as e:\n logger.exception(e)\n self.mainwindow.errorbox(\n \"Something went wrong reading the file. Do you have the right file permissions? Does it contain valid JSON?\")\n return\n try:\n import_saml_config(saml_export, sumo)\n\n except Exception as e:\n logger.exception(e)\n self.mainwindow.errorbox('Something went wrong:\\n\\n' + str(e))\n return\n self.update_SAML_list(SAMLListWidget, url, id, key)\n\n\n else:\n self.mainwindow.errorbox(\"Please select at least one file to restore.\")\n return\n else:\n self.mainwindow.errorbox(\"Please update the SAML config list before restoring a config\")\n return\n","sub_path":"modules/saml_tab.py","file_name":"saml_tab.py","file_ext":"py","file_size_in_byte":15706,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"79746268","text":"import os\nfrom datetime import datetime, timedelta\nfrom pytz import timezone\nfrom crawling_yes24 import parsing_beautifulsoup, extract_book_data\nfrom github_utils import get_github_repo, upload_github_issue\n\n\nif __name__ == \"__main__\":\n access_token = os.environ['MY_GITHUB_TOKEN']\n repository_name = \"TodayReview\"\n\n seoul_timezone = timezone('Asia/Seoul')\n today = datetime.now(seoul_timezone)\n\n close = today + timedelta(days=-1)\n open = today + timedelta(days=1)\n \n closeDate = close.strftime('%Y-%m-%d');\n openDate = open.strftime('%Y-%m-%d');\n \n repo = get_github_repo(access_token, repository_name)\n upload_github_issue(repo, openDate, \"\")\n print(\"Upload Github Issue Success!\")\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":724,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"577922272","text":"# coding: utf-8\n\n\"\"\"\n Yagna Activity API\n\n It conforms with capability level 1 of the [Activity API specification](https://docs.google.com/document/d/1BXaN32ediXdBHljEApmznSfbuudTU8TmvOmHKl0gmQM). # noqa: E501\n\n The version of the OpenAPI document: v1\n Generated by: https://openapi-generator.tech\n\"\"\"\n\n\nimport pprint\nimport re # noqa: F401\n\nimport six\n\nfrom ya_activity.configuration import Configuration\n\n\nclass ExeScriptCommandResult(object):\n \"\"\"NOTE: This class is auto generated by OpenAPI Generator.\n Ref: https://openapi-generator.tech\n\n Do not edit the class manually.\n \"\"\"\n\n \"\"\"\n Attributes:\n openapi_types (dict): The key is attribute name\n and the value is attribute type.\n attribute_map (dict): The key is attribute name\n and the value is json key in definition.\n \"\"\"\n openapi_types = {\n 'index': 'int',\n 'result': 'str',\n 'message': 'str',\n 'is_batch_finished': 'bool'\n }\n\n attribute_map = {\n 'index': 'index',\n 'result': 'result',\n 'message': 'message',\n 'is_batch_finished': 'isBatchFinished'\n }\n\n def __init__(self, index=None, result=None, message=None, is_batch_finished=None, local_vars_configuration=None): # noqa: E501\n \"\"\"ExeScriptCommandResult - a model defined in OpenAPI\"\"\" # noqa: E501\n if local_vars_configuration is None:\n local_vars_configuration = Configuration()\n self.local_vars_configuration = local_vars_configuration\n\n self._index = None\n self._result = None\n self._message = None\n self._is_batch_finished = None\n self.discriminator = None\n\n self.index = index\n self.result = result\n if message is not None:\n self.message = message\n if is_batch_finished is not None:\n self.is_batch_finished = is_batch_finished\n\n @property\n def index(self):\n \"\"\"Gets the index of this ExeScriptCommandResult. # noqa: E501\n\n\n :return: The index of this ExeScriptCommandResult. # noqa: E501\n :rtype: int\n \"\"\"\n return self._index\n\n @index.setter\n def index(self, index):\n \"\"\"Sets the index of this ExeScriptCommandResult.\n\n\n :param index: The index of this ExeScriptCommandResult. # noqa: E501\n :type: int\n \"\"\"\n if self.local_vars_configuration.client_side_validation and index is None: # noqa: E501\n raise ValueError(\"Invalid value for `index`, must not be `None`\") # noqa: E501\n if (self.local_vars_configuration.client_side_validation and\n index is not None and index < 0): # noqa: E501\n raise ValueError(\"Invalid value for `index`, must be a value greater than or equal to `0`\") # noqa: E501\n\n self._index = index\n\n @property\n def result(self):\n \"\"\"Gets the result of this ExeScriptCommandResult. # noqa: E501\n\n\n :return: The result of this ExeScriptCommandResult. # noqa: E501\n :rtype: str\n \"\"\"\n return self._result\n\n @result.setter\n def result(self, result):\n \"\"\"Sets the result of this ExeScriptCommandResult.\n\n\n :param result: The result of this ExeScriptCommandResult. # noqa: E501\n :type: str\n \"\"\"\n if self.local_vars_configuration.client_side_validation and result is None: # noqa: E501\n raise ValueError(\"Invalid value for `result`, must not be `None`\") # noqa: E501\n allowed_values = [\"Ok\", \"Error\"] # noqa: E501\n if self.local_vars_configuration.client_side_validation and result not in allowed_values: # noqa: E501\n raise ValueError(\n \"Invalid value for `result` ({0}), must be one of {1}\" # noqa: E501\n .format(result, allowed_values)\n )\n\n self._result = result\n\n @property\n def message(self):\n \"\"\"Gets the message of this ExeScriptCommandResult. # noqa: E501\n\n\n :return: The message of this ExeScriptCommandResult. # noqa: E501\n :rtype: str\n \"\"\"\n return self._message\n\n @message.setter\n def message(self, message):\n \"\"\"Sets the message of this ExeScriptCommandResult.\n\n\n :param message: The message of this ExeScriptCommandResult. # noqa: E501\n :type: str\n \"\"\"\n\n self._message = message\n\n @property\n def is_batch_finished(self):\n \"\"\"Gets the is_batch_finished of this ExeScriptCommandResult. # noqa: E501\n\n\n :return: The is_batch_finished of this ExeScriptCommandResult. # noqa: E501\n :rtype: bool\n \"\"\"\n return self._is_batch_finished\n\n @is_batch_finished.setter\n def is_batch_finished(self, is_batch_finished):\n \"\"\"Sets the is_batch_finished of this ExeScriptCommandResult.\n\n\n :param is_batch_finished: The is_batch_finished of this ExeScriptCommandResult. # noqa: E501\n :type: bool\n \"\"\"\n\n self._is_batch_finished = is_batch_finished\n\n def to_dict(self):\n \"\"\"Returns the model properties as a dict\"\"\"\n result = {}\n\n for attr, _ in six.iteritems(self.openapi_types):\n value = getattr(self, attr)\n if isinstance(value, list):\n result[attr] = list(map(\n lambda x: x.to_dict() if hasattr(x, \"to_dict\") else x,\n value\n ))\n elif hasattr(value, \"to_dict\"):\n result[attr] = value.to_dict()\n elif isinstance(value, dict):\n result[attr] = dict(map(\n lambda item: (item[0], item[1].to_dict())\n if hasattr(item[1], \"to_dict\") else item,\n value.items()\n ))\n else:\n result[attr] = value\n\n return result\n\n def to_str(self):\n \"\"\"Returns the string representation of the model\"\"\"\n return pprint.pformat(self.to_dict())\n\n def __repr__(self):\n \"\"\"For `print` and `pprint`\"\"\"\n return self.to_str()\n\n def __eq__(self, other):\n \"\"\"Returns true if both objects are equal\"\"\"\n if not isinstance(other, ExeScriptCommandResult):\n return False\n\n return self.to_dict() == other.to_dict()\n\n def __ne__(self, other):\n \"\"\"Returns true if both objects are not equal\"\"\"\n if not isinstance(other, ExeScriptCommandResult):\n return True\n\n return self.to_dict() != other.to_dict()\n","sub_path":"ya_activity/models/exe_script_command_result.py","file_name":"exe_script_command_result.py","file_ext":"py","file_size_in_byte":6525,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"46938581","text":"# import the module\nfrom flask import Flask\nfrom time import gmtime, strftime\nimport aerospike\nimport json\n\n# Configure the client\nconfig = {\n 'hosts': [('127.0.0.1', 3000)]\n}\n# Records are addressable via a tuple of (namespace, set, key)\nread_key = ('test', 'demo', 'foo')\nwrite_key = ('test', 'demo', 'foo')\napp = Flask(__name__)\n\n\n@app.route(\"/write\")\ndef write():\n # Create a client and connect it to the cluster\n try:\n client = aerospike.client(config).connect()\n except Exception as e:\n import sys\n error = \"failed to connect to the cluster with {0} and {1}\".format(\n config['hosts'], e)\n return json.dumps({\"error\": error}, sort_keys=True, indent=2)\n sys.exit(1)\n\n try:\n # Write a record\n data = {\n 'name': 'John Doe',\n 'age': 32,\n 'timestamp': strftime(\"%Y-%m-%d %H:%M:%S\", gmtime())\n }\n client.put(write_key, data)\n except Exception as e:\n import sys\n error = \"{0}\".format(e)\n return json.dumps({\"error\": error}, sort_keys=True, indent=2)\n\n # Close the connection to the Aerospike cluster\n client.close()\n return json.dumps({\"record\": data}, sort_keys=True, indent=2)\n\n\n@app.route(\"/read\")\ndef read():\n # Create a client and connect it to the cluster\n try:\n client = aerospike.client(config).connect()\n except Exception as e:\n import sys\n error = \"failed to connect to the cluster with {0} and {1}\".format(\n config['hosts'], e)\n return json.dumps({\"error\": error}, sort_keys=True, indent=2)\n sys.exit(1)\n\n # Read a record\n (key, metadata, record) = client.get(read_key)\n data = {\n \"key\": str(key),\n \"metadata\": metadata,\n \"record\": record,\n \"timestamp\": strftime(\"%Y-%m-%d %H:%M:%S\", gmtime())\n }\n # Close the connection to the Aerospike cluster\n client.close()\n return json.dumps({\"0\": data}, sort_keys=True, indent=2)\n\n\nif __name__ == \"__main__\":\n app.run()\n","sub_path":"aerospike-server-latency/web-app/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2029,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"98779156","text":"# -*- coding: utf-8 -*-\n\nimport logging\nimport time\nimport multiprocessing\nimport threading\nimport queue\n\nimport memcache\n\nfrom polaris_common import sharedmem\nfrom polaris_health import config, state, util\nfrom polaris_health.prober.probe import Probe\n\n\nLOG = logging.getLogger(__name__)\nLOG.addHandler(logging.NullHandler())\n\n# how long to wait(block) when reading from probe response queue\n# non-blocking will eat 100% cpu at low message rate\nPROBE_RESPONSES_QUEUE_WAIT = 0.050\n\n# how often to scan the state(and issue probe requests)\nSCAN_STATE_INTERVAL = 1 # 1s\n\n# the main load balancing state, initialized in Tracker's init\nSTATE = None\n# lock synchronizing access to the STATE between Tracker and StatePusher\nSTATE_LOCK = threading.Lock()\n# state timestamp is changed whenever a pool member state changes,\n# this in turn used by StatePusher to determine whether it needs \n# to push state into shared memory\nSTATE_TIMESTAMP = 0\n# how long to sleep after a state push before attempting a new push\nSTATE_PUSH_INTERVAL = 0.5\n\n\nclass StatePusher(threading.Thread):\n \n \"\"\"StatePusher pushes state updates into shared memory.\n \"\"\"\n\n def __init__(self):\n super(StatePusher, self).__init__()\n\n # flag the thread as daemon so it's abruptly killed\n # when its parent process exists\n self.daemon = True\n\n # shared memory client\n self.sm = sharedmem.MemcacheClient(\n [config.BASE['SHARED_MEM_HOSTNAME']],\n socket_timeout=config.BASE['SHARED_MEM_SOCKET_TIMEOUT'],\n server_max_value_length=config.BASE['SHARED_MEM_SERVER_MAX_VALUE_LENGTH'])\n\n # on startup do not attempt to push state\n self.state_ts = 0\n\n def run(self):\n while True:\n # initial values of states_ts should be set to 0\n # so we don't attempt a state push until STATE_TIMESTAMP changes\n if STATE_TIMESTAMP != self.state_ts:\n self.push_states()\n # sleep until the next iteration \n time.sleep(STATE_PUSH_INTERVAL)\n\n def push_states(self): \n # lock the state and generate its various forms\n global STATE_LOCK\n with STATE_LOCK:\n # generate ppdns distribution form of the state\n dist_form = STATE.to_dist_dict()\n # generate generic form of the state\n generic_form = util.instance_to_dict(STATE)\n\n # all memcache pushes must succeed in order to\n # reset state changed flag\n pushes_ok = 0\n\n # push PPDNS distribution form of the state\n val = self.sm.set(config.BASE['SHARED_MEM_PPDNS_STATE_KEY'],\n dist_form)\n if val is True:\n pushes_ok += 1\n else: \n log_msg = ('failed to write ppdns state to the shared memory')\n LOG.warning(log_msg)\n\n # push generic form of the state\n # add timestampt to the object\n generic_form['timestamp'] = STATE_TIMESTAMP\n val = self.sm.set(config.BASE['SHARED_MEM_GENERIC_STATE_KEY'],\n generic_form)\n if val is True:\n pushes_ok += 1\n else:\n log_msg = ('failed to write generic state to the shared memory')\n LOG.warning(log_msg)\n\n # push state timestamp last\n val = self.sm.set(config.BASE['SHARED_MEM_STATE_TIMESTAMP_KEY'],\n STATE_TIMESTAMP)\n if val is True:\n pushes_ok += 1\n else: \n log_msg = ('failed to write state timestamp to the shared memory')\n LOG.warning(log_msg)\n\n # if all memcache pushes are successful\n # set self.state_ts to STATE_TIMESTAMP so we don't attempt to\n # push again until STATE_TIMESTAMP changes\n if pushes_ok == 3:\n LOG.debug('synced state to the shared memory')\n self.state_ts = STATE_TIMESTAMP\n\n\nclass Tracker(multiprocessing.Process):\n\n \"\"\"Track the health status of backend servers and propagate it to \n shared memory.\n \"\"\"\n\n def __init__(self, prober_requests, prober_responses):\n \"\"\"\n args:\n prober_requests: multiprocessing.Queue(), \n queue to put new probes on\n prober_responses: multiprocessing.Queue(),\n queue to get processed probes from\n \"\"\"\n super(Tracker, self).__init__()\n\n self.prober_requests = prober_requests\n self.prober_responses = prober_responses\n\n # create health state table from the lb config\n global STATE\n STATE = state.State(config_obj=config.LB)\n\n def run(self):\n \"\"\"Main scheduling/processing loop\"\"\"\n\n # start StatePusher thread\n # must be started from here, not __init__, in order for \n # global variables to be seen across both tracker and pusher\n StatePusher().start()\n\n # run the first scan as soon as we start\n last_scan_state_time = 0\n\n global STATE_LOCK\n while True:\n # read probe response and process it\n try:\n # block with a small timeout,\n # non-blocking will load cpu needlessly\n probe = self.prober_responses.get(\n block=True, timeout=PROBE_RESPONSES_QUEUE_WAIT)\n except queue.Empty: # nothing on the queue\n pass\n else:\n with STATE_LOCK:\n self._process_probe(probe)\n\n # periodically iterate the state and issue new probe requests,\n # if there was a state change in the last SCAN_STATE_INTERVAL,\n # push it to shared mem\n if time.time() - last_scan_state_time > SCAN_STATE_INTERVAL:\n # update last scan state time\n last_scan_state_time = time.time()\n\n # iterate the state, issue new probe requests\n with STATE_LOCK:\n self._scan_state()\n\n def _process_probe(self, probe):\n \"\"\"Process probe, change the associated member status accordingly.\n \n args:\n probe: Probe() object\n \"\"\"\n LOG.debug('received {}'.format(str(probe))) \n\n # get a reference to the individual pool member \n # based on pool_name and member_ip\n for member in STATE.pools[probe.pool_name].members:\n if member.ip == probe.member_ip:\n break\n\n # set member status attributes \n member.status_reason = probe.status_reason\n \n ### probe success ###\n if probe.status:\n # reset the value of retries left to the parent's pool value\n member.retries_left = \\\n STATE.pools[probe.pool_name].monitor.retries\n\n # if member is in UP state, do nothing and return\n if member.status is True:\n return\n\n # member is either in DOWN state or a new member, bring it UP\n else:\n member.status = True\n\n ### probe failed ###\n else:\n # either a new member or a member is UP state\n if member.status is True or member.status is None:\n # more retries left?\n if member.retries_left > 0:\n # decrease the number of retries left by 1 and return\n member.retries_left -= 1\n return\n\n # out of retries, change state to DOWN\n else:\n member.status = False\n\n # member status is False, do nothing and return\n else:\n return\n\n # if we end up here, it means that there was a status change,\n # indicate this to State Pusher by updating global STATE_TIMESTAMP\n global STATE_TIMESTAMP\n STATE_TIMESTAMP = time.time()\n\n LOG.info('pool member status change: '\n 'member {member_ip}'\n '(name: {member_name} monitor IP: {monitor_ip}) '\n 'of pool {pool_name} is {member_status}, '\n 'reason: {member_status_reason}'\n .format(member_ip=probe.member_ip,\n member_name=member.name,\n monitor_ip=member.monitor_ip,\n pool_name=probe.pool_name, \n member_status=state.pool.pprint_status(member.status),\n member_status_reason=member.status_reason))\n # check if this change affects the overall pool's status\n # and generate a log message if it does\n self._change_pool_last_status(STATE.pools[probe.pool_name])\n\n def _scan_state(self):\n \"\"\"Iterate over the state, request health probes\"\"\"\n for pool_name in STATE.pools:\n pool = STATE.pools[pool_name]\n for member in pool.members:\n # request probe if required\n self._request_probe(pool, member)\n\n def _request_probe(self, pool, member):\n \"\"\"Request a probe if required (either the first probe\n or if it's time for a next one)\n \"\"\" \n request_probe = False\n\n # if member.last_probe_issued_time is not None, it means that\n # a probe had been issued for this member already,\n # check if it's time for a new one\n if member.last_probe_issued_time is not None: \n if time.time() - member.last_probe_issued_time \\\n >= pool.monitor.interval:\n request_probe = True\n\n # else this is the first time we're issuing a probe\n # set member.retries_left to the parent's pool monitor retries\n else:\n member.retries_left = pool.monitor.retries\n request_probe = True\n \n if request_probe:\n # issue probe\n probe = Probe(pool_name=pool.name,\n member_ip=member.ip,\n monitor=pool.monitor,\n monitor_ip=member.monitor_ip)\n\n self.prober_requests.put(probe) \n\n # update the time when the probe was issued\n member.last_probe_issued_time = time.time()\n \n #LOG.debug('requested {}'.format(str(probe)))\n\n def _change_pool_last_status(self, pool):\n \"\"\"Compare pool.last_status with pool.status, if different \n pool.last_status is set to pool.status and a log message is generated.\n \"\"\"\n if pool.last_status != pool.status:\n LOG.info('pool status change: pool {} is {}'.\n format(pool.name, state.pool.pprint_status(pool.status))) \n pool.last_status = pool.status\n\n","sub_path":"alternative-polaris/polaris_health/tracker/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":10655,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"60461476","text":"data = open(\"./data/p0.csv\", \"r\")\nbat = open(\"./data/batsman_index.csv\", \"w\")\nbowl = open(\"./data/bowler_index.csv\", \"w\")\nbatsmen = {}\nb1 = {}\nbatsmen_index = 0\nbowlers = {}\nb2 = {}\nbowlers_index =0\n\nfor line in data.readlines():\n line = line.split(',')\n if(line[0] not in batsmen.values()):\n batsmen[batsmen_index] = line[0]\n # b1[line[0]] = batsmen_index\n bat.write(line[0]+ ',' + str(batsmen_index) + '\\n')\n batsmen_index+=1\n\n if(line[1] not in bowlers.values()):\n bowlers[bowlers_index] = line[1]\n # b2[line[1]] = bowlers_index\n bowl.write(line[1]+ ',' + str(bowlers_index) + '\\n')\n bowlers_index+=1\n\n\nbat.close()\nbowl.close()","sub_path":"src/probcalc/CollaborativeFiltering/index_mapping.py","file_name":"index_mapping.py","file_ext":"py","file_size_in_byte":695,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"228597411","text":"\"\"\"Collection of datasets representing all viruses that infect human.\n\nMost of the sequences in these datasets were automatically downloaded\nfrom GenBank by filtering its list of all viral genomes (taxId:10239)\nfor those sequences whose host contains 'human'.\n\nNote that this uses versions of HIV (1 and 2) sequences in which\nthe LTRs have been stripped from both ends -- i.e., it contains\nthe 'hiv1_without_ltr' and 'hiv2_without_ltr' datasets rather than\nthe 'hiv1' and 'hiv2' datasets.\n\"\"\"\n\nimport sys\n\nfrom catch.datasets import DatasetCollection\n\n__author__ = 'Hayden Metsky '\n\n\nDATASETS = [\n 'ablv',\n 'achimota',\n 'aedes',\n 'aguacate',\n 'aichivirus_a',\n 'akabane',\n 'alethinophid_reptarenavirus',\n 'allpahuayo',\n 'amapari',\n 'ambe',\n 'andes',\n 'anhanga',\n 'anjozorobe',\n 'apmv',\n 'apoi',\n 'aravan',\n 'aroa',\n 'arumowot',\n 'b19',\n 'bagaza',\n 'banna',\n 'banzi',\n 'barmah_forest',\n 'bat_hepacivirus',\n 'bat_hepevirus',\n 'bat_sapovirus_tlc58',\n 'bear_canyon',\n 'beilong',\n 'betacoronavirus_1',\n 'bhanja',\n 'bk',\n 'bokeloh_bat',\n 'bouboui',\n 'bourbon',\n 'bovine_hepacivirus',\n 'bowe',\n 'bpv_3',\n 'brazoran',\n 'bruges',\n 'bujaru',\n 'bunyamwera',\n 'bwamba',\n 'cache_valley',\n 'california_encephalitis',\n 'candiru',\n 'canine_distemper',\n 'cano_delgadito',\n 'cao_bang',\n 'capim',\n 'caraparu',\n 'cardiovirus_a',\n 'cardiovirus_b',\n 'cedar',\n 'cell_fusing_agent',\n 'chandipura',\n 'chaoyang',\n 'chapare',\n 'chikungunya',\n 'clo_mor',\n 'colobus_monkey_papillomavirus',\n 'cosavirus_a',\n 'cowpox',\n 'crimean_congo',\n 'ctfv',\n 'cupixi',\n 'cxfv',\n 'dengue',\n 'dengue_1',\n 'dengue_2',\n 'dengue_3',\n 'dengue_4',\n 'dera_ghazi_khan',\n 'dhori',\n 'dobrava_belgrade',\n 'donggang',\n 'dugbe',\n 'duvenhage',\n 'eblv_1',\n 'eblv_2',\n 'ebola_nonzaire',\n 'ebola_zaire_with_2014',\n 'edge_hill',\n 'eee',\n 'entebbe_bat',\n 'enterovirus_a',\n 'enterovirus_b',\n 'enterovirus_c',\n 'enterovirus_d',\n 'eyach',\n 'feline_morbillivirus',\n 'fer_de_lance',\n 'fitzroy_river',\n 'flexal',\n 'fugong',\n 'gadgets_gully',\n 'gairo',\n 'gbv_c',\n 'gemycircularvirus_hvgcv1',\n 'gemykibivirus_2',\n 'giant_panda',\n 'goose_paramyxovirus_sf02',\n 'gorilla',\n 'great_island',\n 'guanarito',\n 'guaroa',\n 'hag1',\n 'hanko',\n 'hantaan',\n 'hantavirus_z10',\n 'hbov',\n 'heartland',\n 'hendra',\n 'hepacivirus_d',\n 'hepatitis_a',\n 'hepatitis_b',\n 'hepatitis_c',\n 'hepatitis_delta',\n 'hepatitis_e',\n 'herpesvirus_1',\n 'herpesvirus_2',\n 'herpesvirus_3',\n 'herpesvirus_4',\n 'herpesvirus_5',\n 'herpesvirus_6',\n 'herpesvirus_7',\n 'herpesvirus_8',\n 'hervk',\n 'hfcj',\n 'hiv1_without_ltr',\n 'hiv2_without_ltr',\n 'hpiv_1',\n 'hpiv_2',\n 'hpiv_3',\n 'hpiv_4',\n 'hpv',\n 'hrsv',\n 'hughes',\n 'human_coronavirus_229e',\n 'human_coronavirus_hku1',\n 'human_coronavirus_nl63',\n 'human_genital_associated_circular_dna',\n 'human_pegivirus_2',\n 'human_picobirnavirus',\n 'human_smacovirus_1',\n 'ikoma',\n 'ilheus',\n 'imjin',\n 'influenza_a',\n 'influenza_b',\n 'influenza_c',\n 'irkut',\n 'isfahan',\n 'jc',\n 'jeju',\n 'jev',\n 'jugra',\n 'junin',\n 'j_virus',\n 'kadam',\n 'kadipiro',\n 'kaeng_khoi',\n 'kamiti_river',\n 'kasokero',\n 'kedougou',\n 'kenkeme',\n 'keterah',\n 'kfd',\n 'khabarovsk',\n 'ki_polyomavirus',\n 'kokobera',\n 'lagos_bat',\n 'langat',\n 'lassa',\n 'latino',\n 'lcmv',\n 'le_dantec',\n 'leopards_hill',\n 'liao_ning',\n 'lloviu_cuevavirus',\n 'louping_ill',\n 'lujo',\n 'luna',\n 'lyssavirus_ozernoe',\n 'machupo',\n 'madrid',\n 'mamastrovirus',\n 'mammalian_1_bornavirus',\n 'manzanilla',\n 'maporal',\n 'mapuera',\n 'maraba',\n 'marburg',\n 'marituba',\n 'mastadenovirus_a',\n 'mastadenovirus_b',\n 'mastadenovirus_c',\n 'mastadenovirus_d',\n 'mastadenovirus_e',\n 'mastadenovirus_f',\n 'mastadenovirus_g',\n 'mayaro',\n 'mcv',\n 'measles',\n 'menangle',\n 'mercadeo',\n 'mers',\n 'metapneumovirus',\n 'modoc',\n 'mojiang',\n 'mokola',\n 'molluscum_contagiosum',\n 'monkeypox',\n 'montana_myotis_leukoencephalitis',\n 'montano',\n 'mopeia',\n 'mopeia_lassa_reassortant_29',\n 'morogoro',\n 'mossman',\n 'mssi2_225',\n 'mumps',\n 'mvev',\n 'nairobi_sheep_disease',\n 'nariva',\n 'nipah',\n 'norwalk',\n 'norway_rat_hepacivirus',\n 'nounane',\n 'ntaya',\n 'nyando',\n 'ochlerotatus_caspius',\n 'oliveros',\n 'omsk_hemorrhagiv_fever',\n 'o_nyong_nyong',\n 'orf',\n 'oriboca',\n 'oropouche',\n 'parana',\n 'parechovirus_a',\n 'parechovirus_b',\n 'parramatta_river',\n 'pbv1',\n 'phocine',\n 'pichinde',\n 'pirital',\n 'piscihepevirus_a',\n 'piv_5',\n 'porcine',\n 'powassan',\n 'ppbv',\n 'ppiv_1',\n 'pprv',\n 'ptlv_1',\n 'ptlv_2',\n 'punta_toro',\n 'puumala',\n 'qalyub',\n 'quang_binh',\n 'quezon',\n 'razdan',\n 'rhabdovirus',\n 'rhinovirus_a',\n 'rhinovirus_b',\n 'rift_valley_fever',\n 'rinderpest',\n 'rio_bravo',\n 'rodent_hepacivirus',\n 'rodent_torque_teno',\n 'rosavirus_a',\n 'ross_river',\n 'rotavirus_a',\n 'rotavirus_b',\n 'rotavirus_c',\n 'rotavirus_f',\n 'rotavirus_g',\n 'rotavirus_h',\n 'rotavirus_i',\n 'royal_farm',\n 'rsv',\n 'rubella',\n 'sabia',\n 'saboya',\n 'salehabad',\n 'salem',\n 'salivirus_a',\n 'sapporo',\n 'sars',\n 'sathuperi',\n 'saumarez_reef',\n 'seal_anellovirus',\n 'semliki_forest',\n 'sendai',\n 'seoul',\n 'sepik',\n 'sfnv',\n 'sfsv',\n 'sfts',\n 'shamonda',\n 'shimoni_bat',\n 'shuni',\n 'simbu',\n 'simian_41',\n 'simian_foamy',\n 'simian_torque_teno',\n 'sindbis',\n 'sin_nombre',\n 'slev',\n 'small_anellovirus',\n 'sosuga',\n 'spanish_goat_encephalitis',\n 'spondweni',\n 'sv40',\n 'tacaribe',\n 'tailam',\n 'tamiami',\n 'tanapox',\n 'tapara',\n 'tbev',\n 'tembusu',\n 'tete',\n 'thiafora',\n 'tho',\n 'thogoto',\n 'thottapalayam',\n 'tioman',\n 'tlmv',\n 'tofla',\n 'toros',\n 'torque_teno',\n 'torque_teno_canis',\n 'torque_teno_douroucouli',\n 'torque_teno_felis',\n 'torque_teno_indri',\n 'torque_teno_leptonychotes_weddelli',\n 'torque_teno_midi',\n 'torque_teno_mini',\n 'torque_teno_sus',\n 'torque_teno_tamarin',\n 'torque_teno_zalophus',\n 'tuhoko',\n 'tula',\n 'tupaia',\n 'uganda_s',\n 'unidentified_circular_ssdna',\n 'uriurana',\n 'urucuri',\n 'usutu',\n 'uukuniemi',\n 'vaccinia',\n 'variola',\n 'vee',\n 'vsiv',\n 'wee',\n 'wesselsbron',\n 'west_caucasion_bat',\n 'west_nile',\n 'whitewater_arroyo',\n 'wu_polyomavirus',\n 'wyeomyia',\n 'yaounde',\n 'yellow_fever',\n 'ymt',\n 'yogue',\n 'yokose',\n 'zerdali',\n 'zika'\n]\n\n\ndsc = DatasetCollection(DATASETS)\n\nsys.modules[__name__] = dsc\n","sub_path":"catch/datasets/collections/viruses_with_human_host.py","file_name":"viruses_with_human_host.py","file_ext":"py","file_size_in_byte":7168,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"59185108","text":"print(\"Welcome to MATRI-HITO!\")\nprint(\"\\n\")\nprint(\"Enter numbers of lines and complete MatrixA\")\n\nprint(\"\\n\")\nprint(\"How to use :\" )\nprint(\"Press q to quit to enter line1\")\nprint(\"Enter as many q as fill all the form to quit to enter lines of MatrixA\")\nprint(\"\\n\")\n\nimport csv\nLINE=[]\nline1=[]\nwhile True:\n line1_fact=input(\"ENTER:\")\n line1.append(line1_fact)\n print(line1)\n if \"q\" in line1:\n e=len(line1)-1\n line1=line1[0:e]\n restriction=len(line1)\n LINE.append(line1)\n print(LINE)\n break\nwhile True:\n line=[]\n lines_end=[\"q\"]*(restriction)\n\n for i in range(1,restriction+1):\n line_fact=input(\"ENTER:\")\n line.append(line_fact)\n print(line)\n LINE.append(line)\n print(LINE)\n\n\n if lines_end in LINE:\n E=len(LINE)-1\n LINE=LINE[0:E]\n print(\"\\n\")\n print(\"Here is MatrixA\")\n\n print(\"\\n\")\n\n\n\n \n \n with open(\"MatrixA\",\"w\") as f:\n w=csv.writer(f,delimiter=\",\")\n x=len(LINE)-1\n for i in range(0,x+1):\n w.writerow(LINE[i])\n with open(\"MatrixA\",\"r\") as f:\n r=csv.reader(f,delimiter=\",\")\n for lines in r:\n print(\"|\".join(lines))\n\n break\n\nprint(\"\\n\")\n\n\n#MatrixB  gets started\n\nprint(\"\\n\")\nprint(\"Well, complete MatrixB\")\n\nprint(\"\\n\")\nprint(\"Press q to quit to enter line1\")\n\nprint(\"\\n\")\n\n\n\nLINE_2=[]\nline1_2=[]\nwhile True:\n line1_2_fact=input(\"ENTER:\")\n line1_2.append(line1_2_fact)\n print(line1_2)\n if \"q\" in line1_2:\n e=len(line1_2)-1\n line1_2=line1_2[0:e]\n restriction_2=len(line1_2)\n LINE_2.append(line1_2)\n print(LINE_2)\n break\nfor i in range(1,restriction):\n line_2=[]\n \n\n for i in range(1,restriction_2+1):\n line_fact_2=input(\"ENTER:\")\n line_2.append(line_fact_2)\n print(line_2)\n \n LINE_2.append(line_2)\n print(LINE_2)\n\nprint(\"\\n\")\n\np=len(LINE_2)\nq=restriction_2\n\nROW=[]\nfor j in range(0,q):\n rows=[]\n for i in range(0,p):\n rows.append(LINE_2[i][j])\n ROW.append(rows)\n\n\nprint(\"Here is MatrixB\")\n\nprint(\"\\n\")\n\nwith open(\"MatrixB\",\"w\") as f:\n w=csv.writer(f,delimiter=\",\")\n x=len(LINE_2)-1\n for i in range(0,x+1):\n w.writerow(LINE_2[i])\nwith open(\"MatrixB\",\"r\") as f:\n r=csv.reader(f,delimiter=\",\")\n for lines_2 in r:\n print(\"|\".join(lines_2))\n \nprint(\"\\n\")\n\n\n\nprint(\"Here is MatrixA and MatrixB\")\n\nprint(\"\\n\")\n\nprint(\"MatrixA\")\nwith open(\"MatrixA\",\"r\") as f:\n r=csv.reader(f,delimiter=\",\")\n for lines in r:\n print(\"|\".join(lines))\n\n\nprint(\"\\n\")\nprint(\"MatrixB\")\nwith open(\"MatrixB\",\"r\") as f:\n r=csv.reader(f,delimiter=\",\")\n for lines_2 in r:\n print(\"|\".join(lines_2))\nprint(\"\\n\")\n\n\n\n\n\nprint(\"Okay, I'll multiply MatrixA and MatrixB\")\n\nprint(\"\\n\")\n\nprint(\"...make it!\")\n\nprint(\"\\n\")\n\nprint(\"This is MatrixC!\")\n\nprint(\"\\n\")\n#translate str into int\n\nfor I in range(0,restriction):\n for J in range(0,len(LINE)):\n LINE[J][I]=int(LINE[J][I])\n\n\nfor I in range(0,restriction):\n for J in range(0,len(ROW)):\n ROW[J][I]=int(ROW[J][I])\n \n\n\n\n\n\nC=[]\nfor a in range(0,len(LINE)):\n linesC=[]\n for b in range(0,len(ROW)):\n Multipled=[]\n for i in range(0,restriction):\n m=int(LINE[a][i]*ROW[b][i])\n Multipled.append(m)\n f=0\n for i in Multipled:\n f +=i\n linesC.append(f) \n C.append(linesC)\n \n\n\n\nwith open(\"MatrixC\",\"w\") as f:\n w=csv.writer(f,delimiter=\",\")\n c=len(C)\n for i in range(0,c):\n w.writerow(C[i])\nwith open(\"MatrixC\",\"r\") as f:\n r=csv.reader(f,delimiter=\",\")\n for LINEC in r:\n print(\"|\".join(LINEC))\n \n\n \n\n","sub_path":"MATRI-HITO.py","file_name":"MATRI-HITO.py","file_ext":"py","file_size_in_byte":3755,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"295756544","text":"\n\nfrom xai.brain.wordbase.nouns._hun import _HUN\n\n#calss header\nclass _HUNS(_HUN, ):\n\tdef __init__(self,): \n\t\t_HUN.__init__(self)\n\t\tself.name = \"HUNS\"\n\t\tself.specie = 'nouns'\n\t\tself.basic = \"hun\"\n\t\tself.jsondata = {}\n","sub_path":"xai/brain/wordbase/nouns/_huns.py","file_name":"_huns.py","file_ext":"py","file_size_in_byte":217,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"44774634","text":"import nodeitems_utils\nimport bpy\nfrom bpy.types import NodeTree, Node, NodeSocket, Operator, PropertyGroup\nimport json\n\nblender_classes = []\n\nRUST_NODES = []\n\n\nclass LogicNodeTree(NodeTree):\n '''A Logic node tree type'''\n bl_idname = 'LogicNodeTree'\n bl_label = 'Logic Node Tree'\n bl_icon = 'BLENDER'\n\n is_just_opened = True\n\n def update_nodes(self):\n for n in self.nodes:\n n.init(self)\n\n def update(self):\n if self.is_just_opened:\n self.is_just_opened = False\n self.update_nodes()\n\n def serialize(self):\n node_tree = {}\n nodes = []\n links = []\n\n for l in self.links:\n link = {}\n link[\"from_node\"] = l.from_socket.node.name\n link[\"to_node\"] = l.to_socket.node.name\n link[\"from_pin\"] = l.from_socket.name\n link[\"to_pin\"] = l.to_socket.name\n links.append(link)\n if hasattr(l.from_socket, 'default_value') and hasattr(l.to_socket, 'default_value'):\n l.to_socket.default_value = l.from_socket.default_value\n for n in self.nodes:\n serialized_node = {}\n serialized_node[\"node_type\"] = n.bl_idname\n node = n.serialize()\n serialized_node[\"node\"] = node[\"node\"]\n nodes.append(serialized_node)\n\n node_tree['nodes'] = nodes\n node_tree['links'] = links\n\n return json.dumps(node_tree)\n\n\nclass NodeSocketLogicExecution(NodeSocket):\n bl_idname = 'NodeSocketLogicExecution'\n bl_label = 'Script Execution Socket'\n\n def draw(self, context, layout, node, text):\n layout.label(text=text)\n\n def draw_color(self, context, node):\n return (1.0, 0.0, 1.0, 1.0)\n\n\nclass LogicNodeBase(Node):\n bl_idname = 'LogicNodeBase'\n bl_label = 'Logic Node Base'\n\n @classmethod\n def poll(cls, ntree):\n return ntree.bl_idname == 'LogicNodeTree'\n\n def copy(self, node):\n print(\"copied node\", node)\n\n def free(self):\n print(\"Node removed\", self)\n\n\nclass FieldData:\n def __init__(self, name, value, is_input):\n self.name = str(name)\n self.is_input = is_input\n\n self.rust_type = str(value[\"pin_type\"])\n if \"value\" in value:\n self.value = value[\"value\"]\n self.value_type = type(self.value)\n\n if self.rust_type == \"LogicExecution\":\n self.socket_type = \"NodeSocketLogicExecution\"\n elif self.rust_type == \"u32\" or self.rust_type == \"i32\" or self.rust_type == \"i8\" or self.rust_type == \"u8\" or self.rust_type == \"i16\" or self.rust_type == \"u16\":\n self.socket_type = \"NodeSocketInt\"\n elif self.rust_type == \"f32\" or self.rust_type == \"f64\":\n self.socket_type = \"NodeSocketFloat\"\n elif self.rust_type == \"String\":\n self.socket_type = \"NodeSocketString\"\n elif self.value_type is int:\n self.socket_type = \"NodeSocketInt\"\n elif self.value_type is float:\n self.socket_type = \"NodeSocketFloat\"\n elif self.value_type is bool:\n self.socket_type = \"NodeSocketBool\"\n elif self.value_type is str:\n self.socket_type = \"NodeSocketString\"\n\n\ndef register_nodes(inox_engine):\n from INOX import inox_blender\n inox_blender.register_nodes(inox_engine)\n\n global RUST_NODES\n node_items = {}\n for n in RUST_NODES:\n bpy.utils.register_class(n)\n if n.category not in node_items:\n node_items[n.category] = []\n node_items[n.category].append(\n nodeitems_utils.NodeItem(n.name, label=n.name))\n\n for key in node_items:\n nodeitems_utils.register_node_categories(\n key, [nodeitems_utils.NodeCategory(\n key, key, items=node_items[key])])\n\n\ndef create_node_from_data(node_name, base_class, category, description, serialized_class):\n from INOX import utils\n base_type = utils.gettype(base_class)\n\n def extract(dictionary, is_input):\n types = \"inputs\"\n if is_input == False:\n types = \"outputs\"\n fields_data = []\n for k in dictionary[\"node\"][types]:\n f = FieldData(k, dictionary[\"node\"][types][k], is_input)\n fields_data.append(f)\n return fields_data\n\n fields_dictionary = json.loads(serialized_class)\n fields_input = extract(fields_dictionary, True)\n fields_output = extract(fields_dictionary, False)\n\n def update_sockets(new_values, node_values):\n for v in node_values:\n exists = False\n for n in new_values:\n if v.name == n[0]:\n exists = True\n if not exists:\n node_values.remove(v)\n\n for n in new_values:\n exists = False\n for v in node_values:\n if v.name == n[0]:\n exists = True\n if not exists:\n node_values.new(n[1], n[0])\n\n def deserialize(self):\n inputs = []\n outputs = []\n for f in fields_input:\n inputs.append((f.name, f.socket_type))\n for f in fields_output:\n outputs.append((f.name, f.socket_type))\n update_sockets(inputs, self.inputs)\n update_sockets(outputs, self.outputs)\n\n def serialize_fields(self, dictionary):\n for f in fields_input:\n if f.rust_type != \"LogicExecution\":\n i = [x for x in self.inputs if x.name == f.name]\n if len(i) > 0 and hasattr(i[0], \"default_value\"):\n dictionary[\"node\"][\"inputs\"][f.name][\"value\"] = i[0].default_value\n for f in fields_output:\n if f.rust_type != \"LogicExecution\":\n i = [x for x in self.outputs if x.name == f.name]\n if len(i) > 0 and hasattr(i[0], \"default_value\"):\n dictionary[\"node\"][\"outputs\"][f.name][\"value\"] = i[0].default_value\n return dictionary\n\n def serialize(self):\n output = self.serialize_fields(\n fields_dictionary)\n return output\n\n def init(self, context):\n self.deserialize()\n\n node_class = type(\n node_name,\n (base_type, Node, ),\n {\n \"bl_idname\": node_name,\n \"bl_label\": node_name,\n \"name\": node_name,\n \"category\": category,\n \"description\": description,\n \"init\": init,\n \"deserialize\": deserialize,\n \"serialize\": serialize,\n \"serialize_fields\": serialize_fields,\n }\n )\n\n RUST_NODES.append(node_class)\n\n\nclass LogicNodeCategory(nodeitems_utils.NodeCategory):\n @ classmethod\n def poll(cls, context):\n return context.space_data.tree_type == 'LogicNodeTree'\n\n\n# make a list of node categories for registration\nnode_categories = []\n\n\nclass OpenInLogicEditor(Operator):\n bl_idname = \"inox.open_in_logic_editor\"\n bl_label = \"Open Logic Editor\"\n\n def execute(self, context):\n for area in bpy.context.screen.areas:\n if area.type == 'VIEW_3D':\n area.type = 'NODE_EDITOR'\n area.spaces.active.node_tree = context.object.inox_properties.logic\n return {'FINISHED'}\n\n\nblender_classes.append(NodeSocketLogicExecution)\nblender_classes.append(LogicNodeTree)\nblender_classes.append(LogicNodeBase)\n\nblender_classes.append(OpenInLogicEditor)\n\n\ndef register():\n for cls in blender_classes:\n bpy.utils.register_class(cls)\n\n nodeitems_utils.register_node_categories(\"LOGIC_NODES\", node_categories)\n\n\ndef unregister():\n nodeitems_utils.unregister_node_categories(\"LOGIC_NODES\")\n\n for cls in blender_classes:\n bpy.utils.unregister_class(cls)\n","sub_path":"crates/blender/inox_blender/INOX/node_tree.py","file_name":"node_tree.py","file_ext":"py","file_size_in_byte":7686,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"133649506","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Apr 6 14:36:32 2021\n\n@author: kariln\n\"\"\"\n\nimport pandas as pd\nimport math\n\ndata = pd.read_csv(r'C:\\Master\\disp_euclid (4).csv', header = 0, sep=',', index_col=False)\n#SURFACE INFLUENZE ZONE\ndata['SIZ'] = None\nseed = 0.0023 #Approximate global size of seeds\ndata['sub_z'] = 0.005 #z-coordinate of the substrate\ntime_steps = data['t'].unique()\nSIZ_V = 4/3*math.pi*data['road_width'].iloc[0]**3\nSIZ_nodes_tot = SIZ_V/seed**3\nfor index,row in data.iterrows(): \n data_time = data[data['t'] == row['t']]\n n_nodes = 0\n for i,r in data_time.iterrows(): \n dx = abs(row['x']-r['x'])\n dy = abs(row['y']-r['y'])\n dz = abs(row['z']-r['z'])\n if dx< 3*row['road_width'] and dy< 3*row['road_width'] and dz< 3*row['road_width']:\n n_nodes += 1\n else:\n pass\n if abs(row['z'] - row['sub_z']) < 3*row['road_width']: #checking if the substrate is within the SIZ\n h = row['road_width'] - row['z'] - row['sub_z'] # height of spherical cap\n r = row['road_width']\n sub_V = math.pi*h**2/3*(3*r-h)\n sub_nodes = sub_V/seed**3\n n_nodes += sub_nodes\n data['SIZ'].iloc[index] = n_nodes/SIZ_nodes_tot\n print(index)\ndata.to_csv('disp_SIZ.csv',encoding='utf-8', index=False) \n","sub_path":"Preprocessing/feature_extraction/siz.py","file_name":"siz.py","file_ext":"py","file_size_in_byte":1232,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"199182003","text":"import os\nimport sys\nimport subprocess\nfrom subprocess import Popen\nimport datetime\nimport git\nimport shutil \nimport csv\n\nrepoDir = r'/home/vinay/workspace/benchmark/cibugs'\n\n#reportFile = open(r'C:\\PHD\\CI_Bugs\\pushCommitreport.txt', 'a+')\n\nhardCheckout = True\nsrcFolder = ''\ndestFolder = 'repo'\n\nrepoName = 'git clone https://github.com/CI-Bugs/repo.git/'\n\nsubprocess.call(repoName, shell=True, cwd = repoDir) \n\nwith open(r'/home/vinay/workspace/benchmark/cibugs/FailingPassing.csv') as csv_file:\n\n csv_reader = csv.reader(csv_file, delimiter=',')\n rows = list(csv_reader)\n\n for row in rows[1:]:\n\n branchName = row[0]\n\n #Create a new branch in dest repo to checkin the commit\n #cmd = 'git checkout -b ' + branchName\n cmd = 'git checkout --orphan ' + branchName \n subprocess.call(cmd, shell=True, cwd = repoDir+\"/\"+destFolder) \n\n print(row)\n\n line = row[1].strip()\n\n print(line)\n\n url_repo = line.split(\"commit\")[0]\n srcFolder = url_repo.split(\"/\")[-2]\n\n print(\"Project Name : \", srcFolder)\n\n url_repo = url_repo[0:-1] + str(\".git\")\n\n print (\"Repo URL : \", url_repo) \n\n cmd = 'git clone ' + url_repo\n subprocess.call(cmd, shell=True, cwd = repoDir) \n\n msgCommit = 'Buggy Commit'\n\n for line in row[1:]:\n commit = line.split(\"commit\")[1][1:]\n\n print (\"Commit : \", commit)\n\n if(hardCheckout == False):\n cmd = 'git checkout ' + commit\n subprocess.call(cmd, shell=True, cwd = repoDir+\"/\"+srcFolder) \n else:\n cmd = 'git fetch origin ' + commit \n subprocess.call(cmd, shell=True, cwd = repoDir+\"/\"+srcFolder) \n\n cmd = 'git reset --hard ' + commit \n subprocess.call(cmd, shell=True, cwd = repoDir+\"/\"+srcFolder) \n\n cmd = 'git rev-parse --verify HEAD ' \n subprocess.call(cmd, shell=True, cwd = repoDir+\"/\"+srcFolder) \n\n cmd = \"cp -r * ../\"+destFolder\n subprocess.call(cmd, shell=True, cwd = repoDir+\"/\"+srcFolder) \n cmd = \"git add .\"\n\n subprocess.call(cmd, shell=True, cwd = repoDir+\"/\"+destFolder) \n\n cmd = \"git commit --allow-empty -m '\" + msgCommit + \" : \" + line + \"'\"\n #cmd = \"git commit -m '\" + msgCommit + \" : \" + line + \"'\"\n #cmd = \"git commit -m 'comiit'\"\n subprocess.call(cmd, shell=True, cwd = repoDir+\"/\"+destFolder) \n\n cmd = \"git push origin \" + branchName\n subprocess.call(cmd, shell=True, cwd = repoDir+\"/\"+destFolder) \n\n msgCommit = 'Fixed Commit' \n\n cmd = \"rm -rf \" + srcFolder\n subprocess.call(cmd, shell=True, cwd = repoDir) \n\n cmd = \"rm -rf \" + destFolder + \"/*\"\n subprocess.call(cmd, shell=True, cwd = repoDir) \n\n\n\n\n","sub_path":"commitCIbugs/commit.py","file_name":"commit.py","file_ext":"py","file_size_in_byte":2983,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"525778847","text":"from torch import nn\nimport torch\n\ndef cnn_categorization_improved(netspec_opts):\n \"\"\"\n Constructs a network for the improved categorization model.\n\n Arguments\n --------\n netspec_opts: (dictionary), the improved network's architecture.\n\n Returns\n -------\n A categorization model which can be trained by PyTorch\n\n \"\"\"\n # instantiate an instance of nn.Sequential\n net = nn.Sequential()\n device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')\n\n # add layers as specified in netspec_opts to the network\n kernal_size = netspec_opts['kernel_size']\n num_filters = netspec_opts['num_filters']\n stride = netspec_opts['stride']\n layer_type = netspec_opts['layer_type']\n previous = 0\n for index, (size_kernal, filters_num, strid, type_layer) in enumerate(\n zip(kernal_size, num_filters, stride, layer_type)):\n if type_layer == \"conv\":\n padding = (size_kernal - 1) / 2\n if index == 0:\n previous = filters_num\n net.add_module(\"conv\" + str(index), nn.Conv2d(3, filters_num, size_kernal, strid, int(padding)))\n else:\n net.add_module(\"conv\" + str(index), nn.Conv2d(previous, filters_num, size_kernal, strid, int(padding)))\n previous = filters_num\n if type_layer == \"bn\":\n net.add_module(\"bn\" + str(index), nn.BatchNorm2d(num_filters[index - 1]))\n if type_layer == \"relu\":\n net.add_module(\"relu\" + str(index), nn.ReLU())\n if type_layer == \"pool\":\n net.add_module(\"pool\" + str(index), nn.AvgPool2d(size_kernal, strid, 0))\n if type_layer == \"drop\":\n net.add_module(\"drop\" + str(index), nn.Dropout2d(0.2))\n net.to(device)\n return net\n","sub_path":"cnn_categorization_improved.py","file_name":"cnn_categorization_improved.py","file_ext":"py","file_size_in_byte":1782,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"510820962","text":"import os\nimport time\nimport sys\nimport weaviate\nfrom integration.crud import IntegrationTestCrud\nfrom integration.graphql import TestGraphQL\nfrom integration.classification import contextual\nfrom integration.integration_util import TestFailedException\n\ngql_get_sophie_scholl = \"\"\"\n{\n Get {\n Person (where: {\n path: [\"id\"]\n operator: Equal\n valueString: \"594b7827-f795-40d0-aabb-5e0553953dad\"\n }){\n name\n _additional {\n id\n }\n }\n }\n}\n\"\"\"\n\ndef query_data(client):\n print(\"Test query\")\n expected_name = \"Sophie Scholl\"\n client.data_object.create({\"name\": expected_name}, \"Person\", \"594b7827-f795-40d0-aabb-5e0553953dad\")\n time.sleep(2.0)\n result = client.query.raw(gql_get_sophie_scholl)\n if result[\"data\"][\"Get\"][\"Person\"][0][\"name\"] != expected_name:\n raise TestFailedException(\"Query result is wrong\")\n\n\ndef creating_schema(client):\n print(\"Checking if weaviate is reachable\")\n if not client.is_ready():\n raise TestFailedException(\"Weaviate not reachable\")\n\n if client.schema.contains():\n raise TestFailedException(\"No schema should be present\")\n\n print(\"Load a schema\")\n schema_json_file = os.path.join(os.path.dirname(__file__), \"people_schema.json\")\n client.schema.create(schema_json_file)\n\n if not client.schema.contains():\n raise TestFailedException(\"Weaviate does not contain loaded schema\")\n \n original_schema = weaviate.util._get_dict_from_object(schema_json_file)\n if not client.schema.contains(original_schema):\n raise TestFailedException(\"Loaded schema does not match the one from Weaviate!\")\n\n single_class = {\n \"class\": \"Barbecue\",\n \"description\": \"Barbecue or BBQ where meat and vegetables get grilled\"\n }\n client.schema.create_class(single_class)\n prop = {\n \"dataType\": [\"string\"],\n \"description\": \"how hot is the BBQ in C\",\n \"name\": \"heat\",\n }\n client.schema.property.create(\"Barbecue\", prop)\n classes = client.schema.get()['classes']\n found = False\n for class_ in classes:\n if class_[\"class\"] == \"Barbecue\":\n found = len(class_['properties']) == 1\n if not found:\n raise TestFailedException(\"Class property not added properly\")\n\n\nif __name__ == \"__main__\":\n print(\"Weaviate should be running at local host 8080\")\n client = weaviate.Client(\"http://localhost:8080\")\n creating_schema(client)\n integration = IntegrationTestCrud(client)\n integration.test_crud()\n query_data(client)\n\n gql_integration = TestGraphQL(client)\n gql_integration.get_data()\n gql_integration.aggregate_data()\n\n contextual(client)\n\n print(\"Integration test finished successfully\")\n","sub_path":"integration/client_functions.py","file_name":"client_functions.py","file_ext":"py","file_size_in_byte":2721,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"588564758","text":"import pymysql\r\nimport threading\r\n# 12.38\r\ndb = pymysql.connect(\r\n \"localhost\",\r\n \"root\",\r\n \"edu123456\",\r\n \"hdkt_dev\",\r\n use_unicode=True,\r\n charset=\"utf8\")\r\ncursor = db.cursor()\r\ndef sp(data):\r\n db_temp = pymysql.connect(\r\n \"localhost\",\r\n \"root\",\r\n \"edu123456\",\r\n \"hdkt_dev\",\r\n use_unicode=True,\r\n charset=\"utf8\")\r\n cursor_temp = db_temp.cursor()\r\n sql = 'UPDATE down2 SET fp=%s WHERE id=%s'\r\n for x in data:\r\n cid = x[0]\r\n filepath = x[1]\r\n filepath=filepath+'/'+x[2]\r\n filepath = filepath.replace(' ', '') \r\n print(filepath)\r\n cursor_temp.execute(sql, (filepath, cid))\r\n db_temp.commit()\r\n cursor.close()\r\n db_temp.close()\r\n\r\ndef getdata():\r\n sql = 'SELECT id,path,filename FROM down2 WHERE ok=0 '\r\n cursor.execute(sql)\r\n data = cursor.fetchall()\r\n return data\r\n\r\n\r\ndef work():\r\n data = getdata()\r\n dataLen = len(data)\r\n x = dataLen // 15\r\n Thead = []\r\n for r in range(0, 15):\r\n t = threading.Thread(target=sp, args=(data[r * x:r * x + x], ))\r\n Thead.append(t)\r\n t = threading.Thread(target=sp, args=(data[x * 15:dataLen], ))\r\n\r\n Thead.append(t)\r\n for t in Thead:\r\n t.start()\r\n\r\n for t in Thead:\r\n t.join()\r\nif __name__ == '__main__':\r\n work()\r\n ","sub_path":"教育网站/problem/splite.py","file_name":"splite.py","file_ext":"py","file_size_in_byte":1354,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"617168864","text":"# Efficiency class\n\nfrom .fmath import *\nfrom scipy.interpolate import interp1d\n\nEFF_TYPES = ['uniform', 'spline']\n\nclass Efficiency:\n def __init__(self, func_type='uniform', control_points=None):\n if func_type not in EFF_TYPES:\n raise Exception('Efficiency function type is not known; select from ', EFF_TYPES)\n self.func_type = func_type\n self.eff_spline = interp1d(control_points[:,0], control_points[:,1],\n kind='cubic', bounds_error=False, fill_value='extrapolate') if func_type=='spline' else None\n \n def __call__(self, energy):\n if self.func_type == 'uniform':\n return 1.0\n elif self.func_type == 'spline':\n return np.heaviside(self.eff_spline(energy), 0.0) * self.eff_spline(energy)","sub_path":"efficiency.py","file_name":"efficiency.py","file_ext":"py","file_size_in_byte":778,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"626841474","text":"###########################################################################\n# In this section, we set the user authentication, app ID, and how\n# we want to update the model. Change these strings to run your own example.\n###########################################################################\n\nUSER_ID = 'YOUR_USER_ID_HERE'\n# Your PAT (Personal Access Token) can be found in the portal under Authentification\nPAT = 'YOUR_PAT_HERE'\nAPP_ID = 'YOUR_APP_ID_HERE'\n# Change these to update your own model \nMODEL_ID = 'petsID'\nMODEL_NAME = 'newname'\nCONCEPT_ID_1 = 'birds'\nCONCEPT_ID_2 = 'hurd'\n\n##########################################################################\n# YOU DO NOT NEED TO CHANGE ANYTHING BELOW THIS LINE TO RUN THIS EXAMPLE\n##########################################################################\n\nfrom clarifai_grpc.channel.clarifai_channel import ClarifaiChannel\nfrom clarifai_grpc.grpc.api import resources_pb2, service_pb2, service_pb2_grpc\nfrom clarifai_grpc.grpc.api.status import status_code_pb2\n\nchannel = ClarifaiChannel.get_grpc_channel()\nstub = service_pb2_grpc.V2Stub(channel)\n\nmetadata = (('authorization', 'Key ' + PAT),)\n\nuserDataObject = resources_pb2.UserAppIDSet(user_id=USER_ID, app_id=APP_ID)\n\npatch_models_response = stub.PatchModels(\n service_pb2.PatchModelsRequest(\n user_app_id=userDataObject,\n action=\"overwrite\",\n models=[\n resources_pb2.Model(\n id=MODEL_ID,\n name=MODEL_NAME,\n output_info=resources_pb2.OutputInfo(\n data=resources_pb2.Data(\n concepts=[\n resources_pb2.Concept(id=CONCEPT_ID_1),\n resources_pb2.Concept(id=CONCEPT_ID_2)\n ]\n ),\n output_config=resources_pb2.OutputConfig(\n concepts_mutually_exclusive=True,\n closed_environment=True,\n )\n )\n )\n ]\n ),\n metadata=metadata\n)\n\nif patch_models_response.status.code != status_code_pb2.SUCCESS:\n print(patch_models_response.status)\n raise Exception(\"Patch models failed, status: \" + patch_models_response.status.description)\n","sub_path":"code_snippets/api-guide/model/create_get_update_delete/py/update_model_name_configuration.py","file_name":"update_model_name_configuration.py","file_ext":"py","file_size_in_byte":2270,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"33129294","text":"from tkinter import *\r\nfrom tkinter import messagebox\r\nfrom tkinter import simpledialog\r\n\r\n\r\ndef display():\r\n messagebox.showinfo(\"Yandex.Taxi profitability\", x)\r\n\r\n\r\nroot = Tk()\r\nroot.title(\"Yandex.Taxi profitability\")\r\nroot.geometry(\"300x250\")\r\nmessagebox.showinfo(\"Yandex.Taxi profitability\",\r\n 'Привет эта программа предназначена для высчитывания выгодности поездки на Yandex.Taxi')\r\nkm = simpledialog.askinteger(\"КМ\", \"Сколько км хочешь проехать?\")\r\npricekm = simpledialog.askinteger(\"Цена КМ\", \"Сколько стоит 1 км?\")\r\nprice = simpledialog.askinteger(\"Цена Подачи\", \"Сколько стоит подача?\")\r\n\r\nif km <= 2: km = 0\r\nb = (km * pricekm) + price\r\nif b > 35: x=w= ('Езжай на iTaxi, YT стоит-', b)\r\nelse: x=q=('Езжай на Yandex.taxi поездака будет стоить-',b)\r\n\r\n\r\nmessage_button = Button(text=\"Посчитать\", command=display)\r\nmessage_button.place(relx=.5, rely=.5, anchor=\"c\")\r\n\r\nroot.mainloop()\r\n","sub_path":"second.py","file_name":"second.py","file_ext":"py","file_size_in_byte":1100,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"88245588","text":"import numpy as np\nimport pandas as pd\nfrom ast import literal_eval\nfrom sklearn.feature_extraction.text import CountVectorizer\nfrom sklearn.metrics.pairwise import cosine_similarity\n\n# image로 인식한 재료\ningredients = np.load('./mini_project/graph/ingredient.npy')\ningred = []\nfor source in ingredients:\n if source == 'carrot':\n source = '당근'\n elif source == 'chicken':\n source = '닭'\n elif source == 'egg':\n source = '계란 달걀'\n elif source == 'fish':\n source = '고등어 삼치 꽁치'\n elif source == 'flour':\n source = '밀가루'\n elif source == 'mashroom':\n source = '버섯'\n elif source == 'meat':\n source = '고기 소고기 돼지고기 '\n elif source == 'onion':\n source = '양파'\n elif source == 'paprika':\n source = '파프리카'\n else:\n source = '감자'\n ingred.append(source)\n\n# recipe_data\nca = pd.read_csv('./mini_project/recipe/recipe_carrot.csv', encoding= \"utf-8\", engine ='python')\nch = pd.read_csv('./mini_project/recipe/recipe_chicken.csv', encoding= \"utf-8\", engine ='python')\negg = pd.read_csv('./mini_project/recipe/recipe_egg.csv', encoding= \"utf-8\", engine ='python')\nfs = pd.read_csv('./mini_project/recipe/recipe_fish7.csv', encoding= \"utf-8\", engine ='python')\nfl = pd.read_csv('./mini_project/recipe/recipe_flour8.csv', encoding= \"utf-8\", engine ='python')\nms = pd.read_csv('./mini_project/recipe/recipe_mashroom.csv', encoding= \"utf-8\", engine ='python')\nmt = pd.read_csv('./mini_project/recipe/recipe_meat.csv', encoding= \"utf-8\", engine ='python')\non = pd.read_csv('./mini_project/recipe/recipe_onion.csv', encoding= \"utf-8\", engine ='python')\npa = pd.read_csv('./mini_project/recipe/recipe_paprika.csv', encoding= \"utf-8\", engine ='python')\npo = pd.read_csv('./mini_project/recipe/recipe_potato.csv', encoding= \"utf-8\", engine ='python')\n\nrecipe = pd.concat([ca, ch, egg, fs, fl, ms, mt, on, pa, po]).dropna()\nrecipe['recipe_source'] = recipe['recipe_source'].apply(literal_eval)\n\nrecipe['recipe_source'] = recipe['recipe_source'].apply(lambda x: \" \".join(x))\n\n# 단어 토큰화\nvector = CountVectorizer(ngram_range=(1, 1)) # 단어 묶음을 1개부터 1개까지 설정\nvector.fit(ingred) \nc_vector_recipe = vector.transform(recipe['recipe_source']) # 변환\nc_vector_ingred = vector.transform(ingred)\n\n# 코사인 유사도를 구한 벡터를 미리 저장\n'''\ningred_c_sim = cosine_similarity(c_vector_ingred, c_vector_recipe).argsort()[:, ::-1] # 내림차순 정렬\nprint(ingred_c_sim.shape)\n\nsim_index = ingred_c_sim[:3]\n\nrecipe_recommend = [i[0]for i in sim_index]\n\nprint(recipe.iloc[recipe_recommend])\n'''\ningred_c_sim = cosine_similarity(c_vector_ingred, c_vector_recipe)\n\ningred_sim_sum = ingred_c_sim.sum(axis = 1)\nprint(ingred_sim_sum)\n\nrecipe_best = np.argmax(ingred_sim_sum)\nprint(recipe_best)\n\nprint(recipe.iloc[recipe_best])","sub_path":"project/project01_ingred_recipe/comp04_recipe_recomend.py","file_name":"comp04_recipe_recomend.py","file_ext":"py","file_size_in_byte":2960,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"547587502","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nimport json\nimport os\nimport re\nimport sqlite3\nimport sys\nimport time\nimport traceback\n\nfrom dpkg import parse\nfrom dpkg import poll\n\ndef db_init(status_file):\n # poll status file\n status_obj = poll.poll(status_file)\n \n # initialize sqlite3\n conn = sqlite3.connect(\":memory:\")\n db_create(conn)\n\n # parse status fileobject, load into database\n db_status_load(conn, status_obj)\n\n # kill that big string obj\n del status_obj\n\n # return ready database handle\n return conn\n\ndef db_query(conn, query):\n db_resp = conn.execute(query).fetchall()\n return db_resp\n\ndef db_create(conn):\n c = conn.cursor()\n\n c.execute('PRAGMA temp_store=MEMORY;')\n c.execute('PRAGMA journal_mode=MEMORY;')\n\n # two tables packages, and a dependency index \n c.execute('create table if not exists packages (packageid integer primary key autoincrement, packagename text, description blob);')\n c.execute('create table if not exists depends (packageid int, dependencyid int, alternate int);')\n c.execute('create table if not exists alternates (packageid int, dependencyid int, alternateid int);')\n conn.commit()\n\ndef db_listPackages(conn):\n c = conn.cursor()\n c.execute('select * from packages')\n rows = c.fetchall()\n return rows\n\ndef db_descPackage(conn, package_name):\n c = conn.cursor()\n c.execute('select * from packages where packagename=?', (package_name,))\n rows = c.fetchall()\n return rows\n\ndef db_namePackage(conn, package_id):\n c = conn.cursor()\n c.execute('select * from packages where packageid=?', (package_id,))\n rows = c.fetchall()\n if len(rows) < 1:\n # No package name for that ID\n package_name = \"NULL\"\n else:\n package_name = str(rows[0][1])\n return package_name\n\ndef db_idPackage(conn, package_name):\n c = conn.cursor()\n c.execute('select * from packages where packagename=?', (str(package_name),))\n rows = c.fetchall()\n if len(rows) < 1:\n # No corresponding package in our status db by that name\n package_id = 0\n else:\n package_id = int(rows[0][0])\n return package_id\n\ndef db_depsPackage(conn, package_id):\n c = conn.cursor()\n c.execute('select * from depends where packageid=?', (package_id,))\n rows = c.fetchall()\n return rows\n\ndef db_indepsPackage(conn, package_id):\n c = conn.cursor()\n c.execute('select * from depends where dependencyid=?', (package_id,))\n rows = c.fetchall()\n return rows\n\ndef db_getAlternates(conn, package_id, dependency_id):\n c = conn.cursor()\n c.execute('select * from alternates where dependencyid=? AND packageid=?', (dependency_id, package_id))\n rows = c.fetchall()\n return rows\n\ndef db_status_load(conn, status_obj):\n c = conn.cursor()\n # render json datastruct from string object\n status_dict = parse.parse(status_obj)\n package_name = package_description = \"\"\n package_depends = []\n\n # stage packages info from status_dict\n # populate packages table\n for packages in status_dict['Packages']:\n # define package name\n package_name = packages\n # print \"inserting \\033[34m %s \\033[0m :\\n\" % package_name\n for idx,stuff in enumerate(status_dict['Packages'][packages]):\n if stuff.has_key(\"Description\"): \n # define package description\n package_description = stuff['Description']\n\n # execute insertion query\n b = sqlite3.Binary(package_description)\n c.execute('insert into packages (packagename, description) values (?,?)', (package_name, b) )\n\n conn.commit()\n\n # populate dependency table\n for packages in status_dict['Packages']:\n package_name = packages\n # print \"inserting depends and alternates for \\033[31m %s \\033[0m :\\n\" % package_name\n for stuff in status_dict['Packages'][packages]:\n if stuff.has_key(\"Depends\"):\n dep_string = stuff['Depends']\n dep_string = dep_string.replace(\" \", \"\")\n dep_array = dep_string.split(',')\n package_id = db_idPackage(conn, package_name)\n for dep in dep_array:\n dep = re.sub(r'\\([^)]*\\)', '', dep)\n if \"|\" in dep: \n alternates = dep.split('|')\n deporig = alternates[0]\n for idx, alternate in enumerate(alternates):\n if idx > 0:\n alternate_id = db_idPackage(conn, alternate)\n dependency_id = db_idPackage(conn, deporig)\n # print \"\\033[33m ALTERNATE: %s, %s, %s \\033[0m \\n\" % (package_id, dependency_id, alternate_id)\n c.execute('insert into alternates (packageid, dependencyid, alternateid) values (?,?,?)', \n (package_id, dependency_id, alternate_id) )\n else:\n dependency_id = db_idPackage(conn, deporig)\n c.execute('insert into depends (packageid, dependencyid, alternate) values (?, ?, ?)',\n (package_id, dependency_id, 1) )\n else:\n dependency_id = db_idPackage(conn, dep)\n c.execute('insert into depends (packageid, dependencyid, alternate) values (?, ?, ?)',\n (package_id, dependency_id, 0) ) \n\n # commit changes to database\n conn.commit()\n\n return 0\n","sub_path":"build/lib.linux-x86_64-2.7/common/db.py","file_name":"db.py","file_ext":"py","file_size_in_byte":5621,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"598331123","text":"\"\"\"\nA simple foodbank flask app.\nata is stored in a SQLite database that looks something like the following:\n\n+---------+--------------+---------+--------+------+------+--------+------+--------+\n| Name | Email | Phone |Address | State| Zip | Country|Amount| Message|\n+=========+==============+===+=====+======--+------+------+--------+------+--------+\n| Neha Ag| neha@pdx.edu | 12345678| Port | OR | 97123| US | 100 | Enjoy |\n+---------+--------------+---------+--------+------+------+--------+------+--------+\n\nThis can be created with the following SQL (see bottom of this file):\n\n create table foodbank (name text, email text, phone int, address text, state text,\\\n zip int, country text, amount int, message);\n\n\"\"\"\nfrom .Model import Model\nimport sqlite3\nDB_FILE = 'entries.db' # file for our Database\n\nclass model(Model):\n def __init__(self):\n # Make sure our database exists\n connection = sqlite3.connect(DB_FILE)\n cursor = connection.cursor()\n try:\n cursor.execute(\"select count(rowid) from foodbank\")\n except sqlite3.OperationalError:\n cursor.execute(\"create table foodbank (name text, email text, phone int, address text,\\\n state text, zip int, country text, amount int, message)\")\n cursor.close()\n\n def select(self):\n \"\"\"\n Gets all rows from the database\n Each row contains: name, email, phone, address, state, zip, country, amount, message\n :return: List of lists containing all rows of database\n \"\"\"\n connection = sqlite3.connect(DB_FILE)\n cursor = connection.cursor()\n cursor.execute(\"SELECT * FROM foodbank\")\n return cursor.fetchall()\n\n def insert(self, name, email, phone, address, state, zip, country, amount, message):\n \"\"\"\n Inserts entry into database\n :param name: String\n :param email: String\n :param phone: Integer\n :param address: String\n :param state: String\n :param zip: Integer\n :param country: String\n :param amount: Integer\n :param message: String\n :return: True\n :raises: Database errors on connection and insertion\n \"\"\"\n params = {'name':name, 'email':email, 'phone':phone,'address':address,'state':state,\\\n 'zip':zip,'country':country,'amount':amount,'message':message}\n connection = sqlite3.connect(DB_FILE)\n cursor = connection.cursor()\n cursor.execute(\"insert into foodbank (name, email, phone, address, state, zip, country, amount, message)\\\n VALUES (:name, :email, :phone, :address, :state, :zip, :country, :amount, :message)\", params)\n\n connection.commit()\n cursor.close()\n return True\n","sub_path":"hw3/gbmodel/model_sqlite3.py","file_name":"model_sqlite3.py","file_ext":"py","file_size_in_byte":2786,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"153459971","text":"from Tree import *\n\ndef preorder(tree):\n if tree:\n print(tree.getRootVal())\n preorder(tree.getLeftChild())\n preorder(tree.getRightChild())\n\ndef postorder(tree):\n if tree:\n postorder(tree.getLeftChild())\n postorder(tree.getRightChild())\n print(tree.getRootVal())\n\ndef inorder(tree):\n if tree:\n inorder(tree.getLeftChild())\n print(tree.getRootVal())\n inorder(tree.getRightChild())\n\nif __name__ == \"__main__\":\n r = BinaryTree(\"a\")\n r.insertLeft('b')\n r.insertRight('c')\n r.getRightChild().setRootVal('hello')\n r.getLeftChild().insertRight('d')\n preorder(r)\n print(\"============\")\n r.preorder()","sub_path":"venv/bin/myTree/TreeTest.py","file_name":"TreeTest.py","file_ext":"py","file_size_in_byte":686,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"624687416","text":"from BLL.FeatureTransmission.Transmit import *\nfrom threading import Thread\nfrom Service.Task import *\nfrom Kit.Prototype.Chain import *\n\nclass DataUpdate(Thread,Chain,Task):\n \"\"\"\n 数据更新任务,负责定时从生产库(数据源)提取并处理特征数据,然后导入\n 数据仓库的特征表\n\n 注意:数据更新完毕后可以进行会员分组(聚类)或者流失预测(分类)任务.但是这两种任务不能再单机上并行,因为它们都很\n 消耗资源,每种任务最好独占CPU和内存资源\n 解决方案1:任务队列,一个任务执行完后进行下一个任务\n 对所有数据进行聚类得到标签--->确定阶段训练数据的标签--->进行流失预测--->对阶段训练数据进行聚类(会员分组)\n 解决方案2:分布式并行,一台节点用于会员分组,另一台节点用于流失预测\n Task for data updating\n \"\"\"\n def __init__(self,instance=None,tag=None,info=None):\n self.transmit = Transmit(instance)\n Chain.__init__(self)\n Task.__init__(self,instance)\n self.worker = Thread(target=self.task)\n self.tag = tag\n self.info = info\n self.logger = Logger()\n\n def start(self):\n \"\"\"\n 触发数据更新任务线程\n :return:\n \"\"\"\n self.worker.start()\n\n def task(self):\n \"\"\"\n 具体的数据更新任务(1.初始化特征表2.更新数据)\n 注意,任务完成后需要触发所有观察者的update方法,执行下一个任务\n :return:\n \"\"\"\n if self.tag is not None and self.info is not None:\n self.logger.log(self.tag,self.info)\n\n self.transmit.initOrUpdate()\n self.transmit.updateData()\n #数据更新完毕后才唤醒会员分组或者会员流失预测任务\n #Clustering or classifying mustn't be triggered until the data updating is finished\n self.wakeUpChild()\n\n def finish(self):\n pass","sub_path":"Service/DataUpdate.py","file_name":"DataUpdate.py","file_ext":"py","file_size_in_byte":2019,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"595911310","text":"'''hfshdfjhsaD\r\nSJDFKSJDF\r\nKSDJFKLSd\r\n]SDJFKKSDF'''\r\ndef wao_o2_get_file_v1(fn, np):\r\n import csv\r\n from time import mktime, strptime\r\n \r\n DT = []\r\n ET = []\r\n DoY = []\r\n O2N2 = []\r\n flag = []\r\n \r\n ifile = open(fn)\r\n reader = csv.reader(ifile, delimiter = chr(44)) #9 = tab, 44 = ,\r\n for row in reader:\r\n xx = str(row[0])\r\n ix = xx.find(\"Date_Time\")\r\n if ix < 0:\r\n xx = str(row[0])\r\n tt = strptime(str(row[0]), '%d/%m/%Y %H:%M')\r\n #DoY\r\n DoY.append(float(tt[7]) + ((((float(tt[5])/60) + float(tt[4]))/60) + float(tt[3]))/24) \r\n #ET\r\n ET.append(int(mktime(tt)))\r\n #DT\r\n DT.append(tt[0:6])\r\n #o2/n2 ratio\r\n xx = str(row[1])\r\n O2N2.append(float(xx))\r\n #fl\r\n xx = str(row[2])\r\n flag.append(int(xx))\r\n\t\t \r\n return np.array(DT), np.array(DoY), np.array(ET), np.array(O2N2), np.array(flag) \r\n \r\ndef wao_o2_parse_data_v1(data):\r\n ix = len(data.DoY)\r\n for ii in range(0,len(data.DoY)):\r\n if data.DT[ii,1] != data.DT[0,1]:\r\n ix = ii\r\n\t\t \r\n return data.DT[0:ix,:], data.DoY[0:ix], data.ET[0:ix], data.O2N2[0:ix], data.flag[0:ix]","sub_path":"o2n2/V1/o2n2_parser_v1.py","file_name":"o2n2_parser_v1.py","file_ext":"py","file_size_in_byte":1191,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"620702120","text":"import openpyxl\n\nbook = openpyxl.Workbook()\n\nsheet = book.active\nsheet.title = 'First sheet'\n\ncells = sheet['A1':'B4']\ni = 0\n\nfor row in cells:\n for cell in row:\n cell.value = i\n i += 1\ncell2 = sheet['C1']\ncell2.value = 'aaa'\n\nbook.save('demo.xlsx')\n ","sub_path":"excel_test.py","file_name":"excel_test.py","file_ext":"py","file_size_in_byte":279,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"11351718","text":"'''-------------------------------------------------------------------------\nCopyright IBM Corp. 2015, 2015 All Rights Reserved\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\nhttp://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nLimitations under the License.\n-------------------------------------------------------------------------'''\n\nfrom __init__ import ACCOUNT\nfrom __init__ import AUTH_IP\nfrom __init__ import AUTH_PORT\nfrom __init__ import PASSWORD\nfrom __init__ import put_storlet_object\nfrom __init__ import USER_NAME\nimport json\nimport os\nimport random\nimport string\nfrom swiftclient import client as c\nfrom test_identity_storlet import deploy_identity_storlet\nfrom test_identity_storlet import IDENTITY_STORLET_NAME\nimport unittest\n\n\nSLOIDENTITY_PATH_TO_BUNDLE = '../../StorletSamples/SLOIdentityStorlet/bin'\nSLOIDENTITY_STORLET_NAME = 'sloidentitystorlet-1.0.jar'\n\n\ndef create_local_chunks():\n for i in range(1, 10):\n oname = '/tmp/slo_chunk_%d' % i\n f = open(oname, 'w')\n f.write(''.join(random.choice(string.ascii_uppercase + string.digits)\n for _ in range(1048576)))\n f.close()\n\n\ndef delete_local_chunks():\n for i in range(1, 10):\n oname = '/tmp/slo_chunk_%d' % i\n os.remove(oname)\n\n\ndef put_SLO(url, token):\n # Create temp files\n assembly = []\n for i in range(1, 10):\n oname = '/tmp/slo_chunk_%d' % i\n f = open(oname, 'r')\n content_length = None\n response = dict()\n c.put_object(url, token, 'myobjects', oname, f,\n content_length, None, None, \"application/octet-stream\",\n None, None, None, None, response)\n f.close()\n status = response.get('status')\n assert (status >= 200 and status < 300)\n\n headers = response.get('headers')\n segment = dict()\n segment['path'] = 'myobjects/%s' % oname\n segment['size_bytes'] = 1048576\n segment['etag'] = headers['etag']\n assembly.append(segment)\n\n content_length = None\n response = dict()\n headers = {'x-object-meta-prop1': 'val1'}\n c.put_object(url, token, 'myobjects', 'assembly', json.dumps(assembly),\n content_length=None, etag=None, chunk_size=None,\n headers=headers, query_string='multipart-manifest=put',\n response_dict=response)\n status = response.get('status')\n assert (status >= 200 and status < 300)\n\n\ndef get_SLO(url, token):\n response = dict()\n headers, body = c.get_object(url, token, 'myobjects', 'assembly',\n http_conn=None, resp_chunk_size=1048576,\n query_string=None, response_dict=response,\n headers=None)\n\n i = 1\n for chunk in body:\n oname = '/tmp/slo_chunk_%d' % i\n f = open(oname, 'r')\n file_content = f.read()\n # print '%s %s' % (chunk[:10], file_content[:10])\n # print '%d %d' % (len(chunk), len(file_content))\n assert(chunk == file_content)\n f.close()\n i = i + 1\n\n\ndef compare_slo_to_chunks(body):\n i = 1\n for chunk in body:\n if chunk:\n if i < 10:\n oname = '/tmp/slo_chunk_%d' % i\n f = open(oname, 'r')\n file_content = f.read()\n # print '%s %s' % (chunk[:10], file_content[:10])\n # print '%d %d' % (len(chunk), len(file_content))\n assert(chunk == file_content)\n f.close()\n i = i + 1\n else:\n aux_content = ''\n for j in range(1, 4):\n oname = '/tmp/aux_file%d' % j\n f = open(oname, 'r')\n aux_content += f.read()\n f.close()\n assert(chunk == aux_content)\n\n\ndef invoke_identity_on_get_SLO(url, token):\n metadata = {'X-Run-Storlet': IDENTITY_STORLET_NAME}\n response = dict()\n headers, body = c.get_object(url, token,\n 'myobjects', 'assembly',\n query_string=None,\n response_dict=response,\n resp_chunk_size=1048576,\n headers=metadata)\n compare_slo_to_chunks(body)\n\n\ndef invoke_identity_on_get_SLO_double(url, token):\n metadata = {'X-Run-Storlet': IDENTITY_STORLET_NAME}\n response = dict()\n headers, body = c.get_object(url, token,\n 'myobjects',\n 'assembly',\n query_string='double=true',\n response_dict=response,\n resp_chunk_size=2048,\n headers=metadata)\n\n i = 1\n oname = '/tmp/slo_chunk_%d' % i\n f = open(oname, 'r')\n file_content = f.read()\n\n j = 0 # Count chunks in file 1...1024\n for chunk in body:\n file_fragment = file_content[j * 1024:(j + 1) * 1024]\n chunk_framgment_low = chunk[0:1024]\n chunk_framgment_high = chunk[1024:2048]\n assert(chunk_framgment_low == file_fragment)\n assert(chunk_framgment_high == file_fragment)\n j = j + 1\n if j == 1024:\n i = i + 1\n if i == 10:\n break\n f.close()\n oname = '/tmp/slo_chunk_%d' % i\n f = open(oname, 'r')\n file_content = f.read()\n j = 0\n assert i == 10\n\n\ndef invoke_identity_on_partial_get_SLO(url, token):\n metadata = {'X-Run-Storlet': IDENTITY_STORLET_NAME}\n for i in range(5):\n response = dict()\n headers, body = c.get_object(url, token,\n 'myobjects',\n 'assembly',\n query_string=None,\n response_dict=response,\n resp_chunk_size=1048576,\n headers=metadata)\n\n j = 1\n for chunk in body:\n j = j + 1\n if j == 5:\n break\n\n# def delete_files():\n# for i in range(1,4):\n# fname = '/tmp/aux_file%d' % i\n# os.remove(fname)\n\n\ndef create_container(url, token, name):\n response = dict()\n c.put_container(url, token, name, headers=None, response_dict=response)\n status = response.get('status')\n assert (status >= 200 or status < 300)\n\n\ndef deploy_sloidentity_storlet(url, token):\n response = dict()\n c.put_container(url, token, 'mysloobject', None, None, response)\n status = response.get('status')\n assert (status >= 200 or status < 300)\n\n put_storlet_object(url, token,\n SLOIDENTITY_STORLET_NAME,\n SLOIDENTITY_PATH_TO_BUNDLE,\n '',\n 'com.ibm.storlet.sloidentity.SLOIdentityStorlet')\n\n\nclass TestSLO(unittest.TestCase):\n def setUp(self):\n os_options = {'tenant_name': ACCOUNT}\n self.url, self.token = c.get_auth(\"http://\" + AUTH_IP + \":\" + AUTH_PORT\n + \"/v2.0\", ACCOUNT + \":\" + USER_NAME,\n PASSWORD, os_options=os_options,\n auth_version=\"2.0\")\n create_container(self.url, self.token, 'myobjects')\n create_container(self.url, self.token, 'container1')\n create_container(self.url, self.token, 'container2')\n create_container(self.url, self.token, 'container3')\n create_local_chunks()\n put_SLO(self.url, self.token)\n get_SLO(self.url, self.token)\n deploy_identity_storlet(self.url, self.token)\n\n def tearDown(self):\n delete_local_chunks()\n\n def test_get_SLO(self):\n invoke_identity_on_get_SLO(self.url, self.token)\n\n # YM comment out 2 lines - temporary only!\n # progress_msg(\"Invoking storlet on SLO in GET with double\")\n # invoke_identity_on_get_SLO_double(url, token)\n\n # progress_msg(\"Invoking storlet on SLO in partial GET\")\n # invoke_identity_on_partial_get_SLO(url, token)\n","sub_path":"tests/functional/test_SLO.py","file_name":"test_SLO.py","file_ext":"py","file_size_in_byte":8585,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"448254546","text":"#!/usr/bin/env python\n# coding=utf-8\n\n# Copyright © 2012-2023 ButenkoMS. All rights reserved. Contacts: \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\"\"\"\nModule Docstring\nDocstrings: http://www.python.org/dev/peps/pep-0257/\n\"\"\"\n\n\n__author__ = \"ButenkoMS \"\n__copyright__ = \"Copyright © 2012-2023 ButenkoMS. All rights reserved. Contacts: \"\n__credits__ = [\"ButenkoMS \", ]\n__license__ = \"Apache License, Version 2.0\"\n__version__ = \"3.2.6\"\n__maintainer__ = \"ButenkoMS \"\n__email__ = \"gtalk@butenkoms.space\"\n# __status__ = \"Prototype\"\n__status__ = \"Development\"\n# __status__ = \"Production\"\n\n\nimport time\nimport asyncio\nfrom typing import List\n\nimport pytermgui as ptg\nfrom cengal.parallel_execution.coroutines.coro_scheduler import *\nfrom cengal.parallel_execution.coroutines.integrations.pytermgui import TerminalApplication, WindowManagerCS\nfrom cengal.parallel_execution.coroutines.coro_tools.run_in_loop import run_in_loop\nfrom cengal.parallel_execution.coroutines.coro_standard_services.sleep import Sleep\nfrom cengal.parallel_execution.coroutines.coro_standard_services.put_coro import PutCoro\nfrom cengal.parallel_execution.coroutines.coro_standard_services.loop_yield import CoroPriority\nfrom cengal.parallel_execution.coroutines.coro_standard_services.asyncio_loop import AsyncioLoopRequest\nfrom enum import Enum\n\n\nclass Model:\n def __init__(self):\n self.all_formats: List[str] = [\n None, \"%H:%M:%S\", \"%c\", \"%I:%M:%S %p\", \"%x\", \"%I:%M %p\", \"%X\", \"%H:%M\",\n ]\n self.current_format_index = 0\n self.current_format = self.all_formats[self.current_format_index]\n\n\nclass HelloWorldApp(TerminalApplication):\n def model_setup(self):\n return Model()\n \n def ui_setup(self, manager: WindowManagerCS, model: Model):\n def macro_time(fmt: str) -> str:\n return time.strftime(fmt if model.current_format is None else model.current_format)\n\n ptg.tim.define(\"!time\", macro_time)\n manager.layout.add_slot(\"Body\")\n manager.add(\n ptg.Window(\"[bold]The current time is:[/]\\n\\n[!time 75]%c\", box=\"EMPTY\")\n )\n\n async def controller_loop_setup(self, i: Interface, model: Model):\n await i(AsyncioLoopRequest().ensure_loop(None, CoroPriority.high, True))\n await i(AsyncioLoopRequest().turn_on_loops_intercommunication())\n await i(PutCoro, self.periodic_format_changer, model)\n\n async def periodic_format_changer(self, i: Interface, model: Model):\n while True:\n await asyncio.sleep(1.5)\n model.current_format_index += 1\n if model.current_format_index >= len(model.all_formats):\n model.current_format_index = 0\n \n model.current_format = model.all_formats[model.current_format_index]\n\n\nif __name__ == \"__main__\":\n app: HelloWorldApp = HelloWorldApp()\n app.run()\n","sub_path":"cengal/parallel_execution/coroutines/integrations/pytermgui/versions/v_0/development/hello_world_app.py","file_name":"hello_world_app.py","file_ext":"py","file_size_in_byte":3482,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"152638829","text":"import random\n\n\ndef game(choice):\n\n options = [\"kamen\", \"nuzky\", \"papir\"]\n bot = random.choice(options)\n\n if choice == \"kamen\" and bot == \"nuzky\":\n print(\"Ty mas kamen, ja mam nuzky. \\nVyhral jsi!\")\n elif choice == \"kamen\" and bot == \"papir\":\n print(\"Ty mas kamen, ja mam papir. \\nProhral jsi.\")\n elif choice == \"kamen\" and bot == \"kamen\":\n print(\"Oba mame kamen. \\nRemiza\")\n elif choice == \"papir\" and bot == \"papir\":\n print(\"Oba mame papir. \\nRemiza\")\n elif choice == \"papir\" and bot == \"nuzky\":\n print(\"Ty mas papir, ja mam nuzky. \\nProhral jsi.\")\n elif choice == \"papir\" and bot == \"kamen\":\n print(\"Ty mas papir, ja mam kamen. \\nVyhral jsi!\")\n elif choice == \"nuzky\" and bot == \"nuzky\":\n print(\"Oba mame nuzky. \\nRemiza\")\n elif choice == \"nuzky\" and bot == \"papir\":\n print(\"Ty mas nuzky, ja mam papir. \\nVyhral jsi!\")\n elif choice == \"nuzky\" and bot == \"kamen\":\n print(\"Ty mas nuzky, ja mam kamen. \\nProhral jsi.\")\n else:\n print(f\"{choice} neni v nabidce, zkus to znova\")\n\n\ncount = 1\n\nwhile True:\n game(input(\"kamen - nuzky - papir? \"))\n repeat = input(\"Jeste jedno kolo? ano / ne \")\n\n if repeat == \"ano\":\n count += 1\n print(f\"{count}.kolo\")\n continue\n else:\n break\n","sub_path":"kamen.py","file_name":"kamen.py","file_ext":"py","file_size_in_byte":1316,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"865394","text":"import re\n\n\nclass Print:\n\tdef __init__(self, edition, print_id, partiture):\n\t\tself.edition = edition\n\t\tself.print_id = print_id\n\t\tself.partiture = partiture\n\n\tdef format(self):\n\n\t\tif self.print_id is None:\n\t\t\treturn\n\t\tprint(\"Print Number: \" + str(self.print_id))\n\n\t\tif len(self.composition().authors) > 0:\n\t\t\toutput_composers = []\n\n\t\t\tfor composer in self.composition().authors:\n\t\t\t\toutput_composer = \"\"\n\t\t\t\tif composer.name is not None:\n\t\t\t\t\toutput_composer = composer.name\n\n\t\t\t\tif composer.born is not None and composer.died is not None:\n\t\t\t\t\toutput_composer = output_composer + \" (\" + str(composer.born) + \"--\" + str(composer.died) + \")\"\n\t\t\t\telif composer.born is not None and composer.died is None:\n\t\t\t\t\toutput_composer = output_composer + \" (\" + str(composer.born) + \"--)\"\n\t\t\t\telif composer.born is None and composer.died is not None:\n\t\t\t\t\toutput_composer = output_composer + \" (--\" + str(composer.died) + \")\"\n\n\t\t\t\toutput_composers.append(output_composer)\n\t\t\tprint(\"Composer: \" + \"; \".join(output_composers))\n\t\telse:\n\t\t\tprint(\"Composer: \")\n\n\t\tif self.composition().name is not None:\n\t\t\tprint(\"Title: \" + self.composition().name)\n\t\telse:\n\t\t\tprint(\"Title: \")\n\n\t\tif self.composition().genre is not None:\n\t\t\tprint(\"Genre: \" + self.composition().genre)\n\t\telse:\n\t\t\tprint(\"Genre: \")\n\n\t\tif self.composition().key is not None:\n\t\t\tprint(\"Key: \" + self.composition().key)\n\t\telse:\n\t\t\tprint(\"Key: \")\n\n\t\tif self.composition().year is not None:\n\t\t\tprint(\"Composition Year: \" + str(self.composition().year))\n\t\telse:\n\t\t\tprint(\"Composition Year: \")\n\n\t\tif self.edition.name is not None:\n\t\t\tprint(\"Edition: \" + self.edition.name)\n\t\telse:\n\t\t\tprint(\"Edition: \")\n\n\t\tif len(self.edition.authors) > 0:\n\t\t\toutput_editors = []\n\t\t\tfor editor in self.edition.authors:\n\t\t\t\toutput_editors.append(editor.name)\n\t\t\tprint(\"Editor: \" + \", \".join(output_editors))\n\t\telse:\n\t\t\tprint(\"Editor: \")\n\n\t\tif len(self.composition().voices) > 0:\n\t\t\toutput_voices = []\n\n\t\t\tfor voice in self.composition().voices:\n\t\t\t\toutput_voice = \"\"\n\t\t\t\tif voice.range is not None and voice.name is not None:\n\t\t\t\t\toutput_voice = output_voice + voice.range + \", \" + voice.name\n\t\t\t\telif voice.range is not None and voice.name is None:\n\t\t\t\t\toutput_voice = output_voice + voice.range\n\t\t\t\telif voice.range is None and voice.name is not None:\n\t\t\t\t\toutput_voice = output_voice + voice.name\n\n\t\t\t\toutput_voices.append(output_voice)\n\n\t\t\tindex = 0\n\t\t\tfor output_voice in output_voices:\n\t\t\t\tprint(\"Voice \" + str(index + 1) + \": \" + output_voice)\n\t\t\t\tindex = index + 1\n\t\telse:\n\t\t\tprint(\"Voice 1: \")\n\n\t\tif self.partiture is not None:\n\t\t\tif self.partiture:\n\t\t\t\tprint(\"Partiture: yes\")\n\t\t\telse:\n\t\t\t\tprint(\"Partiture: no\")\n\t\telse:\n\t\t\tprint(\"Partiture: \")\n\n\t\tif self.composition().incipit is not None:\n\t\t\tprint(\"Incipit: \" + self.composition().incipit)\n\t\telse:\n\t\t\tprint(\"Incipit: \")\n\n\t\tprint()\n\n\tdef composition(self):\n\t\treturn self.edition.composition\n\n\t@staticmethod\n\tdef extract_id(line):\n\t\tid_re = re.compile(r\"Print Number: (.)*\")\n\t\tnew_match = id_re.match(line)\n\n\t\tif new_match is not None:\n\t\t\tnew_id = line.split(\":\")[1].strip()\n\t\t\treturn int(new_id)\n\t\treturn None\n\n\t@staticmethod\n\tdef extract_partiture(line):\n\t\tpartiture_re = re.compile(r\"Partiture: (.)*\")\n\t\tnew_match = partiture_re.match(line)\n\n\t\tif new_match is not None:\n\t\t\tnew_partiture = line.split(\":\")[1].strip()\n\n\t\t\tfirst_word_re = re.compile(r\"^\\w+\")\n\t\t\tfirst_word_match = first_word_re.match(new_partiture)\n\t\t\tif first_word_match is not None:\n\t\t\t\tif new_partiture[0:3].lower() == \"yes\":\n\t\t\t\t\treturn True\n\t\t\t\telif new_partiture[0:2].lower() == \"no\" or new_partiture.lower() != \"\":\n\t\t\t\t\treturn False\n\t\treturn None\n\n\nclass Edition:\n\tdef __init__(self, composition, authors, name):\n\t\tself.composition = composition\n\t\tself.authors = authors\n\t\tself.name = name\n\n\t@staticmethod\n\tdef extract_name(line):\n\t\tname_re = re.compile(r\"Edition: (.*)\")\n\t\tnew_match = name_re.match(line)\n\n\t\tif new_match is not None:\n\t\t\tnew_name = line.split(\":\")[1].strip()\n\t\t\treturn new_name\n\t\treturn None\n\n\nclass Composition:\n\tdef __init__(self, name, incipit, key, genre, year, voices, authors):\n\t\tself.name = name\n\t\tself.incipit = incipit\n\t\tself.key = key\n\t\tself.genre = genre\n\t\tself.year = year\n\t\tself.year = year\n\t\tself.voices = voices\n\t\tself.authors = authors\n\n\t@staticmethod\n\tdef extract_name(line):\n\t\tname_re = re.compile(r\"Title: (.*)\")\n\t\tnew_match = name_re.match(line)\n\n\t\tif new_match is not None:\n\t\t\tnew_name = line.split(\"Title:\")[1].strip()\n\t\t\treturn new_name\n\t\treturn None\n\n\t@staticmethod\n\tdef extract_incipit(line):\n\t\tname_re = re.compile(r\"Incipit: (.*)\")\n\t\tnew_match = name_re.match(line)\n\n\t\tif new_match is not None:\n\t\t\tnew_name = line.split(\"Incipit:\")[1].strip()\n\t\t\treturn new_name\n\t\treturn None\n\n\t@staticmethod\n\tdef extract_key(line):\n\t\tname_re = re.compile(r\"Key: (.*)\")\n\t\tnew_match = name_re.match(line)\n\n\t\tif new_match is not None:\n\t\t\tnew_name = line.split(\"Key:\")[1].strip()\n\t\t\treturn new_name\n\t\treturn None\n\n\t@staticmethod\n\tdef extract_genre(line):\n\t\tname_re = re.compile(r\"Genre: (.*)\")\n\t\tnew_match = name_re.match(line)\n\n\t\tif new_match is not None:\n\t\t\tnew_name = line.split(\"Genre:\")[1].strip()\n\t\t\treturn new_name\n\t\treturn None\n\n\t@staticmethod\n\tdef extract_year(line):\n\t\tcom_year_re = re.compile(r\"Composition Year: (.*)\")\n\t\tnew_match = com_year_re.match(line)\n\n\t\tif new_match is not None:\n\t\t\tnew_year = line.split(\"Composition Year:\")[1].strip()\n\n\t\t\tyear = re.findall(r\"\\d{4}\", new_year)\n\n\t\t\tif len(year) > 0:\n\t\t\t\treturn int(year[0])\n\n\t\treturn None\n\n\nclass Voice:\n\tdef __init__(self, name, range):\n\t\tself.name = name\n\t\tself.range = range\n\n\t@staticmethod\n\tdef extract_voice(line):\n\t\tvoice_re = re.compile(r\"Voice \\d+:\")\n\t\tnew_match = voice_re.match(line)\n\n\t\tif new_match is not None:\n\t\t\tline = re.sub(voice_re, \"Voice:\", line)\n\t\t\tvoice_info = line.split(\"Voice:\")[1].strip()\n\n\t\t\tif \"--\" in voice_info:\n\t\t\t\tvoice_info = voice_info.replace(\",\", \";\", 1)\n\t\t\t\tvoice_info = voice_info.split(\";\")\n\t\t\t\tif len(voice_info) > 1:\n\t\t\t\t\tvoice_range = voice_info[0].strip()\n\t\t\t\t\tvoice_name = voice_info[1].strip()\n\t\t\t\telse:\n\t\t\t\t\tvoice_range = voice_info[0].strip()\n\t\t\t\t\tvoice_name = None\n\t\t\telse:\n\t\t\t\tif len(voice_info.strip()) > 0:\n\t\t\t\t\tvoice_name = voice_info.strip()\n\t\t\t\tvoice_name = None\n\t\t\t\tvoice_range = None\n\n\t\t\tnew_voice = Voice(voice_name, voice_range)\n\t\t\treturn new_voice\n\t\treturn None\n\n\nclass Person:\n\tdef __init__(self, name, born, died):\n\t\tself.name = name\n\t\tself.born = born\n\t\tself.died = died\n\n\t@staticmethod\n\tdef extract_composers(line):\n\t\tcom_re = re.compile(r\"Composer: (.*)\")\n\t\tnew_match = com_re.match(line)\n\n\t\tcomposers_list = []\n\t\tif new_match is not None:\n\t\t\tcomposers = line.split(\"Composer:\")[1].split(\";\")\n\n\t\t\tfor composer in composers:\n\n\t\t\t\tif Person.number_in_string(composer):\n\t\t\t\t\tcom_info = composer.split(\" (\")\n\t\t\t\t\tcom_name = com_info[0].strip()\n\n\t\t\t\t\tif len(com_info) > 1:\n\t\t\t\t\t\tif Person.plus_in_string(com_info[1]):\n\t\t\t\t\t\t\tcom_born = None\n\t\t\t\t\t\t\tcom_died = int(com_info[1].split(\"+\")[1].replace(\")\", \"\")[0:4].strip())\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\tyears = com_info[1].replace(\"--\", \"-\")\n\t\t\t\t\t\t\tif len(years.split(\"-\")[0].strip()) > 0:\n\t\t\t\t\t\t\t\tcom_born = int(years.split(\"-\")[0][0:4].strip())\n\t\t\t\t\t\t\telse:\n\t\t\t\t\t\t\t\tcom_born = None\n\n\t\t\t\t\t\t\tif len(years.split(\"-\")[1].replace(\")\", \"\").strip()) > 0:\n\t\t\t\t\t\t\t\tcom_died = int(years.split(\"-\")[1].replace(\")\", \"\")[0:4].strip())\n\t\t\t\t\t\t\telse:\n\t\t\t\t\t\t\t\tcom_died = None\n\n\t\t\t\telse:\n\t\t\t\t\tcom_name = composer.strip()\n\t\t\t\t\tcom_born = None\n\t\t\t\t\tcom_died = None\n\n\t\t\t\tnew_person = Person(com_name, com_born, com_died)\n\t\t\t\tcomposers_list.append(new_person)\n\t\treturn composers_list\n\n\t@staticmethod\n\tdef extract_editors(line):\n\t\teditors_re = re.compile(r\"Editor: (.*)\")\n\t\tnew_match = editors_re.match(line)\n\n\t\teditors_list = []\n\n\t\tif new_match is not None:\n\t\t\teditors = line.split(\"Editor:\")[1].strip()\n\n\t\t\twhole_names_re = re.compile(r\"\\w+ \\w+\")\n\t\t\twhole_names_match = whole_names_re.match(editors)\n\n\t\t\tif whole_names_match is not None or \"-\" in line:\n\t\t\t\tif ',' in editors:\n\t\t\t\t\teditors = editors.split(\",\")\n\t\t\t\telse:\n\t\t\t\t\teditors = [editors]\n\t\t\telse:\n\t\t\t\tif ',' in editors:\n\t\t\t\t\teditors = editors.split(\",\")\n\t\t\t\t\teditors = [\",\".join(i) for i in zip(editors[::2], editors[1::2])]\n\t\t\t\telse:\n\t\t\t\t\teditors = [editors]\n\n\t\t\tfor editor in editors:\n\t\t\t\tnew_person = Person(editor.strip(), None, None)\n\t\t\t\teditors_list.append(new_person)\n\n\t\treturn editors_list\n\n\t@staticmethod\n\tdef number_in_string(s):\n\t\treturn any(i.isdigit() for i in s)\n\n\t@staticmethod\n\tdef plus_in_string(s):\n\t\treturn \"+\" in s\n\n\ndef open_file(filename):\n\t# fix opening on win - set encoding\n\ttry:\n\t\tf = open(filename, 'r', encoding=\"utf8\")\n\texcept Exception as e:\n\t\tprint(e)\n\t\ttry:\n\t\t\tf = open(filename, 'r')\n\t\texcept Exception as e:\n\t\t\tprint(e)\n\n\treturn f\n\n\ndef parse_sections(filename):\n\tsections = filename.read().split(\"\\n\\n\")\n\n\tif len(sections) > 0:\n\t\treturn sections\n\n\tprint(\"No print sections in file.\")\n\treturn\n\n\ndef load(filename):\n\tprints_list = []\n\n\tf = open_file(filename)\n\tsections = parse_sections(f)\n\n\tfor section in sections:\n\t\tif not section:\n\t\t\tcontinue\n\n\t\tsection_lines = section.split(\"\\n\")\n\n\t\tprint_id = None\n\t\tcomposition_name = None\n\t\tcomposition_incipit = None\n\t\tcomposition_key = None\n\t\tcomposition_genre = None\n\t\tcomposition_year = None\n\t\tvoices = []\n\t\tcomposers = []\n\t\tedition_name = None\n\t\teditors = []\n\t\tprint_id = None\n\t\tpartiture = None\n\n\t\tfor s_line in section_lines:\n\t\t\tif \"Print Number:\" in s_line:\n\t\t\t\tprint_id = Print.extract_id(s_line)\n\t\t\telif \"Partiture:\" in s_line:\n\t\t\t\tpartiture = Print.extract_partiture(s_line)\n\t\t\telif \"Edition:\" in s_line:\n\t\t\t\tedition_name = Edition.extract_name(s_line)\n\t\t\telif \"Composer:\" in s_line:\n\t\t\t\tcomposers = Person.extract_composers(s_line)\n\t\t\telif \"Title:\" in s_line:\n\t\t\t\tcomposition_name = Composition.extract_name(s_line)\n\t\t\telif \"Incipit:\" in s_line:\n\t\t\t\tcomposition_incipit = Composition.extract_incipit(s_line)\n\t\t\telif \"Key:\" in s_line:\n\t\t\t\tcomposition_key = Composition.extract_key(s_line)\n\t\t\telif \"Genre:\" in s_line:\n\t\t\t\tcomposition_genre = Composition.extract_genre(s_line)\n\t\t\telif \"Composition Year:\" in s_line:\n\t\t\t\tcomposition_year = Composition.extract_year(s_line)\n\t\t\telif \"Voice\" in s_line:\n\t\t\t\tnew_voice = Voice.extract_voice(s_line)\n\t\t\t\tvoices.append(new_voice)\n\t\t\telif \"Editor:\" in s_line:\n\t\t\t\teditors = Person.extract_editors(s_line)\n\t\t\telse:\n\t\t\t\tcontinue\n\n\t\tnew_composition = Composition(composition_name, composition_incipit, composition_key, composition_genre, composition_year, voices, composers)\n\t\tnew_edition = Edition(new_composition, editors, edition_name)\n\t\tnew_print = Print(new_edition, print_id, partiture)\n\n\t\tprints_list.append(new_print)\n\n\treturn prints_list\n","sub_path":"03-db/scorelib.py","file_name":"scorelib.py","file_ext":"py","file_size_in_byte":10552,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"451623450","text":"import torch\nfrom torch import nn\nimport numpy as np\nfrom models.dialogue_gcn_cell import GraphConvolution\nfrom torch.nn.parameter import Parameter\nfrom transformers import BertModel, BertTokenizer\nfrom torch.nn.utils.rnn import pad_sequence, pack_padded_sequence, pad_packed_sequence, PackedSequence\nfrom models.visual_features import FaceModule\n\n\nclass DialogueGCN(nn.Module):\n\n def __init__(self, config):\n super(DialogueGCN, self).__init__()\n self.config = config\n self.att_window_size = config.att_window_size\n self.utt_embed_size = config.utt_embed_size\n self.text_encoder = nn.GRU(config.text_in_dim, config.text_out_dim, bidirectional=True, batch_first=True)\n if self.config.use_meld_audio or self.config.use_our_audio:\n if self.config.use_texts:\n self.context_encoder = nn.GRU(config.context_in_dim * 3, config.context_out_dim, bidirectional=True, batch_first=True)\n else:\n self.context_encoder = nn.GRU(config.context_in_dim, config.context_out_dim, bidirectional=True, batch_first=True)\n self.audio_W_fixed_1 = nn.Linear(700, 100, bias=True)\n else:\n self.context_encoder = nn.GRU(config.context_in_dim * 2, config.context_out_dim, bidirectional=True, batch_first=True)#\n self.pred_rel_l1 = GraphConvolution(self.utt_embed_size, self.utt_embed_size, bias=False)\n self.suc_rel_l1 = GraphConvolution(self.utt_embed_size, self.utt_embed_size, bias=False)\n self.same_speak_rel_l1 = GraphConvolution(self.utt_embed_size, self.utt_embed_size, bias=False)\n self.diff_speak_rel_l1 = GraphConvolution(self.utt_embed_size, self.utt_embed_size, bias=False)\n \n self.pred_rel_l2 = GraphConvolution(self.utt_embed_size, self.utt_embed_size, bias=False)\n self.suc_rel_l2 = GraphConvolution(self.utt_embed_size, self.utt_embed_size, bias=False)\n self.same_speak_rel_l2 = GraphConvolution(self.utt_embed_size, self.utt_embed_size, bias=False)\n self.diff_speak_rel_l2 = GraphConvolution(self.utt_embed_size, self.utt_embed_size, bias=False)\n self.edge_att_weights = nn.Linear(self.utt_embed_size*2, self.utt_embed_size*2, bias=False)\n self.w_aggr_1 = nn.Parameter(torch.FloatTensor(self.utt_embed_size*2, self.utt_embed_size*2))\n self.w_aggr_2 = nn.Parameter(torch.FloatTensor(self.utt_embed_size*2, self.utt_embed_size*2))\n \n self.text_attn = nn.Linear(self.utt_embed_size * 2, 1)\n self.w_sentiment = nn.Linear(self.utt_embed_size*4, 3)\n self.w_emotion_1 = nn.Linear(self.utt_embed_size*4, self.utt_embed_size * 2)\n self.w_emotion_2 = nn.Linear(self.utt_embed_size * 2, 7)\n\n self.tokenizer = BertTokenizer.from_pretrained('bert-base-uncased')\n self.bert = BertModel.from_pretrained('bert-base-uncased')\n for param in self.bert.parameters():\n param.requires_grad = False\n\n\n def forward(self, x):\n transcripts, video, audio, speakers = x\n speakers.squeeze_(0)\n if self.config.use_texts:\n indept_embeds = self.embed_text(transcripts)\n if self.config.use_our_audio:\n audio = [audio[i][0] for i in range(len(audio))]\n audio_fixed = torch.cat(audio, dim=0).float().to('cuda')\n audio_fixed = self.audio_W_fixed_1(audio_fixed).unsqueeze(0)\n if self.config.use_texts:\n indept_embeds = torch.cat([indept_embeds, audio_fixed], dim=2)\n context_embeds = self.context_encoder(indept_embeds)[0].squeeze(0)\n #face_embeds = self.face_module(video)\n relation_matrices = self.construct_edges_relations(context_embeds, speakers)\n pred_adj, suc_adj, same_speak_adj, diff_adj_matrix, attn = relation_matrices\n \n h1 = self.pred_rel_l1(context_embeds, pred_adj)\n h1 += self.suc_rel_l1(context_embeds, suc_adj)\n h1 += self.same_speak_rel_l1(context_embeds, same_speak_adj)\n h1 += self.diff_speak_rel_l1(context_embeds, diff_adj_matrix)\n h1 = torch.relu(h1 + torch.matmul(context_embeds, self.w_aggr_1) * attn.diag().unsqueeze(1))\n \n h2 = self.pred_rel_l2(h1, pred_adj)\n h2 += self.suc_rel_l2(h1, suc_adj)\n h2 += self.same_speak_rel_l2(h1, same_speak_adj)\n h2 += self.diff_speak_rel_l2(h1, diff_adj_matrix)\n h2 = torch.relu(h2 + torch.matmul(h1, self.w_aggr_2) * attn.diag().unsqueeze(1))\n h = torch.cat([h2, context_embeds], dim=1)\n return self.w_emotion_2(torch.relu(self.w_emotion_1(h))), self.w_sentiment(h)\n \n def embed_text(self, utterances):\n # Input is a tensor of size N x L x G\n # N - number of utterances\n # L - length of longest (in # of words) utterance\n # G - dimention of Glove embeddings\n lengths = []\n texts = []\n for i, utt in enumerate(utterances):\n input_ids = torch.tensor([self.tokenizer.encode(utt[0])]).to(\"cuda\")\n hidden_states = self.bert(input_ids)[0]\n texts.append(hidden_states.squeeze(0))\n lengths.append(hidden_states.size(1))\n texts = pad_sequence(texts, batch_first=True)\n lengths = torch.LongTensor(lengths)\n # Sort utterance transcripts in decreasing order by the number of words\n sorted_lengths, sorted_idx = lengths.sort(descending=True)\n texts = texts[sorted_idx]\n # Pack -> rnn -> unpack (to handle variable-length sequences)\n texts = pack_padded_sequence(texts, lengths=sorted_lengths, batch_first=True)\n encoded_text = pad_packed_sequence(self.text_encoder(texts)[0], batch_first=True)[0]\n # Attention over word sequences\n averaged_vectors = []\n for i, seq in enumerate(encoded_text):\n word_vecs = seq[0:sorted_lengths[i], :]\n text_raw_attn = self.text_attn(word_vecs)\n text_attn = torch.softmax(text_raw_attn, dim=0)\n att_vec = word_vecs * text_attn\n averaged_vectors.append(att_vec.sum(dim=0))\n encoded_text = torch.stack(averaged_vectors, dim=0)\n # Sorts back to original order\n _, orig_idx = sorted_idx.sort(0)\n encoded_text = encoded_text[orig_idx].unsqueeze(0)\n return encoded_text \n\n def embed_audio(self, audio):\n lengths = []\n audios = []\n for i, utt in enumerate(audio):\n utt = utt.squeeze(0)\n audio_feat = self.audio_W_temp_2(torch.relu(self.audio_W_temp_1(utt.to(\"cuda\"))))\n audios.append(audio_feat)\n lengths.append(audio_feat.size(0))\n audios = pad_sequence(audios, batch_first=True)\n lengths = torch.LongTensor(lengths)\n # Sort utterance transcripts in decreasing order by the number of words\n sorted_lengths, sorted_idx = lengths.sort(descending=True)\n audios = audios[sorted_idx]\n # Pack -> rnn -> unpack (to handle variable-length sequences)\n audios = pack_padded_sequence(audios, lengths=sorted_lengths, batch_first=True)\n encoded_audio = pad_packed_sequence(self.audio_rnn(audios)[0], batch_first=True)[0]\n # Attention over word sequences\n averaged_vectors = []\n for i, seq in enumerate(encoded_audio):\n audio_vecs = seq[0:sorted_lengths[i], :]\n audio_raw_attn = self.audio_attn(audio_vecs)\n audio_attn = torch.softmax(audio_raw_attn, dim=0)\n att_vec = audio_vecs * audio_attn\n averaged_vectors.append(att_vec.sum(dim=0))\n encoded_audio = torch.stack(averaged_vectors, dim=0)\n # Sorts back to original order\n _, orig_idx = sorted_idx.sort(0)\n encoded_audio = encoded_audio[orig_idx].unsqueeze(0)\n #print(encoded_audio.size())\n return encoded_audio \n \n def construct_edges_relations(self, ut_embs, speaker_ids):\n # ut_embs is a tensor of size N x D\n # N - number of utterances\n # D - dimention of utterance embedding\n # speaker is a list of size N corresponding\n # to speaker ids for each utterance\n num_utts = len(ut_embs)\n raw_attn = self.edge_att_weights(ut_embs)\n attn = torch.zeros(num_utts, num_utts).to(\"cuda\")\n for i in range(num_utts):\n curr_utt = ut_embs[i]\n left_bdry = max(0, i - self.att_window_size)\n right_bdry = min(num_utts, i + self.att_window_size + 1)\n for j in range(left_bdry, right_bdry):\n attn[i, j] = curr_utt.dot(ut_embs[j])\n attn = torch.softmax(attn, dim=1)\n relation_matrices = self.build_relation_matrices(ut_embs, speaker_ids, attn)\n return relation_matrices\n \n def build_relation_matrices(self, ut_embs, speaker_ids, attn_mask):\n num_utt = len(ut_embs)\n num_speakers = len(np.unique(speaker_ids))\n pred_adj = torch.ones(num_utt, num_utt, dtype=torch.float).triu(0).to(\"cuda\")\n suc_adj = 1 - pred_adj\n same_adj_matrix = torch.zeros(num_utt, num_utt, dtype=torch.long).to(\"cuda\")\n for i in range(num_speakers):\n same_speak_indices = speaker_ids == i\n same_adj_matrix[same_speak_indices] = same_speak_indices.long().to(\"cuda\")\n diff_adj_matrix = 1 - same_adj_matrix.byte()\n same_adj_pred = same_adj_matrix.float() * pred_adj.float() * attn_mask\n same_adj_post = same_adj_matrix.float() * suc_adj.float() * attn_mask\n diff_adj_pred = diff_adj_matrix.float() * pred_adj.float() * attn_mask\n diff_adj_post = diff_adj_matrix.float() * suc_adj.float() * attn_mask\n return same_adj_pred, same_adj_post, diff_adj_pred, diff_adj_post, attn_mask\n \n \"\"\"\n \"\"\"","sub_path":"models/dialogue_gcn_2.py","file_name":"dialogue_gcn_2.py","file_ext":"py","file_size_in_byte":9704,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"460384527","text":"# _*_ coding:utf-8 _*_\n# Author:Atlantis\n# Date:2020-01-14\n\nimport json\nimport time\nfrom kafka import KafkaProducer\n\n\nclass AsyncWrite(object):\n def __init__(self):\n self.kafka_ips = \"xx.111.127.121:9092,xx.111.148.96:9092,xx.111.154.168:9092\"\n self.producer = None\n\n def reconnect(self):\n config = {\n \"bootstrap_servers\": self.kafka_ips,\n \"value_serializer\": lambda v: json.dumps(v).encode('utf-8')\n }\n self.producer = KafkaProducer(**config)\n\n def write(self, info):\n self.producer.send(\"test\", info)\n\n @staticmethod\n def test(info):\n time.sleep(5)\n with open(\"/Users/wqq/PycharmProjects/py-kafka-test/log/test.log\", \"a+\") as f:\n f.write(info)\n print(\"日志写入完毕。。。\")\n\n","sub_path":"utils/resultlog.py","file_name":"resultlog.py","file_ext":"py","file_size_in_byte":796,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"436364248","text":"# -*- coding: utf-8 -*-\n\nfrom benedict.serializers.abstract import AbstractSerializer\nfrom benedict.serializers.base64 import Base64Serializer\nfrom benedict.serializers.csv import CSVSerializer\nfrom benedict.serializers.json import JSONSerializer\nfrom benedict.serializers.pickle import PickleSerializer\nfrom benedict.serializers.query_string import QueryStringSerializer\nfrom benedict.serializers.toml import TOMLSerializer\nfrom benedict.serializers.xml import XMLSerializer\nfrom benedict.serializers.yaml import YAMLSerializer\n\n_BASE64_SERIALIZER = Base64Serializer()\n_CSV_SERIALIZER = CSVSerializer()\n_JSON_SERIALIZER = JSONSerializer()\n_PICKLE_SERIALIZER = PickleSerializer()\n_QUERY_STRING_SERIALIZER = QueryStringSerializer()\n_TOML_SERIALIZER = TOMLSerializer()\n_YAML_SERIALIZER = YAMLSerializer()\n_XML_SERIALIZER = XMLSerializer()\n\n_SERIALIZERS = {\n 'b64': _BASE64_SERIALIZER,\n 'base64': _BASE64_SERIALIZER,\n 'csv': _CSV_SERIALIZER,\n 'json': _JSON_SERIALIZER,\n 'pickle': _PICKLE_SERIALIZER,\n 'qs': _QUERY_STRING_SERIALIZER,\n 'querystring': _QUERY_STRING_SERIALIZER,\n 'query-string': _QUERY_STRING_SERIALIZER,\n 'query_string': _QUERY_STRING_SERIALIZER,\n 'toml': _TOML_SERIALIZER,\n 'yaml': _YAML_SERIALIZER,\n 'yml': _YAML_SERIALIZER,\n 'xml': _XML_SERIALIZER,\n}\n\n_SERIALIZERS_EXTENSIONS = [\n '.{}'.format(extension) for extension in _SERIALIZERS.keys()]\n\n\ndef get_format_by_path(path):\n path = path.lower()\n for extension in _SERIALIZERS_EXTENSIONS:\n if path.endswith(extension):\n return extension[1:]\n return None\n\n\ndef get_serializer_by_format(format):\n return _SERIALIZERS.get((format or '').lower().replace(' ', '_'))\n\n\ndef get_serializers_extensions():\n return list(_SERIALIZERS_EXTENSIONS)\n","sub_path":"benedict/serializers/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":1774,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"246386751","text":"import turtle\n\na = []\n\ndef get_turtle_state(t):\n return t.heading(), t.position()\n\ndef restore(t, state):\n t.setheading(state[0])\n t.setposition(state[1][0], state[1][1])\n\ndef process(str, t):\n new = \"\"\n for c in str:\n if(c == 'X'):\n new += 'YF+XF+Y'\n elif c == 'Y':\n new += 'XF-YF-X'\n else:\n new += c\n return new\n\ndef createLSystem(Iters, axiom, t):\n create = axiom\n next = \"\"\n for i in range(Iters):\n next = process(create, t)\n create = next\n # print(i, create)\n \n return next\n\ndef drawLsystem(aTurtle, str, angle, dist):\n for c in str:\n if c == 'F':\n aTurtle.forward(dist)\n elif c == '+':\n aTurtle.right(angle)\n elif c == '-':\n aTurtle.left(angle)\n elif c == '[':\n a.append(get_turtle_state(aTurtle))\n elif c == ']':\n aTurtle.up()\n restore(aTurtle, a.pop())\n aTurtle.down()\n\n\n\ndef main():\n t = turtle.Turtle()\n inst = createLSystem(7, \"YF\", t)\n wn = turtle.Screen()\n\n t.up()\n t.forward(100)\n t.backward(0)\n t.right(90)\n t.forward(200)\n t.right(90)\n t.right(90)\n t.down()\n t.speed(1000)\n drawLsystem(t, inst, 60, 2)\n\n wn.exitonclick()\n\nmain()\n","sub_path":"sierpinski-triangle.py","file_name":"sierpinski-triangle.py","file_ext":"py","file_size_in_byte":1310,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"546254579","text":"# -*- coding:utf-8 -*- \n\nfrom django.http import Http404\nfrom django.shortcuts import render, redirect, get_object_or_404, get_list_or_404\nfrom django.core.paginator import Paginator, PageNotAnInteger, EmptyPage\nfrom . import models\nfrom . import forms\n\n\n# Global context\nclass GlobalContext:\n\tcategories = models.Category.objects.all()\n\trecent_post = models.Post.objects.all()[:10]\n\ttags = models.Tag.objects.all()[:20]\n\n# Functional functions.\ndef if_page_number(page_number, paginator):\n\tif page_number:\n\t\ttry:\n\t\t\tpost_list = paginator.page(page_number)\n\t\t\treturn post_list\n\t\texcept PageNotAnInteger:\n\t\t\traise Http404('Page not an integer')\n\t\texcept EmptyPage:\n\t\t\traise Http404('Empty page')\n\telse:\n\t\tpost_list = paginator.page(1)\n\t\treturn post_list\n\n# Create your views here.\ndef index_view(request):\n\tpage_number = request.GET.get('page')\n\tposts = models.Post.objects.all()\n\tpaginator = Paginator(posts, 10)\n\tpage_range = paginator.page_range\n\tpost_list = if_page_number(page_number, paginator)\n\treturn render(request, 'blog/index.html', \n\t\t{'post_list' : post_list, \n\t\t 'page_range' : page_range,\n\t\t 'categories' : GlobalContext.categories,\n\t\t 'recent_post' : GlobalContext.recent_post,\n\t\t 'tags' : GlobalContext.tags,\n\t\t})\n\ndef category_view(request, c):\n\tcategory = get_object_or_404(models.Category, category_eng=c)\n\tposts = category.post_set.all()\n\tpage_number = request.GET.get('page')\n\tpaginator = Paginator(posts, 10)\t\n\tpage_range = paginator.page_range\n\tpost_list = if_page_number(page_number, paginator)\n\treturn render(request, 'blog/categoried_post_list.html', \n\t\t{'post_list' : post_list,\n\t\t 'page_range' : page_range,\n\t\t 'categories' : GlobalContext.categories,\n\t\t 'recent_post' : GlobalContext.recent_post,\n\t\t 'category' : category,\n\t\t 'tags' : GlobalContext.tags,\n\t\t})\n\ndef tag_view(request):\n\ttag = get_object_or_404(models.Tag, tag_name=request.GET.get('tag'))\n\tpage_number = request.GET.get('page')\n\tposts = tag.post_set.all()\n\tpaginator = Paginator(posts, 10)\n\tpage_range = paginator.page_range\n\tpost_list = if_page_number(page_number, paginator)\n\treturn render(request, 'blog/tag_post_list.html',\n\t\t{'post_list' : post_list,\n\t\t 'page_range' : page_range,\n\t\t 'tag' : tag,\n\t\t 'categories' : GlobalContext.categories,\n\t\t 'recent_post': GlobalContext.recent_post,\n\t\t 'tags' : GlobalContext.tags,\n\t\t})\n\ndef archive_view(request):\n\tpage_number = request.GET.get('page')\n\tposts = models.Post.objects.all()\n\tpaginator = Paginator(posts, 10)\n\tpage_range = paginator.page_range\n\tpost_list = if_page_number(page_number, paginator)\n\treturn render(request, 'blog/archived.html', \n\t\t{'post_list' : post_list,\n\t\t 'page_range' : page_range,\n\t\t 'categories' : GlobalContext.categories,\n\t\t 'recent_post' : GlobalContext.recent_post,\n\t\t 'tags' : GlobalContext.tags,\n\t\t})\n\ndef read_view(request, id):\n\tpost = get_object_or_404(models.Post, pk=id)\n\tpost.post_pageviews += 1\n\tpost.save()\n\tif request.method == 'POST':\n\t\tform = forms.CommentForm(request.POST)\n\t\tif form.is_valid():\n\t\t\tcomment = models.Comment(comment_name=form.cleaned_data['comment_name'],\n\t\t\t\t\t\t\t\t\t comment_mail=form.cleaned_data.get('comment_mail'),\n\t\t\t\t\t\t\t\t\t comment_site=form.cleaned_data.get('comment_site'),\n\t\t\t\t\t\t\t\t\t comment_body=form.cleaned_data['comment_body'],\n\t\t\t\t\t\t\t\t\t comment_post=post)\n\t\t\tcomment.save()\n\t\t\treturn redirect('blog:read_url', id=id)\n\telse:\n\t\tform = forms.CommentForm()\n\treturn render(request, 'blog/single.html',\n\t\t{'post' : post,\n\t\t 'categories' : GlobalContext.categories,\n\t\t 'recent_post' : GlobalContext.recent_post,\n\t\t 'form' : form,\n\t\t 'tags' : GlobalContext.tags,\n\t\t})\n\n\t\n# One-step views.\ndef about_view(request):\n\treturn render(request, 'blog/about.html',\n\t\t{'categories' : GlobalContext.categories,\n\t\t 'recent_post': GlobalContext.recent_post,\n\t\t 'tags' : GlobalContext.tags,\n\t\t})\n\ndef message_view(request):\n\tmessages = models.Message.objects.all()\n\tif request.method == 'POST':\n\t\tform = forms.MessageForm(request.POST)\n\t\tif form.is_valid():\n\t\t\tmessage = models.Message(message_name=form.cleaned_data['message_name'],\n\t\t\t\t\t\t\t\t\t message_mail=form.cleaned_data.get('message_mail'),\n\t\t\t\t\t\t\t\t\t message_site=form.cleaned_data.get('message_site'),\n\t\t\t\t\t\t\t\t\t message_body=form.cleaned_data['message_body'])\n\t\t\tmessage.save()\n\t\t\treturn redirect('blog:message_url')\n\telse:\n\t\tform = forms.MessageForm()\n\treturn render(request, 'blog/message.html',\n\t\t{'messages' : messages,\n\t\t 'categories' : GlobalContext.categories,\n\t\t 'recent_post': GlobalContext.recent_post,\n\t\t 'tags' : GlobalContext.tags,\n\t\t 'form' : form,\n\t\t })\n\n\n","sub_path":"blog/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":4629,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"373427587","text":"#-*-coding=utf-8-*-\n'''\n排序算法之:侏儒排序法\n从小到大排序\n最好情况复杂度O(n)\n最坏情况复杂度O(n**2)\n'''\ndef gnomesort(seq):\n i = 0\n while i < len(seq):\n if i == 0 or seq[i-1] < seq[i]:\n i += 1\n else:\n seq[i],seq[i-1] = seq[i-1],seq[i]\n i -= 1\n return seq\n\n\nseq = [2,5,1,8,3,7,9]\nprint(gnomesort(seq))\n","sub_path":"Aigorithm/gnomesort.py","file_name":"gnomesort.py","file_ext":"py","file_size_in_byte":389,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"200342211","text":"import ui\nclass DropletView (object):\n\tdef __init__(self, droplet):\n\t\tself.droplet = droplet\n\t\tself.detailSection = 0\n\t\tself.hardwareSection = 1\n\t\tself.featuresSection = 2\n\t\tself.backupSection = 3\n\t\tself.snapshotSection = 4\n\t\tself.networkSection = 5\n\t\n\tdef tableview_title_for_header(self, tableview, section):\n\t\tif section == self.detailSection:\n\t\t\treturn 'Detail'\n\t\tif section == self.hardwareSection:\n\t\t\treturn 'Hardware'\n\t\tif section == self.featuresSection:\n\t\t\treturn 'Features'\n\t\tif section == self.backupSection:\n\t\t\treturn 'Backups'\n\t\tif section == self.snapshotSection:\n\t\t\treturn 'Snapshots'\n\t\tif section == self.networkSection:\n\t\t\treturn 'Networks'\n\t\t\t\n\tdef tableview_did_select(self, tableview, section, row):\n\t\tpass\n\t\t\n\tdef tableview_number_of_sections(self, tableview):\n\t\treturn 6\n\n\tdef tableview_number_of_rows(self, tableview, section):\n\t\tif section == self.detailSection:\n\t\t\treturn 9\n\t\tif section == self.hardwareSection:\n\t\t\treturn 3\n\t\tif section == self.featuresSection:\n\t\t\treturn len(self.droplet.features)\n\t\tif section == self.backupSection:\n\t\t\treturn len(self.droplet.backup_ids)\n\t\tif section == self.snapshotSection:\n\t\t\treturn len(self.droplet.snapshot_ids)\n\t\tif section == self.networkSection:\n\t\t\treturn len(self.droplet.networks)\n\t\t\n\tdef tableview_cell_for_row(self, tableview, section, row):\n\t\tmain, detail = self.get_cell_details(section, row)\n\t\tcell = ui.TableViewCell('value1')\n\t\tcell.text_label.text = str(main)\n\t\tcell.detail_text_label.text = str(detail)\n\t\treturn cell\n\t\n\tdef get_cell_details(self, section, row):\n\t\tif section == self.detailSection:\n\t\t\tif row == 0:\n\t\t\t\treturn 'Id', self.droplet.id\n\t\t\tif row == 1:\n\t\t\t\treturn 'Name', self.droplet.name\n\t\t\tif row == 2:\n\t\t\t\treturn 'Locked', self.droplet.locked\n\t\t\tif row == 3:\n\t\t\t\treturn 'Status', self.droplet.status\n\t\t\tif row == 4:\n\t\t\t\treturn 'Kernel', self.droplet.kernel\n\t\t\tif row == 5:\n\t\t\t\treturn 'Created at', self.droplet.created_at\n\t\t\tif row == 6:\n\t\t\t\treturn 'Image', self.droplet.image.name\n\t\t\tif row == 7:\n\t\t\t\treturn 'Size', self.droplet.size_slug\n\t\t\tif row == 8:\n\t\t\t\treturn 'Region', self.droplet.region.name\n\t\t\t\n\t\tif section == self.hardwareSection:\n\t\t\tif row == 0:\n\t\t\t\treturn 'Memory', self.droplet.memory\n\t\t\tif row == 1:\n\t\t\t\treturn 'vCPUs', self.droplet.vcpus\n\t\t\tif row == 2:\n\t\t\t\treturn 'Disk', self.droplet.disk\n\t\tif section == self.featuresSection:\n\t\t\treturn self.droplet.features[row], ''\n\t\tif section == self.backupSection:\n\t\t\treturn self.droplet.backup_ids[row], ''\n\t\tif section == self.snapshotSection:\n\t\t\treturn self.droplet.snapshot_ids[row], ''\n\t\tif section == self.networkSection:\n\t\t\tkey = self.droplet.networks.keys()[row]\n\t\t\tvalue = self.droplet.networks[key]\n\t\t\tif len(value)> 0:\n\t\t\t\tvalue = value[0].ip_address\n\t\t\telse:\n\t\t\t\tvalue = None\n\t\t\treturn key, value\n\ndef get_view(droplet):\n\ttest = DropletView(droplet = droplet)\n\ttable_view = ui.TableView('grouped')\n\ttable_view.name = 'Droplet'\n\ttable_view.data_source = test\n\ttable_view.delegate = test\n\ttable_view.flex = 'WH'\n\treturn table_view\n","sub_path":"Views/DropletView.py","file_name":"DropletView.py","file_ext":"py","file_size_in_byte":2994,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"357150995","text":"# -*- coding: utf-8 -*-\n# @Author: lzc\n# @Time : 2019/9/26\nimport os\nfrom datetime import datetime, timedelta\n\n\ndef rm_log(path):\n file_li = os.listdir(path)\n for i in file_li:\n # 当前日期\n date_now = datetime.now()\n # 日志文件的日期\n date_log = i.split('__')[0]\n date_log = date_log.replace(\".log\", '')\n date_log = datetime.strptime(date_log, '%Y-%m-%dT%H_%M_%S')\n # 二者相差的天数\n day = (date_now - date_log).days\n # 删除 2 天前的日志文件\n if day >= 2:\n os.remove(os.path.join(path, i))\n","sub_path":"rm_log.py","file_name":"rm_log.py","file_ext":"py","file_size_in_byte":605,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"220732337","text":"\"\"\"\nTraining of Resnet-50 model in TF2 for animal detection\n\"\"\"\n\nimport os\nimport numpy as np \nimport tensorflow as tf \nimport matplotlib.pyplot as plt \nimport json\nimport pandas as pd\nfrom pathlib import Path\n####\n# Create the input pipeline\n####\n\n\n#### Parameters\nroot_dir = \"E:/wellington_pics/wct_images/images/\"\nroot_dir = \"E:\\\\wellington_pics\\\\wct_images\\\\images\\\\\"\nlabel_file = Path(\"E:/wellington_pics/wellington_camera_traps.json\")\nmodel_dir = Path(\"E:/wellington_pics/model_dir\")\nmodel_save_path = model_dir / \"resnet50_keras\"\nlite_model_path = model_dir / \"resnet50_tflite\"\nlog_dir = Path(\"E:/wellington_pics/model_dir/log_dir\")\nIMG_SHAPE = (244, 244, 3)\nIMG_SIZE = (244, 244)\nlr = 0.00001\nbatch_size = 32\n\n\nwith open(label_file) as f:\n labels = json.load(f)\n\ncategories = pd.DataFrame(labels['categories'])\nannotation = pd.DataFrame.from_dict(labels['annotations'])\nimages = pd.DataFrame.from_dict(labels['images'])\n\n# Make dataframe from anntations\nannotation['filename'] = [root_dir + x + \".JPG\" for x in list(annotation.image_id)]\nclass_labels = [str(x) for x in list(annotation.category_id)]\nannotation['class'] = np.array(class_labels)\n\n# Create the TF dataset (adjusted from https://stackoverflow.com/questions/44416764/loading-folders-of-images-in-tensorflow)\nimage_paths = list(annotation.filename)\nlabels = list(annotation.category_id)\n\nepoch_size = len(image_paths)\nimage_paths = tf.convert_to_tensor(image_paths, dtype=tf.string)\nlabels = tf.convert_to_tensor(labels)\n\ndataset = tf.data.Dataset.from_tensor_slices((image_paths, labels))\n\ndataset = dataset.repeat().shuffle(epoch_size)\n\ndef map_fn(path, label, IMG_SIZE=IMG_SIZE):\n # Load image, resize to (244, 244) and normalize, return label as is\n image = tf.image.decode_jpeg(tf.io.read_file(path))\n image = tf.image.resize(image, IMG_SIZE)\n image = (image/127.5) - 1\n return image, label\n\n\n\ndataset = dataset.map(map_fn, num_parallel_calls=8)\ndataset = dataset.batch(batch_size)\n# try one of the following\nAUTOTUNE = tf.data.experimental.AUTOTUNE\ndataset = dataset.prefetch(buffer_size=AUTOTUNE)\n\n# split into train and validation dataset\ntest_dataset = dataset.take(1000) \ntrain_dataset = dataset.skip(1000)\n\n#==== end dataset creation ====#\n\nIMG_SHAPE = (244, 244, 3)\n\n# Create the model\nbase_model = tf.keras.applications.ResNet50(input_shape=IMG_SHAPE, include_top=False, weights=\"imagenet\")\nglobal_average_layer = tf.keras.layers.GlobalAveragePooling2D()\nprediction_layer = tf.keras.layers.Dense(17)\nmodel = tf.keras.Sequential([\n base_model,\n global_average_layer,\n prediction_layer\n])\n\n\n\nload_pretrained = False\nif load_pretrained:\n model = tf.keras.models.load_model(str(model_save_path))\n\n# Compile the model\nlr = 1e-6\nmodel.compile(optimizer=tf.keras.optimizers.Adam(lr=lr), loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True), metrics=[\"accuracy\"])\n\ntensorboard_callback = tf.keras.callbacks.TensorBoard(log_dir=str(log_dir))\n\n\n# Perform the training\nsteps_per_epoch = 240000 / batch_size\nmodel.fit(x=train_dataset, validation_data=test_dataset, epochs=10, steps_per_epoch=steps_per_epoch, callbacks=[tensorboard_callback], validation_steps=30)\n\n# Save the trained model\n\nmodel.save(str(model_save_path)) \n\n# Convert model to tensorflow-lite\n\nconverter = tf.lite.TFLiteConverter.from_saved_model(str(model_save_path))\ntflite_model = converter.convert()\n\n# Save the TF Lite model.\nwith tf.io.gfile.GFile(str(lite_model_path), 'wb') as f:\n f.write(tflite_model)\n# Also save in this github repo\nwith tf.io.gfile.GFile(\"resnet50_tflite\", 'wb') as f:\n f.write(tflite_model)\n\n","sub_path":"resnet_training_tf2.py","file_name":"resnet_training_tf2.py","file_ext":"py","file_size_in_byte":3610,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"258322765","text":"from pykechain.exceptions import NotFoundError, MultipleFoundError, APIError\nfrom pykechain.models import Part, PartSet\nfrom tests.classes import TestBetamax\n\n\nclass TestParts(TestBetamax):\n def test_retrieve_parts(self):\n parts = self.project.parts()\n\n # Check if there are parts\n assert len(parts)\n\n def test_retrieve_single_part(self):\n part = self.project.part('Front Wheel')\n\n assert part\n\n def test_retrieve_single_unknown(self):\n with self.assertRaises(NotFoundError):\n self.project.part('123lladadwd')\n\n def test_retrieve_single_multiple(self):\n with self.assertRaises(MultipleFoundError):\n self.project.part()\n\n def test_retrieve_models(self):\n project = self.client.scope('Bike Project')\n wheel = project.model('Wheel')\n\n assert project.parts(model=wheel)\n\n def test_retrieve_model_unknown(self):\n with self.assertRaises(NotFoundError):\n self.client.model('123lladadwd')\n\n def test_retrieve_model_multiple(self):\n with self.assertRaises(MultipleFoundError):\n self.client.model()\n\n def test_part_set_iterator(self):\n for part in self.project.parts():\n assert part.name\n\n def test_part_set_get_item_invalid(self):\n part_set = self.project.parts()\n\n with self.assertRaises(NotImplementedError):\n part_set['testing']\n\n def test_part_add_delete_part(self):\n project = self.client.scope('Bike Project')\n\n bike = project.part('Bike')\n wheel_model = project.model('Wheel')\n\n wheel = bike.add(wheel_model, name='Test Wheel')\n wheel.delete()\n\n wheel = wheel_model.add_to(bike)\n wheel.delete()\n\n with self.assertRaises(APIError):\n bike.delete()\n\n def test_part_html_table(self):\n part = self.project.part('Front Wheel')\n\n assert \"\" in part._repr_html_()\n\n def test_part_set_html_table(self):\n parts = self.project.parts()\n\n assert \"\" in parts._repr_html_()\n\n def test_part_set_html_categories(self):\n parts = self.project.parts(category=None)\n\n assert \"Category\" in parts._repr_html_()\n\n # version 1.1.2 and later\n def test_part_set_with_limit(self):\n limit = 5\n parts = self.project.parts(limit=limit)\n\n assert len(parts) == limit\n\n def test_part_set_with_batch(self):\n batch = 5\n parts = self.project.parts(batch=batch)\n assert len(parts) >= batch\n\n # version 1.1.3 and later\n def test_retrieve_parent_of_part(self):\n frame = self.project.part('Frame') # type:Part\n assert hasattr(frame, 'parent_id')\n parent_of_frame = frame.parent()\n assert type(parent_of_frame) is type(frame)\n\n def test_retrieve_children_of_part(self):\n bike = self.project.part('Bike') # type:Part\n assert type(bike) is Part\n children_of_bike = bike.children()\n assert type(children_of_bike) is PartSet\n assert len(children_of_bike) >= 1 # eg. Wheels ...\n\n def test_retrieve_siblings_of_part(self):\n \"\"\"Test if the siblings of a part is the same as the children of the parent of the part\"\"\"\n frame = self.project.part('Frame') # type:Part\n siblings_of_frame = frame.siblings()\n assert type(siblings_of_frame) is PartSet\n assert len(siblings_of_frame) >= 1 # eg. Wheels ...\n\n # double check that the children of the parent of frame are the same as the siblings of frame\n children_of_parent_of_frame = frame.parent().children() # type: PartSet\n assert len(children_of_parent_of_frame) == len(siblings_of_frame)\n children_of_parent_of_frame_ids = [p.id for p in children_of_parent_of_frame]\n for sibling in siblings_of_frame:\n assert sibling.id in children_of_parent_of_frame_ids, \\\n 'sibling {} is appearing in the siblings method and not in the children of ' \\\n 'parent method'.format(sibling)\n\n def test_retrieve_part_without_parent_id(self):\n # only the root does not have a parent_id\n ROOT_NODE_ID = 'f521333e-a1ed-4e65-b166-999f91a38cf1'\n root_node = self.project.part(pk=ROOT_NODE_ID) # type: Part\n assert hasattr(root_node, 'parent_id')\n assert root_node.parent_id == None\n\n def test_retrieve_parent_of_part_without_parent_id(self):\n # only the root does not have a parent_id\n ROOT_NODE_ID = 'f521333e-a1ed-4e65-b166-999f91a38cf1'\n root_node = self.project.part(pk=ROOT_NODE_ID) # type: Part\n parent_of_rootnode = root_node.parent()\n assert parent_of_rootnode is None\n\n def test_retrieve_siblings_of_part_without_parent_id(self):\n ROOT_NODE_ID = 'f521333e-a1ed-4e65-b166-999f91a38cf1'\n root_node = self.project.part(pk=ROOT_NODE_ID) # type: Part\n siblings_of_root_node = root_node.siblings()\n assert type(siblings_of_root_node) is PartSet\n assert len(siblings_of_root_node) is 0\n\n # new in 1.3+\n def test_kwargs_on_part_retrieval(self):\n # test that the additional kwargs are added to the query filter on the api\n bikes = self.project.parts('Bike', descendants=True) # type:Part\n assert len(bikes) > 1\n assert self.client.last_url.find('descendants')\n\n # new in 1.5+\n def test_edit_part_instance_name(self):\n front_fork = self.project.part('Front Fork')\n front_fork.edit(name='Front Fork - updated')\n\n front_fork_u = self.project.part('Front Fork - updated')\n assert front_fork.id == front_fork_u.id\n assert front_fork.name == front_fork_u.name\n assert front_fork.name == 'Front Fork - updated'\n\n front_fork.edit(name='Front Fork')\n\n def test_edit_part_instance_description(self):\n front_fork = self.project.part('Front Fork')\n front_fork.edit(description='A normal Front Fork')\n\n front_fork_u = self.project.part('Front Fork')\n assert front_fork.id == front_fork_u.id\n\n front_fork.edit(description='A perfectly normal Front Fork')\n\n def test_edit_part_model_name(self):\n front_fork = self.project.model('Front Fork')\n front_fork.edit(name='Front Fork - updated')\n\n front_fork_u = self.project.model('Front Fork - updated')\n assert front_fork.id == front_fork_u.id\n assert front_fork.name == front_fork_u.name\n\n front_fork.edit(name='Front Fork')\n\nclass TestPartUpdate(TestBetamax):\n def test_part_update_with_dictionary(self):\n # setup\n front_fork = self.project.part('Front Fork') # type: Part\n saved_front_fork_properties = dict([(p.name, p.value) for p in front_fork.properties])\n\n # do tests\n update_dict = {\n 'Material': 'Unobtanium',\n 'Height (mm)': 123.4,\n 'Color': 'Space Grey (old)'\n }\n front_fork.update(update_dict)\n refreshed_front_fork = self.project.part(pk=front_fork.id)\n for prop in refreshed_front_fork.properties:\n assert prop.name in update_dict, \"property with {} should be in the update dict\".format(prop.name)\n assert update_dict[prop.name] == prop.value, \"property {} with value {} did not match contents \" \\\n \"with KEC\".format(prop.name, prop.value)\n\n # tearDown\n for prop_name, prop_value in saved_front_fork_properties.items():\n front_fork.property(prop_name).value = prop_value\n\n def test_part_update_with_missing_property(self):\n # setup\n front_fork = self.project.part('Front Fork') # type: Part\n saved_front_fork_properties = dict([(p.name, p.value) for p in front_fork.properties])\n\n # do tests\n update_dict = {\n 'Unknown Property': 'Woot!'\n }\n with self.assertRaises(NotFoundError):\n front_fork.update(update_dict)\n\n # tearDown\n for prop_name, prop_value in saved_front_fork_properties.items():\n front_fork.property(prop_name).value = prop_value\n","sub_path":"tests/test_parts.py","file_name":"test_parts.py","file_ext":"py","file_size_in_byte":8138,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"164599951","text":"import numpy as np\nimport cv2\nface_cascade = cv2.CascadeClassifier(\"haarcascade_frontalface_default.xml\")\n\ncolor =cv2.imread('image.jpg')\n\n\n\nimg = cv2.cvtColor(color, cv2.COLOR_BGR2GRAY)\nfaces = face_cascade.detectMultiScale(img,1.3,5)\nfor(x,y,w,h) in faces:\n image = img[y:y+h,x:x+w]\n resized = cv2.resize(image, (413,413))\n cv2.imwrite(\"dataset/User.1.1.jpg\",resized)\n cv2.rectangle(color,(x,y),(x+w,y+h),(255,0,0),3)\n cv2.waitKey(100)\n\n\ncv2.imshow('img',color)\ncv2.waitKey(0)\n\n\n\n\n\n\n\ncv2.destroyAllWindows()\n","sub_path":"dataset.py","file_name":"dataset.py","file_ext":"py","file_size_in_byte":525,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"561042119","text":"import matplotlib.pyplot as plt\nfrom scipy.special import jn\nimport numpy as np\nimport math as ma\n\ndef pos_1(lista): #De vuelve las posiciones en que los elementos valen \"1\"\n ret=[]\n for i in range(len(lista)):\n if lista[i]==1:\n ret.append(i)\n return ret\ndef t_menor_periodo(tiempo,periodo):\n if tiempo<=periodo:\n return tiempo\n else:\n t_nueva=tiempo-periodo\n return t_menor_periodo(t_nueva,periodo)\ndef rad(x): #Conversor a radianes\n return(2*ma.pi*x/360)\ndef pos_el(el,lista): #Busca la posicion de un elemento en una lista\n pos=-1\n for i in range(len(lista)):\n if lista[i]==el:\n pos=i\n \n if pos==-1:\n return -23\n else:\n return pos\ndef sumatoria(tope,epsilon,periodo,tiempo):\n sumatoria=0\n cont=1\n while cont<=tope:\n sumatoria=sumatoria+(2/cont)*jn(cont,cont*epsilon)*ma.sin(2*ma.pi*tiempo*cont/periodo)\n cont=cont+1\n return sumatoria\ndef gira(pos,angulo): #Funcion que me hara el giro segun el parametro \"w\" del planeta\n if len(pos)!=2:\n return 'Error: posicion distinta a 2'\n else:\n return [pos[0]*ma.cos(angulo)-pos[1]*ma.sin(angulo),ma.sin(angulo)*pos[0]+ma.cos(angulo)*pos[1]]\n \nG=6.674e-11 #Constante grav. universal\nM=1.989e30 #Masa Solar\nnu=M*G*((1.49e11)**(-3))*86400**2 #Conversion segundo-dia y metro-unidad astronomica\n \np1=['Mercurio',0.387,0.206,87.97,rad(28.76),'b',3.302e23]\np2=['Venus',0.723,0.007,224.7,rad(54.37),'g',4.869e24]\np3=['Tierra',1,0.017,365.26,rad(101.22),'c',5.9722e24]\np4=['Marte',1.524,0.093,686.98,rad(285.44),'r',6.4185e23]\np5=['Jupiter',5.203,0.048,4332.6,rad(273.28),'y',1.899e27]\np6=['Saturno',9.546,0.056,10759,rad(338.3),'m',5.688e26]\np7=['Urano',19.2,0.047,30687,rad(95.57),'k',8.686e25]\np8=['Neptuno',30.09,0.009,60784,rad(273.15),'b',1.024e26]\nPlanetas=[p1,p2,p3,p4,p5,p6,p7,p8]\n#Aux=['me',p1,'ve',p2,'ti',p3,'ma',p4,'ju',p5,'sa',p6,'ur',p7,'ne',p8]\n\nimport tkinter as tk\nfrom tkinter import font #Cambia fuentes y letra\nfrom tkinter import messagebox\n\nclass Window(tk.Frame): #Window nombre opcional, Frame obligatorio\n def __init__(self, master = None): #Ventana vacia\n tk.Frame.__init__(self, master)\n \n self.master = master\n \n self.init_window() #init_window will be defined later\n \n def init_window(self):\n \n self.master.title('Trabajo Mecanica')#Name of the window\n \n self.pack(fill=tk.BOTH, expand=1)\n \n label_tiempo=tk.Label(self,text='Tiempo(Dias):',relief=tk.GROOVE)\n label_tiempo.pack()\n label_tiempo.place(x=3,y=18)\n tiempo=tk.Spinbox(self,from_=0,to=200,fg='grey',width=5)\n tiempo.pack()\n self.tiempo=tiempo\n tiempo.place(x=85,y=18)\n ######################################\n Fuente_calc=font.Font(family=\"Times\", size=10, weight=font.BOLD)\n Conj_planetas=tk.LabelFrame(self,text=\"Planetas\",padx=1,pady=1,font=Fuente_calc)\n Conj_planetas.pack(padx=10, pady=10)\n \n pl1=tk.IntVar(self)\n pl1.set(0)\n self.pl1=pl1\n mer=tk.Checkbutton(Conj_planetas, text='Mercurio',fg='red',variable=pl1,command=self.mer_check)\n mer.pack(anchor=tk.W)\n self.mer=mer\n \n pl2=tk.IntVar(self)\n pl2.set(0)\n self.pl2=pl2\n ven=tk.Checkbutton(Conj_planetas, text='Venus',fg='red',variable=pl2,command=self.ven_check)\n ven.pack(anchor=tk.W)\n self.ven=ven\n \n pl3=tk.IntVar(self)\n pl3.set(0)\n self.pl3=pl3\n tie=tk.Checkbutton(Conj_planetas, text='Tierra',fg='red',variable=pl3,command=self.tie_check)\n tie.pack(anchor=tk.W)\n self.tie=tie\n \n pl4=tk.IntVar(self)\n pl4.set(0)\n self.pl4=pl4\n mar=tk.Checkbutton(Conj_planetas, text='Marte',fg='red',variable=pl4,command=self.mar_check)\n mar.pack(anchor=tk.W)\n self.mar=mar\n \n pl5=tk.IntVar(self)\n pl5.set(0)\n self.pl5=pl5\n jup=tk.Checkbutton(Conj_planetas, text='Jupiter',fg='red',variable=pl5,command=self.jup_check)\n jup.pack(anchor=tk.W)\n self.jup=jup\n \n pl6=tk.IntVar(self)\n pl6.set(0)\n self.pl6=pl6\n sat=tk.Checkbutton(Conj_planetas, text='Saturno',fg='red',variable=pl6,command=self.sat_check)\n sat.pack(anchor=tk.W)\n self.sat=sat\n \n pl7=tk.IntVar(self)\n pl7.set(0)\n self.pl7=pl7\n ura=tk.Checkbutton(Conj_planetas, text='Urano',fg='red',variable=pl7,command=self.ura_check)\n ura.pack(anchor=tk.W)\n self.ura=ura\n \n pl8=tk.IntVar(self)\n pl8.set(0)\n self.pl8=pl8\n nep=tk.Checkbutton(Conj_planetas, text='Neptuno',fg='red',variable=pl8,command=self.nep_check)\n nep.pack(anchor=tk.W)\n self.nep=nep\n \n Conj_planetas.place(x=3,y=60)\n \n caja_resultados=tk.Listbox(self,width=80,height=26, highlightbackground = \"black\")\n caja_resultados.pack()\n caja_resultados.place(x=200,y=64)\n caja_resultados.insert(tk.END,'Introduzca los datos y presione \"calcular\".')\n self.caja_resultados=caja_resultados\n caja_resultados.configure(font=font.Font(family=\"Arial\",size=9))\n Fuente_res=font.Font(family=\"Times\", size=11, weight=font.BOLD)\n Resultado=tk.Label(self,text='Datos obtenidos:',bg='grey',font=Fuente_res)\n Resultado.pack()\n Resultado.place(x=400,y=45)\n ###########################################\n Boton_calculo=tk.Button(self,text='Calcula',width=10,height=1,font=Fuente_calc,bg = \"green\",command=self.calcula_datos)\n Boton_calculo.pack()\n Boton_calculo.place(x=90,y=80)\n self.Boton_calculo=Boton_calculo\n \n Boton_plot2D=tk.Button(self,text='Grafica 2D',width=10,height=1,font=Fuente_calc,bg = \"green\",command=self.dibuja_datos)\n Boton_plot2D.pack()\n Boton_plot2D.place(x=90,y=110)\n self.Boton_plot2D=Boton_plot2D\n \n Boton_plot3D=tk.Button(self,text='Grafica 3D',width=10,height=1,font=Fuente_calc,bg = \"green\",command=self.not_yet)\n Boton_plot3D.pack()\n Boton_plot3D.place(x=90,y=135)\n self.Boton_plot3D=Boton_plot3D\n ##########################################\n caja_info=tk.Listbox(self,width=31,height=10, highlightbackground = \"blue\")\n caja_info.pack()\n caja_info.place(x=3,y=320)\n self.caja_info=caja_info\n caja_info.insert(tk.END,'...')\n self.caja_info=caja_info\n Fuente_info=font.Font(family=\"Times\", size=12, weight=font.BOLD)\n infor=tk.Label(self,text=' ? ',font=Fuente_info,bg='blue',fg='white',highlightbackground = \"black\")\n infor.pack()\n infor.place(x=83,y=298)\n \n Fuente_infos=font.Font(family=\"Times\", size=10, weight=font.BOLD)\n \n info_calcula=tk.Label(self,text=' ? ',font=Fuente_infos,bg='black',fg='white',highlightbackground = \"black\")\n info_calcula.pack()\n info_calcula.place(x=171,y=82)\n info_calcula.bind(\"\", self.ha_entrado_c)\n info_calcula.bind(\"\", self.ha_salido_c)\n \n info_2D=tk.Label(self,text=' ? ',font=Fuente_infos,bg='black',fg='white',highlightbackground = \"black\")\n info_2D.pack()\n info_2D.place(x=171,y=111)\n info_2D.bind(\"\", self.ha_entrado_2d)\n info_2D.bind(\"\", self.ha_salido_2d)\n \n info_3D=tk.Label(self,text=' ? ',font=Fuente_infos,bg='black',fg='white',highlightbackground = \"black\")\n info_3D.pack()\n info_3D.place(x=171,y=137)\n info_3D.bind(\"\", self.ha_entrado_3d)\n info_3D.bind(\"\", self.ha_salido_3d)\n ############################################\n menu = tk.Menu(self.master)\n self.master.config(menu=menu)\n \n file = tk.Menu(menu)\n file.add_command(label='Info', command=self.client_info)\n file.add_command(label='Cerrar', command=self.client_exit)\n menu.add_cascade(label='Archivo', menu=file)\n \n fuen = tk.Menu(menu)\n fuen.add_command(label='Times', command=self.times)\n fuen.add_command(label='Courier New', command=self.cou)\n fuen.add_command(label='Arial', command=self.aria)\n fuen.add_command(label='Comic Sans MS', command=self.comic)\n fuen.add_command(label='Symbol', command=self.symb)\n fuen.add_command(label='Verdana', command=self.verd)\n fuen.add_command(label='Fixedsys', command=self.fide)\n menu.add_cascade(label='Fuente', menu=fuen)\n \n def times(self):\n fuente_func=font.Font(family=\"Times\",size=9)\n self.caja_resultados.configure(font=fuente_func)\n def cou(self):\n fuente_func=font.Font(family=\"Courier New\",size=9)\n self.caja_resultados.configure(font=fuente_func)\n def aria(self):\n fuente_func=font.Font(family=\"Arial\",size=9)\n self.caja_resultados.configure(font=fuente_func)\n def comic(self):\n fuente_func=font.Font(family=\"Comic Sans MS\",size=9)\n self.caja_resultados.configure(font=fuente_func)\n def symb(self):\n fuente_func=font.Font(family=\"Symbol\",size=9)\n self.caja_resultados.configure(font=fuente_func)\n def verd(self):\n fuente_func=font.Font(family=\"Verdana\",size=9)\n self.caja_resultados.configure(font=fuente_func)\n def fide(self):\n fuente_func=font.Font(family=\"Fixedsys\",size=9)\n self.caja_resultados.configure(font=fuente_func)\n \n def client_info(self):\n self.caja_info.delete(0,tk.END)\n self.caja_info.insert(tk.END,'En esta ventana se mostraran')\n self.caja_info.insert(tk.END,'posicion, distancia al sol,')\n self.caja_info.insert(tk.END,'velocidad, masa, etc, de los') \n self.caja_info.insert(tk.END,'planetas que se seleccionen')\n self.caja_info.insert(tk.END,'en el tiempo introducido.')\n def client_exit(self):\n exit()\n def ha_entrado_c(self,typ):\n self.caja_info.delete(0,tk.END)\n self.caja_info.insert(tk.END,'Se calcularan los datos pedidos')\n self.caja_info.insert(tk.END,'para los planetas escogidos,')\n self.caja_info.insert(tk.END,'para ello introduzca un valor') \n self.caja_info.insert(tk.END,'numerico en \"tiempo\"no negativo.')\n def ha_salido_c(self,typ):\n self.caja_info.delete(0,tk.END)\n self.caja_info.insert(tk.END,'...')\n def ha_entrado_2d(self,typ):\n self.caja_info.delete(0,tk.END)\n self.caja_info.insert(tk.END,'Se mostraran las trayectorias de ')\n self.caja_info.insert(tk.END,'los planetas escogidos, asi como ') \n self.caja_info.insert(tk.END,'su posicion en ellas, para ello') \n self.caja_info.insert(tk.END,'introduzca un valor numerico en') \n self.caja_info.insert(tk.END,'\"tiempo\" no negativo.')\n def ha_salido_2d(self,typ):\n self.caja_info.delete(0,tk.END)\n self.caja_info.insert(tk.END,'...')\n def ha_entrado_3d(self,typ):\n self.caja_info.delete(0,tk.END)\n self.caja_info.insert(tk.END,'Aun en proceso, mostrara las')\n self.caja_info.insert(tk.END,'trayectorias \\n de los planetas') \n self.caja_info.insert(tk.END,'en 3 dimensiones.')\n def ha_salido_3d(self,typ):\n self.caja_info.delete(0,tk.END)\n self.caja_info.insert(tk.END,'...')\n def mer_check(self):\n aux=self.pl1.get()\n if aux==1:\n self.mer.configure(fg='green')\n else:\n self.mer.configure(fg='red')\n def ven_check(self):\n aux=self.pl2.get()\n if aux==1:\n self.ven.configure(fg='green')\n else:\n self.ven.configure(fg='red')\n def tie_check(self):\n aux=self.pl3.get()\n if aux==1:\n self.tie.configure(fg='green')\n else:\n self.tie.configure(fg='red')\n def mar_check(self):\n aux=self.pl4.get()\n if aux==1:\n self.mar.configure(fg='green')\n else:\n self.mar.configure(fg='red')\n def jup_check(self):\n aux=self.pl5.get()\n if aux==1:\n self.jup.configure(fg='green')\n else:\n self.jup.configure(fg='red')\n def sat_check(self):\n aux=self.pl6.get()\n if aux==1:\n self.sat.configure(fg='green')\n else:\n self.sat.configure(fg='red')\n def ura_check(self):\n aux=self.pl7.get()\n if aux==1:\n self.ura.configure(fg='green')\n else:\n self.ura.configure(fg='red')\n def nep_check(self):\n aux=self.pl8.get()\n if aux==1:\n self.nep.configure(fg='green')\n else:\n self.nep.configure(fg='red')\n \n def not_yet(self):\n self.Boton_plot3D.configure(bg='grey')\n messagebox.showwarning('Aviso','Estamos trabajando en ello.')\n def dibuja_datos(self):\n try:\n a=float(self.tiempo.get())\n Planetas_seleccionados=[self.pl1.get(),self.pl2.get(),self.pl3.get(),self.pl4.get(),self.pl5.get(),self.pl6.get(),self.pl7.get(),self.pl8.get()]\n cont=0\n for p in Planetas_seleccionados:\n cont=cont+p\n if float(a)<0:\n self.Boton_plot2D.configure(bg='red')\n messagebox.showerror('Error de datos introducidos','La entrada de tiempo no es valida,\\n no se admiten tiempos negativos...')\n self.caja_resultados.insert(tk.END,)\n elif cont==0:\n self.Boton_plot2D.configure(bg='yellow')\n messagebox.showerror('Error de datos introducidos','No se ha seleccionado ningun planeta...')\n else:\n self.Boton_plot2D.configure(bg='green')\n Posiciones=pos_1(Planetas_seleccionados)\n Planetas_elegidos=[Planetas[i] for i in Posiciones]\n for p in Planetas_elegidos:\n t=a\n u=(2*ma.pi*t/p[3])+sumatoria(5000,p[2],p[3],t)\n pos=[p[1]*(ma.cos(u)-p[2]),p[1]*ma.sqrt(1-p[2]**2)*ma.sin(u)]\n pos_fin=gira(pos,p[4])\n x=[]\n y=[]\n for i in np.linspace(0,p[3]*1.2,200):\n u=(2*ma.pi*i/p[3])+sumatoria(5000,p[2],p[3],i)\n pos_sin_girar=[p[1]*(ma.cos(u)-p[2]),p[1]*ma.sqrt(1-p[2]**2)*ma.sin(u)]\n [a,b]=gira(pos_sin_girar,p[4])\n x.append(a)\n y.append(b)\n plt.plot(x,y,linewidth=2.1,color=p[5] ,label=p[0])\n plt.plot([pos_fin[0]],[pos_fin[1]],'bo')\n plt.plot([0],[0],'ro',label='Sol')\n plt.legend()\n plt.axis('equal')\n plt.show()\n except:\n self.Boton_plot2D.configure(bg='red')\n messagebox.showerror('Error de datos introducidos','No se han introducido datos \\n numericos en \"Tiempo\"')\n def calcula_datos(self):\n try:\n a=float(self.tiempo.get())\n Planetas_seleccionados=[self.pl1.get(),self.pl2.get(),self.pl3.get(),self.pl4.get(),self.pl5.get(),self.pl6.get(),self.pl7.get(),self.pl8.get()]\n cont=0\n for p in Planetas_seleccionados:\n cont=cont+p\n if float(a)<0:\n self.Boton_calculo.configure(bg='red')\n self.caja_resultados.delete(0,tk.END)\n self.caja_resultados.insert(tk.END,'La entrada de tiempo no es valida, no se admiten tiempos negativos...')\n elif cont==0:\n self.Boton_calculo.configure(bg='yellow')\n self.caja_resultados.delete(0,tk.END)\n self.caja_resultados.insert(tk.END,'No se ha seleccionado ningun planeta...')\n else:\n self.Boton_calculo.configure(bg='green')\n self.caja_resultados.delete(0,tk.END)\n Posiciones=pos_1(Planetas_seleccionados)\n Planetas_elegidos=[Planetas[i] for i in Posiciones]\n for p in Planetas_elegidos:\n t=a\n u=(2*ma.pi*t/p[3])+sumatoria(5000,p[2],p[3],t)\n pos=[p[1]*(ma.cos(u)-p[2]),p[1]*ma.sqrt(1-p[2]**2)*ma.sin(u)]\n pos_fin=gira(pos,p[4])\n self.caja_resultados.insert(tk.END,p[0]+':')\n self.caja_resultados.insert(tk.END,'Masa(kg): '+str(p[6]))\n self.caja_resultados.insert(tk.END,'Posicion(uA): '+str(pos_fin))\n dist=ma.sqrt(pos_fin[0]**2+pos_fin[1]**2)\n self.caja_resultados.insert(tk.END,'Distancia al sol(uA): '+str(dist))\n vel_sin_giro=[((p[1]*2*ma.pi)/(p[3]*(1-p[2]*ma.cos(u))))*(-ma.sin(u)),((p[1]*2*ma.pi)/(p[3]*(1-p[2]*ma.cos(u))))*ma.sqrt(1-p[2]**2)*ma.cos(u)]\n vel=gira(vel_sin_giro,p[4])\n mod_vel=ma.sqrt(vel[0]**2+vel[1]**2)\n self.caja_resultados.insert(tk.END,'Velocidad(uA/Dia): '+str(vel))\n self.caja_resultados.insert(tk.END,'Modulo de la velocidad: '+str(mod_vel))\n energia=p[6]*(((p[1]*2*ma.pi/(p[3]*(1-ma.cos(u)*p[2])))**2)*(1-ma.cos(u)*p[2]**2)/2-nu/(p[1]*(1+p[2]*ma.cos(u))))\n self.caja_resultados.insert(tk.END,'Energia del planeta(kg*uA^2/Dia^2) mediante definicion: '+str(energia))\n mom_ang=[0,0,pos_fin[0]*vel[1]-pos_fin[1]*vel[0]]\n self.caja_resultados.insert(tk.END,'Energia obtenida a partir de los parametros del sistema(kg*uA^2/Dia^2): '+str((-1)*p[6]*nu/(2*p[1])))\n self.caja_resultados.insert(tk.END,'Momento angular en funcion de los parametros del sistema: '+str(ma.sqrt(p[1]*nu*(1-p[2]**2))))\n self.caja_resultados.insert(tk.END,'Momento angular mediante su definicion: '+str(mom_ang))\n self.caja_resultados.insert(tk.END,'Anomalia excentrica(Rad): '+str(u))\n if t==0:\n real=ma.acos(int((((1-p[2]**2)/(1-p[2]*ma.cos(u)))-1)/p[2]))\n else:\n real=ma.acos((((1-p[2]**2)/(1-p[2]*ma.cos(u)))-1)/p[2])\n \n self.caja_resultados.insert(tk.END,'Anomalia real a partir de la excentrica(Rad): '+str(real))\n def f(z):\n return z-p[2]*ma.sin(z)-2*ma.pi*t/p[3]\n def f_d(z):\n return 1-p[2]*ma.cos(z)\n u_newt_raph=0\n inr=0\n while inr<1000:\n u_newt_raph=u_newt_raph-f(u_newt_raph)/f_d(u_newt_raph)\n inr=inr+1\n self.caja_resultados.insert(tk.END,'Anomalia excentrica por metodo de Newton Raphson(Rad): '+str(u_newt_raph))\n c=ma.sqrt(p[1]*nu*(1-p[2]**2))\n def theta(x,y):\n return c/((p[1]**2)*(1-p[2]**2)**2)*(1+p[2]*ma.cos(y))**2\n def RungeKutta(a,im_a,b,l): #a y b los valores de x inicial y tope,im_a el valor imagen inicial de a,t el tamanyo de paso\n if b= b_box_lens[:, :, None]\n\n # Pad agent features at temporal and box dimension\n pad_b_agent_feats = torch.zeros(bsz, tmp_dim, max_box_dim, feat_dim)\n for i, temporal_features in enumerate(b_agent_feats):\n for j, box_features in enumerate(temporal_features):\n if len(box_features) > 0:\n pad_b_agent_feats[i, j, :len(box_features)] = torch.tensor(box_features)\n else:\n pad_b_agent_feats = None\n b_agent_mask = None\n\n return b_env_feats, pad_b_agent_feats, b_agent_mask, confidence_labels, start_labels, end_labels\n\n\ndef test_collate_fn(batch):\n video_ids, b_env_feats, b_agent_feats, b_box_lens = zip(*batch)\n\n cfg = get_cfg()\n tmp_dim, feat_dim = cfg.DATA.TEMPORAL_DIM, cfg.DATA.FEATURE_DIM\n\n bsz = len(b_env_feats)\n\n if b_env_feats[0] is not None:\n b_env_feats = torch.stack(b_env_feats)\n else:\n b_env_feats = None\n\n if b_agent_feats[0] is not None:\n # Make new order to inputs by their lengths (long-to-short)\n b_box_lens = torch.stack(b_box_lens, dim=0)\n\n max_box_dim = torch.max(b_box_lens).item()\n\n # Make padding mask for self-attention\n b_agent_mask = torch.arange(max_box_dim)[None, None, :] >= b_box_lens[:, :, None]\n\n # Pad agent features at temporal and box dimension\n pad_b_agent_feats = torch.zeros(bsz, tmp_dim, max_box_dim, feat_dim)\n for i, temporal_features in enumerate(b_agent_feats):\n for j, box_features in enumerate(temporal_features):\n if len(box_features) > 0:\n pad_b_agent_feats[i, j, :len(box_features)] = torch.tensor(box_features)\n else:\n pad_b_agent_feats = None\n b_agent_mask = None\n\n return video_ids, b_env_feats, pad_b_agent_feats, b_agent_mask\n\n\nclass VideoDataSet(Dataset):\n def __init__(self, cfg, split='training'):\n self.split = split\n # self.video_anno_path = cfg.DATA.ANNOTATION_FILE\n self.temporal_dim = cfg.DATA.TEMPORAL_DIM\n self.temporal_gap = 1. / self.temporal_dim\n self.env_feature_dir = cfg.DATA.ENV_FEATURE_DIR\n self.agent_feature_dir = cfg.DATA.AGENT_FEATURE_DIR\n\n self.use_env = cfg.USE_ENV\n self.use_agent = cfg.USE_AGENT\n\n if split == 'training':\n self.video_anno_path = cfg.TRAIN.ANNOTATION_FILE\n self._get_match_map()\n\n if self.split == 'validation':\n self.video_anno_path = cfg.VAL.ANNOTATION_FILE\n\n self._get_dataset()\n\n def _get_match_map(self):\n match_map = []\n for idx in range(self.temporal_dim):\n tmp_match_window = []\n xmin = self.temporal_gap * idx\n for jdx in range(1, self.temporal_dim + 1):\n xmax = xmin + self.temporal_gap * jdx\n tmp_match_window.append([xmin, xmax])\n match_map.append(tmp_match_window)\n match_map = np.array(match_map) # 100x100x2\n match_map = np.transpose(match_map, [1, 0, 2]) # [0,1] [1,2] [2,3].....[99,100]\n match_map = np.reshape(match_map, [-1, 2]) # [0,2] [1,3] [2,4].....[99,101] # duration x start\n self.match_map = match_map\n\n self.anchor_xmin = [self.temporal_gap * (i - 0.5) for i in range(self.temporal_dim)]\n self.anchor_xmax = [self.temporal_gap * (i + 0.5) for i in range(1, self.temporal_dim + 1)]\n\n def _get_dataset(self):\n annotations = load_json(self.video_anno_path)['database']\n\n # Read event segments\n self.event_dict = {}\n self.video_ids = []\n\n for video_id, annotation in annotations.items():\n if annotation['subset'] != self.split:\n continue\n self.event_dict[video_id] = {\n 'duration': annotation['duration'],\n 'events': annotation['annotations']\n # 'events': annotation['timestamps']\n }\n self.video_ids.append(video_id)\n\n print(\"Split: %s. Dataset size: %d\" % (self.split, len(self.video_ids)))\n\n def __getitem__(self, index):\n env_features, agent_features, box_lengths = self._load_item(index)\n if self.split == 'training':\n match_score_start, match_score_end, confidence_score = self._get_train_label(index)\n return env_features, agent_features, box_lengths, confidence_score, match_score_start, match_score_end\n else:\n return self.video_ids[index], env_features, agent_features, box_lengths\n\n def _load_item(self, index):\n video_name = 'v_' + self.video_ids[index]\n\n '''\n Read environment features at every timestamp\n Feature size: TxF\n T: number of timestamps\n F: feature size\n '''\n if self.use_env is True:\n env_features = load_json(os.path.join(self.env_feature_dir, video_name + '.json'))['video_features']\n # env_segments = [env['segment'] for env in env_features]\n env_features = torch.tensor([feature['features'] for feature in env_features]).float().squeeze(1)\n else:\n env_features = None\n\n '''\n Read agents features at every timestamp\n Feature size: TxBxF\n T: number of timestamps\n B: max number of bounding boxes\n F: feature size\n '''\n if self.use_agent is True:\n agent_features = load_json(os.path.join(self.agent_feature_dir, video_name + '.json'))['video_features']\n # agent_segments = [feature['segment'] for feature in agent_features]\n agent_features = [feature['features'] for feature in agent_features]\n # Create and pad agent_box_lengths if train\n box_lengths = torch.tensor([len(x) for x in agent_features])\n else:\n agent_features = None\n box_lengths = None\n\n # assert env_segments == agent_segments and len(env_segments) == 100, 'Two streams must have 100 segments.'\n\n return env_features, agent_features, box_lengths\n\n def _get_train_label(self, index):\n video_id = self.video_ids[index]\n video_info = self.event_dict[video_id]\n video_labels = video_info['events'] # the measurement is second, not frame\n duration = video_info['duration']\n\n ##############################################################################################\n # change the measurement from second to percentage\n gt_bbox = []\n gt_iou_map = []\n for j in range(len(video_labels)):\n tmp_info = video_labels[j]\n tmp_start = max(min(1, tmp_info['segment'][0] / duration), 0)\n tmp_end = max(min(1, tmp_info['segment'][1] / duration), 0)\n gt_bbox.append([tmp_start, tmp_end])\n tmp_gt_iou_map = iou_with_anchors(\n self.match_map[:, 0], self.match_map[:, 1], tmp_start, tmp_end)\n tmp_gt_iou_map = np.reshape(tmp_gt_iou_map,\n [self.temporal_dim, self.temporal_dim])\n gt_iou_map.append(tmp_gt_iou_map)\n gt_iou_map = np.array(gt_iou_map)\n gt_iou_map = np.max(gt_iou_map, axis=0)\n gt_iou_map = torch.Tensor(gt_iou_map)\n ##############################################################################################\n\n ##############################################################################################\n # generate R_s and R_e\n gt_bbox = np.array(gt_bbox)\n gt_xmins = gt_bbox[:, 0]\n gt_xmaxs = gt_bbox[:, 1]\n # gt_lens = gt_xmaxs - gt_xmins\n gt_len_small = 3 * self.temporal_gap # np.maximum(self.temporal_gap, self.boundary_ratio * gt_lens)\n gt_start_bboxs = np.stack((gt_xmins - gt_len_small / 2, gt_xmins + gt_len_small / 2), axis=1)\n gt_end_bboxs = np.stack((gt_xmaxs - gt_len_small / 2, gt_xmaxs + gt_len_small / 2), axis=1)\n ##############################################################################################\n\n ##############################################################################################\n # calculate the ioa for all timestamp\n match_score_start = []\n for jdx in range(len(self.anchor_xmin)):\n match_score_start.append(np.max(\n ioa_with_anchors(self.anchor_xmin[jdx], self.anchor_xmax[jdx], gt_start_bboxs[:, 0], gt_start_bboxs[:, 1])))\n match_score_end = []\n for jdx in range(len(self.anchor_xmin)):\n match_score_end.append(np.max(\n ioa_with_anchors(self.anchor_xmin[jdx], self.anchor_xmax[jdx], gt_end_bboxs[:, 0], gt_end_bboxs[:, 1])))\n match_score_start = torch.tensor(match_score_start)\n match_score_end = torch.tensor(match_score_end)\n ##############################################################################################\n\n return match_score_start, match_score_end, gt_iou_map\n\n def __len__(self):\n return len(self.video_ids)\n\n\nif __name__ == '__main__':\n cfg = get_cfg()\n train_loader = torch.utils.data.DataLoader(VideoDataSet(cfg, split=\"train\"),\n batch_size=cfg.TRAIN.BATCH_SIZE, shuffle=True,\n num_workers=8, pin_memory=True, collate_fn=train_collate_fn)\n for a, b, c, d, e, f in train_loader:\n print(a.size(), b.size(), c.size(), d.size(), e.size(), f.size())\n break\n","sub_path":"dataset.py","file_name":"dataset.py","file_ext":"py","file_size_in_byte":10644,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"528669229","text":"import os, sys #import animator from parent directory\ndir_path = os.path.dirname(os.path.realpath(__file__))\nparent_dir_path = os.path.abspath(os.path.join(dir_path, os.pardir))\nsys.path.insert(0, parent_dir_path)\n\nfrom animator2 import draw_graph\nfrom shuffler import random_sequence\ncounter = 0\n\nfrom random import shuffle\nfrom tkinter import Tk, Canvas\nmyInterface = Tk()\nscreen = Canvas(myInterface, width=1250, height=800, background = \"black\")\nscreen.pack()\nscreen.update()\n\ndef insertion_sort(array):\n for i in range(1, len(array)): #iterate through entire array\n comparator = array[i] #make comparison with this value\n for section in range(i-1, -2, -1): #iterate through array from i backwards\n if comparator > array[section]: #insert comparator into the array, in its correct position\n array[section+1] = comparator\n break\n else: array[section+1] = array[section] #if comparator <= array[section], move array[section] forward to make space\n else: array[section+1] = comparator #if loop wasn't broken, insert comparator in the right spot\n return array\n\ndef merge(array1, array2): #merge two arrays\n array = [] #merged array\n first = second = 0 #starting points\n\n while first < len(array1) and second < len(array2):\n if array1[first] > array2[second]:\n array.append(array2[second])\n second += 1\n elif array1[first] < array2[second]:\n array.append(array1[first])\n first += 1\n else:\n array.append(array1[first])\n first += 1\n array.append(array2[second])\n second += 1\n \n while first < len(array1):\n array.append(array1[first])\n first += 1\n\n while second < len(array2):\n array.append(array2[second])\n second += 1\n\n return array\n\ndef tim_sort(array, run = 32):\n parts = []\n\n for i in range(0, len(array), run):\n parts.append(array[i:i+run])\n \n for index, elem in enumerate(parts):\n parts[index] = insertion_sort(elem)\n \n while len(parts) > 1:\n array = []\n for i in range(0, len(parts), 2):\n array.append(merge(parts[i], parts[i+1]))\n parts = array\n\n return parts[0]\n\nnumVals = 250\n\nshuffled_array = random_sequence(0, min(numVals, screen.winfo_width()))\n\nscreen.update()\n\ndraw_graph(screen, shuffled_array)\n\nsorted_array = tim_sort(shuffled_array)\n\ndraw_graph(screen, sorted_array, finished = True)\n\nscreen.mainloop()","sub_path":"tim-sort/tim-sort-animated.py","file_name":"tim-sort-animated.py","file_ext":"py","file_size_in_byte":2523,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"599994707","text":"import numpy as np\n\nallsteps = np.loadtxt('allsteps_cifar.txt')\n\nind = np.argpartition(allsteps, -5000)[-5000:]\n\n\n\nnp.savetxt(\"cifarids.txt\", ind.astype(int), fmt='%i', delimiter=\",\")\n\n\n\ndic = {}\n\nfor i in range(len(allsteps)):\n dic[i] = allsteps[i]\n\ndic = {k: v for k, v in sorted(dic.items(), key=lambda item: item[1], reverse=True)}\n\nfor i, k in enumerate(dic):\n print(k,dic[k])\n\n'''\ntmp = []\nids = []\nfor i, k in enumerate(dic):\n if i % 6000 < 500:\n ids.append(k)\n\nids=np.array(ids)\nnp.savetxt(\"ids.txt\", ids.astype(int), fmt='%i', delimiter=\",\")\n'''","sub_path":"code/get_ids.py","file_name":"get_ids.py","file_ext":"py","file_size_in_byte":570,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"149999332","text":"# Author: Melnychuk Taras\n# Contact: fenix@quintagroup.com\n# Date: $Date: 2006-08-11 \n# Copyright: quintagroup.com\n\nimport re\nfrom Products.CMFCore.utils import getToolByName\nfrom Products.PortalTransforms.interfaces import itransform\n\nimport string\nletters = string.letters\n_ABSOLUTE_REL_URL=r'(?P(?Phttp|https|ftp|mailto|file|about[:/]+?)?[%s0-9_\\@\\.\\,\\?\\!\\/\\:\\;\\-\\#\\~\\=\\&\\%%\\+\\\\]+)' % letters\n\n\nclass ruid_to_url:\n \"\"\"Transform which replaces resolve uid into urls\"\"\"\n \n __implements__ = itransform\n \n __name__ = \"ruid_to_url\"\n inputs = ('text/html',)\n output = 'text/html'\n \n def __init__(self, name=None):\n if name:\n self.__name__ = name\n self.ruid_regexp = re.compile(\"(?P\\<(?Pa|img)[^>]*(?Phref|src)\\s*=\\s*[\\'|\\\"]?%s[\\'|\\\"]?[\\s|\\>|\\/])\" \\\n % _ABSOLUTE_REL_URL,re.I|re.S)\n\n def name(self):\n return self.__name__\n\n def find_ruid(self, data):\n tags_url = [{m.group('tag'):m.group('url').replace('\\\\','/')}\\\n for m in self.ruid_regexp.finditer(data)]\n tags_ruid = [tu for tu in tags_url if tu.values()[0].startswith('resolveuid')]\n unique_ruid = []\n [unique_ruid.append(tu.values()[0]) for tu in tags_ruid if tu.values()[0] not in unique_ruid]\n return tags_ruid, unique_ruid\n\n def mapRUID_URL(self, unique_ruid, portal):\n ruid_url = {}\n rc = getToolByName(portal, 'reference_catalog')\n pu = getToolByName(portal, 'portal_url')\n for ruid in unique_ruid:\n try:\n obj = rc.lookupObject(ruid.replace('resolveuid/', ''))\n ruid_url[ruid] = pu.getRelativeUrl(obj)\n except:\n ruid_url[ruid] = ruid\n return ruid_url \n \n def convert(self, orig, data, **kwargs):\n text = orig\n tags_ruid, unique_ruid = self.find_ruid(text)\n if unique_ruid:\n ruid_url = self.mapRUID_URL(unique_ruid, kwargs['context'])\n for tag_ruid in tags_ruid:\n tag, ruid = tag_ruid.items()[0]\n text = text.replace(tag, tag.replace(ruid, ruid_url[ruid]))\n \n data.setData(text)\n return data\n\n\ndef register():\n return ruid_to_url()\n ","sub_path":"qPloneResolveUID/tags/0.2/transforms/ruid_to_url.py","file_name":"ruid_to_url.py","file_ext":"py","file_size_in_byte":2294,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"606989063","text":"import os\nimport subprocess\n\nfrom dotenv import load_dotenv\nfrom flask_script import Manager\n\nfrom app import create_app\n\nload_dotenv()\napp = create_app()\nmanager = Manager(app)\n\n\n@manager.command\ndef run():\n if os.getenv('FLASK_ENV') == 'test':\n app.run()\n else:\n subprocess.call(['gunicorn', '--bind', '0.0.0.0:5000', 'wsgi:app'])\n\n\n@manager.command\ndef test():\n if os.getenv('FLASK_ENV') == 'test':\n subprocess.call(['pytest', '-vv'])\n else:\n print('Set FLASK_ENV = \\'test\\' and run again.')\n\n\nif __name__ == '__main__':\n manager.run()\n\n","sub_path":"manage.py","file_name":"manage.py","file_ext":"py","file_size_in_byte":583,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"498068379","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n#\n# Copyright (c) 2017 University of Dundee.\n#\n# This program is free software: you can redistribute it and/or modify\n# it under the terms of the GNU Affero General Public License as\n# published by the Free Software Foundation, either version 3 of the\n# License, or (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 Affero General Public License for more details.\n#\n# You should have received a copy of the GNU Affero General Public License\n# along with this program. If not, see .\n\nimport os\nimport sys\n\nfrom setuptools import setup, find_packages\nfrom setuptools.command.test import test as TestCommand\n\n# Hack to prevent stupid \"TypeError: 'NoneType' object is not callable\" error\n# in multiprocessing/util.py _exit_function when running `python\n# setup.py test` or `python setup.py flake8`. See:\n# * http://www.eby-sarna.com/pipermail/peak/2010-May/003357.html)\n# * https://github.com/getsentry/raven-python/blob/master/setup.py\nimport multiprocessing\nassert multiprocessing # silence flake8\n\nVERSION = '0.0.1'\n\n\ndef get_requirements(suffix=''):\n with open('requirements%s.txt' % suffix) as f:\n rv = f.read().splitlines()\n return rv\n\n\nclass PyTest(TestCommand):\n\n user_options = [('pytest-args=', 'a', 'Arguments to pass to py.test')]\n\n def initialize_options(self):\n TestCommand.initialize_options(self)\n self.pytest_args = []\n\n def finalize_options(self):\n TestCommand.finalize_options(self)\n self.test_args = []\n self.test_suite = True\n\n def run_tests(self):\n import pytest\n errno = pytest.main(self.pytest_args)\n sys.exit(errno)\n\n\ndef read(fname):\n \"\"\"\n Utility function to read the README file.\n :rtype : String\n \"\"\"\n return open(os.path.join(os.path.dirname(__file__), fname)).read()\n\n\nsetup(\n name='idr',\n version=VERSION,\n description='Image Data Repository access library',\n long_description=read('README.md'),\n classifiers=[\n 'Development Status :: 3 - Alpha',\n 'Intended Audience :: Developers',\n 'License :: OSI Approved :: GNU General Public License v2 '\n 'or later (GPLv2+)',\n 'Natural Language :: English',\n 'Operating System :: OS Independent',\n 'Programming Language :: Python :: 2',\n 'Topic :: Software Development :: Libraries :: Python Modules',\n ], # Get strings from\n # http://pypi.python.org/pypi?%3Aaction=list_classifiers\n keywords='',\n author='The Open Microscopy Team',\n author_email='ome-devel@lists.openmicroscopy.org.uk',\n url='https://github.com/idr/idr-python',\n license='GPLv2+',\n packages=find_packages(),\n zip_safe=True,\n include_package_data=True,\n platforms='any',\n setup_requires=['flake8'],\n install_requires=get_requirements(),\n tests_require=get_requirements('-dev'),\n entry_points=\"\"\"\n # -*- Entry points: -*-\n \"\"\",\n cmdclass={'test': PyTest},\n)\n","sub_path":"pypi_install_script/idr-0.0.1.tar/setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":3188,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"135548263","text":"#!/usr/bin/env python\nimport cv2\nimport glob\nimport os\nimport numpy\nfrom PIL import Image, ImageChops\n\npath = '/home/simran/Desktop/OCR_APP2/Images/'\ni=0\nsize=(28,28)\nimagePath = sorted(glob.glob(path + '*.jpg')) \nfor img in imagePath:\n\tthumbnail = Image.open(img)\n\tthumbnail.thumbnail(size, Image.ANTIALIAS)\n\tF_OUT = os.path.join(path, str(i).zfill(4)+'.jpg')\n\n\toffset_x = max((size[0] - thumbnail.size[0]) // 2, 0)\n\toffset_y = max((size[1] - thumbnail.size[1]) // 2, 0)\n\toffset_tuple = (offset_x, offset_y) #pack x and y into a tuple\n\n\t# create the image object to be the final product\n\tfinal_thumb = Image.new(mode='RGB',size=size,color=(255,255,255,0))\n\t# paste the thumbnail into the full sized image\n\tfinal_thumb.paste(thumbnail, offset_tuple)\n\t# save (the PNG format will retain the alpha band unlike JPEG)\n\tfinal_thumb.save(F_OUT)\n\ti=i+1\n","sub_path":"OCR_APP2/char_padding.py","file_name":"char_padding.py","file_ext":"py","file_size_in_byte":846,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"424883454","text":"import json\nimport sys\nimport os\nimport urllib.request\nimport tarfile\nimport zipfile\nimport pickle\n\n########################################################################\n\n# Directory where you want to download and save the data-set.\n# Set this before you start calling any of the functions below.\n# Use the function set_data_dir() to also update train_dir and val_dir.\ndata_dir = \"data/coco/\"\n\n# Sub-directories for the training- and validation-sets.\ntrain_dir = \"data/coco/train2017\"\nval_dir = \"data/coco/val2017\"\n\n# Base-URL for the data-sets on the internet.\ndata_url = \"http://images.cocodataset.org/\"\n\n\n########################################################################\n# Private helper-functions.\n\ndef _load_records(train=True):\n \"\"\"\n Load the image-filenames and captions\n for either the training-set or the validation-set.\n \"\"\"\n\n if train:\n # Training-set.\n filename = \"captions_train2017.json\"\n else:\n # Validation-set.\n filename = \"captions_val2017.json\"\n\n # Full path for the data-file.\n path = os.path.join(data_dir, \"annotations\", filename)\n\n # Load the file.\n with open(path, \"r\", encoding=\"utf-8\") as file:\n data_raw = json.load(file)\n\n # Convenience variables.\n images = data_raw['images']\n annotations = data_raw['annotations']\n\n # Initialize the dict for holding our data.\n # The lookup-key is the image-id.\n records = dict()\n\n # Collect all the filenames for the images.\n for image in images:\n # Get the id and filename for this image.\n image_id = image['id']\n filename = image['file_name']\n\n # Initialize a new data-record.\n record = dict()\n\n # Set the image-filename in the data-record.\n record['filename'] = filename\n\n # Initialize an empty list of image-captions\n # which will be filled further below.\n record['captions'] = list()\n\n # Save the record using the the image-id as the lookup-key.\n records[image_id] = record\n\n # Collect all the captions for the images.\n for ann in annotations:\n # Get the id and caption for an image.\n image_id = ann['image_id']\n caption = ann['caption']\n\n # Lookup the data-record for this image-id.\n # This data-record should already exist from the loop above.\n record = records[image_id]\n\n # Append the current caption to the list of captions in the\n # data-record that was initialized in the loop above.\n record['captions'].append(caption)\n\n # Convert the records-dict to a list of tuples.\n records_list = [(key, record['filename'], record['captions'])\n for key, record in sorted(records.items())]\n\n # Convert the list of tuples to separate tuples with the data.\n ids, filenames, captions = zip(*records_list)\n\n return ids, filenames, captions\n\n\n########################################################################\n# Public functions that you may call to download the data-set from\n# the internet and load the data into memory.\n\ndef _print_download_progress(count, block_size, total_size):\n \"\"\"\n Function used for printing the download progress.\n Used as a call-back function in maybe_download_and_extract().\n \"\"\"\n\n # Percentage completion.\n pct_complete = float(count * block_size) / total_size\n\n # Status-message. Note the \\r which means the line should overwrite itself.\n msg = \"\\r- Download progress: {0:.1%}\".format(pct_complete)\n\n # Print it.\n sys.stdout.write(msg)\n sys.stdout.flush()\n\n\n########################################################################\n\n\ndef _maybe_download_and_extract(url, download_dir):\n \"\"\"\n Download and extract the data if it doesn't already exist.\n Assumes the url is a tar-ball file.\n\n :param url:\n Internet URL for the tar-file to download.\n Example: \"https://www.cs.toronto.edu/~kriz/cifar-10-python.tar.gz\"\n\n :param download_dir:\n Directory where the downloaded file is saved.\n Example: \"data/CIFAR-10/\"\n\n :return:\n Nothing.\n \"\"\"\n\n # Filename for saving the file downloaded from the internet.\n # Use the filename from the URL and add it to the download_dir.\n filename = url.split('/')[-1]\n file_path = os.path.join(download_dir, filename)\n\n # Check if the file already exists.\n # If it exists then we assume it has also been extracted,\n # otherwise we need to download and extract it now.\n if not os.path.exists(file_path):\n # Check if the download directory exists, otherwise create it.\n if not os.path.exists(download_dir):\n os.makedirs(download_dir)\n\n # Download the file from the internet.\n file_path, _ = urllib.request.urlretrieve(url=url,\n filename=file_path,\n reporthook=_print_download_progress)\n\n print()\n print(\"Download finished. Extracting files.\")\n\n if file_path.endswith(\".zip\"):\n # Unpack the zip-file.\n zipfile.ZipFile(file=file_path, mode=\"r\").extractall(download_dir)\n elif file_path.endswith((\".tar.gz\", \".tgz\")):\n # Unpack the tar-ball.\n tarfile.open(name=file_path, mode=\"r:gz\").extractall(download_dir)\n\n print(\"Done.\")\n else:\n print(\"Data has apparently already been downloaded and unpacked.\")\n\n\ndef set_data_dir(new_data_dir):\n \"\"\"\n Set the base-directory for data-files and then\n set the sub-dirs for training and validation data.\n \"\"\"\n\n # Ensure we update the global variables.\n global data_dir, train_dir, val_dir\n\n data_dir = new_data_dir\n train_dir = os.path.join(new_data_dir, \"train2017\")\n val_dir = os.path.join(new_data_dir, \"val2017\")\n\n\ndef maybe_download_and_extract():\n \"\"\"\n Download and extract the COCO data-set if the data-files don't\n already exist in data_dir.\n \"\"\"\n\n # Filenames to download from the internet.\n filenames = [\"zips/train2017.zip\", \"zips/val2017.zip\",\n \"annotations/annotations_trainval2017.zip\"]\n\n # Download these files.\n for filename in filenames:\n # Create the full URL for the given file.\n url = data_url + filename\n\n print(\"Downloading \" + url)\n\n _maybe_download_and_extract(url=url, download_dir=data_dir)\n\n\ndef cache(cache_path, fn, *args, **kwargs):\n \"\"\"\n Cache-wrapper for a function or class. If the cache-file exists\n then the data is reloaded and returned, otherwise the function\n is called and the result is saved to cache. The fn-argument can\n also be a class instead, in which case an object-instance is\n created and saved to the cache-file.\n\n :param cache_path:\n File-path for the cache-file.\n\n :param fn:\n Function or class to be called.\n\n :param args:\n Arguments to the function or class-init.\n\n :param kwargs:\n Keyword arguments to the function or class-init.\n\n :return:\n The result of calling the function or creating the object-instance.\n \"\"\"\n\n # If the cache-file exists.\n if os.path.exists(cache_path):\n # Load the cached data from the file.\n with open(cache_path, mode='rb') as file:\n obj = pickle.load(file)\n\n print(\"- Data loaded from cache-file: \" + cache_path)\n else:\n # The cache-file does not exist.\n\n # Call the function / class-init with the supplied arguments.\n obj = fn(*args, **kwargs)\n\n # Save the data to a cache-file.\n with open(cache_path, mode='wb') as file:\n pickle.dump(obj, file)\n\n print(\"- Data saved to cache-file: \" + cache_path)\n\n return obj\n\n\ndef load_records(train=True):\n \"\"\"\n Load the data-records for the data-set. This returns the image ids,\n filenames and text-captions for either the training-set or validation-set.\n \n This wraps _load_records() above with a cache, so if the cache-file already\n exists then it is loaded instead of processing the original data-file.\n \n :param train:\n Bool whether to load the training-set (True) or validation-set (False).\n\n :return: \n ids, filenames, captions for the images in the data-set.\n \"\"\"\n\n if train:\n # Cache-file for the training-set data.\n cache_filename = \"records_train.pkl\"\n else:\n # Cache-file for the validation-set data.\n cache_filename = \"records_val.pkl\"\n\n # Path for the cache-file.\n cache_path = os.path.join(data_dir, cache_filename)\n\n # If the data-records already exist in a cache-file then load it,\n # otherwise call the _load_records() function and save its\n # return-values to the cache-file so it can be loaded the next time.\n records = cache(cache_path=cache_path,\n fn=_load_records,\n train=train)\n\n return records\n\n########################################################################\n","sub_path":"coco.py","file_name":"coco.py","file_ext":"py","file_size_in_byte":8993,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"216939837","text":"#!/usr/bin/env python3\n\nimport aws_ipv4_size\nfrom netaddr import IPSet, IPNetwork\nfrom requests import get\n\ndef main():\n # I'm shocked, shocked I tell you to see that MS requires you do\n # something oddball like dig into an HTML page to get the latest\n # data file.\n # Google publishes the list in a simple JSON file, and also in an\n # overly complex DNS TXT record, because of course they do\n url = \"https://www.gstatic.com/ipranges/cloud.json\"\n data = get(url).json()\n\n # Pull out all of the IPs, ignore IPv6\n google = IPSet(IPNetwork(y['ipv4Prefix']) for y in data['prefixes'] if 'ipv4Prefix' in y)\n\n # And produce the stats\n public, _internet, google = aws_ipv4_size.parse_aws(google)\n print(f'Google: {google:10d} {google / public * 100.0:6.2f}%')\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"google.py","file_name":"google.py","file_ext":"py","file_size_in_byte":829,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"317198402","text":"#Source : https://leetcode.com/problems/reverse-integer/\n#Author : Yuan Wang\n#Date : 2018-07-05\n'''\n********************************************************************************** \n*Given a 32-bit signed integer, reverse digits of an integer.\n*\n*Example 1:\n*\n*Input: 123\n*Output: 321\n*Example 2:\n*\n*Input: -123\n*Output: -321\n*Example 3:\n*\n*Input: 120\n*Output: 21\n*Note:\n*Assume we are dealing with an environment which could only store integers within \n*the 32-bit signed integer range: [−231, 231 − 1]. For the purpose of this problem,\n*assume that your function returns 0 when the reversed integer overflows.\n**********************************************************************************/\n'''\n#More pythonic solution\ndef reverse(self, x: int) -> int:\n\tr = x // max(1,abs(x)) * int(str(abs(x))[::-1])\n\treturn r if r.bit_length() < 32 or r == -2 ** 31 else 0\n \n#Pythonic solution\ndef reverseIntegerA(x):\n\t\"\"\"\n\t:type x: int\n\t:rtype: int\n\t\"\"\"\n\t\n\tn=str(x)\n\tif x >= 0:\n\t\tresult=int(n[::-1])\n\t\treturn 0 if result > pow(2,31)-1 else result\n\n\telse:\n\t\tresult=int(\"-\"+n[1:][::-1])\n\t\treturn 0 if result < -pow(2,31) else result\n\n\n#Self solution\ndef reverseIntegerB(x):\n\t\"\"\"\n\t:type x: int\n\t:rtype: int\n\t\"\"\"\n\tif x == 0:\n\t\treturn 0\n\tn=str(x)\n\tstart=False\n\tif x> 0:\n\t\tresult=\"\"\n\t\tfor i in range(len(n)-1,-1,-1):\n\t\t\tif n[i] != \"0\":\n\t\t\t\tresult+=n[i]\n\t\t\t\tstart=True\n\t\t\telif n[i] == \"0\" and start == True:\n\t\t\t\tresult+=n[i]\n\t\n\t\tresult=int(result) \n\t\treturn 0 if result > pow(2,31)-1 else result\n\telse:\n\t\tresult=\"-\"\n\t\tfor i in range(len(n)-1,0,-1):\n\t\t\tif n[i] != \"0\":\n\t\t\t\tresult+=n[i]\n\t\t\t\tstart=True\n\t\t\telif n[i] == \"0\" and start == True:\n\t\t\t\tresult+=n[i]\n\t\tresult=int(result) \n\t\treturn 0 if result < -pow(2,31) else result\n\n\nx=-12345\nprint(reverseIntegerB(x))\n","sub_path":"Math/reverseInteger.py","file_name":"reverseInteger.py","file_ext":"py","file_size_in_byte":1765,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"75606706","text":"from Managers import FileManager\nfrom Managers.LoggerManager import Logger\nfrom Managers.FileManager import Process\n\nfrom multiprocessing import Queue\nfrom queue import Empty\nfrom enum import Enum\n\nimport time\nimport configparser\nimport os\n\nimport sys, traceback\n\n# Secretary is meants as a main hub for the entire software.\n# It mediates communication between the processes.\n# \n# Commands between processes are lists, not strings.\n# If the list has 1 element it is always assumed to be an\n# error, otherwise, it is process specific.\n\ndef read_config():\n\tconfig = configparser.ConfigParser()\n\n\twith open('file.cfg') as f:\n\t\tconfig.read_file(f)\n\n\treturn config['FILE']\n\n# Read the the stdin/boss and prepares the data to be ran in the loop\n# Commands from the CMD are expected to have the \n# following form:\n# 1) One word. General command that is expected to do\n# one single thing for the entire software. Ex.\n# \"close\" prepares and closes all processes.\n# 2) Two words. Command aimed at a specific process.\n# Ex. \"ARDUINO retrieveErrors\" sends the command\n# \"retrieveErrors\" to the arduinoer process.\n# 3) Three words. Same as two words command with the\n# addition of a value parameter. Ex. \"ARDUINO setTemperature 10\"\ndef listen_to_boss(*, queue, err):\n\tresponse = { \\\n\t\t'process'\t: Process.NONE, \\\n\t\t'close' \t: False, \t\t\\\n\t\t'cmd' \t\t: '', \t\t\t\\\n\t\t'value'\t\t: ''}\n\n\ttry:\n\t\tcmd = queue.get_nowait()\n\n\t\tif len(cmd) == 1:\n\t\t\tresponse['cmd'] = cmd[0]\n\t\telif len(cmd) == 2:\n\t\t\tresponse['process'] = Process[cmd[0]]\n\t\t\tresponse['cmd'] = cmd[1]\n\t\telif len(cmd) >= 3:\n\t\t\tresponse['process'] = Process[cmd[0]]\n\t\t\tresponse['cmd'] = cmd[1]\n\t\t\tresponse['value'] = cmd[2]\n\n\t\tresponse['close'] = (response['cmd'] == 'close')\n\t\t\t\n\t\treturn (response, err)\n\t\t\n\texcept Empty as error:\n\t\treturn (None, err)\n\texcept Exception as error:\n\t\traise error\n\ndef listen_to_queue(*, queue, err):\n\tif queue is None:\n\t\treturn (None, err)\n\n\ttry:\n\t\titems = queue.get_nowait()\n\t\treturn (items, err)\n\texcept Empty as error:\n\t\treturn (None, err)\n\texcept Exception as error:\n\t\traise error\n\n# Grabs the response or command and relays to the\n# other processes.\ndef relay_message(*, response, queues):\n\tardOutQueue = queues['ArduinoOut']\n\tivOutQueue = queues['ElectrometerOut']\n\tgraQueue = queues['Grapher']\n\n\tif response is not None:\n\t\tif response['process'] == Process.ARDUINO:\n\t\t\tif ardOutQueue is not None:\n\t\t\t\tardOutQueue.put(response)\n\t\telif response['process'] == Process.IV:\n\t\t\tif ivOutQueue is not None:\n\t\t\t\tivOutQueue.put(response)\n\t\telif response['process'] == Process.GRAPHER:\n\t\t\tgraQueue.put(response)\n\t\telif response['process'] == Process.SECRETARY:\n\t\t\tpass # What to do here\n\t\telif response['process'] == Process.ALL:\n\t\t\tgraQueue.put(response)\n\t\t\tif ardOutQueue is not None:\n\t\t\t\tardOutQueue.put(response)\n\t\t\tif ivOutQueue is not None:\n\t\t\t\tivOutQueue.put(response)\n\ndef loop(file, graQueue, bossQueue, ardOutQueue, ardInQueue, ivOutQueue, \\\n\tivInQueue, commErr):\n\t### Saving data to file while-loop ###\n\tprint('[File] Starting listening.')\n\tonGoing = True\n\tisRunning = False\n\n\t# Loop config bits\n\tconfig = read_config()\n\t\n\tendRunByTime = config.getboolean('EndRunTimeCondition')\n\tstartTime = time.time()\n\tendTime = float(config['EndRunTime'])\n\n\twhile onGoing:\n\t\t# Run at ~100 Hz\n\t\ttime.sleep(1.0/100)\n\n\t\t# BOSS LOOP #\n\t\t# Listens to CMD, parses the command, and sends it around.\n\t\tresponse, commErr = listen_to_boss(queue=bossQueue, err=commErr)\n\n\t\t# If the command is specifically formatted, it will relay.\n\t\trelay_message(response = response, queues = { \\\n\t\t\t'ArduinoOut' : ardOutQueue, \\\n\t\t\t'ElectrometerOut' : ivOutQueue, \\\n\t\t\t'Grapher' : graQueue })\n\n\t\t# If commands are single words, we build the command.\n\t\tif response is not None:\n\t\t\tif response['close']:\n\t\t\t\tclose(file, \\\n\t\t\t\t\tgraQueue, bossQueue, ardOutQueue, ardInQueue, ivOutQueue, \\\n\t\t\t\t\t\tivInQueue, commErr)\n\t\t\t\t# Only way to stop the while loop\n\t\t\t\tonGoing = False\n\n\t\t\t# One word commands\n\t\t\t# Restarts the system in case of an error.\n\t\t\tif response['cmd'] == 'restart':\n\t\t\t\tcommErr = restart(file, \\\n\t\t\t\t\tgraQueue, bossQueue, ardOutQueue, ardInQueue, ivOutQueue, \\\n\t\t\t\t\t\tivInQueue, commErr)\n\t\t\t# Sets the arduino and electrometer in standby mode.\n\t\t\telif response['cmd'] == 'standby':\n\t\t\t\tstandbyCMD = { \\\n\t\t\t\t\t'process'\t: Process.ALL, \t\\\n\t\t\t\t\t'close' \t: False, \t\t\\\n\t\t\t\t\t'cmd' \t\t: 'setState', \t\\\n\t\t\t\t\t'value'\t\t: 'STANDBY'}\n\n\t\t\t\tif ardOutQueue is not None:\n\t\t\t\t\tardOutQueue.put(standbyCMD)\n\n\t\t\t\tif ivOutQueue is not None:\n\t\t\t\t\tivOutQueue.put(standbyCMD)\n\n\t\t\t# Starts the system.\n\t\t\telif response['cmd'] == 'run':\n\t\t\t\tisRunning = True\n\n\t\t\t\trunCMD = { \\\n\t\t\t\t\t'process'\t: Process.ALL, \t\\\n\t\t\t\t\t'close' \t: False, \t\t\\\n\t\t\t\t\t'cmd' \t\t: 'setState', \t\\\n\t\t\t\t\t'value'\t\t: 'RUNNING'}\n\n\t\t\t\tif ardOutQueue is not None:\n\t\t\t\t\tardOutQueue.put(runCMD)\n\n\t\t\t\tif ivOutQueue is not None:\n\t\t\t\t\tivOutQueue.put(runCMD)\n\n\t\t\telif response['cmd'] == 'next':\n\t\t\t\tcmd = { \\\n\t\t\t\t\t'process'\t: Process.IV, \t\\\n\t\t\t\t\t'close' \t: False, \t\t\\\n\t\t\t\t\t'cmd' \t\t: 'next', \t\t\\\n\t\t\t\t\t'value'\t\t: ''}\n\n\t\t\t\tif ivOutQueue is not None:\n\t\t\t\t\tivOutQueue.put(cmd)\n\n\t\t\t# # Debug command to let the arduino know we are done with the\n\t\t\t# # measurements.\n\t\t\t# elif response['cmd'] == 'done':\n\t\t\t# \tcmd = { \\\n\t\t\t# \t\t'process'\t: Process.ARDUINO, \t\\\n\t\t\t# \t\t'close' \t: False, \t\t\t\\\n\t\t\t# \t\t'cmd' \t\t: 'done', \t\t\t\\\n\t\t\t# \t\t'value'\t\t: ''}\n\n\t\t\t# \tif ardOutQueue is not None:\n\t\t\t# \t\tardOutQueue.put(cmd)\n\n\n\t\t################\n\n\t\t# IV LOOP #\n\t\titems, commErr = listen_to_queue(queue=ivInQueue, err=commErr)\n\t\tif items is not None:\n\t\t\tif items['Data'] is not None:\n\t\t\t\tdata = items['Data']\n\n\t\t\t\t# data[0] = time\n\t\t\t\t# data[1] = voltage\n\t\t\t\t# data[2] = current\n\t\t\t\tfile.add_IV(data[0:3], numSiPM=data[3])\n\t\t\t\tgraQueue.put([data[0], None, data[1], data[2], None, None])\n\n\t\t\tif items['Error'] is not None:\n\t\t\t\tcommErr = f'{commErr} Electrometer returned error: {items[\"Error\"]}'\n\n\t\t\tif items['FatalError'] is not None:\n\t\t\t\tif items['FatalError']:\n\t\t\t\t\t# If a fatal error is present in any of the\n\t\t\t\t\t# other threads. We close. \n\t\t\t\t\traise Exception('Electrometer returned with a fatal error.')\n\n\t\t\tif items['CMD'] is not None:\n\t\t\t\tcmd = items['CMD']\n\n\t\t\t\trelay_message(response = cmd, queues = { \\\n\t\t\t\t\t'ArduinoOut' : ardOutQueue, \\\n\t\t\t\t\t'ElectrometerOut' : ivOutQueue, \\\n\t\t\t\t\t'Grapher' : graQueue })\n\n\t\t################\n\n\t\t# ARDUINO LOOP #\n\t\titems, commErr = listen_to_queue(queue=ardInQueue, err=commErr)\n\t\tif items is not None:\n\t\t\tif items['Data'] is not None:\n\t\t\t\tdata = items['Data']\n\n\t\t\t\tfile.add_HT(data)\n\t\t\t\tgraQueue.put([None, data[0], None, None, data[1], data[2]])\n\n\t\t\tif items['Error'] is not None:\n\t\t\t\tcommErr = f'{commErr} Arduino returned error: {items[\"Error\"]}'\n\n\n\t\t\tif items['FatalError'] is not None:\n\t\t\t\tif items['FatalError']:\n\t\t\t\t\t# If a fatal error is present in any of the\n\t\t\t\t\t# other threads. We close. \n\t\t\t\t\traise Exception('Arduino returned with a fatal error.')\n\n\t\t\tif items['CMD'] is not None:\n\t\t\t\tcmd = items['CMD']\n\n\t\t\t\trelay_message(response = cmd, queues = { \\\n\t\t\t\t\t'ArduinoOut' : ardOutQueue, \\\n\t\t\t\t\t'ElectrometerOut' : ivOutQueue, \\\n\t\t\t\t\t'Grapher' : graQueue })\n\n\n\t\t################\n\n\t\t# RUNNING LOOP #\n\t\t################ Things done in the loop of secretary.\n\n\t\t# Nothing to see for now.\n\n\t\t################\n\n# Sends a command and listens for a reply from the arduino and\n# electrometer.\ndef send_and_listen(cmd, graQueue, bossQueue, ardOutQueue, ardInQueue, \\\n\tivOutQueue, ivInQueue, commErr):\n\n\tif ardOutQueue is not None:\n\t\tardOutQueue.put(cmd)\n\n\t\ttry:\n\t\t\tresponse = ardInQueue.get(timeout=10)\n\t\t\tif response is not None:\n\t\t\t\tif response['Error'] is not None:\n\t\t\t\t\tcommErr = f'{commErr} {response[\"Error\"]}'\n\n\t\texcept Empty:\n\t\t\tcommErr = f'{commErr} Arduino did not return a response.'\n\t\texcept Exception as err:\n\t\t\tcommErr = f'{commErr} {err}.'\n\t\t\tprint(f'[File] Error while listening to Arduino: {err}.')\n\n\tif ivOutQueue is not None:\n\t\tivOutQueue.put(cmd)\n\n\t\ttry:\n\t\t\tresponse = ivInQueue.get(timeout=10)\n\t\t\tif response is not None:\n\t\t\t\tif response['Error'] is not None:\n\t\t\t\t\tcommErr = f'{commErr} {response[\"Error\"]}'\n\n\t\texcept Empty:\n\t\t\tcommErr = f'{commErr} Electrometer did not return a response.'\n\t\texcept Exception as err:\n\t\t\tcommErr = f'{commErr} {err}.'\n\t\t\tprint(f'[File] Error while listening to Electroemeter: {err}.')\n\n\tif graQueue is not None:\n\t\tgraQueue.put(cmd)\n\n\treturn commErr\n\n# Important commands that needs their own function. #\n# Command -> 'close'\n# Send a command to retrieve all the cumulated errors, and close\n# all the processes.\ndef close(file, graQueue, bossQueue, ardOutQueue, ardInQueue, ivOutQueue, \\\n\tivInQueue, commErr):\n\tprint('[File] Closing everything.')\n\n\tcloseResponse = { \\\n\t\t'process'\t: Process.ALL, \t\\\n\t\t'close' \t: True, \t\t\\\n\t\t'cmd' \t\t: 'close', \t\t\\\n\t\t'value'\t\t: '' }\n\n\tcommErr = send_and_listen(closeResponse, \\\n\t\tgraQueue, bossQueue, ardOutQueue, ardInQueue, ivOutQueue, ivInQueue, commErr)\n\n\t# Finally, add any errors that were\n\t# present in the run.\n\tif file is not None:\n\t\tfile.add_attribute('Error', commErr)\n\n\treturn commErr\n\n# Command -> 'restart'\n# Restarts the software by cleaning the error, and opening a new database\n# under the same name as the last one.\ndef restart(file, graQueue, bossQueue, ardOutQueue, ardInQueue, ivOutQueue, \\\n\tivInQueue, commErr):\n\tprint('[File] Restarting everything.')\n\n\trestartResponse = { \\\n\t\t'process'\t\t: Process.ALL, \t\\\n\t\t'close' \t\t: False, \t\t\\\n\t\t'cmd' \t\t\t: 'restart', \t\\\n\t\t'value'\t\t\t: '' }\n\n\t# Retrieve the errors from all the processes.\n\tcommErr = send_and_listen(restartResponse, \\\n\t\tgraQueue, bossQueue, ardOutQueue, ardInQueue, ivOutQueue, ivInQueue, commErr)\n\n\t# Save errors to file.\n\tif file is not None:\n\t\tfile.add_attribute('Error', commErr)\n\n\t# Reset the error as it was saved to previous 'run'.\n\tcommErr = ''\n\n\t# 'resets' file but in reality it starts another run.\n\tif file is not None:\n\t\tfile.reset()\n\n\t# Should be empty but we are keeping a standard.\n\treturn commErr\n######################################\n\n\ndef file_process_main(*, bossQueue, graQueue, ardOutQueue=None, ardInQueue=None, \\\n\tivOutQueue=None, ivInQueue=None):\n\t\n\t# Makes sure all output gets written to a log and console.\n\tsys.stdout = Logger()\n\n\tfile = None\n\tcommulativeError = ''\n\n\t# Only three config for now. Database name, file name and comment\n\t# Maybe expand to include number of data points, time, etc\n\tconfigs = read_config()\n\tdb_name = configs['DBName']\n\tname_of_measurements = configs['FileName']\n\tcomment = configs['Comment']\n\tNUM_SIPMS = int(configs['NumSiPMsToTest'])\n\n\ttry:\n\t\t# File creation/initialization\n\t\tprint('[File] Setting up database.')\n\t\tfile = FileManager.sipmFileManager(db_name, numSiPMs=NUM_SIPMS)\n\t\tfile.create_dataset(name_of_measurements)\n\t\tfile.add_attribute('Comment', comment)\n\n\t\tloop(file, graQueue, bossQueue, ardOutQueue, ardInQueue, ivOutQueue, \\\n\t\t\tivInQueue, commulativeError)\n\t\t\n\t# If an error occurred during secretary, the best thing to do \n\t# is to delete everything and restart the software.\n\t# Before closing, we retrieve all the errors if possible.\n\texcept Exception as err:\n\t\tprint('[File] Error with the file manager. Deleting previous data base.')\n\t\tprint(f'[File] Error: {err}.')\n\t\tcommulativeError = f'{commulativeError} {err}.'\n\t\t\n\t\t# If the file broke the error will not be saved.\n\t\t# In fact, nothing will.\n\t\tclose(file, graQueue, bossQueue, ardOutQueue, ardInQueue, ivOutQueue, \\\n\t\t\tivInQueue, commulativeError)\n\n\t\tif file is not None:\n\t\t\tfile.delete_dataset()\n\n\t\ttraceback.print_exc(file=sys.stdout)\n\t\t\t\n\t# Open resources.\n\tfinally:\n\t\tif file is not None:\n\t\t\tfile.close()","sub_path":"secretary.py","file_name":"secretary.py","file_ext":"py","file_size_in_byte":11499,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"629082148","text":"from django import forms\nfrom .models import *\n\n\nclass PersonForm(forms.ModelForm):\n name = forms.CharField(label='Имя', required=False,\n widget=forms.TextInput(attrs={\"class\": 'form-control'}))\n last_name = forms.CharField(label='Фамилия', required=False,\n widget=forms.TextInput(attrs={\"class\": 'form-control'}))\n email = forms.CharField(label='email', required=False, widget=forms.EmailInput(attrs={\"class\": 'form-control'}))\n # region = forms.CharField(label='Область', required=False,\n # widget=forms.SelectMultiple(attrs={\"class\": 'form-control'}))\n \n class Meta(object):\n model = Person\n fields = ('name', 'last_name', 'email', 'region', 'phones')\n\n \nclass NewPhoneForm(forms.ModelForm):\n number = forms.CharField(label='Номер', required=True, widget=forms.TextInput(attrs={\"class\": 'form-control'}))\n \n class Meta(object):\n model = Phone\n fields = ('number',)\n\nclass PersonForm1(forms.Form):\n name = forms.CharField(label='Имя', required=False, widget=forms.TextInput(attrs={\"class\": 'form-control'}))\n last_name = forms.CharField(label='Фамилия', required=False, widget=forms.TextInput(attrs={\"class\": 'form-control'}))\n email = forms.CharField(label='Email', required=False, widget=forms.EmailInput(attrs={\"class\": 'form-control'}))\n region = forms.ModelChoiceField(label='Область',queryset=Region.objects.all(),\n empty_label=None, widget=forms.RadioSelect(attrs={\"class\": 'form-control'}))\n \n phones = forms.ModelMultipleChoiceField(label='Дополнительные телефоны', required=False, queryset=Phone.objects.all(), widget=forms.CheckboxSelectMultiple(attrs={\"class\": 'form-control'}))\n \n phone = forms.CharField(label='Телефон', required=False,\n widget=forms.TextInput(attrs={\"class\": 'form-control', 'placeholder': 'Номер телефона должен начинаться с 0 и иметь десять цифр, например 0123456789'}))\n \n \n def clean_email(self):\n email = self.cleaned_data['email']\n qs = Person.objects.filter(email=email).count()\n if qs>0:\n msg = \"Этот email уже используется!\"\n raise forms.ValidationError(msg)\n return email\n \n \n def clean_phone(self):\n phone = self.cleaned_data['phone']\n if phone[0] !='0':\n msg = \"Номер должен начинаться с 0!\"\n raise forms.ValidationError(msg)\n if len(phone) <10:\n msg = \"Номер должен быть длинной в 10 цифр!\"\n raise forms.ValidationError(msg)\n phone = phone[:10]\n try:\n _ = int(phone)\n \n except ValueError:\n msg = \"Телефон должен содержать только цифры!\"\n raise forms.ValidationError(msg)\n \n return phone\n","sub_path":"subscribers/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":3112,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"309343907","text":"#!/usr/bin/python\n# -*- coding: utf-8 -*-\n# Author: wwcheng\n\nimport csv\nimport datetime\nimport logging\nimport logging.handlers\nimport os\nimport random\nimport re\nimport time\nfrom urllib.request import urlretrieve\n\nimport pandas as pd\nimport prettytable as pt\nimport requests\nfrom PIL import Image\nfrom selenium import webdriver\nfrom selenium.common.exceptions import TimeoutException\nfrom selenium.webdriver import ActionChains\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.common.keys import Keys\nfrom selenium.webdriver.support import expected_conditions as EC\nfrom selenium.webdriver.support.wait import WebDriverWait\n\n\nclass Express_Tracking(object):\n\n def __init__(self,count=0):\n self.query_time = datetime.datetime.strftime(datetime.datetime.now(), '%Y-%m-%d %H-%M-%S')\n self.nowpath = os.path.abspath(os.curdir)\n self.sf_Express_url = r'http://www.sf-express.com/cn/sc/dynamic_function/waybill/#search/bill-number/'\n self.kuaidi100_url = r'https://www.kuaidi100.com/?from=openv'\n self.html_size=0.7\n self.mypath=[]\n self.sf_tab=''\n self.kd100_tab=''\n self.count=count\n self.route=''\n self.dzcg=''\n self.shot_name=''\n self.__WelCome()\n self.__ceart_enviroment()\n self.__logging()\n \n if 'PROGRAMFILES(X86)' in os.environ:\n self.executable_path = self.nowpath+r'\\Driver\\geckodriver-win64.exe'\n else:\n self.executable_path = self.nowpath+r'\\Driver\\geckodriver-win32.exe'\n firefox_options = webdriver.FirefoxOptions()\n firefox_options.add_argument('--headless')\n self.browser = webdriver.Firefox(\n executable_path=self.executable_path,\n firefox_options=firefox_options,\n service_log_path=self.mypath[3]+r'\\geckodriver.log'\n )\n \n self.__open_browser()\n self.__scan_login()\n self.user_agent_list = [\n # Opera\n \"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36 OPR/26.0.1656.60\",\n \"Opera/8.0 (Windows NT 5.1; U; en)\",\n \"Mozilla/5.0 (Windows NT 5.1; U; en; rv:1.8.1) Gecko/20061208 Firefox/2.0.0 Opera 9.50\",\n \"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; en) Opera 9.50\",\n # Firefox\n \"Mozilla/5.0 (Windows NT 6.1; WOW64; rv:34.0) Gecko/20100101 Firefox/34.0\",\n \"Mozilla/5.0 (X11; U; Linux x86_64; zh-CN; rv:1.9.2.10) Gecko/20100922 Ubuntu/10.10 (maverick) Firefox/3.6.10\",\n # Safari\n \"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/534.57.2 (KHTML, like Gecko) Version/5.1.7 Safari/534.57.2\",\n # chrome\n \"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.71 Safari/537.36\",\n \"Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.64 Safari/537.11\",\n \"Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US) AppleWebKit/534.16 (KHTML, like Gecko) Chrome/10.0.648.133 Safari/534.16\",\n # 360\n \"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/30.0.1599.101 Safari/537.36\",\n \"Mozilla/5.0 (Windows NT 6.1; WOW64; Trident/7.0; rv:11.0) like Gecko\",\n # 淘宝浏览器\n \"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/536.11 (KHTML, like Gecko) Chrome/20.0.1132.11 TaoBrowser/2.0 Safari/536.11\",\n # 猎豹浏览器\n \"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.1 (KHTML, like Gecko) Chrome/21.0.1180.71 Safari/537.1 LBBROWSER\",\n \"Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; WOW64; Trident/5.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; .NET4.0C; .NET4.0E; LBBROWSER)\",\n \"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; QQDownload 732; .NET4.0C; .NET4.0E; LBBROWSER)\",\n # QQ浏览器\n \"Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; WOW64; Trident/5.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; .NET4.0C; .NET4.0E; QQBrowser/7.0.3698.400)\",\n \"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; QQDownload 732; .NET4.0C; .NET4.0E)\",\n # sogou浏览器\n \"Mozilla/5.0 (Windows NT 5.1) AppleWebKit/535.11 (KHTML, like Gecko) Chrome/17.0.963.84 Safari/535.11 SE 2.X MetaSr 1.0\",\n \"Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; Trident/4.0; SV1; QQDownload 732; .NET4.0C; .NET4.0E; SE 2.X MetaSr 1.0)\",\n # maxthon浏览器\n \"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Maxthon/4.4.3.4000 Chrome/30.0.1599.101 Safari/537.36\",\n # UC浏览器\n \"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/38.0.2125.122 UBrowser/4.0.3214.0 Safari/537.36\",\n ]\n\n def __logging(self):\n # 内部函数;用于记录日志\n logging.basicConfig(filename=self.mypath[3]+r\"\\Express_Tracking.log\",\n filemode=\"w\",\n format=\"%(asctime)s %(name)s:%(levelname)s:%(message)s\",\n datefmt=\"%d-%M-%Y %H:%M:%S\",\n level=logging.INFO\n )\n self.logger_error = logging.getLogger(\"Express_Tracking\")\n self.logger = logging.getLogger(\"15Scends\")\n handler = logging.StreamHandler()\n handler.setLevel(logging.INFO)\n formatter = logging.Formatter(\n \"%(asctime)s %(name)s %(levelname)s %(message)s\")\n handler.setFormatter(formatter)\n self.logger.addHandler(handler)\n self.logger.info('请在60秒内用手机完成微信扫码,超时后会视同不扫码继续运行')\n self.logger.info('可以不使用对应手机号的微信扫码,但是将无法获得电子存根信息')\n self.logger.info('成功扫码之后可以将二维码图片关闭')\n self.logger.info('正在打开微信扫码界面,请耐心等待30秒左右···\\n')\n\n def debug(func):\n def wrapper(self,*args, **kwargs):\n try:\n return func(self,*args, **kwargs)\n except Exception:\n self.logger_error.exception(\"Recording Errors\")\n return wrapper\n\n def __wait(self):\n # 内部函数;随机等待\n sleep_time = round(random.uniform(0.5, 2), 2)\n time.sleep(sleep_time)\n\n def __is_visible(self, locator, timeout=60):\n # 内部函数;判断网页元素是否出现\n try:\n WebDriverWait(self.browser, timeout).until(\n EC.visibility_of_element_located((By.XPATH, locator)))\n return True\n except TimeoutException:\n return False\n\n def __is_not_visible(self, locator, timeout=60):\n # 内部函数;判断网页元素是否消失\n try:\n WebDriverWait(self.browser, timeout).until_not(\n EC.visibility_of_element_located((By.XPATH, locator)))\n return True\n except TimeoutException:\n return False\n\n def __WelCome(self):\n # 打印程序描述\n tb = pt.PrettyTable()\n tb.field_names = ['名称', '快递批量查询截图工具2.0']\n tb.add_row(['作者', '王文铖'])\n tb.add_row(['微信公众号', '15Seconds'])\n tb.add_row(['', ''])\n tb.add_row(['', '关注微信公众号'])\n tb.add_row(['使用方法', '可查看工具详细使用方法'])\n tb.add_row(['', '还能获取更多实用工具'])\n tb.add_row(['', ''])\n tb.add_row(['GitHub项目地址', 'https://github.com/nigo81/tools-for-auditor'])\n tb.add_row(['', ''])\n tb.add_row(['更新时间', '2019-12-02'])\n print(tb)\n print('\\n')\n\n def __ceart_enviroment(self):\n # 创建本次输出的文件环境\n result_path = self.nowpath+'\\\\Output\\\\' + self.query_time\n img_path = result_path+r'\\img'\n xls_path = result_path+r'\\xls'\n log_path = result_path+r'\\log'\n temp_path = result_path+r'\\temp'\n self.mypath=[result_path,img_path,xls_path,log_path,temp_path]\n [os.makedirs(path) for path in self.mypath if not os.path.exists(path)]\n scan_img = temp_path+r'\\scan_img.png'\n self.mypath.append(scan_img)\n\n @debug\n def __open_browser(self):\n # 打开浏览器\n # self.browser.set_window_size(1366,760)\n self.browser.set_window_size(2560,1440)\n self.browser.get(self.sf_Express_url)\n self.__wait()\n js2='window.open(\"{}\");'.format(self.kuaidi100_url)\n self.browser.execute_script(js2)\n self.__wait()\n all_handles = self.browser.window_handles\n self.sf_tab=all_handles[0]\n self.kd100_tab=all_handles[1]\n self.browser.switch_to_window(self.kd100_tab)\n # js1=r\"\"\"\n # var size = {}; \n # document.body.style.zoom = size;\n # document.body.style.cssText += '; -moz-transform: scale(' + size + ');-moz-transform-origin: 0 0; '; \n # \"\"\".format(str(self.html_size))\n # self.browser.execute_script(js1)\n self.browser.switch_to_window(self.sf_tab)\n\n def __scan_login(self):\n # 扫码登陆\n self.__wait()\n try:\n self.browser.find_element_by_xpath('//span[@class=\"agreeCookie\"]').click()\n except:\n pass\n self.__wait()\n self.browser.find_element_by_xpath('//a[@class=\"topa maidian\"]').click()\n self.__is_visible('//img[@class=\"scan-img\"]')\n self.__wait()\n self.browser.save_screenshot(self.mypath[5])\n self.__wait()\n # 创建一个新浏览器打开扫码界面\n driver = webdriver.Firefox(executable_path=self.executable_path)\n scan_pic='file:///' + self.mypath[5].replace('\\\\','/')\n driver.maximize_window()\n driver.get(scan_pic)\n scan = self.__is_not_visible('//div[@class=\"layui-layer-shade\"]')\n if scan == False:\n self.logger.info('超出60秒未进行微信扫码,直接进行查询')\n try:\n self.browser.find_element_by_xpath('//span[@class=\"layui-layer-setwin\"]/a').click()\n self.__wait()\n except Exception:\n self.logger_error.exception(\"Recording Errors\")\n self.logger.info('没有查询到相关物流信息')\n else:\n self.logger.info('扫码成功,开始查询')\n\n @debug\n def input_bill_number(self):\n # 输入快递单号开始查询\n self.logger.info('正在输入单号进行查询')\n input_box=self.browser.find_element_by_xpath('//input[@class=\"token-input\"]')\n input_box.send_keys(self.bill_number+',')\n self.__wait()\n self.browser.find_element_by_xpath('//span[@id=\"queryBill\"]').click()\n self.__wait()\n\n @debug\n def switch_to_iframe(self):\n # 切换至验证码弹窗网页框架\n self.__is_visible('//iframe')\n # 找到“嵌套”的iframe\n iframe = self.browser.find_element_by_xpath('//iframe')\n self.browser.switch_to.frame(iframe)\n self.__wait()\n\n @debug\n def get_verify_img(self,verify_times):\n # 获取验证码图片\n self.logger.info('第 {} 次尝试解析滑动验证码'.format(str(verify_times)))\n self.incomplete_img = self.mypath[4]+r'\\{}_img_incomplete.jpg'.format(str(self.num))\n self.complete_img = self.mypath[4]+r'\\{}_img_complete.jpg'.format(str(self.num))\n # 保存带缺口的滑动图片\n self.__wait()\n img = self.browser.find_element_by_xpath('//img[@id=\"slideBkg\"]')\n incomplete_img_url = img.get_attribute('src')\n urlretrieve(url=incomplete_img_url, filename=self.incomplete_img)\n # 保存完整的滑动图片\n complete_img_url = incomplete_img_url[:-1]+'0'\n urlretrieve(url=complete_img_url, filename=self.complete_img)\n\n def __is_pixel_equal(self, bg_image, fullbg_image, x, y):\n # 内部函数:用于判断两张图片的像素点差异\n # 获取缺口图片的像素点(按照RGB格式)\n bg_pixel = bg_image.load()[x, y]\n # 获取完整图片的像素点(按照RGB格式)\n fullbg_pixel = fullbg_image.load()[x, y]\n # 设置一个判定值,像素值之差超过判定值则认为该像素不相同\n threshold = 50\n # 判断像素的各个颜色之差,abs()用于取绝对值\n se1 = abs(bg_pixel[0] - fullbg_pixel[0])\n se2 = abs(bg_pixel[1] - fullbg_pixel[1])\n se3 = abs(bg_pixel[2] - fullbg_pixel[2])\n if se1 < threshold and se2 < threshold and se3 < threshold:\n return True\n else:\n return False \n\n def get_distance(self):\n # 获取滑动验证码需要滑动的距离\n initial_pos = 24\n fullbg_image = Image.open(self.complete_img)\n bg_image = Image.open(self.incomplete_img)\n for i in range(initial_pos, fullbg_image.size[0]):\n # 遍历像素点纵坐标\n for j in range(fullbg_image.size[1]):\n # 如果不是相同像素\n if not self.__is_pixel_equal(fullbg_image, bg_image, i, j):\n # 返回此时横轴坐标就是滑块需要移动的距离\n mov_pos = i/2-initial_pos\n return mov_pos\n\n def get_tracks(self,mov_pos):\n # 获取滑动路径列表\n forward_tracks=[]\n mov_pos += 6 # 要回退的像素\n v0, s, t = 0, 0, 0.4 # 初速度为v0,s是已经走的路程,t是时间\n mid = mov_pos*3/5 # mid是进行减速的路程\n while s < mov_pos:\n if s < mid: # 加速区\n a = 5\n else: # 减速区\n a = -3\n v = v0\n tance = v*t+0.5*a*(t**2)\n tance = round(tance)\n s += tance\n v0 = v+a*t\n forward_tracks.append(tance)\n # 因为回退20像素,所以可以手动打出,只要和为20即可\n backward_tracks = [-1, -2, -1, -2]\n random.shuffle(backward_tracks) # 洗牌\n return forward_tracks,backward_tracks\n\n def move_slider(self,forward_tracks,backward_tracks):\n # 开始模拟滑动验证码,先前进再后退\n self.logger.info('解析成功,正在模拟滑动验证码···')\n slider = self.browser.find_element_by_xpath(\n '//div[@id=\"tcaptcha_drag_button\"]')\n # 使用click_and_hold()方法悬停在滑块上,perform()方法用于执行\n ActionChains(self.browser).click_and_hold(slider).perform()\n # 使用move_by_offset()方法拖动滑块,perform()方法用于执行\n for forword_track in forward_tracks:\n ActionChains(self.browser).move_by_offset(\n xoffset=forword_track, yoffset=0).perform()\n self.__wait()\n for backward_tracks in backward_tracks:\n ActionChains(self.browser).move_by_offset(\n xoffset=backward_tracks, yoffset=0).perform()\n # 模拟人类对准时间\n self.__wait()\n # 释放滑块\n ActionChains(self.browser).release().perform()\n try:\n if self.__is_not_visible('//p[@class=\"tcaptcha-title\"]',10):\n verify_ok = True\n else:\n verify_ok = False\n except Exception:\n verify_ok = True\n finally:\n return verify_ok\n\n @debug\n def switch_to_default(self):\n # 切换至主页面\n self.browser.switch_to.default_content()\n self.__wait()\n\n def __get_route_pic(self,roll=0,pic_n=''):\n js='document.getElementsByClassName(\"routes-wrapper\")[0].scrollTop='+str(roll)\n self.browser.execute_script(js)\n self.browser.save_screenshot(self.screenshot_img_temp.replace('.png',pic_n))\n return Image.open(self.screenshot_img_temp.replace('.png',pic_n))\n\n @debug\n def get_route_info(self):\n # 获取物流节点信息和截图\n self.route = ''\n self.logger.info('获取物流节点信息和截��')\n self.screenshot_img1 = self.mypath[1] + r'\\%s-WLJD-%s.png' % (self.shot_name, self.bill_number)\n self.screenshot_img_temp = self.mypath[4] + r'\\%s-WLJD-%s.png' % (self.shot_name, self.bill_number)\n try:\n delivery_map=self.browser.find_element_by_xpath('//div[@class=\"delivery\"]/div[1]').get_attribute('class')\n target=self.browser.find_element_by_xpath('//input[@type=\"checkbox\"]')\n if delivery_map=='delivery-item send-out-item' or delivery_map=='delivery-item send-out-item ' :\n js = \"document.getElementsByClassName('delivery-item send-out-item')[0].className = 'delivery-item send-out-item brief-model'\"\n self.browser.execute_script(js)\n # delivery-item send-out-item brief-model\n self.__wait()\n self.browser.execute_script(\"arguments[0].scrollIntoView();\", target)\n self.__wait()\n routes = self.browser.find_elements_by_xpath('//div[@class=\"route-list\"]/ul')\n for rou in routes:\n r = rou.text.replace('\\n', ' ')\n self.logger.info(r)\n self.route = self.route+'\\n'+ r\n if 0< len(routes) <=8:\n newpic=self.__get_route_pic(0,'.png')\n elif 8 < len(routes)<=16:\n im1=self.__get_route_pic(0,'_1.png')\n im2=self.__get_route_pic(285,'_2.png')\n self.logger.info('正在拼接物流节点截图')\n x,y=im1.size[0],im1.size[1]\n sb,xb=290,(1344-580) #上边距,下边距\n y1=im1.size[1]-sb-xb\n im1 = im1.crop((0, 0, x, y-xb))\n im2 = im2.crop((0, sb, x, y-xb))\n newpic = Image.new('RGB', (x, y+y1-xb)) \n newpic.paste(im1, (0, 0, x, y-xb))\n newpic.paste(im2, (0, y-xb, x, y-xb+y1))\n newpic.save(self.screenshot_img1)\n elif len(routes)>16:\n im1=self.__get_route_pic(0,'_1.png')\n im2=self.__get_route_pic(285,'_2.png')\n im3=self.__get_route_pic(570,'_3.png') \n self.logger.info('正在拼接物流节点截图')\n x,y=im1.size[0],im1.size[1]\n sb,xb=290,(1344-580) #上边距,下边距\n y1=im1.size[1]-sb-xb\n im1 = im1.crop((0, 0, x, y-xb))\n im2 = im2.crop((0, sb, x, y-xb))\n im3 = im3.crop((0, sb, x, y-xb))\n newpic = Image.new('RGB', (x, y+y1*2-xb)) \n newpic.paste(im1, (0, 0, x, y-xb))\n newpic.paste(im2, (0, y-xb, x, y-xb+y1))\n newpic.paste(im3, (0, y-xb+y1, x, y-xb+y1+y1))\n newpic.save(self.screenshot_img1)\n newpic = newpic.crop((790, 90, newpic.size[0]-790, newpic.size[1]))\n newpic.save(self.screenshot_img1)\n\n except Exception:\n self.logger.info('没有查询到相关物流信息')\n\n def get_dzcg_info(self):\n # 获取电子存根信息和截图\n self.logger.info('正在获取电子存根信息和截图')\n self.screenshot_img2 = self.mypath[1] + r'\\%s-YDXQ-%s.png' % (self.shot_name, self.bill_number)\n self.screenshot_img3 = self.mypath[1] + r'\\%s-DZCG-%s.png' % (self.shot_name, self.bill_number)\n self.dzcg = ''\n try:\n self.browser.find_element_by_xpath(\n '//div[@class=\"operates-wrapper\"]/a').click()\n self.__wait()\n target = self.browser.find_element_by_xpath(\n '//a[@aria-controls=\"waybillDetail\"]')\n target.click()\n self.browser.execute_script(\n \"arguments[0].scrollIntoView();\", target)\n self.__wait()\n self.browser.save_screenshot(self.screenshot_img2)\n newpic=Image.open(self.screenshot_img2)\n newpic = newpic.crop((980, 460, newpic.size[0]-995, newpic.size[1]-525))\n newpic.save(self.screenshot_img2)\n target = self.browser.find_element_by_xpath(\n '//a[@aria-controls=\"electronicStub\"]')\n target.click()\n self.browser.execute_script(\n \"arguments[0].scrollIntoView();\", target)\n self.__wait()\n self.browser.save_screenshot(self.screenshot_img3)\n newpic=Image.open(self.screenshot_img3)\n newpic = newpic.crop((980, 190, newpic.size[0]-990, newpic.size[1]-520))\n newpic.save(self.screenshot_img3)\n dzcgs = self.browser.find_elements_by_xpath(\n '//table[@class=\"borderrb\"]/tbody/tr')\n for dz in dzcgs:\n r = dz.text.replace('\\n', ' ')\n self.logger.info(r)\n self.dzcg = self.dzcg+'\\n'+r\n except Exception:\n self.logger.info('该单号对应的手机号与扫码的微信号可能不符,无法获取电子存根截图')\n\n @debug\n def next_bill_number(self):\n # 关闭电子存根界面,开始查下一个单号\n try:\n self.browser.find_element_by_xpath(\n '//button[@class=\"close\"]').click()\n self.__wait()\n except Exception:\n self.logger_error.exception(\"Recording Errors\")\n self.browser.find_element_by_xpath(\n '//a[@class=\"close\"]').click()\n self.browser.find_element_by_xpath(\n '//span[@class=\"sfi sfi-trash\"]').click()\n self.__wait()\n\n def sf_single(self):\n ''' 顺丰主体 '''\n self.browser.switch_to_window(self.sf_tab)\n self.__wait()\n self.input_bill_number()\n self.switch_to_iframe()\n verify_times,verify_ok=0,False\n while verify_times<=4 and verify_ok==False:\n try:\n verify_times+=1\n self.browser.find_element_by_xpath('//div[@id=\"reload\"]').click()\n self.get_verify_img(verify_times)\n mov_pos=self.get_distance() \n forward_tracks,backward_tracks=self.get_tracks(mov_pos) \n verify_ok=self.move_slider(forward_tracks,backward_tracks) \n except Exception:\n self.logger_error.exception(\"Recording Errors\")\n self.__wait()\n finally:\n self.logger.info('verify_ok = ' + str(verify_ok))\n if verify_times > 4:\n self.logger.info('验证解析尝试5次失败,不再尝试,开始下一个单号')\n if verify_ok==True:\n self.switch_to_default()\n self.get_route_info()\n self.get_dzcg_info()\n self.next_bill_number()\n\n def kd100_single(self):\n self.browser.switch_to_window(self.kd100_tab)\n self.__wait()\n try:\n self.browser.find_element_by_xpath('//span[@class=\"coupon-pop-close\"]').click()\n except:\n pass\n self.__wait()\n self.__wait()\n input_box=self.browser.find_element_by_xpath('//input[@id=\"postid\"]')\n self.browser.execute_script(\"arguments[0].scrollIntoView();\",input_box)\n input_box.send_keys(self.bill_number) \n self.__wait()\n self.browser.find_element_by_xpath('//a[@id=\"query\"]').click()\n self.__wait()\n # 物流节点\n self.logger.info('正在获取物流节点详细信息')\n self.dzcg = ''\n self.route= ''\n try:\n routes = self.browser.find_elements_by_xpath(\n '//table[@class=\"result-info\"]/tbody/tr')\n for rou in routes:\n r = rou.text.replace('\\n', ' ')\n self.logger.info(r)\n self.route = self.route+'\\n'+r\n except Exception:\n self.logger_error.exception(\"Recording Errors\")\n self.logger.info('没有查询到相关物流信息')\n self.logger.info('正在获取物流节点截图') \n notFindTip=self.browser.find_elements_by_xpath('//div[@id=\"notFindTip\"]')[0].get_attribute(\"style\") \n # 获取截图\n if notFindTip=='display: none;':\n self.screenshot_img4=self.mypath[1] + r'\\%s-WLJD-%s.png' % (self.num, self.bill_number)\n self.browser.save_screenshot(self.screenshot_img4)\n self.__wait()\n im = Image.open(self.screenshot_img4)\n im1 = im.crop((800, 0, im.size[0]-800, im.size[1]-100))\n im1.save(self.screenshot_img4)\n self.logger.info('物流节点截图已保存') \n else:\n self.logger.info('该单号没有物流信息,暂不截图')\n\n def get_comcode(self):\n if self.bill_number[:2]==\"SF\":\n code = 'shunfeng'\n else:\n headers = {'User-Agent': random.choice(self.user_agent_list),\n 'Host': 'www.kuaidi100.com',\n 'Connection': 'keep-alive',\n 'Content-Length': '0',\n 'Accept': 'application/json, text/javascript, */*; q=0.01',\n 'X-Requested-With': 'XMLHttpRequest',\n 'Sec-Fetch-Mode': 'cors',\n 'Origin': 'https://www.kuaidi100.com',\n 'Sec-Fetch-Site': 'same-origin',\n 'Referer': 'https://www.kuaidi100.com/',\n 'Accept-Encoding': 'gzip, deflate, br',\n 'Accept-Language': 'zh-CN,zh;q=0.9',\n }\n url = 'https://www.kuaidi100.com/autonumber/autoComNum?resultv2=1&text='+self.bill_number\n data = {'resultv2': '1', 'text': self.bill_number}\n try:\n r = requests.post(url, headers=headers, data=data)\n result = r.json()\n code_en = [i['comCode'] for i in result['auto']]\n code=code_en[0]\n except:\n code = 'unknow'\n \n return code\n\n def main(self,shot_name,bill_number=[]):\n try:\n self.num,self.bill_number=bill_number[0],str(bill_number[1])\n self.shot_name=shot_name\n self.logger.info('当前进度:{}/{} ,正在查询的单号为 [{}]'.format(self.num,self.count,self.bill_number))\n comcode=self.get_comcode()\n if comcode=='unknow':\n self.logger.info('单号 [{}] 所属快递公司未知,无法查询'.format(self.bill_number))\n else:\n self.logger.info('单号 [{}] 所属快递公司为 [{}]'.format(self.bill_number,comcode))\n if comcode=='shunfeng':\n self.sf_single()\n else:\n self.kd100_single()\n except Exception:\n self.logger_error.exception(\"Recording Errors\")\n finally:\n data=[self.bill_number,self.route,self.dzcg]\n print('\\n')\n return data\n\n def __del__(self):\n self.browser.quit()\n\n\nclass Input_and_Output(object):\n\n def __validateFileName(self,FileName):\n rstr = r\"[\\/\\\\\\:\\*\\?\\\"\\<\\>\\|]\" # '/ \\ : * ? \" < > |'\n new_FileName = re.sub(rstr, \"-\", FileName) # 替换为下划线\n return new_FileName\n\n def load_input(self):\n try:\n input_path=os.path.abspath(os.curdir)+r'\\Input\\bill_number.xlsx'\n df = pd.read_excel(input_path).dropna()\n bill_number_list=(df[\"2\"]).tolist()[1:]\n shot_name_list=(df[\"3\"]).tolist()[1:]\n shot_name_list = [self.__validateFileName(i) for i in shot_name_list]\n if len(bill_number_list) == 0:\n print('bill_number.xlsx 中未发现快递单号') \n return bill_number_list,shot_name_list\n except Exception as e:\n print('快递单号读取错误,检查是否存在 bill_number.xlsx 工作簿') \n \n def output_csv(self, output_path='',data=[]):\n '''输出文件'''\n self.output_path=output_path + r'\\express_route.csv'\n with open(self.output_path, 'a', newline='', encoding='utf-8-sig')as f:\n writer = csv.writer(f)\n writer.writerow(data)\n\n def csv_to_xlsx(self):\n '''转换为xlsx'''\n csv = pd.read_csv(self.output_path, encoding='utf-8-sig')\n csv.to_excel(self.output_path.replace('.csv', '.xlsx'), sheet_name='15Seconds')\n\n\ndef main():\n start=time.time()\n io=Input_and_Output() # 实例1\n bill_number_list,shot_name_list=io.load_input()\n count=len(bill_number_list)\n bill_number_list=list(enumerate(bill_number_list,start=1))\n \n if count>0:\n track=Express_Tracking(count)# 实例2\n mypath=track.mypath\n title=['物流单号','物流节点','电子存根']\n io.output_csv(mypath[2],title)\n for i in range(len(bill_number_list)):\n data = track.main(shot_name_list[i],bill_number_list[i])\n io.output_csv(mypath[2],data)\n io.csv_to_xlsx()\n if count/100==0:\n track.logger.info('每查询100个,休息2分钟')\n time.sleep(120)\n else:\n pass\n stamp = time.time() - start\n mon=round(stamp/60)\n track.logger.info('所有快递单号查询结束,总用时约 {} 分钟'.format(mon))\n del track\n\nif __name__ == \"__main__\":\n main()\n # io=Input_and_Output() # 实例1\n # bill_number_list=io.load_input()\n # print(bill_number_list)\n","sub_path":"19_快递批量查询截图工具/Express_Tracking.py","file_name":"Express_Tracking.py","file_ext":"py","file_size_in_byte":29881,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"226595155","text":"#!/usr/bin/python3\n#-*- coding: utf-8 -*-\n# delete des auth_key de J-1 et somme par customer et login\n# import de la librairie système\nimport sys\n# import de la librairie Operating System\nimport os\n\n#reload(sys)\n#sys.setdefaultencoding('utf-8')\n\n# déntion du rértoire python d'exétion\n#sys.path.append(os.getcwd())\n\n# import du module sql\nimport sqlite3\n\n# import de la fonction de convertion des tuples\nfrom erreur_sqlite import erreur_sqlite\n\nfrom FrameworkPapIT import FrameworkPapIT\nclient = FrameworkPapIT(customer,login,password,auth_key,__file__)\n\n# calcul du nombre de connection par login\nconnection = sqlite3.connect(client.papitSQLite)\nrequest = \"\"\"insert into conso (customer, login, date, connection)\nselect user.customer, user.login, date(auth.ts), count(*) \nfrom auth \ninner join user on user.login = auth.login\nwhere date(auth.ts) = date('now','-1 day') group by user.login;\"\"\"\ntry:\n\tconnection.execute(request)\n\tconnection.commit()\n# purge des connections de la veille\n\trequest = \"\"\"delete from auth where date(auth.ts) = date('now','-1 day');\"\"\"\n\ttry:\n\t\tconnection.execute(request)\n\t\tconnection.commit()\n\t\tconnection.close()\n\t\tok = \"Succès du count de auth et insert dans conso et de la purge de auth\"\n\texcept sqlite3.Error as e:\n\t\terreur_sqlite(connection,request,e.args[0])\n\t\terr = \" erreur sur la requête de delete sur\"\n\t\tclient.Journal(err)\n\t\tsys.stdout.write(err)\nexcept sqlite3.Error as e:\n\terr = \" erreur sur la requête de count de auth et insert dans conso\"\n\tclient.Journal(err)\n\tsys.stdout.write(err)\n\terreur_sqlite(connection,request,e.args[0])\n\t\n# affichage et journalisation\nsys.stdout.write(ok)\nclient.Journal(ok)\n\n# fin de programme sans erreur\nsys.exit(0)\n","sub_path":"py/auth_batch.py","file_name":"auth_batch.py","file_ext":"py","file_size_in_byte":1696,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"497865746","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sun Dec 2 22:22:03 2018\n\n@author: Hugo\n\"\"\"\n\ndef budgeting(budget,products,wishlist):\n \n products = sorted(products.items(), key = lambda x: x[1],reverse = True)\n products = dict(products)\n cost = 0\n n_wish = {}\n \n for i in products:\n prod_price = products[i]\n if i in wishlist:\n cost += prod_price * wishlist[i]\n \n if cost <= budget:\n return wishlist\n elif cost > budget:\n cost = 0\n \n for i in products:\n prod_price = products[i]\n \n if i in wishlist:\n for j in range(wishlist[i]):\n if cost + prod_price <= budget:\n \n if i in n_wish:\n n_wish[i] += 1\n else:\n n_wish.update({i:1})\n cost += prod_price\n return n_wish\n ","sub_path":"1st_Year/1st_Semestre/Fpro/Python/RE/RE09/budgeting.py","file_name":"budgeting.py","file_ext":"py","file_size_in_byte":960,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"395379619","text":"import io, math\nimport numpy\nimport pandas\nimport sqlite3\nimport util.main as main\n\ndef unpack_qc(value):\n 'unpack a qc result from the db'\n\n try:\n qc = numpy.load(io.BytesIO(value), allow_pickle=True)\n except:\n print('failed to unpack qc data - check db for missing entries.')\n qc = numpy.zeros(1, dtype=bool)\n\n return qc\n\ndef summarize(levels):\n 'given an array of level qc decisions, return true iff any of the levels are flagged'\n\n return numpy.any(levels)\n\ndef parse(results):\n 'parse the raw pickled text of a per-level qc result, and return True if any levels are flagged'\n\n return results.apply(unpack_qc).apply(summarize)\n\ndef summarize_truth(levels):\n 'given an array of originator qc decisions, return true iff any of the levels are flagged, ignoring t=99 levels'\n\n return numpy.sum( [not levels.mask[i] and (x==3 or x==4) for i, x in enumerate(levels)]) >= 1\n\ndef parse_truth(results):\n\n return results.apply(unpack_qc).apply(summarize_truth)\n\ndef get_n_levels_before_fail(results):\n\n nlevels = []\n for result in results:\n n = 0\n for qc in unpack_qc(result):\n if qc == False:\n n += 1\n else:\n break\n nlevels.append(n)\n\n return nlevels\n\ndef get_reversed_n_levels_before_fail(results):\n\n nlevels = []\n for result in results:\n n = 0\n for qc in unpack_qc(result)[::-1]:\n if qc == False:\n n -= 1\n else:\n break\n \n nlevels.append(n)\n\n return nlevels\n\ndef check_for_fail(results):\n\n fails = []\n for result in results:\n answer = False\n for qc in unpack_qc(result):\n if qc == True:\n answer = True\n break\n fails.append(answer)\n\n return fails\n\ndef unpack_qc_results(results):\n\n return [unpack_qc(result) for result in results] \n\ndef db_to_df(table,\n filter_on_wire_break_test=False, \n filter_on_tests={},\n n_to_extract=numpy.iinfo(numpy.int32).max,\n applyparse=True,\n targetdb='iquod.db'):\n\n '''\n Reads the table from targetdb into a pandas dataframe.\n If filter_on_wire_break_test is True, the results from that test are used to exclude\n levels below a wire break from the test results and the wire break test is not returned.\n filter_on_tests is a generalised form of filter_on_wire_break and is used to exclude results; it takes a list of\n [testname, action], where levels failing are excluded towards the surface (if action is 'up'), towards depth (if action is 'down') and the whole profile deleted (if action is 'remove').\n Set n_to_extract to limit the number of rows extracted to the specified number.\n '''\n\n # what tests are available\n testNames = main.importQC('qctests')\n testNames.sort()\n\n # connect to database\n conn = sqlite3.connect(targetdb, isolation_level=None)\n cur = conn.cursor()\n\n # extract matrix of test results and true flags into a dataframe\n query = 'SELECT uid, truth'\n for test in testNames:\n query += ', ' + test.lower()\n query += ' FROM ' + table \n query += ' WHERE uid IN (SELECT uid FROM ' + table + ' ORDER BY RANDOM() LIMIT ' + str(n_to_extract) + ')' \n\n cur.execute(query)\n rawresults = cur.fetchall()\n\n sub = 1000\n df_final = None\n for i in range(math.ceil(len(rawresults)/sub)):\n df = pandas.DataFrame(rawresults[i*sub:(i+1)*sub]).astype('bytes')\n df.columns = ['uid', 'Truth'] + testNames\n df = df.astype({'uid': 'int'})\n if filter_on_wire_break_test:\n nlevels = get_n_levels_before_fail(df['CSIRO_wire_break'])\n del df['CSIRO_wire_break'] # No use for this now.\n testNames = df.columns[2:].values.tolist()\n for i in range(len(df.index)):\n for j in range(1, len(df.columns)):\n qc = unpack_qc(df.iloc[i, j])\n # Some QC tests may return only one value so check for this.\n if len(qc) > 1:\n qc = qc[:nlevels[i]]\n df.iat[i, j] = main.pack_array(qc)\n\n todrop = set()\n for action in filter_on_tests:\n # Check if the action is relevant.\n if action == 'Optional' or action == 'At least one from group': continue\n\n # Initialise variables.\n nlevels = -1\n outcomes = False\n qcresults = []\n for testname in filter_on_tests[action]:\n for i in range(0, len(df.index)):\n if action == 'Remove above reject':\n nlevels = get_reversed_n_levels_before_fail([df[testname][i]])[0]\n elif action == 'Remove below reject':\n nlevels = get_n_levels_before_fail([df[testname][i]])[0]\n elif action == 'Remove profile':\n outcomes = check_for_fail([df[testname][i]])[0]\n elif action == 'Remove rejected levels':\n qcresults = unpack_qc_results([df[testname][i]])[0]\n else:\n raise NameError('Unrecognised action: ' + action)\n\n if (((action == 'Remove above reject' or action == 'Remove below reject') and nlevels == 0) or\n (action == 'Remove profile' and outcomes == True) or\n (action == 'Remove rejected levels' and numpy.count_nonzero(qcresults == False) == 0)):\n # Completely remove a profile if it has no valid levels or if it\n # has a fail and the action is to remove.\n todrop.add(i)\n elif (action != 'Remove profile'):\n for j in range(1, len(df.columns)):\n # Retain only the levels that passed testname.\n # Some QC tests may return only one value so check for this.\n qc = unpack_qc(df.iloc[i, j])\n if len(qc) > 1:\n if action == 'Remove above reject':\n qc = qc[nlevels:]\n elif action == 'Remove below reject':\n qc = qc[:nlevels] \n elif action == 'Remove rejected levels':\n qc = qc[qcresults == False] \n df.iat[i, j] = main.pack_array(qc)\n\n del df[testname] # No need to keep this any longer.\n df.reset_index(inplace=True, drop=True)\n \n todrop = list(todrop)\n if len(todrop) > 0:\n df.drop(todrop, inplace=True)\n df.reset_index(inplace=True, drop=True)\n testNames = df.columns[2:].values.tolist()\n if applyparse:\n df[['Truth']] = df[['Truth']].apply(parse_truth)\n df[testNames] = df[testNames].apply(parse)\n\n if i == 0:\n df_final = df\n else:\n df_final = pandas.concat([df_final, df])\n\n return df_final.reset_index(drop=True)\n","sub_path":"util/dbutils.py","file_name":"dbutils.py","file_ext":"py","file_size_in_byte":7274,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"434612663","text":"\"\"\"\n@copyright Copyright (c) 2011 - 2016, Intel Corporation.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n\n@file test_ixnetwork.py\n\n@summary Samples for Traffic Generator IxNetwork configuration.\n\n@details\nFollowing test cases are tested:\n1. IxNetwork interface and traffic configuration.\n2. IxNetwork STP configuration.\n3. IxNetwork LACP configuration.\n4. IxNetwork OSPF configuration.\n5. IxNetwork BGP configuration.\n\"\"\"\n\nimport time\n\nimport pytest\n\nfrom testlib import helpers\n\n\n@pytest.mark.ixnet_simplified\nclass TestTGIxNetworkSamples(object):\n \"\"\"\n @description Suite for Traffic Generator IxNetwork configuration\n \"\"\"\n\n def test_iface_traffic_configuration(self, env):\n \"\"\"\n @brief IxNetwork interface and traffic configuration\n @note IxNetwork HLT API has special Tcl methods in order to configure interfaces and traffic.\n TAF contains Python wrappers for these methods.\n \"\"\"\n # Get available TG ports from the environment\n ports = env.get_ports([['tg1', 'sw1', 4], ])\n tg_ports = list(ports[('tg1', 'sw1')].values())\n # Set necessary ports in Up state\n helpers.set_ports_admin_enabled(env.switch, ports)\n\n # Configure IxNetwork interface\n # Please see ::ixia::interface_config for all supported arguments\n env.tg[1].iface_config(tg_ports[0], autonegotiation='1', duplex='auto',\n speed='auto', intf_ip_addr='10.0.0.3', gateway='10.0.0.1',\n netmask='255.255.255.0')\n\n # Configure IP address and gateaway\n env.tg[1].iface_config(tg_ports[1], autonegotiation=1, duplex='auto',\n speed='auto', intf_ip_addr='10.0.0.2', gateway='10.0.0.1',\n netmask='255.255.255.0')\n\n # Configure traffic\n # Please see ::ixia::traffic_config for all supported arguments\n env.tg[1].traffic_config(\n mode='create', transmit_mode='continuous', src_dest_mesh='fully',\n route_mesh='one_to_one', circuit_type='none',\n circuit_endpoint_type='ipv4',\n emulation_src_handle=\"%s/%s/%s\" % tuple(tg_ports[0]),\n emulation_dst_handle=\"%s/%s/%s\" % tuple(tg_ports[1]),\n rate_percent=99, length_mode='random', frame_size_min=64, frame_size_max=1500\n )\n\n # Start the configured traffic\n env.tg[1].traffic_control(action='run')\n\n time.sleep(10)\n\n # Stop the configured traffic\n env.tg[1].traffic_control(action='stop')\n\n # Get traffic statistics\n env.tg[1].traffic_stats(tg_ports[0])\n env.tg[1].traffic_stats(tg_ports[1])\n\n send = int(env.tg[1].traffic_dictionary[tg_ports[0]]['stats']['aggregate']['tx']['total_pkts'])\n receive = int(env.tg[1].traffic_dictionary[tg_ports[1]]['stats']['aggregate']['rx']['total_pkts'])\n\n assert send <= receive\n\n def test_stp_emulation(self, env):\n \"\"\"\n @brief IxNetwork STP configuration.\n @note IxNetwork HLT API has special Tcl methods in order to configure STP emulation.\n TAF contains Python wrappers for these methods.\n \"\"\"\n # Get available TG ports from the environment\n ports = env.get_ports([['tg1', 'sw1', 4], ])\n tg_ports = list(ports[('tg1', 'sw1')].values())\n # Set necessary ports in Up state\n helpers.set_ports_admin_enabled(env.switch, ports)\n\n # Configure STP bridges\n # Please see ::ixia::emulation_stp_bridge_config for all supported arguments\n env.tg[1].STP.configure_bridges(tg_ports[0],\n auto_pick_bridge_mac=0,\n auto_pick_port=1,\n bridge_mac='00:01:00:00:00:01',\n bridge_mode='mstp',\n bridge_priority=0,\n root_cost=0,\n count='1',\n root_priority=0,\n root_mac='00:01:00:00:00:01',\n forward_delay='15000',\n hello_interval='2000',\n intf_count='1',\n max_age='20000',\n message_age='0')\n\n # Configure STP MSTI\n # Please see ::ixia::emulation_stp_msti_config for all supported arguments\n env.tg[1].STP.configure_msti(tg_ports[0],\n bridge_handler_id=\"1\",\n count='1',\n msti_id=1,\n msti_name='MSTI 1',\n msti_mac='00:01:00:00:00:01',\n msti_internal_root_path_cost=0,\n msti_priority=0,\n msti_vlan_start=10,\n msti_vlan_stop=11)\n\n # Start STP in IxNetwork\n env.tg[1].STP.control(tg_ports[0], bridge_handler_id='1', mode=\"start\")\n\n def test_lacp_emulation(self, env):\n \"\"\"\n @brief IxNetwork LACP configuration.\n @note IxNetwork HLT API has special Tcl methods in order to configure LACP emulation.\n TAF contains Python wrappers for these methods.\n \"\"\"\n # Get available TG ports from the environment\n ports = env.get_ports([['tg1', 'sw1', 4], ])\n tg_ports = tuple(ports[('tg1', 'sw1')].values())\n # Set necessary ports in Up state\n helpers.set_ports_admin_enabled(env.switch, ports)\n\n # Configure TG interfaces\n for tgport in tg_ports:\n env.tg[1].iface_config(tgport, autonegotiation='1', duplex='auto')\n\n # Configure LACP on TG interfaces\n # Please see ::ixia::emulation_lacp_link_config for all supported arguments\n lacplinks = env.tg[1].LACP.configure_links(tg_ports, mode='create',\n reset=True, lag_count='1',\n port_handle='$port_handle',\n actor_key='0',\n actor_port_num='2',\n actor_port_num_step='1',\n actor_port_pri='4096',\n actor_system_id='0000.1111.0000',\n actor_system_pri='8192',\n auto_pick_port_mac='1',\n collector_max_delay='10',\n lacp_activity='active',\n lacp_timeout='short',\n lacpdu_periodic_time_interval='auto')\n for lacp_link in lacplinks:\n env.tg[1].LACP.configure_links(tg_ports,\n link_handler_id=lacp_link,\n mode='enable')\n\n # Start LACP\n env.tg[1].LACP.control(tg_ports, mode='start')\n\n def test_ospf_emulation(self, env):\n \"\"\"\n @brief IxNetwork OSPF configuration.\n @note IxNetwork HLT API has special Tcl methods in order to configure OSPF emulation.\n TAF contains Python wrappers for these methods.\n \"\"\"\n # Get available TG ports from the environment\n ports = env.get_ports([['tg1', 'sw1', 4], ])\n # Set necessary ports in Up state\n helpers.set_ports_admin_enabled(env.switch, ports)\n\n tgport1 = ports[('tg1', 'sw1')][1]\n\n # Configure OSPF\n # Please see ::ixia::emulation_ospf_config for all supported arguments\n session_handle_1 = env.tg[1].OSPF.config(\n tgport1,\n reset=True,\n mode='create',\n mac_address_init='0000.0a01.0002',\n intf_ip_addr='10.1.0.2',\n router_id='2.2.2.2',\n area_id='0.0.0.0',\n router_priority=1,\n neighbor_intf_ip_addr='10.1.0.1',\n lsa_discard_mode=0,\n enable_dr_bdr=1,\n mtu=1500,\n session_type='ospfv2')\n\n # Configure OSPF routes\n # Please see ::ixia::emulation_ospf_topology_route_config for all supported arguments\n env.tg[1].OSPF.topology_route_config(\n session_handle_1,\n summary_number_of_prefix=1,\n summary_prefix_start='10.2.0.1',\n summary_prefix_length=24,\n summary_prefix_metric=20,\n summary_route_type='same_area',\n type='summary_routes')\n\n # start OSPF\n env.tg[1].OSPF.ospf_control(session_handle_1, mode='start')\n\n def test_bgp_emulation(self, env):\n \"\"\"\n @brief IxNetwork BGP configuration.\n @note IxNetwork HLT API has special Tcl methods in order to configure DGP emulation.\n TAF contains Python wrappers for these methods.\n \"\"\"\n # Get available TG ports from the environment\n ports = env.get_ports([['tg1', 'sw1', 4], ])\n tg_ports = list(ports[('tg1', 'sw1')].values())\n # Set necessary ports in Up state\n helpers.set_ports_admin_enabled(env.switch, ports)\n\n # Configure BGP\n # Please see ::ixia::emulation_bgp_config for all supported arguments\n env.tg[1].BGP.configure_neighbour(tg_ports[0],\n mode='enable',\n local_ip_addr='20.20.20.2',\n remote_ip_addr='20.20.20.1',\n count='1',\n hold_time=5,\n neighbor_type='internal',\n ip_version='4',\n vlan_id=1,\n local_as=7675,\n local_router_id='1.1.1.2')\n\n # Start BGP\n env.tg[1].BGP.control(port=tg_ports[0], mode='start')","sub_path":"general/test_ixnetwork.py","file_name":"test_ixnetwork.py","file_ext":"py","file_size_in_byte":10920,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"127828622","text":"\"\"\"\nContains views for the glance plugin.\n\"\"\"\n\n#TODO: Having to import app in all view functions, because i dont understand python imports.\n\nfrom flask import Blueprint, render_template, request, session, redirect, flash, url_for\nfrom flask_login import login_required\nfrom forms import DocumentEdit\n\nimport module.query\nimport config\n\n_glance = Blueprint('glance', 'glance', url_prefix='/glance')\n\nPLUGIN_CHECK = config.Config().AVAILABLE_PLUGINS['glance']\nTEMPLATES = 'plugins/glance/'\nPLUGIN_DISABLED_TEMPLATE = f'{TEMPLATES}glance_disabled.html'\n\n@_glance.route(\"/published_collections\")\n@login_required\ndef published_Collections():\n if PLUGIN_CHECK:\n collections = module.glance.GlanceLib().get_collections()\n\n publishers = []\n if 'data' in collections:\n for x in collections['data']:\n if x['publisher'] != 'None':\n publishers.append(x['publisher'])\n\n bla = sorted(list(set(publishers)))\n\n else:\n bla = []\n\n return render_template(f'{TEMPLATES}published_collections.html', collections=collections, publishers=bla)\n\n else:\n return render_template(PLUGIN_DISABLED_TEMPLATE)\n\n\n\n@_glance.route(\"/collection/delete/\")\n@login_required\ndef collection_delete(collection_id):\n if PLUGIN_CHECK:\n bla = module.glance.GlanceLib().delete_item(collection_id)\n\n return redirect(request.referrer)\n\n else:\n return render_template(PLUGIN_DISABLED_TEMPLATE)\n\n\n\n\n@_glance.route(\"/query\", methods=['GET', 'POST'])\n@login_required\ndef query_glance():\n if PLUGIN_CHECK:\n results = []\n\n form = request.form\n raw_user_query = form['user_query']\n\n query_results = module.glance.GlanceLib().query(raw_user_query)\n if query_results['status'] == 'success':\n if 'data' in query_results:\n results = query_results\n else:\n results = {}\n\n\n return render_template('glance_query.html', results=results)\n\n else:\n return render_template(PLUGIN_DISABLED_TEMPLATE)\n\n\n\n@_glance.route(\"/manage\", methods=['GET', 'POST'])\n@login_required\ndef glance_manage():\n if PLUGIN_CHECK:\n return render_template(f'{TEMPLATES}glance_manage.html')\n\n else:\n return render_template(PLUGIN_DISABLED_TEMPLATE)\n\n\n\n@_glance.route('/manage_selection', methods=['GET', 'POST'])\ndef manage_selection():\n if PLUGIN_CHECK:\n if 'collection_append' in request.form and request.form['collection_append'] != '':\n print('collections_append')\n \"\"\"\n payload = {}\n payload['id'] = request.form['collection_append']\n\n # get items in selection\n ids = []\n form_dict = request.form.to_dict()\n for x in form_dict:\n if form_dict[x] == 'on':\n ids.append(x)\n\n payload['items'] = ' '.join(ids)\n\n glance.modules.api.put_item(account_session.get(), payload)\n\n return redirect(f\"item/{payload['id']}\")\n \"\"\"\n return glance_manage()\n\n\n if 'tags' in request.form and request.form['tags'] != '':\n # imp appending all tags to each item in selection\n print('tags')\n\n \"\"\"\n\n #get selection\n # get items in selection\n ids = []\n form_dict = request.form.to_dict()\n for x in form_dict:\n if form_dict[x] == 'on':\n ids.append(x)\n\n # get tags\n\n payload = {}\n\n for x in ids:\n payload['id'] = x\n payload['tags'] = glance.modules.api.tag_string(request.form['tags'])\n\n glance.modules.api.put_item(account_session.get(), payload)\n\n return manage()\n \"\"\"\n\n return glance_manage()\n\n\n if 'clear_selection' in request.form and request.form['clear_selection'] == 'True':\n args = request.form.to_dict()\n\n items_to_remove_from_selection = []\n for k in args:\n if args[k] == 'on':\n items_to_remove_from_selection.append(k)\n\n for item in items_to_remove_from_selection:\n if item in session['fav']:\n module.query.PortalSession(session).fav(item)\n\n\n return glance_manage()\n\n\n if 'collection_name' in request.form and request.form['collection_name'] != '':\n import app\n print('collection_name')\n # IMP using checked == 'on'\n if 'fav' in session:\n items = []\n for x in session['fav']:\n items.append(x)\n\n payload = {\n 'name': request.form['collection_name'],\n 'item_type': 'collection',\n 'item_loc': 'site/default_cover.jpg',\n 'item_thumb': 'site/default_cover.jpg',\n 'tags': request.form['collection_name'].split(' '),\n 'items': ' '.join(items),\n 'author': app.load_user(session['user_id']).name\n }\n\n res = module.glance.GlanceLib().post_item(payload)\n\n if res:\n return redirect(f\"/glance/item/{res[0]['id']}\")\n\n return glance_manage()\n\n\n if 'delete_selection' in request.form and request.form['delete_selection'] == 'True':\n print('delete_selection')\n \"\"\"\n args = request.form.to_dict()\n\n items_for_deletion = []\n for k in args:\n if args[k] == 'on':\n items_for_deletion.append(k)\n\n for item in items_for_deletion:\n payload = {'id': item}\n resp = glance.modules.api.get_item(account_session.get(), payload)[0]\n \n data = []\n if 'item_loc' in resp:\n data.append(resp['item_loc'])\n if 'item_thumb' in resp:\n data.append(resp['item_thumb'])\n if 'attached' in resp:\n data.append(resp['attached'])\n\n # delete from s3 and database\n # TODO: IMP something safer.\n # upon deletion remove item from favs\n if item in account_session.get()['fav']:\n account_session.fav(item)\n\n auth.delete_from_s3(data)\n glance.modules.api.delete_item(account_session.get(), payload)\n\n\n return manage()\n \"\"\"\n return glance_manage()\n\n\n return glance_manage()\n\n else:\n return render_template(PLUGIN_DISABLED_TEMPLATE)\n\n\n\n@_glance.route(\"/query/\")\n@login_required\ndef query_glance_with_tag(tag):\n if PLUGIN_CHECK:\n results = []\n\n query_results = module.glance.GlanceLib().query(tag)\n if query_results['status'] == 'success':\n if 'data' in query_results:\n results = query_results\n else:\n results = {}\n\n session['query'] = tag\n\n\n return render_template(f'{TEMPLATES}glance_query.html', results=results)\n\n else:\n return render_template(PLUGIN_DISABLED_TEMPLATE)\n\n\n\n@_glance.route(\"/\")\n@login_required\ndef glance():\n if PLUGIN_CHECK:\n collections = module.glance.GlanceLib().get_items_by_amount(item_type='collection', amount=10)\n items = module.glance.GlanceLib().get_items_by_amount(item_type='geometry', amount=10)\n tags = module.glance.GlanceLib().get_tags_by_amount(amount=100)\n\n if 'status' in tags and tags['status'] == 'success':\n tags = tags['data']\n else:\n tags = []\n\n module.query.PortalSession(session).reset_query()\n\n return render_template(f'{TEMPLATES}glance.html', collections=collections, items=items, tags=tags)\n\n else:\n return render_template(PLUGIN_DISABLED_TEMPLATE)\n\n\n\n@_glance.route(\"/item//append\", methods=['GET', 'POST'])\n@login_required\ndef glance_item_append(id):\n if PLUGIN_CHECK:\n form = request.form\n raw_user_tags = form['user_tags']\n\n module.glance.GlanceLib().append_tags(id, raw_user_tags)\n\n return redirect(request.referrer)\n\n else:\n return render_template(PLUGIN_DISABLED_TEMPLATE)\n\n\n\n@_glance.route(\"/item/\")\n@login_required\ndef glance_item(id):\n if PLUGIN_CHECK:\n item = module.glance.GlanceLib().get_item(id)\n\n if 'status' in item and item['status'] == 'success':\n item_type = item['data'][0]['item_type']\n\n if item_type == 'image':\n return render_template(f'{TEMPLATES}glance_type_image.html', item=item)\n if item_type == 'collection':\n return render_template(f'{TEMPLATES}glance_type_collection.html', item=item)\n if item_type == 'geometry':\n return render_template(f'{TEMPLATES}glance_type_geometry.html', item=item)\n if item_type == 'people':\n return render_template(f'{TEMPLATES}glance_type_people.html', item=item)\n if item_type == 'footage':\n return render_template(f'{TEMPLATES}glance_type_footage.html', item=item)\n\n\n return render_template(f'{TEMPLATES}glance_item.html', item=item)\n\n else:\n return render_template(PLUGIN_DISABLED_TEMPLATE)\n","sub_path":"portal/view/glance.py","file_name":"glance.py","file_ext":"py","file_size_in_byte":9415,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"55301427","text":"import pygame, os, sys\nfrom pygame.locals import *\nfrom statemanager import *\nfrom bitmapfont import *\n\n\nclass MainMenuState(GameState):\n def __init__(self, game):\n super().__init__(game)\n self.playGameState = None\n self.font = BitmapFont('fasttracker2-style_12x12.png', 12, 12)\n self.index = 0\n self.inputTick = 0\n self.menuItems = ['Play', 'Quit']\n self.background = pygame.image.load(\"menu_wallpaper.jpg\").convert()\n pygame.mixer.music.load(\"bg_music.mp3\")\n pygame.mixer.music.play()\n\n def setPlayState(self, state):\n self.playGameState = state\n\n def update(self, gameTime):\n print(\"Menu Updating\")\n keys = pygame.key.get_pressed()\n if (keys[K_UP] or keys[K_DOWN]) and self.inputTick == 0:\n '''\n The user presses the up and down button to select a menu item.\n To prevent the menu selection from spinning out of control,\n the updates are clamped to four per second (250 milliseconds).\n '''\n self.inputTick = 250\n if keys[K_UP]:\n self.index -= 1\n if self.index < 0:\n self.index = len(self.menuItems) - 1\n elif keys[K_DOWN]:\n self.index += 1\n if self.index == len(self.menuItems):\n self.index = 0\n\n elif self.inputTick > 0:\n self.inputTick -= gameTime\n if self.inputTick < 0:\n self.inputTick = 0\n\n if keys[K_SPACE]:\n if self.index == 1:\n self.game.changeState(None) # exit the game\n elif self.index == 0:\n self.game.changeState(self.playGameState)\n\n def draw(self, surface):\n surface.blit(self.background, (0,0))\n self.font.centre(surface, \"team#263:whack&roll - POKERBRICKS\", 48)\n\n count = 0\n y = surface.get_rect().height - len(self.menuItems) * 100\n for item in self.menuItems:\n itemText = \" \"\n if count == self.index:\n itemText = \"> \"\n\n itemText += item\n self.font.draw(surface, itemText, 25, y)\n y += 24\n count += 1\n","sub_path":"menu.py","file_name":"menu.py","file_ext":"py","file_size_in_byte":2223,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"492440904","text":"import random\n\ndef pickWord(words):\n\t\n\ttoReturn = random.choice(lol)\n\treturn toReturn\n\nwith open(\"scrabble.txt\", \"r\") as paroleFile:\n\tlol = paroleFile.read().split(\"\\n\")\nprint(\"La parola del 'giorno' è\", pickWord(lol))","sub_path":"Python/30.py","file_name":"30.py","file_ext":"py","file_size_in_byte":219,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"402430163","text":"from __future__ import division, print_function\n\nimport sys\nimport os\nimport numpy as np\nos.environ['GLOG_minloglevel'] = \"4\"\nimport caffe\nimport util\n\n\nclass CNN :\n def __init__(self, opts = None):\n '''\n options:\n cnn_net_file : str, path to cnn.prototxt\n cnn_model_file : str, path to cnn.caffemodel\n cnn_feature_blob : str, feature blob name of cnn model\n cnn_input_means : [[[blue,green,red]]] bias value of input channels\n gpu_id\n\n '''\n caffe.set_device(opts['gpu_id'])\n caffe.set_mode_gpu()\n\n self.net = caffe.Net(opts['cnn_net_file'], opts['cnn_model_file'], caffe.TEST)\n self.input_shape = self.net.blobs['data'].data.shape[2:4]\n self.feature_blob_name = opts['cnn_feature_blob']\n if 'cnn_input_means' in opts:\n self.input_means = opts['cnn_input_means']\n else:\n self.input_means = [[[104, 117, 123]]]\n self.opts = opts\n print('load CNN model from %s' % opts['cnn_net_file'])\n\n def reshape_cnn(self, new_batch_size = None):\n previous_batch_size = self.net.blobs['data'].num\n if new_batch_size and new_batch_size != previous_batch_size:\n input_shape = list(self.net.blobs['data'].shape)\n input_shape[0] = new_batch_size\n self.net.blobs['data'].reshape(*input_shape)\n\n return previous_batch_size\n\n def extract_descriptor(self, image, region_bbox):\n # region_bbox = (x1, y1, x2, y2)\n net = self.net\n assert(net != None)\n # print('||||||||||||| image shape: %s', str(image.shape))\n # print('||||||||||||| image shape: %s', str(self.input_shape))\n im = util.image.resize(image, self.input_shape) - self.input_means\n im = np.transpose(im, axes = (2,0,1))[np.newaxis,:]\n net.forward(data = im)\n image_feature = net.blobs[self.feature_blob_name].data.copy()\n \n\n region = util.image.resize(util.image.crop(image, region_bbox), self.input_shape) - self.input_means\n region = np.transpose(region, axes = (2,0,1))[np.newaxis,:]\n net.forward(data = region)\n region_feature = net.blobs[self.feature_blob_name].data.copy()\n\n h, w = image.shape[0:2]\n x1, y1, x2, y2 = region_bbox\n s_r = (x2 - x1) * (y2 - y1)\n location_feature = np.array([x1/w, y1/h, x2/w, y2/h, s_r/h/w], dtype = np.float32)\n\n descriptor = {'image_feature': image_feature,\\\n 'region_feature': region_feature,\\\n 'location_feature': location_feature}\n return descriptor\n\n def forward_batch(self, image_at, batch_size, rng):\n '''\n image_at: image acceccor, image_at(i) returns the i-th image\n '''\n net = self.net\n output_blob = net.blobs[self.feature_blob_name]\n feature_shape = [output_blob.count / output_blob.num]\n _, c, h, w = net.blobs['data'].shape\n previous_batch_size = self.reshape_cnn()\n\n num_image = rng[1] - rng[0]\n # print('num_image: %d, rng: %s'%(num_image, str(rng)))\n output = np.zeros([num_image] + feature_shape, dtype = np.float32)\n\n # for i in xrange(rng[0], rng[1], batch_size):\n for i in xrange(0, num_image, batch_size):\n begin = i + rng[0]\n n_batch = min(batch_size, num_image - i)\n image_data = np.zeros((n_batch, h, w, c), dtype = np.float32)\n for j in xrange(n_batch):\n image = image_at(begin+j)\n image_data[j,:,:,:] = util.image.resize(image, (w,h)) - self.input_means\n image_data = np.transpose(image_data, axes = (0,3,1,2))\n self.reshape_cnn(n_batch)\n net.forward(data = image_data) \n\n output[i:(i+n_batch), :] = output_blob.data.copy().reshape([n_batch] + feature_shape)\n print('GPU-%d: %d/%d' % (self.opts['gpu_id'], i,num_image))\n self.reshape_cnn(previous_batch_size)\n return output\n\ndef extract_feautre_unit(idx, output_list, gpu_id, image_at, rng):\n # batch_size = 30\n opts = {'cnn_net_file': 'modules/question_generator/model/inception_resnet_cnn_deploy.prototxt',\\\n 'cnn_model_file': 'modules/question_generator/model/inception_resnet.caffemodel',\\\n 'cnn_feature_blob': 'global_pool',\\\n 'gpu_id': gpu_id}\n cnn_net = CNN(opts)\n output = cnn_net.forward_batch(image_at = image_at, rng = rng, batch_size = 30)\n output_list[idx] = output\n\ndef extract_feature_multi_gpu(image_at, rng, gpu_id_list):\n from multiprocessing import Process, Manager\n\n num_gpu = len(gpu_id_list)\n manager = Manager()\n output_list = manager.list(range(num_gpu))\n block_size = (rng[1] - rng[0]) // num_gpu + 1\n p_list = []\n for idx, gpu_id in enumerate(gpu_id_list):\n p = Process(target = extract_feautre_unit,\\\n args = (idx, output_list, gpu_id, image_at, \\\n [rng[0] + idx*block_size, min(rng[1],rng[0] + (idx+1) * block_size)]))\n p.start()\n p_list.append(p)\n\n for p in p_list:\n p.join()\n\n return np.vstack(output_list)\n\ndef test_cnn():\n image = util.image.imread('demo.jpg')\n bbox = [0,0,100,100]\n def _image_at(x):\n return image\n\n # test CNN.extract_descriptor()\n\n # opts = {'cnn_net_file': 'modules/question_generator/model/inception_resnet_cnn_deploy.prototxt',\\\n # 'cnn_model_file': 'modules/question_generator/model/inception_resnet.caffemodel',\\\n # 'cnn_feature_blob': 'global_pool',\\\n # 'gpu_id': 2}\n # cnn_net = CNN(opts)\n # descriptor = cnn_net.extract_descriptor(image, bbox)\n # print(descriptor['location_feature'])\n # print(descriptor['image_feature'][0:10])\n\n # test CNN.batch_forward()\n\n # feature = cnn_net.forward_batch(_image_at, 10, batch_size = 30)\n # print(feature.shape)\n # print(np.all(feature != np.nan))\n # print(feature[0][0:10])\n\n\n # test extract_feature_multi_gpu()\n feature = extract_feature_multi_gpu(image_at = _image_at, rng = [0,10], gpu_id_list = [1])\n print(np.all(feature != np.nan))\n print(feature.shape)\n print(feature)\n\n\nif __name__ == '__main__':\n test_cnn()\n\n\n\n","sub_path":"modules/question_generator/cnn.py","file_name":"cnn.py","file_ext":"py","file_size_in_byte":6251,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"407574319","text":"# uncompyle6 version 3.7.4\n# Python bytecode 3.6 (3379)\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.win-amd64\\egg\\phantom\\faces\\faces.py\n# Compiled at: 2020-01-06 18:37:58\n# Size of source mod 2**32: 14283 bytes\n\"\"\"\nWraps dlib's face detectors and face encoder.\n\nSupport for other detectors could be added in the future.\n\nImportant links:\n\nhttp://blog.dlib.net/2017/02/high-quality-face-recognition-with-deep.html\nhttp://dlib.net/face_detector.py.html\nhttp://dlib.net/face_landmark_detection.py.html\nhttp://dlib.net/face_recognition.py.html\nhttps://github.com/davisking/dlib\nhttps://github.com/davisking/dlib-models\n\"\"\"\nimport cv2, dlib, numpy as np, pickle\nfrom pkg_resources import resource_filename\nfrom sklearn.cluster import DBSCAN, KMeans\n\nclass _LazyStore:\n\n def __init__(self, d=None, r=None):\n if d is None:\n d = {}\n if r is None:\n r = {}\n self.dict = d\n self.reg = r\n\n def register(self, key, initer, *args, **kwargs):\n self.reg[key] = (\n initer, args, kwargs)\n\n def get(self, key):\n try:\n return self.dict[key]\n except KeyError:\n pass\n\n try:\n func, args, kwargs = self.reg[key]\n store = func(*args, **kwargs)\n except KeyError:\n raise KeyError('unregistered lazy key.')\n\n self.dict[key] = store\n return store\n\n\ndef _unpickle(path):\n \"\"\"\n A simple wrapper to keep the loading of pickled models sane, and in line\n with the code style.\n \"\"\"\n with open(path, 'rb') as (filehandle):\n obj = pickle.load(filehandle)\n return obj\n\n\n_path_encoder = resource_filename('phantom', 'models/dlib_face_recognition_resnet_model_v1.dat')\nif dlib.__version__.startswith('19.8'):\n _path_gender = resource_filename('phantom', 'models/phantom_gender_model_v1_dlib_19.8.dat')\nelse:\n _path_gender = resource_filename('phantom', 'models/phantom_gender_model_v1.dat')\n _path_gender_1b = resource_filename('phantom', 'models/phantom_gender_model_v1c.dat')\n_path_age_model = resource_filename('phantom', 'models/phantom_age_model_v1.dat')\n_path_shape_5p = resource_filename('phantom', 'models/shape_predictor_5_face_landmarks.dat')\nlazy_vars = _LazyStore()\nlazy_vars.register('face_detector', dlib.get_frontal_face_detector)\nlazy_vars.register('face_encoder', dlib.face_recognition_model_v1, _path_encoder)\nlazy_vars.register('age_model', _unpickle, _path_age_model)\nlazy_vars.register('gender_model', _unpickle, _path_gender)\nlazy_vars.register('gender_model_1b', _unpickle, _path_gender_1b)\nlazy_vars.register('shape_predictor_5p', dlib.shape_predictor, _path_shape_5p)\n\nclass Shape:\n __doc__ = '\\n Represents the shape of a face, as returned from a facial landmark detector.\\n\\n :param points: ordered list of points, according to a landmark definition.\\n '\n\n def __init__(self, points):\n self.points = points\n self.dict = {}\n self._make_dict()\n self.model = None\n\n def _make_dict(self):\n \"\"\"\n Each subclass has to define this method to populate `self.dict`.\n \"\"\"\n pass\n\n def _draw_lines(self, img, color, thick):\n \"\"\"\n Subclasses must define the logic for drawing this shape over an image,\n using lines.\n \"\"\"\n pass\n\n def _draw_points(self, img, color, thick):\n \"\"\"\n Subclasses can define the logic for drawing this shape over an image,\n using points, however a base implementation is provided.\n \"\"\"\n for point in self.points:\n cv2.circle(img, point, thick, color, thickness=thick)\n\n def _draw_numbers(self, img, color, thick):\n \"\"\"\n Subclasses must define the logic for drawing this shape over an image,\n using numbers.\n \"\"\"\n pass\n\n\nclass Shape5p(Shape):\n __doc__ = '\\n 5-point facial landmarks Shape object.\\n '\n\n def __init__(self, points):\n super().__init__(points)\n self.model = lazy_vars.get('shape_predictor_5p')\n\n def _make_dict(self):\n p = self.points\n self.dict = {'eye_left':p[0:2], \n 'eye_right':p[2:4], \n 'nose':[\n p[4]]}\n\n def _draw_lines(self, img, color, thick):\n d = self.dict\n points = d['eye_left'] + d['nose'] + d['eye_right'][::-1]\n pairs = list(zip(points[:-1], points[1:]))\n for point1, point2 in pairs:\n cv2.line(img, point1, point2, color, thickness=thick)\n\n\nclass Shape68p(Shape):\n __doc__ = '\\n 68-point facial landmarks Shape object.\\n '\n\n def __init__(self, points):\n super().__init__(points)\n self.model = lazy_vars.get('shape_predictor_5p')\n\n def _make_dict(self):\n p = self.points\n self.dict = {'jawline':p[0:17], \n 'eyebrow_right':p[17:22], \n 'eyebrow_left':p[22:27], \n 'nose_bridge':p[27:31], \n 'nose_tip':p[31:36], \n 'eye_right':p[36:42], \n 'eye_left':p[42:48], \n 'lips_top':p[48:55] + p[64:59:-1], \n 'lips_bottom':p[54:60] + [p[48], p[60]] + p[67:63:-1]}\n\n def _draw_lines(self, img, color, thick):\n shape = self.dict\n color_ = color\n for key in shape:\n pairs = zip(shape[key][:-1], shape[key][1:])\n if key == 'right_eye':\n color_ = (0, 0, 255)\n else:\n color_ = color\n for point1, point2 in pairs:\n cv2.line(img, point1, point2, color_, thickness=thick)\n\n\nShape68p = Shape5p\n\nclass Face:\n __doc__ = '\\n This is a convenience class that helps to gather, in a single place, the\\n encoding, landmarks, image, and origin of a face.\\n\\n In time we may use this class to transparently replace some conventions of\\n phantom.\\n\\n :param landmark: a Shape object, that describes the landmarks of the face\\n :param encoding: a 128-d vector encoding for a face\\n :param image: an np.ndarray/cv2 image\\n :param origin: path to a file\\n :param landmarks: Shape object for the face\\n :param location: location of a face within origin\\n '\n\n def __init__(self, encoding=None, image=None, origin=None, landmark=None, location=None):\n self.encoding = encoding\n self.image = image\n self.origin = origin\n self.landmark = landmark\n self.location = location\n self.tags = {}\n\n\nclass Atlas:\n __doc__ = '\\n A large grouping of facial encodings.\\n\\n :param encodings: list of Face objects, which at least have an encoding\\n :param path: the path to which the atlas will persist on disk\\n '\n\n def __init__(self, elements, path):\n self.elements = elements\n self.clusters = {}\n self.groups = None\n self.grouped = False\n self.path = path\n self._dbscan = DBSCAN(eps=0.475, min_samples=2)\n self._kmeans = None\n\n def group(self):\n \"\"\"\n Used clustering algorithms to group all the faces of the Atlas into\n distinct groups. These can later be used to match new faces, or compare\n to other Atlases.\n \"\"\"\n pass\n\n def load(self):\n \"\"\"\n Loads an Atlas from disk, read from `self.path`.\n \"\"\"\n with open(self.path, 'rb') as (fhandle):\n new_dict = pickle.load(fhandle)\n self.__dict__.clear()\n self.__dict__.update(new_dict)\n\n def save(self):\n \"\"\"\n Persists the Atlas on disk, written to `self.path`.\n \"\"\"\n with open(self.path, 'wb') as (fhandle):\n pickle.dump(self.__dict__, fhandle)\n\n\ndef _rect_to_tuple(r):\n \"\"\"\n Helper function.\n\n Transforms a `dlib.rectangle` object into a tuple of (left, top, right,\n bottom) ints(longs).\n\n :param r: `dlib.rectangle` object\n :return: tuple of ints\n \"\"\"\n return (\n r.left(), r.top(), r.right(), r.bottom())\n\n\ndef _tuple_to_rect(t):\n \"\"\"\n Helper function.\n\n Transforms a tuple of (left, top, right, bottom) ints(longs) into a\n `dlib.rectangle` object.\n\n :param t: tuple of ints\n :return: `dlib.rectangle` object\n \"\"\"\n return (dlib.rectangle)(*t)\n\n\ndef detect(img, *, upsample=1):\n \"\"\"\n Detects faces present in an image.\n\n Wrapper of dlibs frontal face detector.\n\n :param img: numpy/cv2 image array\n :param upsample: int, number of times to upsample the image. Helps finding\n smaller faces\n :return: list of tuples (left, top, right, bottom) with each face location\n \"\"\"\n face_detector = lazy_vars.get('face_detector')\n return [_rect_to_tuple(r) for r in face_detector(img, upsample)]\n\n\ndef detect_cnn(img, *, upsample=1):\n \"\"\"\n Detects faces present in an image, using `cv2.dnn` module.\n \n Work in progress.\n :param upsample: (Note: for now it's just to be compatible with the `detect`\n signature, may not be necessary)\n :return: list of tuples (left, top, right, bottom) with each face location\n \"\"\"\n detections = []\n return detections\n\n\ndef landmark(img, *, locations=None, model=Shape68p, upsample=1):\n \"\"\"\n Detects the facial landmarks of each face present in an image.\n\n Wrapper of dlibs shape predictors.\n\n :param img: numpy/cv2 image array\n :param locations: list of tuples (left, top, right, bottom) with face \n locations\n :param model: `Shape` subclass that defines a landmarking model.\n :param upsample: number of upsamples to use when locating faces (only used\n if `locations` is None)\n :return: list of `phantom.faces.Shape` objects, each describing the position\n and landmarks of every face\n \"\"\"\n if locations is None:\n locations = detect(img, upsample=upsample)\n class_ = model\n shaper = model([(i, i) for i in range(68)])\n model = shaper.model\n shapelist = [model(img, _tuple_to_rect(loc)) for loc in locations]\n return [class_([(p.x, p.y) for p in face.parts()]) for face in shapelist]\n\n\ndef encode(img, *, locations=None, model=Shape68p, jitter=1):\n \"\"\"\n Detects and encodes all the faces in an image.\n\n Wrapper of dlibs resnet facial encoder.\n\n :param img: numpy/cv2 image array\n :param locations: list of tuples (left, top, right, bottom) with face \n locations\n :param model: shape predictor\n :param jitter: an integer number of times to scramble the image a bit, and\n re-run the encoding. Higher jitter makes for slightly better encodings,\n though it slows down the encoding.\n \"\"\"\n if locations is None:\n locations = detect(img)\n shaper = model([(i, i) for i in range(68)])\n model = shaper.model\n face_encoder = lazy_vars.get('face_encoder')\n shapelist = [model(img, _tuple_to_rect(loc)) for loc in locations]\n return [np.array(face_encoder.compute_face_descriptor(img, shape, jitter)) for shape in shapelist]\n\n\ndef compare(face1, face2):\n \"\"\"\n Compares two face encodings (from dlib/`phantom.faces.encodings`).\n\n A distance under 0.6 means the faces correspond to the same person. A\n distance slightly over 0.6 (+epsilon) means it could be the same person, for\n a low enough epsilon. Distances over 0.6 mean the faces are of different\n people.\n\n :param face1: dlibs 128-long face encoding\n :param face2: dlibs 128-long face encoding\n :return: float, distance between `face1` and `face2`\n \"\"\"\n return np.linalg.norm(face1 - face2)\n\n\ndef estimate_age(face):\n \"\"\"\n Estimates the age of a person based on a facial encoding.\n\n :param face: dlibs 128-long face encoding\n \"\"\"\n age_model = lazy_vars.get('age_model')\n face = face.reshape(1, -1)\n return age_model.predict(face)\n\n\ndef estimate_gender(face, *, multi=False):\n \"\"\"\n Estimates a characteristic based on the face that is passed.\n\n :param face: dlibs 128-long face encoding\n :return: float, estimated gender. The gender model has been trained as\n value 1 for females, and -1 for males. So, a value of -0.5 means \"mainly\n male\" and can be considered as such. Values between -0.3 and 0.3 mean\n the model is not certain enough, and should be considered as \"unknown\"\n or \"uncertain\"\n \"\"\"\n vector = dlib.vector(face)\n gender_model = lazy_vars.get('gender_model')\n if multi:\n gender_model2 = lazy_vars.get('gender_model_1b')\n return (\n gender_model(vector), gender_model2(vector))\n else:\n return gender_model(vector)","sub_path":"pycfiles/phantom-0.7.2-py3.6/faces.cpython-36.py","file_name":"faces.cpython-36.py","file_ext":"py","file_size_in_byte":12496,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"377279772","text":"#Text Messaging\n\n\"\"\"\nSimula scrittura col telefonino stile nokia 3310\n\"\"\"\n\ndictionary={\"A\":2,\"B\":22,\"C\":222,\"D\":3,\"E\":33,\"F\":333,\"G\":4,\"H\":44,\"I\":444,\"J\":5,\"K\":55,\"L\":555,\\\n \"M\":6,\"N\":66,\"O\":666,\"P\":7,\"Q\":77,\"R\":777,\"S\":7777,\"T\":8,\"U\":88,\"V\":888,\"W\":9,\"X\":99,\"Y\":999,\"Z\":9999,\\\n \" \":0,\".\":1,\",\":11,\"?\":111,\"!\":1111,\":\":11111}\n\nstring=input(\"Inserisci stringa da convertire in sequenza numerica per tastierino telefonico:\")\nstring=string.upper()\nnum_string=\"\"\nfor i in range(len(string)):\n for key in dictionary:\n if string[i]==key:\n num_string+=str(dictionary[key])\nprint(num_string)","sub_path":"cap6/ex_138.py","file_name":"ex_138.py","file_ext":"py","file_size_in_byte":626,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"622900203","text":"from hash_game import main, winner, valid_move, hash_board\nimport pytest\n\n\n@pytest.fixture( params=[\n {\"input\": [[1,1,1],[0,2,0],[0,0,2]], \"expectedResult\" : True},\n {\"input\": [[1,0,0],[1,0,2],[1,2,0]], \"expectedResult\" : True},\n {\"input\": [[1,2,0],[2,1,0],[0,0,1]], \"expectedResult\" : True},\n {\"input\": [[0,2,1],[0,1,2],[1,0,0]], \"expectedResult\" : True},\n {\"input\": [[1,2,2],[1,2,2],[2,1,0]], \"expectedResult\" : True},\n {\"input\": [[0,0,0],[0,0,0],[0,0,0]], \"expectedResult\" : False},\n {\"input\": [[0,1,0],[2,0,2],[0,1,0]], \"expectedResult\" : False},\n {\"input\": [[1,0,0],[0,2,0],[0,0,1]], \"expectedResult\" : False},\n {\"input\": [[1,2,1],[1,2,2],[2,1,1]], \"expectedResult\" : False},\n {\"input\": [[1,2,2],[2,1,1],[1,1,2]], \"expectedResult\" : False}])\n\ndef testCase(request):\n return request.param\n\ndef test_winner(testCase):\n result = winner(testCase[\"input\"])\n assert result == testCase[\"expectedResult\"]","sub_path":"test_hash_game.py","file_name":"test_hash_game.py","file_ext":"py","file_size_in_byte":940,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"580379007","text":"import time\nfrom greenlet import greenlet\nimport gevent\nfrom gevent import monkey\n\nmonkey.patch_all()\n\ndef work1():\n for i in range(10):\n print('work1')\n # gr2.switch()\n time.sleep(0.5)\n # g2.switch()\n\n # yield\n\n\ndef work2():\n for i in range(10):\n print('work2')\n # gr1.switch()\n time.sleep(0.5)\n # g1.switch()\n\n # yield\n\n\nif __name__ == '__main__':\n # for i in range(10):\n # next(work1())\n # next(work2())\n # gr1 = greenlet(work1)\n # gr2 = greenlet(work2)\n # gr1.switch()\n # g1 = gevent.spawn(work1)\n # g2 = gevent.spawn(work2)\n # g1.join()\n # g2.join()\n gevent.joinall([gevent.spawn(work1),\n gevent.spawn(work2)])\n","sub_path":"test/my_yield_greenlet_gevent.py","file_name":"my_yield_greenlet_gevent.py","file_ext":"py","file_size_in_byte":752,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"645270211","text":"\"\"\"\nThis could be used for the sem algorithm running\n\"\"\"\n\n\nimport ctypes\nfrom numpy import ctypeslib\n\nfrom sem_test import gen2\n\nimport os\nimport sys\n\n_d = os.path.dirname(os.path.realpath(__file__))\nif not (_d + '\\\\sem_test.py') in sys.path:\n sys.path.append(_d)\nif not (_d) in sys.path:\n sys.path.append(_d)\n\nfrom sem2 import sem\n\n\nteth_start = 2.0\ndata = gen2(0.5, 1.0, 2.0, 2.0, 1.0)\n\nniter = 100\nk = 2\nn = len(data)\n\nleb = ctypeslib.load_library(libname='SEM-extensions.dll', loader_path=_d)\n\nleb.sem.argtypes = [ctypes.c_int, ctypes.c_int, \n ctypeslib.ndpointer(dtype=data.dtype, ndim=1, flags='C_CONTIGUOUS'), \n ctypes.c_int]\n#leb.sem.restype = ctypeslib.ndpointer(dtype=data.dtype, ndim=1, flags='C_CONTIGUOUS')\nleb.sem.restype = ctypes.POINTER(ctypes.c_double)\nresult = leb.sem(niter, k, data, n)\nresult_ = ctypeslib.as_array(result, shape=((k * 2 + 2),))\n\nresultat = sem(niter=niter, k=k, data=data)","sub_path":"drone2.py","file_name":"drone2.py","file_ext":"py","file_size_in_byte":953,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"415492817","text":"class Validation:\n \"\"\"Contains methods for validating user input\n \"\"\"\n\n def validate_num_input(self, user_input, max_num) -> bool:\n \"\"\"Checks if the user input is a number between 1 and max_numd\n\n Args:\n user_input (str): input provided by the user\n max_num (int): maximum allowed number for the user input\n\n Raises:\n ValueError: Raises an error if the number is out of range.\n\n Returns:\n bool: False if an error was rised, True otherwise\n \"\"\"\n\n try:\n num = int(user_input)\n if num < 1 or num > max_num:\n raise ValueError(\n f'This should be a number between 1 and {max_num}!')\n except ValueError as e:\n print(f'Invalid data: {e}, please try again.\\n')\n return False\n return True\n\n def validate_str_input(self, user_input) -> bool:\n \"\"\"Checks if the user input is a valid string with a minimum length of 2\n characters\n\n Args:\n user_input (str): input provided by the user\n\n Returns:\n bool: False if the input is invalid, True otherwise\n \"\"\"\n if (not user_input.isalpha()) or len(user_input) < 2:\n print(\n 'Your input should be a single word of a minimum of 2'\n 'characters.'\n 'Please try again.')\n return False\n return True\n\n def validate_str_select(self, user_input, answer_set) -> bool:\n \"\"\"Checks if the user input is in a given answer set\n\n Args:\n user_input (str): input provided by the user\n answer_set (tuple): a set containing all the allowed answers\n\n Returns:\n bool: False if the user input is not in the given set, true\n otherwise\n \"\"\"\n if user_input not in answer_set:\n print('Invalid input. Please try again.')\n return False\n return True\n","sub_path":"validation.py","file_name":"validation.py","file_ext":"py","file_size_in_byte":1989,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"373326685","text":"# Given two string, write a method to decide if one string is a permutation of the other.\n\n\ndef arePermutatoin(str1, str2):\n len1 = len(str1)\n len2 = len(str2)\n\n if len1 != len2:\n return False\n\n # str1 = sorted(str1)\n # print(str1)\n a = sorted(str1)\n str1 = \"\".join(a)\n\n b = sorted(str2)\n str2 = \"\".join(b)\n\n for i in range(len1):\n if str1[i] != str2[i]:\n return False\n\n return True\n\n\nstr1 = \"test\"\nstr2 = \"ttes\"\nans = arePermutatoin(str1, str2)\nif ans:\n print(\"Are Permutation\")\nelse:\n print(\"Not permutation\")","sub_path":"checkPermutation.py","file_name":"checkPermutation.py","file_ext":"py","file_size_in_byte":575,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"371817800","text":"'''\r\nMergesort Using Process Spawning and Queue Objects\r\nEach child process produces a single integer response, and the parent process\r\ncombines the repsonses of the children. Here, each child process produces a list\r\nand the parent process merges the produced lists into a larger list.\r\n#1 Sequential Mergesort Code\r\n'''\r\ndef merge(left, right):\r\n ret=[]\r\n li = ri = 0\r\n while li < len(left) and ri < len(right):\r\n if left[li] <= right[ri]:\r\n ret.append(left[li])\r\n li += 1\r\n else:\r\n ret.append(right[ri])\r\n ri += 1\r\n if li == len(left):\r\n ret.extend(right[ri:])\r\n else:\r\n ret.extend(left[li:])\r\n return ret\r\n\r\ndef mergesort(lyst):\r\n if len(lyst) <= 1:\r\n return lyst\r\n ind = len(lyst) // 2\r\n return merge(mergesort(lyst[:ind]), mergesort(lyst[ind:]))\r\n\r\nif __name__ == '__main__':\r\n a = [9,8,7,6,5,4,3,2,1]\r\n print(mergesort(a))\r\n","sub_path":"12.py","file_name":"12.py","file_ext":"py","file_size_in_byte":943,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"576342176","text":"import numpy as np\nimport matplotlib.pyplot as plt\n\nnoise_var = 0.001 # noise variance\nh = 0.005 # step size\nx = np.arange(0, 2 * np.pi, h).reshape(-1, 1)\n\n\ndef y(x):\n return np.sin(x) + np.sin(x) ** 2\n\n\ndef kernel(a, b):\n d = np.sum(a ** 2, 1).reshape(-1, 1) + np.sum(b ** 2, 1) - 2 * np.dot(a, b.T)\n return np.exp(-.5 * d)\n\n\n# similarity of test data to each other\nk_x = kernel(x, x)\n\nx_train = np.array([]) # training values x\nvar = np.array([]) # variance\n\nfor i in range(1, 17):\n # Sample the y-value at the location of biggest uncertainty\n if len(var) != 0:\n a = h * np.argwhere(var == np.amax(var)).flatten()\n sample = np.random.choice(a)\n else:\n sample = np.array(np.random.uniform(0, 2 * np.pi)).reshape(-1, 1)\n\n x_train = np.append(x_train, sample).reshape(-1, 1)\n y_train = y(x_train)\n\n # Apply the kernel function to our training points\n K = kernel(x_train, x_train)\n L = np.linalg.cholesky(K + noise_var * np.eye(len(x_train)))\n\n # Compute the mean at the test points.\n similarity_train = kernel(x_train, x)\n Lk = np.linalg.solve(L, similarity_train)\n mu = np.dot(Lk.T, np.linalg.solve(L, y_train)).reshape((len(x),))\n\n # Compute the standard deviation (for the plots)\n var = np.diag(k_x) - np.sum(Lk ** 2, axis=0)\n stdv = np.sqrt(var)\n\n if i in [1, 2, 4, 8, 16]:\n plt.plot(x_train, y_train, 'bo', ms=5, label=\"Training Data\")\n plt.plot(x, y(x), label=\"Ground Truth\")\n plt.gca().fill_between(x.flat, mu - 2 * stdv, mu + 2 * stdv, color=\"#dddddd\")\n plt.plot(x, mu, label=\"Mean\")\n plt.axis([0, 2 * np.pi, -3, 3])\n plt.title('GP at Iteration ' + str(i))\n plt.legend()\n plt.show()","sub_path":"homework4/gp_reg.py","file_name":"gp_reg.py","file_ext":"py","file_size_in_byte":1727,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"298653537","text":"import urllib\n\n\nh=\"hello\"\nw=\"world\"\nprint(h+' '+w)\n\nDEBUG_MODE=false\n\nmassive = (1,2,3,4)\nprint(massive[2])\nurl = 'https://youtube.com'\nresponse = urllib.urlopen(url)\nprint (response.getcode)\nprint (response.headers)\n","sub_path":"common/scripts/DebugHelper.py","file_name":"DebugHelper.py","file_ext":"py","file_size_in_byte":217,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"301720662","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sat Aug 4 16:30:05 2018\n\n@author: Aquib\n\"\"\"\n\nclass Emp:\n def __init__(self):\n self.name='A'\n print(\"Constructor :\",self.name)\n \n \n def m1(self):\n self.sal=1000\n print(self.sal)\n print(\"Methos :\",self.name)\n \ne1=Emp()\ne1.m1()\nhelp(Emp)","sub_path":"Method/instanceMethod.py","file_name":"instanceMethod.py","file_ext":"py","file_size_in_byte":338,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"314237551","text":"import tensorflow as tf\nfrom tensorflow import keras\nfrom tensorflow.keras import layers\nimport os\nimport matplotlib.pyplot as plt\nfrom pathlib import Path\n\n\ndef build_model(num_classes):\n \"\"\"\n build_model\n - build model from keras application --> efficientNetB0\n - freeze all layers, replace Dense layer (output classification layer)\n - compile\n\n :param NUM_CLASSES: number of classes to be trained\n\n :return model: model_new, keras model variable\n \"\"\"\n model = keras.applications.EfficientNetB0(\n include_top=False,\n weights=\"imagenet\",\n input_shape=(224, 224, 3),\n pooling=\"avg\"\n )\n\n model.trainable = False\n\n # custom modifications on top of pre-trained model and fit\n model_new = tf.keras.models.Sequential()\n model_new.add(model)\n model_new.add(tf.keras.layers.Flatten())\n model_new.add(tf.keras.layers.Dense(512, activation='relu'))\n model_new.add(tf.keras.layers.Dense(256, activation='relu'))\n model_new.add(tf.keras.layers.Dense(128, activation='relu'))\n model_new.add(tf.keras.layers.Dense(num_classes, activation='softmax'))\n\n model_new.compile(\n optimizer='adam',\n loss=keras.losses.SparseCategoricalCrossentropy(),\n metrics=[\"accuracy\"]\n )\n\n return model_new\n\n\nif __name__ == \"__main__\":\n pass\n","sub_path":"src/NN_Classification_efficient/core/nn_model.py","file_name":"nn_model.py","file_ext":"py","file_size_in_byte":1326,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"273942848","text":"import praw\n\nwith open('config.txt') as f:\n lines = f.readlines()\n\n# for i in range(len(lines)):\n# lines[i].rstrip('\\n')\n\nreddit = praw.Reddit(client_id = lines[0].rstrip(),\n client_secret = lines[1].rstrip(),\n username = lines[2].rstrip(),\n password = lines[3].rstrip(),\n user_agent = lines[4].rstrip())\n\nsubredditName = 'hiphopheads'\nsubreddit = reddit.subreddit(subredditName)\n\nhots = subreddit.hot(limit = 1)\n\n\ndef depthFirstIteration (level, comment):\n print (4 * level * ' ', comment.body)\n comment.replies.replace_more(limit=None)\n for reply in comment.replies:\n depthFirstIteration (level + 1, reply)\n return\n\n\nfor submission in hots:\n # if not submission.stickied:\n print(submission.title, submission.num_comments)\n submission.comments.replace_more(limit=None)\n # comments.replace_more(limit = 0)\n for topLevelComment in submission.comments:\n depthFirstIteration(0, topLevelComment)\n","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":1040,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"145311181","text":"#!/usr/bin/python\n# -*- coding: UTF-8 -*-\n\nimport numpy as np\nimport copy\n\n\ndef MaxMinNorm(data, label):\n if label == 'CT':\n data[data < -1000] = -1000\n data[data > 2000] = 2000\n data_max = np.amax(data)\n data_min = np.amin(data)\n print(\"Before:\", data_max, data_min)\n data_norm = copy.deepcopy(data)\n data_norm -= data_min\n data_norm /= (data_max-data_min)\n print(\"After:\", np.amax(data_norm), np.amin(data_norm))\n return data_norm","sub_path":"Unet/process/normalization.py","file_name":"normalization.py","file_ext":"py","file_size_in_byte":473,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"542258648","text":"\"\"\"Создайте словарь с ключами-строками и значениями-числами.\nСоздайте функцию, которая принимает произвольное количество именованных параметров.\nВызовите её с созданным словарём и явно указывая параметры.\"\"\"\n\ndictionary = {'one': 1, 'two': 2, 'three': 3, 'four': 4, 'five': 5,\n 'six': 6, 'seven': 7, 'eight': 8, 'nine': 9, 'zero': 0}\n\n\ndef my_function(*args):\n return args\n\n\nfor i in my_function('eight'):\n print(dictionary[i], end=' ')\nprint()\n\nfor i in my_function('one', 'two', 'five', 'nine'):\n print(dictionary[i], end=' ')\nprint()\n\n\n# * # * # * # * # * # * # * # * # * # * # * # * # * # * # * # * # * # * # * # * # * # * # * # * # * # * # * # * # * #\n\n\ndef my_function_1(first, *args):\n if len(args) == 0:\n result = [first]\n else:\n result = list(args)\n result.insert(0, first)\n return tuple(result)\n\n\nfor i in my_function_1('eight'):\n print(dictionary[i], end=' ')\nprint()\n\nfor i in my_function_1('one', 'two', 'five', 'nine'):\n print(dictionary[i], end=' ')\nprint()\nprint(tuple('1'))\n","sub_path":"ITVDN/PythonEssentialLesson6/Task.py","file_name":"Task.py","file_ext":"py","file_size_in_byte":1222,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"437031421","text":"class RouteTrieNode:\n def __init__(self):\n self.children = {}\n self.handler = None\n\n\nclass RouteTrie:\n def __init__(self):\n self.root = RouteTrieNode()\n self.handler = None\n\n def insert(self, path, handler):\n curr_node = self.root\n for part in path:\n if part not in curr_node.children:\n curr_node.children[part] = RouteTrieNode()\n curr_node = curr_node.children[part]\n curr_node.handler = handler\n\n def lookup(self, path_parts):\n curr_node = self.root\n for part in path_parts:\n if part not in curr_node.children:\n return None\n else:\n curr_node = curr_node.children[part]\n return curr_node.handler\n\n\nclass Router:\n def __init__(self, root, handler):\n self.routes = RouteTrie()\n self.not_found = handler\n self.root_handler = root\n\n def add_handler(self, path, handler):\n path_parts = self.split_path(path)\n self.routes.insert(path_parts, handler)\n\n def lookup(self, path):\n if path == '/':\n return self.root_handler\n path_parts = self.split_path(path)\n handler = self.routes.lookup(path_parts)\n if handler is None:\n return self.not_found\n else:\n return handler\n\n def split_path(self, path):\n if path[-1:] == '/':\n path = path[:-1]\n path_parts_list = path.split('/')\n return path_parts_list\n\n\n# testing\n\ndef test_function(test_cases):\n for test in test_cases:\n if test[1] == test[2]:\n print(\"Test case \" + test[0] + \": Pass!\")\n else:\n print(\"Test case \" + test[0] + \": FAIL.\")\n\n\n# create the router and add routes\n\nrouter = Router(\"root handler\", \"not found handler\")\nrouter.add_handler(\"/home/about\", \"about handler\")\nrouter.add_handler(\"/home/shows/\", \"shows handler\")\nrouter.add_handler(\"/home/shows/archived_shows\", \"archived shows handler\")\nrouter.add_handler(\"/side_projects/films/\", \"films handler\")\nrouter.add_handler(\"/side_projects/films/short_films\", \"short films handler\")\n\n# root handler\ntc_1 = ('1', router.lookup(\"/\"), 'root handler')\n# basic lookup\ntc_2 = ('2', router.lookup(\"/home/about\"), 'about handler')\n# lookup with trailing '/' when added without one\ntc_3 = ('3', router.lookup(\"/home/about/\"), 'about handler')\n# lookup with no trailing '/' when added with one\ntc_4 = ('4', router.lookup(\"/home/shows\"), 'shows handler')\n# path with children with handlers that has no handler itself\ntc_5 = ('5', router.lookup(\"/home\"), 'not found handler')\n# non-existant path\ntc_6 = ('6', router.lookup(\"/home/about/me\"), 'not found handler')\n# path not under /home\ntc_7 = ('7', router.lookup(\"/side_projects/films\"), \"films handler\")\n\ntest_cases = [tc_1, tc_2, tc_3, tc_4, tc_5, tc_6, tc_7]\ntest_function(test_cases)\n","sub_path":"basic_algorithms_project/Problem_7.py","file_name":"Problem_7.py","file_ext":"py","file_size_in_byte":2882,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"146944659","text":"import numpy as np\n\n\nclass Stack():\n def __init__(self):\n # create stack\n self.values = []\n self.executed = False\n self.expressions = 0\n self.radians = True\n\n def get_stack(self, stack=None):\n # get stack as a string\n stackinput = \"\"\n if stack == None:\n stack = self.values\n for i in stack:\n stackinput += str(i[\"value\"])\n\n if stackinput == \"\":\n stackinput = \"0\"\n\n return stackinput\n\n def get_end_raw(self):\n # get end of the stack as a raw stack value\n entryinputstack = [\"\"]\n if self.values == []:\n entryinput = {\"value\": \"0\", \"type\": \"number\"}\n\n else:\n for i in self.values:\n if i[\"type\"] == \"number\" or i[\"type\"] == \"point\":\n entryinputstack[-1] += str(i[\"value\"])\n else:\n entryinputstack.append(\"\")\n\n entryinput = {\"value\": entryinputstack[-1], \"type\": \"number\"}\n if entryinput[\"value\"] == \"\":\n entryinput = self.values[-1]\n\n return entryinput\n\n def get_end(self):\n # get value at end of the stack as a string\n value = self.get_end_raw()\n if value[\"type\"] != \"number\":\n vs = \"0\"\n else:\n vs = value[\"value\"]\n\n return vs\n\n def push(self, value):\n # push a value to the stack\n # determine value type and return dict\n value = {\n \"value\": value,\n \"type\": \"operation\"\n }\n\n # create type for values\n if value[\"value\"] in [\"0\", \"1\", \"2\", \"3\", \"4\", \"5\", \"6\", \"7\", \"8\", \"9\"]:\n # Number value\n value[\"value\"] = int(value[\"value\"])\n value[\"type\"] = \"number\"\n if self.executed:\n self.reset()\n\n elif value[\"value\"] == \".\":\n # Decimal point\n value[\"type\"] = \"point\"\n if self.executed:\n self.reset()\n\n elif value[\"value\"] == \"+/-\":\n if (self.values[-1][\"type\"] == \"number\"):\n self.values[-1][\"value\"] *= -1\n value[\"type\"] = \"clear\"\n\n elif value[\"value\"] == \"CLEAR\":\n # Clear all\n self.reset()\n value[\"type\"] = \"clear\"\n\n elif value[\"value\"] == \"CE\":\n # Clear entry\n if len(self.values) > 0:\n if self.values[-1][\"type\"] == \"operation\":\n self.expressions -= 1\n self.values.pop()\n value[\"type\"] = \"clear\"\n\n elif value[\"value\"] == \"BKSP\":\n # Backspace\n if self.executed:\n self.reset()\n if len(self.values) > 0:\n if self.values[-1][\"type\"] != \"number\" or self.values[-1][\"value\"] < 10:\n self.values.pop()\n if len(self.values) > 0 and self.values[-1][\"type\"] == \"operation\":\n self.expressions -= 1\n else:\n self.values[-1][\"value\"] = int(\n np.floor(self.values[-1][\"value\"] / 10))\n value[\"type\"] = \"clear\"\n\n elif value[\"value\"] == \"=\":\n # Execute\n value[\"type\"] = \"execute\"\n self.executed = True\n\n if self.executed and value[\"type\"] != \"execute\":\n self.executed = False\n\n # add value to stack based on type\n if value[\"type\"] != \"clear\":\n if len(self.values) != 0:\n # do not allow multiple decimal points in single number\n if {\"value\": \".\", \"type\": \"point\"} in self.values[-3:] and value[\"type\"] == \"point\":\n pass\n # do not allow multiple simple operations next to each other\n elif self.values[-1] != \"operation\" or value[\"type\"] != \"operation\":\n # combine numbers into single stack entries\n if value[\"type\"] != \"number\" or self.values[-1][\"type\"] != \"number\":\n if value[\"type\"] == \"operation\":\n self.expressions += 1\n self.values.append(value)\n else:\n self.values[-1][\"value\"] = self.values[-1][\"value\"] * \\\n 10 + value[\"value\"]\n\n elif value[\"type\"] == \"number\" or value[\"type\"] == \"point\":\n if value[\"value\"] != 0:\n self.values.append(value)\n\n return value\n\n def calculate(self, stack=None):\n # execute all calculations currently on the stack\n evalstring = \"\"\n if stack == None:\n stack = self.values\n for i in stack:\n if i[\"type\"] != \"execute\":\n evalstring += str(i[\"value\"])\n else:\n break\n\n result = eval(evalstring)\n return {\"value\": result, \"type\": \"number\"}\n\n def reset(self):\n # reset stack\n self.values = []\n self.expressions = 0\n\n\nclass Memory():\n def __init__(self):\n self.history = []\n self.vars = {}\n\n def create_var(self, name, value):\n var = {name: value}\n self.vars = {**self.vars, **var}\n\n def get_var(self, name):\n return self.vars[name]\n\n def del_var(self, name):\n self.vars.pop(name)\n\n def clear_vars(self):\n self.vars = {}\n\n def push_stack(self, value, result):\n value.append(result)\n self.history.append(value)\n\n def get_stack(self, index):\n return self.history[index]\n\n def clear_history(self):\n self.history = []\n\n def clear_memory(self):\n self.clear_history()\n self.clear_vars()\n\n\nif __name__ == \"__main__\":\n print(\"You seem lost, friend.\\nPerhaps you should try running main.py instead?\")\n","sub_path":"stack.py","file_name":"stack.py","file_ext":"py","file_size_in_byte":5835,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"205249355","text":"# Minimum Replacements to Sort the Array\nfrom typing import List\n\n\ndef minimumReplacement(nums: List[int]) -> int:\n prev = nums[-1]\n result = 0\n\n for num in nums[:-1][::-1]:\n curr = (num + prev - 1) // prev\n result += curr - 1\n prev = num // curr\n \n return result\n\n\nif __name__ == \"__main__\":\n assert 2 == minimumReplacement([3, 9, 3])\n assert 0 == minimumReplacement([1, 2, 3, 4, 5])\n","sub_path":"2366_Minimum_Replacements_to_Sort_the_Array/default.py","file_name":"default.py","file_ext":"py","file_size_in_byte":427,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"8519671","text":"# Brittany Morris\n# Python 2.7 (SSF1910\n#I am Groot\n\nimport random\n\ndef randomator (L):\n random.shuffle(L)\n return random.choice(L)\n\ndef importer(T):\n with open (T, 'r') as f:\n return f.read().splitlines()\n\n# ---------------------------------\n\n# List Characters\ncharacters = [\n 'Alpha Allen',\n 'Bravo Brittany',\n 'Charlie Charlie',\n 'Delta Dave',\n 'Echo Eddie',\n 'Foxtrot Frank',\n 'Golf Greg',\n 'Hotel Henry',\n 'India Izzie',\n 'Juliett James'\n]\n\n# Lists of Attacks\nattacks = ['Fire', 'Earth', 'Water']\n\n# ---------------------------------\n\nplayer = randomator(characters)\nopponent = randomator(characters)\n\nwhile player == opponent:\n opponent = randomator(characters)\n\nprint (player + ' vs ' + opponent)\n\npscore = 0\noscore = 0\ngameover= False\n\nwhile gameover == False:\n\n # Game Toggle\n if pscore >= 3 or oscore >= 3:\n print ('Game Over!')\n print ('Final Score: ' + player + ': ' + str(pscore) + ' - ' + opponent + ': ' + str(oscore))\n gameover = True\n break\n\n # Game Score Update\n print ('Score: ' + player + ': ' + str(pscore) + ' - ' + opponent + ': ' + str(oscore))\n\n # Pick Attacks\n while True:\n try:\n pattack = int(raw_input(\"Enter [1] Fire, [2] Earth or [3] Water: \"))\n break\n except ValueError:\n print ('Please select 1, 2, or 3 ONLY')\n\n # User Attack Converter\n if pattack == 1:\n pattack = 'Fire'\n elif pattack == 2:\n pattack = 'Earth'\n elif pattack == 3:\n pattack = 'Water'\n elif pattack >= 4:\n print (\"You have chosen an invalid attack. A random attack has been chosen for you.\")\n pattack = randomator(attacks)\n\n oattack = randomator(attacks)\n\n while pattack == oattack:\n oattack = randomator(attacks)\n\n print (\" \")\n\n # --------------------------------\n\n # Displaying Attacks Chosen\n print (player + ' attacks with ' + pattack)\n print (opponent + ' attacks with ' + oattack)\n\n # --------------------------------\n\n # Battle Conditional: Fire > Earth > Water\n if pattack == \"Fire\" and oattack == \"Earth\":\n print (player + \" defeats \" + opponent)\n pscore += 1\n elif pattack == 'Earth' and oattack == 'Water':\n print (player + 'defeats' + opponent)\n pscore += 1\n elif pattack == 'Water' and oattack == 'Fire':\n print (player + \" defeats \" + opponent)\n pscore = + 1\n elif oattack == 'Fire' and pattack == 'Earth':\n print (opponent + ' defeats ' + player)\n oscore += 1\n elif oattack == 'Earth' and pattack == 'Water':\n print (opponent + ' defeats ' + player)\n oscore += 1\n elif oattack == 'Water' and pattack == 'Fire':\n print (opponent + ' defeats ' + player)\n oscore += 1","sub_path":"Notes_ErrorHandling.py","file_name":"Notes_ErrorHandling.py","file_ext":"py","file_size_in_byte":2805,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"233916627","text":"import pygame\nimport os\n\nclass Enemy:\n\n def __init__(self):\n self.width = 15\n self.height = 30\n self.imgs = []\n self.img = pygame.transform.scale(pygame.image.load(os.path.join(os.path.dirname(os.path.dirname(__file__)),\"asset/Enemy/\",\"Sinhvien0.png\")).convert_alpha(), (self.width, self.height))\n self.img_num = 0\n self.path = [(10, 224),(19, 224), (177, 235), (282, 283), (526, 277), (607, 217), (641, 105), (717, 57), (796, 83), (855, 222), (973, 284), (1046, 366), (1022, 458), (894, 492), (740, 504), (580, 542), (148, 541), (10, 442), (-20, 335), (-75, 305), (-100, 345)] #path to go through the map, position of center\n self.x = self.path[0][0] # first x and y of enemy\n self.y = self.path[0][1]\n self.max_health = 1\n self.current_health = 1\n\n\n def draw_images(self, win):\n \"\"\"Draw enemies' animations hihi.\n win: game surface.\"\"\"\n self.img = self.imgs[self.img_num]\n draw_pos = (self.x - self.img.get_width()/2, self.y - self.img.get_height()/2)\n win.blit(self.img, draw_pos)\n\n def draw_health_bar(self, win):\n \"\"\"Draw enemies' health bar hihi.\n win: game surface.\"\"\"\n\n\n\n\n","sub_path":"Enemy/enemy.py","file_name":"enemy.py","file_ext":"py","file_size_in_byte":1208,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"545195450","text":"import numpy as np\nimport sys\nimport tensorflow as tf\nfrom tensorflow.contrib import rnn\nimport math\nimport matplotlib.pyplot as plt\nfrom pylab import *\nimport time\n\ntrain_test_proportion=0.8\nlearning_rate=0.01\nBATCH_SIZE=100\nLOOK_BACK=10\nCHARACTER=1\nN_hidden=64\ntraining_idex=sys.argv[1]\ntraining_data='../processed_data/id_%s.npy'%training_idex\ndata=np.load(training_data)\ndata=data[:len(data)*8/10]\ntraining_itea=1000\ndisplay=50\nSAVE_STEP=5000\nSAVE_PATH='../model/model_%s/model_%s'%(training_idex,training_idex)\n\ndef create_dataset(data,look_back=LOOK_BACK,batch_size=BATCH_SIZE):\n\tidex=np.random.randint(0,len(data)-look_back,size=(100))\n\tdataX,dataY=[],[]\n\tfor i in range(len(idex)):\n\t\tdataX.append(data[idex[i]:idex[i]+look_back])\n\t\tdataY.append(data[idex[i]+look_back])\t\n\treturn np.array(dataX),np.array(dataY)\n\nx=tf.placeholder(tf.float32,[BATCH_SIZE,LOOK_BACK,CHARACTER])\ny=tf.placeholder(tf.float32,[BATCH_SIZE,CHARACTER])\n\ndef lstm_model(x,y,n_hidden=N_hidden,name='lstm_model',look_back=LOOK_BACK):\n\tx=tf.transpose(x,[1,0,2])\n\tx=tf.reshape(x,[-1,CHARACTER])\n\tx=tf.split(x,look_back,0)\n\tlstm_cell=rnn.BasicLSTMCell(n_hidden)\n\toutputs,states=rnn.static_rnn(lstm_cell,x,dtype=tf.float32)\n\toutput=outputs[-1]\n\treturn output\n\nfull_w1=tf.Variable(tf.truncated_normal([N_hidden,32]))\nfull_w2=tf.Variable(tf.truncated_normal([32,CHARACTER]))\nfull_b1=tf.Variable(tf.truncated_normal([32]))\nfull_b2=tf.Variable(tf.truncated_normal([CHARACTER]))\n\nlstm_out=lstm_model(x,y)\nfull_con1=tf.nn.relu(tf.matmul(lstm_out,full_w1)+full_b1)\npred=tf.matmul(full_con1,full_w2)+full_b2\n\n#cost=tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(labels=y,logits=pred))\ncost=tf.reduce_mean(abs(pred-y))\noptimizer=tf.train.GradientDescentOptimizer(learning_rate=learning_rate).minimize(cost)\ninit=tf.initialize_all_variables()\nsaver=tf.train.Saver()\nwith tf.Session() as sess:\n\tsess.run(init)\n\t#save_path=saver.restore(sess,SAVE_PATH)\n\tplot_array_label=[]\n\tplot_array_pred=[]\n\tI=[]\n\tfor i in xrange(training_itea):\n\t\tdataX,dataY=create_dataset(data)\n\t\t#print(dataX,dataY,len(dataY),i)\n\t\tloss,_,prediction=sess.run([cost,optimizer,pred],feed_dict={x:dataX,y:dataY})\n\t\t'''\n\t\tif i%1000==0:\n\t\t\tplt.plot(np.array(I),np.array(plot_array_label))\n\t\t\tplt.plot(np.array(I),np.array(plot_array_pred))\n\t\t\tplt.show()\n\t\t\t#time.sleep(1000)\n\t\t\tplot_array_label=[]\n\t\t\tplot_array_pred=[]\n\t\t\tI=[]\n\t\tI.append(i)\n\t\tplot_array_label.append(dataY[0])\n\t\tplot_array_pred.append(prediction[0])\n\t\t#print(plot_array_pred)\n\t\t#time.sleep(1000)\n\t\t'''\n\t\tif i%display==0:\n\t\t\tprint('itear :',i,'cost : ',loss,'label : ',dataY[0],'prediction :',prediction[0])\n\t\tif i%SAVE_STEP==0:\n\t\t\tsave_path=saver.save(sess,SAVE_PATH)\n\n\n","sub_path":"code/model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":2683,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"93237715","text":"# -*- coding: utf-8 -*-\n# @Time : 2020/1/25 19:15\n# @Author : ooooo\n\nclass Test:\n\n def __init__(self, foo) -> None:\n super().__init__()\n self.__foo = foo\n\n def __bar(self):\n print(self.__foo)\n print('__bar')\n\n\n# 通过 _类名 + 属性(方法) 来访问\nif __name__ == '__main__':\n test = Test('hello')\n test._Test__bar()\n print(test._Test__foo)\n","sub_path":"day08/access.py","file_name":"access.py","file_ext":"py","file_size_in_byte":397,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"166607836","text":"#Code Review\n#Привет.\n#1. Line 36-52 не совсем понятно, почему были эти колонки выбраны.\n#2. Хотелось бы логики ограничения датасета в 100к строк из 300к. Сейчас пролучается, просто треть отбрасываем. \n#3. Хорошие комментарии и структура кода.\n#Хорошего дня (:\n\n\n\n#!/usr/bin/env python\n# coding: utf-8\n\n# In[1]:\n\n\n# выбрал xgboost как наиболее эффективный по опыту\nimport pandas as pd\nimport xgboost as xgb\n\n\n# In[2]:\n\n\ntrain = pd.read_csv('lab04_train.csv')\ntrain = train[train['TARGET'].notnull()] # убрал строки с нулевыми таргетами\ntest = pd.read_csv('lab04_test.csv')\n\n\n# In[3]:\n\n\n# ограничил строки в тренировочной выборке 100 000 т.к. комп пыхтел на 300 тыс.\nX = train.iloc[:100000,2:116]\ny = train.iloc[:100000,116]\n\n\n# In[4]:\n\n\n# по-хорошему, надо было эти колонки энкодить (см. запрос ниже), но он генерил десятки тысяч колонок\n# к тому же, по опыту, энкодированные колонки мало влияют на эффективность, а ресурсов компа едят много\n# поэтому решил их вырезать\ncol_to_encode = ['CLNT_TRUST_RELATION',\n'APP_MARITAL_STATUS',\n'APP_KIND_OF_PROP_HABITATION',\n'CLNT_JOB_POSITION_TYPE',\n'CLNT_JOB_POSITION',\n'APP_EDUCATION',\n'APP_TRAVEL_PASS',\n'APP_POSITION_TYPE',\n'APP_EMP_TYPE',\n'APP_COMP_TYPE',\n'APP_DRIVING_LICENSE',\n'APP_CAR',\n'PACK' \n]\n\n# X = X.join(pd.get_dummies(X[col_to_encode]))\nX = X.drop(col_to_encode, axis = 1)\n\n\n# In[6]:\n\n\n# не стал разбивать здесь на трейн тест сплит, т.к. в кросс валидации это будет сделано за меня\ndtrain = xgb.DMatrix(X, label = y)\n\n\n# In[7]:\n\n\n# параметры (ключевые, которые больше всего влияют на эффективность - описаны в соотв ст��очках)\nparam = {\n \"num_parallel_tree\":1,\n \"subsample\":.9, # при бустинге каждого дерева мы берем не 100, а 90% строчек из датасета рандомно\n \"colsample_bytree\":.9,# при бустинге каждого дерева мы берем не 100, а 90% колонок из датасета рандомно\n \"objective\":\"binary:logistic\",\n \"learning_rate\":0.05, # шаг, по которому мы будем двигаться по функции снижения ошибки (большой - промажем, \n # маленький - будем двигаться как черепаха и есть ресурсы компа)\n \"eval_metric\":\"auc\", \n \"max_depth\":5, # глубина дерева\n \"scale_pos_weight\":len(y[y == 0]) / len(y[y == 1]),\n \"min_child_weight\":1,\n \"seed\":7\n}\n\n\n# In[8]:\n\n\n#параметры кросс валидации\nnfold = 5 # на сколько валидаций будем делить. В посл. лекции делили на 10, здесь - на 5\nearly_stopping_rounds = 5 # через сколько раундов остановим бустинг деревьев, если не увидим улучшения. \nstratified = True # распределим поровну нули и единицы между 5 нарезками \nn_estimators = 500 # сколько деревьев будем генерить\n\n\n# In[9]:\n\n\n# кросс-валидация\nbst_cv = xgb.cv(\n param, \n dtrain, \n num_boost_round=n_estimators, \n nfold = nfold,\n early_stopping_rounds=early_stopping_rounds,\n stratified = stratified\n)\n\n\n# In[10]:\n\n\n# получаем отчет о рок-аук. Понимаем, что близко к тому, что в лабе\n# берем для тренировки модели число раундов для бустинга (best_iteration) наиболее оптимальное с т.зр. кросс-валидации\n# чтобы избежать переобучения и сэкономить ресурсы компа\n# Еще std в выводе говорит, насколько велик разброс результатов каждой из 5 кросс-валидаций. \n# Если большой - модель нестабильна (переучена)\ntest_auc_mean = bst_cv[\"test-auc-mean\"]\nbest_iteration = test_auc_mean[test_auc_mean == max(test_auc_mean)].index[0]\n\nbest_test_auc_mean = bst_cv[\"test-auc-mean\"][best_iteration]\nbest_test_auc_mean_std = bst_cv[\"test-auc-std\"][best_iteration]\n\nprint('''XGB CV model report\nBest test-auc-mean {}% (std: {}%)'''.format(round(best_test_auc_mean * 100, 2), \n round(best_test_auc_mean_std * 100, 2)))\n\n\n# In[11]:\n\n\n# тренируем модель\nbst = xgb.train(param, \n dtrain, \n num_boost_round = best_iteration)\n\n\n# In[12]:\n\n\nids = test.ID\n# предсказываем на тестовой выборке\npred_test = test.iloc[:,2:116]\npred_test = pred_test.drop(col_to_encode, axis = 1)\npred_test = xgb.DMatrix(pred_test)\npred = pd.Series(bst.predict(pred_test))\n\n\n# In[20]:\n\n\n# объединяем id и предсказания\nres = pd.concat([ids, pred], axis=1)\n# переименовываем колонки\nres.rename(columns={'ID': \"id\", 0: \"target\"}, inplace=True)\n\n\n# In[25]:\n\n\n# сохраняем.\nres.to_csv(\"lab04.csv\", sep='\\t', index=False)\n\n# roc auc 0.83\n","sub_path":"code-reviews/lab04_valeria.lupanova.py","file_name":"lab04_valeria.lupanova.py","file_ext":"py","file_size_in_byte":5736,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"415415964","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nimport sys\nimport unittest\nfrom datetime import timedelta\n\nsys.path.append(\"..\")\n\n# custom\nfrom data import TRADES, STOCKS\n\nfrom src.tickers import TickerSymbol\nfrom src.stock import Stock, CommonStock, PreferredStock\nfrom config.config_trade import ConfigTrade\nfrom config.config_stock import ConfigStock\n\n\nclass StockInitTestCase(unittest.TestCase):\n\n \n def test_not_instantiable(self):\n ''' Test if CommonStock or PreferredStocks are created accordingly.\n The test will rise an error (pass) if CommonStock or PreferredStock\n contain a missing argument. The test will also rise an error (pass)\n if we access Stock() directly without previously defining the dividend \n property (abstract method)\n '''\n with self.assertRaises(TypeError):\n ''' Correct way to create a new CommonStock:\n stock = CommonStock(ticker_symbol=TickerSymbol.TEA, par_value=100, last_dividend=1)\n '''\n stock1 = Stock(ticker_symbol=TickerSymbol.TEA, par_value=100)\n stock2 = CommonStock(ticker_symbol=TickerSymbol.TEA, par_value=100)\n\n\nclass StockRecordTradeTestCase(unittest.TestCase):\n\n ''' Set for all the tests in the class the stock\n before running the test\n '''\n def setUp(self):\n self.stock = ConfigStock(STOCKS).get_stock()\n\n def test_checks_type(self):\n ''' Test if a wrong value for a trade for a particular stock will\n rise an error. If a wrong value raises the error, the test will pass.\n '''\n \n ''' A correct value is (timestamp, quantity, price, buy/sell indicator)\n '''\n wrong_value = ('wrong', 'value')\n\n with self.assertRaises(TypeError):\n self.stock.record_trade(wrong_value)\n\n def test_trade_is_recorded(self):\n\n trade = ConfigTrade(TRADES).get_trade()\n self.stock.record_trade(trade)\n\n self.assertIn(trade, self.stock.trades)\n\n def test_checks_ticker_symbol(self):\n ale_stock = ConfigStock(STOCKS).get_stock_by_ticker_symbol(TickerSymbol.ALE)\n tea_trade = ConfigTrade(TRADES).get_trade_for_stock(TickerSymbol.TEA)\n with self.assertRaises(ValueError):\n ale_stock.record_trade(tea_trade)\n\n\nclass StockTickerPriceTestCase(unittest.TestCase):\n\n def setUp(self):\n self.stock = ConfigStock(STOCKS).get_stock()\n\n def test_empty_trades_raises_attribute_error(self):\n with self.assertRaises(AttributeError):\n ticker_price = self.stock.ticker_price\n\n def test_price_value(self):\n trade = ConfigTrade(TRADES).get_trade()\n self.stock.record_trade(trade)\n self.assertEqual(trade.price, self.stock.ticker_price)\n\n def test_price_value_is_last_trades(self):\n trades = ConfigTrade(TRADES).get_trades(3)\n last_trade = trades[-1]\n for trade in trades:\n self.stock.record_trade(trade)\n self.assertEqual(last_trade.price, self.stock.ticker_price)\n\n\nclass StockPriceDividendRatioTestCase(unittest.TestCase):\n\n def test_zero_dividend_stock_returns_none(self):\n zero_dividend_stock = ConfigStock(STOCKS).get_zero_dividend_stock()\n trade = ConfigTrade(TRADES).get_trade()\n zero_dividend_stock.record_trade(trade)\n pd_ratio = zero_dividend_stock.price_dividend_ratio\n self.assertEqual(pd_ratio, 0)\n\n\nclass StockPriceTestCase(unittest.TestCase):\n\n def setUp(self):\n self.stock = ConfigStock(STOCKS).get_stock()\n\n def test_not_enough_significant_trades_returns_none(self):\n trade = ConfigTrade(TRADES).get_trade()\n self.stock.record_trade(trade)\n\n stock_price = self.stock.vwap()\n self.assertEqual(stock_price, 0)\n\n def test_price_value_for_one_trade(self):\n trade = ConfigTrade(TRADES).get_trade()\n self.stock.record_trade(trade)\n current_time = trade.timestamp + timedelta(minutes=5)\n\n expected_value = trade.price\n self.assertEqual(self.stock.vwap(current_time), expected_value)\n\n def test_price_value_for_multiple_trades(self):\n trades = ConfigTrade(TRADES).get_trades_for_stock(TickerSymbol.TEA)\n for trade in trades:\n self.stock.record_trade(trade)\n\n # Set the most recent trade timestamp as current_time.\n by_timestamp = sorted(trades,\n key=lambda t: t.timestamp,\n reverse=True)\n\n last_trade = by_timestamp[0]\n selected_trades = [trade for trade in trades\n if trade.timestamp >=\n last_trade.timestamp - self.stock.price_time_interval]\n pxvol = shares = 0\n for trade in selected_trades:\n pxvol= pxvol + (trade.price * trade.quantity)\n shares = shares + trade.quantity\n expected_value = 0 if shares==0 else (pxvol / shares)\n\n self.assertEqual(self.stock.vwap(last_trade.timestamp), expected_value)\n\n\nclass CommonStockDividendTestCase(unittest.TestCase):\n\n def setUp(self):\n self.stock = ConfigStock(STOCKS).get_common_stock()\n\n def test_dividend_value(self):\n expected_value = self.stock.last_dividend\n self.assertEqual(self.stock.dividend, expected_value)\n\n\nclass PreferredStockDividendTestCase(unittest.TestCase):\n\n def setUp(self):\n self.stock = ConfigStock(STOCKS).get_preferred_stock()\n\n def test_dividend_value(self):\n expected_value = self.stock.fixed_dividend * self.stock.par_value\n self.assertEqual(self.stock.dividend, expected_value)\n\n\nif __name__ == '__main__':\n \n unittest.main()\n \n\n","sub_path":"stock_market/tests/test_stock.py","file_name":"test_stock.py","file_ext":"py","file_size_in_byte":5679,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"538919122","text":"#Testowane dla argumentow : 32 f sdsvdFS f#S542 ao \n# python3 main.py 32 f sdsvdFS f#S542 ao \n\n\n# Zad 1\n# Proszę utworzyć string składający się z elementów listy argv z wyłączeniem nazwy programu. Jeżeli program został uruchomiony bez podania parametrów proszę wypisać na ekran komunikat informujący o właściwym sposobie uruchomienia programu (1p)\n\nimport sys\n\nif len(sys.argv) == 1:\n print(\"Wrong number of arguments!!!\")\nelse:\n arr=''.join(sys.argv[1:])\nprint(arr)\n\n\n# Zad 2\n# Na podstawie wcześniej utworzonego stringa proszę utworzyć cztery listy: zawierającą małe litery, zawierającą duże litery, zawierającą cyfry oraz zawierającą wszystko co nie jest literą (2p)\n\nlower = []\nupper = []\ndigits = []\nnoletters = []\n\nfor i in arr:\n if i.isalpha():\n if i.islower():\n lower.append(i)\n else :\n upper.append(i)\n elif i.isdigit():\n digits.append(i)\n else:\n noletters.append(i)\n\n\nprint(\"Lower letters : {}\\nUpper letters: {}\\nDigits : {}\\nNoletters : {}\".format(lower, upper, digits, noletters))\n\n\n\n# Zad 3 \n# Na podstawie utworzonej listy zawierającej małe litery proszę utworzyć listę małych liter bez powtórzeń. Następnie proszę utworzyć nową listę, w której każdy element jest dwuelementową krotką (litera, krotność jej wystąpienia w liście oryginalnej) (2p)\n\nlower_2 = []\n\nfor i in lower:\n if i not in lower_2 :\n lower_2.append(i)\nprint(\"Lista elementów unikalnych :\",lower_2)\n\nuniq = [(letter, lower.count(letter)) for letter in lower_2]\nprint(\"Lista krotek (listera, krotnosc wystapienia :)\", uniq)\n\n\n# Zad 4 \n# Otrzymaną w powyższym punkcie listę proszę wyświetlić w kolejności od najwyższej krotności (1p)\n\n\n# help(uniq)\nuniq.sort(reverse = True, key = lambda el: el[1])\nprint(\"Lista w kolejności od najwyższej krotności : \", uniq)\n\n\n# Zad 5\n# Proszę utworzyć listę dwuelementowych krotek, w których pierwszy element jest liczbą pobraną z listy cyfr, drugi natomiast wartością funkcji liniowej ax+b dla danej liczby; wartości współczynników proszę ustalić w następujący sposób: a równa się liczbie samogłosek w stringu z punktu pierwszego, a b - liczbie spółgłosek tamże (2p)\n\nsamogloski = ['a', 'o', 'e', 'i', 'o', 'u', 'y', 'A', 'E', 'I', 'O', 'U', 'Y']\n\n\nsam_counter = 0\nsp_counter = 0\ntemp = lower + upper\nfor i in temp:\n if i in samogloski:\n sam_counter += 1\n else:\n sp_counter += 1\n\n\na = sam_counter\nb = sp_counter\nprint(\"Ilosc samoglosek : {}\\nIlosc spolglosek : {}\".format(a,b))\ntemp_krotka = [(float(i), a*float(i) + b)for i in digits]\n\nprint(\"Lista dwuelementowych krotek (x, y(x) = ax + b) : \",temp_krotka)\n\n# Zad 6\n# Proszę obliczyć wartości parametrów prostej korzystając z metody najmniejszych kwadratów (2p):\n\nx_sr = 0\ny_sr = 0\nD = 0\na = 0 \nb = 0\n\n# licze x sredni\nfor i in temp_krotka:\n x_sr += i[0]\nx_sr = x_sr / len(temp_krotka)\n\n# licze y sredni\nfor i in temp_krotka:\n y_sr += i[1]\ny_sr = y_sr / len(temp_krotka)\n\n# licze D \nfor i in temp_krotka:\n D += (i[0] - x_sr)**2\n\n#lcize a\nfor i in temp_krotka:\n a += i[1]*(i[0] - x_sr)\na = a/D\n\n#lcize b\nb = y_sr -a*x_sr\n\nprint(\"x_sr : \",x_sr)\nprint(\"y_sr : \",y_sr)\nprint(\"D : \",D)\nprint(\"a : \",a)\nprint(\"b : \",b)","sub_path":"Labs/lab_03.py","file_name":"lab_03.py","file_ext":"py","file_size_in_byte":3217,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"571682969","text":"from pycorenlp import StanfordCoreNLP\nfrom treelib import Node, Tree\nimport treeparser\nimport itertools\nfrom rouge import Rouge\nimport json\nimport numpy as np\nimport pandas as pd\nimport pickle\nimport scipy.stats\nfrom simplenlg import changePOS, changePlurality\n#import lm\n\nnlp = StanfordCoreNLP('http://localhost:9000')\nrules = 'rules.json'\n\ndef getRougeScore(gold, sys):\n rouge = Rouge()\n scores = rouge.get_scores(gold, sys)\n return scores\n\n\n\nclass smic_generator(object):\n \"\"\"docstring for smic_generator.\"\"\"\n def __init__(self, acceptability_type=None, confidence = 0.95):\n super(smic_generator, self).__init__()\n if(acceptability_type is not None):\n self.avgchange = pickle.load( open( \"rougefilter.p\", \"rb\" ) )\n [self.data_mean, self.data_std, self.data_totalmean] = pickle.load( open( \"rouge_stats.p\", \"rb\" ) )\n #type of acceptability measure valid options are:\n # 1. absolute\n # 2. difference\n # 3. fitting_absolute\n # 4. absolute_global\n # 5. fitting_absolute_global\n self.acceptability_type = acceptability_type\n #set confidence\n self.confidence = confidence\n\n def generate(self,source, gold, smc, smcscore, sourceid, judgeid, debugrule=0):\n #parse smc using corenlp\n sys_parse = nlp.annotate(smc, properties={\n 'annotators': 'tokenize,ssplit,pos,depparse,parse',\n 'outputFormat': 'json'\n })\n if(gold is not None):\n #parse gold standard using corenlp\n gold_parse = nlp.annotate(gold, properties={\n 'annotators': 'tokenize,ssplit,pos,depparse,parse',\n 'outputFormat': 'json'\n })\n sents_gold = gold_parse['sentences']\n\n #parse source using corenlp\n source_parse = nlp.annotate(source, properties={\n 'annotators': 'tokenize,ssplit,pos,depparse,parse',\n 'outputFormat': 'json'\n })\n\n #print(sys_parse.keys())\n sents = sys_parse['sentences']\n\n sents_source = source_parse['sentences']\n #print(dparse)\n #print(smc)\n #print(sys_parse['sentences'][0])\n\n\n total = []\n with open(rules) as data_file:\n data = json.load(data_file)\n #smcLMScore = lm.getLMScore(smc)\n smcLMScore = 1\n #get dependency parse convert it to tree and store in list for smc\n dtrees = []\n treeid = 1\n for sent in sents:\n cparse = sent['parse']\n dparse = sent['basicDependencies']\n tokens = sent['tokens']\n #if multiple sentences create multiple dependency trees\n dtrees.append(treeparser.getDependencyTree(dparse, tokens, treeid))\n treeid += 1\n\n\n #get dependency parse convert it to tree and store in list for gold standard\n dtrees_gold = []\n\n if(gold is not None):\n for sent_gold in sents_gold:\n cparse = sent_gold['parse']\n dparse = sent_gold['basicDependencies']\n tokens = sent_gold['tokens']\n #if multiple sentences create multiple dependency trees\n dtrees_gold.append(treeparser.getDependencyTree(dparse, tokens, treeid))\n treeid += 1\n\n dtrees_source = []\n\n for sent_source in sents_source:\n cparse = sent_source['parse']\n dparse = sent_source['basicDependencies']\n tokens = sent_source['tokens']\n #if multiple sentences create multiple dependency trees\n dtrees_source.append(treeparser.getDependencyTree(dparse, tokens, treeid))\n treeid += 1\n\n total_coverage = []\n #for each rule in rule.json\n for rule in data:\n #for debugging rules, debugrule is set to the id of the rule which needs to be deubged\n if(rule[\"id\"]==debugrule or debugrule==0 ):\n\n matched=[]\n matched_gold=[]\n if rule['from']=='SMC':\n #each rule may contain subset of rules whose matches can be substituted\n subsets = rule['match'].split(\",\")\n\n for subset in subsets:\n #each subset may contain different matching criteria but the matched rules may intermix\n matches = subset.split(\" or \")\n submatched=[]\n for match in matches:\n match = match.strip()\n #perform mathing of rules with the dependency parse of given sentences\n submatch = self.getMatches(match, dtrees)\n #we can intermix submatches\n submatched.extend(submatch)\n #matched will contain list of matches for each subset\n matched.append(submatched)\n #print(\"matched\",matched)\n else:\n #match either reference/gold summary or source to smc\n dtrees_secondary = \"\"\n if(rule['from']=='GOLD'):\n if(gold is None):\n continue\n dtrees_secondary = dtrees_gold\n else:\n dtrees_secondary = dtrees_source\n subsets = rule['match'].split(\",\")\n for subset in subsets:\n #each subset may contain different matching criteria but the matched rules may intermix\n matches = subset.split(\" or \")\n submatched=[]\n submatched_gold=[]\n for match in matches:\n match = match.strip()\n #perform mathing of rules with the dependency parse of given sentences\n submatch = self.getMatches(match, dtrees)\n #repeat for matches in gold standard\n submatch_gold = self.getMatches(match, dtrees_secondary)\n #we can intermix submatches\n submatched.extend(submatch)\n #repeat for matches in gold standard\n submatched_gold.extend(submatch_gold)\n #matched will contain list of matches for each subset\n matched.append(submatched)\n #repeat for matches in gold standard\n matched_gold.append(submatched_gold)\n\n\n #get sentences after matching\n sentences = []\n count = 0\n if rule['from']=='SMC':\n #for each set of matches corresponding to each submatch generate all possible sentences\n for match in matched:\n if(len(match)>0):\n #function which generates the sentences\n sentence, coverage = self.generateSentence(dtrees, [], match, [], gold, int(rule['hardmatch']), smcscore, sourceid, smcLMScore, rule[\"id\"], smc, judgeid, rule['from'], total_coverage)\n\n sentences.extend(sentence)\n count += 1\n else:\n dtrees_secondary = \"\"\n if(rule['from']=='GOLD'):\n dtrees_secondary = dtrees_gold\n else:\n dtrees_secondary = dtrees_source\n for match, match_gold in zip(matched, matched_gold):\n if(len(match)>0 and len(match_gold)>0):\n #function which generates the sentences\n sentence, coverage = self.generateSentence(dtrees, dtrees_secondary, match, match_gold, gold, int(rule['hardmatch']), smcscore, sourceid, smcLMScore, rule[\"id\"], smc, judgeid, rule['from'], total_coverage)\n if(len(coverage)!=0):\n total_coverage.extend(coverage)\n sentences.extend(sentence)\n count += 1\n\n total.extend(sentences)\n return total\n\n def getMatches(self, match, dtrees):\n tree, leaves = treeparser.getTree(match)\n #tree.show(line_type=\"ascii-em\")\n matched=[]\n #get root node of searcher\n node = tree.get_node(1)\n #maintain a dtree id\n dtree_id=0\n #for each dependency tree of each sentence\n for dtree in dtrees:\n\n for target_node in dtree.expand_tree():\n target_node = dtree.get_node(target_node)\n #if(target_node.data[0]!='p'):\n # continue\n #print(node.tag, target_node.tag)\n if (node.tag == \".\" or node.tag == target_node.tag):\n subtree = Tree()\n subtree.create_node('ROOT', 0, data=True)\n\n subtree.create_node(target_node.tag, target_node.identifier, parent=0, data=[list(target_node.data),list(node.data)])\n #dtree.show(line_type=\"ascii-em\")\n #tree.show(line_type=\"ascii-em\")\n matchsuccess, subtree, word_target = self.checkmatch(node, target_node, subtree, dtree, tree)\n #print(\"did i catch the right word \", word_target)\n if matchsuccess:\n matched.append([subtree, dtree_id, word_target])\n #subtree.show(line_type=\"ascii-em\")\n dtree_id+=1\n\n return matched\n\n def checkmatch(self, node, target_node, subtree, dtree, tree, word_target=\"\"):\n\n #if(node.data[1]==True):\n #get the word assuming that the target is always POS tag node\n #print(target_node.fpointer[0])\n #print(target_node.identifier)\n #word_target = dtree.get_node(target_node.fpointer[0]).tag\n\n\n\n\n #node matches check for children\n #assume the sub tree has maximum 1 child and take the first one\n children = tree.children(node.identifier)\n\n\n if(children is None or len(children)==0):\n #leaf has been reached\n return 1, subtree, word_target\n else:\n #take the first child\n\n child = children[0]\n\n\n #if(child.data[0]==True):\n #print(child.tag)\n target_children = dtree.children(target_node.identifier)\n if(target_children is None or len(target_children)==0):\n #this means that the dependency tree reached an end but the rule didn't\n #so check if the next node was optional\n if(child.data[0]==True):\n return 1, subtree, word_target\n\n found_match = [0]\n found=0\n for target_child in target_children:\n #print(target_child.tag)\n #target_child = tree.get_node(target_child)\n #print(target_child)\n\n if(child.tag=='.' or target_child.tag == child.tag):\n found=1\n subtreecopy = Tree(subtree, deep=True)\n #check if it is the target\n\n\n #if optional node then check whether the node is within 1 distance away w.r.t sentence\n if(child.data[0]==True):\n relid = target_child.identifier.split('_')\n #print(relid, target_child.tag)\n\n if(len(relid)!=3 or abs(int(relid[0])-int(relid[1]))!=1):\n return 1, subtree, word_target\n\n subtreecopy.create_node(target_child.tag, target_child.identifier, parent=target_node.identifier, data=[list(target_child.data),list(child.data)])\n matchsuccess, subtree, word_target = self.checkmatch(child, target_child, subtreecopy, dtree, tree, word_target)\n if(matchsuccess==0):\n #print('yes something got removed')\n subtree.remove_node(target_child.identifier)\n found_match.append(matchsuccess)\n\n\n if(np.sum(found_match)!=0):\n return 1, subtree, word_target\n elif(child.data[0]==True and found!=1):\n #print(child.tag)\n\n return 1, subtree, word_target\n else:\n return 0, subtree, word_target\n\n\n def verifymatch(self, tree1, tree2):\n #fetch the root node\n tree1_node = tree1.get_node(0)\n tree2_node = tree2.get_node(0)\n\n #iterate through both trees, assume same structure\n while(tree1_node.is_leaf() is False):\n #move pointer to next child, assume one child only\n tree1_node = tree1.get_node(tree1_node.fpointer[0])\n tree2_node = tree2.get_node(tree2_node.fpointer[0])\n\n #check if node is set for hard match if yes then compare the node tags\n if(tree1_node.data[1][2] and tree1_node.tag!=tree2_node.tag):\n return False\n return True\n\n def extractSentence(self, dtree1, dtree2, tree1_node, tree2_node, bool_goldsent, treecopies, treecopies_gold, gold, sourceid, judgeid, ruleid, tree1, tree2):\n #switch words keeping the identifier the same\n dtree1.get_node(tree1_node.identifier).tag = tree2_node.tag\n dtree2.get_node(tree2_node.identifier).tag = tree1_node.tag\n\n target_ident1 = tree1_node.identifier\n target_ident2 = tree2_node.identifier\n\n #print(target_ident1)\n #print(target_ident2)\n\n #\n dwshow=0\n if(tree1_node.is_leaf() is False):\n dwshow=1\n #print(\"yesss\")\n parentwordid = tree1_node.identifier\n new_parentwordid = tree2_node.identifier\n\n\n tree1 = tree1.subtree(tree1_node.fpointer[0])\n node = tree1.get_node(tree1_node.fpointer[0])\n\n\n #change subtree\n fcounter = 1\n bcounter = 1\n #create a partition of 1000 words, which means maximum 1000 words can be added before or after the parent\n partition = 1.0/1000.0\n while(node is not None):\n if(node.data[0][0]=='word'):\n wordid = node.identifier\n\n if(parentwordid0):\n replaced_postions.append(str(posid1[0]))\n if(len(posid2)>0):\n replaced_postions.append(str(posid2[0]))\n #print(sent)\n\n #if both the targets are present in the same sentence\n if(len(sent[sent['target']!=0])==2):\n #then check if the words are linked only through conjugations such as ,, and, or,\n target_posid1 = list(sent[sent['target']==1].index)[0]\n target_posid2 = list(sent[sent['target']==2].index)[0]\n word_list = list(sent['word'])\n sub_sent = ''\n sub_sent_len = 0\n\n if(target_posid1>target_posid2):\n sub_sent_len = target_posid1 - target_posid2 + 1\n sub_sent = \" \".join(word_list[target_posid2 : target_posid1+1])\n else:\n sub_sent_len = target_posid2 - target_posid1 + 1\n sub_sent = \" \".join(word_list[target_posid1 : target_posid2+1])\n\n if((len(sub_sent.split(' , '))*2-1 == sub_sent_len) or (len(sub_sent.split(' and '))*2-1 == sub_sent_len) or (len(sub_sent.split(' or '))*2-1 == sub_sent_len)):\n #print(':O')\n furthercheck = False\n\n if(bool_goldsent and len(sent[sent['target']!=0])==1):\n word_list = list(sent['word'])\n target_posid1 = list(sent[sent['target']==1].index)[0]\n lower = target_posid1 - window_size\n upper = target_posid1 + window_size + 1\n #make lower zero if it becomes less than zero\n lower = 0 if lower<0 else lower\n upper = len(word_list) if upper>len(word_list) else upper\n\n #target_window_sent = word_list[lower:upper]\n target_window_sent = word_list[lower:target_posid1]\n target_window_sent.extend(word_list[target_posid1+1:upper])\n\n\n #print(sent)\n #if(dwshow):\n #print(sent)\n sent = \" \".join(list(sent['word']))\n sents.append(sent)\n\n gold_window_sent = ''\n #get context of word from gold sent, only when rules use gold sents\n if(bool_goldsent):\n for treecopy in treecopies_gold:\n sent = []\n target_posid1 = -1\n target_posid2 = -1\n for nodeid in treecopy.expand_tree():\n node = treecopy.get_node(nodeid)\n\n #print(node.tag)\n if(node.data[0] == 'word'):\n if(nodeid==target_ident1):\n target_posid1 = float(node.data[1])\n sent.append([float(node.data[1]),node.tag, 1])\n #print(node.tag)\n elif(nodeid==target_ident2):\n target_posid2 = float(node.data[1])\n sent.append([float(node.data[1]),node.tag, 2])\n else:\n sent.append([float(node.data[1]),node.tag, 0])\n #print(node.tag)\n\n elif(node.data[0][0]=='word'):\n\n if(nodeid==target_ident1):\n target_posid1 = float(node.data[0][1])\n sent.append([float(node.data[0][1]),node.tag, 1])\n #print(node.tag)\n elif(nodeid==target_ident2):\n target_posid2 = float(node.data[0][1])\n sent.append([float(node.data[0][1]),node.tag, 2])\n else:\n sent.append([float(node.data[0][1]),node.tag, 0])\n\n\n sent = pd.DataFrame(sent)\n sent.columns = ['id', 'word', 'target']\n sent = sent.sort_values('id',axis=0)\n sent = sent.reset_index(drop=True)\n #print(sent)\n\n\n\n if(len(sent[sent['target']!=0])==1):\n word_list = list(sent['word'])\n target_posid1 = list(sent[sent['target']==2].index)[0]\n lower = target_posid1 - window_size\n upper = target_posid1 + window_size + 1\n #make lower zero if it becomes less than zero\n lower = 0 if lower<0 else lower\n upper = len(word_list) if upper>len(word_list) else upper\n\n gold_window_sent = word_list[lower:target_posid1]\n gold_window_sent.extend(word_list[target_posid1+1:upper])\n\n common_words = list(set(target_window_sent).intersection(gold_window_sent))\n #print(gold_window_sent)\n #print(target_window_sent)\n #print(common_words)\n\n gold_window_len = len(gold_window_sent)\n target_window_len = len(target_window_sent)\n common_words_len = len(common_words)\n min_len = min(gold_window_len, target_window_len)\n if(min_len!=0):\n overlap_ratio = float(common_words_len)/float(min_len)\n if(overlap_ratio>=0.65):\n furthercheck = False\n #print(overlap_ratio)\n\n sent = \" \".join(list(sent['word']))\n\n\n if(furthercheck is False):\n return 0\n\n #final sentence\n sent = \" \".join(sents)\n #print(sent)\n\n if(gold is not None):\n #print(sent)\n score = getRougeScore(gold, sent)\n\n scores = score[0]\n #get whether each type of rouge metric was acceptable or not\n #acceptability, smc_score_list, smic_score_list = self.rougeAcceptability(score, smcscore, sourceid)\n\n #smicLMScore = lm.getLMScore(sent)\n #smicLMScore = 1\n #relscore = (smicLMScore - smcLMScore) / smcLMScore\n datarow = {'sourceid':sourceid, 'judgeid':judgeid, 'smic': sent, 'ruleid': ruleid, 'rouge1_f':scores['rouge-1']['f'], 'rouge1_p':scores['rouge-1']['p'], 'rouge1_r':scores['rouge-1']['r'], 'rouge2_f':scores['rouge-2']['f'], 'rouge2_p':scores['rouge-2']['p'], 'rouge2_r':scores['rouge-2']['r'], 'rougel_f':scores['rouge-l']['f'], 'rougel_p':scores['rouge-l']['p'], 'rougel_r':scores['rouge-l']['r'], 'positions': \",\".join(replaced_postions)}\n else:\n datarow = {'sourceid':sourceid, 'judgeid':judgeid, 'smic': sent, 'ruleid': ruleid}\n\n return datarow\n\n def generateSentence(self, dtrees, dtrees_gold, matches, matches_gold, gold, hardmatch, smcscore, sourceid, smcLMScore, ruleid, smc, judgeid, rulefrom, cov_check):\n\n bool_goldsent = False\n #check whether substitution needs to be done within smc standard or not\n if(len(dtrees_gold)==0):\n #create combinations of matches to switch subtrees within smc\n matched = itertools.combinations(matches, 2)\n else:\n #create combinations of matches to switch subtrees between gold and smc\n matched = itertools.product(matches, matches_gold)\n bool_goldsent = True\n\n sentences = []\n\n coverage = []\n\n match_coverage = []\n #print('start####################')\n #loop through combinations of all the matches\n for match in (list(matched)):\n\n #the first index is for accessing the combination returned by combinations and the second is for accessing the tree or dtree id\n tree1 = match[0][0]\n tree2 = match[1][0]\n\n #if(bool_goldsent):\n #verify if the same target word was chosen\n\n #if(match[1][2]==\"\"):\n # raise ValueError('Could not find target, is this possible?')\n #elif(match[1][2].strip().lower()==match[0][2].strip().lower()):\n # continue\n\n if(hardmatch):\n if(self.verifymatch(tree1, tree2) is False):\n continue\n #print(\"hard match accepted\")\n #tree1.show(line_type=\"ascii-em\")\n #tree2.show(line_type=\"ascii-em\")\n\n\n\n #maintain copy of each dependency tree\n treecopies = []\n for dtree in dtrees:\n treecopies.append(Tree(dtree, deep=True))\n treecopies_gold = []\n if(bool_goldsent):\n for dtree in dtrees_gold:\n treecopies_gold.append(Tree(dtree, deep=True))\n\n #get corresponding dtree in which the matched rules are present\n dtree1 = treecopies[match[0][1]]\n dtree2 = \"\"\n if(bool_goldsent):\n dtree2 = treecopies_gold[match[1][1]]\n else:\n dtree2 = treecopies[match[1][1]]\n\n\n match1_id = tree1.get_node(0).fpointer[0]\n match2_id = tree2.get_node(0).fpointer[0]\n parent1_id = dtree1.get_node(match1_id).bpointer\n parent2_id = dtree2.get_node(match2_id).bpointer\n\n #get tree1 word node\n tree1_node = tree1.get_node(match1_id)\n while(tree1_node.data[1][1] is False):\n tree1_node = tree1.get_node(tree1_node.fpointer[0])\n\n #get tree2 word node\n tree2_node = tree2.get_node(match2_id)\n while(tree2_node.data[1][1] is False):\n tree2_node = tree2.get_node(tree2_node.fpointer[0])\n\n\n\n tree1_node_pos = tree1_node.tag\n tree2_node_pos = tree2_node.tag\n\n #assuming the target node is always the pos node\n #get the child which will be the word node\n tree1_node = tree1.get_node(tree1_node.fpointer[0])\n tree2_node = tree2.get_node(tree2_node.fpointer[0])\n\n #do not switch same words\n if(tree2_node.tag.strip().lower() == tree1_node.tag.strip().lower()):\n continue\n\n #print(tree1_node.tag, tree1_node.data)\n #print(tree2_node.tag, tree2_node.data)\n\n\n datarow = 0\n\n #if the rule is for verbs\n if(ruleid==3 or ruleid==7 or ruleid==11):\n #if pos of the two targets differ then we need to convert it using simplenlg\n if(tree1_node_pos!=tree2_node_pos):\n #print(\"POS dont match\")\n #print(tree1_node.tag, tree2_node_pos)\n tree1_word_list = changePOS(tree1_node.tag, tree1_node_pos)\n tree2_word_list = changePOS(tree2_node.tag, tree2_node_pos)\n #print(tree1_node.tag, tree1_word_list, tree2_node_pos, len(tree1_word_list))\n #print(tree2_node.tag, tree2_word_list, tree1_node_pos, len(tree2_word_list))\n #print('###############')\n\n\n if(len(tree1_word_list)==0 or len(tree2_word_list)==0):\n if(len(tree1_word_list)!=0):\n for tree1_word in tree1_word_list:\n tree1_node.tag = tree1_word\n if(rulefrom == 'SMC'):\n #check of the combination of word was already covered\n tuple_tosearch = (tree1_node.tag.lower(), tree2_node.tag.lower())\n\n if(tuple_tosearch in match_coverage or tuple(reversed(tuple_tosearch)) in match_coverage):\n #will reach only if rulefrom SMC\n continue\n datarow = self.extractSentence(dtree1, dtree2, tree1_node, tree2_node, bool_goldsent, treecopies, treecopies_gold, gold, sourceid, judgeid, ruleid, tree1, tree2)\n if(datarow==0):\n continue\n match_coverage.append((tree1_node.tag.lower(), tree2_node.tag.lower()))\n\n sentences.append(datarow)\n else:\n\n for tree2_word in tree2_word_list:\n tree2_node.tag = tree2_word\n tuple_tosearch = (tree1_node.tag.lower(), tree2_node.tag.lower())\n #to track target nodes in GOLD rules so that they dont repeat in SOURCE rules\n if(rulefrom == 'GOLD'):\n coverage.append(tree2_node.tag.lower())\n elif(rulefrom == 'SOURCE'):\n if(tree2_node.tag.lower() in cov_check):\n continue\n #check of the combination of word was already covered\n elif(tuple_tosearch in match_coverage or tuple(reversed(tuple_tosearch)) in match_coverage):\n #will reach only if rulefrom SMC\n continue\n\n datarow = self.extractSentence(dtree1, dtree2, tree1_node, tree2_node, bool_goldsent, treecopies, treecopies_gold, gold, sourceid, judgeid, ruleid, tree1, tree2)\n if(datarow==0):\n continue\n match_coverage.append((tree1_node.tag.lower(), tree2_node.tag.lower()))\n sentences.append(datarow)\n\n else:\n list_combinations = itertools.product(tree1_word_list, tree2_word_list)\n for list_combination in list(list_combinations):\n tree1_node.tag = list_combination[0]\n tree2_node.tag = list_combination[1]\n tuple_tosearch = (tree1_node.tag.lower(), tree2_node.tag.lower())\n #check of the combination of word was already covered\n\n #to track target nodes in GOLD rules so that they dont repeat in SOURCE rules\n if(rulefrom == 'GOLD'):\n coverage.append(tree2_node.tag.lower())\n elif(rulefrom == 'SOURCE'):\n if(tree2_node.tag.lower() in cov_check):\n continue\n #check of the combination of word was already covered\n elif(tuple_tosearch in match_coverage or tuple(reversed(tuple_tosearch)) in match_coverage):\n #will reach only if rulefrom SMC\n continue\n datarow = self.extractSentence(dtree1, dtree2, tree1_node, tree2_node, bool_goldsent, treecopies, treecopies_gold, gold, sourceid, judgeid, ruleid, tree1, tree2)\n if(datarow==0):\n continue\n match_coverage.append((tree1_node.tag.lower(), tree2_node.tag.lower()))\n sentences.append(datarow)\n elif((ruleid==1 or ruleid==5 or ruleid==9)):\n if(((tree1_node_pos=='NNS' and tree2_node_pos=='NN') or (tree1_node_pos=='NNS' and tree2_node_pos=='NN'))):\n #print('Noun with different number')\n #print(tree2_node_pos, tree2_node.tag)\n #print(tree1_node_pos, tree1_node.tag)\n #print(tree1_node.tag, tree2_node_pos)\n tree1_node_new = changePlurality(tree1_node.tag, tree1_node_pos)\n tree2_node_new = changePlurality(tree2_node.tag, tree2_node_pos)\n if(tree1_node_new!=''):\n tree1_node.tag = tree1_node_new\n if(tree2_node_new!=''):\n tree2_node.tag = tree2_node_new\n #print(tree2_node_pos, tree2_node.tag)\n #print(tree1_node_pos, tree1_node.tag)\n #print('############################')\n\n tuple_tosearch = (tree1_node.tag.lower(), tree2_node.tag.lower())\n #to track target nodes in GOLD rules so that they dont repeat in SOURCE rules\n if(rulefrom == 'GOLD'):\n coverage.append(tree2_node.tag.lower())\n elif(rulefrom == 'SOURCE'):\n if(tree2_node.tag.lower() in cov_check):\n continue\n #check of the combination of word was already covered\n elif(tuple_tosearch in match_coverage or tuple(reversed(tuple_tosearch)) in match_coverage):\n #will reach only if rulefrom SMC\n continue\n datarow = self.extractSentence(dtree1, dtree2, tree1_node, tree2_node, bool_goldsent, treecopies, treecopies_gold, gold, sourceid, judgeid, ruleid, tree1, tree2)\n if(datarow==0):\n continue\n\n match_coverage.append((tree1_node.tag.lower(), tree2_node.tag.lower()))\n sentences.append(datarow)\n\n else:\n #to track target nodes in GOLD rules so that they dont repeat in SOURCE rules\n if(rulefrom == 'GOLD'):\n coverage.append(tree2_node.tag.lower())\n elif(rulefrom == 'SOURCE'):\n if(tree2_node.tag.lower() in cov_check):\n continue\n\n datarow = self.extractSentence(dtree1, dtree2, tree1_node, tree2_node, bool_goldsent, treecopies, treecopies_gold, gold, sourceid, judgeid, ruleid, tree1, tree2)\n\n if(datarow==0):\n continue\n\n sentences.append(datarow)\n\n #print(sent)\n #print(smc)\n #print(gold)\n #print('\\n')\n\n #print(\" \".join(sent))\n #dtree.paste(parent1_id, tree2.subtree(match2_id))\n #dtree.paste(parent2_id, tree1.subtree(match1_id))\n #tree1.show(line_type=\"ascii-em\")\n #tree2.show(line_type=\"ascii-em\")\n #treecopy.show(line_type=\"ascii-em\")\n #print('end####################')\n return sentences, coverage\n\n def rougeAcceptability(self, smicscores, smcscores, sourceid):\n reduction = smcscores['rouge-1']['f'] - smicscores['rouge-1']['f']\n result = []\n smc_score_list = []\n smic_score_list = []\n for score_cat in smicscores:\n score_cat_ident = score_cat.split('-')[1]\n for score_type in smicscores[score_cat]:\n\n smc_score_list.append(smcscores[score_cat][score_type])\n smic_score_list.append(smicscores[score_cat][score_type])\n\n if(self.acceptability_type == 'difference'):\n reduction = smcscores[score_cat][score_type] - smicscores[score_cat][score_type]\n if(reduction <= float(self.avgchange['rouge'+ score_cat_ident +'_'+ score_type])):\n result.append(1)\n else:\n result.append(0)\n elif(self.acceptability_type == 'absolute' or self.acceptability_type == 'absolute_global'):\n outij = smicscores[score_cat][score_type]\n\n if(self.acceptability_type == 'absolute_global'):\n #global mean\n ui = self.data_totalmean['rouge'+ score_cat_ident +'_'+ score_type]\n else:\n #individual mean\n ui = self.data_mean.loc[str(sourceid)]['rouge'+ score_cat_ident +'_'+ score_type]\n sigma = self.data_std['rouge'+ score_cat_ident +'_'+ score_type]\n zvalue = abs((outij - ui) / sigma)\n pvalue = scipy.stats.norm.cdf(zvalue)\n #print(pvalue)\n if(pvalue>= self.confidence):\n #print(pvalue)\n result.append(1)\n else:\n result.append(0)\n else:\n #for fitting we will have to select sentences at the extend\n result.append(1)\n\n return result, smc_score_list, smic_score_list\n\n def getSentence(self, tree, matched, leaves, gold):\n bestscore=0\n bestsent=\"\"\n matched = itertools.combinations(matched, 2)\n for match in (list(matched)):\n #deep copy the original tree\n treecopy = Tree(tree, deep=True)\n\n #print(treecopy.get_node(treecopy.get_node(match[0]).fpointer[0]).tag)\n #print(treecopy.get_node(treecopy.get_node(match[1]).fpointer[0]).tag)\n #print(treecopy.parent(match[0]).identifier)\n #replace nodes\n parent1 = treecopy.parent(match[0]).identifier\n parent2 = treecopy.parent(match[1]).identifier\n child1 = treecopy.children(match[0])[0].identifier\n child2 = treecopy.children(match[1])[0].identifier\n\n treecopy.move_node(match[0],parent2)\n treecopy.move_node(match[1],parent1)\n sent = self.linearize(leaves, child1, child2, treecopy)\n score = getRougeScore(gold, sent)[0]['rouge-l']['f']\n\n if(score>bestscore):\n bestscore = score\n bestsent = sent\n\n\n return bestsent, bestscore\n\n def linearize(self, leaves, child1, child2, tree):\n sent=[]\n\n for leafid in leaves:\n if(leafid==child1 or leafid==child2):\n if(leafid==child1):\n #append child2\n sent.append(tree.get_node(child2).tag)\n else:\n #append child1\n sent.append(tree.get_node(child1).tag)\n else:\n #append other words\n sent.append(tree.get_node(leafid).tag)\n sent = \" \".join(sent)\n return sent\n","sub_path":"smic_generator_stepwise.py","file_name":"smic_generator_stepwise.py","file_ext":"py","file_size_in_byte":40631,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"131153324","text":"#coding:utf-8\n\"\"\"\nauthor: Allen\nemail: 1902901293@qq.com\n\"\"\"\n\nimport pygame\nimport pandas as pd\nfrom io import BytesIO\nimport time\nimport os\n\n\n\nclass AudioObj(object):\n def __init__(self):\n \"\"\"播放音频\"\"\"\n self.pygame_mixer = pygame.mixer\n self.pygame_mixer.init()\n\n def play(self, audio_bytes):\n \"\"\"\n 传入音频文件字节码,播放音频\n :param audio_bytes:\n :return:\n \"\"\"\n if audio_bytes is None:\n return\n byte_obj = BytesIO()\n byte_obj.write(audio_bytes)\n byte_obj.seek(0, 0)\n self.pygame_mixer.music.load(byte_obj)\n self.pygame_mixer.music.play()\n while self.pygame_mixer.music.get_busy() == 1:\n time.sleep(0.1)\n self.pygame_mixer.music.stop()\n\n\nclass Dictionary(object):\n def __init__(self):\n self.user_home = os.path.expanduser('~')\n self.dictionary_fn = os.path.join(self.user_home, 'words_dict.pkl')\n self.dictionary_df = pd.read_pickle(self.dictionary_fn)\n self.audio = AudioObj()\n self.audio_byte = None\n\n\n def run(self):\n print(\"欢迎使用小词典,目前词库构建于2018年10月3日,词库根据python3官方文档构建,词库相对较小,可以自己扩展词库后再使用\")\n print(\"按键 s 可以获取语音\")\n while 1:\n input_word = input('input enlish word >>>').strip().lower()\n if input_word == 's':\n if self.audio_byte is None:\n print('没有音频数据...')\n else:\n self.audio.play(self.audio_byte)\n continue\n if input_word:\n cn_seq, self.audio_byte = self.filter_word(input_word)\n if not cn_seq:\n print('没有词条数据...')\n else:\n print(', '.join(cn_seq))\n\n\n def filter_word(self, word):\n word = word.lower().strip()\n data = self.dictionary_df[self.dictionary_df['ENGLISH_WORD'] == word].to_dict(orient='record')\n data = data[0] if data else {}\n cn_seq = data.get('CHINESE_SEQ', [])\n audio_byte = data.get('AUDIO', None)\n return cn_seq, audio_byte\n\n\n\nif __name__ == '__main__':\n dict_work = Dictionary()\n dict_work.run()","sub_path":"sixi_cat.py","file_name":"sixi_cat.py","file_ext":"py","file_size_in_byte":2328,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"328424339","text":"# -*- coding: utf-8 -*-\n\nfrom datetime import datetime\nfrom datetime import timedelta\nfrom datetime import date\nfrom typing import Optional, List\n\nfrom chrono.day import Day, DayType\nfrom chrono import month\nfrom chrono import year\nfrom chrono import errors\nfrom chrono import week\n\n\nclass User(object):\n def __init__(self, name: str = \"\",\n employed_date: Optional[str] = None,\n employment: int = 100,\n payed_vacation: int = 0,\n vacation_month: int = 1,\n extra_vacation: int = 0):\n self.name = name\n self.years = []\n if employed_date is not None:\n self.employed_date = datetime.strptime(\n employed_date, \"%Y-%m-%d\").date()\n\n self.years.append(year.Year(\n str(self.employed_date.year),\n start_date=self.employed_date.isoformat()))\n else:\n self.employed_date = None\n self.employment = employment\n self.flextime = timedelta()\n self.payed_vacation = payed_vacation\n self.vacation_month = vacation_month\n self.extra_vacation = extra_vacation\n self.holidays = {}\n\n def add_day(self, date_string: str) -> Day:\n \"\"\"Add a day.\n :type date_string string: The new date\n :rtype: Day\n \"\"\"\n if self.next_workday()[:4] == self.next_year():\n new_year = year.Year(self.next_year())\n for date, name in self.holidays.items():\n new_year.add_holiday(date, name)\n self.years.append(new_year)\n new_day = self.current_year().add_day(date_string)\n return new_day\n\n def add_year(self, year_object: year.Year):\n if len(year_object.months) != 0:\n raise errors.YearError(\n \"Added year can't contain any reported days.\")\n\n elif (len(self.years) > 0 and\n year_object.year != self.current_year().year and\n not self.current_year().complete()):\n raise errors.YearError(\n \"Previous year ({}) must be completed first.\".format(\n self.current_year().year))\n\n if (len(self.years) > 0 and\n year_object.year == self.current_year().year):\n self.years[-1] = year_object\n else:\n year_object.start_date = self.employed_date\n self.years.append(year_object)\n\n def add_holiday(self, date_string: str, name: str):\n date = datetime.strptime(date_string, \"%Y-%m-%d\").date()\n self.holidays[date_string] = name\n for year in self.years:\n if date.year == year.year:\n year.add_holiday(date_string, name)\n\n def next_workday(self) -> str:\n \"\"\"Return next workday.\n :rtype: Day\n \"\"\"\n return self.current_year().next_workday()\n\n def next_month(self) -> str:\n return self.current_year().next_month()\n\n def next_year(self) -> str:\n return self.current_year().next_year()\n\n def current_year(self) -> year.Year:\n return self.years[-1]\n\n def current_month(self) -> Optional[month.Month]:\n \"\"\"Return the current month.\n \"\"\"\n if len(self.current_year().months) > 0:\n return self.current_year().months[-1]\n else:\n return None\n\n def current_week(self) -> week.Week:\n \"\"\"Return the current week.\n :rtype: week.Week or None\n \"\"\"\n if self.current_month() is None:\n return None\n\n all_days = [day for year in self.years\n for month in year.months\n for day in month.days]\n weekdays = []\n earliest_weekday = 6\n for day in reversed(all_days):\n if day.date.weekday() < earliest_weekday:\n earliest_weekday = day.date.weekday()\n weekdays.append(day)\n else:\n break\n tmp_week = week.Week.from_days(*weekdays)\n\n for weekday in (tmp_week.monday, tmp_week.tuesday, tmp_week.wednesday,\n tmp_week.thursday, tmp_week.friday):\n if weekday.date.isoformat() in self.holidays:\n weekday.day_type = DayType.holiday\n return tmp_week\n\n\n def today(self) -> Day:\n \"\"\"Return the last added day.\n \"\"\"\n if self.current_month() is None:\n return None\n else:\n return self.current_month().days[-1]\n\n def calculate_flextime(self) -> timedelta:\n flextime = self.flextime\n for year in self.years:\n flextime += year.calculate_flextime()\n return flextime\n\n def used_vacation(self, date_string: Optional[str] = None):\n return sum([year.used_vacation(date_string=date_string)\n for year in self.years])\n\n def vacation_left(self, date_string: Optional[str] = None):\n if date_string is None:\n if self.today() is None:\n today = self.employed_date\n else:\n today = self.today().date\n else:\n today = datetime.strptime(date_string, \"%Y-%m-%d\").date()\n\n first_vacation_month = date(\n self.employed_date.year + (\n self.employed_date.month > self.vacation_month),\n self.vacation_month,\n 1)\n\n years_worked = 0\n if today >= first_vacation_month:\n years_worked += (\n (first_vacation_month.month -\n self.employed_date.month) % 12) / 12\n\n years_worked += max(\n today.year - first_vacation_month.year - (\n today.month < self.vacation_month),\n 0)\n\n total_vacation_days = (self.payed_vacation * years_worked +\n self.extra_vacation)\n\n unused_vacation_days = total_vacation_days - self.used_vacation(\n date_string=today.isoformat())\n\n return int(unused_vacation_days)\n\n def all_days(self) -> List[Day]:\n return [day for year in self.years\n for month in year.months\n for day in month.days]\n\n def __str__(self):\n user_string = \"\"\"{user.name}\n{}\nEmployment: {user.employment} %\nEmployed date: {user.employed_date}\nVacation month: {user.vacation_month}\"\"\".format(\n \"-\" * len(self.name), user=self)\n return user_string\n","sub_path":"chrono/user.py","file_name":"user.py","file_ext":"py","file_size_in_byte":6380,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"96026927","text":"#!/usr/bin/env python\n\nimport pandas as pd\nimport numpy as np\nimport networkx as nx\nfrom msda import preprocessing, phospho_network as pn, \\\n process_phospho_ms as ppm\n\ndef p(x):\n \"\"\"Process the Protein Id string in the df_24hr\n to the UniProtKB-AC id. It removes isoform information.\"\"\"\n return x.split(\"|\")[1].split('-')[0]\n\n\nfilename_tc = \"Mature_Neuron_MT_pMS_Stabilizer1_2_time_course_ys.xlsx\"\n\ndf_tc = pd.read_excel(\"../input/\" + filename_tc)\n\n# Short aliases to help keep everything under 80 columns\nEpoB0 = \"DIV 14 EpoB 0 (stabilizer 1)\"\nEpoB60 = \"DIV 14 EpoB 60 min (stabilizer 1)\"\nEpoB60FC = \"EpoB 60 min FC\"\nEpoB60lFC = \"EpoB60 abs(logFC)\"\n\n# Filter out everything with Max Score < 20\ndef safe_maxscore_cutoff(x, cutoff=20.0):\n \"\"\"Convert get the max score for the peptide. In cases of multiple\n phosphorylation sites the string will be semicolon delimited; in this\n case split the string into multiple floats and use the maximum one as\n the max score.\"\"\"\n if ';' in x:\n values = [float(v) for v in x.split(';')]\n else:\n values = [float(x)]\n return max(values) >= cutoff\n\n\ndef dump_site_prizes(df_tc):\n # Separate multiply phosphorylated from singly phosphorylated peptides\n site_df = df_tc[[\"ID\", \"Site Position\", \"EpoB60 abs(logFC)\"]]\n\n # Some Pandas magic to split multiply phosphorylated sites into multiple\n # rows: see https://stackoverflow.com/questions/17116814/pandas-how-do-i-split-text-in-a-column-into-multiple-rows\n s = df_tc['Site Position'].str.split(';').apply(pd.Series, 1).stack()\n s.index = s.index.droplevel(-1)\n s.name = 'Site Position'\n del df_tc['Site Position']\n df_tc = df_tc.join(s)\n # Now take the max abs(fc) for any given site\n # Tip from https://stackoverflow.com/questions/15705630/python-getting-the-row-which-has-the-max-value-in-groups-using-groupby\n df_tc = df_tc.sort_values(EpoB60lFC, ascending=False).drop_duplicates(\n ['gene_symbol', 'Site Position'])\n site_df = df_tc[['ID', 'Site Position', 'EpoB60 abs(logFC)']]\n site_df.columns = ['name', 'site', 'abs_fc']\n site_df = site_df.sort_values('abs_fc', ascending=False)\n site_df.to_csv('../work/site_prizes.txt', sep='\\t', header=True,\n index=False)\n\n\nif __name__ == '__main__':\n filename_tc = \"Mature_Neuron_MT_pMS_Stabilizer1_2_time_course_ys.xlsx\"\n filename_24hr = \"Mature_Neuron_MT_pMS_destabilzer_stablizer_24hr_ys.xlsx\"\n\n df_24hr = pd.read_excel(\"../input/\" + filename_24hr)\n\n # Use MSDA to read and preprocess the dataset\n df_tc = preprocessing.read_dataset(\"../input/\" + filename_tc)\n # Some columns have to be renamed because the data does not conform\n # to the expectations of the latest MSDA\n df_tc = df_tc.rename(columns={'Max Score': 'max_score',\n 'Protein Id': 'Uniprot_Id'})\n\n # Short aliases to help keep everything under 80 columns\n EpoB0 = \"DIV 14 EpoB 0 (stabilizer 1)\"\n EpoB60 = \"DIV 14 EpoB 60 min (stabilizer 1)\"\n EpoB60FC = \"EpoB 60 min FC\"\n EpoB60lFC = \"EpoB60 log2(FC)\"\n EpoB60abslFC = \"EpoB60 abs(log2(FC))\"\n # Create a column for absolute log fold change\n df_tc[EpoB60FC] = df_tc[EpoB60]/df_tc[EpoB0]\n df_tc[EpoB60lFC] = df_tc[EpoB60FC].apply(lambda x: np.log2(x))\n df_tc[EpoB60abslFC] = df_tc[EpoB60lFC].apply(lambda x: np.abs(x))\n\n # File contains matching of UniprotKB-AC ID's and other identifiers. We use\n # this because we do not trust the HGNC ID's in the original files. \n ident_df = pd.read_csv(\"../input/HUMAN_9606_idmapping.dat\", sep=\"\\t\",\n names=[\"UniProtKB-AC\", \"ID_type\", \"ID\"], dtype=str)\n uniprot_genename = ident_df[ident_df[\"ID_type\"]==\"Gene_Name\"]\n uniprot_genename = uniprot_genename[['UniProtKB-AC', 'ID']]\n\n p = lambda x: x.split(\"|\")[1].split('-')[0]\n df_tc[\"UniProtKB-AC\"] = df_tc[\"Uniprot_Id\"].apply(p)\n\n df_tc = pd.merge(left=df_tc, right=uniprot_genename,\n how=\"inner\", on=\"UniProtKB-AC\")\n\n x = df_tc[df_tc['gene_symbol'] != df_tc['ID']]\n # x gives the set of 91 genes with mismatch between UniProtKB-AC and\n # gene_symbol\n\n # Now, use MSDA to filter sites to a max score of 13\n df_tc = ppm.filter_max_score(df_tc, max_score_cutoff=13.0)\n # Split compound sites into separate rows\n df_tc = pn.split_sites(df_tc)\n # Get the largest fold change for sites (which may appear\n df_tc = df_tc.sort_values(EpoB60abslFC, ascending=False).drop_duplicates(\n ['Gene_Symbol', 'Site'])\n\n # Dump a formatted list of sites as GENE_S111 for KEA analysis\n kea_sites = df_tc['Identifier'].apply(lambda x: x.rsplit('_', 1)[0])\n kea_sites.to_csv('../work/sorted_site_list.txt', header=False, index=False)\n\n # Dump sites with fold changes for GSEA\n gsea_sites = df_tc[['Identifier', EpoB60lFC]]\n gsea_sites['Identifier'] = gsea_sites['Identifier'].apply(\n lambda x: x.rsplit('_', 1)[0])\n gsea_sites.to_csv('../work/gsea_sites.rnk', header=False, index=False,\n sep='\\t')\n\n # -----------\n input_df = df_tc[[\"ID\", EpoB60abslFC]]\n input_df.columns = [\"name\", \"prize\"]\n input_df = input_df.sort_values(\"prize\", ascending=False)\n\n # For genes with multiple isoforms and/or phosphosites,\n # only keep row with max value of abs(logFC)\n input_df = pd.DataFrame(input_df.groupby([\"name\"],\n sort=False)[\"prize\"].max())\n input_df.reset_index(level=0, inplace=True)\n\n # Give UBC a negative prize. Otherwise it's too easy to end up with a\n # bicycle spoke graph centered at UBC.\n input_df.loc[input_df['name']=='UBC', 'prize'] = -10000\n\n # Generate prize file\n input_df.to_csv(\"../work/prize.txt\", sep=\"\\t\", header=True, index=False)\n\n\n # Generate a text file containing the list of measured genes. This can be\n # used to highlight the measured genes in cytoscape\n measured_genes = input_df['name']\n measured_genes.to_csv('../work/measured_genes.txt', header=False,\n index=False)\n\n","sub_path":"tubulin/src/generate_prize_file.py","file_name":"generate_prize_file.py","file_ext":"py","file_size_in_byte":6179,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"358534656","text":"# -*- coding: utf-8 -*-\n\n# ----------------------------------------\n# About error code\nCONF_CODE = {\n \"success\" : ( 0 , \"ok\" ),\n \"unknown\" : ( 101 , \"unknown error\" ),\n \"invalid_method\" : ( 102 , \"invalid interfaceName\" ),\n \"para_miss\" : ( 103 , \"miss parameter\" ),\n \"para_error\" : ( 104 , \"para parse error\" ),\n \"sql_error\" : ( 105 , \"exec sql error\" ),\n \"invalid_user_uin\" : ( 1001, \"no such userUin\" ),\n \"invalid_op_mode\" : ( 1101, \"opMode can only be 0/1/2\" ),\n \"invalid_secret_id\" : ( 1102, \"no such secret\" ),\n \"invalid_secret_status_enable\" : ( 1103, \"only disenabled secret can be enabled\" ),\n \"invalid_secret_status_disenable\" : ( 1104, \"only enabled secret can be disenabled\" ),\n \"invalid_secret_status_delete\" : ( 1105, \"only disenabled secret can be deleted\" )\n}\n","sub_path":"src/py_proj/secret/conf/conf_code.py","file_name":"conf_code.py","file_ext":"py","file_size_in_byte":1194,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"566755235","text":"# Copyright 2019 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\"\"\"Benchmark result object.\"\"\"\n\n\nclass BenchmarkResult(object):\n \"\"\"Holds results of a benchmark test.\"\"\"\n\n def __init__(self):\n self.total_time = None\n self.top_1 = None\n self.top_5 = None\n self.exp_per_second = None\n self.other_results = []\n\n def add_top_1(self, result, expected_min=None, expected_max=None):\n \"\"\"Adds a top_1 result entry.\"\"\"\n self.add_other_quality(\n result, 'top_1', expected_min=expected_min, expected_max=expected_max)\n\n def add_top_5(self, result, expected_min=None, expected_max=None):\n \"\"\"Adds a top_5 result entry.\"\"\"\n self.add_other_quality(\n result, 'top_5', expected_min=expected_min, expected_max=expected_max)\n\n def add_examples_per_second(self, result):\n \"\"\"Adds examples per second result entry.\"\"\"\n self.add_result(result, 'exp_per_second', 'exp_per_second')\n\n def add_other_quality(self,\n result,\n quality_unit,\n expected_min=None,\n expected_max=None):\n \"\"\"Adds a quality entry to the results list.\n\n Args:\n result: result to be recorded\n quality_unit: type of quality result, e.g. top_1\n expected_min: minimum expected value to determine pass/fail of result.\n expected_max: max expected value to determine pass/fail of result.\n \"\"\"\n result_status = None\n if expected_min or expected_max:\n result_status = 'FAILED'\n if expected_min and expected_max:\n if result >= expected_min and result <= expected_max:\n result_status = 'PASS'\n elif expected_min:\n if result >= expected_min:\n result_status = 'PASS'\n elif expected_max:\n if result <= expected_max:\n result_status = 'PASS'\n\n self._add_result(\n self.other_results,\n result,\n 'quality',\n quality_unit,\n expected_min=expected_min,\n expected_max=expected_max,\n result_status=result_status)\n\n def add_result(self, result, result_type, result_unit):\n \"\"\"Add benchmark result to list.\"\"\"\n self._add_result(self.other_results, result, result_type, result_unit)\n\n def get_results(self):\n \"\"\"Returns top_1 result entry or none if not set.\"\"\"\n result_list = []\n if self.top_1:\n self._add_result(result_list, self.top_1, 'quality', 'top_1')\n if self.top_5:\n self._add_result(result_list, self.top_5, 'quality', 'top_5')\n if self.exp_per_second:\n self._add_result(result_list, self.exp_per_second, 'exp_per_second',\n 'exp_per_second')\n result_list.extend(self.other_results)\n\n return result_list\n\n def _add_result(self,\n result_list,\n result,\n result_type,\n result_unit,\n expected_min=None,\n expected_max=None,\n result_status=None):\n \"\"\"Adds result to result list passed.\"\"\"\n if result:\n result_dict = {}\n result_dict['result'] = result\n result_dict['result_type'] = result_type\n result_dict['result_unit'] = result_unit\n if expected_min:\n result_dict['expected_min'] = expected_min\n if expected_max:\n result_dict['expected_max'] = expected_max\n if result_status:\n result_dict['result_status'] = result_status\n result_list.append(result_dict)\n","sub_path":"perfzero/lib/perfzero/report/benchmark_result.py","file_name":"benchmark_result.py","file_ext":"py","file_size_in_byte":4059,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"424197601","text":"import datetime\nimport os\n\nimport tensorflow as tf\nfrom DogImageGenerator import DogImageGenerator\nfrom keras.applications import MobileNet\nfrom keras.layers import Dense, GlobalAveragePooling2D\nfrom keras.models import Model\nfrom keras_preprocessing.image import ImageDataGenerator\nfrom tensorflow.compat.v1 import ConfigProto\nfrom tensorflow.compat.v1 import InteractiveSession\nfrom Dog_dict import Dogs_all\n\n# config session and gpu along with tensorflow\nconfig = ConfigProto()\nconfig.gpu_options.allow_growth = True\nsession = InteractiveSession(config=config)\nMAIN_DIR = os.path.dirname(os.getcwd())\ngpu_options = tf.GPUOptions(per_process_gpu_memory_fraction=0.9)\nsess = tf.Session(config=tf.ConfigProto(gpu_options=gpu_options))\nlog_dir = os.path.join(MAIN_DIR, 'logs', 'fit', datetime.datetime.now().strftime(\"%Y%m%d-%H%M%S\"))\ntensorboard_callback = tf.keras.callbacks.TensorBoard(log_dir=log_dir, histogram_freq=0)\n\n# config training\nall_data = True\nepochs = 1\nbatch_size = 6\ndata_augmentation = True\nsave_dir = os.path.join(os.path.dirname(os.getcwd()), 'models')\ndata_dir = os.path.join(MAIN_DIR, 'np_data')\nnum_classes = len(Dogs_all)\nDogGenerator = DogImageGenerator(batch_size)\n\ninput_shape = DogGenerator.WIDTH, DogGenerator.HEIGHT\n\n# imports the mobilenet model and discards the last 1000 neuron layer\nbase_model = MobileNet(weights='imagenet',\n include_top=False)\n\n# add cutom output layers\nx = base_model.output\nx = GlobalAveragePooling2D()(x)\nx = Dense(1024, activation='relu')(x)\nx = Dense(1024, activation='relu')(x)\nx = Dense(512, activation='relu')(x)\npreds = Dense(num_classes, activation='softmax')(x)\nmodel = Model(inputs=base_model.input, outputs=preds)\n\n# compile model\nmodel.compile(loss='categorical_crossentropy',\n optimizer='adam',\n metrics=['accuracy'])\n\n# train with custom generator\nsteps = DogGenerator.images_number // batch_size\nmodel.fit_generator(generator=DogGenerator.generate_train_batch(),\n validation_data=DogGenerator.generate_test_batch(),\n steps_per_epoch=steps,\n validation_steps=steps // 2,\n epochs=epochs,\n callbacks=[tensorboard_callback])\n","sub_path":"src/transfer_network_gen.py","file_name":"transfer_network_gen.py","file_ext":"py","file_size_in_byte":2234,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"495628748","text":"#https://github.com/AkayamaNao/limu-maco.git\nfrom os import environ\nfrom pathlib import Path\nimport psycopg2\nimport subprocess\n\ntestmode=0\n\nDEBUG = True\n\nSWAGGER_UI_DOC_EXPANSION = 'list'\nRESTPLUS_VALIDATE = True\n\nJSON_AS_ASCII = False\n\nUPLOADED_CONTENT_DIR = Path(\"upload\")\n\n# for maco_system\nupdate_time = 20\ngroup_token = 'lhFEwq81neUCR4dBS3XO2d4dfLvAeLqwk63vN00fJ8n'\nmaco_token = 'D9mwMqqQf2dgxS9kJNbIFh0djqCT7n4ywDyHS2ZGZFS'\nmy_token='rL71jYoAcCK3pgRh4JmMzGVPdO8DDKd5y6gk13AVvYO'\n\nroot_password = '88248075a3514f106c0c16ee16aa06a22b56670b7b01ee56da49772218b1b289'\n\nif testmode==1:\n group_token=my_token\n maco_token=my_token\n # maco_db = 'postgres://vojmwqggktbwcq:b68a7729d76ef371569e77a475f9aeab3ef371aa15b3ba128c3ab828cedf5bf8@ec2-54-83-201-84.compute-1.amazonaws.com:5432/ddm0m8tb2f57j8'\n maco_db = 'postgres://yezwtzucqwwbwb:101e900d0112cf656aac45392643e64a5cf159f45df42d03687d40c2c45cc4ed@ec2-23-21-160-38.compute-1.amazonaws.com:5432/d86eg6lncc5u8b'\nelse:\n proc = subprocess.Popen('printenv DATABASE_URL', stdout=subprocess.PIPE, shell=True)\n maco_db = proc.stdout.read().decode('utf-8').strip()\n\n#SQLALCHEMY_DATABASE_URI = 'postgres://{user}:{password}@{host}/{database}'.format(**dbconf.maco_db)\nSQLALCHEMY_DATABASE_URI = maco_db\nSQLALCHEMY_TRACK_MODIFICATIONS = True","sub_path":"settings.py","file_name":"settings.py","file_ext":"py","file_size_in_byte":1298,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"122954110","text":"#!/usr/bin/python\n\ndef pars(fin_file):\n matr=[]\n with open(fin_file) as fin:\n for line in fin:\n matr.append(line.split('\\t'))\n\n fout=[]\n for i in range(len(matr)):\n for j in range(len(matr[i])):\n try:\n fout[j].append(matr[i][j])\n except:\n fout.append([])\n fout[j].append(matr[i][j])\n return fout\n","sub_path":"libs/input_parser.py","file_name":"input_parser.py","file_ext":"py","file_size_in_byte":403,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"313637821","text":"import numpy\nfrom sklearn.svm import LinearSVC\nfrom pymongo import MongoClient\n\nfrom ..doc import Doc\nfrom ..features import mapping\nfrom ..model import model\n\nimport logging\nlog = logging.getLogger()\n\nclass TrainMentionClassifier(object):\n \"\"\" Abstract class for training an SVM classifier over mentions in a corpus of documents. \"\"\"\n def __init__(self, corpus, tag, feature, classifier_id):\n if corpus == None:\n # todo: multi corpus training\n raise NotImplementedError \n\n self.corpus_id = corpus\n self.tag_filter = tag\n self.features = feature\n self.mapping = 'PolynomialMapper'\n self.classifier_id = classifier_id\n self.client = MongoClient()\n \n # todo: parameterise hyperparameters\n self.hparams = {\n 'C': 0.0316228,\n 'penalty': 'l2',\n 'loss': 'l1'\n }\n\n self.hparams['dual'] = self.hparams['penalty'] == 'l2' and \\\n self.hparams['loss'] == 'l1'\n \n def __call__(self):\n log.info('Fetching training docs (%s-%s)...', self.corpus_id or 'all', self.tag_filter or 'all') \n docs = self.get_training_docs() \n \n log.info('Computing feature statistics over %i documents...', len(docs))\n mapper_params = self.compute_mapper_params(docs)\n mapper = mapping.FEATURE_MAPPERS[self.mapping](**mapper_params)\n\n log.info('Building training set...')\n X, y = [], []\n for x, cls in self.iter_instances(mapper(doc) for doc in docs):\n X.append(x)\n y.append(cls)\n\n log.info('Fitting model over %i instances...', len(y))\n svc = LinearSVC(**self.hparams)\n svc.fit(X, y)\n\n correct = sum(1.0 for i, _y in enumerate(svc.predict(X)) if y[i] == _y)\n log.info('Training set pairwise classification: %.1f%% (%i/%i)', correct*100/len(y), int(correct), len(y))\n\n # todo: refactor to avoid dependency on internal classifier representation here\n model.LinearClassifier.create(self.classifier_id, {\n 'weights': list(svc.coef_[0]),\n 'intercept': svc.intercept_[0],\n 'mapping': {\n 'name': mapper.__class__.__name__,\n 'params': mapper_params\n },\n 'corpus': self.corpus_id,\n 'tag': self.tag_filter\n })\n\n log.info('Done.')\n\n def compute_mapper_params(self, docs): \n means, stds = [], []\n for f in self.features:\n raw = [c.features[f] for d in docs for m in d.chains for c in m.candidates]\n means.append(numpy.mean(raw))\n stds.append(numpy.std(raw))\n\n return {\n 'features': self.features,\n 'means': means,\n 'stds': stds\n }\n\n def get_training_docs(self):\n store = self.client.docs[self.corpus_id]\n \n flt = {}\n if self.tag_filter != None:\n flt['tag'] = self.tag_filter\n\n # keeping all docs in memory could be problematic for large datasets\n # but simplifies computation of mapper parameters. todo: offline mapper prep\n return [Doc.obj(json) for json in store.find(flt)]\n\n @classmethod\n def add_arguments(cls, p):\n p.add_argument('classifier_id', metavar='CLASSIFIER_ID')\n p.add_argument('--corpus', metavar='CORPUS', default=None, required=False)\n p.add_argument('--tag', metavar='TAG', default=None, required=False)\n p.add_argument('--feature', metavar='FEATURE_MODEL', action='append')\n p.set_defaults(cls=cls)\n return p\n","sub_path":"nel/learn/train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":3613,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"643944222","text":"import json\nfrom sqlite3 import Connection\n\nfrom awesome.entity.Library import Library\nfrom awesome.entity.value_objects import Text, Source\n\n\nclass LibraryRepository:\n def __init__(self, connection: Connection):\n self.connection = connection\n\n def find_all(self):\n return self._map(\n self.connection.execute('SELECT * FROM library').fetchall()\n )\n\n def find_all_by_language_id(self, language_id: str):\n return self._map(\n self.connection.execute('''\n SELECT l.*, ll.language_id languages\n FROM library l\n LEFT JOIN library_language ll ON l.id = ll.library_id\n WHERE ll.language_id = '%s'\n ''' % language_id).fetchall()\n )\n\n def find_all_by_tag_id(self, tag_id):\n return self._map(\n self.connection.execute('''\n SELECT l.*, lt.tag tag, group_concat(ll.language_id) languages\n FROM library l\n LEFT JOIN library_tag lt ON l.id = lt.library_id\n LEFT JOIN library_language ll ON l.id = ll.library_id\n WHERE lt.tag = '%s'\n GROUP BY l.id\n ''' % tag_id).fetchall()\n )\n\n def _map(self, data):\n result = []\n\n for item in data:\n lang_object = Library(\n id=item['id'],\n name=item['name'],\n description=Text(json.loads(item['description'])),\n language=item['languages'].split(','),\n source=Source(item['source_type'], item['source_value'])\n )\n\n result.append(lang_object)\n\n return result\n","sub_path":"awesome/repository/LibraryRepository.py","file_name":"LibraryRepository.py","file_ext":"py","file_size_in_byte":1730,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"156401529","text":"import sys,os\n\nfilepath=''\n\n\nif len(sys.argv) <2 :\n\tfilepath=raw_input('Where is your FIle ?')\nelse :\n\tfilepath=sys.argv[1]\n\nif os.path.isfile(filepath)==False:\n\tprint('File not found ')\n\texit()\n\ncont=''\nallids=0\nfiltered=0\n\nwith open(filepath) as strm:\n\tlines=strm.readlines()\n\tallids=len(lines)\n\tfor l in lines:\n\t\tlx=l.strip()\n\t\tif lx.isdigit():\n\t\t\tcont=cont+lx+'\\n'\n\t\t\tfiltered=filtered+1\n\noutput=filepath.replace('.txt','')+'___NumbersOnly_.txt'\nif filtered>0:\n\tstrm2=open(output,'w')\n\tstrm2.write(cont)\n\tstrm2.close()\n\tprint(str(filtered)+'/'+str(allids))\n\tprint('\\nSaved at '+output)\n\n","sub_path":"_Numbers_.py","file_name":"_Numbers_.py","file_ext":"py","file_size_in_byte":591,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"503843213","text":"# Ejercicio 3\n'''\nHacer un programa para intercambiar el valor de 2 variables.\n\nPor ejemplo:\n\n a=10 a=5 \n ->\n b=5 b=10\n'''\n\n# a=10\n# b=5\n# c=0\n\na = input(\"a ->\")\nb = input(\"b ->\")\nc = 0\n\n# c=a\n# a=b\n# b=c\n\na , b = b , a # intercambia el valor\n\nprint(f\"El nuevo valor de 'a' es: {a}\")\nprint(f\"El nuevo valor de 'b' es: {b}\")\n","sub_path":"01-Elementos_basicos/Ejercicio3.py","file_name":"Ejercicio3.py","file_ext":"py","file_size_in_byte":356,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"36581361","text":"# module: TokenRules.py\n\n__author__ = 'Qwaxtel'\n\n# title : message\n# participant actor\n# note left of actor : message\n# right of\n# over\n# actor - > actor : message\n# -- >>\n\nimport re\nimport ply.lex as lex\n\n\n# List of reserved key words\nreserved = {\"title\": \"TITLE\",\n \"participant\": \"PARTICIPANT\",\n \"note\": \"NOTE\",\n \"left of\": \"LEFT_OF\",\n \"right of\": \"RIGHT_OF\",\n \"over\": \"OVER\"}\n\n# List of token names.\ntokens = [\"COMMENT\",\n \"MESSAGE\",\n \"ACTOR\",\n \"LINE\",\n \"DASHED_LINE\",\n \"ARROW\",\n \"OPEN_ARROW\",\n \"ID\"] + list(reserved.values())\n\n# Regular expression for the token ACTOR\nactor_regex = r\"[^\\->:\\n,]+\"\n\n# Regular expression rules used directly by lex\nt_ignore = \" \\t|\"\nt_MESSAGE = r\":[^#\\n]+\"\nt_LINE = r\"-\"\nt_DASHED_LINE = r\"--\"\nt_ARROW = r\">\"\nt_OPEN_ARROW = r\">>\"\n\n\ndef t_ID(t):\n r\"[a-zA-Z_][a-zA-Z_0-9]*\"\n t.type = reserved.get(t.value, \"ID\") # returned default value is \"ID\"\n\n # check if the identifier is actually an ACTOR token\n if t.type == \"ID\" and re.match(actor_regex, t.value):\n t.type = \"ACTOR\"\n\n return t\n\n\n# remove comments\ndef t_COMMENT(t):\n r\"\\#.*\"\n pass\n\n\n# keep track of the line\ndef t_newline(t):\n r\"\\n\"\n t.lexer.lineno += 1\n\n\n# Error handling rule\ndef t_error(t):\n print(\"Illegal character '%s'\" % t.value[0])\n t.lexer.skip(1)\n\ntest = '''\ntitle: This is the title\n# comment\nAlice->Bob: Herro\n'''\n\nlex.lex()\n\nimport ply.yacc as yacc\n\n","sub_path":"TokenRules.py","file_name":"TokenRules.py","file_ext":"py","file_size_in_byte":1539,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"189787082","text":"# -*- coding: utf-8 -*-\n# author:maguichang time:2018/9/14\n\nfrom flask import Flask\nfrom flask_script import Manager, Shell\nfrom flask_mail import Mail, Message\nfrom kafka import KafkaClient\nfrom kafka import KafkaConsumer\nimport threading\nimport datetime\nimport time\nimport json\nimport os\nimport numpy as np\nimport pymysql\nfrom Configlist import *\n#\napp = Flask(__name__)\npara = Config()\nconn2 = pymysql.connect(\n # host = 'localhost',\n host = para.MYSQL_URI,\n port = para.MYSQL_PORT,\n user = para.MYSQL_USER,\n passwd = para.MYSQL_PWD,\n db = para.MYSQL_DB,\n charset = 'utf8'\n)\ncur = conn2.cursor()\napp.config['MAIL_SERVER'] = para.MAIL_SERVER\napp.config['MAIL_PORT'] = para.MAIL_PORT\napp.config['MAIL_USE_TLS'] = True\napp.config['MAIL_USERNAME'] = para.MAIL_USERNAME\napp.config['MAIL_PASSWORD'] = para.MAIL_PASSWORD\n\nmail = Mail(app)\n\nmsg = Message('errInfo', sender=para.MAIL_SENDER, recipients=[para.MAIL_RECIPIENTS])\n\nconsumer1=KafkaConsumer('ads-kafka-nmdb-1',group_id='consumer_errTest3',auto_offset_reset='latest',bootstrap_servers=['10.0.7.38:9092'])\nconsumer2=KafkaConsumer('ads-kafka-nmdb-2',group_id='consumer_errTest3',auto_offset_reset='latest',bootstrap_servers=['10.0.7.38:9092'])\nconsumer25=KafkaConsumer('ads-kafka-nmdb-25',group_id='consumer_errTest3',auto_offset_reset='latest',bootstrap_servers=['10.0.7.38:9092'])\n\n\ndef consumerFunc(consumer_id,fj_name):\n before_msg = \"beforeinfo\"\n for m in consumer_id:\n data = bytes.decode(m.value)\n start = data.find(\"main_task_system_date_time\")\n end = start+53\n data2 = data[:start]+data[end:]\n data3 = data2.replace(\":\",'\":').replace(\"{\",'{\"').replace(\",\",',\"')\n data4 = json.loads(data3)\n t = data4[\"time\"]\n # print(t)\n current_state = data4[\"current_state\"]\n if current_state !=101 and current_state !=122:\n errTime = datetime.datetime.utcfromtimestamp(int(t) / 1000.0 + 28800).strftime('%Y-%m-%d %H:%M:%S.%f')\n list_dic ={\"list1_id\":data4[\"list1_id\"],\"list2_id\":data4[\"list2_id\"],\"list3_id\":data4[\"list3_id\"],\n \"list4_id\":data4[\"list4_id\"],\"list5_id\": data4[\"list5_id\"],\"list6_id\":data4[\"list6_id\"],\n \"list7_id\" :data4[\"list7_id\"],\"list8_id\":data4[\"list8_id\"],\"list9_id\":data4[\"list9_id\"],\n \"list10_id\":data4[\"list10_id\"],\"list11_id\":data4[\"list11_id\"],\"list12_id\":data4[\"list12_id\"],\n \"list13_id\":data4[\"list13_id\"],\"list14_id\":data4[\"list14_id\"],\"list15_id\":data4[\"list15_id\"]}\n s = str(fj_name)\n # print(list_dic)\n # print(s)\n for k,v in list_dic.items():\n if v != 255:\n sql = 'select id,errCode from listErr2 where id ='+str(v)\n cur.execute(sql)\n result1 = cur.fetchall()\n result2 = np.array(result1)\n s = s+'{\"'+k+'\" :'+str(result2[0])+\"},\"\n else:\n pass\n # print(s)\n if \"list\" in s:\n msg.body = s\n if before_msg != msg.body:\n with app.app_context():\n before_msg = msg.body\n msg.body = msg.body+errTime\n mail.send(msg)\n","sub_path":"flask/project/ads_errMail_test.py","file_name":"ads_errMail_test.py","file_ext":"py","file_size_in_byte":3282,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"450221062","text":"\"\"\" This module contains functions able to read raw data from different formats.\n Returns data and header as a couple, with minimal data processing, functions are about formats, \n not the specific instrument or specific header, that are handled in calling functions\n (e.g. from instrument_reader). \n \n functions in this module shouldn't have extra args or kwargs.\n \n\n2018/09/26 New refactoring of data reader. Vincenzo Cotroneo vcotroneo@cfa.harvard.edu\"\"\"\n\nimport numpy as np\nfrom dataIO.fn_add_subfix import fn_add_subfix\n\ndef read_fits(fitsfile):\n \"\"\" Generic fits reader, returns data,x,y.\n \n header is ignored. If `header` is set to True is returned as dictionary.\"\"\"\n from astropy.io import fits\n \n a=fits.open(fitsfile)\n meta=a[0] \n data=meta.data\n a.close()\n \n x= meta.x if hasattr(meta,'x') else np.arange(data.shape[1])\n y= meta.y if hasattr(meta,'y') else np.arange(data.shape[0])\n \n raw = meta.header if hasattr(meta,'header') else meta\n \n return (data,x,y),raw\n \ndef read_sur(file):\n from read_sur_files import readsur\n \"\"\"read a sur file using read_sur_files, that is expected to return a structure\n res.points, .xAxis, .yAxis\"\"\"\n\n res = readsur(file) #in readsur the default is False.\n data,x,y = res.points,res.xAxis,res.yAxis\n del res.points\n del res.xAxis\n del res.yAxis\n\n return (data,x,y),res #stripped of all data information\n \nfrom pySurf.points import get_points,points_find_grid,resample_grid\n\ndef read_csv_points(wfile,*args,**kwargs):\n \"\"\"Read a processed points file in format x,y,z as csv output of analysis routines.\"\"\"\n print(\"read_csv_points is obsolete, use read_csv_data\")\n w0=get_points(wfile,*args,**kwargs)\n w=w0.copy()\n raw=w0\n x,y=points_find_grid(w,'grid')[1]\n pdata=resample_grid(w,matrix=True)\n return (pdata,x,y),raw\n\n\nfrom pySurf.points import matrix_to_points2, points_find_grid, resample_grid\ndef read_csv_data(filename,x=None,y=None,matrix=True,addaxis=False,skip_header=None,delimiter=' '):\n\n \"\"\"return `data, x, y` from generic csv files in xyz or matrix format. \n \n for example for nanovea saved txt (matrix=False) or gwyddion saved matrix (matrix=True, xrange, yrange must be defined).\n \n x, y: added 2018/02/17 make sense only for data in matrix format and allow reading from file\n ovevrriding or setting of values for the x and y axis. allowing modification that would not be \n straightforward on the returned value in `points` format.\n\n input x and y can be None or empty object(calculate from data size), M-element array (must fit data size)\n or range (2-el). If the last two cases (when appropriate axis are passed), they are always used and get priority on what is read from file, be careful to omit them unless you want to alter data. \n \n This way I can e.g. open a matrix file and return points with a modified x y grid. Setting x or y to an empty object rather than to None discards axis from file and use grid indices.\n \n A complete description of the possible options is:\n read and use from file: addaxis=True, x= None\n read and discard from file, use passed: addaxis=True, x=np.array\n read and discard from file, use calculated: addaxis=True, x=[]\n don't read from file, use passed: addaxis=False, x=np.array\n don't read from file, use calculated: addaxis=False, x=None|[]\n \n matrix: if set, assume data are a matrix rather than x,y,z points.\n addaxis: (if matrix is set) can be set to read values for axis in first row and column\n (e.g. if points were saved with default addaxis=True in save_points. \n 2018/02/17 reintroduced xrange even if discorauged. implemented x and y (unused as well) to axis, range \n or indices.\n \n skip_header: passed to `np.genfromtxt`, numbers of lines to consider as header\n delimiter: default=whitespace character to divides columns\n \n 2019/04/09 removed scale and extra keywords, copied from points.get_points to format_reader after standardization. It is a more general version of both read_csv_points and data2D.data_from_txt.\n \"\"\"\n #import pdb\n \n #2014/04/29 added x and y as preferred arguments to xrange and yrange (to be removed).\n if skip_header is None: \n skip=0 \n else: \n skip=skip_header\n \n with open(filename) as myfile: #get first `skip` lines as header\n head = [next(myfile) for x in range(skip)]\n \n mdata=np.genfromtxt(filename,skip_header=skip,delimiter=delimiter) \n \n if (matrix): \n if addaxis:\n yy,mdata=np.hsplit(mdata,[1])\n yy=yy[1:] #discard first corner value\n xx,mdata=np.vsplit(mdata,[1])\n \n # x and y can be None or empty object(calculate from data size), M-element array (must fit data size)\n # or range (2-el). Transform them in M-el vectors \n if x is None:\n try:\n x=xx #it was called with addaxis\n except NameError:\n x=[] #this has size 0\n else: #use provided\n\n if np.size(x) != mdata.shape[1]:\n if np.size(x) == 2:\n x=np.linspace(x[0],x[1],mdata.shape[1]) \n else:\n raise ValueError(\"X is not correct size (or 2-el array)\")\n if np.size(x) == 0: #use calculated or read\n x = np.arange(mdata.shape[1]) \n \n if y is None:\n try:\n y=yy #it was called with addaxis\n except NameError:\n y=[]\n else: #use provided\n if np.size(y) != mdata.shape[0]:\n if np.size(y) == 2:\n y=np.linspace(y[0],y[1],mdata.shape[0]) \n else:\n raise ValueError(\"Y is not correct size (or 2-el array)\")\n\n if np.size(y) == 0:\n y = np.arange(mdata.shape[0])\n \n else:\n xx,yy=points_find_grid(wmdata,'grid')[1]\n if np.size(x) == 0: x=xx\n if np.size(y) == 0: y=yy \n mdata=resample_grid(mdata,xgrid=x,ygrid=y,matrix=True)\n \n \n return (mdata,x,y),head \n \n \n\n\n## location of test input and output data,\n## for economy during development, hard coded path.\n#testfolder=r'G:\\My Drive\\libraries\\python\\userKov3\\pySurf\\test' \n \ndef test_reader(file,reader,outfolder=None,infolder=None,**kwargs):\n \"\"\"called without `raw` flag, return data,x,y. Infolder is taken\n from file or can be passed (e.g. to point to local test data).\"\"\"\n \n import os\n import matplotlib.pyplot as plt\n from pySurf.data2D import plot_data\n \n if infolder is None:\n infolder=os.path.dirname(file) \n \n df=os.path.join(infolder,file)\n res,header=reader(df,**kwargs)\n print(\"returned values\",[r.shape for r in res],header)\n \n plot_data(res[0],res[1],res[2])\n if outfolder is not None:\n if outfolder == \"\" : \n display(plt.gcf()) \n else: \n outname=os.path.join(infolder,outfolder,os.path.basename(df))\n os.makedirs(os.path.dirname(outname),exist_ok=True)\n plt.savefig(fn_add_subfix(outname,'','.png'))\n return res,header\n\t\ndef csv_points_reader(wfile,*args,**kwargs):\n \"\"\"Read a processed points file in format x,y,z as csv output of analysis routines.\"\"\"\n w0=get_points(wfile,*args,**kwargs)\n w=w0.copy()\n x,y=points_find_grid(w,'grid')[1]\n pdata=resample_grid(w,matrix=True)\n return pdata,x,y\n\ndef csv_zygo_reader(wfile,*args,**kwargs):\n \"\"\"Read a processed points file in format x,y,z as csv output of analysis routines.\"\"\"\n w0=get_points(wfile,*args,**kwargs)\n w=w0.copy()\n x,y=points_find_grid(w,'grid')[1]\n pdata=resample_grid(w,matrix=True)\n return pdata,x,y\n\n\neegKeys = [\"FP3\", \"FP4\"]\ngyroKeys = [\"X\", \"Y\"]\n\n# 'Foo' is ignored\ndata = {\"FP3\": 1, \"FP4\": 2, \"X\": 3, \"Y\": 4, \"Foo\": 5}\n\nfilterByKey = lambda keys: {x: data[x] for x in keys}\neegData = filterByKey(eegKeys)\ngyroData = filterByKey(gyroKeys)\n\nprint(eegData, gyroData) # ({'FP4': 2, 'FP3': 1}, {'Y': 4, 'X': 3})\n\nfilterByKey2 = lambda data,keys : {key: data[key] for key in keys if key in data}\n\nprint (filterByKey(eegKeys)) # {'FP4': 2, 'FP3': 1}\n","sub_path":"pySurf/readers/old/readers_dev/readers/format_reader.py","file_name":"format_reader.py","file_ext":"py","file_size_in_byte":8332,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"228883546","text":"\"\"\"\nSample Parrot Bot\n\nThis bot responds to any message by repeated what was said to it.\n\nSee ./all-config.py for all config available\n\"\"\"\n__name__ = 'localConfig'\n__package__ = 'ringcentral_bot_framework'\n\nimport copy\nimport time\n\ndef botJoinPrivateChatAction(bot, groupId, user, dbAction):\n \"\"\"\n This is invoked when the bot is added to a private group. \n \"\"\"\n bot.sendMessage(\n groupId,\n {\n 'text': f'Hello, I am a BOT Poly, I will repeat your message as requested. Please reply \"![:Person]({bot.id}) the-message-you-want-me-to-say\" if you want me to say anything.'\n }\n )\n\ndef botGotPostAddAction(\n bot,\n groupId,\n creatorId,\n user,\n text,\n dbAction,\n handledByExtension,\n event\n):\n \"\"\"\n This is invoked when the user sends a message to the bot.\n \"\"\"\n st = f'![:Person]({bot.id}) '\n if not st in text or handledByExtension:\n return\n ntxt = text.replace(st, '', 1)\n if f'![:Person]({bot.id})' in text:\n bot.sendMessage(\n groupId,\n {\n 'text': ntxt\n }\n )\n\n","sub_path":"bot.py","file_name":"bot.py","file_ext":"py","file_size_in_byte":1021,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"471571115","text":"import os\nimport argparse\n\nimport torch\nimport torchvision\n\nimport numpy as np\nimport pandas as pd\n\nfrom torch import optim\nfrom torch.optim.lr_scheduler import CosineAnnealingLR\nfrom torch.utils.data import SubsetRandomSampler\nfrom dataset_helpers import set_random_generators_seed\nfrom get_dataset import GetUnlabeledDataForPIRL\nfrom models import pirl_resnet\nfrom train_test_helper import PIRLModelTrainTest\n\nlog_save_folder = '/content/drive/My Drive/self_dl/log_data'\nmodel_file_path = '/content/drive/My Drive/self_dl/pre_train_subsample/'\n\ndef log_experiment(exp_name, n_epochs, train_losses, val_losses, train_accs, val_accs):\n observations_df = pd.DataFrame()\n observations_df['epoch count'] = [i for i in range(1, n_epochs + 1)]\n observations_df['train loss'] = train_losses\n observations_df['val loss'] = val_losses\n observations_df['train acc'] = train_accs\n observations_df['val acc'] = val_accs\n observations_file_path = os.path.join(log_save_folder, exp_name + '_observations.csv')\n observations_df.to_csv(observations_file_path)\n\n\nif __name__ == '__main__':\n\n # Training arguments\n parser = argparse.ArgumentParser(description='Pre train script for PIRL task')\n parser.add_argument('--num-scene', type=int, default=106, help='number of scenes')\n parser.add_argument('--model-type', type=str, default='res18', help='backbone architecture')\n parser.add_argument('--batch-size', type=int, default=128, metavar='N',\n help='input batch size')\n parser.add_argument('--epochs', type=int, default=100, metavar='N',\n help='number of epochs to train (default: 100)')\n parser.add_argument('--lr', type=float, default=0.01, metavar='LR',\n help='learning rate (default: 0.01)')\n parser.add_argument('--weight-decay', type=float, default=5e-4,\n help='Weight decay constant (default: 5e-4)')\n parser.add_argument('--tmax-for-cos-decay', type=int, default=70)\n parser.add_argument('--warm-start', type=bool, default=False)\n parser.add_argument('--count-negatives', type=int, default=6400,\n help='No of samples in memory bank of negatives')\n parser.add_argument('--beta', type=float, default=0.5, help='Exponential running average constant'\n 'in memory bank update')\n parser.add_argument('--non-linear-head', type=bool, default=False,\n help='If true apply non-linearity to the output of function heads '\n 'applied to resnet image representations')\n parser.add_argument('--temp-parameter', type=float, default=0.07, help='Temperature parameter in NCE probability')\n parser.add_argument('--cont-epoch', type=int, default=0, help='Epoch to start the training from, helpful when using'\n 'warm start')\n parser.add_argument('--experiment-name', type=str, default='e1_resnet50_')\n args = parser.parse_args()\n\n # Set random number generation seed for all packages that generate random numbers\n set_random_generators_seed()\n\n # Identify device for holding tensors and carrying out computations\n device = torch.device(\"cuda:0\" if torch.cuda.is_available() else \"cpu\")\n\n # Define train_set, val_set objects\n scene_index = np.arange(args.num_scene)\n image_folder = '/content/drive/My Drive/self_dl/student_data/data'\n train_set = GetUnlabeledDataForPIRL(image_folder=image_folder, scene_index=scene_index, first_dim='image')\n val_set = GetUnlabeledDataForPIRL(image_folder=image_folder, scene_index=scene_index, first_dim='image')\n\n\n # Define train and validation data loaders\n len_train_set = len(train_set)\n train_indices = list(range(len_train_set))\n np.random.shuffle(train_indices)\n\n\n train_indices = train_indices[:len_train_set]\n val_indices = train_indices[len_train_set:]\n\n\n train_sampler = SubsetRandomSampler(train_indices)\n val_sampler = SubsetRandomSampler(val_indices)\n\n train_loader = torch.utils.data.DataLoader(train_set, batch_size=args.batch_size, sampler=train_sampler,\n num_workers=8)\n val_loader = torch.utils.data.DataLoader(val_set, batch_size=args.batch_size, sampler=val_sampler,\n num_workers=8)\n\n # Train required model using data loaders defined above\n epochs = args.epochs\n lr = args.lr\n weight_decay_const = args.weight_decay\n\n # If using Resnet18\n model_to_train = pirl_resnet(args.model_type, args.non_linear_head)\n\n # Set device on which training is done. Plus optimizer to use.\n model_to_train.to(device)\n sgd_optimizer = optim.SGD(model_to_train.parameters(), lr=lr, momentum=0.9, weight_decay=weight_decay_const)\n scheduler = CosineAnnealingLR(sgd_optimizer, args.tmax_for_cos_decay, eta_min=1e-4, last_epoch=-1)\n\n # Initialize model weights with a previously trained model if using warm start\n if args.warm_start and os.path.exists(model_file_path):\n model_to_train.load_state_dict(torch.load(model_file_path, map_location=device))\n\n # Start training\n all_images_mem = np.random.randn(len_train_set, 128)\n model_train_test_obj = PIRLModelTrainTest(\n model_to_train, device, model_file_path, all_images_mem, train_indices, val_indices, args.count_negatives,\n args.temp_parameter, args.beta\n )\n train_losses, val_losses, train_accs, val_accs = [], [], [], []\n for epoch_no in range(args.cont_epoch, args.cont_epoch + epochs):\n train_loss, train_acc, val_loss, val_acc = model_train_test_obj.train(\n sgd_optimizer, epoch_no, params_max_norm=4,\n train_data_loader=train_loader, val_data_loader=val_loader,\n no_train_samples=len(train_indices), no_val_samples=len(val_indices)\n )\n train_losses.append(train_loss)\n val_losses.append(val_loss)\n train_accs.append(train_acc)\n val_accs.append(val_acc)\n scheduler.step()\n\n # Log train-test results\n log_experiment(args.experiment_name, args.epochs, train_losses, val_losses, train_accs, val_accs)\n","sub_path":"pretrain_obj/pretrain/pirl_train.py","file_name":"pirl_train.py","file_ext":"py","file_size_in_byte":6240,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"256388195","text":"class Hero:\n def __init__(self, name, health):\n self.name = name\n self.health = health\n\n def defend(self, damage):\n self.health = self.health - damage\n if self.health <= 0:\n self.health = 0\n return f'{self.name} was defeated'\n\n def heal(self, amount):\n self.health += amount\n\n\nhero = Hero(\"Peter\", 100)\nprint(hero.defend(50))\nhero.heal(50)\nprint(hero.defend(99))\nprint(hero.defend(1))\n\n# import unittest\n#\n#\n# class Tests(unittest.TestCase):\n# def test_init(self):\n# hero = Hero(\"Alexander\", 75)\n# self.assertEqual(hero.name, \"Alexander\")\n# self.assertEqual(hero.health, 75)\n#\n# def test_attack_success(self):\n# hero = Hero(\"Alexander\", 75)\n# hero.defend(20)\n# self.assertEqual(hero.health, 55)\n#\n# def test_attack_killed(self):\n# hero = Hero(\"Alexander\", 75)\n# res = hero.defend(100)\n# self.assertEqual(hero.health, 0)\n# self.assertEqual(res, \"Alexander was defeated\")\n#\n# def test_heal(self):\n# hero = Hero(\"Alexander\", 5)\n# hero.heal(20)\n# self.assertEqual(hero.health, 25)\n#\n#\n# if __name__ == \"__main__\":\n# unittest.main()\n","sub_path":"defining_classes/13.hero.py","file_name":"13.hero.py","file_ext":"py","file_size_in_byte":1218,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"435941015","text":"import os\n\n\nclass CoinImageUtil:\n\n @staticmethod\n def get_path(a, *p):\n return os.path.join(a, *p)\n\n @staticmethod\n def get_coin_image_by_currency(currency: str):\n currency_lower = currency.lower()\n file_name = 'coin-{}.png'.format(currency_lower)\n return CoinImageUtil.get_path('resources', 'img', file_name)\n","sub_path":"app_tools/coin_img_util.py","file_name":"coin_img_util.py","file_ext":"py","file_size_in_byte":350,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"188870842","text":"'''\nCreated by Andrew Melo on Aug 8, 2012\n\n'''\nfrom AsyncStageOut.TransferWorker import TransferWorker\nfrom WMCore.Database.CMSCouch import CouchServer\nfrom WMCore.WMFactory import WMFactory\n\nimport random, logging\n\n# I think I want this as a module-level global to allow external\n# users (i.e. unittests) to properly change things\n\nfailProbability = 0.0\ndef setFailProbability( value ):\n global failProbability\n failProbability = value\n\ndef getFailProbability():\n global failProbability\n return failProbability\n\nclass FakeTransferWorker(TransferWorker):\n '''\n When monkeypatched into TransferDaemon, this will replace the \"normal\" TransferWorker\n and allow for unittests that don't actually call FTS\n \n this should be the minimal things to fake out running FTS\n '''\n\n\n def __init__(self, user, tfc_map, config):\n \"\"\"\n store the user and tfc the worker\n \"\"\"\n self.user = user[0]\n self.group = user[1]\n self.role = user[2]\n self.tfc_map = tfc_map\n self.config = config \n server = CouchServer(self.config.couch_instance)\n self.db = server.connectDatabase(self.config.files_database)\n logging.basicConfig(level=config.log_level)\n self.logger = logging.getLogger('AsyncTransfer-Worker-%s' % self.user)\n query = {'group': True,\n 'startkey':[self.user], 'endkey':[self.user, {}, {}]}\n self.userDN = self.db.loadView('AsyncTransfer', 'ftscp', query)['rows'][0]['key'][5]\n self.pfn_to_lfn_mapping = {}\n self.max_retry = config.max_retry\n # Set up a factory for loading plugins\n self.factory = WMFactory(self.config.pluginDir, namespace = self.config.pluginDir)\n\n def command(self):\n \"\"\"\n For each job the worker has to complete:\n Delete files that have failed previously\n Create a temporary copyjob file\n Submit the copyjob to the appropriate FTS server\n Parse the output of the FTS transfer and return complete and failed files for recording\n \"\"\"\n self.logger.info(\"beginning command\")\n jobs = self.files_for_transfer()\n transferred_files = []\n failed_files = []\n\n failed_to_clean = {}\n\n #Loop through all the jobs for the links we have\n for link, copyjob in jobs.items():\n self.logger.info(\"checking copyjob\")\n\n if not self.validate_copyjob( copyjob ): continue\n self.logger.info(\"copyjob ok\")\n\n for task in copyjob:\n lfn = '/store' + task.split(' ')[0].split('/store')[1]\n if (random.random() < getFailProbability()):\n failed_files.append( lfn )\n else:\n transferred_files.append( lfn )\n\n return transferred_files, failed_files, []","sub_path":"test/python/AsyncStageOut_t/FakeTransferWorker.py","file_name":"FakeTransferWorker.py","file_ext":"py","file_size_in_byte":2874,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"42479248","text":"from app import *\nfrom app.helpers.log_helper import *\nfrom app.constants.logs import *\n\nlog_bp = Blueprint(\"log_bp\", __name__)\n\n\n@log_bp.route(\"/logs\", methods=[\"GET\"])\n@fractalPreProcess\ndef logs_get(**kwargs):\n starting_index = max(0, int(request.args.get(\"start\")))\n ending_index = min(int(request.args.get(\"end\")), len(logs))\n\n if starting_index >= ending_index or starting_index >= len(logs):\n starting_index = 0\n ending_index = len(logs)\n\n return jsonify({\"logs\": logs[starting_index:ending_index]}), 200\n","sub_path":"server/app/blueprints/log_blueprint.py","file_name":"log_blueprint.py","file_ext":"py","file_size_in_byte":538,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"492479723","text":"#訂正情報以外からデマ情報を検出\n#訂正情報と重複するものを抽出\n#その他情報 test.binaryfile\n#訂正情報 predicted_tweet.binaryfile\nimport pickle\nimport csv\n\nfile1 = open('predicted_tweet.binaryfile', 'rb')\nwords = pickle.load(file1)\nword =[x[0] for x in words]\nword2 =[p[1] for p in words]\n#print (word2)\nfile2 = open('test.binaryfile', 'rb')\nterms = pickle.load(file2)\nterm = [y[0] for y in terms]\nterm2 =[q[1] for q in terms]\n\n\n\nlist = []\nfor l in range(len(word)):\n S1 = set(word[l])\n correct = word2[l]\n for i in range(len(term)):\n S2 = set(term[i])\n rumor = term2[i]\n\n if len(S1 & S2) >= (len(S1)* 0.4) :\n list.append([word[l], term[i]])\n with open(\"test_result.csv\", \"a\", encoding=\"utf_8_sig\", newline=\"\") as files:\n print(\"訂正\", word[l], \",\", \"デマ\", term[i], file = files)\n\n with open(\"false_rumor.csv\", \"a\", encoding=\"utf_8_sig\", newline=\"\") as file1:\n print(term2[i], file = file1)","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":975,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"488623856","text":"from .builder import Builder\nfrom .base import Config\nimport sys\nimport os\n\ndef serve(config):\n output_folder = config.folders['output']\n os.chdir(output_folder)\n import SimpleHTTPServer\n import SocketServer\n\n PORT = 8000\n\n Handler = SimpleHTTPServer.SimpleHTTPRequestHandler\n\n httpd = SocketServer.TCPServer((\"\", PORT), Handler)\n\n print(\"serving at port\", PORT)\n httpd.serve_forever()\n\ncommands = {\n 'serve': serve,\n}\n\ndef main():\n config = Config.from_path('config.yaml')\n\n if len(sys.argv) > 1:\n command = sys.argv[1]\n if command in commands:\n commands[command](config)\n else:\n print('unknown command...?')\n\n else:\n builder = Builder(config)\n builder.run()\n","sub_path":"beetle/cli.py","file_name":"cli.py","file_ext":"py","file_size_in_byte":756,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"630532202","text":"#################################\n##### Name: Angel Tang\n##### Uniqname: rongtang\n#################################\n\nfrom requests_oauthlib import OAuth1\nimport json\nimport requests\nimport re\nimport emoji\nimport webbrowser\nimport math\nimport base64\nimport sqlite3\n\nimport secrets\nimport sqlite\nimport main\n\n\nCACHE_FILENAME = \"spotify_genre_cache.json\"\nCACHE_DICT = {}\n\nclient_key = secrets.CLIENT_ID\nclient_secret = secrets.CLIENT_SECRET\nuser_id = secrets.USER_ID\n\n# class Track:\n# def __init__(self, name, artist, duration, uri):\n# self.name = name\n# self.artist = artist\n# self.duration = duration # in seconds\n# self.uri = uri\n\nclass Playlist:\n def __init__(self, name, id, href, recipe_name, genre, duration=0):\n '''initiate a Playlist\n\n Parameters\n ----------\n self\n name: playlist name\n id: playlist id issued by Spotify\n href: playlist url on Spotify\n recipe_name: the recipe_name that this playlist is made for\n genre: the genre of this playlist\n duration: the total length of this playlist (in seconds)\n\n Returns\n -------\n None\n '''\n self.name = name\n self.id = id\n self.href = href\n self.recipe_name = recipe_name\n self.genre = genre\n self.duration = duration # in seconds\n\n def info(self):\n '''prints playlist info\n\n Parameters\n ----------\n self\n\n Returns\n -------\n a string with playlist info\n '''\n total_seconds = int(self.duration)\n minutes = math.floor(total_seconds/60)\n seconds = total_seconds%60\n return f'{self.name} ({minutes} mins {seconds} secs)'\n\ndef open_cache():\n ''' Opens the cache file if it exists and loads the JSON into\n the CACHE_DICT dictionary.\n if the cache file doesn't exist, creates a new cache dictionary\n\n Parameters\n ----------\n None\n\n Returns\n -------\n The opened cache: dict\n '''\n try:\n cache_file = open(CACHE_FILENAME, 'r')\n cache_contents = cache_file.read()\n cache_dict = json.loads(cache_contents)\n cache_file.close()\n except:\n cache_dict = {}\n return cache_dict\n\ndef save_cache(cache_dict):\n ''' Saves the current state of the cache to disk\n\n Parameters\n ----------\n cache_dict: dict\n The dictionary to save\n\n Returns\n -------\n None\n '''\n dumped_json_cache = json.dumps(cache_dict)\n fw = open(CACHE_FILENAME,\"w\")\n fw.write(dumped_json_cache)\n fw.close()\n\ndef encode_header():\n '''encords the client info into an authorization header\n\n Parameters\n ----------\n None\n\n Returns\n -------\n headers: a string with encoded client info\n '''\n # Encode as Base64\n message = f\"{client_key}:{client_secret}\"\n messageBytes = message.encode('ascii')\n base64Bytes = base64.b64encode(messageBytes)\n base64Message = base64Bytes.decode('ascii')\n headers = {}\n headers['Authorization'] = f\"Basic {base64Message}\"\n return headers\n\nAUTH_HEADERS = encode_header()\n\ndef authenticate():\n '''authenticates the user\n\n Parameters\n ----------\n None\n\n Returns\n -------\n refresh_token: the token required to get new access token in case the old one expires\n '''\n\n # HANDLE NO CLIENT INFO\n if not client_key or not client_secret:\n print(\"You need to fill in CLIENT_KEY and CLIENT_SECRET in secret.py.\")\n exit()\n if not user_id:\n print('You need to fill in USER_ID in secret.py')\n exit()\n\n # GET\n AUTH_CODE_URL = 'https://accounts.spotify.com/authorize'\n auth_code_response = requests.get(AUTH_CODE_URL, params={\n 'client_id': client_key,\n 'response_type': 'code',\n 'redirect_uri': 'http://localhost:8888',\n 'scope': 'playlist-modify-public playlist-modify-private',\n })\n print(emoji.emojize(f':exclamation: To use this app properly, you need to run the following authorization.', use_aliases=True))\n print(f'Please go to this url to authorize: {auth_code_response.url}')\n # wait for the user's authentication\n resp_url = input('Please paste the redirected url: ')\n # EXAMPLE: http://localhost:8888/?code=AQAV97Pts7-6h5XEi9VFJrFBIvznjfIZBJkkUAr0-00JLTjnGP-RndV0fdvYhNlvG40AloL2JoQo0BohbB0Wa-G4mOnzOq5ncSWULEaO_Jv4kGWETsa_Rh6t9piJIqSBdqPF5cDqVGWKhd7tIYObD5mD6wlQMIpE6YBmp0hhJza_omg6TxZNuSucSLNf3_T7_jrh8JJzUqzAKITH4u00XO5bSZktyX2A93o\n code = resp_url.split('?code=')[-1]\n\n # POST\n TOKEN_URL = 'https://accounts.spotify.com/api/token'\n auth_response = requests.post(TOKEN_URL, {\n 'grant_type': 'authorization_code',\n 'code': code,\n 'redirect_uri': 'http://localhost:8888',\n }, headers=AUTH_HEADERS)\n\n # convert the response to JSON\n auth_response_data = auth_response.json()\n refresh_token = auth_response_data['refresh_token']\n\n print('Thank you! Authorization completed.')\n\n return refresh_token\n\nREFRESH_TOKEN = authenticate()\n\ndef get_access_token():\n '''get new access token from the refresh_token\n\n Parameters\n ----------\n None\n\n Returns\n -------\n access_token: a string required to make API requests\n '''\n\n # POST\n TOKEN_URL = 'https://accounts.spotify.com/api/token'\n auth_response = requests.post(TOKEN_URL, {\n 'grant_type': 'refresh_token',\n 'refresh_token': REFRESH_TOKEN\n }, headers=AUTH_HEADERS).json()\n access_token = auth_response['access_token']\n return access_token\n\ndef create_headers():\n '''create headers required for each API request\n\n Parameters\n ----------\n None\n\n Returns\n -------\n headers: a string formatted to include access_token\n '''\n\n access_token = get_access_token()\n headers = {'Authorization': 'Bearer {token}'.format(token=access_token), 'Content-Type': 'application/json'}\n return headers\n\ndef make_request(baseurl, params):\n ''' constructs a key that is guaranteed to uniquely and\n repeatably identify an API request by its baseurl and params\n\n Parameters\n ----------\n baseurl: string\n The URL for the API endpoint\n params: dict\n A dictionary of param:value pairs\n\n Returns\n -------\n string\n the unique key as a string\n '''\n headers = create_headers()\n response = requests.get(baseurl, params=params, headers=headers)\n return response.json()\n\ndef make_request_with_cache(baseurl, genre):\n '''Check the cache for a saved result for this baseurl+params:values\n combo. If the result is found, return it. Otherwise send a new\n request, save it, then return it.\n\n Parameters\n ----------\n baseurl: string\n The URL for the API endpoint\n genre: string\n The genre that the user is interested in\n\n Returns\n -------\n dict\n the results of the query as a dictionary loaded from cache\n JSON\n '''\n\n if genre in CACHE_DICT.keys():\n print(\"... fetching cached data ...\")\n else:\n print(\"... making new request ...\")\n params = {\n 'q':f'genre:{genre}',\n 'type':'track',\n 'limit':50\n }\n temp_list = make_request(baseurl, params)['tracks']['items']\n track_dict = {}\n counter = 1\n for item in temp_list:\n temp = {}\n temp['name'] = item['name']\n temp['artist'] = item['artists'][0]['name']\n temp['duration'] = int(item['duration_ms'] / 1000)\n temp['uri'] = item['uri']\n temp['genre'] = genre\n # track = Track(name, artist, duration, uri)\n track_dict[counter] = temp\n counter += 1\n\n CACHE_DICT[genre] = track_dict\n save_cache(CACHE_DICT)\n return CACHE_DICT[genre]\n\ndef make_genre_dict():\n '''make a dictionary of genres from the Spotify API\n\n Parameters\n ----------\n None\n\n Returns\n -------\n genre_dict: a dict with all genres\n '''\n\n baseurl = 'https://api.spotify.com/v1/recommendations/available-genre-seeds'\n params = ''\n temp_dict = make_request(baseurl, params)\n genre_list = temp_dict['genres']\n genre_dict = {}\n counter = 1\n for genre in genre_list:\n genre_dict[counter] = genre\n counter += 1\n return genre_dict\n\ndef print_genres(genre_dict):\n '''print all genres to console\n\n Parameters\n ----------\n genre_dict: a dict with all genres\n\n Returns\n -------\n None\n '''\n\n header = f'''\n=========================================\n{emoji.emojize(\":musical_note:\", use_aliases=True)} All Spotify Genres (Alphabetical)\n=========================================\n '''\n print(header)\n for k,v in genre_dict.items():\n print(f'{k} - {v}')\n return\n\ndef calculate_playlist_length(current_time, track):\n '''calculate playlist length\n\n Parameters\n ----------\n current_time: the current playlist length\n track: the track to add\n\n Returns\n -------\n total: the updated playlist length\n '''\n\n #retrive track length\n duration = track['duration']\n #add to current_time\n total = current_time + duration\n return total\n\ndef create_playlist(genre, recipe):\n '''create a playlist based on user inputs\n\n Parameters\n ----------\n genre: the genre chosen by user\n recipe: the recipe chosen by user\n\n Returns\n -------\n a Playlist object: empty with no tracks\n '''\n\n name = f'{genre.title()} for Cooking {recipe.name}'\n recipe_name = recipe.name\n\n if name not in main.playlists_list:\n headers = create_headers()\n baseurl = f'https://api.spotify.com/v1/users/{user_id}/playlists'\n\n data=json.dumps({\n 'name': name,\n 'public': True\n })\n response = requests.post(\n baseurl,\n data=data,\n headers=headers\n ).json()\n playlist_id = response['id']\n playlist_href = f'https://open.spotify.com/playlist/{playlist_id}?si={user_id}' # https://open.spotify.com/playlist/323iJk6Ym1egp7KNnm8mg1?si=a66dec6aa55e4751\n\n else:\n print('... fetching from database ...')\n playlist = sqlite.fetch_data_to_dict(name, 'playlist')\n playlist_id = playlist['Playlist_Id']\n playlist_href = playlist['Href']\n\n return Playlist(name, playlist_id, playlist_href, recipe_name, genre)\n\ndef add_tracks(playlist_id, genre, max_time):\n '''add tracks of the requested genre to a playlist\n The function checks if the current playlist length has exceeded the cooking time (max_time),\n if yes, it'll stop adding new songs;\n else it'll add one more song and make the length check again.\n\n Parameters\n ----------\n playlist_id: the playlist id issued by Spotify\n genre: the genre chosen by user\n max_time: the cooking time of the recipe\n * not a true \"max\"\n\n Returns\n -------\n current_time: the updated playlist length\n '''\n\n baseurl_genre = 'https://api.spotify.com/v1/search'\n songs_dict = make_request_with_cache(baseurl_genre, genre)\n\n counter = 1\n current_time = 0\n baseurl_add_track = f'https://api.spotify.com/v1/playlists/{playlist_id}/tracks'\n while current_time < max_time:\n\n try:\n uris = [songs_dict[counter]['uri']]\n except:\n uris = [songs_dict[1]['uri']]\n data=json.dumps({\n 'uris': uris\n })\n headers = create_headers()\n response = requests.post(\n url=baseurl_add_track,\n data=data,\n headers=headers\n ).json()\n\n current_time = calculate_playlist_length(current_time, songs_dict[counter])\n counter += 1\n\n return current_time\n\ndef ask_genre():\n '''ask user for genre\n\n Parameters\n ----------\n None\n\n Returns\n -------\n genre: a string of genre to search Spotify tracks for\n '''\n\n GENRES = make_genre_dict()\n print_genres(GENRES)\n user = input(emoji.emojize(':sparkles: What genre do you want the playlist to be? (To leave, type \"bye\" :wave:) ', use_aliases=True))\n\n if user.strip().lower() == 'bye':\n print('Okie...bye!')\n exit()\n else:\n try:\n genre_id = int(user.strip())\n genre = GENRES[genre_id]\n return genre\n except:\n print('Please enter a valid number.')\n ask_genre()\n\n\ndef process_time_to_seconds(time_string):\n '''process the time_strings of the recipe to seconds\n\n Parameters\n ----------\n time_string: a formatted string of cooking time\n\n Returns\n -------\n seconds: int, the cooking time in seconds\n '''\n\n pattern = r'((\\d*)\\s*hrs?)?\\s*(\\d+)?'\n time = re.search(pattern, time_string)\n try:\n hour = int(time[2])\n except:\n hour = 0\n minute = int(time[3])\n seconds = (60 * hour + minute) * 60\n return seconds\n\ndef ask_table():\n '''asks the user whether they want to export the recipe-playlist results to a table\n\n Parameters\n ----------\n None\n\n Returns\n -------\n None\n '''\n\n user = input(emoji.emojize(':sparkles: Want to export all the existing recipes with playlists? Type \"ya\" or \"nah\" to let me know: ', use_aliases=True))\n user = user.lower().strip()\n if user == 'ya':\n print('... opening the table in browser ...')\n data_dict = sqlite.fetch_combined_to_dict()\n sqlite.show_table(data_dict)\n return\n elif user == 'nah':\n return\n else:\n print(emoji.emojize('Please type \"ya\" or \"nah\" so that I can understand :cold_sweat:', use_aliases=True))\n ask_table()\n\ndef generate_playlist(recipe):\n '''generates a playlist based on the user's choice of recipe\n and opens in browser\n\n Parameters\n ----------\n recipe: a Recipe object\n\n Returns\n -------\n None\n '''\n\n max_time = process_time_to_seconds(recipe.time)\n genre = ask_genre()\n\n try:\n playlist = create_playlist(genre, recipe)\n playlist_id = playlist.id\n length = add_tracks(playlist_id, genre, max_time)\n playlist.duration = length # in seconds\n\n db_value = [\n playlist.name,\n playlist.id,\n playlist.href,\n playlist.recipe_name,\n playlist.genre,\n playlist.duration,\n ]\n db_values = [db_value]\n main.playlists_list = sqlite.check_database(playlist.name, 'playlists', main.playlists_list, db_values)\n\n print(f'Opening in browser: {playlist.info()}')\n url = playlist.href\n webbrowser.open(url)\n print(emoji.emojize(f':musical_note: {playlist.info()} generated for {recipe.name} ({recipe.time})', use_aliases=True))\n\n ask_table()\n except:\n print(emoji.emojize(f'Oops! Looks like the genre {genre} does not actually exist in Spotify\\'s API :cold_sweat:', use_aliases=True))\n generate_playlist(recipe)\n\n return\n","sub_path":"playlist_generator.py","file_name":"playlist_generator.py","file_ext":"py","file_size_in_byte":14957,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"178234088","text":"import sqlite3\nimport datetime\nimport json\n\ngame_db = '/var/jail/home/team48/game1.db'\n\ndef request_handler(request):\n if request['method'] == 'POST':\n game_id = int(request['form']['game_id'])\n player_1 = request['form']['player1'].lower()\n player_2 = request['form']['player2'].lower()\n conn = sqlite3.connect(game_db) # connect to that database (will create if it doesn't already exist)\n c = conn.cursor() # move cursor into database (allows us to execute commands)\n c.execute('''CREATE TABLE IF NOT EXISTS player_table (game_id int, player_1 text, player_2 text);''') # run a CREATE TABLE command\n \n joined_users = c.execute('''SELECT * FROM player_table WHERE game_id == ?;''',(game_id,)).fetchall()\n # return joined_users\n output = c.execute('''SELECT * FROM player_table;''').fetchall()\n # return output\n\n if len(joined_users) == 0:\n # return 'hi'\n c.execute('''INSERT into player_table VALUES (?,?,?);''', (game_id, player_1, player_2))\n output_data = {\"is_new\": True, \"can_start\": True, \"data\":[], \"hint\": \"New game started.\"}\n \n if len(joined_users) > 0:\n # need to get all ball positions from database\n latest_data = c.execute('''SELECT game_state FROM game_table WHERE game_id == ? ORDER BY timing DESC;''',(game_id,)).fetchone()\n \n output_data = {\"is_new\": False, \"can_start\": True, \"data\": json.loads(latest_data[0]), \"hint\": \"Old game loaded.\"}\n \n conn.commit() # commit commands\n conn.close() # close connection to database\n return json.dumps(output_data)","sub_path":"Code/server_files/data_get.py","file_name":"data_get.py","file_ext":"py","file_size_in_byte":1683,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"66646204","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Sep 17 16:46:35 2014\n\n@author: nhpnp3\n\"\"\"\n\nimport vtk_read as vtk\nimport time\nimport euler_to_gsh as gsh\nimport microstructure_function as msf\nimport calibration\nimport validation\nimport results\n\nwrt_file = 'log_%s.txt' %time.strftime(\"%Y-%m-%d_h%Hm%M\")\n\nns_cal = 200\nset_id_cal = 'cal'\n\nns_val = 50\nset_id_val = 'val'\n\n\nvtk_filename = 'Results_Ti64_RandomMicroFZfinal_21x21x21_AbqInp_PowerLaw_%s_data_v2_01.vtk'\n\n## The tensorID determines the type of tensor data read from the .vtk file\n## if tensorID == 0, we read the stress tensor \n## if tensorID == 1, we read the strain tensor \n## if tensorID == 2, we read the plastic strain tensor \n\ntensor_ID = 0\n\n\n## Gather data from calibration vtk files\n\ndir_cal = 'vtk_cal_stress_all_comp'\n\nvtk.read_euler(ns_cal,set_id_cal,vtk_filename,dir_cal, wrt_file)\n\nfor comp in xrange(9):\n vtk.read_meas(ns_cal,set_id_cal,comp,vtk_filename, tensor_ID,dir_cal, wrt_file)\n\n\n## Gather data from validation vtk files \n\ndir_val = 'vtk_val_stress_all_comp'\n\nvtk.read_euler(ns_val,set_id_val,vtk_filename, dir_val, wrt_file)\n\nfor comp in xrange(9):\n vtk.read_meas(ns_val,set_id_val,comp,vtk_filename, tensor_ID, dir_val, wrt_file)\n \n \n## Convert the orientations from the calibration datasets from bunge euler angles\n## to GSH coefficients\ngsh.euler_to_gsh(ns_cal,set_id_cal,wrt_file)\n\n\n## Convert the orientations from the validation datasets from bunge euler angles\n## to GSH coefficients\ngsh.euler_to_gsh(ns_val,set_id_val,wrt_file)\n\n\n## Generate the fftn of the calibration microstructure function\nmsf.micr_func(ns_cal,set_id_cal,wrt_file)\n \n \n## Generate the fftn of the validation microstructure function\nmsf.micr_func(ns_val,set_id_val,wrt_file)\n \n \n## Perform the calibration\nfor comp in xrange(9):\n calibration.calibration_procedure(ns_cal,set_id_cal,comp,wrt_file)\n \n \n## Perform the validation\nfor comp in xrange(9):\n validation.validation_procedure(ns_cal,ns_val,set_id_cal,set_id_val,comp,wrt_file)\n \n\nresults.results_all(ns_val, set_id_val, 'sigma')\n\n","sub_path":"fip_collab/2014_09_16_stress_colony_mks/main_polycrystal_strain.py","file_name":"main_polycrystal_strain.py","file_ext":"py","file_size_in_byte":2086,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"500461913","text":"\"\"\"\n FormatLoader functions, that serve as interface to check and get formats.\n\"\"\"\n\nfrom .csv_format import csv_format\nfrom .txt_format import txt_format\nfrom .xlsx_format import xlsx_format\n\nTYPES = {'.csv': csv_format,\n '.txt': txt_format,\n '.xlsx': xlsx_format}\n\n\ndef checkTypes(type_names=[]):\n \"\"\"\n Cheks if a list of types is supported by the tool.\n If not supported it raises a TypeError exception.\n\n Parameters\n ----------\n type_names: list\n \"\"\"\n\n for type_name in type_names:\n if type_name not in TYPES:\n raise TypeError('Type %s not supported.' % type_name)\n exit()\n\n\ndef getFormats(type_names=[]):\n \"\"\"\n Generates a list of formats to a list of type names.\n\n Parameters\n ----------\n type_names: list\n each type is a str and looks like this '.type'\n\n Returns\n -------\n types: list\n list of Type Objects\n \"\"\"\n\n if not isinstance(type_names, list):\n raise TypeError('type_names must be a list')\n\n checkTypes(type_names)\n\n return [TYPES[type_name] for type_name in type_names]\n","sub_path":"Formats/FormatLoader.py","file_name":"FormatLoader.py","file_ext":"py","file_size_in_byte":1113,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"617403497","text":"# service/resource/project/scope.py\n\n\nclass Scope:\n allow_api = set()\n # allow_redprint = set() #可以通过RedPrint来实现基于此的模块控制\n\n\nclass UserScope(Scope):\n allow_api = {\n 'users.logout_user',\n 'users.get_user_status',\n 'blog.add_category',\n 'blog.delete_single_category',\n 'blog.add_article',\n 'blog.update_single_article',\n }\n\n\nclass AdminScope(Scope):\n allow_api = {\n 'users.add_user',\n 'blog.delete_single_article'\n }\n\n def __init__(self):\n self.allow_api = self.allow_api | UserScope().allow_api\n\n\ndef endpoint_in_scope(endpoint, scope='UserScope'):\n \"\"\"Determine if the endpoint is in the scope.\n\n :param endpoint the flask endpoint of view_func\n :param scope(str): the user's power scope, default is `UserScopoe`\n :return: None if endpoint in scope, else raise APIException - Forbidden.\n \"\"\"\n if endpoint in globals()[scope]().allow_api:\n return True\n else:\n return False\n","sub_path":"services/resource/project/scope.py","file_name":"scope.py","file_ext":"py","file_size_in_byte":1020,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"437885706","text":"import discord\nfrom discord.ext import commands\nimport json\nimport random\nimport datetime as dt\nimport os\nimport requests\nwith open(\"D:\\\\code\\\\Python\\\\setting.json\", 'r', encoding='utf-8') as jfile: # 載入json\n jdata = json.load(jfile)\n\nbot = commands.Bot(command_prefix='/') # 起手字元\n\n\n@bot.event\nasync def on_ready(): # 機器人啟動觸發\n print(\">> Bot is online <<\")\n\n\n@bot.command()\nasync def l(ctx, codes): # 載入\n bot.load_extension(f\"codes.{codes}\")\n await ctx.send(f\"{codes}已成功load!\")\n\n\n@bot.command()\nasync def unl(ctx, codes): # 卸載\n bot.unload_extension(f\"codes.{codes}\")\n await ctx.send(f\"{codes}已成功unload!\")\n\n\n@bot.command()\nasync def rel(ctx, codes): # 重新載入\n bot.reload_extension(f\"codes.{codes}\")\n await ctx.send(f\"{codes}已成功reload!\")\n\n# with open(\"github\\\\RJ_Bot\\\\DATA.json\", \"w\", encoding=\"utf-8\") as f:\n# json.dump(data, f)\n\n# @bot.command()\n# async def reload(ctx): # 名稱為指令\n# # round為四捨五入 ctx指當前頻道觸發人的各種資料\n# await ctx.send(f\"機器人延遲 {round(bot.latency*1000)}ms\")\n\nfor filename in os.listdir('./codes'): # 啟動機器人時 載入所有檔案\n if filename.endswith('.py'):\n bot.load_extension(f\"codes.{filename[:-3]}\")\n\nif __name__ == \"__main__\":\n bot.run(jdata['TOKEN'])\n","sub_path":"discord bot.py","file_name":"discord bot.py","file_ext":"py","file_size_in_byte":1345,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"555249378","text":"#!/usr/bin/env python\r\nimport struct\r\nimport smbus\r\nimport sys\r\nimport time\r\n\r\nclass UPS():\r\n \r\n def __init__(self):\r\n \r\n # Set the bus port either 1 or 0\r\n self.bus = smbus.SMBus(1)\r\n # set low capacity alert for the battery\r\n self.low_capacity = 20\r\n\r\n def read_voltage(self):\r\n\r\n # This function returns the voltage as float from the UPS-Lite via SMBus object\r\n address = 0x36\r\n read = self.bus.read_word_data(address, 2)\r\n swapped = struct.unpack(\"H\", read))[0]\r\n voltage = swapped * 1.25 /1000/16\r\n return voltage\r\n\r\n\r\n def read_capacity(self):\r\n \r\n # This function returns the ramaining capacitiy in int as precentage of the battery connect to the UPS-Lite\r\n address = 0x36\r\n read = self.bus.read_word_data(address, 4)\r\n swapped = struct.unpack(\"H\", read))[0]\r\n capacity = swapped/256\r\n return int(capacity)\r\n \r\n def is_battery_full(self,capacity):\r\n \r\n # This function returns True if the battery is full, else return False\r\n if(capacity == 100):\r\n return True\r\n return False\r\n \r\n def is_battery_low(self,capacity):\r\n \r\n # This function returns True if the battery capacity is low, else return False\r\n if(capacity <= self.low_capacity):\r\n return True\r\n return False\r\n \r\ndef main():\r\n \r\n ups_lite = UPS()\r\n voltage = ups_lite.read_voltage()\r\n capacity = ups_lite.read_capacity()\r\n is_low = ups_lite.is_battery_low(capacity)\r\n is_full = ups_lite.is_battery_full(capacity)\r\n \r\n print(\"[-] Voltage: %s\" % voltage)\r\n print(\"[-] Capacitiy: %s\" % capacity)\r\n \r\nmain()\r\n","sub_path":"UPS_Lite.py","file_name":"UPS_Lite.py","file_ext":"py","file_size_in_byte":2085,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"341908504","text":"'''\n Author: Sam Rosenblum\n Date: 2/11/2013\n Updated: 2/25/2013\n \n This file holds the class GenericDistanceSensor which holds with in it\n equations that holds a map that represent best fit equations for different \n types of distance sensors\n'''\n\nimport math\nfrom common.constants import *\n\ntry:\n import wpilib\nexcept ImportError:\n from pyfrc import wpilib\n\n# sensors\nGP2D120 = 0\nMB10X3 = 1 #covers MB1003, MB1013, MB1023\n\n# settings\nMETRIC = 0\nENGLISH = 1\n\n\nclass GenericDistanceSensor(wpilib.AnalogChannel):\n\n # For each sensor type, define a function that translates the voltage \n # to a distance (in cm units)\n SENSOR_EQUATIONS = {\n GP2D120: lambda v: math.pow((v/11.036), -1/.947),\n MB10X3: lambda v: v * (512/5), #document states distance per mm is 5120/vcc with a 5mm accuracy\n #this function outputs cm \n }\n \n def __init__(self, channel, sensor_type, system=ENGLISH): \n '''\n constructor takes a channel and a sensor_type to figure out the\n real distance\n \n :param channel: The channel number for the associated analog sensor\n '''\n \n super().__init__(channel)\n \n self.distance_fn = self.SENSOR_EQUATIONS[sensor_type]\n self.system = system\n \n \n def GetDistance(self):\n '''gets distance in cm based on the voltage''' \n v = self.GetVoltage()\n \n # if the value is zero, return zero\n if v <= 0:\n return 0\n \n # convert the voltage to a distance\n distance = self.distance_fn(v)\n \n # convert to appropriate units\n if self.system == ENGLISH:\n distance /= INCH_TO_CM\n return distance\n \n \n def GetAverageDistance(self):\n '''Gets average distance based on average voltage'''\n \n v = self.GetAverageVoltage()\n \n # if the value is zero, return zero\n if v <= 0:\n return 0\n \n # convert the voltage to a distance\n distance = self.distance_fn(v)\n \n # convert to appropriate units\n if self.system == ENGLISH:\n distance /= INCH_TO_CM\n \n return distance\n","sub_path":"aerial_assist/debug/electrical test/source/common/generic_distance_sensor.py","file_name":"generic_distance_sensor.py","file_ext":"py","file_size_in_byte":2291,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"439965038","text":"from spacerogue.gameutil import cat\nfrom spacerogue.props import weapon_props\n\nclass Item(object):\n\t'''Generic item, does nothing'''\n\tdef __init__(self, name):\n\t\tself.name = name\n\nclass Weapon(Item):\n\t'''Equippable weapon'''\n\tdef __init__(self, name):\n\t\tItem.__init__(self, name)\n\t\tself.properties = weapon_props[self.name]\n\n\tdef show_stats(self, verbose=True):\n\t\t'''Displays weapon stats'''\n\t\toutput = '%s\\n' % self.name.title()\n\t\tfor stat_name, value in self.properties.items():\n\t\t\tunits = ''\n\t\t\tif stat_name == 'value':\n\t\t\t\tunits = 'space dollar(s)'\n\t\t\telif stat_name == 'damage':\n\t\t\t\tunits = 'megajoules/shot'\n\t\t\telif stat_name == 'ammo usage':\n\t\t\t\tunits = 'kg/shot'\n\t\t\toutput += '|- %s = %s %s\\n' % (stat_name.title(), str(value), units)\n\t\treturn output\n\n","sub_path":"spacerogue/items.py","file_name":"items.py","file_ext":"py","file_size_in_byte":760,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"113916641","text":"import FWCore.ParameterSet.Config as cms\n\nfrom DQMServices.Core.DQMEDAnalyzer import DQMEDAnalyzer\ndtTPmonitor = DQMEDAnalyzer('DTDigiTask',\n # set the max TDC counts for the time-box (6400 or 1600)\n maxTTMounts = cms.untracked.int32(1600),\n # bin size for the time boxes\n timeBoxGranularity = cms.untracked.int32(4),\n # Set to true to read the ttrig from the DB\n readDB = cms.untracked.bool(False),\n # Value of the ttrig pedestal used when not reading from DB\n defaultTtrig = cms.int32(3450),\n # the label to retrieve the DT digis\n dtDigiLabel = cms.untracked.InputTag('dtunpacker'),\n # check the noisy flag in the DB and use it\n checkNoisyChannels = cms.untracked.bool(True),\n # set static booking (all the detector)\n staticBooking = cms.untracked.bool(True),\n inTimeHitsLowerBound = cms.int32(0),\n inTimeHitsUpperBound = cms.int32(0),\n # switch on debug verbosity\n debug = cms.untracked.bool(False),\n # if true access LTC digis\n localrun = cms.untracked.bool(True),\n # define the boundaries for in-time hits (ns)\n defaultTmax = cms.int32(50),\n performPerWireT0Calibration = cms.bool(True),\n # the # of luminosity blocks to reset the histos\n ResetCycle = cms.untracked.int32(400),\n doAllHitsOccupancies = cms.untracked.bool(False),\n doNoiseOccupancies = cms.untracked.bool(False),\n doInTimeOccupancies = cms.untracked.bool(True), \n # switch on the mode for running on test pulses (different top folder)\n testPulseMode = cms.untracked.bool(True),\n # switch on the mode for running on slice test (different top folder and customizations)\n sliceTestMode = cms.untracked.bool(False),\n # time pedestal defining the lower edge of the timebox plots\n tdcPedestal = cms.untracked.int32(0),\n # switch for filtering on synch noise events (threshold on # of digis per chamber)\n filterSyncNoise = cms.untracked.bool(False),\n # threshold on # of digis per chamber to define sync noise\n maxTDCHitsPerChamber = cms.untracked.int32(100),\n # switch for time boxes with layer granularity (commissioning only) \n doLayerTimeBoxes = cms.untracked.bool(False)\n)\n\n\n\n\n\n","sub_path":"DQM/DTMonitorModule/python/dtDigiTask_TP_cfi.py","file_name":"dtDigiTask_TP_cfi.py","file_ext":"py","file_size_in_byte":2227,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"465390710","text":"\"\"\"\nEthan Lyon\nELEC 574\nA4 Code\nApril 20th 2020\n\"\"\"\n\n\nimport cv2\nimport os\nfrom skimage.feature import hog\nfrom sklearn.svm import SVC\nimport numpy as np\nfrom sklearn.model_selection import cross_val_score, train_test_split, ShuffleSplit, StratifiedKFold\nfrom sklearn.metrics import accuracy_score, precision_score, recall_score\nimport matplotlib.pyplot as plt\nfrom sklearn.ensemble import RandomForestClassifier\n\n\n# Use four pre-trained classifiers for face detection\nface_detector_1 = cv2.CascadeClassifier('./haarcascades/haarcascade_frontalface_default.xml')\nface_detector_2 = cv2.CascadeClassifier('./haarcascades/haarcascade_frontalface_alt.xml')\nface_detector_3 = cv2.CascadeClassifier('./haarcascades/haarcascade_frontalface_alt2.xml')\nface_detector_4 = cv2.CascadeClassifier('./haarcascades/haarcascade_frontalface_alt_tree.xml')\n\n\nemotion_labels = {'Neutral': 0,\n 'Anger': 1,\n 'Surprise': 2,\n 'Sadness': 3,\n 'Happy': 4}\n\n# add your photos to the folder and set your netid\nNetID = 'enl1'\n\n\ndef feature_extraction(img, orientations=16, pixels_per_cell=(16, 16), cells_per_block=(1, 1)):\n \"\"\" The function does the following tasks to extract emotion-related features:\n (1) Face detection (2) Cropping the face in the image (3) Resizing the image and (4) Extracting HOG vector.\n\n Args:\n img: The raw image.\n orientations: The number of bins for different orientations.\n pixels_per_cell: The size of each cell.\n cells_per_block: The size of the block for block normalization.\n\n Returns:\n features: A HOG vector is returned if face is detected. Otherwise 'None' value is returned.\n \"\"\"\n\n # If the image is a color image, convert it into gray-scale image\n if img.shape[2] == 3:\n img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\n\n\n face_detection_1 = face_detector_1.detectMultiScale(\n img, scaleFactor=1.1, minNeighbors=10, minSize=(5, 5), flags=cv2.CASCADE_SCALE_IMAGE)\n face_detection_2 = face_detector_2.detectMultiScale(\n img, scaleFactor=1.1, minNeighbors=10, minSize=(5, 5), flags=cv2.CASCADE_SCALE_IMAGE)\n face_detection_3 = face_detector_3.detectMultiScale(\n img, scaleFactor=1.1, minNeighbors=10, minSize=(5, 5), flags=cv2.CASCADE_SCALE_IMAGE)\n face_detection_4 = face_detector_4.detectMultiScale(\n img, scaleFactor=1.1, minNeighbors=10, minSize=(5, 5), flags=cv2.CASCADE_SCALE_IMAGE)\n\n\n # Go over the results of face detection. Stop at the first detected face,\n face_features = None\n if len(face_detection_1) == 1:\n face_features = face_detection_1\n elif len(face_detection_2) == 1:\n face_features = face_detection_2\n elif len(face_detection_3) == 1:\n face_features = face_detection_3\n elif len(face_detection_4) == 1:\n face_features = face_detection_4\n else:\n print(\"No face detected!\")\n # cv2.imshow('No face detected', img)\n # cv2.waitKey(0)\n\n\n if face_features is not None:\n global count\n for x, y, w, h in face_features:\n # Get the coordinates and the size of the rectangle containing face\n img = img[y:y+h, x:x+w]\n \n # Resize all the face images so that all the images have the same size\n img = cv2.resize(img, (350, 350))\n # Uncomment the following two lines to visualize the cropped face image\n # cv2.imshow(\"Cropped Face\", img)\n # cv2.waitKey(0)\n \n # Extract HOG descriptor\n features, hog_img = hog(img, orientations=orientations, pixels_per_cell=pixels_per_cell, cells_per_block=cells_per_block, visualize=True)\n # Uncomment the following tow lines to visualize HOG\n #cv2.imshow('hog', hog_img)\n #cv2.waitKey(0)\n count += 1\n print(\"Loading: {:d}%\".format(int(count / 50 * 100)))\n return features.reshape(1, -1)\n\n else:\n return None\n\n#%%\ndef evaluate_model(X, y, clf = SVC(gamma = 'auto'), split = 5):\n true_labels = list()\n predicted_labels = list()\n clf = SVC(gamma = 'auto')\n for train_index, test_index in StratifiedKFold(n_splits=split, shuffle = True).split(X, y):\n X_train = X[train_index, :]\n Y_train = y[train_index]\n X_test = X[test_index, :]\n Y_test = y[test_index]\n clf = SVC(gamma = 'auto')\n clf.fit(X_train, Y_train)\n predicted_label = clf.predict(X_test)\n print(clf.score(X_test, Y_test))\n predicted_labels += predicted_label.flatten().tolist()\n true_labels += Y_test.flatten().tolist()\n \n return true_labels, predicted_labels\n\ndef get_confusion_mat(X_true, Y_pred, size = 0):\n confusion_matrix = np.zeros((int(max(X_true)) + 1, int(max(Y_pred)) + 1))\n if(not size == 0):\n confusion_matrix = np.zeros((size, size))\n for i in range(len(X_true)):\n confusion_matrix[int(X_true[i]), int(Y_pred[i])] += 1\n return confusion_matrix\n\ndef evaluate_confusion_mat(confusion_matrix):\n accuracy = np.sum(np.diag(confusion_matrix))/np.sum(confusion_matrix)\n precision = np.divide(np.diag(confusion_matrix), np.sum(confusion_matrix, axis = 0))\n recall = np.divide(np.diag(confusion_matrix), np.sum(confusion_matrix, axis = 1))\n \n acc_arr = len(confusion_matrix)*np.diag(confusion_matrix)/np.sum(confusion_matrix)\n print(\"Accuracy: \" + str(accuracy))\n print(\"Acc_arr: \" + str(acc_arr))\n print(\"Precision: \" + str(precision))\n print(\"Recall: \" + str(recall))\n return accuracy, precision, recall\n#%%\nif __name__ == \"__main__\":\n\n\n \"***Feature Extraction***\"\n\n # Dictionary whose is \n dataset = dict()\n\n path = './images'\n\n # Get all the folder of individuad subject\n for subject in os.listdir(path):\n if subject[0] == '.':\n continue\n print(subject)\n count = 0\n emotion_dirs = os.listdir(path + '/%s' %subject)\n feature_matrix = None\n labels = None\n\n for emotion_dir in emotion_dirs:\n if emotion_dir[0] == '.':\n continue\n # Get the index associated with the emotion\n emotion_label = emotion_labels[emotion_dir]\n\n for f in os.listdir(path + '/%s/%s' %(subject, emotion_dir)):\n img = cv2.imread(path + '/%s/%s/' %(subject, emotion_dir) + f)\n # Uncomment the following two lines to visualize the raw images\n # cv2.imshow(\"raw img\", img)\n # cv2.waitKey(0)\n\n # Extract HOG features\n \n features = feature_extraction(img, orientations=10, pixels_per_cell=(16, 16), cells_per_block=(1, 1))\n\n if features is not None:\n feature_matrix = features if feature_matrix is None else np.append(feature_matrix, features, axis=0)\n labels = np.array([emotion_label]) if labels is None else np.append(labels, np.array([emotion_label]), axis=0)\n\n\n dataset[subject] = (feature_matrix, labels)\n\n\n#%%\n \"***Person-dependent Model***\"\n X, y = dataset[NetID]\n\n # TODO: Use the HOG descriptors to classify different emotions (facial expressions).\n # Here, X is the matrix of HOG descriptors with number of rows equal to the number of images.\n # y is a vector of emotion labels whose length is equal to the number of images.\n true_labels = list()\n predicted_labels = list()\n \n\n \n # Use-fold cross validation to evaluate the model\n true_labels, predicted_labels = evaluate_model(X, y) \n confusion_matrix_enl = get_confusion_mat(true_labels, predicted_labels, 5) \n print(\"Person dependent confusion matrix\")\n plt.imshow(confusion_matrix_enl)\n plt.colorbar()\n plt.show()\n evaluate_confusion_mat(confusion_matrix_enl)\n \n \"***Person-independent Models***\"\n # TODO: Use the model trained on your data to predict another person's emotion.\n Xp1, yp1 = dataset['P1']\n clf = SVC(gamma = 'scale')\n clf.fit(X,y)\n Y_p1 = clf.predict(Xp1)\n \n confusion_mat_p1 = get_confusion_mat(yp1, Y_p1)\n print(str('enl1 and P1') + \" Confusion Matrix\")\n plt.imshow(confusion_mat_p1)\n plt.colorbar()\n plt.figure()\n plt.show()\n evaluate_confusion_mat(confusion_mat_p1)\n \n\n \"***Person-independent Models with LOSO on all subjects***\"\n # TODO: Use leave-one-subject-out cross validation to evaluate the generalized (person-independent) models.\n # You will need to train a model on data from different sets of people and predict the remaining person's emotion.\n \n Xg = []\n yg = []\n for subject in dataset.keys():\n Xg = []\n yg = []\n Xs, X_true = dataset[subject]\n for person in dataset.keys():\n if(subject == person):\n continue\n Xt, yt = dataset[person]\n Xg.append(Xt)\n yg.append(yt)\n Xg = np.concatenate(Xg)\n yg = np.concatenate(yg)\n clf = SVC(gamma = 'scale')\n clf.fit(Xg, yg)\n Y_pred = clf.predict(Xs)\n confusion_matrix = get_confusion_mat(X_true, Y_pred, 5)\n print(str(subject) + \" Confusion Matrix\")\n plt.imshow(confusion_matrix)\n plt.colorbar()\n plt.figure()\n plt.show()\n evaluate_confusion_mat(confusion_matrix)\n \n\n#%%\n \n \"***Parameter Analysis***\"\n # Takes about an hour to run...\n\n # Dictionary whose is \n dataset = dict()\n pixel_sizes = [4, 8, 16, 32, 64]\n bin_sizes = [8,16,32,64]\n path = './images'\n \n acc_arr = []\n \n for b in bin_sizes:\n # Get all the folder of individuad subject\n a_arr = []\n for p_n in pixel_sizes:\n \n for subject in os.listdir(path)[0:3]:\n if subject[0] == '.':\n continue\n print(subject)\n count = 0\n emotion_dirs = os.listdir(path + '/%s' %subject)\n feature_matrix = None\n labels = None\n \n for emotion_dir in emotion_dirs:\n if emotion_dir[0] == '.':\n continue\n # Get the index associated with the emotion\n emotion_label = emotion_labels[emotion_dir]\n \n for f in os.listdir(path + '/%s/%s' %(subject, emotion_dir)):\n img = cv2.imread(path + '/%s/%s/' %(subject, emotion_dir) + f)\n # Uncomment the following two lines to visualize the raw images\n # cv2.imshow(\"raw img\", img)\n # cv2.waitKey(0)\n \n # Extract HOG features\n \n features = feature_extraction(img, orientations=10, pixels_per_cell=(p_n, p_n), cells_per_block=(1, 1))\n \n if features is not None:\n feature_matrix = features if feature_matrix is None else np.append(feature_matrix, features, axis=0)\n labels = np.array([emotion_label]) if labels is None else np.append(labels, np.array([emotion_label]), axis=0)\n dataset[subject] = (feature_matrix, labels)\n X, y = dataset[NetID]\n \n # TODO: Use the HOG descriptors to classify different emotions (facial expressions).\n # Here, X is the matrix of HOG descriptors with number of rows equal to the number of images.\n # y is a vector of emotion labels whose length is equal to the number of images.\n true_labels = list()\n predicted_labels = list()\n \n \n # Use-fold cross validation to evaluate the model\n true_labels, predicted_labels = evaluate_model(X, y)\n \n confusion_matrix_enl = get_confusion_mat(true_labels, predicted_labels, 5)\n accuracy, precision, recall = evaluate_confusion_mat(confusion_matrix_enl)\n a_arr.append(accuracy)\n \n acc_arr.append(a_arr)\n print(a_arr)\n \n print(acc_arr)\n#%%\n #Plot accuracy vs. cell size\nfor a in acc_arr:\n plt.plot(pixel_sizes, a)\n plt.legend(bin_sizes)\n plt.xlabel(\"Cell Size (pixels)\")\n plt.ylabel(\"Accuracy\")","sub_path":"A4_Assignment/emotion_recognition.py","file_name":"emotion_recognition.py","file_ext":"py","file_size_in_byte":11862,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"154162075","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\n\nPE_0317\n\nFirecracker\n\n1856532.8455\n\npi*(2gvh+v^3)^2 / 4g^3\n\nCreated on Thu Sep 28 10:45:54 2017\n@author: mbh\n\"\"\"\nimport time\nimport math\nimport numpy as np\nimport matplotlib.pyplot as plt\n\ndef p317(v0=20,y0=100):\n t=time.clock()\n g=9.81\n xmax=ranges(v0,y0)\n ymax=v0**2/(2*g) \n k=(y0+ymax)/xmax**2 \n vol=(np.pi/(2*k))*(y0**2+y0*v0**2/g+v0**4/(4*g**2)) \n print(vol,time.clock()-t)\n\n#find maximum range for given v0 and yo\ndef ranges(v0,y0,thetaMax=45,thetaRange=45):\n \n res=0.00000000001\n xmax=100\n xmaxLast=0\n while abs(xmax-xmaxLast)>res:\n xmaxLast=xmax\n xmax=0\n for theta in np.arange(thetaMax-thetaRange,thetaMax+thetaRange,2*thetaRange/100):\n x=xRange(v0,y0,theta)\n if x>xmax:\n xmax=x\n thetaMax=theta\n thetaRange/=10\n \n return xmax\n\ndef xRange(v0,y0,theta):\n \n g=9.81\n thetaRad=math.radians(theta)\n vx0=v0*math.cos(thetaRad)\n vy0=v0*math.sin(thetaRad)\n tRise=vy0/g\n yRise=vy0*tRise-0.5*g*tRise**2\n if y0<0 and yRise-h:\n t+=dt\n y=v0*math.sin(thetaRad)*t+(g*t**2)/2\n if y<-h:\n break\n x=v0*math.cos(thetaRad)*t\n xs.append(x)\n ys.append(y)\n \n plt.plot(xs,ys)\n \n print((theta,xs[-1]))\n\n \n\n \n \n\n ","sub_path":"PE_0317/PE_0317.py","file_name":"PE_0317.py","file_ext":"py","file_size_in_byte":1686,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"41209997","text":"'''\nCreate the tables about users.\n\nLast update: 24/04/19\n'''\n# Dependancies\nimport asyncpg, asyncio, time\n\nasync def Create_User_Table(client):\n '''\n Create the user table which will store informations about him\n\n Return: void\n '''\n conn = await client.db.acquire()\n create_query = '''\n CREATE TABLE IF NOT EXISTS user_info(\n register_order SERIAL PRIMARY KEY,\n user_name TEXT DEFAULT 'NONE',\n user_id BIGINT,\n user_register_date TEXT DEFAULT 'NONE',\n user_lang TEXT DEFAULT 'EN',\n user_location TEXT DEFAULT 'NONE',\n user_messages BIGINT DEFAULT 0,\n user_level BIGINT DEFAULT 0,\n user_xp BIGINT DEFAULT 0\n );'''\n \n unique_constraint = 'CREATE UNIQUE INDEX IF NOT EXISTS user_id ON user_info(user_id);'\n\n try:\n await conn.execute(create_query)\n await conn.execute(unique_constraint)\n \n except Exception as error:\n error_time = time.strftime('%d/%m/%y - %H:%M', time.gmtime())\n print('{} - Error in user_info.Create_User_Table : Try#1 {}'.format(error_time, error))\n pass\n \n finally:\n await client.db.release(conn)\n\nasync def Create_User_Pilory(client):\n '''\n The table that contains all the users warns, bans count, kicks etc.\n Everything that is bad for a user.\n\n Return: void\n '''\n conn = await client.db.acquire()\n create_query = '''\n CREATE TABLE IF NOT EXISTS user_pilory(\n user_name TEXT DEFAULT 'NONE',\n user_id BIGINT,\n in_server BIGINT,\n user_warns INT DEFAULT 0,\n user_kicks INT DEFAULT 0,\n user_bans INT DEFAULT 0\n )'''\n\n unique_constraint = 'CREATE UNIQUE INDEX IF NOT EXISTS one_per_server ON user_pilory(user_id, in_server);'\n\n try:\n await conn.execute(create_query)\n await conn.execute(unique_constraint)\n \n except Exception as error:\n error_time = time.strftime('%d/%m/%y - %H:%M', time.gmtime())\n print('{} - Error in user_info.Create_User_Pilory : Try#1 {}'.format(error_time, error))\n pass\n \n finally:\n await client.db.release(conn)","sub_path":"data/init/user_info.py","file_name":"user_info.py","file_ext":"py","file_size_in_byte":2135,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"294347467","text":"import sublime, sublime_plugin\n\nimport sys\nimport os.path\n\nfrom string import Template\n\n\nDEFAULT_PAGE_TEMPLATE = \"templates/PageTemplate.md\"\nPRESET_TEMPLATE_TEXT = \"# $title\\n\\n\"\n\nclass PrepareFromTemplateCommand(sublime_plugin.TextCommand):\n def run(self, edit, **args):\n \"\"\"Prepare a new page content from a named template triggered from run command 'prepare_from_template'.\n\n :Example:\n\n view.run_command('prepare_from_template', {\n 'title': pagename,\n 'template': 'default_page'\n })\n\n :param self: This command instance\n :param edit: The sublime edit instance\n :param args: The command arguments including 'title' and 'template'\n \"\"\"\n\n print(\"Running PrepareFromTemplateCommand\")\n template_name = args['template']\n print(\"Creating new page from template: \", template_name)\n\n text = self.generate_from_template(template_name, args)\n self.view.insert(edit, 0, text)\n\n def generate_from_template(self, template_name, args):\n \"\"\"Generate the text using the template\"\"\"\n\n template_text = self.retrieve_template_text(template_name)\n template = Template(template_text)\n return template.substitute(args)\n\n def retrieve_template_text(self, template_name):\n \"\"\"Retrieve the template text.\n\n The setting 'mde.wikilinks.templates' may be configured with a filename for \n the template. This file (if it exists) will be loaded otherwise the preset \n template will be used\n \"\"\"\n\n template = self.view.settings().get(\"mde.wikilinks.templates\", DEFAULT_PAGE_TEMPLATE)\n \n if not os.path.isfile(template):\n current_file = self.view.file_name()\n current_dir = os.path.dirname(current_file)\n template = os.path.join(current_dir, template)\n\n if os.path.isfile(template):\n print(\"Using template:\", template)\n try:\n with open(template, 'rt') as f:\n return f.read()\n except:\n print(\"Unable to read template:\", sys.exc_info()[0])\n\n # Unable to load template so using preset template \n print(\"Template:\", template, \"not found. Using preset.\")\n return PRESET_TEMPLATE_TEXT\n","sub_path":"Sublime_Text/Data/Packages/MarkdownEditing/prepare_from_template.py","file_name":"prepare_from_template.py","file_ext":"py","file_size_in_byte":2297,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"614655349","text":"#! /usr/bin/env python\n# -*- coding: utf-8 -*-\n\"\"\"\nExtract series information from the IMDB web page.\n\"\"\"\n\nfrom __future__ import (\n division, print_function, absolute_import, unicode_literals)\n\n# Standard libraries.\nimport re\nimport csv\nimport argparse\nimport functools\n\n# Third party libraries.\nimport py\nimport requests\nfrom bs4 import BeautifulSoup\n\nfrom .unicodewriter import UnicodeWriter\n\n__date__ = \"2018/01/01 11:30:30 hoel\"\n__author__ = \"`Berthold Höllmann `__\"\n__copyright__ = \"Copyright © 2011,2013 by Berthold Höllmann\"\n\n\nEPISODE_HEADER = re.compile(\n r'Season (?P\\d+), Episode (?P\\d+):')\n\n\nHEADERS = {'version': (\"Mozilla/5.0 (X11; Linux i686 on x86_64; rv:5.0) \"\n \"Gecko/20100101 Firefox/5.0\")}\n\n\nclass IMDBEntry(object):\n\n \"Handle IMDB episodes information for TV series.\"\n\n def __init__(self, season, entry):\n self.season = season\n _entry = entry.parent\n self.episode = int(_entry.find(\n \"meta\", itemprop='episodeNumber').get(\"content\"))\n link = _entry.find('a', itemprop=\"name\")\n self.title = link.get('title')\n self.url = ('http://www.imdb.com%s' %\n link.get('href'))\n self.url = self.url[:self.url.rfind(\"?\")]\n self.descr = _entry.find('div', itemprop=\"description\").text\n\n def list(self):\n \"Return information list.\"\n return (None, self.season, self.episode, None, None, None,\n \"=HYPERLINK(\\\"{}\\\";\\\"{}\\\")\".format(\n self.url, self.title), self.descr)\n\n def __lt__(self, other):\n return self.episode < other.episode\n\n def __le__(self, other):\n return self.episode <= other.episode\n\n def __eq__(self, other):\n return self.episode == other.episode\n\n def __ne__(self, other):\n return self.episode != other.episode\n\n def __gt__(self, other):\n return self.episode > other.episode\n\n def __ge__(self, other):\n return self.episode >= other.episode\n\n\nclass IMDBInfo(object):\n\n \"Process html page from IMDB\"\n\n def __init__(self, args):\n self.url = self.get_url(args.url[0])\n\n self.series = u' '.join(i.decode('utf-8') for i in args.title)\n self.opener = functools.partial(requests.get, headers=HEADERS)\n\n data = self.opener(self.url)\n self.doc = BeautifulSoup(data.text, 'lxml-xml')\n\n def get_url(self, url):\n path = py.path.local(url)\n res = url\n if path.exists():\n with open(path) as csvfile:\n inforeader = csv.reader(csvfile)\n res = next(inforeader)[0].split('\"')[1]\n while res.endswith('/'):\n res = res[:-1]\n if not res.endswith('/episodes'):\n res += '/episodes'\n return res\n\n def __call__(self):\n self.process_data()\n\n def process_data(self):\n \"Generate the csv file.\"\n\n seasons = [int(i.get(\"value\"))\n for i in self.doc.find(\"select\", id='bySeason')('option')]\n\n with open('{}.csv'.format(self.series.strip()), 'w') as filep:\n writer = UnicodeWriter(\n filep, delimiter=str(';'),\n quoting=csv.QUOTE_MINIMAL)\n\n writer.writerow([\"=HYPERLINK(\\\"{}\\\";\\\"{}\\\")\".format(\n self.url.strip()[:-9], self.series.strip())])\n writer.writerow([\n '=HYPERLINK(\"#Übersicht\";\"Datum\")',\n None, None,\n \"Disk\", \"Index\", \"Diskset\", \"IMDB URL\", None,\n \"=MITTELWERT(I3:I10000)\", \"=SUMME(J3:J10000)\"])\n\n for season in seasons:\n print(\"Season {}\".format(season))\n\n params = {'season': season}\n\n data = self.opener(self.url, params=params)\n doc = BeautifulSoup(data.text, 'lxml-xml')\n\n ep_list = doc.select(\"div[class='list detail eplist']\")[0]\n\n sel_str = r\"^info\"\n episodes = [\n IMDBEntry(season, i)\n for i in\n ep_list(\n \"div\", attrs={\"class\": re.compile(sel_str)})]\n\n episodes.sort()\n\n [writer.writerow(\n [j.strip() if isinstance(j, str) else j\n for j in i.list()])\n for i in episodes]\n\n def get_series(self):\n url = self.url[:-9]\n data = self.opener(url)\n doc = BeautifulSoup(data.text, 'lxml-html')\n\n wrapper = doc.find(\"div\", {'class': 'title_wrapper'})\n\n orig = wrapper.find(\"div\", {'class': 'originalTitle'})\n if orig:\n res = orig.text.strip()\n if res.endswith(\" (original title)\"):\n res = res[:-17]\n return res\n else:\n return wrapper.h1.string.strip()\n\n\ndef main():\n \"Main program.\"\n\n parser = argparse.ArgumentParser(\n description='Extract IMDB information for TV series.')\n parser.add_argument('url', metavar='URL', type=str, nargs=1,\n help='URL string / existing CSV file')\n parser.add_argument('title', metavar='TITLE', type=str, nargs='*',\n help='title string', default=\"\")\n\n args = parser.parse_args()\n\n prog = IMDBInfo(args)\n if len(prog.series) == 0:\n prog.series = prog.get_series()\n\n print(\"URL : {}\".format(prog.url))\n print(\"series: {}\".format(prog.series))\n\n prog()\n\n raise SystemExit\n\n\nif __name__ == \"__main__\":\n main()\n\n# args = http://www.imdb.com/title/tt1327801/ Glee test\n# http://www.imdb.com/title/tt1327801/episodes?season=2\n# http://www.imdb.com/title/tt0098844\n\n# Local Variables:\n# mode: python\n# compile-command: \"cd ../..;python3 setup.py install --user\"\n# time-stamp-pattern: \"30/__date__ = \\\"%:y/%02m/%02d %02H:%02M:%02S %u\\\"\"\n# End:\n","sub_path":"berhoel/imdb_extract/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":5877,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"651588571","text":"#!/usr/bin/env python3\n\nfrom fd_account import read_ac, group\n\nlogin_file = '0_login.txt'\n\ndict_ac_group = {}\ndict_login = {}\n\n#=============================================================\n\ndef check_login():\n global dict_ac_group, dict_login, login_file \n f = open(login_file, 'r')\n while True:\n line = f.readline()\n if not line or line.strip() == '':\n break\n bidno = line.split(',')[1].split()[1].strip()\n dict_login[bidno] = line.strip()\n del(dict_ac_group[bidno])\n f.close()\n\n\ndef main():\n global dict_ac_group, dict_bidok, dict_bid112\n dict_ac_group = read_ac()[group]\n check_login()\n print('\\r\\nlogin ok :')\n for bidno in dict_login:\n print(dict_login[bidno])\n print('login ok count: %d \\r\\n' % len(dict_login))\n print('\\r\\nnot login yet :')\n for bidno in dict_ac_group:\n print(dict_ac_group[bidno])\n print('not login count: %d \\r\\n' % len(dict_ac_group))\n\nmain()\n\n","sub_path":"pai/mine/1504/6/rpt_login.py","file_name":"rpt_login.py","file_ext":"py","file_size_in_byte":1103,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"465445500","text":"import datetime\nnow=datetime.datetime.now()\n\n# ユーザーの名前を入力\nuser=input('名前を入力して下さい')\n\n# 時間によって挨拶を変えるための分岐\nif now.hour >= 10 and now.hour<=18:\n print('こんにちは',user,'さん')\nelif now.hour>=18 or now.hour<=4:\n print('こんばんは',user,'さん')\nelse:\n print('おはようございます',user,'さん')\n\ndef wareki():\n year = int(input('西暦を入力して下さい'))\n while year<1868:\n print('その年には対応していません')\n year = int(input('もう一度西暦を入力して下さい'))\n if year >1868 and year<1912:\n print('その年は明治{}年です。'.format(year-1867))\n elif year==1868:\n print('その年は明治元年です。')\n elif year >1912 and year<1926:\n print('その年は大正{}年です。'.format(year-1911))\n elif year ==1912:\n print('その年は大正元年です。')\n elif year >1926 and year<1989:\n print('その年は昭和{}年です。'.format(year-1925))\n elif year ==1926:\n print('その年は昭和元年です。')\n elif year >1989 and year<2019:\n print('その年は平成{}年です。'.format(year-1988))\n elif year ==1989:\n print('その年は平成元年です。')\n elif year >2019 :\n print('その年は令和{}年です。'.format(year-2018))\n elif year ==2019:\n print('その年は令和元年です。')\n\ndef keisan():\n n=int(input('1つ目の整数を入力してください:'))\n m=input('計算記号を入力してください')\n l=int(input('2つ目の整数を入力してください:'))\n if m == '+':\n print('答え:{}'.format(n+l))\n elif m == '-':\n print('答え:{}'.format(n-l))\n elif m == '×':\n print('答え:{}'.format(n*l))\n elif m == '÷':\n print('答え:{}'.format(n/l))\n elif m == '%':\n print('答え:{}'.format(n%l))\n\nkeisan()","sub_path":"効果測定.py","file_name":"効果測定.py","file_ext":"py","file_size_in_byte":1998,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"175175618","text":"s = input()\nlist_a = list(s)\nint_s = int(s)\nlist_a.sort()\n\n# TH1: Nếu dãy chia hết cho 3 thì sắp xếp dãy giảm gần, in dãy -> thoát\nif int_s % 3 == 0:\n list_a.reverse()\n print(''.join(list_a))\n exit()\n\nx = int(int_s % 3)\n\n# tìm i trong a sao cho a[i] % 3 = x, nếu không trả về -1\ndef senario_one(input_string, x):\n ind_result = -1\n if str(x) in input_string:\n ind_result = input_string.index(str(x))\n return ind_result\n \n if str(x + 3) in input_string:\n ind_result = input_string.index(str(x + 3))\n return ind_result\n \n if str(x + 6) in input_string:\n ind_result = input_string.index(str(x + 6))\n return ind_result\n\n return ind_result\n\n# tìm vị trí i, j trong a sao cho a[i] % 3 = x, a[j] % 3 = x, nếu không trả về -1, -1\ndef senario_two(input_string, x):\n first_index = senario_one(input_string, x)\n second_index = senario_one(input_string[first_index + 1: ], x) + first_index + 1\n return first_index, second_index\n\n# Tìm và xóa vị trí không thỏa mãn điều kiện, sắp xếp lại dãy giảm dần, in dãy\nind = senario_one(list_a, x)\nif ind == -1:\n ind_1, ind_2 = senario_two(list_a, (x*2)%3)\n if ind_1 != -1 and ind_2 != -1:\n list_a.remove(list_a[ind_1])\n list_a.remove(list_a[ind_2 - 1])\n\n list_a.reverse()\n\n if len(list_a) == 1:\n print(str(list_a[0]))\n exit()\n else:\n print(''.join(list_a))\n exit()\n\nlist_a.remove(list_a[ind])\nlist_a.reverse()\nif list_a != []:\n print(''.join(list_a))\n exit()","sub_path":"Homework/Week 5/Lock&Lock.py","file_name":"Lock&Lock.py","file_ext":"py","file_size_in_byte":1620,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"394050376","text":"from django.shortcuts import get_object_or_404, render, redirect\n\nfrom django.contrib.auth import authenticate, login as login, logout\n\nfrom django.contrib.auth.decorators import login_required\nfrom django.contrib.auth.models import User\n\nfrom django.utils import timezone\nfrom django.utils.crypto import get_random_string\n\nfrom django.urls import reverse\n\nfrom .models import Team, StationStaff, Station, StationComponent, StationCheckpoint, Timebox, Edition, StationComponentTeamPoints, Scoreboard\n\nfrom .forms import ContactForm, TeamPointsLineForm\n\nfrom django.forms import inlineformset_factory\n\nfrom django.core.mail import EmailMessage\nfrom django.template import Context\nfrom django.template.loader import get_template\n\ndef index(request):\n\treturn render(request, 'kimball/index.html')\n\ndef contact(request):\n\tform_class = ContactForm\n\n\tif request.method == 'POST':\n\t\tform = form_class(data=request.POST)\n\n\t\tname = request.POST.get('name', '')\n\t\tsender = request.POST.get('sender', '')\n\t\tsubject = request.POST.get('subject', '')\n\t\tmessage = request.POST.get('message', '')\n\t\tcc_myself = request.POST.get('cc_myself', False)\n\n\t\tif form.is_valid():\n\t\t\ttemplate = get_template('kimball/contact_template.txt')\n\t\t\tcontext = Context({\n\t\t\t\t'contact_name': name,\n\t\t\t\t'contact_email': sender,\n\t\t\t\t'contact_subject': subject,\n\t\t\t\t'form_content': message,\n\t\t\t})\n\t\t\tcontent = template.render(context)\n\t\t\temail = EmailMessage(\n\t\t\t\t\"Novo contacto via kimball app\",\n\t\t\t\tcontent,\n\t\t\t\t\"No Reply kimball \",\n\t\t\t\t['kimball@escutismo.pt'],\n\t\t\t\theaders = {'Reply-To': sender }\n\t\t\t)\n\t\t\temail.send()\n\t\t\treturn render(request, 'kimball/contact.html' )\n\n\treturn render(request, 'kimball/contact.html', {'form': form_class} )\n\ndef login_view(request):\n\tif 'next' in request.POST:\n\t\tnext_page = request.POST['next']\n\telse:\n\t\tnext_page = reverse('index')\n\tif 'username' in request.POST and 'password' in request.POST:\n\t\tusername = request.POST['username']\n\t\tpassword = request.POST['password']\n\t\tuser = authenticate(request, username=username, password=password)\n\t\tif user is not None:\n\t\t\tlogin(request, user)\n\t\t\treturn redirect(next_page)\n\n\treturn render(request, 'kimball/login.html', {'next':next_page})\n\ndef logout_view(request):\n\tlogout(request)\n\treturn render(request, 'kimball/login.html')\n\ndef timeline(request):\n\n\tif 'edidion_id' in request.POST:\n\t\tedition_id = request.POST['edition_id']\n\t\tedition = Edition.objects.get(pk=edidion_id);\n\telse:\n\t\tedition = None\n\n\teditions = Edition.objects.all()\n\n\tif edition==None and editions.count()>0:\n\t\tedition = editions[0]\n\n\tif edition!=None:\n\t\ttimeboxes = Timebox.objects.filter(edition=edition).order_by('start_date')\n\telse:\n\t\ttimeboxes = []\n\n\treturn render(request, 'kimball/timeline.html', {'edition': edition, 'editions':editions, 'timeboxes': timeboxes})\n\ndef scoreboard(request):\n\n\tboard = Scoreboard.objects.all()\n\n\treturn render(request, 'kimball/scoreboard.html', {'board': board})\n\n@login_required(login_url='/kimball/login')\ndef team(request, team_id):\n\n\tteam = Team.objects.get(pk=team_id)\n\n\treturn render(request, 'kimball/team.html', {'team': team})\n\n@login_required(login_url='/kimball/login')\ndef station(request, station_id):\n\treturn render(request, 'kimball/station.html', {'station_id': station_id})\n\n@login_required(login_url='/kimball/login')\ndef checkin(request, checkin_code):\n\tcheckpoints = StationCheckpoint.objects.filter(checkin_code=checkin_code,checkout__isnull=True)\n\tif checkpoints.count()==1:\n\t\tcheckpoint = checkpoints[0]\n\t\treturn report(request, checkpoint.station.id, checkin_code)\n\telif checkpoints.count()>1:\n\t\treturn checkpoint(request, checkin_code)\n\telse:\n\t\tstaff_stations_ids = StationStaff.objects.filter(user=request.user).values_list('station_id').distinct()\n\t\tstations = Station.objects.filter(id__in=staff_stations_ids).order_by('start_date')\n\t\tif stations.count()==1:\n\t\t\tstation = stations[0]\n\t\t\tpatrol = Team.objects.filter(checkin_code=checkin_code)\n\t\t\tif patrol:\n\t\t\t\tcheckpoint = StationCheckpoint(checkin_code=checkin_code, station=station, patrol=patrol, checkin=timezone.now(), checkedin_by=request.user)\n\t\t\t\tcheckpoint.save()\n\t\t\t\treturn report(request, station.id, checkin_code)\n\t\t\telse:\n\t\t\t\terro = 'Equipa desconhecida!'\n\t\telif stations.count()>1:\n\t\t\terro = 'Escolha o posto...'\n\t\telse:\n\t\t\terro = 'Posto desconhecido!'\n\t\n\t\treturn render(request, 'kimball/checkin.html', {'erro': erro, 'stations': stations})\n\n@login_required(login_url='/kimball/login')\ndef checkpoint(request, checkin_code):\n\n\tif 'station_id' in request.POST:\n\t\tstation_id = request.POST['station_id']\n\t\tstation = Station.objects.get(pk=station_id)\n\telse:\n\t\tstation = None\n\n\tif station == None:\n\t\tstaff_stations_ids = StationStaff.objects.filter(user=request.user).values_list('station_id').distinct()\n\t\tstations = Station.objects.filter(id__in=staff_stations_ids).order_by('start_date')\t\n\n\t\tif stations.count()==1:\n\t\t\tstation = stations[0]\n\n\tcheckpoint = None\n\tif station:\n\t\tcheckpoint = StationCheckpoint.objects.filter(station=station, checkin_code=checkin_code)\n\t\tif checkpoint==None:\n\t\t\tpatrol = Team.objects.filter(checkin_code=checkin_code)\n\t\t\tcheckpoint = StationCheckpoint(checkin_code=checkin_code, station=station, patrol=patrol, checkin=timezone.now(), checkedin_by=request.user)\n\t\t\tcheckpoint.save()\n\n\tif checkpoint:\n\t\treturn report(request, checkpoint.station.id, checkpoint.checkin_code)\n\telse:\n\t\treturn render(request, 'kimball/checkpoint.html', {'checkin_code': checkin_code, 'stations':stations})\n\n@login_required(login_url='/kimball/login')\ndef report(request, station_id=None, checkin_code=None):\n\n\tPointsFormSet = inlineformset_factory(StationCheckpoint, StationComponentTeamPoints, form=TeamPointsLineForm, fields=('component', 'points', 'notes',), extra=0, can_delete=False)\n\n\tif request.method == 'POST':\n\t\tif 'checkin_code' in request.POST:\n\t\t\tcheckin_code = request.POST['checkin_code']\n\t\t\tcheckpoint = StationCheckpoint.objects.filter(checkin_code=checkin_code,checkout__isnull=True)\n\t\t\tteampoints = PointsFormSet(request.POST, request.FILES, instance=checkpoint)\n\t\t\tif teampoints.is_valid():\n\t\t\t\tteampoints.save()\n\t\t\t\t\n\t\t\treturn checkpoint(request, None)\n\t\telse:\n\t\t\tcheckpoint = None\n\n\t\tif 'station_id' in request.POST:\n\t\t\tstation_id = request.POST['station_id']\n\t\t\tstation = Station.objects.get(pk=station_id)\n\t\telse:\n\t\t\tstation = None\n\telse:\n\t\tcheckpoint = None\n\t\tstation = None\n\n\tstaff_stations_ids = StationStaff.objects.filter(user=request.user).values_list('station_id').distinct()\n\tstations = Station.objects.filter(id__in=staff_stations_ids).order_by('start_date')\t\n\n\tif station == None and stations.count()>0:\n\t\tstation = stations[0]\n\n\tif station != None:\n\t\tcheckpoints = StationCheckpoint.objects.filter(station=station,checkout__isnull=True).order_by('checkin')\n\telse:\n\t\tcheckpoints = []\n\n\tif checkpoint == None and checkpoints.count()==1:\n\t\tcheckpoint = checkpoints[0]\n\n\tif checkpoint != None:\n\t\tstart_points(station, checkpoint)\n\t\tteampoints = PointsFormSet(instance=checkpoint)\n\telse:\n\t\tteampoints = None\n\n\treturn render(request, 'kimball/report.html', {'stations': stations, 'checkpoints':checkpoints, 'station': station, 'checkpoint': checkpoint, 'teampoints':teampoints})\n\ndef start_points(station, checkpoint):\n\tif not StationComponentTeamPoints.objects.filter(checkpoint=checkpoint).exists():\n\t\tcomponents = StationComponent.objects.filter(station=station, parent__isnull=True)\n\t\tfor component in components:\n\t\t\tstart_component_points(component, checkpoint)\n\ndef start_component_points(component, checkpoint):\n\tc = StationComponentTeamPoints(component=component, checkpoint=checkpoint)\n\tc.save()\n\tchildren = StationComponent.objects.filter(station=station, parent=component)\n\tfor child in children:\n\t\tstart_component_points(component, checkpoint)\n\n@login_required(login_url='/kimball/login')\ndef checkout(request, checkpoint_id):\n\n\tfailed = False\n\tmsg = 'Checkout feito com sucesso'\n\n\tcheckpoint = StationCheckpoint.objects.get(pk=checkpoint_id)\n\n\tpoints = StationComponentTeamPoints.objects.filter(checkpoint=checkpoint)\n\tcomponents = StationComponent.objects.filter(station=checkpoint.station)\n\n\tif points.count()>100:\n\t\t\n\t\tif checkpoint.checkout__isnull==True:\n\t\t\tfailed = True\n\t\t\tmsg = 'Ja foi feito checkout neste posto para esta equipa'\n\t\telse:\n\n\t\t\tcheckpoint.checkout = timezone.now()\n\t\t\tcheckpoint.checkedout_by = request.user\n\t\t\tcheckpoint.save()\n\n\t\t\tteam = checkpoint.patrol\n\t\t\tteam.checkin_code = get_random_string(length=32)\n\t\t\tteam.save()\n\t\t\n\telse:\n\t\tfailed = True\n\t\tmsg = 'Checkout falhou!'\n\n\n\treturn render(request, 'kimball/checkout.html', {'failed': failed, 'msg': msg})\n","sub_path":"kimball/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":8618,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"15892287","text":"\"\"\"\n{\n \"author\": \"Yucheng Huang\",\n \"difficulty\": \"medium\",\n \"link\": \"https://leetcode.com/problems/beautiful-arrangement-ii/description/\",\n \"beats\": 0.2803,\n \"category\": [\"array\"],\n \"tags\": [],\n \"questions\": []\n}\n\"\"\"\n\n\"\"\"\n思路\n\t- [1,5,2,4,3], n=5, k=4\n\t- [1,5,4,3,2], n=5, k=2\n\t- [1,5,2,3,4], n=5, k=3\n\"\"\"\n\nclass Solution:\n def constructArray(self, n, k):\n \"\"\"\n :type n: int\n :type k: int\n :rtype: List[int]\n \"\"\"\n lst = [1]\n l,r = 2,n\n k -= 1\n while k>0:\n lst.append(r)\n r -= 1\n k -= 1\n if k<= 0:\n break\n lst.append(l)\n l += 1\n k -= 1\n if lst[-1]>r:\n while len(lst) 1 else nets[0])\n finally:\n for net, was_training in zip(nets, were_training):\n if was_training:\n net.train()\n\n\n@contextmanager\ndef training(*nets):\n \"\"\"Temporarily switch to training mode.\"\"\"\n were_training = [net.training for net in nets]\n try:\n for net in nets:\n net.train()\n yield (nets if len(nets) > 1 else nets[0])\n finally:\n for net, was_training in zip(nets, were_training):\n if not was_training:\n net.train()\n\n\nclass freeze:\n def __init__(self, net, fn=None):\n \"\"\"Temporarily switch to evaluation mode.\"\"\"\n was_frozen = []\n self.params = net.parameters() if hasattr(net, 'parameters') else net\n for i, param in enumerate(self.params):\n was_frozen.append(not param.requires_grad)\n if fn is None or fn(param):\n param.requires_grad = False\n self.was_frozen = was_frozen\n\n def __enter__(self):\n pass\n\n def __exit__(self, exc_type, exc_val, exc_tb):\n for i, param in enumerate(self.params):\n if not self.was_frozen[i]:\n param.requires_grad = True\n\n\nclass unfreeze:\n def __init__(self, net, fn=None):\n \"\"\"Temporarily switch to evaluation mode.\"\"\"\n was_frozen = []\n self.params = net.parameters() if hasattr(net, 'parameters') else net\n for i, param in enumerate(self.params):\n was_frozen.append(not param.requires_grad)\n if fn is None or fn(param):\n param.requires_grad = True\n self.was_frozen = was_frozen\n\n def __enter__(self):\n pass\n\n def __exit__(self, exc_type, exc_val, exc_tb):\n for i, param in enumerate(self.params):\n if self.was_frozen[i]:\n param.requires_grad = False\n\n\nclass Identity(torch.nn.Module):\n def forward(self, x, *args, **kwargs):\n return x\n\n\nsubset_list = []\n\n\n@contextmanager\ndef no_subset():\n global subset_list\n redos = [undo_subset() for undo_subset in list(subset_list)]\n yield\n subset_list = [redo() for redo in redos]\n\n\ndef slice_parameters(obj, names, indexer, optimizer):\n subset_module_params = {}\n\n def do_subset():\n subset_module_params.clear()\n for module_param_name in names:\n module_param = getattr(obj, module_param_name)\n if module_param is None:\n continue\n\n subset_module_param = torch.nn.Parameter(module_param[indexer], requires_grad=module_param.requires_grad)\n optimizer_saved_state = None\n optimizer_subset_state = None\n if optimizer is not None and optimizer.state[module_param]:\n optimizer_saved_state = optimizer.state[module_param]\n for group in optimizer.param_groups:\n group['params'] = [subset_module_param if x is module_param else x for x in group['params']]\n optimizer_subset_state = {}\n for optim_param_name, optim_param in optimizer_saved_state.items():\n if hasattr(optim_param, 'shape') and optim_param.shape == module_param.shape:\n optimizer_subset_state[optim_param_name] = optim_param[indexer]\n else:\n optimizer_subset_state[optim_param_name] = optim_param\n optimizer.state[subset_module_param] = optimizer_subset_state\n del optimizer.state[module_param]\n\n subset_module_params[module_param_name] = (subset_module_param,\n module_param.device,\n module_param, # .detach().cpu(),\n optimizer_saved_state,\n optimizer_subset_state)\n setattr(obj, module_param_name, subset_module_param)\n\n subset_list.append(undo_subset)\n return undo_subset\n\n def undo_subset():\n for module_param_name, (subset_module_param,\n device,\n module_param_detached,\n optimizer_saved_state,\n optimizer_subset_state) in subset_module_params.items():\n\n module_param_detached.data[indexer] = subset_module_param.detach()\n restored_param = module_param_detached # torch.nn.Parameter(module_param_detached.to(device), requires_grad=subset_module_param.requires_grad)\n\n # Update old embeddings with new ones\n\n if optimizer_saved_state is not None:\n for group in optimizer.param_groups:\n group['params'] = [restored_param if x is subset_module_param else x for x in group['params']]\n\n for optim_param_name, optim_param in optimizer_subset_state.items():\n if hasattr(optim_param, 'shape') and optim_param.shape == subset_module_param.shape:\n subset_param = optimizer_subset_state[optim_param_name]\n optimizer_subset_state[optim_param_name] = optimizer_saved_state[optim_param_name]\n optimizer_subset_state[optim_param_name][indexer] = subset_param\n optimizer.state[restored_param] = optimizer_subset_state\n del optimizer.state[subset_module_param]\n setattr(obj, module_param_name, restored_param)\n\n subset_list.remove(undo_subset)\n\n return do_subset\n\n return do_subset()\n\n\ndef torch_clone(obj, device=None):\n bio = io.BytesIO()\n with warnings.catch_warnings():\n warnings.filterwarnings(\"ignore\", \"Couldn't retrieve source code for\")\n torch.save(obj, bio)\n bio.seek(0)\n return torch.load(bio, map_location=torch_global.device if device is None else device)\n\n\ndef extract_slices(sequences, flat_begins, flat_ends, flat_sample_idx):\n if isinstance(sequences, torch.Tensor):\n num, device = sequences.shape[1], sequences.device\n elif isinstance(sequences, (list, tuple)):\n num, device = sequences[0].shape[1], sequences[0].device\n elif isinstance(sequences, dict):\n num, device = next(iter(sequences.values())).shape[1], next(iter(sequences.values())).device\n else:\n raise Exception(\"Can only extract slices from Tensor, list of Tensor or dict of (any, Tensor)\")\n\n if len(flat_ends):\n mention_length = (flat_ends - flat_begins).max().item()\n else:\n mention_length = 0\n mentions_from_sequences_col_indexer = torch.min(torch.arange(mention_length).unsqueeze(0) + flat_begins.unsqueeze(1),\n torch.tensor(num, device=device) - 1)\n mentions_from_sequences_row_indexer = flat_sample_idx.unsqueeze(1)\n # token_id_[]\n mask = mentions_from_sequences_col_indexer < flat_ends.unsqueeze(1)\n if isinstance(sequences, torch.Tensor):\n return sequences[mentions_from_sequences_row_indexer, mentions_from_sequences_col_indexer], mask\n elif isinstance(sequences, (list, tuple)):\n return [seq[mentions_from_sequences_row_indexer, mentions_from_sequences_col_indexer] for seq in sequences], mask\n elif isinstance(sequences, dict):\n return {k: seq[mentions_from_sequences_row_indexer, mentions_from_sequences_col_indexer] for k, seq in sequences.items()}, mask\n print(\"Cannot be here, already raised and exception\")\n\n","sub_path":"nlstruct/core/torch.py","file_name":"torch.py","file_ext":"py","file_size_in_byte":8869,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"42560554","text":"'''\nThis program demonstrates the concepts of Classes and Obejcts.\n\nAuthor: Deborah\n'''\n\nfrom Circle import Circle\n\ndef main():\n \n circle1 = Circle(2.5) # Create a new object called circle1\n '''\n circle1.setRadius(1.5)\n print(circle1.getArea())\n print(\"The perimeter is \", circle1.getPerimeter())\n print(\"The radius of circle is \", circle1.getRadius())\n '''\n radius = 2.5\n circle1.printAll()\n\n# Start the program\nmain()\n","sub_path":"ITMD_513/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":450,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"405575714","text":"#coding: utf-8\nimport smbus\nimport time\nimport datetime\nimport requests\nimport RPi.GPIO as GPIO\n\n\nbus_number = 1\ni2c_address = 0x76\ndate = datetime.datetime.now()\ntime = date.strftime(\"%Y/%m/%d %H:%M\")\n\nbus = smbus.SMBus(bus_number)\n\ndigT = []\ndigH = []\n\nt_fine = 0.0\n\n\ndef writeReg(reg_address, data):\n bus.write_byte_data(i2c_address,reg_address,data)\n\ndef get_calib_param():\n calib = []\n \n for i in range (0x88,0x88+24):\n calib.append(bus.read_byte_data(i2c_address,i))\n calib.append(bus.read_byte_data(i2c_address,0xA1))\n for i in range (0xE1,0xE1+7):\n calib.append(bus.read_byte_data(i2c_address,i))\n\n digT.append((calib[1] << 8) | calib[0])\n digT.append((calib[3] << 8) | calib[2])\n digT.append((calib[5] << 8) | calib[4])\n\n digH.append( calib[24] )\n digH.append((calib[26]<< 8) | calib[25])\n digH.append( calib[27] )\n digH.append((calib[28]<< 4) | (0x0F & calib[29]))\n digH.append((calib[30]<< 4) | ((calib[29] >> 4) & 0x0F))\n digH.append( calib[31] )\n \n for i in range(1,2):\n if digT[i] & 0x8000:\n digT[i] = (-digT[i] ^ 0xFFFF) + 1\n\n for i in range(0,6):\n if digH[i] & 0x8000:\n digH[i] = (-digH[i] ^ 0xFFFF) + 1 \n\ndef readData():\n setup()\n get_calib_param()\n \n data = []\n for i in range (0xF7, 0xF7+8):\n data.append(bus.read_byte_data(i2c_address,i))\n temp_raw = (data[3] << 12) | (data[4] << 4) | (data[5] >> 4)\n hum_raw = (data[6] << 8) | data[7]\n \n temp = round(compensate_T(temp_raw), 1)\n hum = round(compensate_H(hum_raw), 1)\n\n return temp, hum\n\n\ndef compensate_T(adc_T):\n global t_fine\n v1 = (adc_T / 16384.0 - digT[0] / 1024.0) * digT[1]\n v2 = (adc_T / 131072.0 - digT[0] / 8192.0) * (adc_T / 131072.0 - digT[0] / 8192.0) * digT[2]\n t_fine = v1 + v2\n temperature = t_fine / 5120.0\n \n return temperature\n\n\ndef compensate_H(adc_H):\n global t_fine\n var_h = t_fine - 76800.0\n if var_h != 0:\n var_h = (adc_H - (digH[3] * 64.0 + digH[4]/16384.0 * var_h)) * (digH[1] / 65536.0 * (1.0 + digH[5] / 67108864.0 * var_h * (1.0 + digH[2] / 67108864.0 * var_h)))\n else:\n return 0\n var_h = var_h * (1.0 - digH[0] * var_h / 524288.0)\n if var_h > 100.0:\n var_h = 100.0\n elif var_h < 0.0:\n var_h = 0.0\n \n return var_h\n\n\ndef setup():\n osrs_t = 1 #Temperature oversampling x 1\n osrs_p = 1 #Pressure oversampling x 1\n osrs_h = 1 #Humidity oversampling x 1\n mode = 3 #Normal mode\n t_sb = 5 #Tstandby 1000ms\n filter = 0 #Filter off\n spi3w_en = 0 #3-wire SPI Disable\n\n ctrl_meas_reg = (osrs_t << 5) | (osrs_p << 2) | mode\n config_reg = (t_sb << 5) | (filter << 2) | spi3w_en\n ctrl_hum_reg = osrs_h\n\n writeReg(0xF2,ctrl_hum_reg)\n writeReg(0xF4,ctrl_meas_reg)\n writeReg(0xF5,config_reg)\n \n\n \n\nif __name__ == '__main__':\n try:\n temp, hum = readData()\n print(\"温度:\" + str(temp) + \"℃\")\n print(\"湿度:\" + str(hum) + \"℃\")\n except KeyboardInterrupt:\n pass\n\n\n\n\n\n\n\n","sub_path":"temp_hum.py","file_name":"temp_hum.py","file_ext":"py","file_size_in_byte":3137,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"299300459","text":"#---------------------------\n#Creator: Brittany Manuel\n#Created: October 27, 2014\n#Revisions: October 31, 2014\n#File: diagonal.py\n#Assignment: 8\n#---------------------------\n\n#---------------------------\n#Update one\n#---------------------------\n\ndef diagonal(board):\n\n\twidth = len(board[0])\n\theight = len(board)\n\n\tfor row in range(height):\n\t\tfor column in range(width):\n\t\t\t\n\t\t\tif row == column:\n\t\t\t\tboard[row][column] = 1 \n\n\t\t\telse:\n\t\t\t\tboard[row][column] = 0\n\n\treturn board","sub_path":"08_Game of Life/diagonal.py","file_name":"diagonal.py","file_ext":"py","file_size_in_byte":474,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"554731511","text":"#####################################################\n# project: 8th project of Python programming #\n# name: Plants vs Zombies part2 #\n# author: Baitao #\n# date: 2014-7-1 #\n#####################################################\n\n#coding: utf-8\nimport simpleguitk as simplegui\nimport math\nimport random\nimport time\n\n# globals for user interface\nWIDTH = 800\nHEIGHT = 600\nscore = 0\nscore_ori = 0\nlives = 1000\nstarted = False\nover = False\nplantID = 0\natt_list = list()\nzombie_vel = -0.5\nzombie_interval = 5000\n\n# globals set\nzombie_group = set()\nshooter_group = set()\nsunflower_group = set()\nsunshine_group = set()\nbullet_group = set()\nexplosion_group = set()\n\n# class definition\nclass ImageInfo:\n def __init__(self, center, size, radius = 0, animated = False, frame = None ,lifespan = None):\n self.center = center\n self.size = size\n self.radius = radius\n if lifespan:\n self.lifespan = lifespan\n else:\n self.lifespan = float('inf')\n self.animated = animated\n if frame:\n self.frame = frame\n else:\n self.frame = 1\n def get_center(self):\n return self.center\n\n def get_size(self):\n return self.size\n\n def get_radius(self):\n return self.radius\n\n def get_lifespan(self):\n return self.lifespan\n\n def get_animated(self):\n return self.animated\n \n def get_frame(self):\n return self.frame\n \nclass Sprite:\n def __init__(self, pos, vel, image, info, health = None, attach = 0, attack = None, attach_obj = None, sound = None):\n self.pos = [pos[0],pos[1]]\n self.vel = [vel[0],vel[1]]\n self.image = image\n self.image_center = info.get_center()\n self.image_size = info.get_size()\n self.radius = info.get_radius()\n self.lifespan = info.get_lifespan()\n self.animated = info.get_animated()\n self.frame = info.get_frame()\n if health:\n self.health = health\n else:\n self.health = 0 \n self.attach = attach\n self.attach_obj = attach_obj\n if attack:\n self.attack = attack\n else:\n self.attack = 0 \n self.age = 0\n if sound:\n sound.rewind()\n sound.play()\n \n def get_position(self):\n return self.pos\n \n def get_radius(self):\n return self.radius\n \n def get_health(self):\n return self.health\n \n def get_attach(self):\n return self.attach\n \n def init_attach(self):\n self.attach = 0\n \n def get_attach_obj(self):\n return self.attach_obj\n \n def get_attack(self):\n return self.attack\n \n def draw(self, canvas):\n if self.animated:\n canvas.draw_image(self.image, [(0.5 + self.age % self.frame) * self.image_size[0], self.image_size[1] / 2], self.image_size, self.pos, self.image_size)\n else:\n canvas.draw_image(self.image, self.image_center, self.image_size, self.pos, self.image_size)\n \n def update(self): \n self.pos[0] = self.pos[0] + self.vel[0]\n self.pos[1] = self.pos[1] + self.vel[1]\n #self.angle += self.angle_vel\n self.age += 1\n if (self.pos[0] < 0) or (self.pos[0] > WIDTH) or (self.age >= self.lifespan):\n return True\n else:\n return False\n \n def collide(self, other_object):\n dis = dist(self.get_position(), other_object.get_position())\n if dis <= self.get_radius() + other_object.get_radius():\n return True\n else:\n return False\n\n# image and sound resource\nbackground_info = ImageInfo([383, 165], [766, 330])\nbackground_image = simplegui.load_image(\"http://byiah.img41.wal8.com/img41/427239_20140710190014/140499012687.png\")\n\nsplash_info = ImageInfo([286, 90], [572, 180])\nsplash_image = simplegui.load_image(\"http://byiah.img41.wal8.com/img41/427239_20140710190014/140499012492.png\")\n\ngameover_info = ImageInfo([163, 147], [327, 294])\ngameover_image = simplegui.load_image(\"http://byiah.img41.wal8.com/img41/427239_20140710190014/140499012868.png\")\n\nzombie_info = ImageInfo([32, 50], [64, 100], 20, True, 15)\nzombie_image = simplegui.load_image(\"http://byiah.img41.wal8.com/img41/427239_20140710190014/140499013175.png\")\n\nzombie1_info = ImageInfo([47.5, 56], [95, 112], 22, True, 17)\nzombie1_image = simplegui.load_image(\"http://byiah.img41.wal8.com/img41/427239_20140710190014/14049901265.png\")\n\nshooter_info = ImageInfo([28.5, 32], [55.5, 64], 20, True, 15)\nshooter_image = simplegui.load_image(\"http://byiah.img41.wal8.com/img41/427239_20140710190014/140499012446.png\")\n\nsunflower_info = ImageInfo([25, 30], [50, 60], 20, True, 6)\nsunflower_image = simplegui.load_image(\"http://byiah.img41.wal8.com/img41/427239_20140710190014/140499012538.png\")\n\nsunshine_info = ImageInfo([20, 20], [40, 40], 20, False, 1, 100)\nsunshine_image = simplegui.load_image(\"http://byiah.img41.wal8.com/img41/427239_20140710190014/140499012582.png\")\n\nbullet_info = ImageInfo([17, 17], [34, 34], 15)\nbullet_image = simplegui.load_image(\"http://byiah.img41.wal8.com/img41/427239_20140710190014/14049901278.png\")\n\nblood_info = ImageInfo([38, 31.5], [76, 63], 17, True, 6, 6)\nblood_image = simplegui.load_image(\"http://byiah.img41.wal8.com/img41/427239_20140710190014/140499012265.png\")\n\nexplosion_info = ImageInfo([37, 32.5], [74, 65], 17, True, 8, 8)\nexplosion_image = simplegui.load_image(\"http://byiah.img41.wal8.com/img41/427239_20140710190014/140499012344.png\")\n\n# common helper functions\ndef dist(p,q):\n return math.sqrt((p[0] - q[0]) ** 2+(p[1] - q[1]) ** 2)\n\n# #helper function to control game\n\ndef game_begin():\n global started, score, lives, over\n started = True\n over = False\n lives = 1000\n score = 0\n\ndef game_over():\n global started, over\n started = False\n over = True\n zombie_group.clear()\n shooter_group.clear()\n sunflower_group.clear()\n sunshine_group.clear()\n bullet_group.clear()\n explosion_group.clear()\n \ndef update_difficulty():\n global zombie_vel, zombie_interval, score_ori\n gap = score - score_ori\n zombie_vel -= 0.01 * gap\n zombie_interval = (zombie_interval - 10 * gap) if (zombie_interval - 10 * gap) > 500 else 500\n score_ori = score\n \n\n# helper function to draw and update sprite\ndef process_sprite_group(a_set, canvas):\n for s in list(a_set):\n s.draw(canvas)\n if s.update():\n if s.get_attach_obj() != None: #It is bullet or sunshine\n s.get_attach_obj().init_attach()\n if s.get_health() * s.get_attack() > 0: #It must be zombie\n game_over()\n else: \n a_set.discard(s)\n \ndef group_collide(att, obj_group):\n for obj in list(obj_group):\n if obj.collide(att):\n if att.get_attack() >= obj.get_health(): \n obj_group.discard(obj)\n if att.get_attach_obj():\n a_explosion = Sprite(obj.get_position(), [0, 0], blood_image, blood_info)\n else: \n a_explosion = Sprite(obj.get_position(), [0, 0], explosion_image, explosion_info) \n explosion_group.add(a_explosion)\n return 2 \n else:\n obj.health -= att.get_attack() \n return 1\n return 0\n\ndef group_group_collide(obj_group, att_group):\n num = 0\n for att in list(att_group):\n result = group_collide(att, obj_group)\n if result != 0:\n if att.get_attach_obj(): #bullet attack\n att.get_attach_obj().init_attach()\n att_group.discard(att)\n else: #zombie attack \n att.vel = [0, 0]\n att_list.append(att)\n if result == 2:\n if att.get_attach_obj():\n num += 1\n else:\n for att_a in att_list:\n att_a.vel = [zombie_vel, 0] \n return num\n\n# timer handler that spawns a sprite (include zombie, sunshine,bullet and flower_sunshine) \ndef zombie_spawner():\n if started:\n x = WIDTH\n y = random.randrange(1, 11, 2) * 60\n zombieID = random.randint(0, 3)\n if zombieID == 0:\n a_zombie = Sprite([x, y], [zombie_vel, 0], zombie1_image, zombie1_info, 200, None, 10) \n else: \n a_zombie = Sprite([x, y], [zombie_vel, 0], zombie_image, zombie_info, 100, None, 5) \n zombie_group.add(a_zombie) \n \ndef sunshine_spawner():\n global lives\n if started:\n x = random.randrange(WIDTH)\n y = 0\n a_sunshine = Sprite([x, y],[0, 2], sunshine_image, sunshine_info)\n sunshine_group.add(a_sunshine)\n lives += 10\n \ndef bullet_spawner():\n if started:\n for s in shooter_group:\n if (s.get_attach() == 0):\n s.attach = 1\n a_bullet = Sprite(s.get_position(),[10, 0], bullet_image, bullet_info, None, 1, 20, s)\n bullet_group.add(a_bullet)\n \ndef flower_sunshine_spawner():\n global lives\n if started:\n for s in sunflower_group:\n if (s.get_attach() == 0):\n s.attach = int(time.time())\n elif time.time() - s.get_attach() > 5:\n s.attach = int(time.time())\n a_sunshine = Sprite(s.get_position(),[0, -2], sunshine_image, sunshine_info, None, 1, None, s)\n sunshine_group.add(a_sunshine)\n lives += 20\n\n# helper function to spawns a plant in mouseclick handler \ndef plant_spawner(plantID,pos):\n global lives\n if started:\n for p in list(sunflower_group.union(shooter_group)):\n if (p.get_position() == pos):\n return\n if plantID == 1:\n a_sunflower = Sprite(pos,[0, 0], sunflower_image, sunflower_info, 300)\n sunflower_group.add(a_sunflower)\n lives -= 100\n if plantID == 2:\n a_shooter = Sprite(pos,[0, 0], shooter_image, shooter_info, 360)\n shooter_group.add(a_shooter) \n lives -= 150 \n \ndef draw(canvas):\n global score \n canvas.draw_image(background_image, background_info.get_center(), background_info.get_size(), [WIDTH / 2, HEIGHT / 2], [WIDTH, HEIGHT])\n canvas.draw_image(sunflower_image, sunflower_info.get_center(), sunflower_info.get_size(), [20, 20], [40,40])\n canvas.draw_image(shooter_image, shooter_info.get_center(), shooter_info.get_size(), [80, 20], [40,40])\n canvas.draw_image(sunshine_image, sunshine_info.get_center(), sunshine_info.get_size(), [140, 20], sunshine_info.get_size())\n canvas.draw_text(\"100\", (40, 40), 10, 'White', 'serif')\n canvas.draw_text(\"150\", (100, 40), 10, 'White', 'serif')\n canvas.draw_text(str(lives), (160, 30), 16, 'White', 'serif')\n canvas.draw_text('得分:'+ str(score), (WIDTH - 100, 30), 16, 'White', 'serif')\n if not started and not over:\n canvas.draw_image(splash_image, splash_info.get_center(), splash_info.get_size(), (WIDTH / 2, HEIGHT / 2), splash_info.get_size())\n if over:\n canvas.draw_image(gameover_image, gameover_info.get_center(), gameover_info.get_size(), (WIDTH / 2, HEIGHT / 2), gameover_info.get_size())\n # draw and update sprites\n process_sprite_group(zombie_group, canvas)\n process_sprite_group(shooter_group, canvas)\n process_sprite_group(sunflower_group, canvas)\n process_sprite_group(sunshine_group, canvas)\n process_sprite_group(bullet_group, canvas)\n process_sprite_group(explosion_group, canvas)\n \n # update score and lives when collisions happened\n score += (group_group_collide(zombie_group, bullet_group) * 10)\n update_difficulty()\n group_group_collide(shooter_group, zombie_group) \n group_group_collide(sunflower_group, zombie_group) \n\n \n\n \n# mouseclick handler, keydown handler and input handler \ndef mouseclick(pos):\n global plantID, over\n splash_size = splash_info.get_size() \n x_range = (pos[0] <= WIDTH / 2 + splash_size[0] / 2) and (pos[0] >= WIDTH / 2 - splash_size[0] / 2)\n y_range = (pos[1] <= HEIGHT / 2 + splash_size[1] / 2) and (pos[1] >= HEIGHT / 2 - splash_size[1] / 2)\n if x_range and y_range:\n if not started and not over:\n game_begin()\n if over:\n over = False \n #soundtrack.rewind()\n if (plantID == 1) or (plantID == 2):\n plant_x = (pos[0] // 80) * 80 + 40\n plant_y = (pos[1] // 120) * 120 + 60\n plant_spawner(plantID,[plant_x, plant_y])\n \n if (pos[0] > 0) and (pos[0] < 40) and (pos[1] > 0) and (pos[1] < 40) and (lives >= 100):\n plantID = 1 \n elif (pos[0] > 60) and (pos[0] < 100) and (pos[1] > 0) and (pos[1] < 40) and (lives >= 150):\n plantID = 2\n else:\n plantID = 0\n\n \ndef key_down(key):\n if key == simplegui.KEY_MAP[\"space\"]: \n game_begin()\n \ndef input_handler(text_input):\n global lives\n if text_input.isdigit(): \n lives = int(text_input)\n\n# initialize frame\nframe = simplegui.create_frame(\"Asteroids\", WIDTH, HEIGHT)\ninp = frame.add_input('初始阳光:', input_handler, 50)\ninp.set_text(1000)\n\n# register handlers\nframe.set_draw_handler(draw)\nframe.set_keydown_handler(key_down)\nframe.set_mouseclick_handler(mouseclick)\n\ntimer = simplegui.create_timer(random.randint(500, zombie_interval), zombie_spawner)\ntimer1 = simplegui.create_timer(5000.0, sunshine_spawner)\ntimer2 = simplegui.create_timer(1000.0, bullet_spawner)\ntimer3 = simplegui.create_timer(100.0, flower_sunshine_spawner)\n\n# get things rolling\ntimer.start()\ntimer1.start()\ntimer2.start()\ntimer3.start()\nframe.start()","sub_path":"py_files/pvz.py","file_name":"pvz.py","file_ext":"py","file_size_in_byte":13882,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"132592970","text":"import requests, bs4, sys\n\n# remove spacing, adding lowercase to match Azlyrics url format\nartist=input(\"artist: \").replace(\" \",\"\")\nsong=input(\"song: \").replace(\" \",\"\")\n\n# url format: www.azlyrics.com/lyrics//.html\nurl='http://www.azlyrics.com/lyrics/%s/%s.html' % (artist,song)\n\n\n# http://stackoverflow.com/questions/33174804/python-requests-getting-connection-aborted-badstatusline-error\n# using a header to hide like a browser\nheaders = { 'User-Agent': 'Mozilla/5.0 (Windows NT 6.0; WOW64; rv:24.0) Gecko/20100101 Firefox/24.0' }\n\nr=requests.get(url,headers=headers)\n\nprint('\\nconnected to %s' % url)\n\nlyric_page=bs4.BeautifulSoup(r.text,\"html.parser\")\n\n# a div has no name\nfor lyrics in lyric_page.find_all(\"div\", {\"class\":\"\"}):\n print(lyrics.text)\n\ninput(\"Press Enter to continue...\")\n\nimport msvcrt as m\ndef wait():\n m.getch()","sub_path":"lyrics-fetcher/lyrics-fetcher.py","file_name":"lyrics-fetcher.py","file_ext":"py","file_size_in_byte":850,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"561008657","text":"\nimport os\nimport shutil\nimport sys\n\nsys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '.')))\n\nimport lumapi\n\nimport functools\nimport h5py\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport time\n\n#\n# Create FDTD hook\n#\nfdtd_hook = lumapi.FDTD()\n\n\ndef get_efield( monitor_name ):\n\tfield_polariations = [ 'Ex', 'Ey', 'Ez' ]\n\tdata_xfer_size_MB = 0\n\n\tstart = time.time()\n\n\tEpol_0 = fdtd_hook.getdata( monitor_name, field_polariations[ 0 ] )\n\tdata_xfer_size_MB += Epol_0.nbytes / ( 1024. * 1024. )\n\n\ttotal_efield = np.zeros( [ len (field_polariations ) ] + list( Epol_0.shape ), dtype=np.complex )\n\ttotal_efield[ 0 ] = Epol_0\n\n\tfor pol_idx in range( 1, len( field_polariations ) ):\n\t\tEpol = fdtd_hook.getdata( monitor_name, field_polariations[ pol_idx ] )\n\t\tdata_xfer_size_MB += Epol.nbytes / ( 1024. * 1024. )\n\n\t\ttotal_efield[ pol_idx ] = Epol\n\n\telapsed = time.time() - start\n\n\treturn total_efield\n\n\nproject_name = 'e_field_convergence_finer_volume'\npython_src_directory = os.path.abspath(os.path.join(os.path.dirname(__file__), '.'))\nprojects_directory_location = os.path.abspath(os.path.join(os.path.dirname(__file__), '../projects/'))\nprojects_directory_location += \"/\" + project_name\n\nif not os.path.isdir(projects_directory_location):\n\tos.mkdir(projects_directory_location)\n\nfdtd_hook.newproject()\nfdtd_hook.save(projects_directory_location + \"/optimization\")\n\nlambda_min_um = 1.05\nlambda_max_um = 1.55\n\nnum_observed_frequency_points = 10\n\nnum_index_values = 5\nblock_indices = np.linspace( 1.5, 3.5, num_index_values )\n\nR_min_um = 0.1 * lambda_min_um# 0.25 * lambda_min_um\nR_max_um = 1.0 * lambda_max_um\nblock_width_um = 0.5 * lambda_min_um\n\nlateral_gap_um = 0.5 * lambda_max_um\ntfsf_lateral_buffer_um = 0.25 * lambda_max_um\ntfsf_width_um = 0.5 * block_width_um + R_max_um + tfsf_lateral_buffer_um\n\nblock_height_um = 2 * lambda_min_um\n\nvertical_gap_um = lambda_max_um\ntfsf_top_gap_um = 1.25 * lambda_max_um\ntfsf_bottom_gap_um = 0.25 * lambda_max_um\n\nsimulation_lateral_size_um = 2 * lateral_gap_um + 2 * tfsf_width_um\nsimulation_vertical_size_um = 2 * vertical_gap_um + block_height_um + tfsf_top_gap_um + tfsf_bottom_gap_um\n\nsimulation_vertical_min_um = -( vertical_gap_um + tfsf_bottom_gap_um )\nsimulation_vertical_max_um = ( vertical_gap_um + tfsf_top_gap_um + block_height_um )\n\nmesh_fractions = np.array( [ 1. / ( 4 * ( 6 - k ) ) for k in range( 0, 5 ) ] )\nnum_mesh_sizes = len( mesh_fractions )\n\nnum_R_values = 6\nR_values_um = np.linspace( R_min_um, R_max_um, num_R_values )\n\nfdtd_simulation_time_fs = 4 * 700\n\nfdtd = fdtd_hook.addfdtd()\nfdtd['x span'] = simulation_lateral_size_um * 1e-6\nfdtd['y span'] = simulation_lateral_size_um * 1e-6\nfdtd['z max'] = simulation_vertical_max_um * 1e-6\nfdtd['z min'] = simulation_vertical_min_um * 1e-6\nfdtd['mesh type'] = 'uniform'\nfdtd['mesh refinement'] = 'volume average'\nfdtd['define x mesh by'] = 'number of mesh cells'\nfdtd['define y mesh by'] = 'number of mesh cells'\nfdtd['define z mesh by'] = 'number of mesh cells'\nindex_air = 1.0\nfdtd['background index'] = index_air\nfdtd['simulation time'] = fdtd_simulation_time_fs * 1e-15\n\nexcitation = fdtd_hook.addtfsf()\nexcitation['name'] = 'excitation'\nexcitation['angle phi'] = 0\nexcitation['direction'] = 'Backward'\nexcitation['x span'] = ( 2 * tfsf_width_um ) * 1e-6\nexcitation['y span'] = ( 2 * tfsf_width_um ) * 1e-6\nexcitation['z max'] = ( tfsf_top_gap_um + block_height_um ) * 1e-6\nexcitation['z min'] = -( tfsf_bottom_gap_um ) * 1e-6\nexcitation['wavelength start'] = lambda_min_um * 1e-6\nexcitation['wavelength stop'] = lambda_max_um * 1e-6\n\nE_monitors_x = []\nE_monitors_y = []\n\nfor R_idx in range( 0, num_R_values ):\n\tR_um = R_values_um[ R_idx ]\n\n\tE_monitor_x = fdtd_hook.addpower()\n\tE_monitor_x['name'] = 'focal_monitor_' + str( R_idx ) + \"_x\"\n\tE_monitor_x['monitor type'] = 'point'\n\tE_monitor_x['spatial interpolation'] = 'specified position'\n\tE_monitor_x['x'] = ( 0.5 * block_width_um + R_um ) * 1e-6\n\tE_monitor_x['y'] = 0 * 1e-6\n\tE_monitor_x['z'] = 0.5 * block_height_um * 1e-6\n\tE_monitor_x['override global monitor settings'] = 1\n\tE_monitor_x['use wavelength spacing'] = 1\n\tE_monitor_x['use source limits'] = 1\n\tE_monitor_x['frequency points'] = num_observed_frequency_points\n\n\tE_monitors_x.append( E_monitor_x )\n\n\tE_monitor_y = fdtd_hook.addpower()\n\tE_monitor_y['name'] = 'focal_monitor_' + str( R_idx ) + \"_y\"\n\tE_monitor_y['monitor type'] = 'point'\n\tE_monitor_y['spatial interpolation'] = 'specified position'\n\tE_monitor_y['x'] = 0 * 1e-6\n\tE_monitor_y['y'] = ( 0.5 * block_width_um + R_um ) * 1e-6\n\tE_monitor_y['z'] = 0.5 * block_height_um * 1e-6\n\tE_monitor_y['override global monitor settings'] = 1\n\tE_monitor_y['use wavelength spacing'] = 1\n\tE_monitor_y['use source limits'] = 1\n\tE_monitor_y['frequency points'] = num_observed_frequency_points\n\n\tE_monitors_y.append( E_monitor_y )\n\nblock_import = fdtd_hook.addimport()\nblock_import['name'] = 'block_import'\nblock_import['x span'] = block_width_um * 1e-6\nblock_import['y span'] = block_width_um * 1e-6\nblock_import['z max'] = block_height_um * 1e-6\nblock_import['z min'] = 0 * 1e-6\n\nblock_x_um = 1e-6 * np.linspace( -0.5 * block_width_um, 0.5 * block_width_um, 2 )\nblock_y_um = 1e-6 * np.linspace( -0.5 * block_width_um, 0.5 * block_width_um, 2 )\nblock_z_um = 1e-6 * np.linspace( 0, block_height_um, 2 )\n\nelectric_fields_scan_x = np.zeros( ( num_index_values, num_mesh_sizes, num_R_values, 3, num_observed_frequency_points ), dtype=np.complex )\nelectric_fields_scan_y = np.zeros( ( num_index_values, num_mesh_sizes, num_R_values, 3, num_observed_frequency_points ), dtype=np.complex )\n\nmesh_sizes_all_um = np.zeros( ( num_index_values, num_mesh_sizes ) )\n\nfor index_idx in range( 0, num_index_values ):\n\n\tprint( 'Currently working on index ' + str( index_idx ) + ' out of ' + str( num_index_values - 1 ) )\n\n\tblock_index = block_indices[ index_idx ]\n\timport_block = block_index * np.ones( ( len( block_x_um ), len( block_y_um ), len( block_z_um ) ) )\n\n\tmesh_sizes_um = ( 1. / block_index ) * mesh_fractions * lambda_min_um\n\n\tmesh_sizes_all_um[ index_idx, : ] = mesh_sizes_um\n\n\tfor mesh_idx in range( 0, num_mesh_sizes ):\n\t\tprint( 'Currently mesh ' + str( mesh_idx ) + ' out of ' + str( num_mesh_sizes - 1 ) )\n\n\t\tmesh_size_um = mesh_sizes_um[ mesh_idx ]\n\n\t\t#\n\t\t# Adjust mesh\n\t\t#\n\t\tfdtd_region_minimum_vertical_voxels = int( np.ceil( simulation_vertical_size_um / mesh_size_um ) )\n\t\tfdtd_region_minimum_lateral_voxels = int( np.ceil( simulation_lateral_size_um / mesh_size_um ) )\n\n\t\tfdtd_hook.switchtolayout()\n\n\t\tfdtd['mesh cells x'] = fdtd_region_minimum_lateral_voxels\n\t\tfdtd['mesh cells y'] = fdtd_region_minimum_lateral_voxels\n\t\tfdtd['mesh cells z'] = fdtd_region_minimum_vertical_voxels\n\n\t\tfdtd_hook.select( block_import['name'] )\n\t\tfdtd_hook.importnk2( import_block, block_x_um, block_y_um, block_z_um )\n\n\t\tfdtd_hook.run()\n\n\t\t#\n\t\t# Now we need to collect the electric field data\n\t\t#\n\t\tfor E_monitor_idx in range( 0, len( E_monitors_x ) ):\n\t\t\tE_data_scan_x = get_efield( E_monitors_x[ E_monitor_idx ][ 'name' ] )\n\t\t\tE_data_scan_y = get_efield( E_monitors_x[ E_monitor_idx ][ 'name' ] )\n\n\t\t\telectric_fields_scan_x[ index_idx, mesh_idx, E_monitor_idx, :, : ] = E_data_scan_x[ :, 0, 0, 0, : ]\n\t\t\telectric_fields_scan_y[ index_idx, mesh_idx, E_monitor_idx, :, : ] = E_data_scan_y[ :, 0, 0, 0, : ]\n\nnp.save( projects_directory_location + \"/electric_fields_scan_x.npy\", electric_fields_scan_x )\nnp.save( projects_directory_location + \"/electric_fields_scan_y.npy\", electric_fields_scan_y )\nnp.save( projects_directory_location + \"/block_indices.npy\", block_indices )\nnp.save( projects_directory_location + \"/mesh_sizes_all_um.npy\", mesh_sizes_all_um )\nnp.save( projects_directory_location + \"/R_values_um.npy\", R_values_um )\n","sub_path":"inverse_design/ElectricFieldConverence.py","file_name":"ElectricFieldConverence.py","file_ext":"py","file_size_in_byte":7716,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"190139132","text":"# MIT License\n#\n# Copyright (C) 2021. 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# Do not make any change to this file when merging. Just use my version.\nfrom collections import deque, namedtuple\nimport numpy as np\nimport random, copy\nimport torch\nfrom marl_scalability.utils.common import normalize_im\nfrom collections.abc import Iterable\n\nfrom torch.utils.data import Dataset, Sampler, DataLoader\n\nTransition = namedtuple(\n \"Transition\",\n field_names=[\"state\", \"action\", \"reward\", \"next_state\", \"done\", \"others\"],\n # others may contain importance sampling ratio, GVF rewards,... etc\n defaults=(None,) * 6,\n)\n\n\nclass RandomRLSampler(Sampler):\n def __init__(self, data_source, batch_size):\n self.datasource = data_source\n self.batch_size = batch_size\n\n def __len__(self):\n return len(self.datasource)\n\n def __iter__(self):\n n = len(self.datasource)\n return iter(torch.randperm(n).tolist()[0 : self.batch_size])\n\n\nclass ReplayBufferDataset(Dataset):\n cpu = torch.device(\"cpu\")\n\n def __init__(self, buffer_size, device):\n self.buffer_size = buffer_size\n self.memory = deque(maxlen=self.buffer_size)\n self.device = device\n\n def add(\n self,\n state,\n action,\n reward,\n next_state,\n done,\n prev_action,\n others=None,\n ):\n if others is None:\n others = {}\n # dereference the states\n state = copy.deepcopy(state)\n next_state = copy.deepcopy(next_state)\n state[\"low_dim_states\"] = np.float32(\n np.append(state[\"low_dim_states\"], prev_action)\n )\n state[\"low_dim_states\"] = torch.from_numpy(state[\"low_dim_states\"]).to(\n self.device\n )\n state[\"social_vehicles\"] = torch.from_numpy(state[\"social_vehicles\"]).to(\n self.device\n )\n\n next_state[\"low_dim_states\"] = np.float32(\n np.append(next_state[\"low_dim_states\"], action)\n )\n next_state[\"social_vehicles\"] = torch.from_numpy(\n next_state[\"social_vehicles\"]\n ).to(self.device)\n next_state[\"low_dim_states\"] = torch.from_numpy(\n next_state[\"low_dim_states\"]\n ).to(self.device)\n\n action = np.asarray([action]) if not isinstance(action, Iterable) else action\n action = torch.from_numpy(action).float()\n reward = torch.from_numpy(np.asarray([reward])).float()\n done = torch.from_numpy(np.asarray([done])).float()\n new_experience = Transition(state, action, reward, next_state, done, others)\n self.memory.append(new_experience)\n\n def __len__(self):\n return len(self.memory)\n\n def __getitem__(self, idx):\n if torch.is_tensor(idx):\n idx = idx.tolist()\n state, action, reward, next_state, done, others = tuple(self.memory[idx])\n return state, action, reward, next_state, done, others\n\n\nclass ReplayBuffer:\n def __init__(\n self,\n buffer_size,\n batch_size,\n device_name,\n pin_memory=False,\n num_workers=0,\n ):\n self.replay_buffer_dataset = ReplayBufferDataset(buffer_size, device=None)\n self.sampler = RandomRLSampler(self.replay_buffer_dataset, batch_size)\n self.data_loader = DataLoader(\n self.replay_buffer_dataset,\n sampler=self.sampler,\n pin_memory=pin_memory,\n num_workers=num_workers,\n )\n self.storage_device = torch.device(device_name)\n\n def add(self, *args, **kwargs):\n self.replay_buffer_dataset.add(*args, **kwargs)\n\n def __len__(self):\n return len(self.replay_buffer_dataset)\n\n def __getitem__(self, idx):\n return self.replay_buffer_dataset[idx]\n\n def make_state_from_dict(self, states, device):\n # image_keys = states[0][\"images\"].keys()\n # images = {}\n # for k in image_keys:\n # _images = torch.cat([e[k] for e in states], dim=0).float().to(device)\n # _images = normalize_im(_images)\n # images[k] = _images\n low_dim_states = (\n torch.cat([e[\"low_dim_states\"] for e in states], dim=0).float().to(device)\n )\n if \"social_vehicles\" in states[0]:\n social_vehicles = [\n e[\"social_vehicles\"][0].float().to(device) for e in states\n ]\n else:\n social_vehicles = False\n out = {\n # \"images\": images,\n \"low_dim_states\": low_dim_states,\n \"social_vehicles\": social_vehicles,\n }\n return out\n\n def sample(self, device=None):\n device = device if device else self.storage_device\n batch = list(iter(self.data_loader))\n states, actions, rewards, next_states, dones, others = zip(*batch)\n states = self.make_state_from_dict(states, device)\n next_states = self.make_state_from_dict(next_states, device)\n actions = torch.cat(actions, dim=0).float().to(device)\n rewards = torch.cat(rewards, dim=0).float().to(device)\n dones = torch.cat(dones, dim=0).float().to(device)\n return states, actions, rewards, next_states, dones, others\n","sub_path":"marl_scalability/marl_scalability/baselines/common/replay_buffer.py","file_name":"replay_buffer.py","file_ext":"py","file_size_in_byte":6252,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"379487673","text":"from utils import create_input_files, create_scene_graph_input_files\nimport argparse\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser('prepare')\n parser.add_argument('-s', dest='sg', action='store_true', help='if we need to prepare scene graph files')\n args = parser.parse_args()\n # Create input files (along with word map)\n create_input_files(dataset='coco',\n karpathy_json_path='data/caption_datasets/dataset_coco.json',\n captions_per_image=5,\n min_word_freq=5,\n output_folder='final_dataset',\n max_len=50)\n if args.sg:\n create_scene_graph_input_files(dataset='coco',\n karpathy_json_path='data/caption_datasets/dataset_coco.json',\n output_folder='final_dataset')","sub_path":"create_input_files.py","file_name":"create_input_files.py","file_ext":"py","file_size_in_byte":888,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"265648971","text":"import os\nimport pickle\nimport pprint\nfrom urllib.request import Request, urlopen\nfrom urllib.error import URLError, HTTPError\nimport csv\n\ndef csv_writer_places_to_local(places, filename):\n with open(filename, 'a') as csvfile:\n fieldnames = [ 'cityid', 'cityname', 'jobname',\n 'business_status', 'formatted_address', 'name',\n 'opening_hours', 'plus_code', 'rating', 'types',\n 'user_ratings_total']\n writer = csv.DictWriter(csvfile, fieldnames=fieldnames)\n writer.writeheader()\n for p in places:\n writer.writerow({\n 'cityid': p.cityid,\n 'cityname': p.cityname,\n 'jobname': p.jobname,\n 'business_status': p.business_status,\n 'formatted_address': p.formatted_address,\n 'name': p.name,\n 'opening_hours': p.opening_hours,\n 'plus_code': p.plus_code,\n 'types': p.types,\n 'rating': p.rating,\n 'user_ratings_total': p.user_ratings_total\n })\n\n\ndef csv_reader(filename, directory='./'):\n with open(os.path.join(directory, filename), newline='') as csvfile:\n reader = csv.reader(csvfile, delimiter=' ', quotechar='|')\n mylist = []\n for row in reader:\n mylist.append(row[0].split(',')) \n return mylist","sub_path":"university_counselor/a6042professions_crawler/csv_operation.py","file_name":"csv_operation.py","file_ext":"py","file_size_in_byte":1430,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"289321852","text":"import zipfile\r\n\r\nzf = zipfile.ZipFile(\"files/channel.zip\", \"r\")\r\n\r\ndef decodeZip(zipFile, startNum, files = []):\r\n direction = \"files/channel/\" + str(startNum) + \".txt\"\r\n try:\r\n with open(direction, \"r\") as file:\r\n files.append(str(startNum) + \".txt\")\r\n line = file.read()\r\n decodeZip(zipFile, [int(i) for i in line.split() if i.isdigit()][0], files)\r\n except:\r\n print(\"Decoded all files\")\r\n\r\n return [zf.getinfo(f).comment.decode(\"utf-8\") for f in files]\r\n\r\nfor char in decodeZip(zf, 90052):\r\n print(char, end=\"\")\r\nzf.close()\r\n\r\n\r\n","sub_path":"Level6.py","file_name":"Level6.py","file_ext":"py","file_size_in_byte":591,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"216180674","text":"def FinalSample():\n\n #generic imports\n import pandas as pd\n import numpy as np\n import matplotlib\n import matplotlib.pyplot as plt\n import matplotlib.colors as colors\n \n #import functions for reading data tables\n import astropy\n from astropy.io import ascii, fits\n from astropy.table import Table, Column\n\n #Location ID,Telescope,Field,2Mass ID,Plate,MJD,Fiber,RA,DEC,Density,Temp,Chi,Max Line,Br11 SNR,Br11 EqW,Br12 EqW,Br13 EqW,Br14 EqW,Br15 EqW,Br16 EqW,Br17 EqW,Br18 EqW,Br19 EqW,Br20 EqW,Br11 Error,Br12 Error,Br13 Error,Br14 Error,Br15 Error,Br16 Error,Br17 Error,Br18 Error,Br19 Error,Br20 Error,Br11 Peak Flux,Br12 Peak Flux,Br13 Peak Flux,Br14 Peak Flux,Br15 Peak Flux,Br16 Peak Flux,Br17 Peak Flux,Br18 Peak Flux,Br19 Peak Flux,Br20 Peak Flux,Br11 Std Dev,Br12 Std Dev,Br13 Std Dev,Br14 Std Dev,Br15 Std Dev,Br16 Std Dev,Br17 Std Dev,Br18 Std Dev,Br19 Std Dev,Br20 Std Dev\n\n #read in the EqWs from the Sample\n filepath = \"/Users/coveyk/Dropbox/python/T-Tauri/Summer_2021/dataFiles/NeuralNet+YoungCluster_EqWs\"\n catalog = fits.open(filepath)\n data = catalog[1].data\n\n #repackage info into arrays\n# IDs = catalog['2Mass ID'].array\n# plates = catalog['Plate'].array\n mjds = np.asarray(data['mjd_1'])\n fibers = np.asarray(data['fiber_1'])\n densities = np.asarray(data['Density'])\n temps = np.asarray(data['Temp'])\n chis = np.asarray(data['Chi'])\n Br11_EqW = np.asarray(data['Br11 EqW'])\n Br12_EqW = np.asarray(data['Br12 EqW'])\n Br13_EqW = np.asarray(data['Br13 EqW'])\n Br14_EqW = np.asarray(data['Br14 EqW'])\n Br15_EqW = np.asarray(data['Br15 EqW'])\n Br16_EqW = np.asarray(data['Br16 EqW'])\n Br17_EqW = np.asarray(data['Br17 EqW'])\n Br18_EqW = np.asarray(data['Br18 EqW'])\n Br19_EqW = np.asarray(data['Br19 EqW'])\n Br20_EqW = np.asarray(data['Br20 EqW'])\n Br11_Error = np.asarray(data['Br11 Error']) \n Br12_Error = np.asarray(data['Br12 Error'])\n Br13_Error = np.asarray(data['Br13 Error'])\n Br14_Error = np.asarray(data['Br14 Error'])\n Br15_Error = np.asarray(data['Br15 Error'])\n Br16_Error = np.asarray(data['Br16 Error'])\n Br17_Error = np.asarray(data['Br17 Error'])\n Br18_Error = np.asarray(data['Br18 Error'])\n Br19_Error = np.asarray(data['Br19 Error'])\n Br20_Error = np.asarray(data['Br20 Error'])\n\n plates = np.asarray(data['plate_1'])\n paths = np.asarray(data['path'])\n APOGEE_IDs = np.asarray(data['APOGEE_ID'])\n detected = np.asarray(data['detected'])\n good = np.asarray(data['good'])\n double = np.asarray(data['double'])\n nebular = np.asarray(data['nebular'])\n\n print('Full File plates: ', len(np.unique(plates)))\n print('Full File spectra: ', len(np.unique(paths)))\n print('Full File objects: ', len(np.unique(APOGEE_IDs)))\n print(' ')\n \n detected_line = np.nonzero(detected == True)\n good_line = np.nonzero(good == True)\n double_line = np.nonzero(double == True)\n nebular_line = np.nonzero(nebular == True)\n\n print('Full File spectra detected: ', len(np.unique(paths[detected_line])))\n print('Full File spectra good: ', len(np.unique(paths[good_line])))\n print('Full File spectra double: ', len(np.unique(paths[double_line])))\n print('Full File spectra nebular: ', len(np.unique(paths[nebular_line])))\n print(' ')\n\n print('Full File sources detected: ', len(np.unique(APOGEE_IDs[detected_line])))\n print('Full File sources good: ', len(np.unique(APOGEE_IDs[good_line])))\n print('Full File sources double: ', len(np.unique(APOGEE_IDs[double_line])))\n print('Full File sources nebular: ', len(np.unique(APOGEE_IDs[nebular_line])))\n print(' ')\n \n #find objects in the YoungClusterPlates - lots of logical ors on pairs of logical statements\n InYoungClusterPlates_set1 = np.logical_or( ( plates == 6103 ), ( (plates > 6217) & (plates < 6228) ) )\n InYoungClusterPlates_set2 = np.logical_or( ( (plates > 7069) & (plates < 7076) ), (plates == 7079) )\n InYoungClusterPlates_set3 = np.logical_or( ( (plates > 7219) & (plates < 7235) ), ( (plates > 8878) & (plates < 8907) ) )\n InYoungClusterPlates_set4 = np.logical_or( ( plates == 9244 ), ( (plates > 9256) & (plates < 9260) ) )\n InYoungClusterPlates_set5 = np.logical_or( ( (plates > 9286) & (plates < 9289) ), ( (plates > 9467) & (plates < 9483) ) )\n InYoungClusterPlates_set6 = np.logical_or( ( plates == 9533 ), ( (plates > 9536) & (plates < 9539) ) )\n InYoungClusterPlates_set7 = np.logical_or( ( ( plates > 9658) & (plates < 9662) ), ( plates == 9752 ) )\n InYoungClusterPlates_set8 = np.logical_or( ( plates == 10100 ), ( (plates > 10293) & (plates < 10299) ) )\n InYoungClusterPlates_set9 = np.logical_or( ( plates == 10302), ( plates == 10718 ) )\n InYoungClusterPlates_set10 = np.logical_or( ( (plates > 11270) & (plates < 11277) ), ( (plates > 11408) & (plates < 11421) ) )\n InYoungClusterPlates_set11 = np.logical_or( ( (plates > 11424) & (plates < 11442) ), ( (plates > 11592) & (plates < 11595) ) )\n InYoungClusterPlates_set12 = np.logical_or( ( (plates > 11619) & (plates < 11623) ), ( plates == 11778 ) )\n InYoungClusterPlates_set13 = np.logical_or( (plates == 12266), ( plates == 12273 ) )\n InYoungClusterPlates_set14 = np.logical_or( ( plates == 12276 ), ( (plates > 12355) & (plates < 12359) ) )\n \n #now logical ors on outputs of pairs (ie, pairs of pairs)\n InYC_1_2 = np.logical_or(InYoungClusterPlates_set1,InYoungClusterPlates_set2) \n InYC_3_4 = np.logical_or(InYoungClusterPlates_set3,InYoungClusterPlates_set4) \n InYC_5_6 = np.logical_or(InYoungClusterPlates_set5,InYoungClusterPlates_set6) \n InYC_7_8 = np.logical_or(InYoungClusterPlates_set7,InYoungClusterPlates_set8) \n InYC_9_10 = np.logical_or(InYoungClusterPlates_set9,InYoungClusterPlates_set10) \n InYC_11_12 = np.logical_or(InYoungClusterPlates_set11,InYoungClusterPlates_set12) \n InYC_13_14 = np.logical_or(InYoungClusterPlates_set13,InYoungClusterPlates_set14)\n \n #now logical ors on pairs of pairs of pairs\n InYC_1_4 = np.logical_or(InYC_1_2, InYC_3_4) \n InYC_5_8 = np.logical_or(InYC_5_6, InYC_7_8) \n InYC_9_12 = np.logical_or(InYC_9_10, InYC_11_12)\n\n #and logical ors on pairs of pairs of pairs of pairs\n InYC_1_8 = np.logical_or(InYC_1_4, InYC_5_8)\n InYC_9_14 = np.logical_or(InYC_9_12, InYC_13_14)\n\n #last logical set?!?!\n InYC_1_14 = np.logical_or(InYC_1_8, InYC_9_14)\n\n #one last merge for a final straggling plate\n InYC = np.logical_or(InYC_1_14, ( plates == 12706) )\n \n #InYoungClusterPlates = np.any( ( ( (plates > 6217) & (plates < 6228) ), ( (plates > 7069) & (plates < 7076) ), ( plates == 11425 ), ( (plates > 7219) & (plates < 7235) ) ) )\n\n #logical_or(InYoungClusterPlates_set1, InYoungClusterPlates_set2)\n print('YC plates: ', len(np.unique(plates[InYC])))\n print('YC spectra: ', len(np.unique(paths[InYC])))\n print('YC objects: ', len(np.unique(APOGEE_IDs[InYC])))\n print(' ')\n\n YC_detected = np.logical_and( (detected == True), InYC)\n YC_good = np.logical_and( (good == True), InYC)\n YC_doubles = np.logical_and( (double == True), InYC)\n YC_nebular = np.logical_and( (nebular == True), InYC)\n \n print('YC detected spectra: ', len(np.unique(paths[YC_detected]) ) )\n print('YC good spectra: ', len(np.unique(paths[YC_good]) ) )\n print('YC double_line spectra: ', len(np.unique(paths[YC_doubles]) ) )\n print('YC nebular_line spectra: ', len(np.unique(paths[YC_nebular]) ) )\n print(' ')\n\n print('YC detected sources: ', len(np.unique(APOGEE_IDs[YC_detected]) ) )\n print('YC good sources: ', len(np.unique(APOGEE_IDs[YC_good]) ) )\n print('YC double_line sources: ', len(np.unique(APOGEE_IDs[YC_doubles]) ) )\n print('YC nebular_line sources: ', len(np.unique(APOGEE_IDs[YC_nebular]) ) )\n print(' ')\n \n n_lines = 10\n lines = np.arange(n_lines)+11\n \n# print(len(Br11_EqW))\n\n #open the model grid\n #models = ascii.read(\"/Users/kcovey/Dropbox/python/T-Tauri/Summer_2021/dataFiles/DR15/Density_Temp_Files/Profile Test.csv\", format = 'csv')\n openmodel = pd.read_csv(\"/Users/coveyk/Dropbox/python/T-Tauri/Summer_2021/dataFiles/DR15/Density_Temp_Files/Profile Test.csv\")\n cols = openmodel.columns\n headers = cols.tolist()\n\n #make arrays for storing the outcomes of the model fits\n best_temp = np.zeros(len(Br11_EqW))\n best_density = np.zeros(len(Br11_EqW))\n best_chi = np.zeros(len(Br11_EqW))\n best_residuals = np.zeros(len(Br11_EqW))\n best_normed_residuals = np.zeros(len(Br11_EqW))\n \n #now loop through the stars to make the model fit.\n for i in range(len(Br11_EqW)):\n #for i in range(20):\n \n #prepare info for this fit\n Chi = [] #zero out the chi square array\n equivs = np.asarray([Br11_EqW[i], Br12_EqW[i], Br13_EqW[i], Br14_EqW[i], Br15_EqW[i],\n Br16_EqW[i], Br17_EqW[i], Br18_EqW[i], Br19_EqW[i], Br20_EqW[i]])\n \n equiverr = np.asarray([Br11_Error[i], Br12_Error[i], Br13_Error[i], Br14_Error[i], Br15_Error[i],\n Br16_Error[i], Br17_Error[i], Br18_Error[i], Br19_Error[i], Br20_Error[i]])\n\n #print(equivs)\n #print(equiverr)\n\n for k in range(len(cols)): \n chi_squared = 0\n probs = np.asarray(openmodel[cols[k]])\n \n # Calculating numerator\n #Normalizes the measured line strengths to Brackett 11\n ratio = equivs / equivs[0]\n norm_error = equiverr / equivs[0]\n prob_ratio = probs / probs[0]\n \n # Calculates the residual between the normalized observed line\n # and the normalized model line strength\n numerator = ( (ratio - prob_ratio) )**2\n #numerator = numerator**2\n \n # Expressing uncertainty in observed ratio\n # Finds fractional error in k line and fractional error in\n # Brackett 11, adds them in quadrature, then multiplies by ratio\n sigma = ratio * np.sqrt((equiverr / equivs)**2 + (equiverr[0] / equivs[0])**2)\n #sigma=(equivs[0]*equiverr - equivs*equiverr[0])/(equivs[0]**2)\n\t\n # Calculating denominator\n # The left and right sides of the below equation are probably\n # to create a minimum error, the left side scaling with the ratio\n # and the right side being a flat .01\n denominator = (np.sqrt(0.02) * ratio)**2 + sigma**2 + (0.1**2)\n\t \n # Adding to Chi\n chi_squared = np.sum(numerator / denominator) # Append information to Chi\n residuals = np.sum(np.sqrt(numerator))\n normed_residuals = np.sum(np.sqrt(numerator)/norm_error)\n# print(chi_squared)\n\n #print(ratio)\n #print(prob_ratio)\n #print(ratio - prob_ratio)\n #print(headers[k], chi_squared)\n \n if headers[k].startswith('1'):\n Chi.append((headers[k][0:4],headers[k][5:],chi_squared,residuals,normed_residuals))\n #print(headers[k][5:])\n else:\n Chi.append((headers[k][0:3],headers[k][4:],chi_squared,residuals,normed_residuals))\n \n #finds smallest chisquare value in chi\n BestChiSquare = min(ChiSquare for (Temperature,Density,ChiSquare,Residual,Norm_Residual) in Chi)\n #print(BestChiSquare) \n for index, item in enumerate(Chi):\n if item[2] == BestChiSquare:\n index1 = headers[index]\n bestindex = index\n best_residuals[i] = item[3]\n best_normed_residuals[i] = item[4]\n \n if index1.startswith('1'):\n dens,temp = index1[0:4],index1[5:]\n else:\n dens,temp = index1[0:3],index1[4:]\n\n probs = np.asarray(openmodel[cols[bestindex]])\n \n best_temp[i] = temp\n best_density[i] = dens\n best_chi[i] = BestChiSquare\n #best_residuals[i] = BestChiSquare\n #best_normed_residuals[i] = BestChiSquare\n\n #print(index1,BestChiSquare)\n #return(index1,BestChiSquare)\n\n# plt.plot(lines, probs/probs[0], linewidth=2, color = 'k', linestyle = 'solid', label = 'rho= '+str(best_density[i])+' temp= '+str(best_temp[i]) )\n# plt.errorbar(lines, equivs / equivs[0], yerr = equiverr / equivs[0], fmt='ro', label = IDs[i])\n# plt.legend()\n# fig_string = 'Plots/FitPlots/'+IDs[i]+'-'+str(plates[i])+'-'+str(mjds[i])+'-'+str(fibers[i])+'.pdf'\n# title_string = IDs[i]+'-'+str(plates[i])+'-'+str(mjds[i])+'-'+str(fibers[i])+' chi= '+str(best_chi[i])\n# plt.title(title_string)\n #print(fig_string)\n #print(best_temp[i], temps[i])\n #print(best_density[i], densities[i])\n #print(best_chi[i], chis[i])\n #print(' ')\n# plt.savefig(fig_string)\n# plt.clf()\n \n ## define temperature axis\n n_temps = 8\n temp_axis = np.ones(n_temps)\n temp_axis[0] = 3100\n temp_axis[1] = 4375\n temp_axis[2] = 6250\n temp_axis[3] = 8125\n temp_axis[4] = 9375\n temp_axis[5] = 11250\n temp_axis[6] = 13750\n temp_axis[7] = 16250\n #print(temps)\n\n ## define density axis\n n_densities = 24\n density_axis = np.ones(n_densities)\n for x in range(n_densities):\n density_axis[x] = 7.9 + x*0.2\n #print(density_axis)\n\n #repackage info into arrays\n plt.hist2d(best_density[YC_good], best_temp[YC_good], bins = [density_axis, temp_axis], norm=colors.LogNorm(), cmap = plt.cm.gnuplot)\n plt.ylabel('Temp (K)')\n plt.xlabel('Log density')\n plt.colorbar()\n plt.savefig('Plots/YC_hist.pdf')\n plt.clf()\n\n# best_fit = np.nonzero(best_chi < 4)\n# print('best: ', len(best_fit))\n\n #print(np.asarray(best_temp[best_fit]))\n #print(np.asarray(best_density[best_fit]))\n \n #repackage info into arrays\n# plt.hist2d(best_density[best_fit], best_temp[best_fit], bins = [density_axis, temp_axis], norm=colors.LogNorm(), cmap = plt.cm.gnuplot)\n# plt.ylabel('Temp (K)')\n# plt.xlabel('Log density')\n# plt.colorbar()\n# plt.savefig('Plots/best_fit_hist.pdf')\n# plt.clf()\n\n# ok_fit = np.nonzero( (best_chi > 4) & (best_chi < 15) )\n# print('ok: ', len(ok_fit))\n\n #repackage info into arrays\n# plt.hist2d(best_density[ok_fit], best_temp[ok_fit], bins = [density_axis, temp_axis], norm=colors.LogNorm(), cmap = plt.cm.gnuplot)\n# plt.ylabel('Temp (K)')\n# plt.xlabel('Log density')\n# plt.colorbar()\n# plt.savefig('Plots/ok_fit_hist.pdf')\n# plt.clf()\n\n# bad_fit = np.nonzero(best_chi > 15)\n# print('bad: ', len(bad_fit))\n\n #repackage info into arrays\n# plt.hist2d(best_density[bad_fit], best_temp[bad_fit], bins = [density_axis, temp_axis], norm=colors.LogNorm(), cmap = plt.cm.gnuplot)\n# plt.ylabel('Temp (K)')\n# plt.xlabel('Log density')\n# plt.colorbar()\n# plt.savefig('Plots/bad_fit_hist.pdf')\n# plt.clf()\n \n plt.hist2d(densities[YC_good], temps[YC_good], bins = [density_axis, temp_axis], norm=colors.LogNorm(), cmap = plt.cm.gnuplot)\n plt.ylabel('Temp (K)')\n plt.xlabel('Log density')\n plt.colorbar()\n plt.savefig('Plots/old_hist.pdf')\n plt.clf()\n\n #plt.show()\n\n #find sources that best fit to the density of 10^9\n# density_9 = np.argwhere(best_density == 9.0)\n #print(best_density[density_9])\n# print('num 9s: ',len(density_9))\n \n# not_density_9 = np.argwhere(best_density != 9.0)\n #print(best_density[not_density_9])\n# print('non 9s: ',len(not_density_9))\n \n# plt.hist(best_chi[not_density_9], bins=10, label = 'not-9')\n# plt.hist(best_chi[density_9], bins=10, label = '9')\n# plt.yscale('log')\n# plt.legend()\n# plt.savefig('Plots/chisquare_compare.png')\n# plt.clf()\n #plt.show()\n\n YC_best = np.logical_and( YC_good, (best_chi < 4) )\n YC_nine = np.logical_and( YC_good, (best_density == 9) )\n\n #repackage info into arrays\n plt.hist2d(best_density[YC_best], best_temp[YC_best], bins = [density_axis, temp_axis], norm=colors.LogNorm(), cmap = plt.cm.gnuplot)\n plt.ylabel('Temp (K)')\n plt.xlabel('Log density')\n plt.colorbar()\n plt.savefig('Plots/YC_best_hist.pdf')\n plt.clf()\n\n \n plt.hist(best_chi[YC_good], bins=10, label = 'YC good', color = 'blue')\n plt.hist(best_chi[YC_nine], bins=10, label = 'YC nine', color = 'orange')\n# plt.hist(best_chi[density_9], bins=10, label = '9')\n plt.yscale('log')\n plt.legend()\n plt.savefig('Plots/chisquare_YCgood_v_nine.png')\n plt.clf()\n \n# plt.scatter(best_chi, best_residuals, s=2, marker = '.')\n# plt.scatter(best_chi[density_9], best_residuals[density_9], s=2, marker = '.', color = 'red')\n# plt.xlabel('best chi')\n# plt.ylabel('best_residuals')\n# plt.yscale('log')\n# plt.xscale('log')\n# plt.xlim(1e-2,1e4)\n# plt.savefig('Plots/ChiResiduals.png')\n# plt.clf()\n \n# plt.scatter(best_chi, best_normed_residuals, s=2, marker = '.')\n# plt.scatter(best_chi[density_9], best_normed_residuals[density_9], s=2, marker = '.', color = 'red')\n# plt.xlabel('best chi')\n# plt.ylabel('best_normed_residuals')\n# plt.yscale('log')\n# plt.xscale('log')\n# plt.xlim(1e-2,1e4)\n# plt.savefig('Plots/ChiNormedResiduals.png')\n# plt.clf()\n \n# cols = ['2Mass ID','Plate','MJD','Fiber',\"Density\",\"Temp\"]\n# newdf = pd.DataFrame(columns = cols)\n\n\n# newdf['2Mass ID'] = IDs\n# newdf['Plate'] = plates\n# newdf['MJD'] = mjds\n# newdf['Fiber'] = fibers\n# newdf['Density'] = densities\n# newdf['Temp'] = temps\n \n# newdf.to_csv('//alpha.univ.dir.wwu.edu/Research/Covey/APOGEE_Spectra/Hunter/DR17/Files/BetterErrors/JustEqw_gtr_0.75_AND_SNR_gtr_1_DensTemp.csv', index=False)\n\nFinalSample()\n\n\n\n\n","sub_path":"Summer_2021/Kevin/FinalSample.py","file_name":"FinalSample.py","file_ext":"py","file_size_in_byte":17850,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"462979120","text":"import numpy as np\nimport networkx as nx\nfrom networkx.algorithms.flow import shortest_augmenting_path\nimport time\n\n\nfrom typing import Any, Dict, Iterable, List, Optional, Sequence, Tuple, Union\n\n\n\ndef merge_cross_chunk_edges(edges: Iterable[Sequence[np.uint64]],\n affs: Sequence[np.uint64]):\n \"\"\" Merges cross chunk edges\n\n :param edges: n x 2 array of uint64s\n :param affs: float array of length n\n :return:\n \"\"\"\n\n cross_chunk_edge_mask = np.isinf(affs)\n\n cross_chunk_graph = nx.Graph()\n cross_chunk_graph.add_edges_from(edges[cross_chunk_edge_mask])\n\n ccs = nx.connected_components(cross_chunk_graph)\n\n remapping = {}\n mapping = np.array([], dtype=np.int).reshape(-1, 2)\n\n for cc in ccs:\n nodes = np.array(list(cc))\n rep_node = np.min(nodes)\n\n remapping[rep_node] = nodes\n\n rep_nodes = np.ones(len(nodes), dtype=np.int).reshape(-1, 1) * rep_node\n m = np.concatenate([nodes.reshape(-1, 1), rep_nodes], axis=1)\n\n mapping = np.concatenate([mapping, m], axis=0)\n\n u_nodes = np.unique(edges)\n u_unmapped_nodes = u_nodes[~np.in1d(u_nodes, mapping)]\n\n unmapped_mapping = np.concatenate([u_unmapped_nodes.reshape(-1, 1),\n u_unmapped_nodes.reshape(-1, 1)], axis=1)\n mapping = np.concatenate([mapping, unmapped_mapping], axis=0)\n\n sort_idx = np.argsort(mapping[:, 0])\n idx = np.searchsorted(mapping[:, 0], edges, sorter=sort_idx)\n remapped_edges = np.asarray(mapping[:, 1])[sort_idx][idx]\n\n remapped_edges = remapped_edges[~cross_chunk_edge_mask]\n remapped_affs = affs[~cross_chunk_edge_mask]\n\n return remapped_edges, remapped_affs, remapping\n\n\ndef mincut(edges: Iterable[Sequence[np.uint64]], affs: Sequence[np.uint64],\n source: np.uint64, sink: np.uint64) -> np.ndarray:\n \"\"\" Computes the min cut on a local graph\n\n :param edges: n x 2 array of uint64s\n :param affs: float array of length n\n :param source: uint64\n :param sink: uint64\n :return: m x 2 array of uint64s\n edges that should be removed\n \"\"\"\n\n time_start = time.time()\n\n # edges, affs, remapping = merge_cross_chunk_edges(edges, affs)\n\n weighted_graph = nx.Graph()\n weighted_graph.add_edges_from(edges)\n\n for i_edge, edge in enumerate(edges):\n weighted_graph[edge[0]][edge[1]]['capacity'] = affs[i_edge]\n\n dt = time.time() - time_start\n print(\"Graph creation: %.2fms\" % (dt * 1000))\n time_start = time.time()\n\n ccs = list(nx.connected_components(weighted_graph))\n for cc in ccs:\n if not (source in cc and sink in cc):\n weighted_graph.remove_nodes_from(cc)\n\n # cutset = nx.minimum_edge_cut(weighted_graph, source, sink)\n cutset = nx.minimum_edge_cut(weighted_graph, source, sink,\n flow_func=shortest_augmenting_path)\n\n dt = time.time() - time_start\n print(\"Mincut: %.2fms\" % (dt * 1000))\n\n if cutset is None:\n return np.array([], dtype=np.uint64)\n\n time_start = time.time()\n\n weighted_graph.remove_edges_from(cutset)\n ccs = list(nx.connected_components(weighted_graph))\n print(\"Graph split up in %d parts\" % (len(ccs)))\n\n for cc in ccs:\n print(\"CC size = %d\" % len(cc))\n\n dt = time.time() - time_start\n print(\"Test: %.2fms\" % (dt * 1000))\n\n return np.array(list(cutset), dtype=np.uint64)","sub_path":"pychunkedgraph/backend/mincut.py","file_name":"mincut.py","file_ext":"py","file_size_in_byte":3394,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"1678878","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Tue Mar 2 09:14:12 2021\r\n\r\n@author: Wountry\r\n\"\"\"\r\nimport pandas as pd\r\nimport os\r\nimport matplotlib.pyplot as plt\r\nimport numpy as np\r\nfrom sklearn.svm import SVR\r\nfrom sklearn.metrics import mean_absolute_error #平均绝对误差,用于评估预测结果和真实数据集的接近程度的程度其其值越小说明拟合效果越好。\r\nfrom sklearn.metrics import mean_squared_error #均方差,该指标计算的是拟合数据和原始数据对应样本点的误差的平方和的均值,其值越小说明拟合效果越好。\r\nfrom sklearn.preprocessing import normalize\r\n\r\nall_data = pd.read_csv('D:\\\\Pythondata\\\\wcr.csv',header=0,index_col=0) #读取文件 第一行当表头和第一列当索引\r\ndata_test=all_data[all_data.index <= 19] #利用索引选取第一个文件做测试集\r\ndata_train=all_data[all_data.index > 19] #选取后面所有文件做训练集\r\ndata_train= normalize(data_train) #归一化\r\ndata_test= normalize(data_test)\r\ndata_train=pd.DataFrame(data_train) #列表格式转化为dataframe格式\r\ndata_test=pd.DataFrame(data_test)\r\nX_train=data_train.iloc[:, 0:10] #训练集中选取前10列\r\ny_train=data_train.iloc[:, [10]] #训练集中选取第11列\r\n\r\nsvr = SVR(kernel = 'rbf')\r\nsvr.fit(X_train, y_train)\r\n\r\nX_test=data_test.iloc[:, 0:10] #测试集中选取前10列\r\ny_test=data_test.iloc[:, [10]] #测试集中选取第11列\r\n\r\n\r\ny_test_pred = svr.predict(X_test)\r\n\r\n\r\nprint(y_test_pred)\r\nprint(y_test)\r\nprint(mean_absolute_error(y_test, y_test_pred))\r\nprint(mean_squared_error(y_test, y_test_pred))\r\nprint(svr.score(X_test, y_test))\r\n\r\ndeflection=data_test.iloc[:,[9]] #测试集第10列作为x轴\r\nresistance=data_test.iloc[:, [10]] #测试集第11列作为y轴\r\npred_resistance=y_test_pred #训练结果作为y轴进行对比\r\nplt.plot(deflection,resistance,\"bs-\",label=\"Original data\")\r\nplt.plot(deflection,pred_resistance,\"rs-\",label=\"Predicted data\")\r\nplt.ylim(0,1)\r\nplt.title(\"Support Vector Machine\")\r\nplt.xlabel(\"deflection\")\r\nplt.ylabel(\"resistance\")\r\nplt.legend()\r\nplt.grid(color='black',linestyle='--')\r\nplt.show()","sub_path":"支持向量机.py","file_name":"支持向量机.py","file_ext":"py","file_size_in_byte":2146,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"164200312","text":"from kafka import KafkaConsumer, TopicPartition\nfrom json import loads\n\nclass XactionConsumer:\n def __init__(self):\n self.consumer = KafkaConsumer('bank-customer-events',\n bootstrap_servers=['localhost:9092'],\n # auto_offset_reset='earliest',\n value_deserializer=lambda m: loads(m.decode('ascii')))\n ## These are two python dictionarys\n # Ledger is the one where all the transaction get posted\n self.ledger = {}\n # custBalances is the one where the current blance of each customer\n # account is kept.\n self.custBalances = {}\n # THE PROBLEM is every time we re-run the Consumer, ALL our customer\n # data gets lost!\n # add a way to connect to your database here.\n\n #Go back to the readme.\n\n def handleMessages(self):\n for message in self.consumer:\n message = message.value\n print('{} received'.format(message))\n self.ledger[message['custid']] = message\n # add message to the transaction table in your SQL usinf SQLalchemy\n if message['custid'] not in self.custBalances:\n self.custBalances[message['custid']] = 0\n if message['type'] == 'dep':\n self.custBalances[message['custid']] += message['amt']\n else:\n self.custBalances[message['custid']] -= message['amt']\n print(self.custBalances)\n\nif __name__ == \"__main__\":\n c = XactionConsumer()\n c.handleMessages()","sub_path":"phase1/consumer-to-SQL.py","file_name":"consumer-to-SQL.py","file_ext":"py","file_size_in_byte":1517,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"639212672","text":"# Copyright 2021 The Kubeflow Authors.\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 chocolate as choco\nimport logging\nimport base64\nimport warnings\n\nfrom pkg.suggestion.v1beta1.internal.constant import MAX_GOAL, INTEGER, DOUBLE, CATEGORICAL, DISCRETE\nfrom pkg.suggestion.v1beta1.internal.trial import Assignment\n\nlogger = logging.getLogger(__name__)\n\nDB_ADDRESS = \"sqlite:///my_db.db?check_same_thread=False\"\nDB_FIELD_LOSS = \"_loss\"\nDB_FIELD_CHOCOLATE_ID = \"_chocolate_id\"\nDB_FIELD_TRIAL_NAME = \"_trial_name\"\n\nDEPRECATED_ALGORITHM_NAME = {\n \"chocolate-random\": \"random\",\n \"chocolate-quasirandom\": \"quasirandom\",\n \"chocolate-bayesian-optimization\": \"bayesianoptimization\",\n \"chocolate-mocmaes\": \"mocmaes\",\n}\n\n\nclass BaseChocolateService(object):\n \"\"\"\n Refer to https://chocolate.readthedocs.io/\n \"\"\"\n\n def __init__(self, algorithm_name, search_space):\n self.conn = choco.SQLiteConnection(DB_ADDRESS)\n self.search_space = search_space\n self.chocolate_optimizer = None\n self.create_optimizer(algorithm_name)\n # created_trials is the list of dicts with all created trials assignments, loss and trial name\n # _chocolate_id is the ID of the trial, Assignment names are encoded, _loss is the target metric, _trial_name is the Trial name\n # One row example:\n # {'_chocolate_id': 0, 'LS1scg==': 0.001, 'LS1udW0tZXBvY2hz': 1, 'LS1udW0tbGF5ZXJz': 2, \"_loss\": \"0.97\", \"_trial_name\": \"grid-example-hsdvfdwl\"}\n self.created_trials = []\n self.recorded_trials_names = []\n\n def create_optimizer(self, algorithm_name):\n\n # Search Space example: {\"x\" : choco.uniform(-6, 6), \"y\" : choco.uniform(-6, 6)}\n chocolate_search_space = {}\n\n for param in self.search_space.params:\n key = BaseChocolateService.encode(param.name)\n if param.type == INTEGER:\n chocolate_search_space[key] = choco.quantized_uniform(\n int(param.min), int(param.max), int(param.step))\n elif param.type == DOUBLE:\n chocolate_search_space[key] = choco.quantized_uniform(\n float(param.min), float(param.max), float(param.step))\n # For Categorical and Discrete insert indexes to DB from list of values\n elif param.type == CATEGORICAL or param.type == DISCRETE:\n chocolate_search_space[key] = choco.choice(\n [idx for idx, _ in enumerate(param.list)])\n\n if algorithm_name in DEPRECATED_ALGORITHM_NAME:\n warnings.warn(\n \"Algorithm name '{}' is deprecated. Please use '{}'.\".format(\n algorithm_name, DEPRECATED_ALGORITHM_NAME[algorithm_name],\n ),\n DeprecationWarning,\n )\n algorithm_name = DEPRECATED_ALGORITHM_NAME[algorithm_name]\n\n # Refer to https://chocolate.readthedocs.io/tutorials/algo.html\n if algorithm_name == \"grid\":\n self.chocolate_optimizer = choco.Grid(\n self.conn, chocolate_search_space, clear_db=True)\n # hyperopt-random is the default option in katib.\n elif algorithm_name == \"random\":\n self.chocolate_optimizer = choco.Random(\n self.conn, chocolate_search_space, clear_db=True)\n elif algorithm_name == \"quasirandom\":\n self.chocolate_optimizer = choco.QuasiRandom(\n self.conn, chocolate_search_space, clear_db=True)\n elif algorithm_name == \"bayesianoptimization\":\n self.chocolate_optimizer = choco.Bayes(\n self.conn, chocolate_search_space, clear_db=True)\n # elif self.algorithm_name == \"chocolate-CMAES\":\n # self.chocolate_optimizer = choco.CMAES(self.conn, chocolate_search_space, clear_db=True)\n elif algorithm_name == \"mocmaes\":\n mu = 1\n self.chocolate_optimizer = choco.MOCMAES(\n self.conn, chocolate_search_space, mu=mu, clear_db=True)\n else:\n raise Exception(\n '\"Failed to create Chocolate optimizer for the algorithm: {}'.format(algorithm_name))\n\n def getSuggestions(self, trials, request_number):\n \"\"\"\n Get the new suggested trials with chocolate algorithm.\n \"\"\"\n logger.info(\"-\" * 100 + \"\\n\")\n logger.info(\"New GetSuggestions call\\n\")\n for _, trial in enumerate(trials):\n if trial.name not in self.recorded_trials_names:\n loss_for_choco = float(trial.target_metric.value)\n if self.search_space.goal == MAX_GOAL:\n loss_for_choco = -1 * loss_for_choco\n\n trial_assignments_dict = {}\n for param in self.search_space.params:\n param_assignment = None\n for assignment in trial.assignments:\n if param.name == assignment.name:\n param_assignment = assignment.value\n break\n if param.type == INTEGER:\n param_assignment = int(param_assignment)\n elif param.type == DOUBLE:\n param_assignment = float(param_assignment)\n elif param.type == CATEGORICAL or param.type == DISCRETE:\n param_assignment = param.list.index(param_assignment)\n trial_assignments_dict.update({BaseChocolateService.encode(\n param.name): param_assignment})\n\n # Finding index for the current Trial Assignments in created_trial list without loss\n new_trial_loss_idx = -1\n i = 0\n while new_trial_loss_idx == -1 and i < len(self.created_trials):\n # Created Trial must not include loss and must have the same param assignment\n if ((DB_FIELD_LOSS not in self.created_trials[i] or self.created_trials[i][DB_FIELD_LOSS] is None) and\n len(trial_assignments_dict.items() & self.created_trials[i].items()) == len(self.search_space.params)):\n new_trial_loss_idx = i\n i += 1\n\n if new_trial_loss_idx != -1:\n self.created_trials[new_trial_loss_idx][DB_FIELD_LOSS] = loss_for_choco\n self.created_trials[new_trial_loss_idx][DB_FIELD_TRIAL_NAME] = trial.name\n\n # Update sqlite database with new loss and trial assignments\n id_filter = {\n DB_FIELD_CHOCOLATE_ID: self.created_trials[new_trial_loss_idx][DB_FIELD_CHOCOLATE_ID]}\n self.conn.update_result(\n id_filter,\n self.created_trials[new_trial_loss_idx])\n\n self.recorded_trials_names.append(trial.name)\n\n logger.info(\"New record in sqlite DB is updated\")\n logger.info(\"{}\\n\".format(\n self.created_trials[new_trial_loss_idx]))\n\n list_of_assignments = []\n for i in range(request_number):\n try:\n token, chocolate_params = self.chocolate_optimizer.next()\n new_assignment = BaseChocolateService.convert(\n self.search_space, chocolate_params)\n list_of_assignments.append(new_assignment)\n logger.info(\"New suggested parameters for Trial with chocolate_id: {}\".format(\n token[DB_FIELD_CHOCOLATE_ID]))\n for assignment in new_assignment:\n logger.info(\"Name = {}, Value = {}\".format(\n assignment.name, assignment.value))\n logger.info(\"-\" * 50 + \"\\n\")\n # Add new trial assignment with chocolate_id to created trials\n token.update(chocolate_params)\n new_trial_dict = token\n self.created_trials.append(new_trial_dict)\n\n except StopIteration:\n logger.info(\n \"Chocolate db is exhausted, increase Search Space or decrease maxTrialCount!\")\n\n if len(list_of_assignments) > 0:\n logger.info(\n \"GetSuggestions returns {} new Trials\\n\\n\".format(request_number))\n\n return list_of_assignments\n\n @staticmethod\n def convert(search_space, chocolate_params):\n assignments = []\n for param in search_space.params:\n key = BaseChocolateService.encode(param.name)\n if param.type == INTEGER:\n assignments.append(Assignment(\n param.name, chocolate_params[key]))\n elif param.type == DOUBLE:\n assignments.append(Assignment(\n param.name, chocolate_params[key]))\n elif param.type == CATEGORICAL or param.type == DISCRETE:\n assignments.append(Assignment(\n param.name, param.list[chocolate_params[key]]))\n return assignments\n\n @staticmethod\n def encode(name):\n \"\"\"Encode the name. Chocolate will check if the name contains hyphens.\n Thus we need to encode it.\n \"\"\"\n return base64.b64encode(name.encode('utf-8')).decode('utf-8')\n","sub_path":"pkg/suggestion/v1beta1/chocolate/base_service.py","file_name":"base_service.py","file_ext":"py","file_size_in_byte":9759,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"123994424","text":"import sys\nimport numpy as np\nfrom matplotlib import pyplot as plt\n\nfrom scipy.signal import lfilter, butter\nfrom scipy.stats import gennorm\n\n\nimport time as timer\n\nimport warnings\nwarnings.simplefilter(action='ignore', category=DeprecationWarning)\nfrom hmmlearn import hmm\nimport nmf\n\nexpName = sys.argv[1]\nrunN = sys.argv[2]\nchan = sys.argv[3]\n\nK = 1\nL = 25\n\nlmbda = 100.0 # sparsity coeff\nalpha = 0.25 # sparsity exponent\n\nsteps = 100+9\n\ntemplate_data = []\ntry:\n annotations = open(\"data/annotations/annotation_\"+expName+\"_\"+str(runN)+\"_\"+str(chan)+\".txt\").readlines()\n startPoint = int(annotations.pop(0))\n for line in annotations:\n if line == \"\":\n continue\n line = line.split(\" \")\n s, e = int(float(line[0])*20000), int(float(line[1])*20000)\n template_data.append((s, e))\n\nexcept:\n print(\"Could not load annotations\")\n\nendPoint = startPoint + 150000\n\ndef butter_highpass(cutoff, fs, order=5):\n nyq = 0.5 * fs\n normal_cutoff = cutoff / nyq\n b, a = butter(order, normal_cutoff, btype='highpass', analog=False)\n return b, a\n\n\nhb, ha = butter_highpass(300, 20000.0, 5)\ndata = np.load(\"E:\\\\bryan\\\\recordings\\\\4Jun2018\\\\\"+expName+\"\\\\\"+runN+\"\\\\chan_\" + chan + \".npy\")\nburst = lfilter(hb, ha, data)[startPoint:endPoint]\nX = burst.T.astype(np.float32)\ntime = np.arange(0.0, len(burst)*0.00005, 0.00005)\nseparator = 1000\n\nfig, ax = plt.subplots(3, 1)\nax0 = plt.subplot(4, 1, 1)\nax1 = plt.subplot(4, 1, 2, sharex=ax0, sharey=ax0)\nax2 = plt.subplot(4, 1, 3, sharex=ax0)\nax3 = plt.subplot(4, 1, 4)\n\nax = [ax0, ax1, ax2, ax3]\n\ncosts = [0]*steps\np0, = ax[0].plot(time, burst, linewidth=0.3, color='C1')\n\nax[0].set_title(\"Original Signal\")\np1, = ax[1].plot(time, burst, linewidth=0.3, color='C2')\nax[1].set_title(\"Reconstructed Signal\")\np3, = ax[3].plot(range(steps), costs, linewidth=0.3, color='C2')\nax[3].set_title(\"Cost Function\")\nax[2].set_title(\"Activation Coefficients\")\n\nx_end = len(burst)*0.00005\nax[0].set_xlim((0, x_end))\nax[0].set_ylim((-1000, 1000))\nax[1].set_xlim((0, x_end))\nax[2].set_xlim((0, x_end))\nax[2].set_ylim((-10, 600))\nax[3].set_ylim((-10, 100000000))\nax[3].set_xlim((0, steps-1))\nplt.tight_layout()\nplt.subplots_adjust(hspace=0.2)\nplt.get_current_fig_manager().window.state('zoomed')\n\nT = len(burst)\nA = np.zeros((T, K))\nB = np.zeros((K, L))\n\nnmf.setGlobals(T, L, K, lmbda, alpha)\n\nA_templates = np.zeros((T, K))\nfor ann in template_data:\n A_templates[ann[0]-L:ann[1],0] = 1\n\ntoPlot = []\nfor k in range(K):\n toPlot.append(time)\n toPlot.append(A[:,k])\naPlots = ax[2].plot(*toPlot, linewidth=0.3)\n\nfigK, axK = plt.subplots(K, 1)\naxK = []\nkPlots = []\nfor k in range(K):\n if k == 0:\n p = plt.subplot(K, 1, k+1)\n else:\n p = plt.subplot(K, 1, k+1, sharex=axK[0], sharey=axK[0])\n pk, = p.plot(B[k], color=\"C\"+str(k))\n kPlots.append(pk)\n p.set_xlim((0, L))\n p.set_ylim((-2, 1))\n axK.append(p)\nfigK.canvas.manager.window.wm_geometry(\"1920x1140+1920+0\")\nplt.ion()\nplt.show()\n\nfor k in range(K):\n A[:,k] = np.load(\"data/activations/spikeActivation_\"+expName+\"_\"+str(runN)+\"_\"+str(chan)+\"_\"+str(k)+\".npy\")\nB = np.load(\"data/templates/spikeTemplate_\"+expName+\"_\"+str(runN)+\"_\"+str(chan)+\"_\"+str(k)+\"_avg.npy\")\nB = np.reshape(B, (K, L))\n\nest = nmf.estimate(A, B)\np1.set_ydata(est)\nfor k in range(K):\n aPlots[k].set_ydata(A[:,k])\n\nfor k in range(K):\n kPlots[k].set_ydata(B[k])\nplt.draw()\nplt.pause(0.01)\n\nhistogram_fig = plt.figure()\n(beta, loc, scale) = gennorm.fit(X, fbeta=1.3)\nn, bins, _ = plt.hist(X, bins=100, density=True)\nl = plt.plot(bins, gennorm.pdf(bins, beta=beta, loc=loc, scale=scale), 'r--', linewidth=2)\n\nprint(\"scale=\", scale)\n\nhistogram_fig = plt.figure()\nAvalues = []\nAantivalues = []\nlevels = 5\n\nfor t in range(T):\n value = A[t,0]//scale\n if value > A[t,0]//levels:\n value = levels-1\n value += 0.5\n\n if A_templates[t,0] != 0:\n Avalues.append(value)\n else:\n Aantivalues.append(value)\n\nbins = range(levels+1)\n\neBursting, _, _ = plt.hist(Avalues, bins=bins, density=True, alpha=0.5)\neNotBursting, _, _ = plt.hist(Aantivalues, bins=bins, density=True, alpha=0.5)\n\nprint(\"Bursting:\", eBursting)\nprint(\"Not Bursting:\", eNotBursting)\np = 0.74\n\ntransition_p = np.array([\n [p, 1-p],\n [1-p, p]\n])\n\nemission_p = np.array([\n eNotBursting,\n eBursting\n])\n\nstarting_p = np.array([\n 1.0,\n 0.0\n])\n\nmultinomial_A = (A[:,0] // scale).astype(np.int)\nmultinomial_A = np.minimum(multinomial_A, levels-2)\nmultinomial_A.shape = (T,1)\n\nhmmmodel = hmm.MultinomialHMM(n_components=2, params=\"\", init_params=\"\")\nhmmmodel.transmat_ = transition_p\nhmmmodel.emissionprob_ = emission_p\nhmmmodel.startprob_ = starting_p\n\nhmmmodel.fit(multinomial_A)\nhmmA = hmmmodel.predict(multinomial_A)\n\n#Elongate detection\nt = 0\ninBurst = hmmA[t] == 1\nwhile t < T:\n if inBurst and hmmA[t] == 0:\n if t+L > T-1:\n hmmA[t:] = 1\n t = t+L\n continue\n hmmA[t:t+L] = 1\n t = t+L\n inBurst = hmmA[t] == 1\n continue\n\n if hmmA[t] == 1:\n inBurst = True\n t += 1\n\n#Quality criteria\nthreshold = 500\nt = 0\nwhile t < T:\n if hmmA[t] == 1:\n start = t\n while t < T and hmmA[t] == 1:\n t += 1\n end = t\n\n if np.max(A[start:end,0]) < threshold:\n hmmA[start:end] = 0\n\n #print(start * 0.00005, end-start, np.sum(A[start:end] > 300), np.sum(A[start:end] > 300) / (end-start))\n t += 1\n\nax[0].plot(time, np.roll(hmmA*300, L//2), linewidth=0.6, color=\"C0\")\nax[1].plot(time, np.roll(hmmA*300, L//2), linewidth=0.6, color=\"C1\")\nax[1].plot(time, A_templates[:,0]*300, linewidth=0.6, color=\"C4\")\nax[2].plot(time, hmmA*300, linewidth=0.6, color=\"C9\")\n\nfigMain = plt.figure()\n#figMain = plt.figure(figsize=(25,5))\n#plt.plot(time, X, linewidth=0.05)\n#plt.plot(time, np.roll(hmmA*500, L//2), linewidth=0.1)\nplt.plot(time, X, linewidth=0.3)\nplt.plot(time, np.roll(hmmA*500, L//2), linewidth=0.6)\nplt.xlim((0, T*0.00005))\nplt.subplots_adjust(left=0.01, right=0.99)\n\nfigMain.savefig(\"large_\"+expName+\"_\"+str(runN)+\"_\"+str(chan)+\".png\", dpi=1000, pad_inches=0)\nfigMain.canvas.manager.window.wm_geometry(\"4000x1000+0+0\")\nplt.pause(1000)","sub_path":"trainMarkov.py","file_name":"trainMarkov.py","file_ext":"py","file_size_in_byte":6181,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"625667819","text":"import tensorflow as tf\n\n\"\"\"\n텐서플로(TensorFlow)\n\"\"\"\n\n'''\ntf.keras.layers\n딥러닝 모델을 만드는 것은 마치 블록을 하나씩 쌓아서 전체 구조를 만들어 가는 것\n케라스는 텐서플로와 같은 별개의 딥러닝 오픈소스이나, 텐서플로에서도 케라스를 사용 할 수 있다.\n'''\n\n'''\ntf.keras.layers.Dense\nhttps://www.tensorflow.org/api_docs/python/tf/keras/layers/Dense\n\n신경망 구조의 가장 기본적인 형태 | 은닉층이 없는 간단한 신경망 형태\n\ny = f(Wx+b) 를 만족하는 기본적인 싱경망 형태의 층\nx, b는 각각 입력 벡터, 편향 벡터\nW는 가중치 행렬\n\n\n'''\n\n\ndef dense_pure(x):\n \"\"\"\n Dense 층을 구성하는 기본적인 방법\n :param x:\n :return:\n \"\"\"\n W = tf.Variable(tf.random_uniform([5, 10], -1.0, 1.0)) # 가중치\n b = tf.Variable(tf.zeros([10])) # 편향\n\n y = tf.matmul(W, x) + b\n\n\ndef dense(input):\n \"\"\"\n Dense 를 사용하는 방법\n :return:\n \"\"\"\n # 1. 객체 생성 후 다시 호출하면서 입력값 설정\n dense = tf.keras.layers.Dense()\n output = dense(input)\n\n # 2. 객체 생성 시 입력 값 설정\n output = tf.keras.layers.Dense()(input)\n\n\ndef example_02_dense_01():\n \"\"\"\n 입력 값에 대해 활성화 함수로 시그모이드 함수를 사용\n 출력 값으로 10개의 값을 출력하는 완전 연결 계층(Fully Connected Layer)\n units: 출력 값의 크기\n activation: 활성화 함수\n :return:\n \"\"\"\n INPUT_SIZE = (20, 1)\n\n input = tf.placeholder(tf.float32, shape=INPUT_SIZE)\n output = tf.keras.layers.Dense(units=10, activation=tf.nn.sigmoid)(input)\n\n return output\n\n\ndef example_02_dense_02():\n \"\"\"\n 10개의 노드를 가지는 은닉층이 있고 최종 출력 값은 2개의 노드가 있는 신경망 구조\n :return:\n \"\"\"\n INPUT_SIZE = (20, 1)\n\n input = tf.placeholder(tf.float32, shape=INPUT_SIZE)\n hidden = tf.keras.layers.Dense(units=10, activation=tf.nn.sigmoid)(input)\n output = tf.keras.layers.Dense(units=2, activation=tf.nn.sigmoid)(hidden)\n\n return output\n","sub_path":"02/01_01_tensorflow_dense.py","file_name":"01_01_tensorflow_dense.py","file_ext":"py","file_size_in_byte":2127,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"395093774","text":"import numpy as np \nfrom mayavi import mlab\n\n#建立数据\nt = np.linspace(0,4*np.pi,20)\nx = np.sin(2*t)\ny = np.cos(t)\nz = np.cos(2*t)\ns = 2 + np.sin(t)\n\n#对数据继续宁可视化\npoints = mlab.points3d(x,y,z,s,colormap=\"Reds\",scale_factor=.25)\nmlab.show()","sub_path":"PythonVIS/class3/point3dexample.py","file_name":"point3dexample.py","file_ext":"py","file_size_in_byte":259,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"37648883","text":"#!/usr/bin/env python3\n'''Module - Factors natural numbers'''\n\nfrom __future__ import division\nimport sys\nimport os\n\n\ndef func_factors(filename):\n '''Read and find Factorials of every line '''\n with open(filename, 'r') as f:\n for line in f:\n num = int(line)\n resul = factors(num)\n print (\"{}={}*{}\".format(num, int(num / resul), resul))\n f.closed\n\ndef factors(x):\n '''Returns the minimun factorial number '''\n for y in range(1, x + 1):\n if x % y == 0 and y != 1:\n return y\n\nif __name__ == \"__main__\":\n '''main'''\n if (len(sys.argv) != 2):\n raise SyntaxError(\"[BAD-USAGE]: Expected only one argument\")\n func_factors(sys.argv[1])\n","sub_path":"rsa.py","file_name":"rsa.py","file_ext":"py","file_size_in_byte":748,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"297293641","text":"#!/usr/bin/env python3.5\n# -*- coding: utf-8 -*-\n\"\"\"\n__author__ = xyy\n__mtime__ = 2016/11/21\n\"\"\"\n\n'''\npyspider结果保存到数据库简单样例。\n使用方法:\n 1,把本文件放到pyspider/pyspider/database/mysql/目录下命名为mysqldb.py。\n 2,修改本文件的数据库配置参数及建立相应的表和库。\n 3,在脚本文件里使用from pyspider.database.mysql.mysqldb import SQL引用本代码.\n 4,重写on_result方法,实例化sql并调用replace(replace方法参数第一个是表名,第二个是结果。)。简单例子如下:\n#!/usr/bin/env python\n# -*- encoding: utf-8 -*-\n# Created on 2015-01-26 13:12:04\n# Project: jishubu.net\n\nfrom pyspider.libs.base_handler import *\nfrom pyspider.database.mysql.mysqldb import SQL\n\n\nclass Handler(BaseHandler):\n crawl_config = {\n }\n\n @every(minutes=24 * 60)\n def on_start(self):\n self.crawl('http://www.jishubu.net/', callback=self.index_page)\n\n @config(age=10 * 24 * 60 * 60)\n def index_page(self, response):\n for each in response.doc('p.pic a[href^=\"http\"]').items():\n print each.attr.href\n\n @config(priority=2)\n def detail_page(self, response):\n return {\n \"url\": response.url,\n \"title\": response.doc('HTML>BODY#presc>DIV.main>DIV.prices_box.wid980.clearfix>DIV.detail_box>DL.assort.tongyong>DD>A').text(),\n }\n def on_result(self, result):\n #print result\n if not result or not result['title']:\n return\n sql = SQL()\n sql.replace('info',**result)\n'''\nfrom six import itervalues\nimport mysql.connector\n\n\nclass SQL:\n username = 'root' # 数据库用户名\n password = 'root' # 数据库密码\n database = 'pyspider' # 数据库\n host = 'localhost' # 数据库主机地址\n connection = ''\n connect = True\n\n\nplaceholder = '%s'\n\n\ndef __init__(self):\n if self.connect:\n SQL.connect(self)\n\n\ndef escape(self, string):\n return '`%s`' % string\n\n\ndef connect(self):\n config = {\n 'user': SQL.username,\n 'password': SQL.password,\n 'host': SQL.host\n }\n if SQL.database != None:\n config['database'] = SQL.database\n\n try:\n cnx = mysql.connector.connect(**config)\n SQL.connection = cnx\n return True\n except mysql.connector.Error as err:\n print(\"Something went wrong: \", err)\n return False\n\n\ndef replace(self, tablename=None, **values):\n if SQL.connection == '':\n print(\"Please connect first\")\n return False\n\n tablename = self.escape(tablename)\n if values:\n _keys = \", \".join(self.escape(k) for k in values)\n _values = \", \".join([self.placeholder, ] * len(values))\n sql_query = \"REPLACE INTO %s (%s) VALUES (%s)\" % (tablename, _keys, _values)\n else:\n sql_query = \"REPLACE INTO %s DEFAULT VALUES\" % tablename\n\n cur = SQL.connection.cursor()\n try:\n if values:\n cur.execute(sql_query, list(itervalues(values)))\n else:\n cur.execute(sql_query)\n SQL.connection.commit()\n return True\n except mysql.connector.Error as err:\n print(\"An error occured: {}\".format(err))\n return False","sub_path":"pyspider/database/mysql/mysqldb.py","file_name":"mysqldb.py","file_ext":"py","file_size_in_byte":3209,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"230375704","text":"import pandas as pd\r\nfrom datetime import *\r\nimport csv\r\nimport shutil\r\nfrom dateutil.parser import parse\r\nfrom tkinter import *\r\ndef clicked():\r\n dt1=str(txt1.get())\r\n dt2=str(txt2.get())\r\n td1=parse(dt1)\r\n td2=parse(dt2)\r\n dtnow=datetime.now()\r\n fdt=str(dtnow.year)+str(dtnow.month)+str(dtnow.day)+str(dtnow.hour)+str(dtnow.minute)+str(dtnow.second)\r\n shutil.copy('ssss.csv','temp\\ dupliss.csv')\r\n with open(fdt+'.csv', 'w', newline='') as file:\r\n writer = csv.writer(file)\r\n writer.writerow([\"Date and Time\",\"Temprature(C)\"])\r\n df = pd.read_csv('temp\\ dupliss.csv')\r\n final= df['Date'] +\" \"+ df['Time']\r\n a= df['Date'] +\" \"+ df['Time']\r\n dtlen=len(a)\r\n x=1\r\n new=a\r\n while(xdf['Date'][x]):\r\n with open(fdt+\".csv\",\"a\", newline='') as file2:\r\n writerr=csv.writer(file2)\r\n writerr.writerow([str(df['Date'][x]),str(df['Temprature'][x])])\r\n x=x+1\r\n window.quit()\r\nwindow = Tk()\r\nwindow.title(\"Welcome\")\r\nwindow.geometry('500x250')\r\nlbl1 = Label(window, text=\"Please Enter First Date(YYYY-MM-DD HH:MM:SS):- \")\r\nlbl1.grid(column=0, row=0)\r\ntxt1 = Entry(window,width=20)\r\ntxt1.grid(column=1,row=0)\r\nlbl2= Label(window, text=\"Please Enter Second Date(YYYY-MM-DD HH:MM:SS):- \")\r\nlbl2.grid(column=0, row=1)\r\ntxt2 = Entry(window,width=20)\r\ntxt2.grid(column=1,row=1)\r\nbtn=Button(window,text=\"Click Me! And Exit\",command=clicked)\r\nbtn.grid(column=0,row=2)\r\nwindow.mainloop()\r\n","sub_path":"csvcc.py","file_name":"csvcc.py","file_ext":"py","file_size_in_byte":1756,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"189618378","text":"from bs4 import BeautifulSoup\n\nimport requests\nimport csv\n\nurl = 'https://www.bithumb.com/'\n\nres = requests.get(url).text\nsoup = BeautifulSoup(res, 'html.parser')\n\ncoins = soup.select('tbody > tr')\n\nwith open('coin.csv', 'w', encoding='utf-8', newline='') as f:\n csv_writer = csv.writer(f)\n\n for coin in coins:\n row = [coin.select_one('.blind').text, coin.select_one('.sort_real').text]\n csv_writer.writerow(row)\n","sub_path":"03.python_plus/coin.py","file_name":"coin.py","file_ext":"py","file_size_in_byte":433,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"162975342","text":"# Programe una función que determine si un número entero suministrado como argumento es primo\ndef esPrimo (num):\n if num < 1:\n return False\n elif num == 2:\n return True\n else:\n for i in range (2, num):\n if (num % i) == 0:\n return False\n return True\n\ndef app():\n num = int(input(\"ingrese un numero :\"))\n\n if(esPrimo(num)):\n print(\"El numero es primo\")\n else:\n print(\"El numero no es primo\")\n\n assert esPrimo(2) == True\n assert esPrimo(4) == False\n\nif __name__ == '__main__':\n app()","sub_path":"practico_01_cvg/ejercicio_13.py","file_name":"ejercicio_13.py","file_ext":"py","file_size_in_byte":577,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"41664740","text":"\"\"\"\ndata_parser query\n\nuse crowdfund;\n\nSELECT url,\nimage_url,\nlength(title),\nlocation_country,\nlocation_type,\nlength(sub_title),\nvideo_url,\ncategory,\ncategory_slug,\ncurrency,\nfunding_goal,\nstate,\nend_date,\nlaunch_date,\nnum_supporters,\nnum_updates,\nnum_comments,\nlength(story),\nnum_fb_shares,\nREPLACE(REPLACE(REPLACE(story,'\\n',''), '\\t',''),';',''),\nREPLACE(REPLACE(REPLACE(title,'\\n',''), '\\t',''),';',''),\nREPLACE(REPLACE(REPLACE(sub_title,'\\n',''), '\\t',''),';',''),\nREPLACE(rewards,\";\", \"\"),\nusd_currently_raised\nFROM training_data\nWHERE state = \"successful\" OR state = \"failed\"\nORDER BY launch_date DESC \nLIMIT 23200;\n\n\n- length of title : 79 (That is our baseline for 1)\n- length of sub_title : 249 (That is our baseline for 1)\n- length of story : 57275 (That is our baseline for 1)\n- size of funding goal: 172,266 (That is our baseline for 1 which is the average funding goal,\ntimes 2 standard deviations to the left)\n- size of num_supporters: 998 (That is our baseline for 1)\n- size of num_updates: 93 (That is our baseline for 1)\n- size of num_comments: 998 (That is our baseline for 1)\n- size of nun_fb_shares: 235648 (That is our baseline for 1)\n- size of currently_raised_max value = SQL statement dump\n\nMAX LAUNCH DATE UNIX TIME = 1493817026\nMAX END DATE UNIX TIME = 1496534975\n\nBaseline for 1 with Duration of Campaign = 2717949 // 31.45774 Days\n\nInput Layer (Last 4 nodes)\n\n-\tUS_Currently_Raised\n-\tState of Success / Failure\n-\tFB Shares\n-\t# of Supporters\n\n\"\"\"\nimport time\nimport datetime\nimport csv\nimport json\nfrom textblob import TextBlob\n\ntime_start = time.time()\n\n\ndef data_parser():\n location_country_dict = {\n 'AE': 0,\n 'AF': 0,\n 'AG': 0,\n 'AM': 0,\n 'AQ': 0,\n 'AR': 0,\n 'AT': 0,\n 'AU': 0,\n 'BA': 0,\n 'BB': 0,\n 'BE': 0,\n 'BF': 0,\n 'BG': 0,\n 'BO': 0,\n 'BQ': 0,\n 'BR': 0,\n 'BS': 0,\n 'BW': 0,\n 'BY': 0,\n 'BZ': 0,\n 'CA': 0,\n 'CH': 0,\n 'CL': 0,\n 'CM': 0,\n 'CN': 0,\n 'CO': 0,\n 'CR': 0,\n 'CU': 0,\n 'CW': 0,\n 'CY': 0,\n 'CZ': 0,\n 'DE': 0,\n 'DJ': 0,\n 'DK': 0,\n 'DM': 0,\n 'DO': 0,\n 'EC': 0,\n 'EE': 0,\n 'EG': 0,\n 'ES': 0,\n 'ET': 0,\n 'FI': 0,\n 'FM': 0,\n 'FR': 0,\n 'GB': 0,\n 'GE': 0,\n 'GH': 0,\n 'GL': 0,\n 'GP': 0,\n 'GR': 0,\n 'GT': 0,\n 'GU': 0,\n 'GY': 0,\n 'HK': 0,\n 'HN': 0,\n 'HR': 0,\n 'HT': 0,\n 'HU': 0,\n 'ID': 0,\n 'IE': 0,\n 'IL': 0,\n 'IN': 0,\n 'IQ': 0,\n 'IR': 0,\n 'IS': 0,\n 'IT': 0,\n 'JM': 0,\n 'JP': 0,\n 'KE': 0,\n 'KG': 0,\n 'KH': 0,\n 'KR': 0,\n 'KW': 0,\n 'KZ': 0,\n 'LA': 0,\n 'LB': 0,\n 'LI': 0,\n 'LK': 0,\n 'LT': 0,\n 'LU': 0,\n 'LV': 0,\n 'MA': 0,\n 'MC': 0,\n 'MD': 0,\n 'ME': 0,\n 'MG': 0,\n 'MK': 0,\n 'MM': 0,\n 'MN': 0,\n 'MT': 0,\n 'MX': 0,\n 'MY': 0,\n 'MZ': 0,\n 'NA': 0,\n 'NG': 0,\n 'NI': 0,\n 'NL': 0,\n 'NO': 0,\n 'NP': 0,\n 'NZ': 0,\n 'PA': 0,\n 'PE': 0,\n 'PG': 0,\n 'PH': 0,\n 'PK': 0,\n 'PL': 0,\n 'PR': 0,\n 'PT': 0,\n 'PY': 0,\n 'RO': 0,\n 'RS': 0,\n 'RU': 0,\n 'RW': 0,\n 'SE': 0,\n 'SG': 0,\n 'SI': 0,\n 'SJ': 0,\n 'SK': 0,\n 'SL': 0,\n 'SN': 0,\n 'SO': 0,\n 'SR': 0,\n 'SV': 0,\n 'TH': 0,\n 'TN': 0,\n 'TO': 0,\n 'TR': 0,\n 'TT': 0,\n 'TW': 0,\n 'TZ': 0,\n 'UA': 0,\n 'UG': 0,\n 'US': 0,\n 'UY': 0,\n 'VC': 0,\n 'VE': 0,\n 'VI': 0,\n 'VN': 0,\n 'YE': 0,\n 'ZA': 0,\n 'ZM': 0,\n 'ZW': 0\n\n }\n\n category_dict = {\n 'Horror': 0,\n 'Comedy': 0,\n 'Apps': 0,\n 'Product Design': 0,\n 'Mixed Media': 0,\n 'Comic Books': 0,\n 'Tabletop Games': 0,\n 'Zines': 0,\n 'Music Videos': 0,\n 'Rock': 0,\n 'Radio & Podcasts': 0,\n 'Immersive': 0,\n 'Playing Cards': 0,\n 'Shorts': 0,\n 'Crafts': 0,\n 'Fine Art': 0,\n 'Drinks': 0,\n 'Festivals': 0,\n 'Documentary': 0,\n 'Video Games': 0,\n 'Children's Books': 0,\n 'Country & Folk': 0,\n 'Gadgets': 0,\n 'Music': 0,\n 'Experimental': 0,\n 'Technology': 0,\n 'Footwear': 0,\n 'Art': 0,\n 'Print': 0,\n 'Theater': 0,\n 'Ready-to-wear': 0,\n 'Photography': 0,\n 'Webseries': 0,\n 'Restaurants': 0,\n 'Web': 0,\n 'Design': 0,\n 'Games': 0,\n 'Fashion': 0,\n 'Nonfiction': 0,\n 'Fiction': 0,\n 'Live Games': 0,\n 'Indie Rock': 0,\n '3D Printing': 0,\n 'Software': 0,\n 'Apparel': 0,\n 'Farms': 0,\n 'Public Art': 0,\n 'Woodworking': 0,\n 'Hardware': 0,\n 'Photobooks': 0,\n 'Illustration': 0,\n 'Publishing': 0,\n 'Calendars': 0,\n 'Film & Video': 0,\n 'Gaming Hardware': 0,\n 'Flight': 0,\n 'Graphic Novels': 0,\n 'Architecture': 0,\n 'Spaces': 0,\n 'Metal': 0,\n 'Food': 0,\n 'Cookbooks': 0,\n 'Hip-Hop': 0,\n 'Art Books': 0,\n 'Thrillers': 0,\n 'People': 0,\n 'Pop': 0,\n 'Anthologies': 0,\n 'Camera Equipment': 0,\n 'Science Fiction': 0,\n 'Narrative Film': 0,\n 'Television': 0,\n 'Accessories': 0,\n 'World Music': 0,\n 'Photo': 0,\n 'Animation': 0,\n 'Painting': 0,\n 'Comics': 0,\n 'Webcomics': 0,\n 'Space Exploration': 0,\n 'Installations': 0,\n 'Graphic Design': 0,\n 'Mobile Games': 0,\n 'Faith': 0,\n 'Drama': 0,\n 'DIY': 0,\n 'Young Adult': 0,\n 'Stationery': 0,\n 'Sound': 0,\n 'Performances': 0,\n 'Small Batch': 0,\n 'Electronic Music': 0,\n 'Civic Design': 0,\n 'Punk': 0,\n 'Jazz': 0,\n 'Conceptual Art': 0,\n 'Audio': 0,\n 'Academic': 0,\n 'Ceramics': 0,\n 'Musical': 0,\n 'Dance': 0,\n 'Classical Music': 0,\n 'Fabrication Tools': 0,\n 'Interactive Design': 0,\n 'Places': 0,\n 'Plays': 0,\n 'R&B': 0,\n 'Family': 0,\n 'Jewelry': 0,\n 'Sculpture': 0,\n 'Wearables': 0,\n 'Candles': 0,\n 'DIY Electronics': 0,\n 'Performance Art': 0,\n 'Video': 0,\n 'Printing': 0,\n 'Quilts': 0,\n 'Food Trucks': 0,\n 'Journalism': 0,\n 'Events': 0,\n 'Literary Journals': 0,\n 'Typography': 0,\n 'Childrenswear': 0,\n 'Blues': 0,\n 'Translations': 0,\n 'Fantasy': 0,\n 'Periodicals': 0,\n 'Poetry': 0,\n 'Couture': 0,\n 'Makerspaces': 0,\n 'Vegan': 0,\n 'Pet Fashion': 0,\n 'Workshops': 0,\n 'Action': 0,\n 'Textiles': 0,\n 'Crochet': 0,\n 'Romance': 0,\n 'Robots': 0,\n 'Community Gardens': 0,\n 'Digital Art': 0,\n 'Puzzles': 0,\n 'Nature': 0,\n 'Pottery': 0,\n 'Animals': 0,\n 'Kids': 0,\n 'Movie Theaters': 0,\n 'Embroidery': 0,\n 'Latin': 0,\n 'Farmer's Markets': 0,\n 'Glass': 0,\n 'Bacon': 0,\n 'Video Art': 0,\n 'Weaving': 0,\n 'Knitting': 0,\n 'Residencies': 0,\n 'Taxidermy': 0,\n 'Letterpress': 0,\n 'Literary Spaces': 0,\n 'Chiptune': 0,\n\n }\n\n location_type_dict = {\n 'Town': 0,\n 'County': 0,\n 'Suburb': 0,\n 'Zip': 0,\n 'LocalAdmin': 0,\n 'Island': 0,\n 'Country': 0,\n 'Miscellaneous': 0,\n 'Estate': 0\n\n }\n\n category_slug_dict = {\n\n 'art': 0,\n 'art/ceramics': 0,\n 'art/conceptual art': 0,\n 'art/digital art': 0,\n 'art/illustration': 0,\n 'art/installations': 0,\n 'art/mixed media': 0,\n 'art/painting': 0,\n 'art/performance art': 0,\n 'art/public art': 0,\n 'art/sculpture': 0,\n 'art/textiles': 0,\n 'art/video art': 0,\n 'comics': 0,\n 'comics/anthologies': 0,\n 'comics/comic books': 0,\n 'comics/events': 0,\n 'comics/graphic novels': 0,\n 'comics/webcomics': 0,\n 'crafts': 0,\n 'crafts/candles': 0,\n 'crafts/crochet': 0,\n 'crafts/diy': 0,\n 'crafts/embroidery': 0,\n 'crafts/glass': 0,\n 'crafts/knitting': 0,\n 'crafts/pottery': 0,\n 'crafts/printing': 0,\n 'crafts/quilts': 0,\n 'crafts/stationery': 0,\n 'crafts/taxidermy': 0,\n 'crafts/weaving': 0,\n 'crafts/woodworking': 0,\n 'dance': 0,\n 'dance/performances': 0,\n 'dance/residencies': 0,\n 'dance/spaces': 0,\n 'dance/workshops': 0,\n 'design': 0,\n 'design/architecture': 0,\n 'design/civic design': 0,\n 'design/graphic design': 0,\n 'design/interactive design': 0,\n 'design/product design': 0,\n 'design/typography': 0,\n 'fashion': 0,\n 'fashion/accessories': 0,\n 'fashion/apparel': 0,\n 'fashion/childrenswear': 0,\n 'fashion/couture': 0,\n 'fashion/footwear': 0,\n 'fashion/jewelry': 0,\n 'fashion/pet fashion': 0,\n 'fashion/ready-to-wear': 0,\n 'film & video': 0,\n 'film & video/action': 0,\n 'film & video/animation': 0,\n 'film & video/comedy': 0,\n 'film & video/documentary': 0,\n 'film & video/drama': 0,\n 'film & video/experimental': 0,\n 'film & video/family': 0,\n 'film & video/fantasy': 0,\n 'film & video/festivals': 0,\n 'film & video/horror': 0,\n 'film & video/movie theaters': 0,\n 'film & video/music videos': 0,\n 'film & video/narrative film': 0,\n 'film & video/romance': 0,\n 'film & video/science fiction': 0,\n 'film & video/shorts': 0,\n 'film & video/television': 0,\n 'film & video/thrillers': 0,\n 'film & video/webseries': 0,\n 'food': 0,\n 'food/bacon': 0,\n 'food/community gardens': 0,\n 'food/cookbooks': 0,\n 'food/drinks': 0,\n 'food/events': 0,\n 'food/farmer's markets': 0,\n 'food/farms': 0,\n 'food/food trucks': 0,\n 'food/restaurants': 0,\n 'food/small batch': 0,\n 'food/spaces': 0,\n 'food/vegan': 0,\n 'games': 0,\n 'games/gaming hardware': 0,\n 'games/live games': 0,\n 'games/mobile games': 0,\n 'games/playing cards': 0,\n 'games/puzzles': 0,\n 'games/tabletop games': 0,\n 'games/video games': 0,\n 'journalism': 0,\n 'journalism/audio': 0,\n 'journalism/photo': 0,\n 'journalism/print': 0,\n 'journalism/video': 0,\n 'journalism/web': 0,\n 'music': 0,\n 'music/blues': 0,\n 'music/chiptune': 0,\n 'music/classical music': 0,\n 'music/comedy': 0,\n 'music/country & folk': 0,\n 'music/electronic music': 0,\n 'music/faith': 0,\n 'music/hip-hop': 0,\n 'music/indie rock': 0,\n 'music/jazz': 0,\n 'music/kids': 0,\n 'music/latin': 0,\n 'music/metal': 0,\n 'music/pop': 0,\n 'music/punk': 0,\n 'music/r&b': 0,\n 'music/rock': 0,\n 'music/world music': 0,\n 'photography': 0,\n 'photography/animals': 0,\n 'photography/fine art': 0,\n 'photography/nature': 0,\n 'photography/people': 0,\n 'photography/photobooks': 0,\n 'photography/places': 0,\n 'publishing': 0,\n 'publishing/academic': 0,\n 'publishing/anthologies': 0,\n 'publishing/art books': 0,\n 'publishing/calendars': 0,\n 'publishing/children's books': 0,\n 'publishing/comedy': 0,\n 'publishing/fiction': 0,\n 'publishing/letterpress': 0,\n 'publishing/literary journals': 0,\n 'publishing/literary spaces': 0,\n 'publishing/nonfiction': 0,\n 'publishing/periodicals': 0,\n 'publishing/poetry': 0,\n 'publishing/radio & podcasts': 0,\n 'publishing/translations': 0,\n 'publishing/young adult': 0,\n 'publishing/zines': 0,\n 'technology': 0,\n 'technology/3d printing': 0,\n 'technology/apps': 0,\n 'technology/camera equipment': 0,\n 'technology/diy electronics': 0,\n 'technology/fabrication tools': 0,\n 'technology/flight': 0,\n 'technology/gadgets': 0,\n 'technology/hardware': 0,\n 'technology/makerspaces': 0,\n 'technology/robots': 0,\n 'technology/software': 0,\n 'technology/sound': 0,\n 'technology/space exploration': 0,\n 'technology/wearables': 0,\n 'technology/web': 0,\n 'theater': 0,\n 'theater/comedy': 0,\n 'theater/experimental': 0,\n 'theater/festivals': 0,\n 'theater/immersive': 0,\n 'theater/musical': 0,\n 'theater/plays': 0,\n 'theater/spaces': 0\n }\n\n currency_dict = {\n 'AUD': 0,\n 'CAD': 0,\n 'CHF': 0,\n 'DKK': 0,\n 'EUR': 0,\n 'GBP': 0,\n 'HKD': 0,\n 'MXN': 0,\n 'NOK': 0,\n 'NZD': 0,\n 'SEK': 0,\n 'SGD': 0,\n 'USD': 0\n }\n\n baseline_title = 79\n baseline_sub_title = 249\n baseline_of_story = 57275\n baseline_of_funding_goal = 172266\n baseline_of_num_supporters = 998\n baseline_of_num_updates = 93\n baseline_of_num_comments = 998\n baseline_of_fb_shares = 235648\n baseline_of_campaign_duration = 2717949\n baseline_of_currently_raised = 12393140\n baseline_of_max_rewards = 200000\n baseline_of_max_num_rewards = 68\n malformed_json = []\n rewards = []\n\n with open(\"training_data.csv\", \"r\", encoding=\"utf8\")as rfh, open(\"machine_learning_data.csv\", \"w+\",\n encoding=\"utf8\") as wfh:\n\n reader = csv.reader(rfh, delimiter=\"~\")\n writer = csv.writer(wfh, delimiter=\",\", quotechar='\"', quoting=csv.QUOTE_NONE, escapechar=\" \")\n\n for cols in reader:\n\n\n url = ()\n image_url = ()\n title = ()\n location_country = ()\n location_type = ()\n sub_title = ()\n video_url = ()\n category = ()\n category_slug = ()\n currency = ()\n funding_goal = ()\n currently_raised = ()\n campaign_state = ()\n num_supporters = ()\n duration_of_campaign = ()\n num_updates = ()\n num_comments = ()\n length_story = ()\n num_fb_shares = ()\n story_sentiment = 0\n title_sentiment = 0\n sub_title_sentiment = 0\n num_of_rewards = ()\n len_of_rewards = ()\n avg_rewards = 0\n usd_funding_raised = 0\n\n if cols[0] != \"\" and cols[0] != \"NULL\":\n url = 1\n else:\n url = 0\n\n if cols[1] != \"\" and cols[1] != \"NULL\":\n image_url = 1\n else:\n image_url = 0\n\n if len(cols[2]) > 0 and cols[2] != \"NULL\":\n title = (int(cols[2]) / int(baseline_title))\n else:\n title = 0\n\n for k in location_country_dict:\n if k == cols[3]:\n location_country_dict[cols[3]] = 1\n for k, v in location_country_dict.items():\n location_country = location_country + (v,)\n\n for k in location_type_dict:\n if k == cols[4]:\n location_type_dict[cols[4]] = 1\n for k, v in location_type_dict.items():\n location_type = location_type + (v,)\n\n if len(cols[5]) > 0 and cols[5] != \"NULL\":\n sub_title = (int(cols[5]) / int(baseline_sub_title))\n\n else:\n sub_title = 0\n\n if cols[6] != \"\" and cols[6] != \"NULL\":\n video_url = 1\n\n elif cols[6] == \"NULL\":\n video_url = 0\n\n for k in category_dict:\n if k == cols[7]:\n category_dict[cols[7]] = 1\n for k, v in category_dict.items():\n category = category + (v,)\n\n for k in category_slug_dict:\n if k == cols[8]:\n category_slug_dict[cols[8]] = 1\n for k, v in category_slug_dict.items():\n category_slug = category_slug + (v,)\n\n for k in currency_dict:\n if k == cols[9]:\n currency_dict[cols[9]] = 1\n for k, v in currency_dict.items():\n currency = currency + (v,)\n\n if len(cols[10]) > 0 and cols[10] != \"NULL\":\n funding_goal = (int(cols[10]) / int(baseline_of_funding_goal))\n\n if cols[11] == str(\"successful\").lower() and cols[11] != \"NULL\":\n campaign_state = (1)\n\n else:\n campaign_state = (0)\n\n if cols[12] != \"\" and cols[13] != \"\" and cols[12] != \"NULL\" and cols[13] != \"NULL\":\n start_time = time.mktime(\n datetime.datetime.strptime(str(cols[13]), '%Y-%m-%d %H:%M:%S').timetuple())\n end_time = time.mktime(datetime.datetime.strptime(str(cols[12]), '%Y-%m-%d %H:%M:%S').timetuple())\n\n duration_of_campaign = (int(end_time - start_time) / int(baseline_of_campaign_duration))\n\n if int(cols[14]) > 0 and cols[14] != \"NULL\":\n num_supporters = (int(cols[14]))\n else:\n num_supporters = 0\n\n if int(cols[15]) >= 0 and cols[15] != \"NULL\":\n num_updates = (int(cols[15]) / baseline_of_num_updates)\n else:\n num_updates = 0\n\n if int(cols[16]) > 0 and cols[16] != \"NULL\":\n num_comments = (int(cols[16]) / baseline_of_num_comments)\n else:\n num_comments = 0\n\n if len(cols[17]) > 0 and cols[17] != \"NULL\":\n length_story = (len(cols[17]) / baseline_of_story)\n else:\n length_story = 0\n\n if int(cols[18]) >= 0 and cols[18] != \"NULL\":\n num_fb_shares = int(cols[18])\n else:\n num_fb_shares = 0\n\n if len(cols[19]) > 0:\n story_sentiment = TextBlob(str(cols[19]))\n\n else:\n story_sentiment = 0\n\n if len(cols[20]) > 0 or len(cols[20]):\n title_sentiment = TextBlob(str(cols[20]))\n\n else:\n title_sentiment = 0\n\n if len(cols[21]) > 0:\n sub_title_sentiment = TextBlob(str(cols[21]))\n\n else:\n sub_title_sentiment = 0\n\n if len(cols[22]) > 0:\n data = str(cols[22])\n data = data[:2] + '\"' + data[2:]\n if data.endswith('\"'):\n data = data[:-1]\n\n try:\n json_data = json.loads(str(data))\n\n for iter in json_data:\n rewards.append(iter['minimum'])\n len_of_rewards = len_of_rewards + (len(json_data),)\n\n num_of_rewards = int(len(len_of_rewards) / baseline_of_max_num_rewards)\n avg_rewards = int((sum(rewards) / len(rewards)) / baseline_of_max_rewards)\n\n except json.decoder.JSONDecodeError as e:\n malformed_json.append(e.lineno)\n pass\n\n\n\n else:\n num_of_rewards = 0\n\n if cols[23] != 0 or cols[23] != \"NULL\":\n print(cols[23])\n usd_funding_raised = float(cols[23])\n\n writer.writerow([\n float(url), float(image_url), float(title), ','.join(map(str, location_country)),\n ','.join(map(str, location_type)), float(sub_title), float(video_url),\n ','.join(map(str, category)), ','.join(map(str, category_slug)),\n ','.join(map(str, currency)), float(funding_goal), float(duration_of_campaign),\n float(num_updates), float(num_comments), float(length_story), float(story_sentiment.subjectivity),\n float(title_sentiment.subjectivity), float(sub_title_sentiment.subjectivity), float(\n ((story_sentiment.polarity + 1) / 2)), float(((title_sentiment.polarity + 1) / 2)), float(\n ((sub_title_sentiment.polarity + 1) / 2)), float(num_of_rewards), float(\n avg_rewards), float(campaign_state), float(num_fb_shares), float(\n num_supporters), float(usd_funding_raised)\n ])\n\n url = ()\n image_url = ()\n title = ()\n location_country = ()\n location_type = ()\n sub_title = ()\n video_url = ()\n category = ()\n category_slug = ()\n currency = ()\n funding_goal = ()\n currently_raised = ()\n campaign_state = ()\n num_supporters = ()\n duration_of_campaign = ()\n num_updates = ()\n num_comments = ()\n length_story = ()\n num_fb_shares = ()\n story_sentiment = 0\n title_sentiment = 0\n sub_title_sentiment = 0\n num_of_rewards = ()\n avg_rewards = 0\n usd_funding_raised = 0\n\n for k in category_dict:\n category_dict[k] = 0\n\n for k in location_country_dict:\n location_country_dict[k] = 0\n\n for k in location_type_dict:\n location_type_dict[k] = 0\n\n for k in category_slug_dict:\n category_slug_dict[k] = 0\n\n for k in currency_dict:\n currency_dict[k] = 0\n\n\ndata_parser()\n\ntime_end = time.time()\nprint(\"Done\")\nprint(\"Processing Time {0}\".format(time_end - time_start))\n","sub_path":"data_parser/kickstarter_data_parser.py","file_name":"kickstarter_data_parser.py","file_ext":"py","file_size_in_byte":22683,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"406160659","text":"# Copyright 2008-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.\n\n# Permission is hereby granted, free of charge, to any person obtaining a copy of this\n# software and associated documentation files (the \"Software\"), to deal in the Software\n# without restriction, including without limitation the rights to use, copy, modify,\n# merge, publish, distribute, sublicense, and/or sell copies of the Software, and to\n# permit persons to whom the Software is furnished to do so.\n\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,\n# INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A\n# PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT\n# HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION\n# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE\n# SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n\nfrom __future__ import print_function\nimport sys\nimport requests\nimport json\nimport yaml\nimport os\nimport datetime\n\n\ndef status(cloud_endure, project_id, launchtype, dryrun):\n config = cloud_endure.config\n HOST = cloud_endure.host\n endpoint = cloud_endure.endpoint\n headers = cloud_endure.headers\n session = cloud_endure.session\n machine_status = 0\n machine_list = json.loads(\n requests.get(HOST + endpoint.format('projects/{}/machines').format(project_id), headers=headers,\n cookies=session).text)[\"items\"]\n cloudEndure_machines = {machine['sourceProperties']['name']: machine for machine in machine_list}\n for config_machine in config['Machines'].keys():\n machine_exist = False\n if config_machine in cloudEndure_machines.keys():\n machine_exist = True\n machine = cloudEndure_machines[config_machine]\n # Check replication status\n if 'lastConsistencyDateTime' not in machine['replicationInfo']:\n print(\"ERROR: Machine: \" + machine['sourceProperties'][\n 'name'] + \" replication in progress, please wait for a few minutes....\")\n sys.exit(1)\n else:\n # check replication lag\n a = int(machine['replicationInfo']['lastConsistencyDateTime'][11:13])\n b = int(machine['replicationInfo']['lastConsistencyDateTime'][14:16])\n x = int(datetime.datetime.utcnow().isoformat()[11:13])\n y = int(datetime.datetime.utcnow().isoformat()[14:16])\n result = (x - a) * 60 + (y - b)\n if result > 180:\n print(\"ERROR: Machine: \" + machine['sourceProperties'][\n 'name'] + \" replication lag is more than 180 minutes....\")\n print(\"- Current Replication lag for \" + machine['sourceProperties']['name'] + \" is: \" + str(\n result) + \" minutes....\")\n sys.exit(6)\n else:\n # Check dryrun flag and skip the rest of checks\n if dryrun:\n machine_status += 1\n else:\n # Check if the target machine has been tested already\n if launchtype == \"test\":\n if 'lastTestLaunchDateTime' not in machine[\"lifeCycle\"] and 'lastCutoverDateTime' not in \\\n machine[\"lifeCycle\"]:\n machine_status += 1\n else:\n print(\"ERROR: Machine: \" + machine['sourceProperties'][\n 'name'] + \" has been tested already....\")\n sys.exit(2)\n # Check if the target machine has been migrated to PROD already\n elif launchtype == \"cutover\":\n if 'lastTestLaunchDateTime' in machine[\"lifeCycle\"]:\n if 'lastCutoverDateTime' not in machine[\"lifeCycle\"]:\n machine_status += 1\n else:\n print(\"ERROR: Machine: \" + machine['sourceProperties'][\n 'name'] + \" has been migrated already....\")\n sys.exit(3)\n else:\n print(\"ERROR: Machine: \" + machine['sourceProperties'][\n 'name'] + \" has not been tested....\")\n sys.exit(4)\n elif config_machine.lower() in map(lambda x: x.lower(), cloudEndure_machines.keys()):\n print(\"ERROR: Machine Named \" + config_machine +\n \" is written with different case in CloudEndure, please verify...\")\n sys.exit(7)\n else:\n print(\"ERROR: Machine: \" + config_machine + \" does not exist....\")\n sys.exit(7)\n\n if machine_status == len(config[\"Machines\"].keys()):\n print(\"All Machines in the config file are ready....\")\n else:\n print(\"ERROR: some machines in the config file are not ready....\")\n sys.exit(5)\n","sub_path":"CheckMachine.py","file_name":"CheckMachine.py","file_ext":"py","file_size_in_byte":5234,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"560747618","text":"# Written: 08-Dec-2019\n# https://edabit.com/challenge/2yHQwkecEHZBfHcmN\n\ndef progress_days(runs):\n progress = 0\n for days in range(len(runs)-1):\n if runs[days] < runs[days+1]:\n progress += 1\n return progress\n # return len([days for days in range(len(runs)-1) if runs[days] < runs[days+1]])","sub_path":"Python/Is Johnny Making Progress/code.py","file_name":"code.py","file_ext":"py","file_size_in_byte":319,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"638619130","text":"#-*- coding: utf-8 -*-\n#@File : test_login.py\n#@Time : 2021/5/28 20:24\n#@Author : xintian\n#@Email : 1730588479@qq.com\n#@Software: PyCharm\n#Date:2021/5/28\nimport allure\nimport os\nimport pytest\n\nfrom libs.login import Login\nfrom tools.excelControl import get_excel_data,get_excel_data2\nfrom tools.logBasic import logger\n\nlog = logger()\nimport traceback\n#定义测试类\n@allure.epic(\"点餐系统\")#项目级别\n@allure.feature(\"登录模块\")#模块级别\n@pytest.mark.Login#mark 标签\nclass TestLogin:\n #写测试方法\n #数据驱动 ----[(1,2),(3,4)]\n # @pytest.mark.parametrize('caseTitle,inBody,expData',get_excel_data('../data/testCaseFile_V1.5.xls',\"登录模块\",\"Login\",\n # \"标题\",\"请求参数\",\"响应预期结果\"))\n @pytest.mark.parametrize('caseTitle,inBody,expData',\n get_excel_data2('../data/testCaseFile_V1.5.xls', \"登录模块\", \"Login\"))\n #@pytest.mark.parametrize('caseTitle,inBody,expData',get_yaml_caseData(projectPath+'/data/data.yaml'))\n @allure.story(\"登录接口\")#接口级别\n @allure.title(\"{caseTitle}\")#用例级别\n @pytest.mark.login # mark 标签\n def test_login(self,caseTitle,inBody,expData):\n #allure 增加selenium截图的操作\n allure.attach.file('../data/123.png','登录的截图',\n attachment_type=allure.attachment_type.PNG)\n\n print('---登录接口正在运行---')\n try:\n res = Login().login(inBody) # 1- 调用登录的接口函数\n assert res['msg'] == expData['msg']#断言:预期与实际相比较,一致返回真,不一致-假\n except Exception as err:#异常处理\n log.error(traceback.format_exc())#具体的报错信息\n raise err# 需要抛出异常给pytest--报告需要体现!\n\n \"\"\"\n pytest在控制台输出的信息一些标识:\n . 表示该用例执行成功!\n F 表示该用例执行失败!\n E 语法错误\n \"\"\"\n\n\n\nif __name__ == '__main__':\n #--clean-alluredir 清除数据!\n pytest.main(['test_login.py','-s','--alluredir','../report/tmp'])# -s 打印print信息\n os.system('allure serve ../report/tmp')\n print(\"pass\")\n \"\"\"\n 运行一个报告需要什么?需要报告的源数据\n 原理:\n 1- 使用pytest框架运行后产生测试结果数据\n - 需要把数据存放一个路径\n --alluredir ../report/tmp\n 2- 使用allure工具去解析这个源数据--展示出来效果\n os.system(\"cmd命令行\")\n 3- 这个allure serve 是一个服务,\n 4- 最好使用火狐浏览器,设置默认浏览器\n \"\"\"\n\n\n\n","sub_path":"waimaiProject/test_case/test_login.py","file_name":"test_login.py","file_ext":"py","file_size_in_byte":2708,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"339633669","text":"from fetchai.ledger.api import LedgerApi\nfrom fetchai.ledger.contract import SmartContract\nfrom fetchai.ledger.crypto import Entity, Address\nimport sys\nimport time\n\ndef main(source):\n # Create keypair for the contract owner\n entity = Entity()\n address = Address(entity)\n \n # Setting API up\n api = LedgerApi('127.0.0.1', 8100)\n\n # Need funds to deploy contract\n api.sync(api.tokens.wealth(entity, 5000000))\n\n # Create contract\n contract = SmartContract(source)\n\n # Deploy contract\n api.sync(api.contracts.create(entity, contract, 2456766))\n\n # Printing balance of the creating address\n print(contract.query(api, 'balanceOf', owner = address)) \n\n # Getting the 9'th token id.\n token_id = contract.query(api, 'getTokenId', number = 9) \n\n # Testing\n contract.query(api, 'isEqual', number = 9, expected = token_id) \n\n # Locating the owner of a token\n print(\"Finding the owner of \", token_id) \n print(contract.query(api, 'ownerOf', token_id = token_id))\n\nif __name__ == '__main__': \n # Loading contract\n if len(sys.argv) != 2:\n print(\"Usage: \", sys.argv[0], \"[filename]\")\n exit(-1)\n\n with open(sys.argv[1], \"r\") as fb:\n source = fb.read()\n\n main(source)","sub_path":"Fet-2/submit_contract.py","file_name":"submit_contract.py","file_ext":"py","file_size_in_byte":1240,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"312826849","text":"# Flask params\nDEBUG = True\nTESTING = True\nSECRET_KEY = 'hy[>tW?A5WLYrn+~Ek&FW8<]NfPbvwpw-test'\nSESSION_COOKIE_SECURE = False\n\n# Web server bind\nWEBSERVER_DOMAIN = 'localhost:8888'\n\n# Celery\nCELERY_BACKEND = 'memory://'\nCELERY_BROKER = CELERY_BACKEND\n\n# SocketIO\nSOCKET_IO_REDIS_CONN = None\nSOCKET_IO_CHANNEL_NAME = 'socket_io_rpgcore_test'\n\n# SQLAlchemy\nSQLALCHEMY_DATABASE_URI = 'sqlite://'\nSQLALCHEMY_TRACK_MODIFICATIONS = False\nSQLALCHEMY_ECHO = False\nSQLALCHEMY_POOL_RECYCLE = 60 * 5 # 5 minutes\n\n# Sendgrid\nSENDGRID_API_KEY = None\nSENDGRID_FROM_ADDRESS = 'no-reply@adventurekit.app'\n","sub_path":"src/rpgcore/config/flask_test.py","file_name":"flask_test.py","file_ext":"py","file_size_in_byte":590,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"453808765","text":"# weather data\ndataset1_title = ['outlook', 'temperature', 'humidity', 'windy', 'play']\ndataset1 = {\n 'data': [\n ['sunny', 'hot', 'high', 'false', 'no'],\n ['sunny', 'hot', 'high', 'true', 'no'],\n ['overcast', 'hot', 'high', 'false', 'yes'],\n ['rainy', 'mild', 'high', 'false', 'yes'],\n ['rainy', 'cool', 'normal', 'false', 'yes'],\n ['rainy', 'cool', 'normal', 'true', 'no'],\n ['overcast', 'cool', 'normal', 'true', 'yes'],\n ['sunny', 'mild', 'high', 'false', 'no'],\n ['sunny', 'cool', 'normal', 'false', 'yes'],\n ['rainy', 'mild', 'normal', 'false', 'yes'],\n ['sunny', 'mild', 'normal', 'true', 'yes'],\n ['overcast', 'mild', 'high', 'true', 'yes'],\n ['overcast', 'hot', 'normal', 'false', 'yes'],\n ['rainy', 'mild', 'high', 'true', 'no'],\n ],\n 'title': ['outlook', 'temperature', 'humidity', 'windy', 'play'],\n}\n","sub_path":"data.py","file_name":"data.py","file_ext":"py","file_size_in_byte":919,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"414601681","text":"# !/usr/bin/env python2.7\n# -*- coding: utf-8 -*-\nimport argparse\nimport sys\nimport os\n\nfrom twisted.python import log\n\nfrom desertbot.bothandler import BotHandler\n\n\nparser = argparse.ArgumentParser(description=\"An IRC bot written in Python.\")\nparser.add_argument(\"-c\", \"--configs\", help=\"the config files to use for connections (required)\",\n type=str, nargs=\"+\", required=True)\nparser.add_argument(\"-l\", \"--logfile\",\n help=\"the file the debug log will be written to (default desertbot.log)\",\n type=str, default=\"desertbot.log\")\nparser.add_argument(\"-v\", \"--verbose\", help=\"log to console (default False)\", action=\"store_true\")\ncmdArgs = parser.parse_args()\n\nif __name__ == \"__main__\":\n # Create folders\n if not os.path.exists(os.path.join(\"config\")):\n os.makedirs(\"config\")\n\n # Open log file\n open(cmdArgs.logfile, \"a\").close()\n log.startLogging(open(cmdArgs.logfile, \"a\"), setStdout=False)\n if cmdArgs.verbose:\n log.startLogging(sys.stdout)\n\n botHandler = BotHandler(cmdArgs)\n","sub_path":"start.py","file_name":"start.py","file_ext":"py","file_size_in_byte":1070,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"467162014","text":"from Kernels.Kernel import KernelBase\nfrom sklearn.feature_extraction.text import HashingVectorizer\n\n\nclass BagOfWords(KernelBase):\n \"\"\"\n Implementation of a SKLearn kernel for Natural Language processing\n \"\"\"\n\n def __init__(self, filereader_instance):\n \"\"\"\n Constructor\n :param lambda_decay: lambda parameter for the algorithm\n :type lambda_decay: float\n :param subseq_length: maximal subsequence length\n :type subseq_length: int\n \"\"\"\n self.vec = None\n KernelBase.__init__(filereader_instance)\n\n def _my_kernel(self, data, n_features):\n \"\"\"\n\n :return:\n \"\"\"\n self.vec = HashingVectorizer(stop_words='english', non_negative=True,\n n_features=n_features)\n return self.vec.transform(data)\n\n","sub_path":"Kernels/BagOfWords.py","file_name":"BagOfWords.py","file_ext":"py","file_size_in_byte":837,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"490206397","text":"# Gregor will help us, can only do this after the abstract base class is defined\n# Example can find under\n#\n# cloudmesh-cloud/cloudmesh/compute/*,\n# cloudmesh-cloud/cloudmesh/vm/command,\n# cloudmesh-storage/cloudmesh/storage/*\nimport os\nimport json\n\nfrom cloudmesh.common.Printer import Printer\nfrom cloudmesh.volume.VolumeABC import VolumeABC\nfrom cloudmesh.common.util import banner\nfrom cloudmesh.common.Shell import Shell\nfrom cloudmesh.configuration.Config import Config\nfrom cloudmesh.mongo.DataBaseDecorator import DatabaseUpdate\nfrom cloudmesh.management.configuration.arguments import Arguments\nfrom cloudmesh.common.console import Console\nfrom cloudmesh.common.variables import Variables\n\n# class Provider(VolumeABC): # correct\nclass Provider(object): # broken\n # kind = \"multipass\"\n\n @staticmethod\n def get_kind():\n banner(\"get in def get_kind()\")\n kind = [\"multipass\",\n \"aws\",\n \"azure\",\n \"google\",\n \"openstack\",\n \"oracle\"]\n return kind\n\n @staticmethod\n def get_provider(kind):\n\n if kind == \"multipass\":\n from cloudmesh.volume.multipass.Provider import Provider as P\n\n elif kind == \"aws\":\n from cloudmesh.volume.aws.Provider import Provider as P\n\n elif kind == \"azure\":\n from cloudmesh.volume.azure.Provider import Provider as P\n\n elif kind == \"google\":\n from cloudmesh.volume.google.Provider import Provider as P\n\n elif kind == \"openstack\":\n from cloudmesh.volume.openstack.Provider import Provider as P\n\n elif kind == \"oracle\":\n from cloudmesh.volume.oracle.Provider import Provider as P\n\n else:\n Console.error(f\"Compute provider {kind} not supported\")\n\n raise ValueError(f\"Compute provider {kind} not supported\")\n\n return P\n\n # noinspection PyPep8Naming\n\n def Print(self, data, kind=None, output=\"table\"):\n\n if kind is None and len(data) > 0:\n kind = data[0][\"cm\"][\"kind\"]\n\n if output == \"table\":\n\n order = self.provider.output[kind]['order']\n header = self.provider.output[kind]['header']\n\n if 'humanize' in self.provider.output[kind]:\n humanize = self.provider.output[kind]['humanize']\n else:\n humanize = None\n\n print(Printer.flatwrite(data,\n sort_keys=[\"name\"],\n order=order,\n header=header,\n output=output,\n humanize=humanize)\n )\n else:\n print(Printer.write(data, output=output))\n\n def __init__(self,\n name=None,\n configuration=\"~/.cloudmesh/cloudmesh.yaml\"):\n try:\n conf = Config(configuration)[\"cloudmesh\"]\n self.spec = conf[\"volume\"][name]\n self.cloud = name\n # print('self.cloud = ', self.cloud)\n self.kind = self.spec[\"cm\"][\"kind\"]\n super().__init__()\n\n except:\n Console.error(f\"provider {name} not found in {configuration}\")\n raise ValueError(f\"provider {name} not found in {configuration}\")\n\n P = None\n\n if self.kind in [\"multipass\",\n \"aws\",\n \"azure\",\n \"google\",\n \"openstack\",\n \"oracle\"]:\n\n P = Provider.get_provider(self.kind)\n\n if P is None:\n Console.error(f\"provider {name} not supported\")\n raise ValueError(f\"provider {name} not supported\")\n\n self.provider = P(self.cloud)\n\n @DatabaseUpdate()\n def create(self, **kwargs):\n try:\n data = self.provider.create(**kwargs)\n variables = Variables()\n variables[\"volume\"] = data[\"cm\"][\"name\"]\n except:\n raise ValueError(\"Volume could not be created\")\n return data\n\n @DatabaseUpdate()\n def delete(self, name=None):\n d = self.provider.delete(name)\n return d\n\n @DatabaseUpdate()\n def list(self, **kwargs):\n data = self.provider.list(**kwargs)\n return data\n\n def info(self, name=None):\n volumes = self.provider.list()\n for volume in volumes:\n if volume[\"cm\"][\"name\"] == name:\n return volume\n return None\n\n @staticmethod\n def search(self, name=None):\n raise NotImplementedError\n\n #\n # BUG: two different definitiosn of mount\n #\n # def mount(self, path=None, name=None):\n # self.provider.mount(path, name)\n\n @DatabaseUpdate()\n def attach(self, NAME=None, vm=None):\n\n \"\"\"\n Attatch volume to a vm\n\n :param NAME: volume name\n :param vm: vm name which the volume will be attached to\n :return: dict\n \"\"\"\n result = self.provider.attach(NAME, vm)\n return result\n\n @DatabaseUpdate()\n def detach(self, NAME=None):\n\n \"\"\"\n Detach a volume from vm\n\n :param NAME: name of volume to detach\n :return: str\n \"\"\"\n result = self.provider.detach(NAME)\n return result\n\n # BUG NO GENERAL DEFINITIONS OF MIGRATE\n # BUG THE PARAMETER NAMES ARE REALY NOT GOOD\n #\n def migrate(self,\n name=None,\n fvm=None,\n tvm=None,\n fregion=None,\n tregion=None,\n fservice=None,\n tservice=None,\n fcloud=None,\n tcloud=None,\n cloud=None,\n region=None,\n service=None):\n\n \"\"\"\n Migrate volume from one vm to another vm.\n\n :param name: name of volume\n :param fvm: name of vm where volume will be moved from\n :param tvm: name of vm where volume will be moved to\n :param fregion: the region where the volume will be moved from\n :param tregion: region where the volume will be moved to\n :param fservice: the service where the volume will be moved from\n :param tservice: the service where the volume will be moved to\n :param fcloud: the provider where the volume will be moved from\n :param tcloud: the provider where the volume will be moved to\n :param cloud: the provider where the volume will be moved within\n :param region: the region where the volume will be moved within\n :param service: the service where the volume will be moved within\n :return: dict\n \"\"\"\n\n raise NotImplementedError\n\n #\n # BUG NO GENERAL DEFINITION OF WHAT SYNC IS DOING\n # DEFINITION OF SYNC MAY BE WRONG\n # ARCHITECTURE DOCUMENT IS MISSING\n #\n def sync(self,\n volume_id=None,\n zone=None,\n cloud=None):\n \"\"\"\n sync contents of one volume to another volume\n\n :param volume_id: id of volume A\n :param zone: zone where new volume will be created\n :param cloud: the provider where volumes will be hosted\n :return: str\n \"\"\"\n raise NotImplementedError\n\n\n","sub_path":"cloudmesh/volume/Provider.py","file_name":"Provider.py","file_ext":"py","file_size_in_byte":7223,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"588067993","text":"# -*- coding: utf-8 -*-\n# flake8: noqa\n\n\"\"\"\n批量移动文件\n\nhttps://developer.qiniu.com/kodo/api/1250/batch\n\"\"\"\n\n\nfrom qiniu import build_batch_move, Auth, BucketManager\n\naccess_key = ''\n\nsecret_key = ''\n\n\nq = Auth(access_key, secret_key)\n\nbucket = BucketManager(q)\n\nsrc_bucket_name = ''\n\ntarget_bucket_name = ''\n\n# force为true时强制同名覆盖, 字典的键为原文件,值为目标文件\nops = build_batch_move(src_bucket_name,\n {'src_key1': 'target_key1',\n 'src_key2': 'target_key2'},\n target_bucket_name,\n force='true')\nret, info = bucket.batch(ops)\nprint(info)\n","sub_path":"examples/batch_move.py","file_name":"batch_move.py","file_ext":"py","file_size_in_byte":666,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"585407067","text":"from PyQt5.QtGui import QPainter, QColor\nfrom PyQt5.QtCore import Qt, QThread, pyqtSignal\nfrom PyQt5.QtWidgets import QWidget, QProgressDialog\n\nfrom raytracer import Color\nfrom raytracer import render_default_scene\n\n\nclass RenderingWidget(QWidget):\n def __init__(self):\n super().__init__()\n self.rendered_scene = None\n\n def on_render_required(self, settings):\n settings.update({\"width\": self.width()})\n settings.update({\"height\": self.height()})\n\n rendering_thread = RenderingThread(settings)\n rendering_thread.progress_update.connect(self.show_image)\n rendering_thread.start()\n\n self.rendering_progress = RenderingProgressBar()\n self.rendering_progress.exec()\n\n def paintEvent(self, QPaintEvent):\n painter = QPainter()\n painter.begin(self)\n\n for i in range(self.width()):\n for j in range(self.height()):\n if self.rendered_scene:\n color = self.rendered_scene[i + self.width() * j]\n painter.setPen(QColor(int(255 * color.r), int(255 * color.g), int(255 * color.b)))\n else:\n painter.setPen(Qt.lightGray)\n painter.drawPoint(i, self.height() - 1 - j)\n painter.end()\n\n def show_image(self, rendered_scene):\n self.rendering_progress.close()\n self.rendered_scene = rendered_scene\n self.repaint()\n\n\nclass RenderingProgressBar(QProgressDialog):\n def __init__(self, ):\n super().__init__()\n self.setMinimum(0)\n self.setMaximum(0)\n self.setValue(0)\n self.setModal(True)\n self.setFixedSize(350, 80)\n self.setCancelButton(None)\n self.setWindowTitle(\"Raytracer\")\n self.setLabelText(\"Rendering scene…\")\n\n\nclass RenderingThread(QThread):\n progress_update = pyqtSignal(object)\n\n def __init__(self, settings):\n super().__init__()\n self.settings = settings\n\n def run(self):\n rendered_scene = render_default_scene(\n self.settings[\"width\"],\n self.settings[\"height\"],\n self.settings[\"antialising\"],\n self.settings[\"distance\"]\n )\n self.progress_update.emit(rendered_scene)\n","sub_path":"raytracer_gui/rendering_widget.py","file_name":"rendering_widget.py","file_ext":"py","file_size_in_byte":2242,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"448060619","text":"# uncompyle6 version 3.7.4\n# Python bytecode 3.6 (3379)\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/artellapipe/libs/pyblish/validators/modeling/uvs/penetratinguvs.py\n# Compiled at: 2020-04-17 19:10:25\n# Size of source mod 2**32: 2015 bytes\n\"\"\"\nModule that contains penetrating uvs validation implementation\n\"\"\"\nfrom __future__ import print_function, division, absolute_import\n__author__ = 'Tomas Poveda'\n__license__ = 'MIT'\n__maintainer__ = 'Tomas Poveda'\n__email__ = 'tpovedatd@gmail.com'\nimport tpDcc as tp, pyblish.api\n\nclass ValidatePenetratingUVs(pyblish.api.InstancePlugin):\n __doc__ = '\\n Checks if a geometry node has its UVs penetrating or not\\n '\n label = 'UVs - Penetrating UVs'\n order = pyblish.api.ValidatorOrder\n hosts = ['maya']\n families = ['geometry']\n must_pass = True\n\n def process(self, instance):\n import maya.cmds as cmds\n node = instance.data.get('node', None)\n if not tp.Dcc.object_exists(node):\n raise AssertionError('No valid node found in current instance: {}'.format(instance))\n else:\n nodes_to_check = self._nodes_to_check(node)\n assert nodes_to_check, 'No Nodes to check found!'\n penetrating_uvs_found = list()\n for node in nodes_to_check:\n shape = tp.Dcc.list_shapes(node, full_path=True)\n convert_to_faces = cmds.ls(cmds.polyListComponentConversion(shape, tf=True), fl=True)\n overlapping = cmds.polyUVOverlap(convert_to_faces, oc=True)\n if overlapping:\n for obj in overlapping:\n penetrating_uvs_found.append(obj)\n\n assert not penetrating_uvs_found, 'Penetrating UVs found in following geometry nodes: {}'.format(penetrating_uvs_found)\n\n def _nodes_to_check(self, node):\n valid_nodes = list()\n nodes = tp.Dcc.list_children(node=node, all_hierarchy=True, full_path=True, children_type='transform')\n if not nodes:\n nodes = [\n node]\n else:\n nodes.append(node)\n for node in nodes:\n shapes = tp.Dcc.list_shapes(node=node, full_path=True)\n if not shapes:\n pass\n else:\n valid_nodes.append(node)\n\n return valid_nodes","sub_path":"pycfiles/artellapipe_libs_pyblish-0.0.4-py3.6/penetratinguvs.cpython-36.py","file_name":"penetratinguvs.cpython-36.py","file_ext":"py","file_size_in_byte":2392,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"429136861","text":"import numpy as np\nimport scipy as sc\nfrom scipy import stats\nimport matplotlib.pyplot as plt\nfrom matplotlib import pyplot\nimport pylab\nfrom mpl_toolkits.mplot3d import Axes3D\n\n#Calculation of pi:\ndef pi():\n a = 0\n for i in range(1000):\n x = np.random.uniform(-1,1)\n y = np.random.uniform(-1,1)\n if x**2 +y**2 <=1:\n a += 1\n return (a/1000)*4\n\nl2=[]\nfor i in range(1000):\n l2.append(pi())\nmu = np.mean(l2)\nsigma = np.std(l2)\n\nplt.hist(l2, bins=200, color = 'b', alpha = .5)\nplt.title(\"pi calculation\")\nplt.xlabel(\"The approximate value of pi\")\nplt.ylabel(\"Frequency\")\nplt.show()\n\n\n","sub_path":"PythonToyModel/Calculation_of_pi.py","file_name":"Calculation_of_pi.py","file_ext":"py","file_size_in_byte":625,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"574377064","text":"#! /usr/bin/python3\n\nimport re\nimport argparse\nfrom math import floor\nfrom card import *\nfrom unit_test import test_cards\n\nclass MarkdownEngine:\n def __init__(self, outfile=\"flashcards.pdf\", infile=\"in.md\", debug=False):\n # set file for output\n self.set_outfile(outfile)\n\n # set file for input\n self.set_infile(infile)\n\n # set debug mode\n self.debug = debug\n\n # create the initial pdf\n self.reset_pdf()\n\n # set cards array to empty\n self.cards = []\n\n # set the file for output\n # extensions are ignored and .pdf is assumed\n def set_outfile(self, outfile):\n name = re.search(\"^(.*)\\..*\", outfile)\n try:\n # append .pdf to filename\n self.outfile = name[1] + \".pdf\"\n except TypeError:\n # if no extension provided, add one\n self.outfile = outfile + \".pdf\"\n return self\n\n # set the file for input\n # extensions are ignored and .md is assumed\n def set_infile(self, infile):\n name = re.search(\"^(.*)\\..*\", infile)\n try:\n # append .md to filename\n self.infile = name[1] + \".md\"\n except TypeError:\n # if no extension provided, add one\n self.infile = infile + \".md\"\n return self\n\n # reset the PDF object\n def reset_pdf(self):\n # create PDF object\n self.pdf = Cards(\"L\", \"pt\", (360,576))\n self.pdf.set_font(\"Arial\", size=12)\n self.pdf.set_margins(40,30)\n return self\n\n # generate the flashcards\n def generate_flashcards(self, spaces):\n self.parse_cards(spaces)\n self.reset_pdf()\n\n for card in self.cards:\n self.pdf.add_card(card)\n\n self.pdf.export(self.outfile)\n\n def parse_cards(self, spaces):\n # reset cards\n self.cards = []\n\n # read in card from the file\n with open(self.infile) as f:\n # set first subsection to true\n first = True\n # set card to None for now\n card = None\n # initialize point number for numbered points\n point_number = 1\n for line in f:\n # attempt to find section, card, or line\n cardtitle = re.match(r\"^\\s*#\\s+(.*)\", line)\n subtitle = re.match(r\"^\\s*##\\s+(.*)\", line)\n subsubtitle = re.match(r\"^\\s*###\\s+(.*)\", line)\n subsubsubtitle = re.match(r\"^\\s*#####*\\s+(.*)\", line)\n bulleted = re.match(r\"^(\\s*)(?:[\\-\\*\\+])\\s+(.*)\", line)\n numbered = re.match(r\"^(\\s*)(?:\\d\\.|\\d\\)|\\(\\d\\))\\s+(.*)\", line)\n\n # try to add a card\n try:\n cardtitle[1]\n\n card = Card(title_str=cardtitle[1])\n self.cards.append(card)\n first = True\n\n continue\n except TypeError:\n pass\n\n # try to add a subtitle\n try:\n subtitle[1]\n\n content = Subtitle(text=subtitle[1], first=first)\n if card is not None:\n card.add_content(content)\n first = False\n\n continue\n except TypeError:\n pass\n\n # try to add a subsubtitle\n try:\n subsubtitle[1]\n\n content = Subsubtitle(text=subsubtitle[1])\n if card is not None:\n card.add_content(content)\n first = False\n\n continue\n except TypeError:\n pass\n\n # try to add a subsubsubtitle\n try:\n subsubsubtitle[1]\n\n content = Subsubsubtitle(text=subsubsubtitle[1])\n if card is not None:\n card.add_content(content)\n first = False\n\n continue\n except TypeError:\n pass\n\n # try to add a bulleted point\n try:\n bulleted[1]\n\n level = floor(len(bulleted[1]) / spaces)\n\n content = BulletedPoint(text=bulleted[2], level=level)\n if card is not None:\n card.add_content(content)\n first = False\n\n continue\n except TypeError:\n pass\n\n # try to add a numbered point\n try:\n numbered[1]\n\n level = floor(len(numbered[1]) / spaces)\n\n content = NumberedPoint(text=numbered[2], number=point_number, level=level)\n if card is not None:\n card.add_content(content)\n point_number += 1\n first = False\n\n continue\n except TypeError:\n point_number = 1\n\n # add plaintext if all else failed\n if card is not None and line.strip() is not '':\n card.add_content(Text(text=line))\n first = False\n\nif __name__ == \"__main__\":\n # parse arguments\n parser = argparse.ArgumentParser(description = \"Generate flash cards from a Markdown file.\")\n parser.add_argument(\"input\", metavar='INFILE',\n help=\"Set the filename for input. Extensions are ignored and .md is assumed.\")\n parser.add_argument(\"-o\", \"--out\", metavar='OUTFILE', default=\"flashcards.pdf\",\n help=\"Set the filename for output. Extensions are ignored and .pdf is assumed. (Default: flashcards.pdf)\")\n parser.add_argument(\"-s\", \"--spaces\", metavar='SPACES', type=int, default=4,\n help=\"Set the number of spaces per indent. (Default: 4)\")\n args = parser.parse_args()\n\n # create markdown engine\n me = MarkdownEngine(outfile=args.out, infile=args.input, debug=False)\n\n # generate flashcards\n me.generate_flashcards(args.spaces)\n","sub_path":"study-buddy.py","file_name":"study-buddy.py","file_ext":"py","file_size_in_byte":6145,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"97206554","text":"import os\nimport sys\nimport logging\n\n\ndef get_logger(logger_name: str = 'enigma') -> logging.Logger:\n logger = logging.getLogger(logger_name)\n loglevel = getattr(logging, os.getenv('LOG_LEVEL', '').upper(), logging.INFO)\n if not isinstance(loglevel, int):\n raise ValueError('Invalid log level: %s' % loglevel)\n\n logger.setLevel(level=loglevel)\n handler = logging.StreamHandler(sys.stdout)\n handler.setLevel(logging.DEBUG)\n formatter = logging.Formatter('%(asctime)s [%(name)s] %(levelname)-8s %(funcName)s:%(lineno)s -- %(message)s')\n handler.setFormatter(formatter)\n\n logger.addHandler(handler)\n return logger\n","sub_path":"common_scripts/enigma_docker_common/logger.py","file_name":"logger.py","file_ext":"py","file_size_in_byte":648,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"455131184","text":"# uncompyle6 version 3.7.4\n# Python bytecode 3.7 (3394)\n# Decompiled from: Python 3.7.9 (tags/v3.7.9:13c94747c7, Aug 17 2020, 18:58:18) [MSC v.1900 64 bit (AMD64)]\n# Embedded file name: T:\\InGame\\Gameplay\\Scripts\\Server\\world\\region.py\n# Compiled at: 2020-09-23 18:13:55\n# Size of source mod 2**32: 19060 bytes\nfrom bucks.bucks_enums import BucksType\nfrom fishing.fishing_data import TunableFishingDataSnippet\nfrom objects.components import ComponentContainer, forward_to_components\nfrom objects.components.statistic_component import HasStatisticComponent\nfrom seasons.seasonal_parameters_mixin import SeasonalParametersMixin\nfrom seasons.seasons_enums import SeasonType, SeasonParameters\nfrom sims.outfits.outfit_enums import OutfitCategory\nfrom sims.outfits.outfit_generator import TunableOutfitGeneratorSnippet, OutfitGenerator\nfrom sims4.localization import TunableLocalizedString\nfrom sims4.tuning.instances import HashedTunedInstanceMetaclass\nfrom sims4.tuning.tunable import HasTunableReference, TunableEnumSet, TunableMapping, TunableRegionDescription, TunableReference, TunableList, Tunable, TunableEnumEntry, TunableTuple, TunableRange, OptionalTunable, HasTunableSingletonFactory, AutoFactoryInit\nfrom sims4.tuning.tunable_base import ExportModes, GroupNames\nfrom sims4.utils import constproperty\nfrom tunable_time import TunableTimeOfDay\nfrom tunable_utils.tunable_white_black_list import TunableWhiteBlackList\nfrom world.terrain_enums import TerrainTag\nimport enum, services, sims4.log, tag\nfrom weather.weather_tuning_mixin import WeatherTuningMixin\nlogger = sims4.log.Logger('Region')\n\nclass RegionType(enum.Int):\n REGIONTYPE_NONE = 0\n REGIONTYPE_RESIDENTIAL = 1\n REGIONTYPE_DESTINATION = 2\n\n\nclass _RegionalRequiredOutfitGenerator(HasTunableSingletonFactory, AutoFactoryInit):\n FACTORY_TUNABLES = {'outfit_category':TunableEnumEntry(description='\\n The outfit category that is required for the region.\\n ',\n default=OutfitCategory.SWIMWEAR,\n tunable_type=OutfitCategory,\n invalid_enums=(\n OutfitCategory.CURRENT_OUTFIT,\n OutfitCategory.CAREER,\n OutfitCategory.SITUATION,\n OutfitCategory.SPECIAL)), \n 'generator':TunableOutfitGeneratorSnippet()}\n\n def generate_outfit(self, sim_info):\n if sim_info.has_outfit_category(self.outfit_category):\n return\n OutfitGenerator.generate_outfit(self, sim_info, self.outfit_category)\n\n\nclass Region(HasTunableReference, ComponentContainer, HasStatisticComponent, WeatherTuningMixin, SeasonalParametersMixin, metaclass=HashedTunedInstanceMetaclass, manager=services.region_manager()):\n REGION_DESCRIPTION_TUNING_MAP = TunableMapping(description='\\n A mapping between Catalog region description and tuning instance. This\\n way we can find out what region description the current zone belongs to\\n at runtime then grab its tuning instance.\\n ',\n key_type=TunableRegionDescription(description='\\n Catalog-side Region Description.\\n ',\n pack_safe=True,\n export_modes=(ExportModes.All)),\n value_type=TunableReference(description=\"\\n Region Tuning instance. This is retrieved at runtime based on what\\n the active zone's region description is.\\n \",\n pack_safe=True,\n manager=(services.region_manager()),\n export_modes=(ExportModes.All)),\n key_name='RegionDescription',\n value_name='Region',\n tuple_name='RegionDescriptionMappingTuple',\n export_modes=(ExportModes.All))\n INSTANCE_TUNABLES = {'gallery_download_venue_map':TunableMapping(description='\\n A map from gallery venue to instanced venue. We need to be able to\\n convert gallery venues into other venues that are only compatible\\n with that region.\\n ',\n key_type=TunableReference(description='\\n A venue type that exists in the gallery.\\n ',\n manager=(services.venue_manager()),\n export_modes=(ExportModes.All),\n pack_safe=True),\n value_type=TunableReference(description='\\n The venue type that the gallery venue will become when it is\\n downloaded into this region.\\n ',\n manager=(services.venue_manager()),\n export_modes=(ExportModes.All),\n pack_safe=True),\n key_name='gallery_venue_type',\n value_name='region_venue_type',\n tuple_name='GalleryDownloadVenueMappingTuple',\n export_modes=ExportModes.All), \n 'compatible_venues':TunableList(description='\\n A list of venues that are allowed to be set by the player in this\\n region.\\n ',\n tunable=TunableReference(description='\\n A venue that the player can set in this region.\\n ',\n manager=(services.venue_manager()),\n export_modes=(ExportModes.All),\n pack_safe=True),\n export_modes=ExportModes.All), \n 'tags':TunableList(description='\\n Tags that are used to group regions. Destination Regions will\\n likely have individual tags, but Home/Residential Regions will\\n share a tag.\\n ',\n tunable=TunableEnumEntry(description='\\n A Tag used to group this region. Destination Regions will\\n likely have individual tags, but Home/Residential Regions will\\n share a tag.\\n ',\n tunable_type=(tag.Tag),\n default=(tag.Tag.INVALID),\n pack_safe=True)), \n 'region_buffs':TunableList(description='\\n A list of buffs that are added on Sims while they are instanced in\\n this region.\\n ',\n tunable=TunableReference(description='\\n A buff that exists on Sims while they are instanced in this\\n region.\\n ',\n manager=(services.buff_manager()),\n pack_safe=True)), \n 'store_travel_group_placed_objects':Tunable(description='\\n If checked, any placed objects while in a travel group will be returned to household inventory once\\n travel group is disbanded.\\n ',\n tunable_type=bool,\n default=False), \n 'travel_group_build_disabled_tooltip':TunableLocalizedString(description='\\n The string that will appear in the tooltip of the grayed out build\\n mode button if build is being disabled because of a travel group in\\n this region.\\n ',\n allow_none=True,\n export_modes=ExportModes.All), \n 'sunrise_time':TunableTimeOfDay(description='\\n The time, in Sim-time, the sun rises in this region.\\n ',\n default_hour=6,\n tuning_group=GroupNames.TIME), \n 'seasonal_sunrise_time':TunableMapping(description='\\n A mapping between season and sunrise time. If the current season\\n is not found then we will default to the tuned sunrise time.\\n ',\n key_type=TunableEnumEntry(description='\\n The season.\\n ',\n tunable_type=SeasonType,\n default=(SeasonType.SUMMER)),\n value_type=TunableTimeOfDay(description='\\n The time, in Sim-time, the sun rises in this region, in this\\n season.\\n ',\n default_hour=6,\n tuning_group=(GroupNames.TIME))), \n 'sunset_time':TunableTimeOfDay(description='\\n The time, in Sim-time, the sun sets in this region.\\n ',\n default_hour=20,\n tuning_group=GroupNames.TIME), \n 'seasonal_sunset_time':TunableMapping(description='\\n A mapping between season and sunset time. If the current season\\n is not found then we will default to the tuned sunset time.\\n ',\n key_type=TunableEnumEntry(description='\\n The season.\\n ',\n tunable_type=SeasonType,\n default=(SeasonType.SUMMER)),\n value_type=TunableTimeOfDay(description='\\n The time, in Sim-time, the sun sets in this region, in this\\n season.\\n ',\n default_hour=20,\n tuning_group=(GroupNames.TIME))), \n 'provides_sunlight':Tunable(description='\\n If enabled, this region provides sunlight between the tuned Sunrise\\n Time and Sunset Time. This is used for gameplay effect (i.e.\\n Vampires).\\n ',\n tunable_type=bool,\n default=True,\n tuning_group=GroupNames.TIME), \n 'weather_supports_fresh_snow':Tunable(description='\\n If enabled, this region supports fresh snow.\\n ',\n tunable_type=bool,\n default=True), \n 'fishing_data':OptionalTunable(description='\\n If enabled, define all of the data for fishing locations in this region.\\n Only used if objects are tuned to use region fishing data.\\n ',\n tunable=TunableFishingDataSnippet()), \n 'welcome_wagon_replacement':OptionalTunable(description='\\n If enabled then we will replace the Welcome Wagon with a new situation.\\n \\n If the narrative is also set to replace the welcome wagon that will take precedent over this replacement.\\n ',\n tunable=TunableReference(description='\\n The situation we will use to replace the welcome wagon.\\n ',\n manager=(services.get_instance_manager(sims4.resources.Types.SITUATION)))), \n 'region_currency_bucks_type':TunableEnumEntry(description='\\n If this is set to INVALID, this region will by default use Simoleon as\\n currency type. Otherwise it will use selected bucks type as currency type.\\n ',\n tunable_type=BucksType,\n default=BucksType.INVALID,\n export_modes=ExportModes.All), \n 'outfit_category_restrictions':TunableTuple(description='\\n A setting which specifies which outfits Sims are able to have in this region.\\n ',\n travel_groups_only=Tunable(description='\\n When set, this applies only to Sims in travel groups.\\n ',\n tunable_type=bool,\n default=False),\n required_outfit_category=OptionalTunable(description='\\n If set, when a playable Sim spawns into this region, they are granted an outfit in this outfit category\\n if they do not have one set.\\n ',\n tunable=(_RegionalRequiredOutfitGenerator.TunableFactory())),\n allowed_outfits=TunableWhiteBlackList(description='\\n The outfit categories that are valid for this region.\\n ',\n tunable=TunableEnumEntry(default=(OutfitCategory.EVERYDAY),\n tunable_type=OutfitCategory,\n invalid_enums=(\n OutfitCategory.CURRENT_OUTFIT,)))), \n 'default_outfit_category':TunableEnumEntry(description='\\n The default outfit category to set on the played Sim if they were in an invalid outfit category for this\\n region when they were last saved.\\n ',\n default=OutfitCategory.EVERYDAY,\n tunable_type=OutfitCategory,\n invalid_enums=(\n OutfitCategory.CURRENT_OUTFIT,)), \n 'is_persistable':Tunable(description='\\n If true, we will create an instance for this region and save/load it. The instance has a commodity tracker\\n which can be used for region based commodities.\\n ',\n tunable_type=bool,\n default=False), \n 'region_type':TunableEnumEntry(description='\\n The region type for this region. Keep in sync with UI region\\n tuning in Tuning->ui.ui_tuning->UiTuning->Pack Specific Data->\\n [Pack] -> Region List -> region type\\n ',\n tunable_type=RegionType,\n default=RegionType.REGIONTYPE_RESIDENTIAL), \n 'is_summit_weather_enabled':Tunable(description='\\n Whether this region has summit (EP10) weather enabled.\\n ',\n tunable_type=bool,\n default=False), \n 'tracked_terrain_tags':OptionalTunable(description='\\n What terrain transitions should be tracked in this region. Used to tuned which terrains\\n are important and exist in this region.\\n ',\n tunable=TunableEnumSet(enum_type=TerrainTag,\n enum_default=(TerrainTag.INVALID)))}\n\n def save(self, region_data):\n region_data.region_id = self.guid64\n region_data.ClearField('commodity_tracker')\n commodities, _, _ = self.commodity_tracker.save()\n region_data.commodity_tracker.commodities.extend(commodities)\n\n def load(self, region_data):\n self.commodity_tracker.load(region_data.commodity_tracker.commodities)\n\n @forward_to_components\n def on_finalize_load(self):\n pass\n\n @constproperty\n def is_sim():\n return False\n\n @property\n def is_downloaded(self):\n return False\n\n @classmethod\n def _cls_repr(cls):\n return \"Region: \".format(cls.__module__, cls.__name__)\n\n @classmethod\n def is_region_compatible(cls, region_instance, ignore_tags=False):\n if region_instance is cls or region_instance is None:\n return True\n if ignore_tags:\n return False\n for tag in cls.tags:\n if tag in region_instance.tags:\n return True\n\n return False\n\n @classmethod\n def is_sim_info_compatible(cls, sim_info):\n other_region = get_region_instance_from_zone_id(sim_info.zone_id)\n if cls.is_region_compatible(other_region):\n return True\n travel_group_id = sim_info.travel_group_id\n if travel_group_id:\n travel_group = services.travel_group_manager().get(travel_group_id)\n if travel_group is not None:\n if not travel_group.played:\n return True\n return False\n\n @classmethod\n def get_sunrise_time(cls):\n season_service = services.season_service()\n if season_service is None:\n return cls.sunrise_time\n return cls.seasonal_sunrise_time.get(season_service.season, cls.sunrise_time)\n\n @classmethod\n def get_sunset_time(cls):\n season_service = services.season_service()\n if season_service is None:\n return cls.sunset_time\n return cls.seasonal_sunset_time.get(season_service.season, cls.sunset_time)\n\n\ndef get_region_instance_from_zone_id(zone_id):\n zone_proto = services.get_persistence_service().get_zone_proto_buff(zone_id)\n if zone_proto is None:\n return\n return get_region_instance_from_world_id(zone_proto.world_id)\n\n\ndef get_region_description_id_from_zone_id(zone_id):\n persistence_service = services.get_persistence_service()\n zone_proto = persistence_service.get_zone_proto_buff(zone_id)\n if zone_proto is None:\n return\n return persistence_service.get_region_id_from_world_id(zone_proto.world_id)\n\n\ndef get_region_instance_from_world_id(world_id):\n region_description_id = services.get_persistence_service().get_region_id_from_world_id(world_id)\n if region_description_id is None:\n return\n return Region.REGION_DESCRIPTION_TUNING_MAP.get(region_description_id)","sub_path":"Scripts/simulation/world/region.py","file_name":"region.py","file_ext":"py","file_size_in_byte":15304,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"103355779","text":"import argparse\nimport configparser\nimport datetime\nimport logging\n\nfrom .engine import Engine\nfrom .logger import DummyLogger, FileLogger\n\n\ndef _parse_args():\n parser = argparse.ArgumentParser(description='Run a workflow.')\n parser.add_argument('--dir', type=str, required=True,\n help='a path to the data directory')\n parser.add_argument('--targets', nargs='+', required=True,\n help='targets to run')\n parser.add_argument('--deps', action='store_true',\n help='add upstream targets (resolve dependencies)')\n parser.add_argument('--engine', required=False, default='engine.yaml',\n help='engine configuration file in YAML format')\n parser.add_argument('--conf', nargs='+', required=False, default=None,\n help='parameter file(s) in INI format')\n parser.add_argument('--params', nargs='+', required=False, default=[],\n help='additional parameters from command line')\n return parser.parse_args()\n\n\ndef read_context(param_file_paths, command_line_params):\n context = dict()\n if not param_file_paths:\n param_file_paths = []\n for param_file_path in param_file_paths:\n if param_file_path is None:\n continue\n config = configparser.ConfigParser()\n config.read(param_file_path)\n for section in config:\n for key in config[section]:\n context[section + '.' + key] = config[section][key]\n for param in command_line_params:\n if '=' in param:\n key, value = param.split('=')\n if '.' in key:\n section, key = key.split('.', 2)\n else:\n section = 'default'\n context[section + '.' + key.lower()] = value\n return context\n\n\ndef run_engine(timestamp: int = None, callback=None, logs: bool = True):\n \"\"\"\n Set up and run an engine instance. Read config files, parse command-line arguments,\n register file specs and tasks found in the config, set up logging, etc. and run the engine.\n\n It is suggested to run this function in the main function.\n If additional tweaking is needed between setting up the engine and running it,\n provide a callback function.\n\n :param timestamp: Optional timestamp of the run, as integer in YYYYMMDDHHMMSS format.\n :param callback: Optional function to call just before running the engine.\n The callback function will receive two arguments: the configured engine instance,\n and a dictionary of arguments that were about to be passed to the engine's `run()` method.\n :param logs: Whether to configure logging.\n \"\"\"\n\n # Set timestamp\n if timestamp is None:\n timestamp = int(datetime.datetime.now().strftime(\"%Y%m%d%H%M%S\"))\n\n # Read command-line parameters\n args = _parse_args()\n\n # Set up logging\n logger = FileLogger(args.dir, timestamp) if logs else DummyLogger()\n log = logging.getLogger(__name__)\n\n # Set up engine\n log.info(\"Setting up engine\")\n engine = Engine(timestamp=timestamp)\n engine.read(args.engine)\n targets = engine.expand_targets(args.targets, args.deps)\n\n # Set up context\n log.info(\"Setting up context\")\n context = read_context(args.conf, args.params)\n\n # Run the engine\n arguments = dict(\n workspace=args.dir,\n context=context,\n targets=targets,\n )\n if callback:\n log.info(\"Executing callback\")\n arguments = callback(engine, arguments)\n logger.report_start(timestamp, targets, context)\n log.info(\"Running the engine\")\n try:\n engine.run(**arguments)\n logger.report_finish(timestamp, True)\n except Exception as e:\n logger.report_finish(timestamp, False)\n log.exception('Exception caught')\n raise e\n\n\nif __name__ == '__main__':\n run_engine()\n","sub_path":"elkhound/runner.py","file_name":"runner.py","file_ext":"py","file_size_in_byte":3886,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"146737057","text":"# Copyright 2017 Battelle Energy Alliance, 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\"\"\"\nCreated on September 12, 2016\n\"\"\"\n#for future compatibility with Python 3--------------------------------------------------------------\nfrom __future__ import division, print_function, unicode_literals, absolute_import\nimport warnings\nwarnings.simplefilter('default',DeprecationWarning)\nif not 'xrange' in dir(__builtins__):\n xrange = range\n#End compatibility block for Python 3----------------------------------------------------------------\n\n#External Modules------------------------------------------------------------------------------------\nimport collections\nimport subprocess\n# try : import Queue as queue\n# except ImportError: import queue\nimport os\nimport signal\nimport copy\nimport abc\n#import logging, logging.handlers\nimport threading\n\n#External Modules End--------------------------------------------------------------------------------\n\n#Internal Modules------------------------------------------------------------------------------------\nfrom utils import utils\nfrom BaseClasses import BaseType\nimport MessageHandler\nfrom .InternalRunner import InternalRunner\n#Internal Modules End--------------------------------------------------------------------------------\n\nclass SharedMemoryRunner(InternalRunner):\n \"\"\"\n Class for running internal objects in a threaded fashion using the built-in\n threading library\n \"\"\"\n def __init__(self, messageHandler, args, functionToRun, identifier=None, metadata=None, uniqueHandler = \"any\"):\n \"\"\"\n Init method\n @ In, messageHandler, MessageHandler object, the global RAVEN message\n handler object\n @ In, args, dict, this is a list of arguments that will be passed as\n function parameters into whatever method is stored in functionToRun.\n e.g., functionToRun(*args)\n @ In, functionToRun, method or function, function that needs to be run\n @ In, identifier, string, optional, id of this job\n @ In, metadata, dict, optional, dictionary of metadata associated with\n this run\n @ In, uniqueHandler, string, optional, it is a special keyword attached to\n this runner. For example, if present, to retrieve this runner using the\n method jobHandler.getFinished, the uniqueHandler needs to be provided.\n If uniqueHandler == 'any', every \"client\" can get this runner\n @ In, clientRunner, bool, optional, Is this runner needed to be executed in client mode? Default = False\n @ Out, None\n \"\"\"\n ## First, allow the base class handle the commonalities\n # we keep the command here, in order to have the hook for running exec code into internal models\n super(SharedMemoryRunner, self).__init__(messageHandler, args, functionToRun, identifier, metadata, uniqueHandler)\n\n ## Other parameters manipulated internally\n self.subque = collections.deque()\n #self.subque = queue.Queue()\n\n self.skipOnCopy.append('subque')\n\n def isDone(self):\n \"\"\"\n Method to check if the calculation associated with this Runner is finished\n @ In, None\n @ Out, finished, bool, is it finished?\n \"\"\"\n ## If the process has not been started yet, then return False\n if not self.started:\n return False\n\n if self.thread is None:\n return True\n else:\n return not self.thread.is_alive()\n\n def getReturnCode(self):\n \"\"\"\n Returns the return code from running the code. If return code not yet\n set, then set it.\n @ In, None\n @ Out, returnCode, int, the return code of this evaluation\n \"\"\"\n if not self.hasBeenAdded:\n self._collectRunnerResponse()\n ## Is this necessary and sufficient for all failed runs?\n if len(self.subque) == 0 and self.runReturn is None:\n self.runReturn = None\n self.returnCode = -1\n\n return self.returnCode\n\n def _collectRunnerResponse(self):\n \"\"\"\n Method to add the process response in the internal variable (pointer)\n self.runReturn\n @ In, None\n @ Out, None\n \"\"\"\n if not self.hasBeenAdded:\n if len(self.subque) == 0:\n ## Queue is empty!\n self.runReturn = None\n else:\n self.runReturn = self.subque.popleft()\n\n self.hasBeenAdded = True\n\n def start(self):\n \"\"\"\n Method to start the job associated to this Runner\n @ In, None\n @ Out, None\n \"\"\"\n try:\n self.thread = threading.Thread(target = lambda q, *arg : q.append(self.functionToRun(*arg)), name = self.identifier, args=(self.subque,)+tuple(self.args))\n\n self.thread.daemon = True\n self.thread.start()\n self.started = True\n except Exception as ae:\n self.raiseAWarning(self.__class__.__name__ + \" job \"+self.identifier+\" failed with error:\"+ str(ae) +\" !\",'ExceptedError')\n self.returnCode = -1\n\n def kill(self):\n \"\"\"\n Method to kill the job associated to this Runner\n @ In, None\n @ Out, None\n \"\"\"\n self.raiseAWarning(\"Terminating \"+self.thread.pid+ \" Identifier \" + self.identifier)\n os.kill(self.thread.pid, signal.SIGTERM)\n","sub_path":"framework/Runners/SharedMemoryRunner.py","file_name":"SharedMemoryRunner.py","file_ext":"py","file_size_in_byte":5582,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"68576003","text":"# Import dependencies\r\nimport twitter\r\nfrom bs4 import BeautifulSoup\r\nimport requests\r\nimport pymongo\r\nimport pprint\r\nfrom datetime import datetime, timedelta\r\n# Import program used to categorize sentiments\r\nimport sent_rating \r\nimport config as config\r\n\r\n# Initialize PyMongo to work with MongoDBs\r\nconn = 'mongodb://localhost:27017'\r\nclient = pymongo.MongoClient(conn)\r\n\r\n# Define database and collection\r\ndb = client.twitter_db\r\ncollection = db.tweets\r\ncollection.drop()\r\n\r\napi = twitter.Api(consumer_key=config.API_KEY,\r\n consumer_secret=config.API_SECRET,\r\n access_token_key=config.ACCESS_TOKEN,\r\n access_token_secret=config.ACCESS_TOKEN_SECRET)\r\n\r\n#print(api.VerifyCredentials())\r\n\r\n# Create a search list for companies\r\nsearch_list = [{\"id\":\"SB\",\"name\":\"Star Bucks\",\"search_str\":'Starbucks Coffee'},\r\n {\"id\":\"MD\",\"name\":\"McDonalds\",\"search_str\":\"McDonald Coffee\"},\r\n {\"id\":\"DD\",\"name\":\"Dunkin Donuts\",\"search_str\":\"Dunkin Coffee\"}]\r\n\r\n\r\n# Calculate a date range array with a range starting from current date going back 10 days\r\nN=10\r\nv_curr_date = datetime.today().strftime('%Y-%m-%d')\r\nv_rng_strt_dt_char = (datetime.today() - timedelta(days=N)).strftime('%Y-%m-%d')\r\nv_rng_strt_dt = datetime.strptime(v_rng_strt_dt_char,'%Y-%m-%d')\r\ndate_arr=[]\r\nfor i in range(0,11):\r\n date_arr.append((v_rng_strt_dt + timedelta(days=i)).strftime('%Y-%m-%d'))\r\n\r\nv_lang = \"en\"\r\nv_count = 1000\r\nv_geo_code = [40.7128, -74.0060, \"5000mi\"]\r\nv_sentiment=\"\"\r\n\r\nfor x in search_list:\r\n\r\n for v_strt_dt in date_arr:\r\n \r\n query = x['search_str']\r\n v_id = x['id']\r\n v_name = x['name']\r\n \r\n v_end_dt = (datetime.strptime(v_strt_dt, '%Y-%m-%d') + timedelta(days=1)).strftime('%Y-%m-%d')\r\n \r\n search = api.GetSearch(term=query,since=v_strt_dt,until=v_end_dt,lang=v_lang,count=v_count)\r\n\r\n\r\n for tweet in search:\r\n # Error handling\r\n try:\r\n \r\n # Print the output from twitter on the screen\r\n #print(tweet.id, tweet.text);\r\n #create_date = datetime.strptime(tweet.created_at, '%a %b %d %H:%M:%S +%f %Y').strftime('%d/%m/%Y')\r\n create_date = datetime.strptime(tweet.created_at, '%a %b %d %H:%M:%S +%f %Y').strftime('%Y-%m-%d')\r\n print(f'Create Date: {create_date} Rng_Str: {v_strt_dt} Rng_End: {v_end_dt}')\r\n \r\n v_sentiment = sent_rating.get_rating(tweet.text);\r\n \r\n \r\n \r\n # Dictionary to be inserted as a MongoDB document\r\n post = {\r\n 'id': v_id,\r\n 'name': v_name,\r\n 'created' : create_date,\r\n 'range_strt_dt': v_strt_dt,\r\n 'range_end_dt' : v_end_dt,\r\n 'search_str': query,\r\n 'tweet_id': tweet.id,\r\n 'tweet_text': tweet.text,\r\n 'retweet_count': tweet.retweet_count,\r\n 'source' : tweet.source,\r\n 'favourite_count' : tweet.user.favourites_count,\r\n 'sentiment' : v_sentiment\r\n }\r\n\r\n collection.insert_one(post)\r\n\r\n except Exception as e:\r\n print(e)\r\n #print(tweet.id);\r\n\r\n##Checking the load into mongo db\r\n\r\n# Display items in MongoDB collection\r\ntweet_recs = db.tweets.find()\r\n\r\n#for tweet in tweet_recs:\r\n# print(tweet)\r\n\r\ndb.tweets.count() \r\n\r\ny=db.tweets.aggregate([\r\n{ \"$group\": { \"_id\": \"$name\", \"No_of_Times\": { \"$sum\": 1 } } }\r\n])\r\n\r\nfor t in y:\r\n print(t)\r\n\r\n","sub_path":"extract_tweets.py","file_name":"extract_tweets.py","file_ext":"py","file_size_in_byte":3631,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"449289980","text":"# -*- coding: utf-8 -*-\n\"\"\"\n@File : 04_Functions.py\n@Modify Time : 2020/2/9 16:10 \n@Author : Calvin.zhu \n@Version : 1.0\n@Description : 函数\n\"\"\"\n\n\ndef my_return(name, age=20):\n \"\"\"\n 函数可以以tuple的方式,返回多个值\n\n :param name:\n :param age:\n :return:\n \"\"\"\n user_name = 'test_' + name\n user_age = age\n return user_name, user_age\n\n\ndef school(*args):\n \"\"\"\n 不定量位置参数,即入参数目不定,入参以tuple的类型传入\n :param args:\n :return:\n \"\"\"\n school_info = []\n for x in args:\n school_info.append(x)\n else:\n school_info.append(\"小学\")\n return school_info\n\n\ndef city(**kwargs):\n \"\"\"\n 不定量关键字参数,即入参数目不定,入参以dict的类型传���\n :param kwargs:\n :return:\n \"\"\"\n city_name = []\n city_ares = []\n for name, ares in kwargs.items():\n city_name.append(name)\n city_ares.append(ares)\n return city_name, city_ares\n\n\nif __name__ == '__main__':\n # name, age = my_return(\"hello\", 10) # 批量赋值,专业说法叫做“序列解包”\n # name2, age2 = my_return(age=10, name=\"yes\") # 关键字参数的方式调用函数\n # print(name, age)\n # print(name2, age2)\n\n # my_school = school(\"abcd\", \"deng\", 111)\n # my_school2 = school()\n # print(my_school, '\\n', my_school2)\n\n city_list = city(sh=100, bj=1000)\n print(city_list)\n","sub_path":"01 MyBase/Junior/04_Functions.py","file_name":"04_Functions.py","file_ext":"py","file_size_in_byte":1454,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"566969037","text":"from bokeh.io import output_file, show\nfrom bokeh.models import ColumnDataSource, GMapOptions\nfrom bokeh.plotting import gmap\nfrom .model import CrimeScene\nfrom bokeh.io import output_file, output_notebook, show, save\nfrom bokeh.models import (\n GMapPlot, GMapOptions, ColumnDataSource, Circle, LogColorMapper, BasicTicker, ColorBar,\n Range1d, PanTool, WheelZoomTool, BoxSelectTool\n)\nfrom bokeh.models.mappers import ColorMapper, LinearColorMapper\nfrom bokeh.palettes import Viridis5\nimport os\n\n\ndef get_co_ordinates():\n crimes_scenes = CrimeScene.query.all()\n longitudes = [crimescene.longitude for crimescene in crimes_scenes]\n latitudes = [crimescene.latitude for crimescene in crimes_scenes]\n colors = [crimescene.scene.category_color for crimescene in crimes_scenes]\n return latitudes, longitudes, colors\n\n\ndef showmap():\n tools = \"pan,wheel_zoom,box_zoom,reset,save,hover,zoom_in,box_edit,poly_draw\"\n # tools = \" box_edit, box_select, box_zoom, click, crosshair, help, hover, lasso_select, pan, point_draw, poly_draw, poly_edit, poly_select, previewsave, redo, reset, save, tap, undo, wheel_zoom, xbox_select, xbox_zoom, xpan, xwheel_pan, xwheel_zoom, xzoom_in, xzoom_out, ybox_select, ybox_zoom, ypan, ywheel_pan, ywheel_zoom, yzoom_in, yzoom_out, zoom_in\"\n map_options = GMapOptions(\n lat=0.3476, lng=32.5825, map_type=\"roadmap\", zoom=13)\n GOOGLE_API_KEY = \"AIzaSyAFCR-n7VxtftzPKR4gCje1T-cAxQXn7S8\"\n plot = gmap(GOOGLE_API_KEY, map_options, tools=tools,\n title=\"Crimes visualizing center\", height=700, width=1100)\n latitude_list, longitude_list, colors_list = get_co_ordinates()\n source = ColumnDataSource(\n data=dict(\n lat=latitude_list,\n lon=longitude_list,\n color=colors_list\n )\n )\n plot.circle(x=\"lon\", y=\"lat\", size=15, fill_color=\"color\",\n fill_alpha=0.8, source=source)\n BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))\n storage_path = os.path.join(BASE_DIR, 'pathfinder/templates/pages')\n map_path = os.path.join(storage_path, 'gmap_plot.html')\n output_file(map_path)\n print(\"saved...\")\n save(plot)\n","sub_path":"pathfinder/PlotData.py","file_name":"PlotData.py","file_ext":"py","file_size_in_byte":2187,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"415988337","text":"'''image combining demonstrates PIL.Image.paste()\r\nUnpublished work (c)2013 Project Lead The Way\r\nAdapted from CSE Activity 1.3.7 PIL API\r\nVersion 12/16/2013 '''\r\n\r\nimport PIL\r\nimport matplotlib.pyplot as plt\r\nimport os.path \r\nimport PIL.ImageDraw \r\n\r\n# Open a file named image1.jpg in the same directory as the Python script\r\ndirectory = os.path.dirname(os.path.abspath(__file__)) \r\nimage1_file = os.path.join(directory, 'image1.jpg')\r\n\r\n# Open and show the first image in a new Figure window\r\nimg1 = PIL.Image.open(image1_file)\r\nfig, axes = plt.subplots(1, 1)\r\naxes.imshow(img1)\r\n#fig.show()\r\n\r\n\r\n# Open, resize, and display a second image (PNG FORMAT)\r\nimage2_file = os.path.join(directory, 'image2.png')\r\nimg2 = PIL.Image.open(image2_file)\r\nimg2_small = img2.resize((345, 200)) #width and height measured in plt\r\nfig2, axes2 = plt.subplots(1, 2)\r\naxes2[0].imshow(img2)\r\naxes2[1].imshow(img2_small)\r\n# fig2.show()\r\n\r\n\r\n#define the image size to create a mask\r\nwidth, height = img2_small.size\r\n\r\n#start with transparent mask\r\ntriangle_mask = PIL.Image.new('RGBA', (width, height), (0,0,0,0))\r\ndrawing_layer = PIL.ImageDraw.Draw(triangle_mask)\r\n#draw the triangle shape by using three points\r\ndrawing_layer.polygon([(0,height),(width/2,0),\r\n (width,height)],\r\n fill=(0,0,0,255))\r\n\r\n# Paste Tiny Toons into TV display and display\r\n# Uses alpha from mask\r\nimg1.paste(img2_small, (260, 20), mask=triangle_mask) #coordinate of upper left corner\r\n# Display\r\nfig3, axes3 = plt.subplots(1, 1) #changed to (1, 1) from (1, 2)\r\naxes3.imshow(img1, interpolation='none')\r\n#axes3[1].imshow(img1, interpolation='none') \r\n#axes3[1].set_xlim(500, 1500)\r\n#axes3[1].set_ylim(1130, 850)\r\nfig3.show()\r\n","sub_path":"montage.py","file_name":"montage.py","file_ext":"py","file_size_in_byte":1738,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"4818488","text":"failed_max = int(input())\n\nsum_grades = 0\nnum_tasks = 0\nname_last_task = \" \"\nfailed_grades = 0\n\n\nwhile failed_grades < failed_max:\n name_task = str(input())\n if name_task == \"Enough\":\n print(f\"Average score: {sum_grades / num_tasks:.2f}\")\n print(f\"Number of problems: {num_tasks}\")\n print(f\"Last problem: {name_last_task}\")\n break\n\n grade = int(input())\n\n if grade <= 4:\n failed_grades += 1\n if failed_grades == failed_max:\n print(f\"You need a break, {failed_grades} poor grades.\")\n break\n\n num_tasks += 1\n name_last_task = name_task\n sum_grades += grade\n","sub_path":"Python_ProgramingBasics/While Loop - Exercise/02. Exam Preparation.py","file_name":"02. Exam Preparation.py","file_ext":"py","file_size_in_byte":640,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"223431111","text":"from ..common import RawDataset, MultilingualRawDataset\nfrom ..data_configs import task2datadir, abbre2language\nimport itertools\nfrom collections import OrderedDict, defaultdict\nimport os\n\n\nclass UDPOSDataset(MultilingualRawDataset):\n def __init__(self):\n self.name = \"udpos\"\n self.data_dir = task2datadir[self.name]\n # (\"english,afrikaans,arabic,bulgarian,german,greek,spanish,\"\n # \"estonian,basque,persian,finnish,french,hebrew,hindi,hungarian,\"\n # \"indonesian,italian,japanese,korean,\"\n # \"marathi,dutch,portuguese,russian,\"\n # \"tamil,telugu,turkish,urdu,vietnamese,chinese\")\n self.lang_abbres = [\n \"en\",\n \"af\",\n \"ar\",\n \"bg\",\n \"de\",\n \"el\",\n \"es\",\n \"et\",\n \"eu\",\n \"fa\",\n \"fi\",\n \"fr\",\n \"he\",\n \"hi\",\n \"hu\",\n \"id\",\n \"it\",\n \"ja\",\n \"ko\",\n \"mr\",\n \"nl\",\n \"pt\",\n \"ru\",\n \"ta\",\n \"te\",\n \"tr\",\n \"ur\",\n \"vi\",\n \"zh\",\n ]\n self.metrics = [\"f1_score_tagging\"]\n self.label_list = []\n self.label2idx = {}\n self.pad_id = None\n self.num_labels = -1\n self.contents = OrderedDict()\n self.create_contents()\n\n def get_labels(self):\n return self.label_list\n\n def get_language_data(self, language):\n return self.contents[language]\n\n def create_contents(self):\n entries = []\n for lang in self.lang_abbres:\n for which_split, wsplit in (\n (\"train\", \"trn\"),\n (\"dev\", \"val\"),\n (\"test\", \"tst\"),\n ):\n if which_split == \"train\":\n which_split = f\"train-{lang}.tsv\"\n if which_split == \"dev\":\n which_split = f\"dev-{lang}.tsv\"\n if which_split == \"test\":\n which_split = f\"test-{lang}.tsv\"\n file_ = os.path.join(self.data_dir, which_split)\n entries.extend(self.udpos_parse(lang, file_, wsplit))\n entries = sorted(entries, key=lambda x: x[0]) # groupby requires contiguous\n self.label_list = sorted(list(set(self.label_list)))\n self.label_list.append(\"\")\n self.label2idx = {t: i for i, t in enumerate(self.label_list)}\n self.pad_id = self.label2idx[\"\"]\n self.num_labels = len(self.label_list)\n for language, triplets in itertools.groupby(entries, key=lambda x: x[0]):\n # language, [(lang, split, eg)...]\n triplets = list(triplets)\n trn_egs, val_egs, tst_egs = [], [], []\n for _language, split, eg in triplets:\n assert language == _language\n if split == \"trn\":\n trn_egs.append(eg)\n elif split == \"val\":\n val_egs.append(eg)\n elif split == \"tst\":\n tst_egs.append(eg)\n else:\n raise ValueError\n _dataset = RawDataset(\n name=f\"{self.name}-{language}\",\n language=language,\n metrics=self.metrics,\n label_list=self.label_list,\n label2idx=self.label2idx, # make all have the same mapping\n )\n _dataset.trn_egs = trn_egs if len(trn_egs) else None\n _dataset.val_egs = val_egs if len(val_egs) else None\n _dataset.tst_egs = tst_egs if len(tst_egs) else None\n # only for tagging task\n _dataset.idx2label = {v: k for k, v in _dataset.label2idx.items()}\n\n self.contents[language] = _dataset\n\n def udpos_parse(self, lang, input_file, which_split, update_label_list=True):\n # or just use nltk\n sentence_egs = []\n language = abbre2language[lang]\n with open(input_file, \"r\") as f:\n lines = f.read().strip().split(\"\\n\\n\")\n for line in lines:\n sent_vec = line.strip().split(\"\\n\")\n token_tag_vec = [wt.strip().split(\"\\t\") for wt in sent_vec]\n if update_label_list:\n for _, tag in token_tag_vec:\n self.label_list.append(tag)\n sentence_egs.append((language, which_split, token_tag_vec,))\n return sentence_egs\n","sub_path":"code/data_loader/pos/udpos.py","file_name":"udpos.py","file_ext":"py","file_size_in_byte":4492,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"303087957","text":"# -*- coding:Utf-8 -*-\n# Ligne permettant l'utilisation des accents\n\n# Importation de pygame\nimport pygame\nfrom pygame.locals import *\n\n# Importation de la bibliothèque system\nimport sys\nsys.path.insert(0, 'Buttons.py')\n# Initialisation de pygame\npygame.init()\n\nimport Buttons\n\n# Création de la fenêtre\n# Fenêtre de 900 pixels de largeur et de 899 pixels de hauteur\n# Resizable permet à la fenêtre d'être redimensionnée durant l'exécution\nfenetre = pygame.display.set_mode((700,700), RESIZABLE)\n\n# Création fond d'écran\nfond_e = pygame.image.load(\"Images/fond_cuisine.jpg\").convert()\n\n\n# Création du texte du score\nfenetre.blit(fond_e,(0,0))\nfont = pygame.font.Font(None, 24)\n\npygame.display.flip()\n\nclass Button:\n def __init__(self):\n self.main()\n\n #Create a display\n def display(self):\n self.screen = fenetre\n\n #Update the display and show the button\n def update_display(self):\n #Parameters: surface, color, x, y, length, height, width, text, text_color\n self.Button1.create_button(self.screen, (127,51,6), 50, 600, 250, 75, 0, \"Retour\", (255,255,255))\n pygame.display.flip()\n\n\n #Run the loop\n def main(self):\n self.Button1 = Buttons.Button()\n self.display()\n while True:\n self.update_display()\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n pygame.quit()\n elif event.type == MOUSEBUTTONDOWN:\n if self.Button1.pressed(pygame.mouse.get_pos()):\n import main\n\ndef menu(): #procedure qui affiche le menu\n\n # musique du menu\n pygame.mixer.music.load(\"Transforyou.mp3\")\n pygame.mixer.music.play()\n\n #création fond d'écran menu\n fond_e = pygame.image.load(\"Images/fond_cuisine.jpg\").convert()\n fenetre.blit(fond_e,(0,0)) #affiche l'image \"fond_e\" aux coordonnées \"(0,0)\" de la fenêtre \"fenetre\"\n pygame.display.flip() #rafraichit la fenêtre pour voir les changements\n\n\n boutonJouer = Button()\n\nwhile 1:\n # Boucle sur les différents évènement reçut\n for event in pygame.event.get(): # Ferme la fenetre si appuie sur la croix rouge\n if event.type == QUIT:\n sys.exit()\n fenetre.blit(fond_e, (0,0))\n\n\n #On refresh l'affichage\n pygame.display.flip()\n\n\n # Limite le nombre d'image par secondes\n pygame.time.wait(10)\n menu()\n","sub_path":"Credit.py","file_name":"Credit.py","file_ext":"py","file_size_in_byte":2493,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"248756700","text":"import pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom textblob import TextBlob\n#为使控制台输出完整----------------------------------------------------------------------------------------------------------------------\npd.set_option('display.max_columns',1000)\npd.set_option('display.width', 1000)\npd.set_option('display.max_colwidth',1000)\n#----------------------------------------------------------------------------------------------------------------------\ndata=pd.read_csv(r'C:\\Users\\lenovo\\Desktop\\2020_Weekend2_Problems\\Problem_C_Data\\Problem_C_Data\\hair_dryer.tsv',sep='\\t',header=0)\ndate = pd.read_csv(r'C:\\Users\\lenovo\\Desktop\\date.csv')\ndef dealwith_vine(x):\n if x == 'Y':\n x = 1.5\n else:\n x = 1\n return x\ndef salescount(x):\n if x == 'Y':\n x = 1\n else:\n x = 0\n return x\ndef dealwith_verified_purchase(x):\n if x == 'Y':\n x = 1\n else:\n x = 0.2\n return x\n\ndata_quantified=pd.DataFrame()#新DF,用于存储量化后的data数据\ndata_quantified['review_date']=data['review_date']\ndata_quantified['star_rating']=data['star_rating']\ndata_quantified['vine_weigh'] = list(map(dealwith_vine, data['vine'])) # 将vine的权重调整为两倍\ndata_quantified['verified_purchase_weigh'] = list(map(dealwith_verified_purchase, data['verified_purchase'])) # 将未购买的评论调整未0.1\ndata_quantified['helpful_votes_weigh'] = (data['helpful_votes'])*0.1+1#+1将所有0投票的评论算进去\ndata_quantified['star_weigh'] = data_quantified['vine_weigh'] * data_quantified['verified_purchase_weigh'] #总权重 weight 改为weigh\ndata_quantified['star_rating_weighed']=data_quantified['star_rating']* data_quantified['star_weigh']\ndata_quantified['sales']=list(map(salescount, data['verified_purchase']))\ndata_quantified['review_date']=pd.to_datetime(data['review_date'])#标准时转换\ndata_quantified=data_quantified.set_index('review_date')\ndata_quantified['sales_cumsum']=data_quantified['sales'].cumsum()\ndata_quantified['star_cumsum']=(data_quantified['star_rating_weighed']*data_quantified['sales']).cumsum()#去除未付款者后进行计数\ndata_quantified['star_current']=data_quantified['star_cumsum']/data_quantified['sales_cumsum']\n#print(data_quantified)\nsales_sum=data_quantified.resample('M').sum()['sales']\ndata_M=data_quantified.resample('M').mean()\ncorr_star_sale=sales_sum.corr(data_M['star_rating'])\ncorr_star_weighed_sale=sales_sum.corr(data_M['star_rating_weighed'])\n#print(sales_sum)\nprint(corr_star_sale)\nprint(corr_star_weighed_sale)\ndata_M['sales']=sales_sum\ndata_M=data_M.reset_index()\ndata['review_date']=pd.to_datetime(data['review_date'])\ndata_M['delta_date']=(data_M['review_date'] - data['review_date'][11469]).map(lambda x:x.days)#转换为数字格式的天数\n\nx=data_M['delta_date'].to_list()\ny=sales_sum.to_list()\nx = np.array(x)\nprint('x is :\\n',x)\ny = np.array(y)\nf1 = np.polyfit(x, y, 5)\nprint('f1 is :\\n',f1)\nsale_time = np.poly1d(f1)\nprint('p1 is :\\n', sale_time)\n#data_M_mean['sales'].plot()\n#plt.show()\nfig = plt.figure()\nax1=fig.add_subplot(2,1,1)\nax2=fig.add_subplot(2,1,2)\nax1.plot(data_M['sales'])\n#ax2.plot(data_M_mean['star_current'])\nax2.plot(x,y)\nplt.show()\n#print(data_M_mean)\n#print(weighed_mean)\n#print(sales_sum)\n\n\n\n","sub_path":"corr_analyze.py","file_name":"corr_analyze.py","file_ext":"py","file_size_in_byte":3280,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"37558330","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\n# Author: Francium\n# www.francium.me\n\nimport argparse\nimport os\nimport sqlite3\nfrom scapy.all import sniff, ARP\n\n\ndef command_parser():\n parser = argparse.ArgumentParser(description=\"ARP Watcher Script\")\n parser.add_argument(\"-i\", \"--interface\", metavar=\"interface\", dest=\"interface\", required=True, nargs='?',\n help=\"interface name\")\n parser.add_argument(\"-f\", \"--db_file\", metavar=\"db file\", dest=\"db_file\", required=True, nargs='?',\n help=\"sqlite3 db file\")\n return parser.parse_args()\n\n\nclass database(object):\n\n def __init__(self, db_file_name):\n if not os.path.exists(db_file_name):\n self.connect = sqlite3.connect(db_file_name)\n self._create_table()\n else:\n self.connect = sqlite3.connect(db_file_name)\n\n def __enter__(self):\n return self\n\n def __exit__(self, exc_type, exc_val, exc_tb):\n self.connect.close()\n\n def _create_table(self):\n with self.connect:\n self.connect.execute(\"\"\"\n CREATE TABLE arp (\n id INTEGER PRIMARY KEY,\n ip VARCHAR(15) UNIQUE,\n mac VARCHAR(17)\n )\n \"\"\")\n\n def fetch_data(self):\n cursor = self.connect.cursor()\n data = {}\n for item in cursor.execute(\"SELECT ip, mac FROM arp\"):\n data[item[0]] = item[1]\n cursor.close()\n return data\n\n def _drop_table(self):\n with self.connect:\n self.connect.execute(\"DROP TABLE arp\")\n\n def update_data(self, data):\n self._drop_table()\n self._create_table()\n with self.connect:\n self.connect.executemany(\"INSERT INTO arp (ip, mac) VALUES (?, ?)\", list(data.items()))\n\n\ndef watch_arp(pkt):\n # Got a ARP response\n if pkt[ARP].op == 2:\n if IP_MAC.get(pkt[ARP].psrc) is None:\n # New ip, mac\n print(\"[*] Found a new device IP: {} ------ MAC: {}\".format(pkt[ARP].psrc, pkt[ARP].hwsrc))\n IP_MAC[pkt[ARP].psrc] = pkt[ARP].hwsrc\n elif IP_MAC.get(pkt[ARP].psrc) and IP_MAC[pkt[ARP].psrc] != pkt[ARP].hwsrc:\n # Some device changed\n print(\"[!!!] IP {} has some change or problem\".format(pkt[ARP].psrc))\n print(\"[!!!] Old: IP: {} ------ MAC: {}\".format(pkt[ARP].psrc, IP_MAC[pkt[ARP].psrc]))\n print(\"[!!!] New: IP: {} ------ MAC: {}\".format(pkt[ARP].psrc, pkt[ARP].hwsrc))\n # Do something, send mail to manager or log\n # ...\n IP_MAC[pkt[ARP].psrc] = pkt[ARP].hwsrc\n\n\ndef main():\n args = command_parser()\n interface = args.interface\n db_file = args.db_file\n\n print(\"[*] Beginning script\")\n\n global IP_MAC\n\n with database(db_file) as db:\n IP_MAC = db.fetch_data()\n\n # Print existed ip and mac\n print(\"[*] IP and MAC existed in DB\")\n for ip, mac in IP_MAC.items():\n print(\"[*] IP: {} ------ MAC: {}\".format(ip, mac))\n\n try:\n # Begin sniff\n print(\"[*] Beginning sniff. [CTRL-C to stop]\")\n sniff(prn=watch_arp, filter=\"arp\", iface=interface, store=0)\n except KeyboardInterrupt:\n pass\n finally:\n with database(db_file) as db:\n print(\"[*] Update IP end MAC to DB\")\n for ip, mac in IP_MAC.items():\n print(\"[*] IP: {} ------ MAC: {}\".format(ip, mac))\n db.update_data(IP_MAC)\n print(\"[*] Script end\")\n\nIP_MAC = None\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"arp_watcher.py","file_name":"arp_watcher.py","file_ext":"py","file_size_in_byte":3564,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"385351584","text":"''' File identifer for MP4 and M4A files\n'''\n\n\n\n#-- see https://mutagen.readthedocs.org/en/latest/api/mp4.html for details:\nkeysDict = {\n 'title':'\\xa9nam',\n 'album':'\\xa9alb',\n 'artist':'\\xa9ART',\n 'album artist':'aART',\n 'composer':'\\xa9wrt',\n 'year':'\\xa9day',\n 'comment':'\\xa9cmt',\n 'desc':'desc',\n 'ldes':'ldes',\n 'date':'purd',\n 'grouping':'\\xa9grp',\n 'genre':'\\xa9gen',\n 'lyrics':'\\xa9lyr',\n 'pURL':'purl',\n 'pepisode':'egid',\n 'pcategory':'catg',\n 'pkeywords':'keyw',\n 'enc':'\\xa9too',\n 'copyright':'cprt',\n 'soal':'soal',\n 'soaa':'soaa',\n 'soar':'soar',\n 'sonm':'sonm',\n 'soco':'soco',\n 'sosn':'sosn',\n 'show':'tvsh',\n 'iscompilation':'cpil',\n 'isgapless':'pgap',\n 'ispodcast':'pcst',\n 'track':'trkn',\n 'disk':'disk',\n 'tempo':'tmpo',\n }\n\ndescriptions = {\n 'title':'track title (text)',\n 'album':'album (text)',\n 'artist':'artist (text)',\n 'album artist':'album artist (text)',\n 'composer':'composer (text)',\n 'year':'year (text)',\n 'comment':'comment (text)',\n 'desc':'description (usually used in podcasts) (text)',\n 'ldesc':'long description (usually used in podcasts) (text)',\n 'date':'purchase date (text)',\n 'grouping':'grouping (text)',\n 'genre':'genre (text)',\n 'lyrics':'lyrics (text)',\n 'pURL':'podcast URL (text)',\n 'pepisode':'podcast episode GUID (text)',\n 'pcategory':'podcast category (text)',\n 'pkeywords':'podcast keywords (text)',\n 'enc':'encoded by (text)',\n 'copyright':'copyright (text)',\n 'soal':'album sort order (text)',\n 'soaa':'album artist sort order (text)',\n 'soar':'artist sort order (text)',\n 'sonm':'title sort order (text)',\n 'soco':'composer sort order (text)',\n 'sosn':'show sort order (text)',\n 'show':'show name (text)',\n 'iscompilation':'part of a compilation (boolean)',\n 'isgapless':'part of a gapless album (boolean)',\n 'ispodcast':'podcast (iTunes reads this only on import) (boolean)',\n 'track':'track number, total tracks (tuple of ints)',\n 'disk':'disc number, total discs (tuple of ints)',\n 'tempo':'tempo/BPM (16-bit int)',\n }\n\nimport identifiers \nimport mutagen.mp4 \n\nclass mp4_identifier (identifiers.FileIdentifier):\n\n # --------------------------------------------------\n # required properties: \n # - name: str\n # - extensions: (str)\n # - defaultSettings: dict -- must be compatible with json.dump()\n # --------------------------------------------------\n name = 'MP4'\n extensions = (\n '.mp4',\n '.m4a',\n '.aac',\n '.mpeg',\n )\n\n\n defaultSettings = {\n 'storedFields':[\n 'track',\n 'title',\n 'album',\n 'disk',\n 'artist',\n 'composer',\n 'genre',\n 'comment',\n 'ldes',\n 'year',\n 'ispodcast',\n 'iscompilation',\n ],\n 'formatStringDefaults':{\n 'artist':'Unknown Artist',\n 'album':'Unknown Album',\n 'title':None,\n 'composer':None,\n 'genre':None,\n 'disk':None,\n 'comment':None,\n 'iscompilation':False,\n 'track':None,\n 'recordingType':'Music',\n },\n 'podcastPathStrings':( \n # note that there are defaults for each of these values...\n 'Podcasts/{album}',\n ), \n 'compilationPathStrings':( \n # note that there are defaults for each of these values...\n 'Music/Compilations/{album}',\n ), \n 'musicPathStrings':( \n # note that there are defaults for each of these values...\n 'Music/{artist}/{album}',\n ), \n 'fileNameStrings':(\n \"{track[0]:0>2} of {track[1]:0>2} {title}\",\n \"{track[0]:0>2} of {track[1]:0>2} {title[0]}\",\n \"{title}\",\n )\n }\n#TODO: get rid references of the defunct processFile() method (replaced with load())\n\n # ----------------------------------------\n # required method: load \n # ----------------------------------------\n def load(self,fh):\n \"\"\" This method is responsible for extracting data \n sufficient to: \n \n 1. the location where the file should reside in the archive\n 2. evaluate __eq__(self,other)\n 3. (optinally), suggest a name for the file in the directory.\n\n The only persistent data used to determing the above \n should be should be stored in the data attribute (or property)\n of an instance of this class\n\n PARAMETERS: \n \n @fh an object of the `file` type returned by calling: \n \n with `open(fileName,'rb')` as fh:\n identifier.load(fh)\n \"\"\"\n \n # mutagen mutagen.mp4.MP4 tries to `open(fh)` so we'll prevent this \n # from causing an error\n def pretendOpen(x,*args,**kwargs):\n return x\n mutagen.mp4.open = pretendOpen\n\n # READ THE FILE TAGS\n try:\n tags = mutagen.mp4.MP4(fh)\n except mutagen.mp4.MP4StreamInfoError:\n raise identifiers.InvalidFileError\n\n # ADD ASSORTED ID4 TAGS TO THE DICTIONARY SELF.DATA\n self.data = {}\n for desc in self.settings['storedFields']:\n try:\n val = tags[keysDict[desc]]\n except KeyError:\n next\n\n if isinstance(val,list):\n val = val[0]\n if isinstance(val,basestring):\n self.data[desc] = unicode(val).encode('utf-8')\n elif isinstance(val,bool):\n self.data[desc] = val\n elif isinstance(val,tuple) and all(isinstance(i,int) for i in val):\n self.data[desc] = val\n else:\n self.data[desc] = repr(val)\n\n # ----------------------------------------\n # optional read-only property: filename \n # ----------------------------------------\n @property\n def archiveName(self):\n \"\"\" This read-only property is responsible for suggesting a \n file name for the file within the archive.\n\n If no suggestion is made, this function should return `None`\n (implicitly).\n \"\"\"\n\n data = self.settings['formatStringDefaults'].copy()\n data.update(self.data)\n\n try: \n return identifiers.format(data,self.settings['fileNameStrings'])\n except: \n pass\n\n # ----------------------------------------\n # required read-only property: archivePath \n # ----------------------------------------\n @property\n def archivePath(self):\n \"\"\" This read-only property is responsible for determining the \n appropriate location of the file within the archive. The\n location should *only* depend on the attributes self.data\n and self.settings.\n \"\"\"\n\n data = self.settings['formatStringDefaults'].copy()\n data.update(self.data)\n\n if 'genre' in self.data and (u'Podcast' in self.data['genre']):\n return identifiers.format( data, self.settings['podcastPathStrings'])\n else:\n return identifiers.format( data, self.settings['musicPathStrings'])\n\n\n","sub_path":"identifiers/mp4_identifier.py","file_name":"mp4_identifier.py","file_ext":"py","file_size_in_byte":7440,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"243986026","text":"\"\"\"Testday01 URL Configuration\n\nThe `urlpatterns` list routes URLs to views. For more information please see:\n https://docs.djangoproject.com/en/1.11/topics/http/urls/\nExamples:\nFunction views\n 1. Add an import: from my_app import views\n 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')\nClass-based views\n 1. Add an import: from other_app.views import Home\n 2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')\nIncluding another URLconf\n 1. Import the include() function: from django.conf.urls import url, include\n 2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls'))\n\"\"\"\nfrom django.conf.urls import url, include\nfrom django.contrib import admin\nfrom . import views\n\n\nurlpatterns = [\n url(r'^admin/', admin.site.urls),\n # 访问路径是show/的时候, 交给views.show()去处理请求和响应\n url(r'^show/$', views.show),\n url(r'^show01/$', views.show01),\n # ��访问路径时 /show/四位数字/ 的时候\n url(r'^show/(\\d{4})/$', views.show02),\n url(r'^show/(\\d{4})/(\\d{1,2}?)/(\\d{1,2}?)$', views.show03),\n]\n\n# app路由\nurlpatterns += [\n url(r'^music/', include('music.urls')),\n url(r'^index/', include('index.urls')),\n url(r'^sport/', include('sport.urls')),\n url(r'^news/', include('news.urls')),\n]\n","sub_path":"PythonWeb/Django/1809/djangoproject/Testday01/Testday01/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1316,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"85939807","text":"\"\"\"\nTitle: Island Perimeter\n\nYou are given a map in form of a two-dimensional integer grid where 1 represents\nland and 0 represents water.\n\nGrid cells are connected horizontally/vertically (not diagonally). The grid is\ncompletely surrounded by water, and there is exactly one island (i.e., one or more\nconnected land cells).\n\nThe island doesn't have \"lakes\" (water inside that isn't connected to the water\naround the island). One cell is a square with side length 1. The grid is rectangular,\nwidth and height don't exceed 100. Determine the perimeter of the island.\n\nExample 1:\n\nInput:\n[[0,1,0,0],\n [1,1,1,0],\n [0,1,0,0],\n [1,1,0,0]]\n\nOutput: 16\n\nExplanation: The perimeter is the 16 yellow stripes in the image below:\n\n\n\"\"\"\n\nfrom typing import List\n\n\nclass Solution:\n\n def islandPerimeter(self, grid: List[List[int]]) -> int:\n perimeter = 0\n if grid:\n rows = len(grid)\n if rows:\n columns = len(grid[0])\n perimeter_grid = [[0 for _ in range(columns)] for _ in range(rows)]\n\n if grid[0][0] == 1:\n perimeter_grid[0][0] = 4\n\n for i in range(1, rows):\n if grid[i][0] == 1:\n perimeter_grid[i][0] = 4\n if grid[i - 1][0] == 1:\n perimeter_grid[i - 1][0] -= 1\n perimeter_grid[i][0] -= 1\n\n for j in range(1, columns):\n if grid[0][j] == 1:\n perimeter_grid[0][j] = 4\n if grid[0][j - 1] == 1:\n perimeter_grid[0][j - 1] -= 1\n perimeter_grid[0][j] -= 1\n\n for i in range(1, rows):\n for j in range(1, columns):\n if grid[i][j] == 1:\n perimeter_grid[i][j] = 4\n if grid[i - 1][j] == 1:\n perimeter_grid[i - 1][j] -= 1\n perimeter_grid[i][j] -= 1\n if grid[i][j - 1] == 1:\n perimeter_grid[i][j - 1] -= 1\n perimeter_grid[i][j] -= 1\n\n #print(\" perimeter_grid: \", perimeter_grid)\n\n for i in range(rows):\n for j in range(columns):\n perimeter += perimeter_grid[i][j]\n return perimeter\n\n\ndef get_test_case_1():\n return [\n [0,0,0,0],\n [0,0,0,0],\n [0,0,0,0],\n [0,0,0,0]\n ]\n\n\ndef get_test_case_2():\n return [\n [0,1,0,0],\n [1,1,1,0],\n [0,1,0,0],\n [1,1,0,0]\n ]\n\n\ndef get_test_case_3():\n return [\n [1,1,1,1],\n [1,1,1,1],\n [1,1,1,1],\n [1,1,1,1]\n ]\n\n\ndef test(got, expected):\n if got == expected:\n prefix = ' OK '\n else:\n prefix = ' X '\n print('{} got: {} expected: {}'.format(prefix, repr(got), repr(expected)))\n\n\nif __name__ == \"__main__\":\n solution = Solution()\n\n test(solution.islandPerimeter(get_test_case_1()), 0)\n test(solution.islandPerimeter(get_test_case_2()), 16)\n test(solution.islandPerimeter(get_test_case_3()), 16)\n","sub_path":"leetcode/30_day_leetcoding_challenge/202007/20200707_island_perimeter/island_perimeter_solution_1.py","file_name":"island_perimeter_solution_1.py","file_ext":"py","file_size_in_byte":3243,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"233658501","text":"# Chapter 6 implementation for Caesar Cipher\n\nmessage = \"This is my secret message.\"\nmessage = \"GUVF VF ZL FRPERG ZRFFNTR.\"\nkey = 13\n\n# mode can be either either \"encrypt\" or \"decrypt\"\nmode = \"encrypt\"\nmode = \"decrypt\"\n\n# The dictionary for valid letters\nLETTERS = \"ABCDEFGHIJKLMNOPQRSTUVWXYZ\"\n\ntranslated = \"\"\n\nmessage = message.upper()\n\nfor letter in message:\n index = LETTERS.find(letter)\n if index != -1:\n if mode == \"encrypt\":\n letter = LETTERS[(index + key) % 26]\n elif mode == \"decrypt\":\n letter = LETTERS[(index - key) % 26]\n else:\n print(\"Invalid execution mode. It can only be either 'encrypt' or 'decrypt'. Exit the program.\")\n break\n\n translated += letter\n\nprint(translated)","sub_path":"Caesar.py","file_name":"Caesar.py","file_ext":"py","file_size_in_byte":760,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"424822720","text":"# Copyright 2017, David Wilson\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# 1. Redistributions of source code must retain the above copyright notice,\n# this list of conditions and the following disclaimer.\n#\n# 2. Redistributions in binary form must reproduce the above copyright notice,\n# this list of conditions and the following disclaimer in the documentation\n# and/or other materials provided with the distribution.\n#\n# 3. Neither the name of the copyright holder nor the names of its contributors\n# may be used to endorse or promote products derived from this software without\n# specific prior written permission.\n#\n# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE\n# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR\n# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF\n# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS\n# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN\n# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)\n# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE\n# POSSIBILITY OF SUCH DAMAGE.\n\nfrom __future__ import absolute_import\nimport threading\nimport os\n\nimport mitogen\nimport mitogen.core\nimport mitogen.master\nimport mitogen.service\nimport mitogen.unix\nimport mitogen.utils\n\nimport ansible_mitogen.logging\nimport ansible_mitogen.services\n\n\nclass State(object):\n \"\"\"\n Process-global state that should persist across playbook runs.\n \"\"\"\n #: ProcessState singleton.\n _instance = None\n\n @classmethod\n def instance(cls):\n \"\"\"\n Fetch the ProcessState singleton, constructing it as necessary.\n \"\"\"\n if cls._instance is None:\n cls._instance = cls()\n return cls._instance\n\n def __init__(self):\n ansible_mitogen.logging.setup()\n self._setup_master()\n self._setup_services()\n\n def _setup_master(self):\n \"\"\"\n Construct a Router, Broker, and mitogen.unix listener\n \"\"\"\n self.router = mitogen.master.Router()\n self.router.responder.whitelist_prefix('ansible')\n self.router.responder.whitelist_prefix('ansible_mitogen')\n mitogen.core.listen(self.router.broker, 'shutdown', self.on_broker_shutdown)\n self.listener = mitogen.unix.Listener(self.router)\n os.environ['MITOGEN_LISTENER_PATH'] = self.listener.path\n if 'MITOGEN_ROUTER_DEBUG' in os.environ:\n self.router.enable_debug()\n\n def _setup_services(self):\n \"\"\"\n Construct a ContextService and a thread to service requests for it\n arriving from worker processes.\n \"\"\"\n self.service = ansible_mitogen.services.ContextService(self.router)\n self.service_thread = threading.Thread(target=self.service.run)\n self.service_thread.start()\n\n def on_broker_shutdown(self):\n \"\"\"\n Respond to the Router shutdown (indirectly triggered through exit of\n the main thread) by unlinking the listening socket. Ideally this would\n happen explicitly, but Ansible provides no hook to allow it.\n \"\"\"\n os.unlink(self.listener.path)\n self.service_thread.join(timeout=10)\n","sub_path":"ansible_mitogen/process.py","file_name":"process.py","file_ext":"py","file_size_in_byte":3582,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"286119479","text":"\nfrom __future__ import print_function\nimport os\nimport json\nimport time\nimport warnings\nimport argparse\nimport numpy as np\nfrom distutils.dir_util import mkpath\nfrom skimage import io\n\nimport torch\nimport torch.nn as nn\nimport torch.backends.cudnn as cudnn\nimport torchvision.transforms as transforms\nfrom torch.autograd import Variable\nimport scipy.io as sio\n\nprint(torch.__version__)\n\nfrom PIL import Image, ImageDraw\nfrom pyramid import build_sfd\nfrom layers import *\nimport cv2\nimport numpy as np\nimport math\nfrom random import randint\nimport sys\n\ncur_dir = os.path.dirname(__file__)\nsys.path.append(os.path.dirname(__file__) )\n\nos.environ[\"CUDA_VISIBLE_DEVICES\"]='0'\ntorch.cuda.set_device(0)\n\nprint('Loading model..')\nssd_net = build_sfd('test', 640, 2)\nnet = ssd_net\nnet.load_state_dict(torch.load( os.path.join(cur_dir, 'Res50_pyramid.pth')) )\nnet.cuda()\nnet.eval()\nprint('Finished loading model!')\n\n#parser = argparse.ArgumentParser()\n#parser.add_argument('--data_dir', default='ai_challenger_keypoint_test_a_20180103')\n#parser.add_argument('--out_dir', default='annotations')\n#parser.add_argument('--faces_out_dir', default='images_out')\n#parser.add_argument('--background_out_dir', default='images_out')\n#parser.add_argument('--image_dir', default='keypoint_test_a_images_20180103')\n#parser.add_argument('--json_file', default='keypoint_test_a_annotations_20180103.json')\n#parser.add_argument('--confidence', type=float, default=0.1)\n#args = parser.parse_args()\n\n# set variable paths to images and json file\n#image_dir = os.path.join(args.data_dir, args.image_dir)\n#images = os.listdir(image_dir)\n#print('images', len(images))\n\n#json_file = os.path.join(args.data_dir, args.json_file)\n#annos = json.load(open(json_file, 'r'))\n#print('annos', len(annos))\n\n#target_annotation_dir = os.path.join(args.out_dir)\n#mkpath(target_annotation_dir)\n#target_images_dir = args.faces_out_dir\n#mkpath(target_images_dir)\n#target_negative_images_dir = args.background_out_dir\n#mkpath(target_negative_images_dir)\n\n\n#start = time.time()\n#file_mapping = []\n\ndef detect_face(image, shrink, confidence):\n x = image\n\n shrink = 1.0\n if shrink != 1:\n x = cv2.resize(image, None, None, fx=shrink, fy=shrink, interpolation=cv2.INTER_LINEAR)\n\n width = x.shape[1]\n height = x.shape[0]\n x = x.astype(np.float32)\n x -= np.array([104, 117, 123],dtype=np.float32)\n\n x = torch.from_numpy(x).permute(2, 0, 1)\n x = x.unsqueeze(0)\n x = Variable(x.cuda(), volatile=True)\n\n net.priorbox = PriorBoxLayer(width,height)\n net.cuda()\n y = net(x)\n detections = y.data\n scale = torch.Tensor([width, height, width, height])\n\n boxes=[]\n scores = []\n for i in range(detections.size(1)):\n j = 0\n while detections[0,i,j,0] >= confidence:\n score = detections[0,i,j,0]\n pt = (detections[0, i, j, 1:]*scale).cpu().numpy()\n boxes.append([pt[0],pt[1],pt[2],pt[3]])\n scores.append(score)\n j += 1\n if j >= detections.size(2):\n break\n\n det_conf = np.array(scores)\n boxes = np.array(boxes)\n\n if boxes.shape[0] == 0:\n return np.array([[0,0,0,0,0.001]])\n\n det_xmin = boxes[:,0] / shrink\n det_ymin = boxes[:,1] / shrink\n det_xmax = boxes[:,2] / shrink\n det_ymax = boxes[:,3] / shrink\n det = np.column_stack((det_xmin, det_ymin, det_xmax, det_ymax, det_conf))\n\n keep_index = np.where(det[:, 4] >= 0)[0]\n det = det[keep_index, :]\n return det\n\ndef multi_scale_test(image, max_im_shrink, confidence):\n # shrink detecting and shrink only detect big face\n st = 0.5 if max_im_shrink >= 0.75 else 0.5 * max_im_shrink\n det_s = detect_face(image, st, confidence)\n if max_im_shrink > 0.75:\n det_s = np.row_stack((det_s,detect_face(image,0.75, confidence)))\n index = np.where(np.maximum(det_s[:, 2] - det_s[:, 0] + 1, det_s[:, 3] - det_s[:, 1] + 1) > 30)[0]\n det_s = det_s[index, :]\n # enlarge one times\n bt = min(2, max_im_shrink) if max_im_shrink > 1 else (st + max_im_shrink) / 2\n det_b = detect_face(image, bt, confidence)\n\n # enlarge small iamge x times for small face\n if max_im_shrink > 1.5:\n det_b = np.row_stack((det_b,detect_face(image,1.5, confidence)))\n if max_im_shrink > 2:\n bt *= 2\n while bt < max_im_shrink: # and bt <= 2:\n det_b = np.row_stack((det_b, detect_face(image, bt, confidence)))\n bt *= 2\n\n det_b = np.row_stack((det_b, detect_face(image, max_im_shrink, confidence)))\n\n # enlarge only detect small face\n if bt > 1:\n index = np.where(np.minimum(det_b[:, 2] - det_b[:, 0] + 1, det_b[:, 3] - det_b[:, 1] + 1) < 100)[0]\n det_b = det_b[index, :]\n else:\n index = np.where(np.maximum(det_b[:, 2] - det_b[:, 0] + 1, det_b[:, 3] - det_b[:, 1] + 1) > 30)[0]\n det_b = det_b[index, :]\n\n return det_s, det_b\n\ndef multi_scale_test_pyramid(image, max_shrink, confidence):\n # shrink detecting and shrink only detect big face\n det_b = detect_face(image, 0.25, confidence)\n index = np.where(\n np.maximum(det_b[:, 2] - det_b[:, 0] + 1, det_b[:, 3] - det_b[:, 1] + 1)\n > 30)[0]\n det_b = det_b[index, :]\n\n st = [1.25, 1.75, 2.25]\n for i in range(len(st)):\n if (st[i] <= max_shrink):\n det_temp = detect_face(image, st[i], confidence)\n # enlarge only detect small face\n if st[i] > 1:\n index = np.where(\n np.minimum(det_temp[:, 2] - det_temp[:, 0] + 1,\n det_temp[:, 3] - det_temp[:, 1] + 1) < 100)[0]\n det_temp = det_temp[index, :]\n else:\n index = np.where(\n np.maximum(det_temp[:, 2] - det_temp[:, 0] + 1,\n det_temp[:, 3] - det_temp[:, 1] + 1) > 30)[0]\n det_temp = det_temp[index, :]\n det_b = np.row_stack((det_b, det_temp))\n return det_b\n\ndef flip_test(image, shrink, confidence):\n image_f = cv2.flip(image, 1)\n det_f = detect_face(image_f, shrink, confidence)\n\n det_t = np.zeros(det_f.shape)\n det_t[:, 0] = image.shape[1] - det_f[:, 2]\n det_t[:, 1] = det_f[:, 1]\n det_t[:, 2] = image.shape[1] - det_f[:, 0]\n det_t[:, 3] = det_f[:, 3]\n det_t[:, 4] = det_f[:, 4]\n return det_t\n\ndef bbox_vote(det):\n order = det[:, 4].ravel().argsort()[::-1]\n det = det[order, :]\n while det.shape[0] > 0:\n # IOU\n area = (det[:, 2] - det[:, 0] + 1) * (det[:, 3] - det[:, 1] + 1)\n xx1 = np.maximum(det[0, 0], det[:, 0])\n yy1 = np.maximum(det[0, 1], det[:, 1])\n xx2 = np.minimum(det[0, 2], det[:, 2])\n yy2 = np.minimum(det[0, 3], det[:, 3])\n w = np.maximum(0.0, xx2 - xx1 + 1)\n h = np.maximum(0.0, yy2 - yy1 + 1)\n inter = w * h\n o = inter / (area[0] + area[:] - inter)\n\n # get needed merge det and delete these det\n merge_index = np.where(o >= 0.3)[0]\n det_accu = det[merge_index, :]\n det = np.delete(det, merge_index, 0)\n\n if merge_index.shape[0] <= 1:\n continue\n det_accu[:, 0:4] = det_accu[:, 0:4] * np.tile(det_accu[:, -1:], (1, 4))\n max_score = np.max(det_accu[:, 4])\n det_accu_sum = np.zeros((1, 5))\n det_accu_sum[:, 0:4] = np.sum(det_accu[:, 0:4], axis=0) / np.sum(det_accu[:, -1:])\n det_accu_sum[:, 4] = max_score\n try:\n dets = np.row_stack((dets, det_accu_sum))\n except:\n dets = det_accu_sum\n\n dets = dets[0:750, :]\n return dets\n\n#def write_to_txt(f, det, image_path):\n# f.write('{:s}\\n'.format(image_path))\n# f.write('{:d}\\n'.format(det.shape[0]))\n# for i in range(det.shape[0]):\n# xmin = det[i][0]\n# ymin = det[i][1]\n# xmax = det[i][2]\n# ymax = det[i][3]\n# score = det[i][4]\n# f.write('{:.1f} {:.1f} {:.1f} {:.1f} {:.3f}\\n'.\n# format(xmin, ymin, (xmax - xmin + 1), (ymax - ymin + 1), score))\n\n\n#def generate_neg_samples(image, det_list):\n# height, width, channels = image.shape\n# neg_samples_list = []\n\n# for i in range( len(det_list) ):\n# for det in det_list:\n# try:\n# x = randint(1, width - 150)\n# y = randint(1, height - 150)\n# box_size = randint(100, 220)\n# if (det[0] > x and det[0]< x+box_size) or (det[1] > y and det[1] < y+box_size) or (det[2] > x and det[2]< x+box_size) or (det[3] > y and det[3] < y+box_size) or ((det[2]-det[0])/2 > x and (det[2]-det[0])/2 < x+box_size) or ((det[3]-det[1])/2 > y and (det[3]-det[1])/2 < y+box_size):\n# continue\n# else:\n# neg_samples_list.append([x, y, min(x+box_size, width-1), min(y+box_size, height-1)])\n# break\n# \n# except: \n# continue\n#\n# return neg_samples_list\n\n\n'''\nfor idx, anno in enumerate(annos):\n # Print status.\n if (idx + 1) % 1000 == 0 or (idx + 1) == len(annos):\n print(str(idx + 1) + ' / ' + str(len(annos)) + \"test\")\n\n # read images\n image_path = image_dir + \"/\" + anno['image_id'] + '.jpg';\n image = cv2.imread(image_dir + \"/\" + anno['image_id'] + '.jpg', cv2.IMREAD_COLOR)\n print (image_path)\n\n max_im_shrink = (0x7fffffff / 200.0 / (image.shape[0] * image.shape[1])) ** 0.4 # the max size of input image for caffe\n max_im_shrink = 3 if max_im_shrink > 3 else max_im_shrink\n shrink = max_im_shrink if max_im_shrink < 1 else 1\n \n # start detection\n det0 = detect_face(image, shrink) # origin test\n det1 = flip_test(image, shrink) # flip test\n [det2, det3] = multi_scale_test(image, max_im_shrink) #min(2,1400/min(image.shape[0],image.shape[1]))) #multi-scale test\n det4 = multi_scale_test_pyramid(image, max_im_shrink)\n det = np.row_stack((det0, det1, det2, det3, det4))\n dets = bbox_vote(det)\n\n # read keypoints from json\n Keypoints_list = []\n keypoints_all = anno['keypoint_annotations']\n #print(keypoints_all)\n for key, value in keypoints_all.iteritems():\n #print(value)\n Keypoints_list.append(value[36:]) # last 6 elements contain head and neck info\n #print(Keypoints_list )\n #print(Keypoints_list[0][1])\n \n count = 0\n height, width, channels = image.shape\n det_list = []\n for i in range(dets.shape[0]):\n xmin = int(dets[i][0])\n ymin = int(dets[i][1])\n xmax = int(dets[i][2])\n ymax = int(dets[i][3])\n score = dets[i][4]\n #det_list.append([xmin, ymin, xmax, ymax])\n\n #if score > args.confidence:\n padding = 25\n xmin_c = max(0, xmin- padding)\n ymin_c = max(0, ymin- padding)\n xmax_c = min(width, xmax+ padding)\n ymax_c = min(height, ymax+ padding)\n det_list.append([xmin_c, ymin_c, xmax_c, ymax_c])\n print(\"face_bound: \", xmin_c, ymin_c, xmax_c, ymax_c, score)\n \n for idx, human in enumerate(Keypoints_list):\n #print(\"human: \", human)\n if human[0] >= xmin_c and human[0] <= xmax_c and human[3] >= xmin_c and human[3] <= xmax_c and human[1] >= (ymin_c-20) and human[1] <= (ymax_c+20) and human[4] >= (ymin_c-20) and human[4] <= (ymax_c+20):\n\n face_crop = image[ymin_c:ymax_c, xmin_c:xmax_c]\n face_resized = cv2.resize(face_crop, (224, 224))\n #cv2.imshow(\"img_crop\", face_resized)\n #cv2.waitKey(0)\n face_name = target_images_dir + \"/\" + anno['image_id'] + '_' + str(count) +'.jpg'\n face_out = cv2.imwrite(face_name, face_resized)\n count+=1\n #cv2.rectangle(image, (int(xmin_c),int(ymin_c)), (int(xmax_c),int(ymax_c)), (0, 255, 0), 1)\n #cv2.circle(image,(human[0],human[1]), 3, (0,0,255), -1)\n #cv2.circle(image,(human[3],human[4]), 3, (0,0,255), -1)\n del Keypoints_list[idx]\n\n #cv2.imshow(\"img\", image)\n #cv2.waitKey(0)\n \n count_neg = 0\n neg_boxes = generate_neg_samples(image, det_list)\n for item in neg_boxes:\n crop = image[item[1]:item[3], item[0]:item[2]]\n resized = cv2.resize(crop, (224, 224))\n name = target_negative_images_dir + \"/\" + anno['image_id'] + '_' + str(count_neg) +'.jpg'\n out = cv2.imwrite(name, resized)\n count_neg += 1\n\n\n #image_annotation_path = target_annotation_dir + \"/\" + anno['image_id'] + '.txt';\n #print(image_annotation_path)\n #f = open(image_annotation_path, 'w')\n #write_to_txt(f, dets, image_path)\n\nprint('Successfully processed all the images in %.2f seconds.' % (time.time() - start))\n'''\n\n","sub_path":"scripts/utils/PyramidBox-Pytorch/detection_fns.py","file_name":"detection_fns.py","file_ext":"py","file_size_in_byte":12679,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"271208562","text":"#ODEV1\n\nn = int(input())\nfor i in range(n):\n print((\"#\"*(i+1)).rjust(n))\n\n#ODEV2\n\nfirst_multiple_input =input().rstrip().split()\narr = list(map(int, input().rstrip().split()))\nbrr = list(map(int, input().rstrip().split()))\n\nliste=[i for i in range(max(arr),min(brr)+1) for j in arr if i%j==0]\nb=[i for i in liste if liste.count(i)==int(first_multiple_input[0])]\nliste2=[i for i in set(b) for j in brr if j%i==0]\nc=[i for i in liste2 if liste2.count(i)==int(first_multiple_input[1])]\n\nprint(len(set(c)))\n\n# ODEV3\n\nnk = list(map(int, input().rstrip().split()))\nar = list(map(int, input().rstrip().split()))\n\nprint(len([[ar[i],ar[j]] for i in range(nk[0]) for j in range(nk[0]) if (ar[i]+ar[j])%nk[1]==0 and i= 0 and hour < 12:\n speak(\"Good Morning Sir!\")\n \n elif hour >= 12 and hour < 18:\n speak(\"Good Afternoon Sir!\")\n\n else:\n speak(\"Good Evening Sir!\")\n\n speak(\"please tell Me How may i help you \")\n\n\ndef takecommand():\n r = sr.Recognizer()\n with sr.Microphone() as source:\n print(\"Listening...\")\n r.pause_threshold = 1\n r.energy_threshold = 300\n audio = r.listen(source)\n\n try:\n print(\"Recognizing....\")\n query = r.recognize_google(audio, language='en-in')\n print(f\"User Said: {query}\\n\")\n\n except Exception as e:\n print(e)\n print(\"Say That again please\")\n speak(\"Say That again please\")\n return \"None\"\n return query\n\n\ndef beginner():\n r = sr.Recognizer()\n with sr.Microphone() as source:\n print(\"Say the command to activate....\")\n r.pause_threshold = 1\n r.energy_threshold = 400\n audio = r.listen(source)\n\n try:\n print(\"Recognizing....\")\n command = r.recognize_google(audio, language='en-in')\n print(f\"User Said: {command}\\n\")\n\n except Exception as e:\n print(e)\n return \"None\"\n return command\n\n\nemail_id = os.environ['email_id']\nemail_pswd = os.environ['email_pswd']\n\ndef sendemail(to, content):\n server = smtplib.SMTP('smtp.gmail.com', 587)\n server.ehlo()\n server.starttls()\n server.login(email_id, email_pswd)\n server.sendmail(email_id, to, content)\n server.close()\n\n\nwhile True:\n command = beginner().lower()\n if \"jarvis\" in command:\n wishme()\n while True:\n query = takecommand().lower()\n\n if \"search wikipedia for\" in query:\n speak(\"Surfing through wikipedia...\")\n query = query.replace(\"search wikipedia for\", \"\")\n results = wikipedia.summary(query, sentences=2)\n speak(\"I found that\")\n print(results)\n speak(results)\n\n elif 'open youtube' in query:\n webbrowser.open(\"www.youtube.com\")\n\n elif 'open google' in query:\n webbrowser.open(\"www.google.com\")\n\n elif 'open whatsapp' in query:\n webbrowser.open(\"https://web.whatsapp.com/\")\n\n elif 'open stack overflow' in query:\n webbrowser.open(\"www.stackoverflow.com\")\n\n elif 'open github' in query:\n webbrowser.open(\"www.github.com\")\n\n elif 'open facebook' in query:\n webbrowser.open(\"www.facebook.com\")\n\n elif 'open snapchat' in query:\n webbrowser.open(\"www.snapchat.com\")\n\n elif 'open instagram' in query:\n webbrowser.open(\"www.instagram.com\")\n\n elif 'play music' in query:\n music_dir = 'C:\\\\music'\n songs = os.listdir(music_dir)\n print(songs)\n os.startfile(os.path.join(music_dir, random.choice(songs)))\n\n elif 'the time' in query:\n strTime = datetime.datetime.now().strftime(\"%H:%M:%S\")\n print(strTime)\n speak(f\"Sir the time is {strTime}\")\n\n elif \"the date\" in query:\n day = int(datetime.datetime.now().day)\n month = int(datetime.datetime.now().month)\n year = int(datetime.datetime.now().year)\n print(f\"{day}/{month}/{year}\")\n speak(f\"sir the date is {day} {month} {year}\")\n\n elif 'open code' in query:\n codePath = \"C:\\Microsoft VS Code\\Code.exe\"\n os.startfile(codePath)\n\n elif 'open chrome' in query:\n codePath = \"C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe\"\n os.startfile(codePath)\n\n elif 'open edge' in query:\n codePath = \"C:\\Program Files (x86)\\Microsoft\\Edge\\Application\\msedge.exe\"\n os.startfile(codePath)\n\n elif 'send an email' in query:\n try:\n query = query.replace(\"send an email to\", \"\")\n speak(\"what should i send\")\n content = takecommand()\n to = emails[query]\n sendemail(to, content)\n speak(\"Email has been sucessfully sent\")\n except Exception as e:\n print(e)\n speak(\"Sorry Boss! i am not able to send the email\")\n\n elif 'send whatsapp message' in query:\n speak(\"whom should i send the message to ?\")\n contact_name = takecommand().lower()\n speak(\"what should i send\")\n message = takecommand()\n pywhatkit.sendwhatmsg_instantly(numbers[contact_name], message)\n pyautogui.press(\"enter\", 1, 5)\n \n\n elif 'group message' in query:\n speak(\"what shld i send\")\n hour = int(datetime.datetime.now().hour)\n minute = int(datetime.datetime.now().minute) + 0.2\n group_message = takecommand()\n codePath = \"C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe\"\n os.startfile(codePath)\n pywhatkit.sendwhatmsg_to_group(\"L05OubINfe5226ZEMAZEVP\", group_message, 18, 00, 2)\n\n elif 'web search' in query:\n speak(\"From google i found that\")\n query = query.replace(\"web search\", \"\")\n pywhatkit.search(query)\n\n elif \"shut down my laptop\" in query:\n pywhatkit.shutdown()\n\n elif \"cancel shutdown\" in query:\n pywhatkit.cancelShutdown()\n\n elif \"close jarvis\" in query:\n speak(\"Have a Good Day sir\")\n exit()\n\n elif \"show the weather\" in query:\n speak(\"which city's weather do you want to know about sir?\")\n user_api = \"1318a0fc30fc99cc8c183a4bfed36423\"\n weather_city = takecommand()\n api_link_complete = \"http://api.openweathermap.org/data/2.5/weather?q=\"+weather_city+\"&appid=\"+user_api\n api_link = requests.get(api_link_complete)\n api_data = api_link.json()\n #api_data for the city is below#\n temp_city = ((api_data['main']['temp']) - 273.15)\n feel_temp = ((api_data['main']['feels_like']) - 273.15)\n weather_desc = api_data['weather'][0]['description']\n hmdt = api_data['main']['humidity']\n wind_spd = api_data['wind']['speed']\n print(\"---------------------------------------------------------------\")\n print(f\"weather stats for {weather_city} is\")\n print(\"---------------------------------------------------------------\")\n speak(f\"weather stats for {weather_city} is\")\n print(f\"The Temperature is {temp_city:.2f} degree celcius.You will feel the temperature to be {feel_temp:.2f} degree celcius.The Humidity is {hmdt}.Weather can be described as {weather_desc}.Wind is blowing at a speed of {wind_spd} Km/h\")\n speak(f\"The Temperature is {temp_city:.2f} degree celcius . You will feel the temperature to be {feel_temp:.2f} degree celcius . The Humidity is {hmdt} . Weather can be described as {weather_desc} . Wind is blowing at a speed of {wind_spd} kilometer per hour\")\n\n elif \"who are you\" in query:\n name = \"Jarvis\"\n created_on = datetime.date(2020, 5, 28)\n present_date = datetime.datetime.now().day\n present_month = datetime.datetime.now().month\n present_year = datetime.datetime.now().year\n created_date = 28\n created_month = 5\n created_year = 2021\n day_from_birth = abs(int(present_date) - int(created_date))\n year_from_birth = abs(int(present_year) - int(created_year))\n month_from_birth = abs(int(present_month) - int(created_month))\n\n speak(f\"Sir i am An Programme made to make Your work easier my name is {name} . I was created on {created_on} . i am {day_from_birth} days {month_from_birth} months {year_from_birth} years old . I am still Devloping\")\n\n\n\n elif \"play a song\" in query:\n speak(\"which song do you want to listen ? \")\n song_name = takecommand()\n pywhatkit.playonyt(song_name)\n\n \n \n elif \"volume up\" in query:\n pyautogui.press(\"volumeup\", 3)\n\n elif \"volume down\" in query:\n pyautogui.press(\"volumedown\", 3)\n\n elif \"volume mute\" in query:\n pyautogui.press(\"volumemute\")\n\n elif \"what are you doing\" in query:\n speak(\"Sir i am at your service . I listen to your commands and respond accordingly.\")\n\n\n elif \"how are you\" in query:\n speak(\"i am doing great . how about you sir ? \")\n speak(\"how's your day going ? \")\n answer = takecommand()\n if \"yes its a great day\" in answer:\n speak(\"awesome hope u enjoy a lot . \")\n\n elif \"lot of work to do\" in answer:\n speak(\"best of luck . sir you can upgrade me so that i can be of more help to you\")\n \n else:\n speak(\"sir are u doing well . you don't sound well ? \")\n answer_1 = takecommand()\n if \"yes i am fine\" in answer_1:\n speak(\"okay sir . do take a break periodically . hope your day goes well .\")\n elif \"no just a bit tired\" in answer_1:\n speak(\"sir i am closing the program and the device is going to sleep . do take care\")\n else:\n speak(\"may everyday be the most happiest day for you\")\n\n \n elif \"\" in query:\n speak(\"\")\n\n \n else:\n speak(\"Jarvis did not activate\")\n \n","sub_path":"jarvis.py","file_name":"jarvis.py","file_ext":"py","file_size_in_byte":11269,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"588443454","text":"from openerp import models, fields, api\nfrom openerp.tools.translate import _\nfrom lxml import etree\nfrom openerp.osv import osv\nfrom datetime import datetime\nfrom openerp.tools import DEFAULT_SERVER_DATE_FORMAT, DEFAULT_SERVER_DATETIME_FORMAT, DATETIME_FORMATS_MAP\nfrom openerp.tools.float_utils import float_compare\n\n\nclass PurchaseOrder(models.Model):\n\n _inherit = \"purchase.order\"\n\n cost_center_id = fields.Many2one('account.cost.center', 'Cost center', required=True,\n domain=[('active_center', '=', True)])\n\n def fields_view_get(self, cr, uid, view_id=None, view_type='form',\n context=None, toolbar=False, submenu=False):\n res = super(PurchaseOrder, self).fields_view_get(\n cr, uid, view_id=view_id, view_type=view_type,\n context=context, toolbar=toolbar, submenu=False)\n if not context:\n context = {}\n if not context.get('cost_center_default', False):\n if view_type == 'form':\n view_obj = etree.XML(res['arch'])\n invoice_line = view_obj.xpath(\"//field[@name='order_line']\")\n extra_ctx = \"'cost_center_default': 1, \" \\\n \"'cost_center_id': cost_center_id\"\n for el in invoice_line:\n ctx = el.get('context')\n if ctx:\n ctx_strip = ctx.rstrip(\"}\").strip().rstrip(\",\")\n ctx = ctx_strip + \", \" + extra_ctx + \"}\"\n else:\n ctx = \"{\" + extra_ctx + \"}\"\n el.set('context', str(ctx))\n res['arch'] = etree.tostring(view_obj)\n return res\n\n def _prepare_inv_line(self, cr, uid, account_id, order_line, context=None):\n \"\"\"Collects require data from purchase order line that is used to create invoice line\n for that purchase order line\n :param account_id: Expense account of the product of PO line if any.\n :param browse_record order_line: Purchase order line browse record\n :return: Value for fields of invoice lines.\n :rtype: dict\n \"\"\"\n return {\n 'name': order_line.name,\n 'account_id': account_id,\n 'price_unit': order_line.price_unit or 0.0,\n 'quantity': order_line.product_qty,\n 'product_id': order_line.product_id.id or False,\n 'uos_id': order_line.product_uom.id or False,\n 'invoice_line_tax_id': [(6, 0, [x.id for x in order_line.taxes_id])],\n 'account_analytic_id': order_line.account_analytic_id.id or False,\n 'cost_center_id': order_line.cost_center_id.id,\n 'purchase_line_id': order_line.id,\n }\n\n def _prepare_invoice(self, cr, uid, order, line_ids, context=None):\n \"\"\"Prepare the dict of values to create the new invoice for a\n purchase order. This method may be overridden to implement custom\n invoice generation (making sure to call super() to establish\n a clean extension chain).\n\n :param browse_record order: purchase.order record to invoice\n :param list(int) line_ids: list of invoice line IDs that must be\n attached to the invoice\n :return: dict of value to create() the invoice\n \"\"\"\n journal_ids = self.pool['account.journal'].search(\n cr, uid, [('type', '=', 'purchase'),\n ('company_id', '=', order.company_id.id)],\n limit=1)\n if not journal_ids:\n raise osv.except_osv(\n _('Error!'),\n _('Define purchase journal for this company: \"%s\" (id:%d).') % \\\n (order.company_id.name, order.company_id.id))\n return {\n 'name': order.partner_ref or order.name,\n 'reference': order.partner_ref or order.name,\n 'account_id': order.partner_id.property_account_payable.id,\n 'type': 'in_invoice',\n 'partner_id': order.partner_id.id,\n 'currency_id': order.currency_id.id,\n 'journal_id': len(journal_ids) and journal_ids[0] or False,\n 'invoice_line': [(6, 0, line_ids)],\n 'origin': order.name,\n 'fiscal_position': order.fiscal_position.id or False,\n 'payment_term': order.payment_term_id.id or False,\n 'company_id': order.company_id.id,\n 'cost_center_id': order.cost_center_id.id,\n }\n\n\n def action_invoice_create(self, cr, uid, ids, context=None):\n \"\"\"Generates invoice for given ids of purchase orders and links that invoice ID to purchase order.\n :param ids: list of ids of purchase orders.\n :return: ID of created invoice.\n :rtype: int\n \"\"\"\n context = dict(context or {})\n\n inv_obj = self.pool.get('account.invoice')\n inv_line_obj = self.pool.get('account.invoice.line')\n\n res = False\n uid_company_id = self.pool.get('res.users').browse(cr, uid, uid, context=context).company_id.id\n for order in self.browse(cr, uid, ids, context=context):\n context.pop('force_company', None)\n if order.company_id.id != uid_company_id:\n #if the company of the document is different than the current user company, force the company in the context\n #then re-do a browse to read the property fields for the good company.\n context['force_company'] = order.company_id.id\n order = self.browse(cr, uid, order.id, context=context)\n\n # generate invoice line correspond to PO line and link that to created invoice (inv_id) and PO line\n inv_lines = []\n for po_line in order.order_line:\n if po_line.state == 'cancel':\n continue\n acc_id = self._choose_account_from_po_line(cr, uid, po_line, context=context)\n inv_line_data = self._prepare_inv_line(cr, uid, acc_id, po_line, context=context)\n inv_line_id = inv_line_obj.create(cr, uid, inv_line_data, context=context)\n inv_lines.append(inv_line_id)\n po_line.write({'invoice_lines': [(4, inv_line_id)]})\n\n # get invoice data and create invoice\n inv_data = self._prepare_invoice(cr, uid, order, inv_lines, context=context)\n inv_id = inv_obj.create(cr, uid, inv_data, context=context)\n\n # compute the invoice\n inv_obj.button_compute(cr, uid, [inv_id], context=context, set_total=True)\n\n # Link this new invoice to related purchase order\n order.write({'invoice_ids': [(4, inv_id)]})\n res = inv_id\n return res\n\n\nclass Sale(models.Model):\n\n _inherit = \"purchase.order.line\"\n\n @api.model\n def _default_cost_center(self):\n return self._context.get('cost_center_id') \\\n or self.env['account.cost.center']\n\n last_purchase_price = fields.Float('Last Purchase Price', required=True)\n cost_center_id = fields.Many2one('account.cost.center', 'Cost center', required=True,\n domain=[('active_center', '=', True)], default=_default_cost_center)\n\n @api.onchange('cost_center_id')\n def onchange_cost_center(self):\n if self.cost_center_id:\n self.account_analytic_id = self.cost_center_id.purchase_account_id.id\n else:\n self.account_analytic_id = False\n\n def onchange_product_id(self, cr, uid, ids, pricelist_id, product_id, qty, uom_id,\n partner_id, date_order=False, fiscal_position_id=False, date_planned=False,\n name=False, price_unit=False, state='draft', context=None):\n \"\"\"\n onchange handler of product_id.\n \"\"\"\n if context is None:\n context = {}\n\n res = {'value': {'price_unit': price_unit or 0.0, 'name': name or '', 'product_uom' : uom_id or False}}\n if not product_id:\n return res\n\n product_product = self.pool.get('product.product')\n product_uom = self.pool.get('product.uom')\n res_partner = self.pool.get('res.partner')\n product_pricelist = self.pool.get('product.pricelist')\n account_fiscal_position = self.pool.get('account.fiscal.position')\n account_tax = self.pool.get('account.tax')\n\n # - check for the presence of partner_id and pricelist_id\n #if not partner_id:\n # raise osv.except_osv(_('No Partner!'), _('Select a partner in purchase order to choose a product.'))\n #if not pricelist_id:\n # raise osv.except_osv(_('No Pricelist !'), _('Select a price list in the purchase order form before choosing a product.'))\n\n # - determine name and notes based on product in partner lang.\n context_partner = context.copy()\n if partner_id:\n lang = res_partner.browse(cr, uid, partner_id).lang\n context_partner.update( {'lang': lang, 'partner_id': partner_id} )\n product = product_product.browse(cr, uid, product_id, context=context_partner)\n #call name_get() with partner in the context to eventually match name and description in the seller_ids field\n if not name or not uom_id:\n # The 'or not uom_id' part of the above condition can be removed in master. See commit message of the rev. introducing this line.\n dummy, name = product_product.name_get(cr, uid, product_id, context=context_partner)[0]\n if product.description_purchase:\n name += '\\n' + product.description_purchase\n res['value'].update({'name': name})\n\n # - set a domain on product_uom\n res['domain'] = {'product_uom': [('category_id','=',product.uom_id.category_id.id)]}\n\n # - check that uom and product uom belong to the same category\n product_uom_po_id = product.uom_po_id.id\n if not uom_id:\n uom_id = product_uom_po_id\n\n if product.uom_id.category_id.id != product_uom.browse(cr, uid, uom_id, context=context).category_id.id:\n if context.get('purchase_uom_check') and self._check_product_uom_group(cr, uid, context=context):\n res['warning'] = {'title': _('Warning!'), 'message': _('Selected Unit of Measure does not belong to the same category as the product Unit of Measure.')}\n uom_id = product_uom_po_id\n\n res['value'].update({'product_uom': uom_id})\n\n # - determine product_qty and date_planned based on seller info\n if not date_order:\n date_order = fields.datetime.now()\n\n\n supplierinfo = False\n precision = self.pool.get('decimal.precision').precision_get(cr, uid, 'Product Unit of Measure')\n for supplier in product.seller_ids:\n if partner_id and (supplier.name.id == partner_id):\n supplierinfo = supplier\n if supplierinfo.product_uom.id != uom_id:\n res['warning'] = {'title': _('Warning!'), 'message': _('The selected supplier only sells this product by %s') % supplierinfo.product_uom.name }\n min_qty = product_uom._compute_qty(cr, uid, supplierinfo.product_uom.id, supplierinfo.min_qty, to_uom_id=uom_id)\n if float_compare(min_qty , qty, precision_digits=precision) == 1: # If the supplier quantity is greater than entered from user, set minimal.\n if qty:\n res['warning'] = {'title': _('Warning!'), 'message': _('The selected supplier has a minimal quantity set to %s %s, you should not purchase less.') % (supplierinfo.min_qty, supplierinfo.product_uom.name)}\n qty = min_qty\n dt = self._get_date_planned(cr, uid, supplierinfo, date_order, context=context).strftime(DEFAULT_SERVER_DATETIME_FORMAT)\n qty = qty or 1.0\n res['value'].update({'date_planned': date_planned or dt})\n if qty:\n res['value'].update({'product_qty': qty})\n\n price = price_unit\n if price_unit is False or price_unit is None:\n # - determine price_unit and taxes_id\n if pricelist_id:\n date_order_str = datetime.strptime(date_order, DEFAULT_SERVER_DATETIME_FORMAT).strftime(DEFAULT_SERVER_DATE_FORMAT)\n price = product_pricelist.price_get(cr, uid, [pricelist_id],\n product.id, qty or 1.0, partner_id or False, {'uom': uom_id, 'date': date_order_str})[pricelist_id]\n else:\n price = product.standard_price\n\n taxes = account_tax.browse(cr, uid, map(lambda x: x.id, product.supplier_taxes_id))\n fpos = fiscal_position_id and account_fiscal_position.browse(cr, uid, fiscal_position_id, context=context) or False\n taxes_ids = account_fiscal_position.map_tax(cr, uid, fpos, taxes)\n po_line_obj = self.pool.get('purchase.order.line')\n po_rcd = po_line_obj.search(cr, uid, [('product_id', '=', product_id)], limit=1, order='id DESC')\n if po_rcd:\n last_price = po_line_obj.browse(cr, uid, po_rcd).price_unit\n res['value'].update({'price_unit': price, 'taxes_id': taxes_ids, 'last_purchase_price': last_price})\n else:\n res['value'].update({'last_purchase_price': price, 'price_unit': price, 'taxes_id': taxes_ids})\n return res\n","sub_path":"brothers/steel_accounts/models/purchase.py","file_name":"purchase.py","file_ext":"py","file_size_in_byte":13397,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"76590008","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\nfrom django.db import models\nfrom django.utils.safestring import mark_safe\nfrom django.utils.translation import ugettext_lazy as _\nfrom cms.models.pluginmodel import CMSPlugin\nfrom django.utils.encoding import python_2_unicode_compatible, force_text\n\n\n@python_2_unicode_compatible\nclass ContainerPlugin(CMSPlugin):\n\n FULL_WIDTH = 100\n THREE_QUARTER_WIDTH = 75\n TWO_THIRD_WIDTH = 66\n HALF_WIDTH = 50\n THIRD_WIDTH = 33\n QUARTER_WIDTH = 25\n\n NO_MARGIN = _('No margin')\n ONE_COL_MARGIN = '8.33%'\n TWO_COL_MARGIN = '16.66%'\n THREE_COL_MARGIN = '25%'\n FOUR_COL_MARGIN = '33.33%'\n\n CONTAINER_TYPES = [\n (0, _('One tile - full width')),\n (1, _('Two tiles - 50 | 50')),\n (2, _('Two tiles - 25 | 75')),\n (3, _('Two tiles - 75 | 25')),\n (4, _('Two tiles - 33 | 66')),\n (5, _('Two tiles - 66 | 33')),\n (6, _('Three tiles - 33 | 33 | 33')),\n (7, _('Three tiles - 25 | 25 | 50')),\n (8, _('Three tiles - 25 | 50 | 25')),\n (9, _('Three tiles - 50 | 25 | 25')),\n (10, _('Four tiles - 25 | 25 | 25 | 25')),\n ]\n\n TYPE_COLUMNS = {\n 0: [FULL_WIDTH],\n 1: [HALF_WIDTH, HALF_WIDTH],\n 2: [QUARTER_WIDTH, THREE_QUARTER_WIDTH],\n 3: [THREE_QUARTER_WIDTH, QUARTER_WIDTH],\n 4: [THIRD_WIDTH, TWO_THIRD_WIDTH],\n 5: [TWO_THIRD_WIDTH, THIRD_WIDTH],\n 6: [THIRD_WIDTH, THIRD_WIDTH, THIRD_WIDTH],\n 7: [QUARTER_WIDTH, QUARTER_WIDTH, HALF_WIDTH],\n 8: [QUARTER_WIDTH, HALF_WIDTH, QUARTER_WIDTH],\n 9: [HALF_WIDTH, QUARTER_WIDTH, QUARTER_WIDTH],\n 10: [QUARTER_WIDTH, QUARTER_WIDTH, QUARTER_WIDTH, QUARTER_WIDTH]\n }\n\n MARGIN_TYPES = (\n (0, NO_MARGIN),\n (1, ONE_COL_MARGIN),\n (2, TWO_COL_MARGIN),\n (3, THREE_COL_MARGIN),\n (4, FOUR_COL_MARGIN)\n )\n\n container_type = models.IntegerField(choices=CONTAINER_TYPES, null=False, blank=False, default=TYPE_COLUMNS[0])\n\n margin = models.IntegerField(choices=MARGIN_TYPES, null=False, blank=False, default=MARGIN_TYPES[0][0],\n help_text=_('How much margin is needed on the left and right side?'))\n\n # To achieve same height columns we use the CSS3 flex box grid. For more information about it have a look at\n # http://caniuse.com/flexbox\n equal_height = models.BooleanField(verbose_name=_('Align Content Height'),\n help_text=_('Align height of all columns in this row. Please note: '\n 'This setting is not supported by Internet Explorer 9 and below.'),\n null=False, blank=False, default=False)\n\n css_classes = models.CharField(max_length=512, blank=True, null=True)\n\n @property\n def max_children(self):\n return len(self.TYPE_COLUMNS[self.container_type])\n\n def __str__(self):\n name = self.CONTAINER_TYPES[self.container_type][1]\n if self.num_children() > self.max_children:\n name = 'Warning, too many tiles! {}'.format(name)\n\n return mark_safe(force_text(name))\n","sub_path":"layouter/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":3218,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"215400851","text":"#!/usr/bin/env python\n# Build the project on Travis CI.\n\nfrom __future__ import print_function\nimport mmap, os, re, shutil, tempfile, zipfile\nfrom bootstrap import bootstrap\nfrom download import Downloader\nfrom subprocess import call, check_call, check_output, Popen, PIPE, STDOUT\n\ndef extract_docs(output_dir):\n \"Extract the AMPLGSL documentation from the code.\"\n output = None\n dir = os.path.dirname(__file__)\n output_dir = os.path.join(output_dir, 'amplgsl')\n if not os.path.exists(output_dir):\n os.mkdir(output_dir)\n with open(os.path.join(dir, '../src/gsl/amplgsl.c'), 'r+b') as input:\n map = mmap.mmap(input.fileno(), 0)\n for i in re.finditer(r'/\\*\\*(.*?)\\*/', map, re.DOTALL):\n s = re.sub(r'\\n +\\* ?', r'\\n', i.group(1))\n s = re.sub(r'\\$(.+?)\\$', r':math:`\\1`', s, flags=re.DOTALL)\n m = re.search(r'@file (.*)', s)\n if m:\n filename = m.group(1)\n if output:\n output.close()\n output = open(os.path.join(output_dir, filename + '.rst'), 'w')\n s = s[:m.start()] + s[m.end():]\n output.write(s.rstrip(' '))\n map.close()\n\ndef get_mp_version():\n filename = os.path.join(os.path.dirname(__file__), '..', 'CMakeLists.txt')\n with open(filename, 'r') as f:\n for line in f:\n m = re.search(r'MP_VERSION (\\d+\\.\\d+\\.\\d+)', line)\n if m:\n return m.group(1)\n\ndef pip_install(package, commit):\n \"Install package from GitHub using pip.\"\n check_call(['pip', 'install',\n 'git+git://github.com/{0}.git@{1}'.format(package, commit)])\n\ndef build_docs(workdir, travis):\n # Install dependencies.\n if travis:\n check_call(['sudo', 'apt-get', 'install', 'python-virtualenv', 'doxygen'])\n # Create virtualenv.\n virtualenv_dir = os.path.join(workdir, 'virtualenv')\n check_call(['virtualenv', virtualenv_dir])\n activate_this_file = os.path.join(virtualenv_dir, 'bin', 'activate_this.py')\n execfile(activate_this_file, dict(__file__=activate_this_file))\n # Install Sphinx and Breathe.\n pip_install('sphinx-doc/sphinx', 'a1a80ab509fbf01aa459e0ec5a5c9b66f011ee47')\n pip_install('michaeljones/breathe', '4dd996b9789f851ed32e35d9cae173508582ff74')\n # Clone the ampl.github.io repo.\n repo = 'ampl.github.io'\n check_call(['git', 'clone', 'https://github.com/ampl/{}.git'.format(repo)],\n cwd=workdir)\n repo_dir = os.path.join(workdir, repo)\n # Copy API docs and the database connection guides to the build directory.\n # The guides are not stored in the mp repo to avoid polluting history with\n # image blobs.\n build_dir = os.path.join(workdir, 'build')\n shutil.copytree(os.path.join(repo_dir, 'src'), build_dir)\n for entry in os.listdir('doc'):\n src = os.path.join('doc', entry)\n dst = os.path.join(build_dir, entry)\n if os.path.isdir(src):\n shutil.copytree(src, dst)\n else:\n shutil.copyfile(src, dst)\n # Remove generated content.\n keep = {\n '.git', 'demo', 'models', 'src', 'ampl-book.pdf', 'nlwrite.pdf',\n '.gitignore', '.nojekyll'\n }\n for entry in os.listdir(repo_dir):\n if entry in keep:\n continue\n path = os.path.join(repo_dir, entry)\n if os.path.isdir(path):\n shutil.rmtree(path)\n else:\n os.remove(path)\n # Build docs.\n extract_docs(build_dir)\n p = Popen(['doxygen', '-'], stdin=PIPE, cwd=build_dir)\n p.communicate(input=r'''\n PROJECT_NAME = MP\n INPUT = {0}/include/mp/common.h \\\n {0}/include/mp/nl.h\n EXCLUDE_SYMBOLS = mp::internal::*\n GENERATE_LATEX = NO\n GENERATE_MAN = NO\n GENERATE_RTF = NO\n GENERATE_HTML = NO\n GENERATE_XML = YES\n XML_OUTPUT = doxyxml\n QUIET = YES\n JAVADOC_AUTOBRIEF = YES\n AUTOLINK_SUPPORT = NO\n ALIASES = \"rst=\\verbatim embed:rst\"\n ALIASES += \"endrst=\\endverbatim\"\n '''.format(os.path.abspath('.')))\n if p.returncode != 0:\n return p.returncode\n check_call(['sphinx-build', '-D', 'version=' + get_mp_version(),\n '-b', 'html', build_dir, repo_dir])\n # Push docs to GitHub pages.\n if travis:\n check_call(['git', 'config', '--global', 'user.name', 'amplbot'])\n check_call(['git', 'config', '--global', 'user.email', 'viz@ampl.com'])\n check_call(['git', 'add', '--all'], cwd=repo_dir)\n returncode = 0\n if call(['git', 'diff-index', '--quiet', 'HEAD'], cwd=repo_dir):\n check_call(['git', 'commit', '-m', 'Update documentation'], cwd=repo_dir)\n cmd = 'git push https://$KEY@github.com/ampl/{}.git master'.format(repo)\n p = Popen(cmd, shell=True, stdout=PIPE, stderr=STDOUT, cwd=repo_dir)\n # Remove URL from output because it may contain a token.\n print(re.sub(r'https:.*\\.git', '', p.communicate()[0]))\n returncode = p.returncode\n return returncode\n\nbuild = os.environ['BUILD']\nif build == 'doc':\n returncode = 1\n travis = 'TRAVIS' in os.environ\n workdir = tempfile.mkdtemp()\n try:\n returncode = build_docs(workdir, travis=travis)\n finally:\n # Don't remove workdir on Travis because the VM is discarded anyway.\n if not travis:\n shutil.rmtree(workdir)\n exit(returncode)\n\ncmake_flags = ['-DBUILD=all']\nubuntu_packages = ['gfortran', 'unixodbc-dev']\n\nif build == 'cross':\n cmake_flags = [\n '-DCMAKE_SYSTEM_NAME=Windows',\n '-DCMAKE_SYSTEM_PROCESSOR=x86_64',\n '-DBUILD_SHARED_LIBS:BOOL=ON',\n '-DCMAKE_C_COMPILER=/opt/mingw64/bin/x86_64-w64-mingw32-gcc',\n '-DCMAKE_CXX_COMPILER=/opt/mingw64/bin/x86_64-w64-mingw32-g++',\n '-DCMAKE_RC_COMPILER=/opt/mingw64/bin/x86_64-w64-mingw32-windres',\n '-DCMAKE_FIND_ROOT_PATH=/opt/mingw64',\n '-DCMAKE_FIND_ROOT_PATH_MODE_LIBRARY=ONLY',\n '-DCMAKE_FIND_ROOT_PATH_MODE_INCLUDE=ONLY',\n '-DCMAKE_FIND_ROOT_PATH_MODE_PROGRAM=NEVER']\n ubuntu_packages = ['mingw64-x-gcc']\n for ppa in ['tobydox/mingw-x-precise', 'ubuntu-wine/ppa']:\n check_call(['sudo', 'add-apt-repository', 'ppa:' + ppa, '-y'])\n\n# Install dependencies.\nos_name = os.environ['TRAVIS_OS_NAME']\nif os_name == 'linux':\n # Install newer version of CMake.\n check_call(['sudo', 'apt-get', 'update'])\n check_call(['sudo', 'apt-get', 'install'] + ubuntu_packages)\n cmake_path = bootstrap.install_cmake(\n 'cmake-3.1.1-Linux-x86_64.tar.gz', check_installed=False,\n download_dir=None, install_dir='.')\nelse:\n # Install Java as a workaround for bug\n # http://bugs.java.com/bugdatabase/view_bug.do?bug_id=7131356.\n java_url = 'http://support.apple.com/downloads/DL1572/en_US/JavaForOSX2014-001.dmg'\n with Downloader().download(java_url) as f:\n bootstrap.install_dmg(f)\n cmake_path = 'cmake'\n\ncheck_call([cmake_path] + cmake_flags + ['.'])\ncheck_call(['make', '-j3'])\n\n# Install test dependencies.\nif build == 'cross':\n check_call(['sudo', 'apt-get', 'install', 'wine1.7'])\n if check_output(['objdump', '-p', 'bin/libasl.dll']).find('write_sol_ASL') < 0:\n print('ASL symbols not exported')\n exit(1)\n\n# Run tests.\ncheck_call(['ctest', '-V'])\n","sub_path":"support/travis-build.py","file_name":"travis-build.py","file_ext":"py","file_size_in_byte":6932,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"521944430","text":"from __future__ import division\r\n\r\nimport math\r\nfrom collections import namedtuple\r\n\r\nimport torch\r\nimport torch.nn as nn\r\nimport torch.nn.functional as F\r\nfrom torch.autograd.function import InplaceFunction\r\nfrom torch.nn.parameter import Parameter\r\n\r\nQuantizeScheme = namedtuple('QuantizScheme', ['method'])\r\nDefaultScheme = QuantizeScheme('none') # layer, bias\r\n\r\nquant_hyp = {\r\n 'weights': {'int': 4.0, 'range': 11.0, 'float': 11.0},\r\n 'bias': {'int': 7.0, 'range': 8.0, 'float': 8.0},\r\n 'activation': {'int': 7.0, 'range': 8.0, 'float': 8.0}\r\n}\r\n\r\n\r\ndef compute_delta(input, bits, overflow_rate=0):\r\n # assert input.requires_grad==False, \"tensor data must be no grad\"\r\n abs_value = input.abs().view(-1)\r\n sorted_value = abs_value.sort(dim=0, descending=True)[0]\r\n split_idx = int(overflow_rate * len(sorted_value))\r\n v = sorted_value[split_idx]\r\n v = v.item()\r\n I_max = 2 ** (bits - 1) - 1\r\n si = math.floor(math.log(I_max / (v + 1e-12), 2))\r\n\r\n delta = math.pow(2.0, -si)\r\n return delta\r\n\r\n\r\nclass Quantization(InplaceFunction):\r\n @staticmethod\r\n def forward(ctx, input, inplace=False, scheme=DefaultScheme):\r\n ctx.inplace = inplace\r\n if ctx.inplace:\r\n ctx.mark_dirty(input)\r\n output = input\r\n else:\r\n output = input.clone()\r\n\r\n with torch.no_grad():\r\n if scheme.method == 'bias':\r\n _int = 2 ** quant_hyp['bias']['int']\r\n _range = 2 ** quant_hyp['bias']['range']\r\n _float = 2 ** (-quant_hyp['bias']['float'])\r\n output = output.mul_(_range).round_().mul_(_float).clamp_(-_int, _int - _float)\r\n return output\r\n\r\n if scheme.method == 'layer':\r\n _int = 2 ** quant_hyp['weights']['int']\r\n _range = 2 ** quant_hyp['weights']['range']\r\n _float = 2 ** (-quant_hyp['weights']['float'])\r\n output = output.mul_(_range).round_().mul_(_float).clamp_(-_int, _int - _float)\r\n return output\r\n\r\n if scheme.method == 'bn':\r\n delta = compute_delta(input, 16, overflow_rate=0.001)\r\n float_ = - math.log(delta, 2)\r\n int_ = 7 - float_\r\n output = output / delta\r\n rounded = torch.floor(output) * delta\r\n clipped_value = torch.clamp(rounded, - 2 ** int_, 2 ** int_ - 2 ** (-float_))\r\n output = clipped_value\r\n return output\r\n\r\n @staticmethod\r\n def backward(ctx, grad_output):\r\n grad_input = grad_output\r\n return grad_input, None, None\r\n\r\n\r\ndef quantize(x, scheme=DefaultScheme, inplace=False):\r\n return Quantization().apply(x, inplace, scheme)\r\n\r\n\r\ndef weightquant(x, inplace=False):\r\n if x.dim() == 4:\r\n scheme = QuantizeScheme('layer')\r\n elif x.dim() == 2:\r\n scheme = QuantizeScheme('layer')\r\n elif x.dim() == 1:\r\n scheme = QuantizeScheme('bias')\r\n else:\r\n raise ValueError('dont support other shapes')\r\n\r\n return quantize(x, scheme=scheme, inplace=inplace)\r\n\r\n\r\nclass ActQuantize(InplaceFunction):\r\n @staticmethod\r\n def forward(ctx, input, inplace=False):\r\n ctx.inplace = inplace\r\n if ctx.inplace:\r\n ctx.mark_dirty(input)\r\n output = input\r\n else:\r\n output = input.clone()\r\n\r\n with torch.no_grad():\r\n _int = 2 ** quant_hyp['activation']['int']\r\n _range = 2 ** quant_hyp['activation']['range']\r\n _float = 2 ** (-quant_hyp['activation']['float'])\r\n output = output.mul_(_range).floor_().mul_(_float).clamp_(-_int, _int - _float)\r\n\r\n return output\r\n\r\n @staticmethod\r\n def backward(ctx, grad_output):\r\n grad_input = grad_output\r\n return grad_input, None, None, None, None\r\n\r\n\r\nclass ActQuant(nn.Module):\r\n def __init__(self, inplace=False):\r\n super(ActQuant, self).__init__()\r\n\r\n def forward(self, input):\r\n output = ActQuantize().apply(input, False)\r\n return output\r\n\r\n\r\nclass QConv2d(nn.Conv2d):\r\n def __init__(self, in_channels, out_channels, kernel_size, stride=1, padding=0,\r\n dilation=1, groups=1, bias=False):\r\n super(QConv2d, self).__init__(in_channels, out_channels, kernel_size, stride=stride,\r\n padding=padding, dilation=dilation, groups=groups, bias=bias)\r\n self.actquant = ActQuant()\r\n\r\n def forward(self, input):\r\n temp_weight = weightquant(self.weight)\r\n if self.bias is not None:\r\n temp_bias = weightquant(self.bias)\r\n else:\r\n temp_bias = None\r\n qinput = self.actquant(input)\r\n output = F.conv2d(qinput, temp_weight, temp_bias, self.stride,\r\n self.padding, self.dilation, self.groups)\r\n\r\n qoutput = self.actquant(output)\r\n\r\n return qoutput\r\n\r\n\r\nclass QRelu(nn.ReLU):\r\n def __init__(self, inplace=False):\r\n super(QRelu, self).__init__(inplace=inplace)\r\n self.actquant = ActQuant()\r\n\r\n def forward(self, input):\r\n qinput = self.actquant(input)\r\n qoutput = F.leaky_relu(qinput, 0.125)\r\n qoutput = self.actquant(qoutput)\r\n return qoutput\r\n\r\n\r\nclass QLeakyReLu(nn.LeakyReLU):\r\n def __init__(self, negative_slope=0.125, inplace=False):\r\n super(QLeakyReLu, self).__init__(negative_slope=negative_slope, inplace=inplace)\r\n self.actquant = ActQuant()\r\n\r\n def forward(self, input):\r\n qinput = self.actquant(input)\r\n qoutput = F.leaky_relu(qinput, self.negative_slope)\r\n qoutput = self.actquant(qoutput)\r\n return qoutput\r\n\r\n\r\nclass IdentityBN(nn.BatchNorm2d):\r\n def __init__(self, num_features, eps=1e-5, momentum=0.1, affine=True,\r\n track_running_stats=True):\r\n super(IdentityBN, self).__init__(\r\n num_features, eps, momentum, affine, track_running_stats)\r\n\r\n def forward(self, input):\r\n return input\r\n\r\n\r\nclass QLinear(nn.Linear):\r\n\r\n def __init__(self, in_features, out_features, bias=True):\r\n super(QLinear, self).__init__(in_features, out_features, bias=bias)\r\n self.actquant = ActQuant()\r\n\r\n def forward(self, input):\r\n self.weight.data = weightquant(self.weight)\r\n if self.bias is not None:\r\n self.bias.data = weightquant(self.bias)\r\n output = F.linear(input, self.weight, self.bias)\r\n qoutput = self.actquant(output)\r\n\r\n return qoutput\r\n","sub_path":"quantization.py","file_name":"quantization.py","file_ext":"py","file_size_in_byte":6549,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"229047430","text":"# Copyright (c) 2014 Cisco Systems Inc.\n# All Rights Reserved.\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\nfrom oslo.config import cfg\n\nfrom nova.openstack.common.gettextutils import _\nfrom nova.openstack.common import log as logging\nfrom nova.scheduler.solvers import linearconstraints\n\nLOG = logging.getLogger(__name__)\nCONF = cfg.CONF\n\nram_allocation_ratio_opt = cfg.FloatOpt('linearconstraint_ram_allocation_ratio',\n default=1.0,\n help='Virtual ram to physical ram allocation ratio.')\nCONF.register_opt(ram_allocation_ratio_opt)\n\ndisk_allocation_ratio_opt = cfg.FloatOpt(\"linearconstraint_disk_allocation_ratio\",\n default=1.0,\n help=\"Virtual disk to physical disk allocation ratio.\")\nCONF.register_opt(disk_allocation_ratio_opt)\n\nclass ResourceAllocationConstraint(linearconstraints.BaseLinearConstraint):\n \"\"\"Base class of resource allocation constraints.\"\"\"\n def __init__(self, variables, hosts, instance_uuids, request_spec, filter_properties):\n [self.num_hosts, self.num_instances] = self._get_host_instance_nums(hosts,instance_uuids,request_spec)\n def _get_host_instance_nums(self,hosts,instance_uuids,request_spec):\n \"\"\"This method calculates number of hosts and instances\"\"\"\n num_hosts = len(hosts)\n if instance_uuids:\n num_instances = len(instance_uuids)\n else:\n num_instances = request_spec.get('num_instances', 1)\n return [num_hosts,num_instances]\n \nclass MaxDiskAllocationPerHostConstraint(ResourceAllocationConstraint):\n \"\"\"Constraint of the maximum total disk demand acceptable on each host.\"\"\"\n \n # The linear constraint should be formed as:\n # coeff_matrix * var_matrix' (operator) (constants)\n # where (operator) is ==, >, >=, <, <=, !=, etc.\n # For convenience, the (constants) is merged into left-hand-side,\n # thus the right-hand-side is 0.\n \n def get_coefficient_matrix(self,variables,hosts,instance_uuids,request_spec,filter_properties):\n # Give demand as coefficient for each variable and -supply as constant in each constraint.\n demand = [self._get_required_disk_mb(filter_properties) for j in range(self.num_instances)]\n supply = [self._get_usable_disk_mb(hosts[i]) for i in range(self.num_hosts)]\n coefficient_matrix = [demand + [-supply[i]] for i in range(self.num_hosts)]\n return coefficient_matrix\n \n def get_variable_matrix(self,variables,hosts,instance_uuids,request_spec,filter_properties):\n # The variable_matrix[i,j] denotes the relationship between host[i] and instance[j].\n variable_matrix = []\n variable_matrix = [[variables[i][j] for j in range(self.num_instances)] + [1] for i in range(self.num_hosts)]\n return variable_matrix\n \n def get_operations(self,variables,hosts,instance_uuids,request_spec,filter_properties):\n # Operations are '<='.\n operations = [(lambda x: x<=0) for i in range(self.num_hosts)]\n return operations\n \n def _get_usable_disk_mb(self, host_state):\n \"\"\"This method returns the usable disk in mb for the given host.\n Takes into account the disk allocation ratio (virtual disk to physical disk allocation ratio)\n \"\"\"\n free_disk_mb = host_state.free_disk_mb\n total_usable_disk_mb = host_state.total_usable_disk_gb * 1024\n disk_mb_limit = total_usable_disk_mb * CONF.linearconstraint_disk_allocation_ratio\n used_disk_mb = total_usable_disk_mb - free_disk_mb\n usable_disk_mb = disk_mb_limit - used_disk_mb\n return usable_disk_mb\n \n def _get_required_disk_mb(self,filter_properties):\n \"\"\" This method returns the required disk in mb from\n the given filter_properties dictionary object\n \"\"\"\n requested_disk_mb = 0\n instance_type = filter_properties.get('instance_type')\n if instance_type is not None:\n requested_disk_mb = 1024 * (instance_type.get('root_gb',0) +\n instance_type.get('ephemeral_gb',0))\n return requested_disk_mb\n\nclass MaxRamAllocationPerHostConstraint(ResourceAllocationConstraint):\n \"\"\"Constraint of the total ram demand acceptable on each host.\"\"\"\n \n # The linear constraint should be formed as:\n # coeff_matrix * var_matrix' (operator) (constants)\n # where (operator) is ==, >, >=, <, <=, !=, etc.\n # For convenience, the (constants) is merged into left-hand-side,\n # thus the right-hand-side is 0.\n \n def get_coefficient_matrix(self,variables,hosts,instance_uuids,request_spec,filter_properties):\n # Give demand as coefficient for each variable and -supply as constant in each constraint.\n [num_hosts,num_instances] = self._get_host_instance_nums(hosts,instance_uuids,request_spec)\n demand = [self._get_required_memory_mb(filter_properties) for j in range(self.num_instances)]\n supply = [self._get_usable_memory_mb(hosts[i]) for i in range(self.num_hosts)]\n coefficient_matrix = [demand + [-supply[i]] for i in range(self.num_hosts)]\n return coefficient_matrix\n \n def get_variable_matrix(self,variables,hosts,instance_uuids,request_spec,filter_properties):\n # The variable_matrix[i,j] denotes the relationship between host[i] and instance[j].\n variable_matrix = []\n variable_matrix = [[variables[i][j] for j in range(self.num_instances)] + [1] for i in range(self.num_hosts)]\n return variable_matrix\n \n def get_operations(self,variables,hosts,instance_uuids,request_spec,filter_properties):\n # Operations are '<='.\n operations = [(lambda x: x<=0) for i in range(self.num_hosts)]\n return operations\n \n def _get_usable_memory_mb(self,host_state):\n \"\"\"This method returns the usable memory in mb for the given host.\n Takes into account the ram allocation ratio (Virtual ram to physical ram allocation ratio)\n \"\"\"\n free_ram_mb = host_state.free_ram_mb\n total_usable_ram_mb = host_state.total_usable_ram_mb\n ram_allocation_ratio = CONF.linearconstraint_ram_allocation_ratio\n memory_mb_limit = total_usable_ram_mb * ram_allocation_ratio\n used_ram_mb = total_usable_ram_mb - free_ram_mb\n usable_ram_mb = memory_mb_limit - used_ram_mb\n return usable_ram_mb\n \n def _get_required_memory_mb(self,filter_properties):\n \"\"\" This method returns the required memory in mb from\n the given filter_properties dictionary object\n \"\"\"\n required_ram_mb = 0\n instance_type = filter_properties.get('instance_type')\n if instance_type is not None:\n required_ram_mb = instance_type.get('memory_mb',0)\n return required_ram_mb\n\nclass MaxVcpuAllocationPerHostConstraint(ResourceAllocationConstraint):\n \"\"\"Constraint of the total vcpu demand acceptable on each host.\"\"\"\n \n # The linear constraint should be formed as:\n # coeff_matrix * var_matrix' (operator) (constants)\n # where (operator) is ==, >, >=, <, <=, !=, etc.\n # For convenience, the (constants) is merged into left-hand-side,\n # thus the right-hand-side is 0.\n \n def get_coefficient_matrix(self,variables,hosts,instance_uuids,request_spec,filter_properties):\n # Give demand as coefficient for each variable and -supply as constant in each constraint.\n [num_hosts,num_instances] = self._get_host_instance_nums(hosts,instance_uuids,request_spec)\n demand = [self._get_required_vcpus(filter_properties) for j in range(self.num_instances)]\n supply = [self._get_usable_vcpus(hosts[i]) for i in range(self.num_hosts)]\n coefficient_matrix = [demand + [-supply[i]] for i in range(self.num_hosts)]\n return coefficient_matrix\n \n def get_variable_matrix(self,variables,hosts,instance_uuids,request_spec,filter_properties):\n # The variable_matrix[i,j] denotes the relationship between host[i] and instance[j].\n variable_matrix = []\n variable_matrix = [[variables[i][j] for j in range(self.num_instances)] + [1] for i in range(self.num_hosts)]\n return variable_matrix\n \n def get_operations(self,variables,hosts,instance_uuids,request_spec,filter_properties):\n # Operations are '<='.\n operations = [(lambda x: x<=0) for i in range(self.num_hosts)]\n return operations\n \n def _get_usable_vcpus(self,host_state):\n \"\"\"This method returns the usable vcpus for the given host.\n \"\"\"\n total_usable_vcpus = host_state.vcpus_total\n used_vcpus = host_state.vcpus_used\n usable_vcpus = total_usable_vcpus - used_vcpus\n return usable_vcpus\n \n def _get_required_vcpus(self,filter_properties):\n \"\"\" This method returns the required vcpus from\n the given filter_properties dictionary object\n \"\"\"\n required_vcpus = 1\n instance_type = filter_properties.get('instance_type')\n if instance_type is not None:\n required_vcpus = instance_type.get('vcpus',1)\n return required_vcpus","sub_path":"nova/scheduler/solvers/linearconstraints/resource_allocation_constraint.py","file_name":"resource_allocation_constraint.py","file_ext":"py","file_size_in_byte":9594,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"385867624","text":"\nclass base(object):\n def __init__( self, keys = None ):\n \"Perform standard initiation on simulation objects.\"\n\n #initialize any specified parameters if they exist in the simulation\n if keys is not None:\n for k in keys.keys():\n if k in self.__dict__:\n self.__dict__[k] = keys[k]\n\n #create the attr dictionary to easily refer to any necessary attributes\n self.attr = {}\n for k,v in self.__dict__.items():\n self.recurse_attr( k, v )\n\n def reparse( self ):\n for k,v in self.__dict__.items():\n self.recurse_attr( k, v )\n\n def recurse_attr( self, k, v ):\n if k == \"attr\":\n #uhh, okay computer\n return\n \n try:\n #allow derived classes to opt out of member listing\n if not v.recurse_attributes:\n return\n except AttributeError:\n #if recurse_attributes isn't defined continue\n pass\n \n try:\n for k2, v2 in v.__dict__.items():\n self.recurse_attr( k + \".\" + k2, v2 )\n except AttributeError:\n self.attr[ k ] = v\n","sub_path":"PyPlay/civ/backs/base.py","file_name":"base.py","file_ext":"py","file_size_in_byte":1190,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"442685472","text":"import vcr\nfrom unittest import TestCase\nfrom contentful_management.usage_period import UsagePeriod\nfrom contentful_management.organization import Organization\nfrom .test_helper import CLIENT\n\nBASE_USAGE_PERIOD_ITEM = {\n 'sys': {\n 'id': 1,\n 'type': 'UsagePeriod',\n },\n 'startDate': '2018-10-10T20:10:10Z',\n 'endDate': None\n}\n\n\nclass UsagePeriodTest(TestCase):\n def test_usage_period(self):\n usage_period = UsagePeriod(BASE_USAGE_PERIOD_ITEM)\n\n self.assertEqual(str(usage_period), \"\")\n self.assertEqual(usage_period.start_date.isoformat(), '2018-10-10T20:10:10+00:00')\n self.assertTrue(usage_period.end_date is None)\n\n @vcr.use_cassette('fixtures/usage_period/all.yaml')\n def test_usage_period_all(self):\n usage_periods = CLIENT.usage_periods('test_org').all()\n\n self.assertEqual(str(usage_periods[0]), \"\")\n self.assertEqual(str(usage_periods[1]), \"\")\n\n @vcr.use_cassette('fixtures/usage_period/all.yaml')\n def test_usage_period_organization_all(self):\n organization = Organization({'sys': {'id': 'test_org'}}, client=CLIENT)\n usage_periods = organization.usage_periods().all()\n\n self.assertEqual(str(usage_periods[0]), \"\")\n self.assertEqual(str(usage_periods[1]), \"\")\n","sub_path":"tests/usage_period_test.py","file_name":"usage_period_test.py","file_ext":"py","file_size_in_byte":1386,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"79674856","text":"# =============================================================================\r\n# TFM Fernando Cañavate Vega - Master of AI - Polytechnic University of Madrid\r\n# Script: name vectors clustering\r\n# =============================================================================\r\n\r\n\r\n\r\n# =============================================================================\r\n# realiza clusterizacion de los nombres utilizando sus vectores con kmeans, y drendograma\r\n# =============================================================================\r\n\r\n\r\n\r\n\r\nimport rdflib\r\nimport openpyxl\r\nfrom os import listdir\r\nfrom os import scandir\r\nimport xlrd\r\n#from google.colab import drive\r\nfrom openpyxl import load_workbook\r\nfrom openpyxl import Workbook\r\nfrom urllib import request\r\nimport numpy as np\r\nfrom scipy import sparse\r\nfrom scipy.sparse import coo_matrix\r\nfrom scipy import stats\r\nimport pandas as pd\r\nfrom sklearn.decomposition import TruncatedSVD\r\nfrom sklearn.cluster import KMeans\r\nimport scipy.cluster.hierarchy as sch\r\nimport matplotlib.pyplot as plt\r\n\r\n#from sparsesvd import sparsesvd\r\nfrom scipy.sparse.linalg import svds\r\n#https://pypi.org/project/sparsesvd/\r\n#drive.mount('/content/gdrive')\r\n#root_dir = \"/content/gdrive/My Drive/\"\r\n#def ls2(path): \r\n# return [obj.name for obj in scandir(path) if obj.is_file()]\r\n\r\n\r\nbase_verb_pd=pd.read_csv(\"base_verb_5000.csv\",header=0,names=['index_verb','verbostd','verbo'])\r\nbase_noun_pd=pd.read_csv(\"base_noun_5000.csv\",header=0,names=['index_noun','nombrestd'])\r\nnombres_vectores_pd=base_noun_pd\r\nvectores_pd=pd.read_csv(\"coord_nounsuj_verb_5000_densa.csv\")\r\n \r\ndef indexnombre(nombre):\r\n filanombre=base_noun_pd[(base_noun_pd['nombrestd']==nombre)]\r\n indexn=filanombre.iloc[0][0]\r\n return(indexn) \r\ndef indexverbo(verbo):\r\n filaverbo=base_verb_pd[(base_verb_pd['verbostd']==verbo)]\r\n indexv=filaverbo.iloc[0][0]\r\n return(indexv)\r\n \r\ndef nombre(indicenombre):\r\n filanombre=base_noun_pd[(base_noun_pd['index_noun']==indicenombre)]\r\n nombre=filanombre.iloc[0][1]\r\n return(nombre) \r\n\r\ndef verbo(indiceverbo):\r\n filaverbo=base_verb_pd[(base_verb_pd['index_verb']==indiceverbo)]\r\n verbo = filaverbo.iloc[0][1]\r\n return(verbo) \r\n\r\n\r\n\r\ndef vector_noun_suj_index(index):\r\n index_noun=index\r\n vectornombre=coord_nounsuj_verb_matrix.getrow(index_noun)\r\n vector_noun_dense=vectornombre.todense()\r\n return(vector_noun_dense)\r\ndef vector_noun_suj(nombre):\r\n index_noun=indexnombre(nombre)\r\n vectornombre=coord_nounsuj_verb_matrix.getrow(index_noun)\r\n vector_noun_dense=vectornombre.todense()\r\n return(vector_noun_dense)\r\n\r\ndef listadoverbos(vector1):\r\n vector=vector1.transpose()\r\n vector.reset_index(drop=True,inplace=True)\r\n listado_verbs_pd=pd.concat([vector,base_verb_pd['verbostd']],axis=1,join=\"inner\")\r\n listado_verbs_pd.columns=[\"coord\",\"verbos\"]\r\n listado_verbs_pd_ordenado=listado_verbs_pd.sort_values(by=['coord'],ascending=False)\r\n #print (listado_verbs_pd.shape)\r\n #print (listado_verbs_pd)\r\n print (listado_verbs_pd_ordenado.iloc[0:10,:])\r\n #return (listado_verbs_pd_ordenado.iloc[0:10,:].values.tolist())\r\n #print (listado_verbs_pd_ordenado.iloc[0:10,:])\r\n return (listado_verbs_pd_ordenado.iloc[0:10,:])\r\ndef listadoverbos_nombre(nombre1):\r\n #vector (primeros 100 elementos a un nombre dado)\r\n vec=vector_noun_suj(nombre1)\r\n vec_pd=pd.DataFrame(vec)\r\n tabla_verbos=[]\r\n for a in range(1,53094):\r\n tabla_verbos.append([vec_pd.iloc[0,a],verbo(a)])\r\n listado_verbs_pd=pd.DataFrame(tabla_verbos)\r\n listado_verbs_pd.columns=[\"coord\",\"verbos\"]\r\n listado_verbs_pd_ordenado=listado_verbs_pd.sort_values(by=['coord'],ascending=False)\r\n return (listado_verbs_pd_ordenado.iloc[0:20,:])\r\ndef listadoverbos_cluster(vector):\r\n listado_verbs_pd=pd.DataFrame({\"coord\":vector,\"verbos\":base_verb_500['verbostd']})\r\n listado_verbs_pd_ordenado=listado_verbs_pd.sort_values(by=['coord'],ascending=False)\r\n #print (listado_verbs_pd.shape)\r\n #print (listado_verbs_pd)\r\n #print (listado_verbs_pd_ordenado.iloc[0:10,:])\r\n return (listado_verbs_pd_ordenado.iloc[0:10,:])\r\ndef listado_a_cadenas (listadoverbos1):\r\n cadena=\"=\"\r\n for index,linea in listadoverbos1.iterrows():\r\n print(\"linea\",linea)\r\n if type(linea['verbos']) == str and type(linea['coord'])==int:\r\n cadena=cadena+str(linea['coord'])+\"x\"+linea['verbos']+\" + \"\r\n print (\"cadena\",cadena)\r\n return cadena\r\n\r\n\r\n#clusterizamos con Kmeans\r\nkmeans=KMeans(n_clusters=500)\r\nkmeans.fit(vectores_pd)\r\nlabels = kmeans.predict(vectores_pd)\r\ncentroids = kmeans.cluster_centers_\r\nnombres_vectores_pd['clases']=labels\r\nnombres_vectores_pd.to_csv(\"base_noun_5000_clusters.csv\",index=False,encoding=\"utf_8_sig\")\r\n#print(labels)\r\n#print(centroids)\r\ncentroids_pd=pd.DataFrame(centroids[:,0])\r\ncentroids_pd['verbos1'] = None\r\nnombres_vectores_pd['verbos1']=None\r\ncentroids_aux=[]\r\nnombres_vect_aux=[]\r\n\r\n#for index, row in nombres_vectores_pd.iterrows():\r\n# print(\"index\",index)\r\n# print (\"row\",row)\r\n# nombre1=row['word']\r\n# print (\"word\", nombre1)\r\n# nombres_vectores_pd.loc[index,'verbos1']=listado_a_cadenas(listadoverbos_nombre(nombre1))\r\n# if index%10:\r\n# nombres_vectores_pd.to_csv(\"nombres_vectores_500_3_labels_verbos_1.csv\",encoding=\"utf_8_sig\")\r\n#nombres_vectores_pd.to_csv(\"nombres_vectores_500_3_labels_verbos.csv_1\",encoding=\"utf_8_sig\")\r\n#Clustering jerárquico\r\n# Creamos el dendograma para encontrar el número óptimo de clusters\r\nlabel_palabras=nombres_vectores_pd['nombrestd']\r\n#print (vectores_pd)\r\nR=dendrogram = sch.dendrogram(sch.linkage(vectores_pd, metric='cosine', method = 'single'),p=100,truncate_mode=\"lastp\",orientation='top')\r\ntemp = {R[\"leaves\"][ii]: labels[ii] for ii in range(len(R[\"leaves\"]))}\r\ndef llf(xx):\r\n return (label_palabras.iloc[temp[xx]])\r\ndendrogram = sch.dendrogram(sch.linkage(vectores_pd, metric='cosine',method = 'single'),p=100,leaf_label_func=llf,truncate_mode=\"lastp\",orientation='top')\r\nplt.title('Dendrograma')\r\nplt.xlabel('Distancias')\r\nplt.ylabel('Palabras')\r\nplt.show()\r\n\r\n\r\n","sub_path":"a6_clustering_5000.py","file_name":"a6_clustering_5000.py","file_ext":"py","file_size_in_byte":6148,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"66473680","text":"import matplotlib.pyplot as plt\nfrom PIL import Image\nimport os\nimport numpy as np\nimport math\n\ndef get_data(filepath):\n ret_dic = []\n print(filepath)\n with open(filepath, 'r') as f:\n for line in f.readlines():\n try:\n if line.startswith('mean_pos'):\n # print(line)\n pp = [float(x.split(':')[1][:10]) for x in line.strip().split(' ')[:4]]\n #print(pp)\n #print(line.strip().split(',')[:4])\n ret_dic.append(pp)\n except:\n print(line)\n ret_dic.append([0.,0., 0.,0.])\n\n return ret_dic\n\n\n#_FileNames = ['gt', 'cae', 'mpca', 'mpca_gt']\n_FileNames = ['gt', 'mpca_gt', 'mpca_gt','mpca_gt']\n_FileNames = ['recons_error_{}_2'.format(f) for f in _FileNames]\n\ndef draw_error_curve(datas, idx):\n print(idx)\n factor = 1 if idx == 0 or idx == 3 else 10\n print(datas)\n start_idx = 12\n if idx >= 2:\n datas = datas[::4]\n print(datas)\n if idx == 3 or idx == 0:\n datas = datas[start_idx:]# datas[1:]\n datas[-1] = [(a + b) / 2 for a, b in zip(datas[-3],datas[-2])]\n print(datas)\n for i in range(2):\n #print(datas[0])\n means = [abs(p[i]) for p in datas]\n stds = [p[i+2] for p in datas]\n\n upper = [m + s for m, s in zip(means, stds)]\n lower = [m - s for m, s in zip(means, stds)]\n labels = ['Inliers', 'Outliers']\n color = ['g', 'r']\n plt.plot(np.arange(start_idx, len(means) * factor + start_idx, factor).astype(dtype=np.str), means, c=color[i],label=labels[i])\n\n plt.fill_between(np.arange(start_idx, len(means) * factor + start_idx, factor).astype(dtype=np.str),\n upper,\n lower,\n color=color[i],\n alpha=0.2)\n #plt.legend(prop={'size': 15})\n plt.tick_params(labelsize=13)\n names = ['GEOM', 'AE/CAE', 'AE-LFR', 'GT-LFR']\n plt.xlabel(names[idx], fontsize=20)\n #plt.ylabel('Scores', fontsize=20)\n if idx == 1:\n plt.ylim((0, 100))\n\n plt.savefig('../figures/{}.pdf'.format(_FileNames[idx]),bbox_inches = 'tight')\n plt.show()\n\ndef draw_error_curve_merge(datas1, datas2):\n factor = 1\n datas1 = datas1[1:]\n datas2 = datas2[::4][1:]\n for datas, color in [(datas1, ['lightgreen', 'lightcyan']), (datas2, ['g', 'r'])]:\n for i in range(2):\n #print(datas[0])\n means = [abs(p[i]) for p in datas]\n stds = [p[i+2] for p in datas]\n\n upper = [m + s for m, s in zip(means, stds)]\n lower = [m - s for m, s in zip(means, stds)]\n labels = ['Inliers', 'Outliers']\n plt.plot(np.arange(1, len(means) * factor + 1, factor), means, c=color[i],label=labels[i])\n\n plt.fill_between(np.arange(1, len(means) * factor + 1, factor),\n upper,\n lower,\n color=color[i],\n alpha=0.2)\n plt.legend(prop={'size': 15})\n plt.tick_params(labelsize=13)\n names = ['GEOM', 'AE/CAE', 'AE-LFR', 'GT-LFR']\n plt.xlabel('Mix', fontsize=20)\n #plt.ylabel('Scores', fontsize=20)\n # if idx == 1:\n # plt.ylim((0, 100))\n\n plt.savefig('../figures/{}.pdf'.format('Mix'),bbox_inches = 'tight')\n plt.show()\n print(datas1[-1])\n print(datas2[-1])\n\n#draw_error_curve_merge(get_data('/Users/linjinghuang/data/MPCA/log_score_mean/{}.log'.format(_FileNames[0])),\n# get_data('/Users/linjinghuang/data/MPCA/log_score_mean/{}.log'.format(_FileNames[1])))\n\nfor i in range(2):\n draw_error_curve(get_data('/Users/linjinghuang/data/MPCA/log_score_mean/{}.log'.format(_FileNames[i])),\n [0, 3][i])","sub_path":"scripts/draw_error_result.py","file_name":"draw_error_result.py","file_ext":"py","file_size_in_byte":3814,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"559487717","text":"import theano\nimport theano.tensor as T\nimport numpy as np\nimport time\nimport h5py\nimport cPickle as pickle\n\nfrom utilityFunctions import (preds, printStats, geoMean, floatToString,\n\t\tgetWithName, intCounter)\nfrom objectives import objecD\nfrom optimisers import optD, Optimiser\n\n# Wrapper object for the theano tensors and associated information that\n# get passed though the network when it's constructed.\nclass Representation(object): # {{{\n\n\tdef __init__(self, shape, trainTensor=None, testTensor=None, layers=None):\n\t\tif layers is None:\n\t\t\tlayers = []\n\t\tself.shape = shape\n\t\tself.layers = layers\n\t\tnd = len(self.shape)+1\n\t\tif trainTensor is None:\n\t\t\tself.trainTensor = T.TensorType(\n\t\t\t\tdtype=theano.config.floatX, broadcastable=(False,)*nd\n\t\t\t)('X_tr')\n\t\telse:\n\t\t\tself.trainTensor = trainTensor\n\t\tif testTensor is None:\n\t\t\tself.testTensor = T.TensorType(\n\t\t\t\tdtype=theano.config.floatX, broadcastable=(False,)*nd\n\t\t\t)('X_te')\n\t\telse:\n\t\t\tself.testTensor = testTensor\n\n\t# Given an archiver object, reports the layers the rep has passed through.\n\tdef show(self, arc):\n\t\tarc.log(\"\")\n\t\tarc.log(\"A representation having moved through:\")\n\t\tfor layer in self.layers:\n\t\t\tlayer.show(arc) # }}}\n\n# Actual Neural Network object.\nclass NN(object): # {{{\n\n\tdef __init__(self, inRep, outRep, archiver=None, # {{{\n\t\t\tobjective=None, optimiser=None, postBatchFunctions=None,\n\t\t\tpostEpochFunctions=None, classify=True):\n\n\t\tif postBatchFunctions is None:\n\t\t\tpostBatchFunctions = []\n\t\tif postEpochFunctions is None:\n\t\t\tpostEpochFunctions = []\n\t\tif archiver is None:\n\t\t\tarchiver = Archiver()\n\n\t\tself.testInTensor = inRep.testTensor\n\t\tself.trainInTensor = inRep.trainTensor\n\t\tself.testOutTensor = outRep.testTensor\n\t\tself.trainOutTensor = outRep.trainTensor\n\n\t\tself.classify = classify\n\t\tself.labelTensor = T.matrix('y')\n\n\t\tself.set(objective, optimiser)\n\n\t\tself.trainCompiled = False\n\t\tself.evaluateCompiled = False\n\t\tself.observeCompiled = False\n\n\t\tself.layers = outRep.layers\n\t\tself.trainableWeights = []\n\t\tself.depth = 0\n\t\tself.numWeights = 0\n\t\tndict = {}\n\t\tfor layer in self.layers:\n\t\t\tself.trainableWeights += layer.trainableWeights\n\t\t\tself.depth += layer.depth\n\t\t\tself.numWeights += layer.numWeights\n\t\t\tif layer.name not in ndict:\n\t\t\t\tndict[layer.name] = 0\n\t\t\tndict[layer.name] += 1\n\t\t\tlayer.name += \"_\"+str(ndict[layer.name])\n\t\tself.pbfs = postBatchFunctions\n\t\tself.pefs = postEpochFunctions\n\t\tself.LSUVFlag = False\n\t\tself.LSUVdata = None\n\t\tself.restarts = 0\n\t\tself.observationLayers = []\n\t\tself.observationFs = []\n\t\tself.arc = archiver # }}}\n\n\tdef set(self, objective, optimiser): # {{{\n\t\tif objective is not None:\n\t\t\tself.objective = getWithName(objecD, objective)\n\n\t\tif type(optimiser) is str:\n\t\t\tself.optimiser = getWithName(optD, optimiser)() # passed the name\n\t\telif type(optimiser) is type and issubclass(optimiser, Optimiser):\n\t\t\tself.optimiser = optimiser() # passed the class\n\t\telif optimiser is not None:\n\t\t\tself.optimiser = optimiser # assumed to have passed an instance }}}\n\n\tdef compileTrain(self, objective=None, optimiser=None): # {{{\n\t\tself.set(objective, optimiser)\n\t\tself.trainLoss = self.objective(self.trainOutTensor, self.labelTensor)\n\t\tfor layer in self.layers:\n\t\t\tfor W in layer.regWeights:\n\t\t\t\tself.trainLoss += 0.5 * layer.reg * layer.regFunction(W)\n\t\tself.optimiser.compile(self.trainLoss)\n\n\t\tself.updates = []\n\t\tself.weightList = []\n\t\tfor layer in self.layers:\n\t\t\tself.weightList += layer.trainableWeights\n\t\t\tself.updates += layer.manualUpdates\n\t\tself.updates += self.optimiser(self.weightList)\n\n\t\tout = self.trainLoss\n\t\tif self.classify:\n\t\t\t_, accuracy = preds(self.trainOutTensor, self.labelTensor)\n\t\t\tout = [out, accuracy]\n\t\tself._trainOnBatch = theano.function(\n\t\t\t[self.trainInTensor, self.labelTensor]\n\t\t,\tout\n\t\t,\tupdates=self.updates\n\t\t)\n\t\tself.trainCompiled = True\n\n\tdef trainOnBatch(self, x, y):\n\t\tif not self.trainCompiled:\n\t\t\tself.compileTrain()\n\t\treturn self._trainOnBatch(x, y) # }}}\n\n\tdef compileEvaluate(self): # {{{\n\t\tself.testLoss = self.objective(self.testOutTensor, self.labelTensor)\n\t\tout = [self.testLoss]\n\t\tif self.classify:\n\t\t\tpredictions, accuracy = preds(self.testOutTensor, self.labelTensor)\n\t\t\tout += [predictions, accuracy]\n\t\telse:\n\t\t\tout += [self.testOutTensor]\n\t\tself._eval = theano.function(\n\t\t\t[self.testInTensor, self.labelTensor]\n\t\t,\tout\n\t\t)\n\t\tself.evaluateCompiled = True\n\n\tdef evaluate(self, x, y, batchSize=64):\n\t\tif not self.evaluateCompiled:\n\t\t\tself.compileEvaluate()\n\t\tnumBatches = x.shape[0]/batchSize\n\t\tbatches = [\n\t\t\t(x[i*batchSize:(i + 1)*batchSize], y[i*batchSize:(i + 1)*batchSize])\n\t\t\tfor i in range(numBatches)\n\t\t]\n\t\tif x.shape[0] % batchSize != 0:\n\t\t\tbatches.append((x[numBatches*batchSize:], y[numBatches*batchSize:]))\n\t\tlS = []\n\t\taS = []\n\t\tpredS = []\n\t\tfor xBatch, yBatch in batches:\n\t\t\tif self.classify:\n\t\t\t\tl, pred, a = self._eval(xBatch, yBatch)\n\t\t\t\taS.append(xBatch.shape[0]*a)\n\t\t\telse:\n\t\t\t\tl, pred = self._eval(xBatch, yBatch)\n\t\t\tlS.append(xBatch.shape[0]*l)\n\t\t\tpredS.append(pred)\n\t\tl = sum(lS)/x.shape[0]\n\t\tpred = np.concatenate(predS, axis=0)\n\t\tif self.classify:\n\t\t\ta = sum(aS)/x.shape[0]\n\t\t\treturn l, pred, a\n\t\telse:\n\t\t\treturn l, pred # }}}\n\n\tdef trainForEpoch(self, x, y, batchSize, # {{{\n\t\t\tvalidationData=None, verbosity=1, plotting=False, r=6):\n\t\t# x, y can be numpy arrays wth data and labels respectively,\n\t\t# or x can be a callable returning a batch: data, labels\n\t\t# in which case y must specify the number of batches to perform,\n\t\t# and x must accept the batchSize keyword argument.\n\t\tif type(y) is int:\n\t\t\tgenerating = True\n\t\t\tbatchIndices = range(y)\n\t\t\tepochLen = y * batchSize\n\t\telse:\n\t\t\tgenerating = False\n\t\t\tepochLen = x.shape[0]\n\t\t\tinds = np.arange(epochLen)\n\t\t\tnp.random.shuffle(inds)\n\t\t\tbatchIndices = [inds[batchSize*i:batchSize*(i + 1)]\n\t\t\t\t\tfor i in range(epochLen / batchSize)]\n\t\t\tif epochLen % batchSize != 0:\n\t\t\t\tbatchIndices += [inds[batchSize*(epochLen / batchSize):]]\n\n\t\tloss = 0.\n\t\tacc = 0.\n\t\ta = 0.\n\t\tif plotting:\n\t\t\tlosses = []\n\t\t\taccs = []\n\n\t\tt0 = time.time()\n\t\tfor i, binds in enumerate(batchIndices):\n\t\t\tif generating:\n\t\t\t\txBatch, yBatch = x(batchSize=batchSize)\n\t\t\telse:\n\t\t\t\txBatch = x[binds]\n\t\t\t\tyBatch = y[binds]\n\t\t\tif self.classify:\n\t\t\t\tl, a = self.trainOnBatch(xBatch, yBatch)\n\t\t\telse:\n\t\t\t\tl = self.trainOnBatch(xBatch, yBatch)\n\t\t\tif plotting:\n\t\t\t\tlosses.append(l)\n\t\t\t\taccs.append(a)\n\t\t\tloss = (i*loss + l) / (i + 1)\n\t\t\tacc = (i*acc + a) / (i + 1)\n\t\t\ttcur = time.time() - t0\n\t\t\tif i == 0:\n\t\t\t\ttproj = (epochLen / batchSize) * tcur\n\t\t\t\tt0 = time.time()\n\t\t\telse:\n\t\t\t\ttproj = (epochLen / batchSize) * (tcur / i)\n\n\t\t\tif verbosity == 1:\n\t\t\t\tself.arc.log(\n\t\t\t\t\t(\"(%d/%d) - Loss: \" + floatToString(loss, r) + \" - Acc: \"\n\t\t\t\t\t+ floatToString(acc, r) + \" - T: %d/%ds \"\n\t\t\t\t\t) % (\n\t\t\t\t\t\tmin(batchSize*(i + 1), epochLen)\n\t\t\t\t\t,\tepochLen\n\t\t\t\t\t,\tint(tcur)\n\t\t\t\t\t,\tint(tproj)\n\t\t\t\t\t)\n\t\t\t\t,\teol='\\r'\n\t\t\t\t)\n\t\t\tfor f in self.pbfs:\n\t\t\t\tf(model=self, l=l, a=a, avgLoss=loss, avgAcc=acc, t=tcur)\n\t\t\tif np.isnan(l):\n\t\t\t\tself.arc.log(\"\")\n\t\t\t\tself.arc.log(\"Loss is NaN; cancelling epoch.\")\n\t\t\t\treturn None, None, [[], [], None, None]\n\t\ttf = time.time()\n\n\t\treport = \"Loss: \" + floatToString(loss, r)\n\t\treport += \" - Acc: \" + floatToString(acc, r)\n\t\tif validationData is not None:\n\t\t\tvloss, _, vacc = self.evaluate(validationData[0], validationData[1])\n\t\t\treport += \" - V loss: \" + floatToString(vloss, r)\n\t\t\treport += \" - V acc: \" + floatToString(vacc, r)\n\t\telse:\n\t\t\teplToken = \"(%d/%d) - \" % (epochLen, epochLen)\n\t\t\treport = eplToken + report\n\t\ttLen = max(4, 2*len(str(int(tf-t0))) + 1)\n\t\treport += \" - T: \" + floatToString(tf-t0, tLen) + \"s\"\n\t\tself.arc.log(report)\n\n\t\tif plotting:\n\t\t\tif validationData is None:\n\t\t\t\treturn loss, acc, [losses, accs]\n\t\t\telse:\n\t\t\t\treturn loss, acc, [losses, accs, vloss, vacc]\n\t\telse:\n\t\t\treturn loss, acc, [] # }}}\n\n\tdef schedule(self, x, y, scheduler, batchSize=64, # {{{\n\t\t\tvalidationData=None, verbosity=1, plotting=False,\n\t\t\tsaveWeights=True, name='1', restartDecay=1.):\n\n\t\tscheduler.set(optimiser=self.optimiser, archiver=self.arc)\n\n\t\tif plotting:\n\t\t\tds = ['plots', name]\n\t\t\tcuunter = 0\n\t\t\tlosses = []\n\t\t\taccs = []\n\t\t\tallEpochLs = []\n\t\t\tallEpochAs = []\n\t\t\tif validationData is not None:\n\t\t\t\tvlosses = []\n\t\t\t\tvaccs = []\n\n\t\tif saveWeights:\n\t\t\tself.arc.saveWeights(self, name + \" - epoch 0 (init).h5\")\n\n\t\tloss = None\n\t\tacc = None\n\t\tepochLs = None\n\t\tepochAs = None\n\t\tvloss = None\n\t\tvacc = None\n\t\twhile scheduler.epoch(loss=loss, acc=acc):\n\n\t\t\tself.arc.log(\"\")\n\t\t\tself.arc.log(\"Epoch #%d, with learning rate %f and batch size %d\"\n\t\t\t\t\t% (scheduler.currentEpoch, scheduler.lr, batchSize))\n\n\t\t\tloss, acc, l = self.trainForEpoch(x, y, batchSize,\n\t\t\t\t\tvalidationData=validationData,\n\t\t\t\t\tverbosity=verbosity, plotting=plotting)\n\t\t\tif plotting:\n\t\t\t\tlosses.append(loss)\n\t\t\t\tcuunter += 1\n\t\t\t\taccs.append(acc)\n\t\t\t\tepochLs = l[0]\n\t\t\t\tepochAs = l[1]\n\t\t\t\tallEpochLs.extend(epochLs)\n\t\t\t\tallEpochAs.extend(epochAs)\n\n\t\t\t\tpe_ds=['epochal data']\n\t\t\t\tself.arc.plot([], [epochLs], name='Loss - Epoch %d'\n\t\t\t\t\t\t% scheduler.currentEpoch, directoryStructure=ds+pe_ds)\n\t\t\t\tself.arc.plot([], [epochAs], name='Accuracy - Epoch %d'\n\t\t\t\t\t\t% scheduler.currentEpoch, directoryStructure=ds+pe_ds)\n\n\t\t\t\tlossesL = [losses]\n\t\t\t\taccsL = [accs]\n\t\t\t\tif validationData is not None:\n\t\t\t\t\tvloss = l[2]\n\t\t\t\t\tvacc = l[3]\n\t\t\t\t\tvlosses.append(vloss)\n\t\t\t\t\tvaccs.append(vacc)\n\t\t\t\t\tlossesL.append(vlosses)\n\t\t\t\t\taccsL.append(vaccs)\n\n\t\t\t\tself.arc.plot([], lossesL, name='Per Epoch Loss',\n\t\t\t\t\t\tdirectoryStructure=ds)\n\t\t\t\tself.arc.plot([], accsL, name='Per Epoch Accuracy',\n\t\t\t\t\t\tdirectoryStructure=ds)\n\n\t\t\t\tself.arc.plot([], [allEpochLs], name='Loss',\n\t\t\t\t\t\tdirectoryStructure=ds)\n\t\t\t\tself.arc.plot([], [allEpochAs], name='Accuracy',\n\t\t\t\t\t\tdirectoryStructure=ds)\n\n\t\t\t\tself.arc.pickle(\n\t\t\t\t\t{'loss':loss, 'acc':acc, 'l':l}\n\t\t\t\t,\t\"epoch %d.b\" % scheduler.currentEpoch\n\t\t\t\t,\tdirectoryStructure=ds+pe_ds\n\t\t\t\t)\n\t\t\tfor f in self.pefs:\n\t\t\t\trestartFlag = f(model=self, epoch=scheduler.currentEpoch,\n\t\t\t\t\t\tavgLoss=loss, avgAcc=acc, losses=epochLs,\n\t\t\t\t\t\taccs=epochAs, valLoss=vloss, valAcc=vacc)\n\t\t\t\tif restartFlag:\n\t\t\t\t\tself.restarts += 1\n\t\t\t\t\tself.arc.log(\"\")\n\t\t\t\t\tself.arc.log(\n\t\t\t\t\t\t\"Restarting for the \"+intCounter(self.restarts)+\" time.\"\n\t\t\t\t\t)\n\t\t\t\t\tself.reinit()\n\t\t\t\t\tscheduler.refresh(lr=scheduler.lr*restartDecay)\n\t\t\t\t\treturn self.schedule(x, y, scheduler=scheduler,\n\t\t\t\t\t\t\tbatchSize=batchSize, validationData=validationData,\n\t\t\t\t\t\t\tverbosity=verbosity, plotting=plotting,\n\t\t\t\t\t\t\tsaveWeights=saveWeights, name=name,\n\t\t\t\t\t\t\trestartDecay=restartDecay)\n\t\t\tif saveWeights:\n\t\t\t\tself.arc.saveWeights(self,\n\t\t\t\t\t\tname + \" - epoch %d.h5\" % scheduler.currentEpoch)\n\t\tif validationData is not None:\n\t\t\treturn l[2], l[3]\n\t\telse:\n\t\t\treturn loss, acc # }}}\n\n\tdef loadWeights(self, name): # {{{\n\t\tf = h5py.File(name, 'r')\n\t\tfor layer in self.layers:\n\t\t\tlayer.loadWeights(f)\n\t\tf.close() # }}}\n\n\tdef reinit(self, newArchiver=None): # {{{\n\t\tif self.optimiser is not None:\n\t\t\tself.optimiser.refresh()\n\t\tfor layer in self.layers:\n\t\t\tlayer.reinit()\n\t\tif self.LSUVFlag:\n\t\t\tself.LSUV(self.LSUVdata)\n\t\tif newArchiver is not None:\n\t\t\tself.arc = newArchiver # }}}\n\n\tdef show(self): # {{{\n\t\tself.arc.log(\"\")\n\t\tself.arc.log(\"A depth %d Neural Net on %d parameters, with layers:\" %\n\t\t\t\t(self.depth, self.numWeights))\n\t\tfor layer in self.layers:\n\t\t\tlayer.show(self.arc) # }}}\n\n\tdef debugInit(self, x): # {{{\n\t\tm, v = printStats(self.arc, x)\n\t\tfor i, layer in enumerate(self.layers):\n\t\t\tself.arc.log(\"\")\n\t\t\tself.arc.log(\"The batch of reprentations is shape \"+str(x.shape))\n\t\t\tself.arc.log(\"Now passing through:\")\n\t\t\tlayer.show(self.arc)\n\t\t\tx = layer.debugCall(x)\n\t\t\tm, v = printStats(self.arc, x) # }}}\n\n\tdef compileObservation(self): # {{{\n\t\tpreviousTensor = self.trainInTensor\n\t\ttlBuffer = []\n\t\tfor layer in self.layers:\n\t\t\tif layer.name[:11] == \"Observation\":\n\t\t\t\tself.observationLayers.append(layer)\n\t\t\t\tf = theano.function([previousTensor], layer.tensor)\n\t\t\t\tself.observationFs.append(f)\n\t\t\t\tlayer.setF(f)\n\t\t\t\tlayer.setPredecessors(tlBuffer)\n\t\t\t\ttlBuffer = []\n\t\t\t\tpreviousTensor = layer.tensor\n\t\t\telif layer.trainable:\n\t\t\t\ttlBuffer.append(layer)\n\t\tself.observeCompiled = True\n\n\tdef observe(self, x):\n\t\tif not self.observeCompiled:\n\t\t\tself.compileObservation()\n\t\tself.arc.log(\"\")\n\t\tself.arc.log(\"The batch of reprentations is shape \"+str(x.shape))\n\t\tm, v = printStats(self.arc, x)\n\t\tfor layer in self.observationLayers:\n\t\t\tx = layer.f(x)\n\t\t\tself.arc.log(\"\")\n\t\t\tself.arc.log(\"The batch of reprentations is shape \"+str(x.shape))\n\t\t\tm, v = printStats(self.arc, x) # }}}\n\n\t# {{{ Not quite LSUV as originally proposed, but closely based on.\n\t# Passes one batch to start, making the required corrections to the weights.\n\t# Next pass, it passes twice as many batches though at the same time,\n\t# applying the (geometric) mean of their corrective factors.\n\t# The variance is measured at observation points that are inserted by using\n\t# Observation layers in the model, and the corrective factors are\n\t# distributed over all trainable layers in between the observation points.\n\tdef LSUV(self, data, batchSize=256, debug=False, passes=5):\n\t\tif not self.observeCompiled:\n\t\t\tself.compileObservation()\n\t\tfor j in range(passes):\n\t\t\tinds = np.arange(data.shape[0]); np.random.shuffle(inds)\n\t\t\txs = [data[inds[batchSize*i:batchSize*(i + 1)]] for i in range(2**j)]\n\n\t\t\tfor layer in self.observationLayers:\n\t\t\t\tvs = []\n\t\t\t\tfor x in xs:\n\t\t\t\t\txtmp = layer.f(x)\n\t\t\t\t\tm = xtmp.mean()\n\t\t\t\t\tv = ((xtmp-m)**2).mean()\n\t\t\t\t\tif v > 10**(-8):\n\t\t\t\t\t\tvs.append(v)\n\t\t\t\tstd = pow(geoMean(vs), 1./(2*len(layer.predecessors)))\n\t\t\t\tstd += 10**(-6)\n\t\t\t\tfor pred in layer.predecessors:\n\t\t\t\t\tfor W in pred.trainableWeights:\n\t\t\t\t\t\tW.set_value(W.get_value()/std)\n\t\t\t\tfor i, x in enumerate(xs):\n\t\t\t\t\txs[i] = layer.f(x)\n\t\tif debug:\n\t\t\tinds = np.random.random_integers(size=(batchSize,), low=0,\n\t\t\t\t\thigh=(data.shape[0]-1))\n\t\t\tself.arc.log(\"\")\n\t\t\tself.arc.log(\"Dry run with fresh batch:\")\n\t\t\tself.observe(data[inds])\n\n\t\tself.LSUVdata = data\n\t\tself.LSUVFlag = True # }}}\n\n# }}}\n\n","sub_path":"neuralNetwork.py","file_name":"neuralNetwork.py","file_ext":"py","file_size_in_byte":13881,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"13559247","text":"import psycopg2\r\nimport psycopg2.extras\r\nimport json\r\nfrom configparser import ConfigParser\r\n\r\n\r\nclass PostgreSQL:\r\n @staticmethod\r\n def config(filename='database.ini', section='postgresql'):\r\n parser = ConfigParser()\r\n parser.read(filename)\r\n db = {}\r\n if parser.has_section(section):\r\n params = parser.items(section)\r\n for param in params:\r\n db[param[0]] = param[1]\r\n else:\r\n raise Exception('Section {0} not found in the {1} file'.format(section, filename))\r\n\r\n return db\r\n\r\n @staticmethod\r\n def connect():\r\n \"\"\" Connect to the PostgreSQL database server \"\"\"\r\n connection = None\r\n try:\r\n params = PostgreSQL.config()\r\n print('Connecting to the PostgreSQL database...')\r\n connection = psycopg2.connect(**params)\r\n except (Exception, psycopg2.DatabaseError) as error:\r\n print(error)\r\n return connection\r\n\r\n @staticmethod\r\n def version():\r\n connection = PostgreSQL.connect()\r\n cursor = connection.cursor()\r\n print('PostgreSQL database version:')\r\n cursor.execute('SELECT version()')\r\n db_version = cursor.fetchone()\r\n print(db_version)\r\n cursor.close()\r\n\r\n\r\n# base = PostgreSQL.connect()\r\n# cursor = base.cursor(cursor_factory=psycopg2.extras.RealDictCursor)\r\n# cursor.execute(\"SELECT id, author, name, avatar, url, description, language, stars, forks \" +\r\n# \" FROM public.repository\")\r\n# data = json.dumps(cursor.fetchall())\r\n# print(type(data))\r\n# print(data)\r\n# cursor.close()\r\n# dt = {\r\n# \"author\": \"test5\",\r\n# \"name\": \"test5\",\r\n# \"avatar\": \"test5\",\r\n# \"url\": \"test5\",\r\n# \"description\": \"test5\",\r\n# \"language\": \"test5\",\r\n# \"stars\": 5,\r\n# \"forks\": 5\r\n# }\r\n# cursor = base.cursor()\r\n# query = 'INSERT INTO public.repository(author, name, avatar, url, description, language, stars, forks) ' +\\\r\n# \"VALUES('{0}', '{1}', '{2}', '{3}', '{4}', '{5}', {6}, {7});\"\\\r\n# .format(dt[\"author\"], dt[\"name\"], dt[\"avatar\"], dt[ \"url\"], dt[\"description\"], dt[\"language\"],\r\n# dt[\"stars\"], dt[\"forks\"])\r\n# cursor.execute(query)\r\n# base.commit()\r\n# cursor.close()\r\n# base.close()","sub_path":"hiring-backend/database.py","file_name":"database.py","file_ext":"py","file_size_in_byte":2287,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"547784434","text":"# -*- coding: utf-8 -*-\r\nfrom perform.defines import *\r\nfrom perform.object import Perform as CustomPerform\r\n\r\n#导表开始\nclass Perform(CustomPerform):\n\tid = 5502\n\tname = \"免疫封印\"\n\tbuffId = 501\n#导表结束\r\n\r\n\tdef onSetup(self, w):\r\n\t\tself.addFunc(w, \"onAddWarrior\", self.onAddWarrior)\r\n\t\t\r\n\tdef onAddWarrior(self, w):\r\n\t\tbuff.addOrReplace(w, self.buffId, 99)\r\n\t\t\r\n\t\t\r\nimport buff","sub_path":"logic/perform/npcs/pf5502.py","file_name":"pf5502.py","file_ext":"py","file_size_in_byte":391,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"391161788","text":"import argparse\nimport os\nimport shlex\nimport subprocess\nimport sys\n\nfrom setup_helpers.cuda import USE_CUDA\n\nif __name__ == '__main__':\n # Placeholder for future interface. For now just gives a nice -h.\n parser = argparse.ArgumentParser(description='Build libtorch')\n args = parser.parse_args()\n\n os.environ['BUILD_TORCH'] = 'ON'\n os.environ['BUILD_TEST'] = 'ON'\n os.environ['ONNX_NAMESPACE'] = 'onnx_torch'\n os.environ['PYTORCH_PYTHON'] = sys.executable\n\n tools_path = os.path.dirname(os.path.abspath(__file__))\n build_pytorch_libs = os.path.join(tools_path, 'build_pytorch_libs.sh')\n\n command = '{} --use-nnpack '.format(build_pytorch_libs)\n if USE_CUDA:\n command += '--use-cuda '\n command += 'caffe2'\n\n sys.stdout.flush()\n sys.stderr.flush()\n subprocess.check_call(shlex.split(command), universal_newlines=True)\n","sub_path":"tools/build_libtorch.py","file_name":"build_libtorch.py","file_ext":"py","file_size_in_byte":868,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"371020535","text":"import utils\nfrom db_utils import getAllLinks\nfrom db_utils import getAllHosts\n\nimport webapp2\nimport logging\nfrom google.appengine.api import users\n\nJINJA_ENVIRONMENT = utils.getJinjaEnvironment()\n\n\nclass MainPage(webapp2.RequestHandler):\n def get(self):\n user = users.get_current_user()\n template_values = {\n 'user': user,\n 'activeNav': 0\n }\n template = JINJA_ENVIRONMENT.get_template('index.html')\n self.response.write(template.render(template_values))\n\n\nclass ErrorPage(webapp2.RequestHandler):\n def get(self):\n error_msg = self.request.get('error_msg')\n template_values = {\n 'error_msg': error_msg\n }\n template = JINJA_ENVIRONMENT.get_template('error.html')\n self.response.write(template.render(template_values))\n\n\nclass NotFoundErrorPage(webapp2.RequestHandler):\n def get(self):\n error_msg = 'Page Not found'\n template_values = {\n 'error_msg': error_msg\n }\n template = JINJA_ENVIRONMENT.get_template('error.html')\n self.response.write(template.render(template_values))\n\n\nclass HelpPage(webapp2.RequestHandler):\n def get(self):\n user = users.get_current_user()\n template_values = {\n 'user': user,\n 'activeNav': 2\n }\n template = JINJA_ENVIRONMENT.get_template('help.html')\n self.response.write(template.render(template_values))\n","sub_path":"src/main_views.py","file_name":"main_views.py","file_ext":"py","file_size_in_byte":1326,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"635227196","text":"import sys\nimport json\nimport logging\nimport argparse\n\nfrom preprocessing import BeneficiarySummaryParser\nfrom preprocessing import ClaimParser\nfrom util import (\n configure_logger,\n save_to_json\n)\n\ndef run_beneficiary_summary_parser(sample_num, config, logger):\n \"\"\"Run beneficiary summary parser\"\"\"\n logger.info('Start parsing beneficiary summary sample \"{}\"...'.format(sample_num))\n parser = BeneficiarySummaryParser()\n for raw_data_fn in config['beneficiary']:\n raw_data_fn = raw_data_fn.replace('*', sample_num)\n logger.info('Adding {} to the queue...'.format(raw_data_fn))\n parser.add_data_file(raw_data_fn)\n\n logger.info('Parsing beneficiary summary files...')\n output_data_fns = parser.parse_data()\n\n logger.info('Combining parsed beneficiary summary files...')\n bene = parser.combine_data(\n {\n year: parsed_data_fn for year, parsed_data_fn in zip(\n ['2008', '2009', '2010'], output_data_fns\n )\n }\n )\n logger.info(\n 'Finish parsing - {} beneficiaries found in the beneficiary summary sample \"{}\"'.format(\n len(bene), sample_num\n )\n )\n return bene\n\ndef run_claim_parser(claim_type, sample_num, raw_data_fns, logger):\n \"\"\"Run `claim_type` claim parser\"\"\"\n logger.info('Start parsing {} claim sample \"{}\"...'.format(claim_type, sample_num))\n parser = ClaimParser(claim_type)\n for raw_data_fn in raw_data_fns:\n raw_data_fn = raw_data_fn.replace('*', sample_num)\n logger.info('Adding {} to the queue...'.format(raw_data_fn))\n parser.add_data_file(raw_data_fn)\n\n logger.info('Parsing {} claim files...'.format(claim_type))\n output_data_fns = parser.parse_data()\n\n logger.info('Merging parsed {} claim files...'.format(claim_type))\n for fn in output_data_fns:\n parser.add_data_file(fn)\n claims = parser.merge_claim_lines()\n\n logger.info(\n 'Finish parsing - {} beneficiaries found in the {} claims sample \"{}\"'.format(\n len(claims), claim_type, sample_num\n )\n )\n return claims\n\ndef combine_files(bene, inp_claims, outp_claims, car_claims, pde_claims):\n for member_id in bene:\n member_doc = bene[member_id]\n member_inp_claims = inp_claims.get(member_id, [])\n member_outp_claims = outp_claims.get(member_id, [])\n member_car_claims = car_claims.get(member_id, [])\n member_doc['medClaims'] = sorted(\n member_inp_claims+member_outp_claims+member_car_claims,\n key=lambda claim: claim['startDate']\n )\n member_pde_claims = pde_claims.get(member_id, [])\n member_doc['rxFills'] = member_pde_claims\n\nif __name__ == '__main__':\n argparser = argparse.ArgumentParser(description='DE-SynPUF processing program')\n argparser.add_argument('-l', '--log_fn',\n help='full path to the log file', required=True)\n argparser.add_argument('-cfg', '--config',\n help='full path to the config file', required=True)\n argparser.add_argument('-sn', '--sample_num',\n help='data sample number', required=True)\n args = argparser.parse_args()\n\n logger = logging.getLogger(__name__)\n configure_logger(logger, args.log_fn)\n with open(args.config, 'r') as fp:\n config = json.load(fp)\n\n sample_beneficiary_summary = run_beneficiary_summary_parser(args.sample_num, config, logger)\n sample_claims = {}\n for claim_type in ['inpatient', 'outpatient', 'carrier', 'pde']:\n claims = run_claim_parser(claim_type, args.sample_num, config[claim_type], logger)\n sample_claims[claim_type] = claims\n\n combine_files(sample_beneficiary_summary, sample_claims['inpatient'], sample_claims['outpatient'],\n sample_claims['carrier'], sample_claims['pde'])\n\n save_to_json(sample_beneficiary_summary, config['output'].replace('*', args.sample_num))\n","sub_path":"run_preprocessing.py","file_name":"run_preprocessing.py","file_ext":"py","file_size_in_byte":3951,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"142427836","text":"import datetime, os, random, string\nfrom flask import Flask, request, render_template, session, url_for, redirect\nfrom flask_babelex import Babel\nfrom flask_sqlalchemy import SQLAlchemy\nfrom flask_user import current_user, login_required, roles_required, UserManager, UserMixin, user_manager\nfrom flask_uploads import UploadSet, configure_uploads, IMAGES, patch_request_class\nfrom flask_wtf import FlaskForm\nfrom flask_wtf.file import FileField, FileRequired, FileAllowed\nfrom wtforms.validators import DataRequired\nfrom werkzeug.utils import secure_filename\nfrom wtforms_sqlalchemy.fields import QuerySelectField\nfrom wtf_tinymce.forms.fields import TinyMceField\nfrom wtforms import SubmitField, StringField, PasswordField, TextAreaField\nfrom flask_admin import Admin\nfrom flask_admin.contrib.sqla import ModelView\nfrom faker import Faker\n\nclass ConfigClass(object):\n \"\"\" Flask application config \"\"\"\n\n # Flask settings\n SECRET_KEY = 'This is an INSECURE secret!! DO NOT use this in production!!'\n\n # Flask-SQLAlchemy settings\n SQLALCHEMY_DATABASE_URI = 'sqlite:///blog.db' # File-based SQL database\n SQLALCHEMY_TRACK_MODIFICATIONS = False # Avoids SQLAlchemy warning\n\n # Flask-Mail SMTP server settings\n MAIL_SERVER = 'smtp.gmail.com'\n MAIL_PORT = 465\n MAIL_USE_SSL = True\n MAIL_USE_TLS = False\n MAIL_USERNAME = 'email@example.com'\n MAIL_PASSWORD = 'password'\n MAIL_DEFAULT_SENDER = '\"MyApp\" '\n\n # Flask-User settings\n USER_APP_NAME = \"PAPERBLOG\" # Shown in and email templates and page footers\n USER_ENABLE_EMAIL = False # Enable email authentication\n USER_ENABLE_USERNAME = True # Disable username authentication\n USER_EMAIL_SENDER_NAME = USER_APP_NAME\n USER_EMAIL_SENDER_EMAIL = \"noreply@example.com\"\n\napp = Flask(__name__)\n\n# Class-based application configuration\n# image-upload settings\nUPLOAD_FOLDER = 'static/uploads'\nALLOWED_EXTENSIONS = set(['jpeg', 'jpg', 'png', 'gif'])\napp.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER\n\napp.config.from_object(__name__+'.ConfigClass')\n# Initialize Flask-BabelEx\nbabel = Babel(app)\n# Initialize Flask-SQLAlchemy\ndb = SQLAlchemy(app)\n\n# faker init\n\nfake = Faker()\nadmin = Admin(app)\nfrom wtf_tinymce import wtf_tinymce\nwtf_tinymce.init_app(app)\n\n# Define the User data-model.\n# NB: Make sure to add flask_user UserMixin !!!\n\nclass Categories(db.Model):\n __tablename_ = 'categories'\n id = db.Column(db.Integer, primary_key=True)\n category_name = db.Column(db.String(120), nullable=False)\n created = db.Column(db.DateTime, default=datetime.datetime.utcnow)\n\n def __init__(self, category_name):\n self.category_name = category_name\n\n def __repr__(self):\n return '%r' % (self.category_name)\n\n\nclass Pages(db.Model):\n __tablename__ = 'pages'\n\n id = db.Column(db.Integer, primary_key=True)\n category = db.Column(db.Integer, db.ForeignKey('categories.id'))\n title = db.Column(db.String(1000))\n content = db.Column(db.Text())\n page_created = db.Column(db.DateTime, default=datetime.datetime.utcnow)\n topic_name = db.Column(db.String(120), nullable=False)\n\n def __init__(self, title, content, topic_name, category):\n self.title = title\n self.content = content\n self.topic_name = topic_name\n self.category = category\n\n def __repr__(self):\n return '' % (self.id, self.title, self.content)\n\nclass User(db.Model, UserMixin):\n __tablename__ = 'users'\n id = db.Column(db.Integer, primary_key=True)\n active = db.Column('is_active', db.Boolean(), nullable=False, server_default='1')\n # User authentication information. The collation='NOCASE' is required\n # to search case insensitively when USER_IFIND_MODE is 'nocase_collation'.\n username = db.Column(db.String(100, collation='NOCASE'), nullable=False, unique=True)\n password = db.Column(db.String(255), nullable=False, server_default='')\n email_confirmed_at = db.Column(db.DateTime())\n # User information\n first_name = db.Column(db.String(100, collation='NOCASE'), nullable=False, server_default='')\n last_name = db.Column(db.String(100, collation='NOCASE'), nullable=False, server_default='')\n # Define the relationship to Role via UserRoles\n roles = db.relationship('Role', secondary='user_roles')\n# Define the Role data-model\nclass Role(db.Model):\n __tablename__ = 'roles'\n id = db.Column(db.Integer(), primary_key=True)\n name = db.Column(db.String(50), unique=True)\n# Define the UserRoles association table\nclass UserRoles(db.Model):\n __tablename__ = 'user_roles'\n id = db.Column(db.Integer(), primary_key=True)\n user_id = db.Column(db.Integer(), db.ForeignKey('users.id', ondelete='CASCADE'))\n role_id = db.Column(db.Integer(), db.ForeignKey('roles.id', ondelete='CASCADE'))\n\n # Setup Flask-User and specify the User data-model\nuser_manager = UserManager(app, db, User)\n\nadmin.add_view(ModelView(Categories, db.session))\nadmin.add_view(ModelView(Pages, db.session))\n # Create all database tables\ndb.create_all()\n\n # Create 'member@example.com' user with no roles\nif not User.query.filter(User.username == 'member').first():\n user = User(\n username='member',\n email_confirmed_at=datetime.datetime.utcnow(),\n password=user_manager.hash_password('Password1'),\n )\n db.session.add(user)\n db.session.commit()\n\n # Create 'admin@example.com' user with 'Admin' and 'Agent' roles\nif not User.query.filter(User.username == 'droidthelast').first():\n user = User(\n username='droidthelast',\n email_confirmed_at=datetime.datetime.utcnow(),\n password=user_manager.hash_password('Password1'),\n )\n user.roles.append(Role(name='Admin'))\n user.roles.append(Role(name='Agent'))\n db.session.add(user)\n db.session.commit()\n\nclass CategoriesForm(FlaskForm):\n categories = StringField('Category', validators=[DataRequired()])\n submit = SubmitField(u'Update')\n\ndef cate_form():\n return Categories.query\n\nclass PagesForm(FlaskForm):\n categories = QuerySelectField('Categories', query_factory=cate_form, get_label='Categories', allow_blank=False)\n title = StringField('Title', validators=[DataRequired()])\n content = TinyMceField(\n 'Content',\n tinymce_options={'toolbar': 'bold italic | link | code'}\n )\n topic = StringField('Topic', validators=[DataRequired()])\n submit = SubmitField(u'Upload')\n\n@app.route('/', methods=['POST', 'GET'])\ndef index():\n\tpages = Pages.query.all()\n\treturn render_template('index.html', pages=pages)\n\n\n@app.route('/new_post/')\n@login_required\n@roles_required('Admin')\ndef new_post():\n form = PagesForm()\n return render_template('newpost.html', form=form) \n\n@app.route('/new_category/')\n@login_required\n@roles_required('Admin')\ndef new_category():\n form = CategoriesForm()\n return render_template('newcategory.html', form=form) \n\n@app.route('/post/')\ndef post(page_id):\n\tpage = Pages.query.filter_by(id=page_id).first()\n\treturn render_template('single-post.html', id=page.id, category=page.category, title=page.title, page_created=page.page_created, content=page.content)\n\n@app.route('/edit-page/')\n@login_required\ndef edit_page(page_id):\n page = Pages.query.filter_by(id=page_id).first()\n return render_template('edit.html', id=page.id, category=page.category, title=page.title, page_created=page.page_created, content=page.content)\n\n@app.route('/update-post/', methods=['POST'])\n@login_required\ndef update_post():\n page_id = request.form['id']\n category = request.form['category']\n title = request.form['title']\n content = request.form['content']\n page_created = request.form['page_created']\n Pages.query.filter_by(id=page_id).update({'title': title, 'category': category, 'page_created': page_created, 'content': content})\n db.session.commit()\n return redirect('/post/' + page_id)\n\n@app.route('/save-post/', methods=['POST', 'GET'])\n@login_required\n@roles_required('Admin')\ndef save_post():\n form = PagesForm()\n page = Pages(title=form.title.data, category=form.categories.data, content=form.content.data, topic_name=form.topic.data)\n db.session.add(page)\n db.session.commit()\n return redirect('/post/%d' % page.id)\n\n@app.route('/save_cat/', methods=['POST', 'GET'])\n@login_required\n@roles_required('Admin')\ndef save_cat():\n form = CategoriesForm()\n categ = Categories(category_name=form.categories.data)\n db.session.add(categ)\n db.session.commit()\n return redirect('/')\n\n@app.route('/delete-page/')\n@login_required\ndef delete_page(page_id):\n db.session.query(Pages).filter_by(id=page_id).delete()\n db.session.commit()\n return redirect('/')\n\nif __name__=='__main__':\n\tapp.run(debug=True)","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":8809,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"580483269","text":"#import os\nfrom Product import Product\nfrom NIBORLAN import middle_to_after\nfrom NIBORLAN import expression_to_value\nfrom time import sleep\nclass Prepare:\n # 题目对象数组\n quesList=[]\n # 需要的题目数量\n quesCount = 10\n # 运算数范围\n operRange = 10\n # 操作符个数,当前无参数\n operCount = 3\n # 出现分数的概率\n decChance = 0.5\n #给定的题目文件名\n exercisefile = ''\n #给定的答案文件名\n answerfile = ''\n\n def __init__(self,argv):\n initSuccess=self.checkArgv(argv)\n\n if initSuccess == 0:\n return\n else:\n self.quesList=self.createQuestionList(self.quesCount,self.operRange,self.operCount,self.decChance)\n self.compareResult=self.compareFile(self.exercisefile,self.answerfile)\n\n #命令行参数判断\n def checkArgv(self, argv):\n i = 0\n while i < len(argv):\n command = argv[i]\n\n # 设置存储题目数.\n if command == \"-n\":\n i += 1\n if 0 < int(argv[++i]) and int(argv[++i]) < 99999:\n self.quesCount = int(argv[++i])\n else:\n print(\"命令行-n后的参数\",argv[i],\"错误\")\n return False\n\n # 设置题目中运算数范围\n elif command == \"-r\":\n i += 1\n if 0 < int(argv[++i]) and int(argv[++i]) < 99999:\n self.operRange = int(argv[++i])\n else:\n print(\"命令行-r后的参数\",argv[i],\"错误\")\n return False\n\n # 设置题目中运算数个数\n elif command == \"-c\":\n i += 1\n if 0 < int(argv[++i]) and int(argv[++i]) < 5:\n self.operCount = int(argv[++i])\n else:\n print(\"命令行-c后的参数\",argv[i],\"错误\")\n return False\n\n # 设置题目中小数出现的概率\n elif command == \"-d\":\n i += 1\n if 0 <= float(argv[++i]) and float(argv[++i]) <= 1:\n self.decChance = float(argv[++i])\n else:\n print(\"命令行-d后的参数\",argv[i],\"错误\")\n return False\n\n #给定的题目文件exercisefile.txt\n elif command == \"-e\":\n i += 1\n if( len(argv[++i]) >0 ):\n self.exercisefile=argv[++i]\n print(argv[++i])\n else:\n print(\"命令行-e后的参数\",argv[i],\"错误\")\n return False\n\n #给定的用户文件answerfile.txt\n elif command == \"-a\":\n i += 1\n if( len(argv[++i]) >0 ):\n self.answerfile=argv[++i]\n print(argv[++i])\n else:\n print(\"命令行-a后的参数\",argv[i],\"错误\")\n return False\n\n i += 1\n return True\n\n\n #生成题目\n def createQuestionList(self,count,operRange,operCount,decChance):\n '''\n count: 题目个数\n operRange: 题目操作数范围\n operCount: 题目操作数个数\n decChance: 出现分数的概率\n '''\n qList=[]\n i = 0\n while i < count:\n newQues = Product(operRange,operCount,decChance)\n #调用查重,若重复就在重新初始化一个题目组\n while self.checkRepeat(newQues,qList):\n newQues = Product(operRange, operCount, decChance)\n\n # 将生成的题目推入数组中\n qList.append({\n \"problemArray\":newQues.__dict__['problemArray'],\n \"exStr\":newQues.__dict__['exStr'],\n \"answer\":newQues.__dict__['answer'],\n \"answerStr\":newQues.__dict__['answerStr']\n })\n i += 1\n return qList\n\n #查重\n def checkRepeat(self,newQues,qList):\n problemArray=newQues.__dict__['problemArray']\n for item in qList:\n if problemArray == item['problemArray']:\n return True\n return False\n\n #返回题目列表\n def getQuestionList(self):\n return self.quesList\n\n # 对给定问题文件和用户答案文件,对比后得到的分数\n def compareFile(self, efile, afile):\n '''\n efile: 题目文件名\n afile: 答案文件名\n '''\n #题目文件按行读取的列表\n elines = []\n #用户文件按行读取的列表\n alines = []\n #标准答案的列表\n eanswer = []\n #答对的题号列表\n rightList = []\n #答错的题目列表\n wrongList = []\n\n j = 0\n with open('exercisefile.txt', 'r') as f1:\n elines.append((f1.read().splitlines()))\n print(elines)\n\n with open('answerfile.txt', 'r') as f2:\n alines.append((f2.read().splitlines()))\n print(alines)\n\n for eline in elines:\n elineprace = eline\n #标准答案eanswer列表\n for i in elineprace:\n eanswer.append(str(expression_to_value(middle_to_after(str(i)))))\n print(eanswer)\n user=alines[0]\n print(user)\n #统计答案文件的对错情况\n while j < len(eanswer):\n if(eanswer[j] == user[j]):\n rightList.append(j+1)\n else:\n wrongList.append(j+1)\n j += 1\n print(rightList,wrongList)\n return rightList,wrongList\n\n\n","sub_path":"Prepare.py","file_name":"Prepare.py","file_ext":"py","file_size_in_byte":5669,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"15338864","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sat Jul 6 17:17:50 2019\n\n@author: rajdua\n\nDescription: Use logistic regression to train on data from 2002-2013 and produce\nan output file with predictions for 2014+. Uses entire feature set. Doesn't artifically\ndouble dataset.\n\"\"\"\n\n\nimport pandas as pd\nimport numpy as np\n\ndata = pd.read_csv('FinalData_Cleaned.csv', encoding='latin-1', low_memory = False)\ndata = data.drop(columns = ['Unnamed: 0'])\n\ndata = data.sort_values(by = ['Date', 'players'])\n\ndata = data.reset_index()\n\na = data.iloc[::4, :]\n\nb = data.iloc[3::4, :]\n\ndata = pd.concat([a, b])\n \n\n\ndata['Date'] = pd.to_datetime(data['Date'])\n\ndate = pd.to_datetime('2013')\n\ndataLate = data[(data.Date > date)]\n\ndata['Date'] = pd.to_datetime(data['Date'])\n\ndate = pd.to_datetime('2002')\n\ndata = data[(data.Date > date)]\n\ndate = pd.to_datetime('2013')\n\ndata = data[(data.Date < date)]\n\nX = data[['Best of', 'WRank', 'LRank', 'winner_hand', 'winner_ht', 'winner_age',\n 'loser_hand', 'loser_ht', 'loser_age', 'SOT', 'Major', 'oddsw', 'oddsl',\n 'Clay', 'Hard', 'Grass', 'Carpet', 'Wcomb', 'Lcomb', 'RTrendW', 'RTrendL',\n 'WInverseRank', 'LInverseRank', 'CWPW', 'CWPL', 'POSW', 'POSL', 'PINW',\n 'PINL', 'GPW', 'DSWW', 'DSLW', 'CSWW', 'CSLW', 'TieWW', 'TieLW', 'FSIW', 'FSWW',\n 'BPFGW', 'BPWGW', 'BPFCW', 'BPWCW', 'DSWL', 'DSLL', 'CSWL', 'CSLL',\n 'TieWL', 'TieLL', 'APSGL', 'FSIL', 'FSWL', 'BPFGL', 'BPWGL', 'BPFCL',\n 'BPWCL', 'TSSW', 'TSSL', 'GPL']]\n\nX = X.replace('Nan', np.nan).astype(float)\n# X = X.fillna(0)\n\nX = X.fillna(X.mean())\n\ny = data[['y']]\n\nfrom sklearn.linear_model import LogisticRegressionCV\nfrom sklearn.model_selection import train_test_split\nfrom sklearn import metrics\nfrom sklearn.preprocessing import StandardScaler\n\nX_train, X_test, y_train, y_test = train_test_split(X.values, y.values, test_size=0.3, random_state=0)\n\nscaler = StandardScaler()\nscaler.fit(X)\nX_train = scaler.transform(X_train)\nX_test2 = X_test\nX_test = scaler.transform(X_test)\nlogreg = LogisticRegressionCV(penalty = 'elasticnet', solver = 'saga', max_iter = 50000, \n l1_ratios = [0.1, 0.1], Cs = 10, cv = 5)\nlogreg.fit(X_train, y_train.ravel())\n\n\nprint('Accuracy of logistic regression classifier on test set:')\nprint(logreg.score(X_test, y_test))\n\nX_scaled = scaler.transform(X)\npredictions = logreg.predict_proba(X_scaled)\n\nprint('Accuracy of logistic regression classifier on entire dataset:')\nprint(logreg.score(X_scaled, y))\n\na = logreg.coef_\n\ncoef_df = pd.DataFrame(np.transpose(a))\ncoef_df['names'] = X.columns\n\ncoef_df.to_csv('LogRegCoef3.csv')\n\n\nbetting = data[['oddsw', 'oddsl']]\nbetting['predictions1'] = predictions[:,1]\nbetting['result'] = data['y']\nbetting['predictions2'] = predictions[:,0]\n\nbetting['impliedodds1'] = betting['oddsw'].apply(lambda x: 1/ x)\nbetting['impliedodds2'] = betting['oddsl'].apply(lambda x: 1/ x)\nbetting['date'] = data['Date']\nbetting['Player1'] = data['Winner']\nbetting['Player2'] = data['Loser']\nbetting['Rank1'] = data['WRank']\nbetting['Rank2'] = data['LRank']\n\nbetting = betting.rename(columns = {'oddsw':'odds1', 'oddsl':'odds2'})\n\nbetting.to_csv('Predictions(Log_Reg)3.csv')\n\ndata['impliedodds1'] = data['oddsw'].apply(lambda x: 1/ x)\ndata['impliedodds2'] = data['oddsl'].apply(lambda x: 1/ x)\ndata['predictions1'] = predictions[:,1]\ndata['predictions2'] = predictions[:,0]\n\ndata.to_csv('Data_and_predictions(Log_Reg)3.csv')\n\n\nX_test2 = dataLate[['Best of', 'WRank', 'LRank', 'winner_hand', 'winner_ht', 'winner_age',\n 'loser_hand', 'loser_ht', 'loser_age', 'SOT', 'Major', 'oddsw', 'oddsl',\n 'Clay', 'Hard', 'Grass', 'Carpet', 'Wcomb', 'Lcomb', 'RTrendW', 'RTrendL',\n 'WInverseRank', 'LInverseRank', 'CWPW', 'CWPL', 'POSW', 'POSL', 'PINW',\n 'PINL', 'GPW', 'DSWW', 'DSLW', 'CSWW', 'CSLW', 'TieWW', 'TieLW', 'FSIW', 'FSWW',\n 'BPFGW', 'BPWGW', 'BPFCW', 'BPWCW', 'DSWL', 'DSLL', 'CSWL', 'CSLL',\n 'TieWL', 'TieLL', 'APSGL', 'FSIL', 'FSWL', 'BPFGL', 'BPWGL', 'BPFCL',\n 'BPWCL', 'TSSW', 'TSSL', 'GPL']]\n\nX_test2 = X_test2.replace('Nan', np.nan).astype(float)\n# X = X.fillna(0)\n\nX_test2 = X_test2.fillna(X_test2.mean())\n\nylate = dataLate[['y']]\n\nX_testLate = scaler.transform(X_test2)\n\n\npredictions = logreg.predict_proba(X_testLate)\nX_test2 = pd.DataFrame(X_test2, columns = X.columns)\nbetting2 = X_test2[['oddsw', 'oddsl']]\nbetting2['predictions1'] = predictions[:,1]\nbetting2['result'] = ylate\nbetting2['predictions2'] = predictions[:,0]\nbetting2['impliedodds1'] = betting2['oddsw'].apply(lambda x: 1/ x)\nbetting2['impliedodds2'] = betting2['oddsl'].apply(lambda x: 1/ x)\nbetting2['date'] = dataLate['Date']\nbetting2['Player1'] = dataLate['Winner']\nbetting2['Player2'] = dataLate['Loser']\nbetting2['Rank1'] = X_test2['WRank']\nbetting2['Rank2'] = X_test2['LRank']\nbetting2 = betting2.rename(columns = {'oddsw':'odds1', 'oddsl':'odds2'})\nbetting2.to_csv('PredictionsTest(Log_Reg)3.csv')\n\n\n\n\n\n ","sub_path":"Logistic_Regression/LogisticRegression(Half).py","file_name":"LogisticRegression(Half).py","file_ext":"py","file_size_in_byte":5007,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"131350650","text":"import argparse\n\nimport os\nimport cv2\nimport json\nimport shutil\nimport numpy as np\nimport pandas as pd\nimport xml.etree.ElementTree as ET\n\nimport wwtool\nfrom wwtool.datasets import Convert2COCO\n\nclass SN62COCO(Convert2COCO):\n def __generate_coco_annotation__(self, annotpath, imgpath):\n \"\"\"\n docstring here\n :param self: \n :param annotpath: the path of each annotation\n :param return: dict() \n \"\"\"\n objects = self.__sn6_parse__(annotpath, imgpath) \n coco_annotations = []\n\n if generate_small_dataset and len(objects) > 0:\n pass\n # wwtool.generate_same_dataset(imgpath, \n # annotpath,\n # dst_image_path,\n # dst_label_path,\n # src_img_format='.png',\n # src_anno_format='.txt',\n # dst_img_format='.png',\n # dst_anno_format='.txt',\n # parse_fun=wwtool.voc_parse,\n # dump_fun=wwtool.simpletxt_dump)\n\n for object_struct in objects:\n bbox = object_struct['bbox']\n segmentation = object_struct['segmentation']\n label = object_struct['label']\n\n xmin, ymin, width, height = bbox\n xmax = xmin + width\n ymax = ymin + height\n area = height * width\n\n if (area <= self.small_object_area) and self.groundtruth:\n self.small_object_idx += 1\n continue\n\n coco_annotation = {}\n coco_annotation['bbox'] = bbox\n coco_annotation['segmentation'] = [segmentation]\n coco_annotation['category_id'] = label\n coco_annotation['area'] = np.float(area)\n\n coco_annotations.append(coco_annotation)\n\n return coco_annotations\n\n def __sn6_parse__(self, label_file, image_file):\n \"\"\"\n (xmin, ymin, xmax, ymax)\n \"\"\"\n objects = []\n if self.groundtruth:\n image_file_name = os.path.splitext(os.path.basename(image_file))[0]\n\n image_name_postfix = image_file_name + '.tif'\n if imageset == 'val':\n if image_name_postfix in valset_image_names:\n pass\n else:\n return []\n\n if imageset == 'train':\n if image_name_postfix in valset_image_names:\n return []\n else:\n pass\n\n save_image = wwtool.generate_image(800, 800, color=(0, 0, 0))\n img = cv2.imread(image_file)\n img_height, img_width, _ = img.shape\n\n image_name = os.path.basename(image_file).split('SN6_{}_AOI_11_Rotterdam_{}_'.format(imageset_file_name, data_source))[1].split('.tif')[0]\n masks = sn6_parse.sn6_parse(image_name)\n objects_small_save = []\n total_object_num = len(masks)\n small_object_num = 0\n large_object_num = 0\n total_object_num = 0\n for mask in masks:\n object_struct = {}\n object_struct_small = {}\n xmin, ymin, xmax, ymax = wwtool.pointobb2bbox(mask['segmentation'])\n bbox_w = xmax - xmin\n bbox_h = ymax - ymin\n\n total_object_num += 1\n if bbox_h * bbox_w <= small_size:\n small_object_num += 1\n if bbox_h * bbox_w >= large_object_size:\n large_object_num += 1\n\n object_struct['bbox'] = [xmin, ymin, bbox_w, bbox_h]\n object_struct['segmentation'] = mask['segmentation']\n object_struct['label'] = 1\n\n object_struct_small = object_struct.copy()\n object_struct_small['bbox'] = [xmin, ymin, xmax, ymax]\n object_struct_small['label'] = 'building'\n\n objects_small_save.append(object_struct_small)\n objects.append(object_struct)\n\n if total_object_num > self.max_object_num_per_image:\n self.max_object_num_per_image = total_object_num\n\n if just_keep_small or generate_small_dataset:\n if small_object_num >= total_object_num * small_object_rate and large_object_num < 1 and len(objects_small_save) > 0:\n # print(os.path.join(dst_image_path, image_file_name + '.png'))\n save_image[0:img_height, 0:img_width, :] = img\n cv2.imwrite(os.path.join(dst_image_path, image_file_name + '.png'), save_image)\n anno_file = os.path.join(dst_label_path, image_file_name + '.txt')\n wwtool.simpletxt_dump(objects_small_save, anno_file)\n return objects\n else:\n return []\n else:\n return objects\n else:\n obj_struct = {}\n obj_struct['segmentation'] = [0, 0, 0, 0, 0, 0, 0, 0]\n obj_struct['bbox'] = [0, 0, 0, 0]\n obj_struct['label'] = 0\n\n objects.append(obj_struct)\n\n return objects\n\nif __name__ == \"__main__\":\n # basic dataset information\n info = {\"year\" : 2019,\n \"version\" : \"1.0\",\n \"description\" : \"SN6-COCO\",\n \"contributor\" : \"Jinwang Wang\",\n \"url\" : \"jwwangchn.cn\",\n \"date_created\" : \"2019\"\n }\n \n licenses = [{\"id\": 1,\n \"name\": \"Attribution-NonCommercial\",\n \"url\": \"http://creativecommons.org/licenses/by-nc-sa/2.0/\"\n }]\n\n # dataset's information\n image_format='.tif'\n anno_format='.csv'\n\n data_source = 'SAR-Intensity' # SAR-Intensity or PS-RGB\n if data_source == 'SAR-Intensity':\n image_fold = 'SAR'\n else:\n image_fold = 'RGB'\n\n original_sn6_class = {'building' : 1}\n\n converted_sn6_class = [{'supercategory': 'none', 'id': 1, 'name': 'building'}]\n\n core_dataset_name = 'sn6'\n imagesets = ['train', 'val', 'trainval']\n if imagesets[0] == 'test':\n imageset_file_name = 'Test_Public'\n else:\n imageset_file_name = 'Train'\n\n valset_image_names = []\n\n release_version = 'v1'\n rate = '1.0'\n groundtruth = True\n keypoint = False\n \n just_keep_small = False\n generate_small_dataset = False\n small_size = 16 * 16\n small_object_rate = 0.5\n large_object_size = 64 * 64\n\n anno_name = [core_dataset_name, release_version, data_source]\n if just_keep_small:\n anno_name.append('small_object')\n\n if generate_small_dataset:\n dst_image_path = '/data/small/{}/{}'.format(core_dataset_name, image_fold)\n dst_label_path = '/data/small/{}/labels'.format(core_dataset_name)\n wwtool.mkdir_or_exist(dst_image_path)\n wwtool.mkdir_or_exist(dst_label_path)\n\n if keypoint:\n for idx in range(len(converted_sn6_class)):\n converted_sn6_class[idx][\"keypoints\"] = ['top', 'right', 'bottom', 'left']\n converted_sn6_class[idx][\"skeleton\"] = [[1,2], [2,3], [3,4], [4,1]]\n anno_name.append('keypoint')\n \n if groundtruth == False:\n anno_name.append('no_ground_truth')\n\n for imageset in imagesets:\n imgpath = './data/{}/{}/{}/{}'.format(core_dataset_name, release_version, imageset, image_fold)\n annopath = './data/{}/{}/{}/labels'.format(core_dataset_name, release_version, imageset)\n save_path = './data/{}/{}/coco/annotations'.format(core_dataset_name, release_version)\n if not os.path.exists(save_path):\n os.makedirs(save_path)\n\n if imageset in ['train', 'val', 'trainval']:\n anno_file = os.path.join(annopath, 'SN6_Train_AOI_11_Rotterdam_Buildings.csv')\n sn6_parse = wwtool.SN6Parse(anno_file)\n\n valset_file = './tools/datasets/sn6/val.csv'\n valset_data = pd.read_csv(valset_file)\n valset_data = valset_data.dropna(axis=0)\n for idx in range(valset_data.shape[0]):\n valset_image_names.append(valset_data.iloc[idx, 0])\n\n sn6 = SN62COCO(imgpath=imgpath,\n annopath=annopath,\n image_format=image_format,\n anno_format=anno_format,\n data_categories=converted_sn6_class,\n data_info=info,\n data_licenses=licenses,\n data_type=\"instances\",\n groundtruth=groundtruth,\n small_object_area=0)\n\n images, annotations = sn6.get_image_annotation_pairs()\n\n json_data = {\"info\" : sn6.info,\n \"images\" : images,\n \"licenses\" : sn6.licenses,\n \"type\" : sn6.type,\n \"annotations\" : annotations,\n \"categories\" : sn6.categories}\n\n anno_name.insert(1, imageset)\n with open(os.path.join(save_path, \"_\".join(anno_name) + \".json\"), \"w\") as jsonfile:\n json.dump(json_data, jsonfile, sort_keys=True, indent=4)\n","sub_path":"tools/datasets/sn6/sn62coco.py","file_name":"sn62coco.py","file_ext":"py","file_size_in_byte":9325,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"558800317","text":"import sys\nsys.path.insert(0,'..')\n\nimport itertools\nimport os\nimport pickle\nimport sys\nimport copy\nimport numpy as np\nimport random\nimport tensorflow as tf\nfrom argparse import Namespace\n\nfrom data import Data\n#from acquisition_functions import acq_fn\n#from bo.bo.probo import ProBO\n#from bo.dom.list import ListDomain\nfrom bo.pp.pp_gp_my_distmat import MyGpDistmatPP\n#from argparse import Namespace\n\nfrom tqdm import tqdm\nfrom cyDPP.decompose_kernel import decompose_kernel\nfrom cyDPP.sample_dpp import sample_dpp\n\ndef run_batch_nas_algorithm(search_space,algo_params):\n\n # run nas algorithm\n ps = copy.deepcopy(algo_params)\n algo_name = ps['algo_name']\n\n if algo_name == 'random':\n data = random_search(search_space, **ps)\n elif algo_name == 'evolution':\n data = evolution_search(search_space, **ps)\n elif \"gp\" in algo_name:\n data = gp_batch_bayesopt_search(search_space, **ps)\n else:\n print('invalid algorithm name')\n sys.exit()\n\n k = 1\n if 'k' in ps:\n k = ps['k']\n\n result_val=compute_best_val_losses(data, k, len(data))\n result_test=compute_best_test_losses(data, k, len(data))\n return result_val,result_test\n\n\n\ndef compute_best_test_losses(data, k, total_queries):\n \"\"\"\n Given full data from a completed nas algorithm,\n output the test error of the arch with the best val error \n after every multiple of k\n \"\"\"\n results = []\n for query in range(k, total_queries + k, k):\n best_arch = sorted(data[:query], key=lambda i:i[3])[0]\n test_error = best_arch[3]\n results.append((query, test_error))\n\n return results\n\ndef compute_best_val_losses(data, k, total_queries):\n \"\"\"\n Given full data from a completed nas algorithm,\n output the test error of the arch with the best val error \n after every multiple of k\n \"\"\"\n results = []\n for query in range(k, total_queries + k, k):\n best_arch = sorted(data[:query], key=lambda i:i[2])[0]\n test_error = best_arch[2]\n results.append((query, test_error))\n\n return results\n\n\ndef random_search(search_space,\n total_queries=100, \n k=10,\n allow_isomorphisms=False, \n deterministic=True,\n verbose=1):\n \"\"\" \n random search\n \"\"\"\n data = search_space.generate_random_dataset(num=total_queries, \n allow_isomorphisms=allow_isomorphisms, \n deterministic_loss=deterministic)\n \n val_losses = [d[2] for d in data]\n \n #top 10\n val_losses = [np.asscalar(d[2]) for d in data]\n top_arches_idx = np.argsort(np.asarray(val_losses))[:10] # descending\n top_arches=[data[ii][0] for ii in top_arches_idx]\n\n pickle.dump([top_arches,val_losses], open( \"10_best_architectures.p\", \"wb\" ) )\n \n print(val_losses[top_arches_idx[0]])\n if verbose:\n top_5_loss = sorted([d[2] for d in data])[:min(5, len(data))]\n print('Query {}, top 5 val losses {}'.format(total_queries, top_5_loss)) \n \n \n \n return data\n\n\ndef evolution_search(search_space,\n num_init=10,\n k=10,\n population_size=50,\n total_queries=100,\n tournament_size=10,\n mutation_rate=1.0, \n allow_isomorphisms=False,\n deterministic=True,\n verbose=1):\n \"\"\"\n regularized evolution\n \"\"\"\n \n data = search_space.generate_random_dataset(num=num_init, \n allow_isomorphisms=allow_isomorphisms,\n deterministic_loss=deterministic)\n val_losses = [d[2] for d in data]\n query = num_init\n\n if num_init <= population_size:\n population = [i for i in range(num_init)]\n else:\n population = np.argsort(val_losses)[:population_size]\n\n while query <= total_queries:\n\n # evolve the population by mutating the best architecture\n # from a random subset of the population\n sample = random.sample(population, tournament_size)\n best_index = sorted([(i, val_losses[i]) for i in sample], key=lambda i:i[1])[0][0]\n mutated = search_space.mutate_arch(data[best_index][0], mutation_rate)\n #permuted = search_space.perturb_arch(data[best_index][0])\n\n archtuple = search_space.query_arch(mutated, deterministic=deterministic)\n \n data.append(archtuple)\n val_losses.append(archtuple[2])\n population.append(len(data) - 1)\n\n # kill the worst from the population\n if len(population) >= population_size:\n worst_index = sorted([(i, val_losses[i]) for i in population], key=lambda i:i[1])[-1][0]\n population.remove(worst_index)\n\n if verbose and (query % k == 0):\n top_5_loss = sorted([d[2] for d in data])[:min(5, len(data))]\n print('Query {}, top 5 val losses {}'.format(query, top_5_loss))\n\n query += 1\n\n return data\n\ndef GP_ThompsonSampling(myGP,xtrain,ytrain,xtest,modelp,newls,batch_size=5):\n\n localGP=copy.deepcopy(myGP) \t# update myGP\n mu_test,sig_test=localGP.gp_post_cache(xtrain,ytrain,xtest,ls=newls,alpha=1,sigma=1e-3)\n mu_test=np.ravel(mu_test)\n # normalise mu_test\n idx_all=np.random.choice(len(xtest), batch_size, mu_test)\n \n return xtest[idx_all],idx_all\n\n\ndef GP_BUCB(myGP,xtrain,ytrain,xtest,modelp,newls,batch_size=5):\n # Kriging Believer, Constant Liar for Batch BO\n # minimisation problem\n\n def LCB(mu,sigma):\n mu=np.reshape(mu,(-1,1))\n sigma=np.reshape(sigma,(-1,1))\n beta_t=2*np.log(100)\n return mu-beta_t*sigma\n \n x_t_all=[0]*batch_size\n idx_all=[]\n \n localGP=copy.deepcopy(myGP) \t# update myGP\n\n for bb in range(batch_size):\n # update xtrain, ytrain\n data = Namespace()\n data.X = xtrain\n data.y = ytrain\n \n localGP.set_data(data)\n\n mu_test,sig_test=localGP.gp_post_cache(xtrain,ytrain,xtest,ls=newls,alpha=1,sigma=1e-3)\n \n acq_value=LCB(mu_test,np.diag(sig_test))\n idxbest=np.argmin(acq_value )\n \n idx_all=np.append(idx_all,idxbest)\n x_t=xtest[idxbest]\n x_t_all[bb]=x_t\n \n xtrain=np.append(xtrain,x_t)\n ytrain=np.append(ytrain,mu_test[idxbest])\n \n return x_t_all,idx_all\n\n\ndef GP_KDPP_Quality(myGP,xtrain,ytrain,xtest,newls,batch_size=5) :\n# KDPP for sampling diverse + quality items\n\n localGP=copy.deepcopy(myGP)\n N=len(xtest)\n mu_test,sig_test=localGP.gp_post(xtrain,ytrain,xtest,ls=newls,alpha=1,sigma=1e-3)\n \n score=np.exp(-mu_test)\n\n qualityK=np.zeros((N,N))+np.eye(N)*score.reshape((-1,1))\n\n L=qualityK*sig_test*qualityK\n\t\n\t# decompose it into eigenvalues and eigenvectors\n vals, vecs = decompose_kernel(L)\n\n dpp_sample = sample_dpp(vals, vecs, k=batch_size)\n x_t_all=[ xtest[ii] for ii in dpp_sample]\n return x_t_all,dpp_sample\n\ndef GP_KDPP(myGP,xtrain,ytrain,xtest,newls,batch_size=5) :\n# KDPP for sampling diverse + quality items\n\n localGP=copy.deepcopy(myGP)\n mu_test,sig_test=localGP.gp_post(xtrain,ytrain,xtest,ls=newls,alpha=1,sigma=1e-3)\n \n #qualityK=np.zeros((N,N))+np.eye(N)*mu_test.reshape((-1,1))\n\n L=sig_test\n\t\n\t# decompose it into eigenvalues and eigenvectors\n vals, vecs = decompose_kernel(L)\n\n dpp_sample = sample_dpp(vals, vecs, k=batch_size)\n x_t_all=[ xtest[ii] for ii in dpp_sample]\n return x_t_all,dpp_sample\n\ndef optimize_GP_hyper(myGP,xtrain,ytrain,distance):\n if distance==\"tw_3_distance\" or distance ==\"tw_distance\":\n newls=myGP.optimise_gp_hyperparameter_v3(xtrain,ytrain,alpha=1,sigma=1e-4)\n #mu_train,sig_train=myGP.gp_post_v3(xtrain,ytrain,xtrain,ls=newls,alpha=1,sigma=1e-4)\n #mu_test,sig_test=myGP.gp_post_v3(xtrain,ytrain,xtest,ls=newls,alpha=1,sigma=1e-4)\n elif distance==\"tw_2_distance\":\n newls=myGP.optimise_gp_hyperparameter_v2(xtrain,ytrain,alpha=1,sigma=1e-4)\n #mu_train,sig_train=myGP.gp_post_v3(xtrain,ytrain,xtrain,ls=newls,alpha=1,sigma=1e-4)\n #mu_test,sig_test=myGP.gp_post_v3(xtrain,ytrain,xtest,ls=newls,alpha=1,sigma=1e-4)\n else:\n newls=myGP.optimise_gp_hyperparameter(xtrain,ytrain,alpha=1,sigma=1e-3)\n #mu_train,sig_train=myGP.gp_post(xtrain,ytrain,xtrain,ls=newls,alpha=1,sigma=1e-3)\n #mu_test,sig_test=myGP.gp_post(xtrain,ytrain,xtest,ls=newls,alpha=1,sigma=1e-3)\n return newls\n \ndef gp_batch_bayesopt_search(search_space,\n num_init=10,\n batch_size=5,\n total_queries=100,\n distance='edit_distance',\n algo_name='gp_bucb',\n deterministic=True,\n nppred=1000):\n \"\"\"\n Bayesian optimization with a GP prior\n \"\"\"\n num_iterations = total_queries - num_init\n\n # black-box function that bayesopt will optimize\n def fn(arch):\n return search_space.query_arch(arch, deterministic=deterministic)[2]\n\n # this is GP\n modelp = Namespace(kernp=Namespace(ls=0.11, alpha=1, sigma=1e-5), #ls=0.11 for tw\n infp=Namespace(niter=num_iterations, nwarmup=5),#500\n distance=distance, search_space=search_space.get_type())\n modelp.distance=distance\n\n\n\t# Set up initial data\n init_data = search_space.generate_random_dataset(num=num_init, \n deterministic_loss=deterministic)\n\n xtrain = [d[0] for d in init_data]\n ytrain = np.array([[d[2]] for d in init_data])\n \n # init\n data = Namespace()\n data.X = xtrain\n data.y = ytrain\n \n myGP=MyGpDistmatPP(data,modelp,printFlag=False)\n\n for ii in tqdm(range(num_iterations)):##\n \n ytrain_scale=(ytrain-np.mean(ytrain))/np.std(ytrain)\n\n\n data = Namespace()\n data.X = xtrain\n data.y = ytrain_scale\n \n myGP.set_data(data) #update new data\n\n xtest=search_space.get_candidate_xtest(xtrain,ytrain)\n xtest=xtest[:100]\n\n \n \n # this is to enforce to reupdate the K22 between test points\n myGP.K22_d=None\n myGP.K22_d1=None\n\n\t # generate xtest # check here, could be wrong\n #xtest = mylist.unif_rand_sample(500)\n \n if ii%5==0:\n newls=optimize_GP_hyper(myGP,xtrain,ytrain_scale,distance)\n\n # select a batch of candidate\n if algo_name==\"gp_bucb\":\n x_batch,idx_batch=GP_BUCB(myGP,xtrain,ytrain_scale,xtest,modelp,newls,batch_size) \n elif algo_name==\"gp_kdpp\":\n x_batch,idx_batch=GP_KDPP(myGP,xtrain,ytrain_scale,xtest,newls,batch_size) \n elif algo_name==\"gp_kdpp_quality\":\n x_batch,idx_batch=GP_KDPP_Quality(myGP,ytrain_scale,ytrain,xtest,newls,batch_size) \n elif algo_name==\"gp_kdpp_rand\":\n idx_batch = np.random.choice( len(xtest), size=batch_size, replace=False)\n x_batch=[xtest[ii] for ii in idx_batch]\n elif algo_name==\"gp_ts\":\n x_batch,idx_batch=GP_ThompsonSampling(myGP,xtrain,ytrain_scale,xtest,modelp,newls,batch_size) \n # evaluate the black-box function\n for xt in x_batch:\n yt=fn(xt)\n xtrain=np.append(xtrain,xt)\n ytrain=np.append(ytrain,yt)\n \n print(np.min(ytrain))\n \n # get the validation and test loss for all architectures chosen by BayesOpt\n results = []\n for arch in xtrain:\n archtuple = search_space.query_arch(arch,deterministic=deterministic)\n results.append(archtuple)\n\n return results\n\n\n","sub_path":"batch_nas_algorithms.py","file_name":"batch_nas_algorithms.py","file_ext":"py","file_size_in_byte":11878,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"528758733","text":"# Python\n\n# Third\nfrom mongoengine.errors import NotUniqueError, ValidationError\n\n# Apps\n\n# Local\nfrom .models import Dataset, Log\nfrom apps.responses import Response\n\n\nclass DatasetRepo:\n def __init__(self):\n self.model = Dataset\n self.resource = \"Dataset\"\n self.response = Response(self.resource)\n\n def create(self, data: dict):\n try:\n return self.model(**data).save()\n\n except NotUniqueError as e:\n raise e\n\n except ValidationError as e:\n raise e\n\n except Exception as e:\n raise e\n\n def by_id(self, object_id):\n try:\n return self.model.objects.get(id=object_id)\n\n except Exception as e:\n return self.response.exception(description=e.__str__())\n\n def by_criteria(\n self, criteria: dict, order: str = \"created\", items: int = None, status=None\n ):\n try:\n if status:\n dataset = self.model.objects(status, **criteria).order_by(order)\n else:\n dataset = self.model.objects(**criteria).order_by(order)\n if items:\n return dataset[:items]\n\n return dataset\n\n except Exception as e:\n return self.response.exception(description=e.__str__())\n\n def paginate(self, criteria: dict, page, per_page, order: str = \"created\"):\n try:\n return (\n self.model.objects(**criteria).order_by(order).paginate(page, per_page)\n )\n\n except Exception as e:\n raise e\n\n\nclass LogRepo:\n def __init__(self):\n self.model = Log\n self.resource = \"Log\"\n self.response = Response(self.resource)\n\n def insert(self, logs: list):\n \"\"\"Bulk create\"\"\"\n try:\n return self.model.objects.insert(logs)\n\n except NotUniqueError as e:\n raise e\n\n except ValidationError as e:\n raise e\n\n except Exception as e:\n raise e\n\n def paginate(self, criteria: dict, page, per_page, order: str = \"created\"):\n try:\n return (\n self.model.objects(**criteria).order_by(order).paginate(page, per_page)\n )\n\n except Exception as e:\n raise e\n","sub_path":"api/apps/core/repositories.py","file_name":"repositories.py","file_ext":"py","file_size_in_byte":2270,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"458158430","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Dec 16 14:19:34 2019\n\n@author: verron\n\"\"\"\n\n\nimport networkx as nx\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nfrom ast import literal_eval\nimport config as c\n\n\nclass CoordGPS:\n \n def __init__ (self, lat, lon):\n\t#Création d'une position GPS via ses coordonnées GPS\n self.lat = lat\n self.lon = lon\n\n\n def distance(self):\n Lat,Lon=(c.Solo['Lat']),(c.Solo['Lon'])\n Dist=pd.DataFrame(columns=['Distance'])\n for i in range(163):\n dist=0\n dist=100000*np.sqrt((self.lat-Lat[i])**2 + (self.lon-Lon[i])**2)\n Dist.loc[i,'Distance']=dist\n Tab=Dist.sort_values(by=['Distance']).reset_index(drop=False) #On ne change pas l'index pour avoir accès au numéro des stations\n mask= Tab['Distance']<=Tab['Distance'][0]+175\n tableau=Tab[mask]\n if len(tableau)==0:\n return([Tab[0]])\n return(tableau)\n \n \n def temps_marche(self):\n distance=self.distance()\n liste_temps_marche=[int(i/c.vitesse_marche) for i in list(distance['Distance'])]\n return(liste_temps_marche)\n\nclass Fonctions:\n \n def EnsRes():\n Ligne=c.Metro['Ligne'] #récupère seulement les numeros de ligne\n Reseaux=[]\n LenRes=[]\n LenResSum=[]\n for i in range(1,13):\n Reseaux.append([ligne for ligne in Ligne if ligne==(i)]) \n LenRes.append(len(Reseaux[i-1])) \n LenResSum=np.insert(np.cumsum(LenRes),0,0,axis=0) \n Ensemble=12*[[]]\n for i in range(0,12):\n Ensemble[i]= c.Metro[LenResSum[i]:LenResSum[i+1]]\n Ensemble[i]=Ensemble[i].sort_values(by=['Sens']).reset_index(drop=True)\n return(Ensemble,LenResSum)\n \n \n def dessin(self):\n for ligne in Fonctions.EnsRes()[0]:\n plt.scatter(ligne['Lon'],ligne['Lat'],marker='.')\n plt.plot(ligne['Lon'],ligne['Lat'])\n \n\n def Tuple():\n liste_station=[]\n for df in Fonctions.EnsRes()[0]:\n for station in df[\"Station\"]:\n liste_station.append(station)\n nom=12*[[]]\n liste_tuple=[]\n liste_tuple_rev=[]\n for k in range(0,12):\n nom[k]=liste_station[Fonctions.EnsRes()[1][k]:Fonctions.EnsRes()[1][k+1]]\n for camino in nom:\n for i in range(1,len(camino)):\n liste_tuple.append((camino[i-1],camino[i]))\n liste_tuple_rev.append((camino[i],camino[i-1]))\n return(liste_tuple+liste_tuple_rev)\n \n \n def adjency_matrix():\n Graphe_réseau=nx.DiGraph()\n Graphe_réseau.add_nodes_from(c.Metro['Station'].drop_duplicates(keep='first').reset_index(drop=True))\n Graphe_réseau.add_edges_from(Fonctions.Tuple())\n matrice_adjacence=nx.to_numpy_matrix(Graphe_réseau,nodelist=list(c.Metro['Station'].drop_duplicates(keep='first')))\n for i in range(len(matrice_adjacence)):\n for j in range(len(matrice_adjacence)):\n if i!=j and matrice_adjacence[i,j]==0:\n matrice_adjacence[i,j]=float('inf')\n return(matrice_adjacence)\n \n \n def Floyd_Warshall():\n mat_adj=Fonctions.adjency_matrix() \n (m,v)=np.shape(mat_adj)\n nxt=np.zeros([m,v])\n for i in range(m):\n for j in range(m):\n nxt[i][j]=i # On crée une matrice de prédécesseur avec des nombres qui coorespondent à l'ordre des stations dans self.liste_station\n for k in range(m):\n for i in range(m):\n for j in range(m):\n if mat_adj[i,j] > mat_adj[i,k] + mat_adj[k,j]:\n mat_adj[i,j] = mat_adj[i,k] + mat_adj[k,j]\n nxt[i][j] = nxt[k][j]\n return(mat_adj,nxt) \n \n \n def ConstructPath(i,j):\n mat_pred=Fonctions.Floyd_Warshall()[1]\n if mat_pred[i,j] == float('inf'):\n return []\n path = [j]\n while i!=j :\n j = int(mat_pred[i,j]) \n path.append(j)\n return path\n\n \n def Shortest_path(départ,destination):\n liste_chemins=[]\n Temps=[]\n closest_stat_pt_dep=list(départ.distance()['index'])\n closest_stat_pt_arr=list(destination.distance()['index'])\n k=0\n tps_marche_dep=départ.temps_marche()\n tps_marche_arr=destination.temps_marche()\n for i in closest_stat_pt_dep:\n for j in closest_stat_pt_arr:\n liste_chemins.append(Fonctions.ConstructPath(i,j))\n for liste in liste_chemins:\n time=0\n if len(tps_marche_dep)==1 and len(tps_marche_arr)==1:\n time=c.tps_inter_stat*(len(liste)-1)+tps_marche_dep[0]+tps_marche_arr[0]\n elif len(tps_marche_dep)==1 and len(tps_marche_arr)>1:\n time=c.tps_inter_stat*(len(liste)-1)+tps_marche_dep[0]+tps_marche_arr[k]\n elif len(tps_marche_dep)>1 and len(tps_marche_arr)==1:\n time=c.tps_inter_stat*(len(liste)-1)+tps_marche_dep[k]+tps_marche_arr[0]\n else :\n time=c.tps_inter_stat*(len(liste)-1)+tps_marche_dep[k]+tps_marche_arr[k]\n for i in range(1,len(liste)-1):\n if liste[i] in list(c.Corres['index']) and c.Solo['Ligne'][liste[i-1]]==c.Solo['Ligne'][liste[i+1]]:\n time+=c.tps_corres\n k+=1\n Temps.append(time)\n less_time = min(Temps)\n indice=Temps.index(less_time)\n return(liste_chemins[indice],less_time)\n \n \nclass Réseau(Fonctions):\n \n def __init__(self):\n self.liste_station=list(c.Metro['Station'].drop_duplicates(keep='first'))\n self.Geopoints=[]\n for coordonnées in list(c.Metro['Geopoint'].drop_duplicates(keep='first')):\n (x,y)=literal_eval(coordonnées)\n self.Geopoints.append(CoordGPS(x,y))\n \n \n def Trace(self,départ,destination):\n num_stat=Fonctions.Shortest_path(départ,destination)[0]\n liste_coord=[self.Geopoints[k] for k in num_stat]\n self.dessin()\n plt.scatter(départ.lon,départ.lat,marker='*',c='b',s=150, label='Départ')\n plt.scatter(destination.lon,destination.lat,marker='*',c='r',s=150, label='Arrivée')\n plt.scatter([coord.lon for coord in liste_coord],[coord.lat for coord in liste_coord],marker='.',c='black')\n plt.plot([coord.lon for coord in liste_coord],[coord.lat for coord in liste_coord],c='black',linewidth=2) \n plt.plot([départ.lon,liste_coord[-1].lon],[départ.lat,liste_coord[-1].lat],linestyle='--',c='black')\n plt.plot([destination.lon,liste_coord[0].lon],[destination.lat,liste_coord[0].lat],linestyle='--',c='black')\n plt.legend()\n plt.axis('equal') \n plt.show()\n \n \n def ordre_station(self,départ,destination):\n chemin,temps=Fonctions.Shortest_path(départ,destination)\n chemin_ord=[station for station in reversed(chemin)]\n ligne=[]\n for i in range(len(chemin_ord)-1):\n if c.Solo['Ligne'][chemin_ord[i]]==c.Solo['Ligne'][chemin_ord[i+1]]:\n ligne.append(c.Solo['Ligne'][chemin_ord[i]])\n \n if c.Solo['Ligne'][chemin_ord[i]]==c.Solo['Corresp. 1'][chemin_ord[i+1]]:\n ligne.append(c.Solo['Ligne'][chemin_ord[i]])\n \n if c.Solo['Corresp. 1'][chemin_ord[i]]==c.Solo['Ligne'][chemin_ord[i+1]]:\n ligne.append(c.Solo['Corresp. 1'][chemin_ord[i]])\n \n if c.Solo['Corresp. 2'][chemin_ord[i]]==c.Solo['Ligne'][chemin_ord[i+1]]:\n ligne.append(c.Solo['Corresp. 2'][chemin_ord[i]]) \n \n if c.Solo['Corresp. 3'][chemin_ord[i]]==c.Solo['Ligne'][chemin_ord[i+1]]:\n ligne.append(c.Solo['Corresp. 3'][chemin_ord[i]])\n \n if c.Solo['Ligne'][chemin_ord[i]]==c.Solo['Corresp. 2'][chemin_ord[i+1]]:\n ligne.append(c.Solo['Ligne'][chemin_ord[i]])\n \n if c.Solo['Ligne'][chemin_ord[i]]==c.Solo['Corresp. 3'][chemin_ord[i+1]]:\n ligne.append(c.Solo['Ligne'][chemin_ord[i]]) \n \n if temps // 3600 == 0:\n print(\"En absence de grève, votre trajet devrait durer \",temps//60,\" minute(s) et \", temps%60,\" seconde(s)\") \n \n else:\n print(\"En absence de grève, votre trajet devrait durer \",temps//3600,\" heure(s), \", (temps%3600)//60,\" minutes et \",(temps%3600)%60,\" seconde(s)\" )\n print(f\"Marchez jusqu'à la station {self.liste_station[chemin_ord[0]]} et prenez la ligne {ligne[0]} en direction de {self.liste_station[chemin_ord[1]]}\")\n for k in range(len(ligne)-1):\n if ligne[k]!=ligne[k+1]:\n print(f\"Transférez vers la ligne {ligne[k+1]} à la station {self.liste_station[chemin_ord[k+1]]} direction {self.liste_station[chemin_ord[k+2]]}\")\n print(f\"Descendez à la station {self.liste_station[chemin_ord[-1]]} et marchez jusqu'à votre destination\")\n \n\n\n\n","sub_path":"Bibliotheque_CV_PR.py","file_name":"Bibliotheque_CV_PR.py","file_ext":"py","file_size_in_byte":9189,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"40732052","text":"### 클래스\nclass Unit:\n def __init__(self,name,hp,damage):\n self.name = name # self 는 멤버 변수를 정의하는 것임\n self.hp = hp\n self.damage = damage\n print(\"{0} unit was produced\".format(name))\n print(\"hp : {0}, damage : {1}\".format(hp, damage))\n print()\n\nmarine1 = Unit(\"marine\",40,5)\ntank = Unit(\"tank\",150,35)\n\nmarine2 = Unit(\"upgrade marine\",40,5)\nmarine2.steampack = True # 파이썬은 외부에서 클래스 내부의 멤버 변수를 만드는 것을 허용함\nif marine2.steampack == True:\n print(\"steampack is ready\")\nprint()\n\n\nclass AttackUnit:\n def __init__(self,name,hp,damage):\n self.name = name\n self.hp = hp\n self.damage = damage\n\n def attack(self,location):\n print(\"{0}: attack at {1} for damage {2}\".format(self.name,location,self.damage))\n\n def damaged(self,damage):\n print(\"{0}: {1} damgaed\".format(self.name,damage))\n self.hp -= damage\n print(\"{0}: remaing hp is {1}\".format(self.name,self.hp))\n if self.hp <= 0:\n print(\"unit was dead\")\n print()\n\nclass FlyableUnit:\n def __init__(self, flying_speed):\n self.flying_speed = flying_speed\n \n def fly(self, name, location):\n print(\"{0}: fly towards at {1} speed {2}\".format(name, location, self.flying_speed))\n\nclass ColckingAttackUnit(AttackUnit): # 상속\n def __init__(self, name, hp, damage, clocking):\n AttackUnit.__init__(self,name,hp,damage)\n print(\"{0} unit was produced\".format(name))\n print(\"hp : {0}, damage : {1}\".format(hp, damage))\n self.clocking = clocking\n if clocking == True:\n print(\"clocking is ready\")\n\nclass FlyableAttackUnit(FlyableUnit, AttackUnit): # 다중상속\n def __init__(self,name,hp,damage,flying_speed):\n AttackUnit.__init__(self,name,hp,damage)\n FlyableUnit.__init__(self,flying_speed)\n \n def attack(self, location, direction): # 메소드 오버로딩\n self.fly(self.name,location) # 상속받은 메소드를 이용할 수 있다.\n print(\"{0}\".format(direction))\n\ndef game_start():\n print(\"game start\")\n\ndef game_over():\n pass # pass 키워드는 아무것도 안하고 넘어감\n\ngame_start()\nfirebat1 = AttackUnit(\"firebat\",40,16)\nfirebat1.attack(\"5\")\nfirebat1.damaged(25)\nfirebat1.damaged(25)\nwraith = ColckingAttackUnit(\"wraith\",150,8,True)\nvalkyrie = FlyableAttackUnit(\"valkyrie\",200,6,5)\nvalkyrie.fly(valkyrie.name,3)\nvalkyrie.attack(6,\"sky\")\ngame_over()","sub_path":"Python tutorial/클래스.py","file_name":"클래스.py","file_ext":"py","file_size_in_byte":2527,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"219215508","text":"# -*- coding: utf-8 -*-\n\n\"\"\"Console script for dmriprep.\"\"\"\nimport sys\nimport click\nfrom . import run\nfrom . import io\nimport os\n\n\n@click.command()\n@click.option('--participant-label', help=\"The label(s) of the participant(s) that should be\"\n \"analyzed. The label corresponds to\"\n \"sub- from the BIDS spec (so it does\"\n \"not include 'sub-'). If this parameter is not provided\"\n \"all subjects will be analyzed. Multiple participants\"\n \"can be specified with a space separated list.\",\n default=None\n )\n@click.argument('bids_dir',\n )\n@click.argument('output_dir',\n )\n@click.argument('analysis_level',\n type=click.Choice(['participant', 'group']),\n default='participant')\ndef main(participant_label, bids_dir, output_dir, analysis_level=\"participant\"):\n \"\"\"\n BIDS_DIR: The directory with the input dataset formatted according to the BIDS standard.\n\n OUTPUT_DIR: The directory where the output files should be stored.\n If you are running a group level analysis, this folder\n should be prepopulated with the results of\n the participant level analysis.\n\n ANALYSIS_LEVEL: Level of the analysis that will be performed. Multiple\n participant level analyses can be run independently\n (in parallel).\n \"\"\"\n\n if analysis_level is not 'participant':\n raise NotImplementedError('The only valid analysis level for dmriprep is participant at the moment.')\n\n inputs = io.get_bids_files(participant_label, bids_dir)\n\n for subject_inputs in inputs:\n run.run_dmriprep_pe(**subject_inputs,\n working_dir=os.path.join(output_dir, 'scratch'),\n out_dir=output_dir)\n\n return 0\n\n\nif __name__ == \"__main__\":\n sys.exit(main()) # pragma: no cover\n","sub_path":"dmriprep/cli.py","file_name":"cli.py","file_ext":"py","file_size_in_byte":2044,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"359188286","text":"import random\nx = 1\nname = str(input(\"What is your characters name? \"))\nprint(\"Adding character... \\nSuccessfully added: \" + name)\ndifficulty = str(input(\"What difficulty would you like to play on?\\nEasy \\nMedium \\nHard \\n\"))\nif difficulty.lower() == \"easy\":\n ouch = random.randint(5,10)\n creatures = 10\n print(\"In Easy difficulty there are \" + str(creatures) + \" creatures and they do \" + str(ouch) + \" Damage\")\nelif difficulty.lower() == \"medium\":\n ouch = random.randint(10,15)\n creatures = 10\n print(\"In Medium difficulty there are \" + str(creatures) + \" creatures and they do \" + str(ouch) + \" Damage\")\nelif difficulty.lower() == \"hard\":\n ouch = random.randint(15,25)\n creatures = 10\n print(\"In Hard difficulty there are \" + str(creatures) + \" creatures. \")\nelse:\n print(\"That's not a difficulty \\n\")\n\nask1 = str(input(\"Are you sure you want to play on difficulty \" + str(difficulty) + \"? \"))\n\n\n\ndef round(x, health):\n healingPotion = random.randint(10,20)\n hardcreatures = random.randint(1,5)\n healing = 10\n potionamount = 5\n for y in range(0, hardcreatures):\n health = health - (hardcreatures * ouch) + healing\n if health <= 50:\n potion = str(input(\"You are talking massive damage, would you like to splash a potion of Health? \\n\"))\n print(\"You have only \" + str(health) + \" health left!\")\n if potion.lower() == \"yes\":\n health = health + healingPotion\n potionamount = potionamount - 1\n print(health)\n print(\"You have only \" + str(health) + \" health left!\")\n if health <= 0:\n print(\"Your Died on level \" + x + \"...\")\n\n\n\n\n print(health)\n return health\n\n\nhealth = 100\n\nwhile health > 0:\n if x == 1:\n answer1 = str(input(\"Round 1 is easy, Are you ready? \\n\"))\n else:\n answer1 = str(input(\"Round \" + str(x) + \" will be harder, Are you ready? \\n\"))\n if answer1.lower() == \"yes\":\n health = round(x, health)\n x = x + 1\n else:\n break\nprint(\"Your Died on level \" + str(x) + \"...\")","sub_path":"PycharmProjects/pythonProject0001/game001.py","file_name":"game001.py","file_ext":"py","file_size_in_byte":2099,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"422901066","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Feb 16 14:44:13 2018\n\nhttps://www.hackerrank.com/contests/rookierank-4/challenges/exam-rush\n\"\"\"\nimport sys\n\ndef examRush(tm, t):\n sortedTime = sorted(tm)\n result = 0\n totTime = 0\n i = 0\n for i in range (len(sortedTime)):\n totTime = totTime + sortedTime[i]\n if(totTime > t): \n break\n else:\n result = result + 1\n return i\n \n \n \n\nif __name__ == \"__main__\":\n n, t = input().strip().split(' ')\n n, t = [int(n), int(t)]\n tm = []\n tm_i = 0\n for tm_i in range(n):\n tm_t = int(input().strip())\n tm.append(tm_t)\n result = examRush(tm, t)\n print(result)","sub_path":"HackerRank/Competition/RookieRank/exam-rush.py","file_name":"exam-rush.py","file_ext":"py","file_size_in_byte":692,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"218895373","text":"#!/usr/bin/python3\n\"\"\" Module for State objects that handles all defaults RestFul API \"\"\"\nfrom api.v1.views import app_views\nfrom models.city import City\nfrom models.state import State\nfrom models import storage\nfrom flask import jsonify, request, abort\n\n\n@app_views.route('/states//cities', methods=['GET', 'POST'])\ndef cities(state_id):\n \"\"\" Method that retrieves the list of all State objects \"\"\"\n if request.method == 'GET':\n states = storage.get(State, state_id)\n if states:\n print(states)\n else:\n abort(404)\n cities = [city.to_dict() for city in states.cities]\n return jsonify(cities)\n\n if request.method == 'POST':\n states = storage.get(State, state_id)\n if states is None:\n abort(404)\n info = request.get_json()\n info['state_id'] = state_id\n if info is None:\n abort(400, 'Not a JSON')\n if 'name' not in info:\n abort(400, 'Missing name')\n city = City(**info)\n city.save()\n return jsonify(city.to_dict()), 201\n\n\n@app_views.route('/cities/', methods=['DELETE', 'GET'])\ndef del_cities(city_id):\n \"\"\" Method that deletes a State object \"\"\"\n if request.method == 'DELETE':\n cities = storage.get(City, city_id)\n if cities:\n storage.delete(cities)\n storage.save()\n return jsonify({}), 200\n abort(404)\n\n if request.method == 'GET':\n cities = storage.get(City, city_id)\n if cities:\n return jsonify(cities.to_dict())\n abort(404)\n\n\n@app_views.route('/cities/', methods=['PUT'])\ndef put_cities(city_id):\n \"\"\" Method that updates a State object \"\"\"\n cities = storage.get(City, city_id)\n if cities:\n if request.is_json is False:\n abort(400, 'Not a JSON')\n info = request.get_json()\n cities.update(info)\n return jsonify(cities.to_dict()), 200\n abort(404)\n","sub_path":"api/v1/views/cities.py","file_name":"cities.py","file_ext":"py","file_size_in_byte":1983,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"220205875","text":"# cubic root of x with bisection\n\n\"\"\"\n- set low and high boundaries:\n # low = 0\n # high = x\n\n- set an initial guess that is:\n # guess = (high + low) / 2.0\n\n- while abs(guess**3 - cube) is not good enough (is not less than epsilon):\n # check if guess**3 was less than x:\n - if yes, set low boundary to be equal to guess.\n - if no, set high boundary to be equal to guess.\n # with the new low or high boundary value, make a new guess\n # repeat\n\"\"\"\n\ncube = -3\n\nepsilon = 0.01\nnum_guesses = 1\nlow = 0\nhigh = abs(cube)\n\nif (cube < 1 and cube > 0):\n low = cube\n high = 1\n\nguess = (high + low) / 2.0\n\nwhile abs(guess**3 - abs(cube)) >= epsilon:\n if guess**3 < abs(cube):\n low = guess\n else:\n high = guess\n \n guess = (high + low) / 2.0\n num_guesses += 1\n \nprint('num_guesses is=', num_guesses)\n\nif (cube < 0):\n guess *= -1\n print(guess, 'is close enough to the cube root of', cube)\nelse:\n print(guess, 'is close enough to the cube root of', cube)","sub_path":"0.MIT-6.0001/notes/4.algorithm_bisection.py","file_name":"4.algorithm_bisection.py","file_ext":"py","file_size_in_byte":1016,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"132297907","text":"#!/usr/bin/env python\n#coding=utf-8\n\n'''\nDefinition of OneHotEncoding class (for named entity sparse representation),\nPretrainedEmbs (for pretrained embeddings) and \nRndInitLearnedEmbs (for random initialized ones). # just indices starting from 1?\nEmbs puts everything together, using the same random seed.\n\n@author: Marco Damonte (m.damonte@sms.ed.ac.uk)\n@since: 03-10-16\n'''\n\nimport re\nimport string\nimport random\n\nclass OneHotEncoding:\n def __onehot(self, index):\n onehot = [0]*(self.dim)\n onehot[index - 1] = 1\n return onehot\n\n def __init__(self, vocab):\n lines = open(vocab).readlines()\n self.dim = len(lines) + 3\n self.enc = {}\n for counter, line in enumerate(lines):\n self.enc[line.strip()] = self.__onehot(counter + 1)\n self.enc[\"\"] = self.__onehot(len(self.enc) + 1)\n self.enc[\"\"] = self.__onehot(len(self.enc) + 1)\n self.enc[\"\"] = self.__onehot(len(self.enc) + 1)\n def get(self, label):\n assert(label is not None)\n if label == \"\":\n return self.enc[\"\"]\n if label.startswith(\"\"]\n if label in self.enc:\n return self.enc[label]\n return self.enc[\"\"]\n\nclass PretrainedEmbs:\n def __init__(self, generate, initializationFileIn, initializationFileOut, dim, unk, root, nullemb, prepr, punct):\n self.prepr = prepr # boolean\n self.indexes = {} # a dictionary from word to index.\n self.initialization = {}\n self.counter = 1\n self.dim = dim\n self.punct = punct\n self.nullemb = nullemb\n self.vecs = {}\n\n if generate:\n fw = open(initializationFileOut, \"w\")\n\n # Loop through all the word embeddings from the resources input.\n for line in open(initializationFileIn).readlines()[2:]: # first two lines are not actual embeddings (dims and )\n v = line.split()\n\n # Extract word and embeddings seperatedly from initializationFileIn\n word = v[0]\n self.vecs[word] = \" \".join(v[1:])\n \n # If need preprocessing.\n if self.prepr:\n word = self._preprocess(word)\n # If the word is already in the indexes diction, than continue with the next word.\n if word in self.indexes:\n continue\n # Enroll the word into the indexes word dictionary.\n self.indexes[word] = self.counter\n \n # Write the embeddings into the new output files, ',' seperated.\n if generate:\n fw.write(v[1])\n for i in v[2:]:\n fw.write(\",\" + str(i))\n fw.write(\"\\n\")\n self.counter += 1\n \n # Add \"\", \"\", \"\" to the word->index dictionary, and write random embeddings to their corresponding output files enties.\n self.indexes[\"\"] = self.counter\n if generate:\n fw.write(str(unk[0]))\n for i in unk[1:]:\n fw.write(\",\" + str(i))\n fw.write(\"\\n\")\n self.counter += 1\n\n self.indexes[\"\"] = self.counter\n if generate:\n fw.write(str(root[0]))\n for i in root[1:]:\n fw.write(\",\" + str(i))\n fw.write(\"\\n\")\n self.counter += 1\n\n self.indexes[\"\"] = self.counter\n if generate:\n fw.write(str(nullemb[0]))\n for i in nullemb[1:]:\n fw.write(\",\" + str(i))\n fw.write(\"\\n\")\n self.counter += 1\n\n if punct is not None:\n self.indexes[\"\"] = self.counter\n if generate:\n fw.write(str(punct[0]))\n for i in punct[1:]:\n fw.write(\",\" + str(i))\n fw.write(\"\\n\")\n self.counter += 1\n \n def get(self, word):\n assert(word is not None)\n if word == \"\":\n return self.indexes[\"\"]\n if word.startswith(\"\"]\n\n if self.prepr:\n word = self._preprocess(word)\n if self.punct is not None and word not in self.indexes and word in list(string.punctuation):\n return self.indexes[\"\"]\n elif word in self.indexes:\n return self.indexes[word]\n else:\n return self.indexes[\"\"]\n\n def _preprocess(self, word):\n if word.startswith('\"') and word.endswith('\"') and len(word) > 2:\n word = word[1:-1]\n reg = re.compile(\".+-[0-9][0-9]\")\n word = word.strip().lower()\n if reg.match(word) is not None:\n word = word.split(\"-\")[0]\n if re.match(\"^[0-9]\", word) is not None:\n word = word[0]\n word = word.replace(\"0\",\"zero\")\n word = word.replace(\"1\",\"one\")\n word = word.replace(\"2\",\"two\")\n word = word.replace(\"3\",\"three\")\n word = word.replace(\"4\",\"four\")\n word = word.replace(\"5\",\"five\")\n word = word.replace(\"6\",\"six\")\n word = word.replace(\"7\",\"seven\")\n word = word.replace(\"8\",\"eight\")\n word = word.replace(\"9\",\"nine\")\n return word\n \n def vocabSize(self):\n return self.counter - 1\n\n\n\nclass RndInitLearnedEmbs:\n def __init__(self, vocab):\n self.indexes = {}\n for counter, line in enumerate(open(vocab)):\n word = line.strip()\n self.indexes[word] = counter + 1\n self.indexes[\"\"] = len(self.indexes) + 1\n self.indexes[\"\"] = len(self.indexes) + 1\n self.indexes[\"\"] = len(self.indexes) + 1\n\n def get(self, label):\n assert(label is not None and label != \"\")\n if label == \"\":\n return self.indexes[\"\"]\n if label.startswith(\"\"]\n\n if label not in self.indexes:\n label = \"\"\n return self.indexes[label]\n \n def vocabSize(self):\n return len(self.indexes)\n\nclass Embs:\n\n def _create_concept_vec(self, wordembs, conceptembs, propbank, wordvecs):\n fw = open(conceptembs, \"w\") \n for line in open(wordembs):\n fw.write(line.strip() + \"\\n\")\n for p in open(propbank):\n p2 = p.split(\"-\")[0] \n if p2 in wordvecs.indexes:\n fw.write(p.strip() + \" \" + wordvecs.vecs[p2] + \"\\n\")\n fw.close()\n \n def __init__(self, resources_dir, model_dir, generate = False):\n random.seed(0)\n \n\t# Random float vectors with values [-0.01, 0.01)\n punct50 = [float(0.02*random.random())-0.01 for i in xrange(50)]\n punct100 = [float(0.02*random.random())-0.01 for i in xrange(100)]\n \n root10 = [float(0.02*random.random())-0.01 for i in xrange(10)]\n root50 = [float(0.02*random.random())-0.01 for i in xrange(50)]\n root100 = [float(0.02*random.random())-0.01 for i in xrange(100)]\n\n unk10 = [float(0.02*random.random())-0.01 for i in xrange(10)]\n unk50 = [float(0.02*random.random())-0.01 for i in xrange(50)]\n unk100 = [float(0.02*random.random())-0.01 for i in xrange(100)]\n\n null10 = [float(0.02*random.random())-0.01 for i in xrange(10)]\n null50 = [float(0.02*random.random())-0.01 for i in xrange(50)]\n\n # Assign each dep, pos a number.\n self.deps = RndInitLearnedEmbs(model_dir + \"/dependencies.txt\")\n self.pos = RndInitLearnedEmbs(resources_dir + \"/postags.txt\")\n # Get the pretrained word embeddings.\n self.words = PretrainedEmbs(generate, resources_dir + \"/wordvec50.txt\", resources_dir + \"/wordembs.txt\", 50, unk50, root50, null50, True, punct50)\n self.nes = OneHotEncoding(resources_dir + \"/namedentities.txt\")\n","sub_path":"embs.py","file_name":"embs.py","file_ext":"py","file_size_in_byte":7864,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"535011429","text":"\"\"\"\nSpectrum Map class\nVersion 2\nLast updated: 19/10/2021\n\nCreated: 08/10/2021\n\"\"\"\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom ipywidgets import interact, IntSlider\n\nclass _noise_replace(object):\n \"\"\"\n Hidden class with attributes for replacing spikes with noise\n ...\n \n Attributes\n ----------\n noise_fill : array\n a short array containing noise within the range of minimum/ maximum values of surrounding signal\n \n start_replace : float\n the index to start replacing data with noise\n \n end_replace : float\n the index to finish replacing data with noise \n \"\"\"\n def __init__(self, shift, intensity, spike_pos, smooth_width=10):\n spike_idx = np.argmin(abs(shift-spike_pos))\n ## if near the minimum of the shift axis:\n if spike_idx < 2*smooth_width:\n min_spike = 0\n min_avg = 0\n max_avg = spike_idx+2*smooth_width\n max_spike = spike_idx+smooth_width\n ## if near the maximum of the shift axis:\n elif shift.shape[0]-spike_idx < 2*smooth_width:\n min_spike = spike_idx-smooth_width\n min_avg = spike_idx-2*smooth_width\n max_avg = shift.shape[0]\n max_spike = shift.shape[0]\n else:\n min_spike = spike_idx-smooth_width\n min_avg = spike_idx-2*smooth_width\n max_avg = spike_idx+2*smooth_width\n max_spike = spike_idx+smooth_width\n\n noise_min = np.nanmin([np.nanmin(intensity[min_avg:min_spike]),\n np.nanmin(intensity[max_spike:max_avg])])\n\n noise_max = np.nanmax([np.nanmax(intensity[min_avg:min_spike]),\n np.nanmax(intensity[max_spike:max_avg])])\n\n self.noise_fill = np.random.rand(2*smooth_width)*(noise_max-noise_min)+noise_min\n self.start_replace = min_spike\n self.end_replace = max_spike\n \ndef CRE_single(shift, intensity, spike_pos, smooth_width=10):\n \"\"\"\n Function to repair a single spectrum with a cosmic ray spike at a user-defined position\n \n Parameters:\n shift (array): The shift/ x-axis for the data to be repaired\n intensity (array): The intensity/ y values of the data to be repaired\n spike_pos (float): The shift value at which the cosmic ray occurs\n smooth_width (int) (default = 10): The number of shift values to replace by noise\n \"\"\"\n repaired = np.zeros((intensity.shape))\n \n if type(spike_pos)==list:\n replacements = [_noise_replace(shift=shift, intensity=intensity, spike_pos=pos, smooth_width=smooth_width) \\\n for pos in spike_pos]\n replacement_idx = np.array([np.arange(replacement.start_replace, replacement.end_replace) for replacement in replacements])\n \n for x in range(intensity.shape[0]):\n if x not in replacement_idx:\n repaired[x] = intensity[x]\n \n for rp in replacements:\n repaired[rp.start_replace:rp.end_replace] = rp.noise_fill\n repaired[:rp.start_replace] = intensity[:rp.start_replace]\n repaired[rp.end_replace:] = intensity[rp.end_replace:]\n\n if type(spike_pos) == float or type(spike_pos) == int:\n rp = _noise_replace(shift=shift, intensity=intensity, spike_pos=spike_pos, smooth_width=smooth_width)\n repaired[rp.start_replace:rp.end_replace] = rp.noise_fill\n repaired[:rp.start_replace] = intensity[:rp.start_replace]\n repaired[rp.end_replace:] = intensity[rp.end_replace:]\n \n return np.vstack((shift, repaired)).T\n\n\nclass _Map(object):\n \"\"\"\n Hidden container class\n ...\n Attributes\n ----------\n shift: array\n The shift (x) axis\n shift_extent: int\n The length of the shift axis array\n map: array\n The Raman map data with size (x_extent, y_extent, shift_extent)\n \"\"\"\n def __init__(self, shift, map_data):\n self.shift = shift\n self.shift_extent = shift.shape[0]\n self.map = map_data\n \n \nclass SpectrumMap(object):\n \"\"\"\n A class to contain Raman map data, with associated pre-processing and display functions\n ...\n\n Input arguments\n ----------\n filename: str\n name and path of the four-column text file of Raman map data, including file extension\n\n Attributes\n ----------\n x_coords: numpy array\n x positions corresponding to spectra positions\n y_coords: numpy array\n y positions corresponding to spectra positions\n x_extent: int\n number of x positions at which spectra were collected\n y_extent: int\n number of y positions at which spectra were collected\n \n Subclass (_Map) for raw data: \n raw.shift: numpy array\n the Raman shift axis corresponding to the map data\n raw.shift_extent: int\n number of shift values\n raw.map: numpy array\n 3d array containing the map data (dimensions for x, y, and shift axes)\n \n Methods\n ----------\n slide_viewer(xmin=None, ymin=None):\n returns an interactive (ipywidgets) plot of the signal\n \n fix_cosmic_ray(x_pos, y_pos, spike_pos, smooth_width=10):\n repairs cosmic rays at user-defined x_pos, y_pos map positions at shift value spike_pos. \n corrects values directly in all _Map subclasses (raw, plus ccd and clipped if created)\n returns none\n \n set_CCD_remove(pixel_position, smooth_width=10):\n removes a spike located at the same shift value (i.e. pixel position) throughout a map\n returns 'ccd' as new attribute of SpectrumMap (_Map class with shift, shift_extent, and map attributes)\n \n set_clip_range(start_shift=None, end_shift=None):\n returns 'clipped' as a new attribute of SpectrumMap (_Map class with shift, shift_extent, and map attributes)\n \n Notes\n ----------\n \n To instantiate the class, use:\n s = SpectrumMap(filename)\n\n The data will be accessible using:\n s.raw.map\n\n To view the data, use:\n s.slide_viewer()\n\n To remove cosmic rays, use:\n s.fix_cosmic_ray(x_pos, y_pos, spike_pos)\n\n To remove a consistent spike (from a dead CCD pixel), use:\n s.set_CCD_remove(pixel_position)\n\n The fixed data will be accessible using:\n s.ccd.map\n\n NB: fix the spike before clipping the data range\n\n To clip the range of data to view, use:\n s.set_clip_range(start_shift, end_shift)\n\n The clipped data will be accessible using:\n s.clipped.map\n \"\"\"\n \n def __init__(self, data_file):\n raw_data = np.loadtxt(data_file)\n self.x_coords = np.array(np.unique(raw_data[:, 0]), dtype=int)\n self.y_coords = np.array(np.unique(raw_data[:, 1]), dtype=int)\n raw_shift, raw_shift_locs = np.unique(raw_data[:, 2], return_index=True)\n \n self.x_extent = self.x_coords.shape[0]\n self.y_extent = self.y_coords.shape[0] \n \n raw_shift_extent = raw_shift.shape[0]\n raw_map = np.zeros((self.x_extent, self.y_extent, raw_shift_extent))\n for nx, x in enumerate(self.x_coords):\n for ny, y in enumerate(self.y_coords):\n spectrum = raw_data[np.nonzero((raw_data[:, 0] == x) & (raw_data[:, 1] == y)), -1].flatten()\n raw_map[nx, ny, :] = spectrum[::-1] \n \n setattr(self, \"raw\", _Map(shift=raw_shift, map_data=raw_map))\n \n def set_CCD_remove(self, pixel_position, smooth_width=10):\n \"\"\"\n Removes a spike at a constant shift value at every (x, y) position in a Raman map, for example due to a faulty pixel on a CCD device\n \n Parameters:\n pixel_position (float): The shift value at which the spike occurs\n smooth_width (int, default=10): The number of shift values to be replaced by random noise each side of the spike\n \n Returns:\n self.ccd (object): A _Map class with shift, shift_extent, and map attributes\n \"\"\"\n pixel_idx = np.argmin(abs(self.raw.shift-pixel_position)) \n CCD_map = np.zeros((self.x_extent, self.y_extent, self.raw.shift_extent))\n \n for x in range(self.x_extent):\n for y in range(self.y_extent):\n pre_max = np.nanmax(self.raw.map[x, y, pixel_idx-2*smooth_width:pixel_idx-smooth_width])\n post_max = np.nanmax(self.raw.map[x, y, pixel_idx+smooth_width:pixel_idx+2*smooth_width])\n pre_min = np.nanmin(self.raw.map[x, y, pixel_idx-2*smooth_width:pixel_idx-smooth_width])\n post_min = np.nanmin(self.raw.map[x, y, pixel_idx+smooth_width:pixel_idx+2*smooth_width])\n \n noise_fill = min([pre_min, post_min])+(max([pre_max, post_max])-min([pre_min, post_min]))*np.random.rand(2*smooth_width)\n \n CCD_map[x, y, :pixel_idx-smooth_width] = self.raw.map[x, y, :pixel_idx-smooth_width] \n CCD_map[x, y, pixel_idx-smooth_width:pixel_idx+smooth_width] = noise_fill\n CCD_map[x, y, pixel_idx+smooth_width:] = self.raw.map[x, y, pixel_idx+smooth_width:] \n \n setattr(self, \"ccd\", _Map(shift=self.raw.shift, map_data=CCD_map))\n \n def set_clip_range(self, start_shift=None, end_shift=None):\n \"\"\"\n Returns a map with x_extent and y_extent corresponding to raw data, with a range of shift values corresponding to a region of interest defined by the user\n \n Parameters:\n start_shift (float, default=None): The shift value corresponding to the lower bound of the region of interest.\n If 'None', uses the first shift value in the data\n end_shift (float, default=None): The shift value corresponding to the upper bound of the region of interest.\n If 'None', uses the last shift value in the data\n \"\"\"\n if start_shift == None:\n start_shift = min(self.raw.shift)\n if end_shift == None:\n end_shift = max(self.raw.shift)\n start_idx = np.argmin(abs(self.raw.shift-start_shift))\n end_idx = np.argmin(abs(self.raw.shift-end_shift))\n \n if \"ccd\" in vars(self).keys():\n setattr(self, \"clipped\", _Map(shift=self.raw.shift[start_idx:end_idx],\n map_data=self.ccd.map[:, :, start_idx:end_idx]))\n else:\n setattr(self, \"clipped\", _Map(shift=self.raw.shift[start_idx:end_idx],\n map_data=self.raw.map[:, :, start_idx:end_idx]))\n \n def fix_cosmic_ray(self, x_pos, y_pos, spike_pos, smooth_width=10):\n \"\"\"\n Repairs cosmic rays identified by the user and applies repairs to \"raw\", AND \"ccd\", AND \"clipped\" maps if defined. \n \n Parameters:\n x_pos (int): the x position of the spectrum to repair within the SpectrumMap map\n y_pos (int): the y position of the spectrum to repair within the SpectrumMap map\n spike_pos (float): the shift value at which the spike occurs\n smooth_width (int, default=10): the number of shift positions either side of the spike to replace with noise\n \n \"\"\"\n maps_to_fix = [key for key in vars(self).keys() if key in [\"raw\", \"ccd\", \"clipped\"]]\n \n for processed in maps_to_fix:\n if spike_pos < max(vars(self)[processed].shift) and spike_pos > min(vars(self)[processed].shift):\n vars(self)[processed].map[x_pos, y_pos, :] = CRE_single(shift=vars(self)[processed].shift,\n intensity=vars(self)[processed].map[x_pos, y_pos, :],\n spike_pos=spike_pos,\n smooth_width=smooth_width)[:, 1]\n def slide_viewer(self, display=\"raw\"):\n \"\"\"\n Returns an ipywidgets controlled interactive graph display, with widgets to control x and y position of spectrum to display\n \n Parameters:\n display (str): one of \"raw\", \"clipped\", or \"ccd\"\n selects the (pre-processed) data to display\n \"\"\"\n f, ax = plt.subplots()\n shift = vars(self)[display].shift\n map_data = vars(self)[display].map\n \n spectrum, = ax.plot(shift, map_data[0, 0, :])\n \n ax.tick_params(which=\"both\", tickdir=\"in\", right=True, top=True)\n ax.set_xlabel(\"Raman shift (cm$^{-1}$)\")\n ax.set_ylabel(\"Intensity (a.u.)\")\n \n def update(x, y):\n spectrum.set_ydata(map_data[x, y, :])\n ax.set_ylim([0.9*min(map_data[x, y, :]),\n 1.1*max(map_data[x, y, :])])\n\n \n interact(update, x=IntSlider(min=0, max=self.x_extent-1, step=1),\n y=IntSlider(min=0, max=self.y_extent-1, step=1))\n","sub_path":"SpectrumMap.py","file_name":"SpectrumMap.py","file_ext":"py","file_size_in_byte":13193,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"637637875","text":"import hlt\r\nfrom hlt import NORTH, EAST, SOUTH, WEST, STILL, Move, Square\r\nimport random\r\nimport numpy as np\r\nfrom scipy.ndimage.filters import generic_filter\r\nimport sys\r\n\r\n# log\r\nimport logging\r\nfrom logging.handlers import RotatingFileHandler\r\nlogger = logging.getLogger()\r\nlogger.setLevel(logging.DEBUG)\r\n# création d'un formateur qui va ajouter le temps, le niveau\r\n# de chaque message quand on écrira un message dans le log\r\nformatter = logging.Formatter('%(levelname)s :: %(message)s')\r\n# création d'un handler qui va rediriger une écriture du log vers\r\n# un fichier en mode 'append', avec 1 backup et une taille max de 1Mo\r\nfile_handler = RotatingFileHandler('activity.log', 'a', 1000000, 1)\r\n# on lui met le niveau sur DEBUG, on lui dit qu'il doit utiliser le formateur\r\n# créé précédement et on ajoute ce handler au logger\r\nfile_handler.setLevel(logging.DEBUG)\r\nfile_handler.setFormatter(formatter)\r\nlogger.addHandler(file_handler)\r\n\r\n\r\nBIGINT = 99999\r\n\r\n\r\ndef path_towards(x, y, tx, ty, hard = True):\r\n \"\"\"For an owned cell at x, y, and a target cell at tx, ty,\r\n return the cardinal direction to move along.\r\n Moves along the shortest nonzero cardinal first.\r\n \"\"\"\r\n dists = np.array([\r\n (y - ty) % HEIGHT,\r\n (tx - x) % WIDTH,\r\n (ty - y) % HEIGHT,\r\n (x - tx) % WIDTH\r\n ])\r\n dists[dists == 0] = BIGINT\r\n distorder = np.argsort(dists)\r\n \r\n #smooth direction\r\n if hard:\r\n return distorder[0] \r\n else:\r\n return random.choice((distorder[0] ,distorder[0] ,distorder[1]))\r\n \r\n \r\ndef find_nearest_border_direction(square, game_map):\r\n direction = NORTH\r\n max_distance = min(game_map.width, game_map.height) / 2\r\n for d in (NORTH, EAST, SOUTH, WEST):\r\n distance = 0\r\n current = square\r\n while current.owner == myID and distance < max_distance:\r\n distance += 1\r\n current = game_map.get_target(current, d)\r\n if distance < max_distance:\r\n direction = d\r\n max_distance = distance\r\n return direction\r\n\r\n#####################################\r\n\r\ndef get_move(square, gmap, alpha_prod = 5, max_vision = 2, ratio_neutral = 1):\r\n \r\n \"\"\" alpha_prod : ratio strenght/prod \r\n max_vision : vision for detecting enemy \r\n ratio_neutral : ratio strenght/strenght_neutral before capture \"\"\"\r\n\r\n # Border\r\n border = any(neighbor.owner != myID for neighbor in gmap.neighbors(square))\r\n enemy = any(neighbor.owner not in [myID,0] for neighbor in gmap.neighbors(square))\r\n \r\n \r\n # if enemy close by :\r\n if enemy:\r\n l_nbrs = list(gmap.neighbors(square, n=max_vision))\r\n logger.debug(' ENNEMY :' + str(l_nbrs))\r\n l_txty = [(nbrs.x,nbrs.y) for nbrs in l_nbrs if nbrs.owner not in [0, myID]] \r\n dire = np.random.choice([path_towards(square.x,square.y,z[0],z[1]) for z in l_txty])\r\n logger.debug('- list dire :' + str([path_towards(square.x,square.y,z[0],z[1]) for z in l_txty]))\r\n return Move(square, dire)\r\n \r\n else: # no enemy \r\n if not border:\r\n if square.strength < alpha_prod * square.production:\r\n return Move(square, STILL)\r\n else:\r\n return Move(square, find_nearest_border_direction(square, gmap))\r\n \r\n else:\r\n for dire,nbrs in enumerate(gmap.neighbors(square, n=1)):\r\n #logger.debug('enum nbrs :' + str(nbrs))\r\n if nbrs.owner == 0: \r\n if square.strength >= nbrs.strength * ratio_neutral + LATEGAME:\r\n #logger.debug('move border : ' + str(square) + str(dire)) \r\n return Move(square, dire)\r\n return Move(square, STILL)\r\n\r\n########################################\r\n\r\ngame_map = TomGameMap()\r\nmyID = game_map.my_id\r\nhlt.send_init(\"TomBot²\")\r\n\r\nHEIGHT, WIDTH = game_map.height, game_map.width\r\nTURN = 0\r\nEARLYGAME, LATEGAME = 1, 0\r\nwhile True:\r\n if TURN > 150:\r\n LATEGAME = 1\r\n game_map.get_frame()\r\n moves = [get_move(square,game_map) for square in game_map if square.owner == myID]\r\n hlt.send_frame(moves)\r\n TURN += 1\r\n","sub_path":"bot_ref/TomBot_v2 (1).py","file_name":"TomBot_v2 (1).py","file_ext":"py","file_size_in_byte":4255,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"308035917","text":"# refer to https://leetcode.com/problems/reorder-log-files/discuss/192144 and\n# https://leetcode.com/problems/reorder-log-files/discuss/198197\nclass Solution(object):\n def reorderLogFiles(self, logs):\n \"\"\"\n :type logs: List[str]\n :rtype: List[str]\n \"\"\"\n letter_logs = []\n digit_logs = []\n \n for log in logs:\n if log[log.find(\" \")+1].isdigit():\n digit_logs.append(log)\n else:\n letter_logs.append(log)\n \n # for tuple, compare the first element, then compare the second element\n # thus, compare log[log.find(\" \")+1:], then compare log[:log.find(\" \")] \n letter_logs.sort(key=lambda log: (log[log.find(\" \")+1:], log[:log.find(\" \")]))\n \n return letter_logs + digit_logs\n\n","sub_path":"LeetCode/937-ReorderLogFiles.py","file_name":"937-ReorderLogFiles.py","file_ext":"py","file_size_in_byte":825,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"243876164","text":"# 对经过去停词、频率筛选后的训练模型进行测试\n# 集合了批量测试和自定义测试两种功能,注释部分代码即可\n# 暂未加入gensim预处理函数\n\nimport os\nos.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'\n\nimport numpy as np\nfrom keras.models import load_model\nfrom keras.preprocessing import sequence\nfrom keras.preprocessing.text import Tokenizer\n\nimport joblib as jl\nimport re\n\nfilepath = '../data/input_total/question/'\nmodel = load_model('./models/textCNN_model_gensim.h5')\n\ngenre = 9\nmaxLen = 20\n\ndef rm(text):\n\n\trm = re.compile(r'\\n')\n\treturn rm.sub('', text)\n\ndef readFile(path=filepath):\n\t\n\tquestions = []\n\tlabels = []\n\tfile_list = []\n\n\tfor file in os.listdir(path):\n\t\tfile_list.append(path + file)\n\n\tcounter_question = 0\n\tcounter_file = 0\n\tfor file_name in file_list:\n\t\twith open(file_name, encoding='utf-8') as f:\n\t\t\twhile 1:\n\t\t\t\tline = f.readline()\n\t\t\t\tif not line:\n\t\t\t\t\tcounter_file += 1\n\t\t\t\t\tbreak;\n\t\t\t\tquestions.append(rm(\"\".join(line)))\n\t\t\t\tlabels.append(counter_file)\n\t\t\t\tcounter_question += 1\n\n\treturn questions, labels, counter_question\n\n# 去停词与出现频率低的词\ndef stringProcessing(questions):\n\n\twith open('./string/module/stoplist', \"rb\") as handler:\n\t\tstoplist = jl.load(handler)\n\twith open('./string/module/frequency', \"rb\") as handler:\n\t\tfrequency = jl.load(handler)\n\n\tquestions = [[word for word in question.lower().split() if word not in stoplist]\n\t\t\tfor question in questions]\n\n\t# 将出现次数大于一的保留\n\tquestions = [[token for token in question if frequency[token] > 1]\n\t\t\t for question in questions]\n\n\tquestion_concate = []\n\tfor question in questions:\n\t\tquestion_concate.append(\" \".join(question))\n\n\treturn question_concate\n\n# 字典预处理,转化为矩阵\ndef preprocessing(question):\n\n\twith open('./models/tokenizer_gensim', \"rb\") as handler:\n\t\ttokenizer = jl.load(handler)\n\n\tquestion = tokenizer.texts_to_sequences(question)\n\tquestion = sequence.pad_sequences(question, maxlen=maxLen)\n\n\treturn question\n\n# 输出批量测试结果``````````````````````````\n\n# questions, labels, num_questions = readFile()\n\n# questions = stringProcessing(questions)\n# questions_array = preprocessing(questions)\n\n# result = model.predict(questions_array)\n# result_array = np.argmax(result, axis=1)\n\n# # 输出所有预测结果\n# # for index in range(num_questions):\n# # \tprint(questions[index], result_array[index])\n\n# # 错误语句输出\n# counter_failed = 0\n# for index in range(num_questions):\n# \tif labels[index] != result_array[index]:\n# \t\tcounter_failed += 1\n# \t\tprint(questions[index], ', 预测分类为: ', result_array[index], ', 正确分类为: ', labels[index])\n\n# print('总共测试 ', num_questions, ' 个样本, ', counter_failed, ' 个样本预测失败, 正确率为: ', (num_questions - counter_failed) / num_questions)\n\n# 自定义问题的分类测试``````````````````````````\n\n# 正确结果是 0 2 7 3 5 4 8\n# 注:分类9的问题经常会被分错类\n\nquestions = ['Could you please introduce yourself ?', \n\t\t\t\t'Do you consider yourself successful ?', \n\t\t\t\t'What do you enjoy most about what you do now ?', \n\t\t\t\t'Who was your best boss and who was the worst ?', \n\t\t\t\t'What about your salary benefits ?',\n\t\t\t\t'What was your biggest accomplishment on the job ? ',\n\t\t\t\t'What type of work environment do you prefer ?'\n\t\t\t\t]\n\nquestions = stringProcessing(questions)\nquestion_array = preprocessing(questions)\n\nresult = model.predict(question_array)\nresult_array = np.argmax(result, axis=1)\n\nprint(result)\nprint(result_array)\n","sub_path":"tensorflow/scripts/demo/scripts/test_textCNN_gensim.py","file_name":"test_textCNN_gensim.py","file_ext":"py","file_size_in_byte":3521,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"248580616","text":"#!/usr/bin/env python\n\nfrom __future__ import print_function\nimport eagle_util_funcs\nimport os.path\nimport subprocess\nimport sys\ntry:\n import yaml\nexcept ImportError:\n print('Please install PyYaml')\n sys.exit(1)\n\n\ndef generate_gerber(brdFile, outFile, layers):\n ret = eagle_util_funcs.run_eagle([\n '-X', # Run the command line CAM processor\n '-N', # No output messages\n '-dGERBER_RS274X', # Output in gerber format\n '-o' + outFile, # Output path\n brdFile, # Input board\n ] + layers # Layers to process\n )\n\n if ret != 0:\n print(\"Eagle returned error!\")\n sys.exit(ret)\n\n\ndef generate_drill(brdFile, outFile, layers):\n ret = eagle_util_funcs.run_eagle([\n '-X', # Run the command line CAM processor\n '-N', # No output messages\n '-dEXCELLON', # Output in gerber format\n '-o' + outFile, # Output path\n brdFile, # Input board\n ] + layers # Layers to process\n )\n\n if ret != 0:\n print(\"Eagle returned error!\")\n sys.exit(ret)\n\n\ndef zip_up_results(outfile):\n subprocess.call(\"zip %s *\" % outfile, shell=True)\n print(\"Made zip!\")\n\n\ndef main():\n if len(sys.argv) < 4:\n print(\"Usage: %s config.yaml in.brd out.zip\" % (sys.argv[0]))\n sys.exit(1)\n\n configFileName = os.path.abspath(sys.argv[1])\n inputFileName = os.path.abspath(sys.argv[2])\n outputFileName = os.path.abspath(sys.argv[3])\n\n # Get the \"base\" (no path, no extension) part of the input name\n inputBaseName = os.path.splitext(os.path.basename(inputFileName))[0]\n\n # Read configuration\n configFile = open(configFileName, 'r')\n configData = yaml.load(configFile)\n configFile.close()\n\n # Create temporary directory\n tempdir = eagle_util_funcs.setup_tmp_dir()\n\n # Process each section\n for configSection in configData:\n print(\"Running section %s...\" % configSection['description'])\n sectionOutputFilePath = (\"%s/%s.%s\" %\n (tempdir, inputBaseName,\n configSection['output_extension']))\n\n layers = configSection['layers']\n if type(layers) == int:\n layers = str(layers)\n layers = layers.split()\n\n if configSection['type'] == 'gerber':\n generate_gerber(inputFileName, sectionOutputFilePath, layers)\n elif configSection['type'] == 'excellon':\n generate_drill(inputFileName, sectionOutputFilePath, layers)\n else:\n print(\"Section ignored, unknown type %s\" % configSection['type'])\n\n # Zip outputs\n zip_up_results(outputFileName)\n\n # Clean up\n eagle_util_funcs.remove_tmp_dir(tempdir)\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"tools/run-eagle-cam-v2.py","file_name":"run-eagle-cam-v2.py","file_ext":"py","file_size_in_byte":2855,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"320691806","text":"import os\nimport sys\nimport pygame\nfrom pygame.constants import AUDIO_ALLOW_CHANNELS_CHANGE\nfrom pieces import Piece, Pawn, Knight, Bishop, Rook, Queen, King\n\npygame.init()\npygame.mixer.init()\n\n# Setting up the window\nscreen_width = 600\nscreen_height = 600\nmod = (screen_height + screen_width) // 16\n\n# Loading sounds\nmove_sound = pygame.mixer.Sound(\"sounds\\move.wav\")\ncapture_sound = pygame.mixer.Sound(\"sounds\\capture.wav\")\n\n# Colors\nRED = (255, 0, 0, 50)\nGREEN = (0, 255, 0, 50)\nBLUE = (0, 0, 255, 50)\nWHITE = (255, 255, 255, 50)\nBLACK = (0, 0, 0, 50)\nYELLOW = (255, 255, 0, 50)\nTAN = (240, 217, 181, 128)\nDARK_TAN = (181, 136, 99, 128)\n\nwin = pygame.display.set_mode((screen_width, screen_height))\npygame.display.set_caption(\"Chess\")\n\n# Loading the chess board\nchessBoard = pygame.image.load(\"img/chess_board.png\")\n\n\n# Loading the black and white chess pieces\nwhite_pieces = [pygame.image.load(\"img/white_pieces/wP.png\"),\n pygame.image.load(\"img/white_pieces/wN.png\"),\n pygame.image.load(\"img/white_pieces/wB.png\"),\n pygame.image.load(\"img/white_pieces/wR.png\"),\n pygame.image.load(\"img/white_pieces/wQ.png\"),\n pygame.image.load(\"img/white_pieces/wK.png\")]\n\nblack_pieces = [pygame.image.load(\"img/black_pieces/bP.png\"),\n pygame.image.load(\"img/black_pieces/bN.png\"),\n pygame.image.load(\"img/black_pieces/bB.png\"),\n pygame.image.load(\"img/black_pieces/bR.png\"),\n pygame.image.load(\"img/black_pieces/bQ.png\"),\n pygame.image.load(\"img/black_pieces/bK.png\")]\n\n\n# Defines each king's position throughout the game\nwhite_king = [7, 4]\nblack_king = [0, 4]\n\n# Creates out the chess board\n\n\ndef createBoard(board, white_king, black_king, validlist):\n win.blit(chessBoard, (0, 0))\n highlightValid(validlist)\n highlightCheck(board, white_king, black_king)\n for i in range(len(board)):\n for j in range(len(board[i])):\n\n # Checks if the piece is black or white\n piece = abs(board[i][j]) - 1\n if board[i][j] > 0:\n win.blit(white_pieces[piece], (j * mod, i * mod))\n\n elif board[i][j] < 0:\n win.blit(black_pieces[piece], (j * mod, i * mod))\n\n\n# Highlights the king if it is in check\ndef highlightCheck(board, white_king, black_king):\n inCheck = check(board, white_king, black_king)\n if inCheck != 0:\n if inCheck == 1:\n highlightRect(RED, white_king[0], white_king[1])\n\n elif inCheck == -1:\n highlightRect(RED, black_king[0], black_king[1])\n\n\n# Returns mouse coordinates\ndef getMousePos():\n y, x = pygame.mouse.get_pos()\n x //= mod\n y //= mod\n\n return x, y\n\n\n# Checks if there is a piece under the mouse\ndef pieceUnderMouse(board):\n x, y = getMousePos()\n return board[x][y]\n\n\n# Moves a piece on the board(Drag and drop animation)\ndef movePiece(piece):\n pos = pygame.mouse.get_pos()\n if piece > 0:\n win.blit(white_pieces[piece - 1],\n white_pieces[piece - 1].get_rect(center=pos))\n\n elif piece < 0:\n win.blit(black_pieces[abs(piece) - 1],\n black_pieces[abs(piece) - 1].get_rect(center=pos))\n\n\n# Animation for highliting a rectangle\ndef highlightRect(col, x, y):\n pygame.draw.rect(win, col, (y * mod, x * mod, mod, mod))\n if abs(x - y) % 2 == 0:\n pygame.draw.rect(\n win, TAN, (y * mod + 3, x * mod + 3, mod - 6, mod - 6))\n\n else:\n pygame.draw.rect(win, DARK_TAN, (y * mod + 3,\n x * mod + 3, mod - 6, mod - 6))\n\n\n# Highlights all the valid moves for a side\ndef highlightValid(validlist):\n if not validlist:\n return\n\n for i in range(len(validlist)):\n highlightRect(YELLOW, validlist[i][2], validlist[i][3])\n\n# Creates a piece with defined properties\n# See \"Pieces\" class\n\n\ndef createPiece(board, piece, x, y):\n piece = abs(piece)\n pieceMap = {1: Pawn(board, x, y),\n 2: Knight(board, x, y),\n 3: Bishop(board, x, y),\n 4: Rook(board, x, y),\n 5: Queen(board, x, y),\n 6: King(board, x, y)}\n\n return pieceMap[piece]\n\n# Checks if a pawn can promote\n\n\ndef canPromote(x):\n if x == 0 or x == 7:\n return True\n\n return False\n\n# Shortens the piece coordinates\n# Ex: [x1, y1, x2, y2] --> [x2, y2]\n\n\ndef reduce(validlist):\n newList = []\n for i in validlist:\n newList.append([i[2], i[3]])\n\n return newList\n\n# Finds all the squares \"protected\" by white\n\n\ndef validWhite(board):\n white = []\n for i in range(len(board)):\n for j in range(len(board[i])):\n if board[i][j] > 0:\n curr = createPiece(board, board[i][j], i, j)\n white += curr.validMoves()\n\n return white\n\n\n# Finds all the squares \"protected\" by black\ndef validBlack(board):\n black = []\n for i in range(len(board)):\n for j in range(len(board[i])):\n if board[i][j] < 0:\n curr = createPiece(board, board[i][j], i, j)\n black += curr.validMoves()\n\n return black\n\n\n# Checks if either of the kings are in check\ndef check(board, white_king, black_king):\n if black_king in reduce(validWhite(board)):\n return -1\n\n if white_king in reduce(validBlack(board)):\n return 1\n\n return 0\n\n\n\"\"\"\ndef castle():\n \n # Black side castling\n if x == 0:\n if board[x][y - 1] == 0 and board[x][y - 2] == 0 and board[x][y - 3] == 0:\n validList.append([x, y, x, y - 2])\n\n if board[x][y + 1] == 0 and board[x][y + 2] == 0:\n validList.append([x, y, x, y + 2])\n\n # White side castling\n if x == 7:\n if board[x][y + 1] == 0 and board[x][y + 2] == 0:\n validList.append([x, y, x, y + 2])\n\n if board[x][y - 1] == 0 and board[x][y - 2] == 0 and board[x][y - 3] == 0:\n validList.append([x, y, x, y - 2]) \n\"\"\"\n'''\n# Creates a short \"animation\" for promotion\ndef promoteBox(color):\n new_y = int((mod // 2) * 7)\n off = (mod * 8) // 60\n dim = mod + 2 * off\n\n \n # Drawing the selectable promotions\n for i in range(4):\n pygame.draw.rect(win, WHITE, ((2 * i * mod) + mod // 2 - off, \n new_y - off, dim, dim))\n if color > 0: \n win.blit(white_pieces[i + 1], ((2 * i * mod) + mod // 2,\n new_y)) \n\n elif color < 0: \n win.blit(black_pieces[i + 1], ((2 * i * mod) + mod // 2, \n new_y))\n\n'''\n\n\ndef main(white_king, black_king):\n '''\n Representation of the chess board in an array\n Each number in the array represents a piece:\n\n 0 - Empty Space\n 1 - Pawn\n 2 - Knight\n 3 - Bishop\n 4 - Rook\n 5 - Queen\n 6 - King\n\n Positive values indicate white pieces\n Negative values indicate black pieces\n\n '''\n # Chess board\n board = [[-4, -2, -3, -5, -6, -3, -2, -4],\n [-1, -1, -1, -1, -1, -1, -1, -1],\n [0, 0, 0, 0, 0, 0, 0, 0],\n [0, 0, 0, 0, 0, 0, 0, 0],\n [0, 0, 0, 0, 0, 0, 0, 0],\n [0, 0, 0, 0, 0, 0, 0, 0],\n [1, 1, 1, 1, 1, 1, 1, 1],\n [4, 2, 3, 5, 6, 3, 2, 4]]\n\n # Important variables\n running = True\n isClicked = False\n\n curr = 0\n color = 1\n valid = []\n cm = False\n counter = 1\n curr_piece = 10\n canCastle = False\n curr_x, curr_y = 10, 10\n\n # Setting a gameloop\n while running:\n\n # Stuff that will run in the background\n createBoard(board, white_king, black_king, valid)\n piece = pieceUnderMouse(board)\n if curr_piece != 0:\n color = curr_piece // abs(curr_piece)\n x, y = getMousePos()\n\n for event in pygame.event.get():\n\n # Exits program\n if event.type == pygame.QUIT:\n running = False\n\n # Checking if the mouse has been pressed\n if event.type == pygame.MOUSEBUTTONDOWN:\n if piece != 0 and not isClicked:\n\n # Set the clicked piece as the current piece\n curr_piece = piece\n curr_x, curr_y = x, y\n isClicked = True\n\n # Checking if the mouse has been released\n if event.type == pygame.MOUSEBUTTONUP:\n\n if isClicked:\n # Animation stuff\n board[curr_x][curr_y] = curr_piece\n lastPiece = board[x][y]\n capture = board[x][y]\n # Checks if the desired move is valid\n if [curr_x, curr_y, x, y] in valid:\n # Update the king's positions\n if abs(curr_piece) == 6:\n if color > 0:\n white_king = [x, y]\n\n else:\n black_king = [x, y]\n\n Piece.placePiece(board, curr_x, curr_y, x, y, 0)\n inCheck = check(board, white_king, black_king)\n counter *= -1\n\n if inCheck != 0:\n \"\"\"\n This part checks if there is a checkmate or not\n\n It looks one move into the future to determine if \n a side has any possible moves that can be played\n \"\"\"\n if inCheck > 0:\n val = validWhite(board)\n\n else:\n val = validBlack(board)\n\n count = 0\n\n # Looping through all the possible moves\n for i in val:\n\n x1, y1, x2, y2 = i\n last = board[x2][y2]\n\n \"\"\"\n Here, we simulate all the possible moves that a side can\n play by taking its \"validMove\" list and placing all of the \n moves on the board, one by one.\n\n We then check if the king is in check if that move is played\n and then reset the move so as to not disturb the game \n \"\"\"\n Piece.placePiece(board, x1, y1, x2, y2, 0)\n if abs(board[x2][y2]) == 6:\n if color < 0:\n white_king = [x2, y2]\n\n elif color > 0:\n black_king = [x2, y2]\n\n inCheck = check(board, white_king, black_king)\n if inCheck != 0:\n count += 1\n\n # Reseting the moves\n Piece.placePiece(board, x2, y2, x1, y1, last)\n if abs(board[x1][y1]) == 6:\n if color < 0:\n white_king = [x1, y1]\n\n elif color > 0:\n black_king = [x1, y1]\n\n # Checking for checkmate\n if count == len(val):\n cm = True\n\n else:\n cm = False\n\n # If a side puts itself in check\n if color == inCheck:\n Piece.placePiece(\n board, x, y, curr_x, curr_y, lastPiece)\n counter *= -1\n\n elif color != inCheck:\n if cm:\n sys.exit()\n\n if capture == 0:\n pygame.mixer.Sound.play(move_sound)\n\n else:\n pygame.mixer.Sound.play(capture_sound)\n curr_piece = board[x][y]\n\n isClicked = False\n\n # If the mouse button is clicked\n if isClicked:\n board[curr_x][curr_y] = curr_piece\n curr = createPiece(board, curr_piece, curr_x, curr_y)\n valid = curr.validMoves()\n board[curr_x][curr_y] = 0\n\n # Using drag n' drop functionality to move the piece\n movePiece(curr_piece)\n\n else:\n # Pawn Promotion functionality\n if abs(curr_piece) == 1 and curr_piece == piece:\n pr = 5\n if canPromote(x):\n board[x][y] = pr * color\n curr_piece = board[x][y]\n\n pygame.display.update()\n\n\n# Running the code\nif __name__ == \"__main__\":\n main(white_king, black_king)\n pygame.quit()\n","sub_path":"chess.py","file_name":"chess.py","file_ext":"py","file_size_in_byte":13135,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"90071156","text":"# DATE: 22.06.2020\n\n\n__author__ = \"PiereLucas\"\n\n\nimport requests\nimport json\nfrom threading import Thread\n\n\nURLADDR = \"https://www.inhalt.com/wp-admin/admin-ajax.php\"\n\nTHREADN = 1000\n\nHEADERS = {\n 'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_6) \\\n AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.109 Safari/537.36',\n 'Accept': 'application/json, application/xml, text/*, text/javascript, */*; q=0.01',\n 'Accept': '*/*',\n 'Accept-Language': 'en-US,en;q=0.5',\n 'Accept-Encoding': 'gzip, deflate, br',\n 'Content-Type': 'multipart/form-data',\n}\n\n\ndef threaded(func):\n \"\"\" Multi-Threading Decorator Function. \"\"\"\n\n def wrapper(*args, **kwargs):\n t = Thread(target=func, args=args, kwargs=kwargs)\n t.start()\n return\n return wrapper\n\n@threaded\ndef makeRequest(url: str):\n\n payload = {\n \"X\": \"d\"\n }\n\n with requests.Session() as s:\n r = s.post(url=url, json=payload)\n\n return r\n\n\nif __name__ == \"__main__\":\n \n for threadNumber in range(1, THREADN + 1):\n print(f\"Starting Thread -> {threadNumber}\")\n r = makeRequest(URLADDR)\n\n#e0f\n","sub_path":"materials/hacking-projects/ajax_request.py","file_name":"ajax_request.py","file_ext":"py","file_size_in_byte":1141,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"641489480","text":"# Copyright (c) 2014 ThoughtWorks\n# Copyright (c) 2016 Platform9 Systems Inc.\n# All Rights Reserved.\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\nclass GroupRuleRefresher:\n\n def __init__(self, ec2_connection, openstack_rule_service, ec2_rule_service):\n self.ec2_conn = ec2_connection\n self.openstack_rule_service = openstack_rule_service\n self.ec2_rule_service = ec2_rule_service\n\n def refresh(self, group_name):\n openstack_rules = self.openstack_rule_service.get_rules_for_group(group_name)\n ec2_rules = self.ec2_rule_service.get_rules_for_group(group_name)\n\n self._add_rules_to_ec2(ec2_rules, group_name, openstack_rules)\n self._remove_rules_from_ec2(ec2_rules, group_name, openstack_rules)\n\n def _add_rules_to_ec2(self, ec2_rules, group_name, openstack_rules):\n for rule in openstack_rules - ec2_rules:\n self._add_rule_on_ec2(group_name, rule)\n\n def _remove_rules_from_ec2(self, ec2_rules, group_name, openstack_rules):\n for rule in ec2_rules - openstack_rules:\n self._remove_rule_from_ec2(group_name, rule)\n\n def _remove_rule_from_ec2(self, group_name, rule):\n self.ec2_conn.revoke_security_group(\n group_name=group_name,\n ip_protocol=rule.ip_protocol,\n from_port=rule.from_port,\n to_port=rule.to_port,\n cidr_ip=rule.ip_range\n )\n\n def _add_rule_on_ec2(self, group_name, rule):\n self.ec2_conn.authorize_security_group(\n group_name=group_name,\n ip_protocol=rule.ip_protocol,\n from_port=rule.from_port,\n to_port=rule.to_port,\n cidr_ip=rule.ip_range\n )\n","sub_path":"nova/ec2/group_rule_refresher.py","file_name":"group_rule_refresher.py","file_ext":"py","file_size_in_byte":2224,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"432518666","text":"from tensorflow.keras.models import Model, Sequential\nfrom tensorflow.keras.layers import Dense, Input\nfrom tensorflow.keras.optimizers import Adam\nfrom tensorflow.keras.optimizers.schedules import PolynomialDecay\nfrom tensorflow.keras.losses import MeanSquaredError\n\nimport tensorflow as tf\nimport tensorflow.keras as K\n\nimport os\nimport sys\nimport csv\nimport numpy as np\nimport datetime\nimport logging\n\nfrom .models import get_model\n\n\n\"\"\"PPO Pseudocode\"\"\"\n# Initial Policy Parameters and Initial Value Function parameters\n# For Num Steps, Do:\n# Collect Trajectories by Running Policy in Environment for n Steps\n# Compute Advantages & Return Estimates with Value Function\n# Update Policy by Maximizing PPO-clip Objective via Adam\n# Update Value Function by Regression with MSE error via Adam\n\n\nclass PPOAgent():\n \"\"\"Proximal Policy Optimisation Agent with Clipping\"\"\"\n\n def __init__(self, opt=None):\n\n # Configs & Hyperparameters\n self.name = \"{}_{}_{}Actions\".format(opt.agent, opt.arch, opt.num_actions)\n self.lr = opt.lr\n self.epochs = opt.num_epochs\n self.batch_size = opt.batch_size\n self.num_actions = opt.num_actions\n self.obs_dim = opt.obs_dim\n self.memory_size = opt.ppo_memory_size\n self.target_steps = 200 * opt.num_episodes\n\n # PPO Hyperparameters\n self.GAE_GAMMA = opt.gae_gamma\n self.GAE_LAMBDA = opt.gae_lambda\n self.PPO_EPSILON = opt.ppo_epsilon\n self.TARGET_KL = opt.target_kl\n self.ENTROPY = 0.001\n\n # Instantiate Model & Optimizer\n self.policy = PolicyModel(opt)\n self.val_loss = MeanSquaredError()\n lr_schedule = PolynomialDecay(self.lr, self.target_steps // self.memory_size * 12 * self.epochs, end_learning_rate=0)\n self.optimizer = Adam(learning_rate=lr_schedule if opt.lr_decay else self.lr)\n\n # Variables to Track Training Progress & Experience Replay Buffer\n self.total_steps = self.num_updates = 0\n self.best = self.eval_best = 0\n self.losses = []\n \n # Initialise Replay Memory Buffer\n self.reset_memory()\n\n # Manage Logging Properties\n time = '{0:%Y-%m-%d_%H-%M-%S}'.format(datetime.datetime.now())\n self.logdir = f\"{opt.exp_dir}/log_{time}\"\n os.mkdir(self.logdir)\n \n # Python Logging Gives Easier-to-read Outputs\n logging.basicConfig(filename=self.logdir+'/log.log', format='%(message)s', filemode='w', level = logging.DEBUG)\n logging.getLogger().addHandler(logging.StreamHandler(sys.stdout))\n\n with open(self.logdir + '/log.csv', 'w+', newline ='') as file:\n write = csv.writer(file)\n write.writerow(['Total Steps', 'Avg Reward', 'Min Reward', 'Max Reward', 'Eval Reward', 'Avg Ep Length'])\n \n with open(self.logdir + '/opt.txt', 'w+', newline ='') as file:\n args = dict((name, getattr(opt, name)) for name in dir(opt) if not name.startswith('_'))\n for k, v in sorted(args.items()):\n file.write(' %s: %s\\n' % (str(k), str(v)))\n \n # Load Last Model if Resume is Specified\n if opt.resume:\n weights2load = K.models.load_model(f'{opt.exp_dir}/last_best.model').get_weights()\n self.policy.set_weights(weights2load)\n logging.info(\"Loaded Weights from Last Best Model!\")\n\n\n def write_log(self, step, **logs):\n \"\"\"Write Episode Information to CSV File\"\"\"\n line = [step] + [round(value, 3) for value in logs.values()]\n with open(self.logdir + '/log.csv', 'a', newline ='') as file:\n write = csv.writer(file)\n write.writerow(line)\n\n \n def callback(self, avg_reward):\n \"\"\"Write Training Information to Console\"\"\"\n \n self.avg_ep_len = self.memory_size / self.episode_counter\n \n logging.info(40*\"-\")\n logging.info(f\"Total Steps: {self.total_steps}\")\n logging.info(f\"Average Train Reward: {avg_reward:.3f}\")\n logging.info(f\"Average Train Ep Length: {self.avg_ep_len:.3f}\")\n logging.info(f\"Average Eval Reward: {self.eval_reward:.3f}\")\n logging.info(f\"Num. Model Updates: {self.num_updates}\")\n \n if len(self.losses) > 0:\n logging.info(f\"Total Loss: {np.mean(self.losses):.5f}\")\n logging.info(f\"Actor Loss: {np.mean(self.a_losses):.5f}\")\n logging.info(f\"Critic Loss: {np.mean(self.c_losses):.5f}\")\n logging.info(f\"Entropy Loss: {np.mean(self.e_losses):.5f}\")\n logging.info(f\"Approx KL Div: {np.mean(self.kl_divs):.3f}\")\n logging.info(f\"Explained Var: {self.explained_var:.3f}\")\n logging.info(f\"Policy Std Dev: {np.exp(self.policy.log_std.numpy()).squeeze():.3f}\")\n logging.info(f\"Learning Rate: {self.optimizer._decayed_lr('float32').numpy():.8f}\")\n \n logging.info(40*\"-\")\n\n\n def learn(self, env, opt):\n \"\"\"Run Rollout & Training Sequence\"\"\"\n while self.total_steps < self.target_steps:\n self.collect_rollout(env, opt)\n self.train()\n self.policy.save(f'{opt.exp_dir}/model_last.model')\n \n\n def reset_memory(self):\n \"\"\"Reset Agent Replay Memory Buffer\"\"\"\n self.replay_memory = {\n \"obss\" : np.zeros((self.memory_size, *self.obs_dim,)),\n \"acts\" : np.zeros((self.memory_size, self.num_actions,)),\n \"rews\" : np.zeros(self.memory_size),\n \"vals\" : np.zeros(self.memory_size),\n \"prbs\" : np.zeros(self.memory_size),\n \"done\" : np.zeros(self.memory_size),\n \"last_ep_starts\" : np.zeros(self.memory_size)\n }\n\n\n def update_replay(self, step, obs, act, rew, val, prb, done, last_ep_start):\n \"\"\"Record Stepwise Episode Information with Critic Output\"\"\"\n self.replay_memory[\"obss\"][step] = obs\n self.replay_memory[\"acts\"][step] = act\n self.replay_memory[\"rews\"][step] = rew\n self.replay_memory[\"vals\"][step] = val\n self.replay_memory[\"prbs\"][step] = prb\n self.replay_memory[\"done\"][step] = done\n self.replay_memory[\"last_ep_starts\"][step] = last_ep_start\n \n\n def collect_rollout(self, env, opt):\n \"\"\"Collect Experiences from Environment for Training\"\"\"\n \n # For Logging of Agent Performance\n ep_rewards = []\n num_steps = 0\n self.episode_counter = 0\n self.last_obs = env.reset()\n\n # printProgressBar(0, self.memory_size, prefix = 'Rollout Collection:', suffix = 'Complete', length = 50)\n \n while num_steps != self.memory_size - 1:\n\n steps, done = 0, False\n last_ep_start = True\n ep_reward = 0\n\n while True:\n\n # Get Action & Step Environment\n action, value, logp = self.policy.act(self.last_obs)\n new_obs, reward, done, _ = env.step(action)\n \n # Break Early if Rollout has Been Filled, Mark Step as End\n if done or num_steps == self.memory_size - 1:\n self.update_replay(num_steps, self.last_obs, action, reward, value, logp, done, last_ep_start)\n self.episode_counter += 1\n break\n \n self.update_replay(num_steps, self.last_obs, action, reward, value, logp, done, last_ep_start)\n self.last_obs = new_obs\n last_ep_start = done\n \n # Increment Step Counters\n steps += 1\n num_steps += 1\n ep_reward += reward\n \n # printProgressBar(num_steps+1, self.memory_size, prefix = 'Rollout Collection:', suffix = 'Complete', length = 50)\n\n self.last_obs = env.reset()\n ep_rewards.append(ep_reward)\n \n # Calculate Last Value for Finished Episode\n _, self.last_val, _ = self.policy.act(new_obs)\n self.total_steps += num_steps + 1\n\n # Log Memory Buffer Information & Write to CSV\n avg_reward = np.mean(ep_rewards)\n min_reward = np.min(ep_rewards)\n max_reward = np.max(ep_rewards)\n \n # Run One Evaluation Run (Deterministic Actions)\n obs, rew, done = env.reset(), 0, False\n while not done:\n action, _ = self.policy(np.expand_dims(obs, axis=0))\n obs, reward, done, _ = env.step(action)\n rew += reward\n self.eval_reward = rew\n \n # Show Training Progress on Console\n self.callback(avg_reward)\n\n self.write_log(self.total_steps, reward_avg=avg_reward, reward_min=min_reward,\n reward_max=max_reward, eval_reward=self.eval_reward, avg_ep_len=self.avg_ep_len)\n\n # Save Model if Average Reward is Greater than a Minimum & Better than Before\n if avg_reward >= np.max([opt.min_reward, self.best]) and opt.save_model:\n self.best = avg_reward\n self.policy.save(f'{opt.exp_dir}/R{avg_reward:.0f}.model')\n \n # Save Model if Eval Reward is Greater than a Minimum & Better than Before\n if self.eval_reward >= np.max([opt.min_reward, self.eval_best]) and opt.save_model:\n self.eval_best = self.eval_reward\n self.policy.save(f'{opt.exp_dir}/eval_R{self.eval_reward:.0f}.model')\n \n # Save Model Every 20 PPO Update Iterations\n if self.total_steps % (20 * self.memory_size) == 0:\n self.policy.save(f'{opt.exp_dir}/checkpoint_{self.total_steps}.model')\n\n\n def process_replay(self, mem):\n \"\"\"Process Episode Information for Value & Advantages\"\"\"\n\n # Calculate Values & Log Probs\n vals = mem[\"vals\"]\n rews = mem[\"rews\"]\n prbs = mem[\"prbs\"]\n done = mem[\"done\"][-1]\n last_ep_starts = mem[\"last_ep_starts\"]\n \n g = self.GAE_GAMMA\n l = self.GAE_LAMBDA\n\n # Initialise Return Arrays with Appropriate Shapes\n advs = np.empty((self.memory_size,))\n rets = np.empty((self.memory_size,))\n\n # Calculate Advantages & Returns\n last_adv = 0\n\n for step in reversed(range(self.memory_size)):\n if step == self.memory_size - 1:\n next_non_terminal = 1.0 - done\n next_value = self.last_val.squeeze()\n else:\n next_non_terminal = 1.0 - last_ep_starts[step + 1]\n next_value = vals[step + 1]\n delta = rews[step] + g * next_value * next_non_terminal - vals[step]\n last_adv = delta + g * l * next_non_terminal * last_adv\n advs[step] = last_adv\n\n rets = advs + vals\n\n return mem[\"obss\"], mem[\"acts\"], advs, rets, vals, prbs\n \n\n def train(self):\n \"\"\"Train Agent by Consuming Collected Memory Buffer\"\"\"\n\n # Process Returns & Advantages for Buffer Info\n buffer_obss, buffer_acts, buffer_advs, buffer_rets, buffer_vals, buffer_prbs = self.process_replay(self.replay_memory)\n \n # Generate Indices for Sampling\n ind = np.random.permutation(self.memory_size)\n \n # Train Logging\n self.losses = []\n self.a_losses = []\n self.c_losses = []\n self.e_losses = []\n self.kl_divs = []\n\n for epoch in range(self.epochs):\n \n for batch_idx in range(0, self.memory_size, self.batch_size): \n\n # Go Through Buffer Batch Size at a Time\n obss = buffer_obss[ind[batch_idx:batch_idx + self.batch_size]]\n acts = buffer_acts[ind[batch_idx:batch_idx + self.batch_size]]\n advs = buffer_advs[ind[batch_idx:batch_idx + self.batch_size]]\n rets = buffer_rets[ind[batch_idx:batch_idx + self.batch_size]]\n prbs = buffer_prbs[ind[batch_idx:batch_idx + self.batch_size]]\n \n # Normalise Advantages\n advs = (advs - advs.mean()) / (advs.std() + 1e-8)\n \n # Cast Constant Inputs to Tensors\n acts = tf.constant(acts, tf.float32)\n advs = tf.constant(advs, tf.float32)\n rets = tf.constant(rets, tf.float32)\n prbs = tf.constant(prbs, tf.float32)\n \n with tf.GradientTape() as tape:\n\n # Run Forward Passes on Models & Get New Log Probs\n a_pred, v_pred = self.policy(obss, training = True)\n new_log_probs = self.policy.logp(a_pred, acts)\n\n # Calculate Ratio Between Old & New Policy\n ratios = tf.exp(new_log_probs - prbs)\n\n # Clipped Actor Loss\n loss1 = advs * ratios\n loss2 = advs * tf.clip_by_value(ratios, 1 - self.PPO_EPSILON, 1 + self.PPO_EPSILON)\n a_loss = tf.reduce_mean(-tf.math.minimum(loss1, loss2))\n\n # Entropy Loss\n entropy = self.policy.entropy()\n e_loss = -tf.reduce_mean(entropy)\n\n # Value Loss\n c_loss = self.val_loss(rets, v_pred)\n\n tot_loss = 0.5 * c_loss + a_loss + self.ENTROPY * e_loss\n \n # Compute KL Divergence for Early Stopping Before Backprop\n kl_div = 0.5 * tf.reduce_mean(tf.square(new_log_probs - prbs))\n\n if self.TARGET_KL != None and kl_div > self.TARGET_KL:\n logging.info(f\"Early stopping at epoch {epoch+1} due to reaching max kl: {kl_div:.3f}\")\n break\n \n # Compute Gradients & Apply to Model\n gradients = tape.gradient(tot_loss, self.policy.trainable_variables)\n gradients, _ = tf.clip_by_global_norm(gradients, 0.5)\n self.optimizer.apply_gradients(zip(gradients, self.policy.trainable_variables))\n \n # Logging\n self.losses.append(tot_loss.numpy())\n self.a_losses.append(a_loss.numpy())\n self.c_losses.append(c_loss.numpy())\n self.e_losses.append(e_loss.numpy())\n self.kl_divs.append(kl_div)\n \n self.num_updates += 1\n\n self.explained_var = explained_variance(buffer_vals, buffer_rets)\n \n self.reset_memory()\n \n\nclass PolicyModel(Model):\n \"\"\"Actor Critic Policy Model for PPO\"\"\"\n \n def __init__(self, opt):\n \"\"\"Pass Model Parameters from Opt & Initialise Learnable Log Std Param\"\"\"\n super().__init__('PolicyModel')\n self.build_model(opt)\n self.log_std = tf.Variable(initial_value=-0.5*np.ones(opt.num_actions, dtype=np.float32))\n \n \n def build_model(self, opt):\n \"\"\"Build Model Layers & Architecture\"\"\"\n \n self.feature_extractor = get_model(opt)\n \n # Retrieve Post-Feature Extractor Dimensions\n for layer in self.feature_extractor.layers:\n feature_output_dim = layer.output_shape\n\n # Define Actor & Critic Networks\n self.actor_network = Sequential()\n self.critic_network = Sequential()\n \n for _ in range(opt.fc_layers):\n self.actor_network.add(Dense(opt.fc_width, activation='tanh'))\n self.critic_network.add(Dense(opt.fc_width, activation='tanh'))\n \n self.actor_network.add(Dense(opt.num_actions, activation='tanh'))\n self.critic_network.add(Dense(1))\n \n self.actor_network.build(feature_output_dim)\n self.critic_network.build(feature_output_dim)\n\n \n def call(self, inputs):\n \"\"\"Run Forward Pass For Training (Deterministic Action)\"\"\"\n feats = self.feature_extractor(inputs)\n action_output = self.actor_network(feats)\n value_output = self.critic_network(feats)\n return action_output, tf.squeeze(value_output)\n \n \n def act(self, obss):\n \"\"\"Get Actions, Values & Log Probs During Experience Collection\"\"\"\n \n obss = np.expand_dims(obss, axis=0)\n \n # Run Forward Passes\n feats = self.feature_extractor(obss)\n a_pred = self.actor_network(feats)\n v_pred = self.critic_network(feats)\n \n # Calcualte Log Probabilities\n std = tf.exp(self.log_std)\n action = a_pred + tf.random.normal(tf.shape(a_pred)) * std\n action = tf.clip_by_value(action, -1, 1)\n logp_t = self.logp(action, a_pred)\n \n return action.numpy(), v_pred.numpy().squeeze(), logp_t.numpy().squeeze()\n \n \n def logp(self, x, mu):\n \"\"\"Return Log Probability of Action Given Distribution Parameters\"\"\"\n pre_sum = -0.5 * (((x - mu) / (tf.exp(self.log_std) + 1e-8))**2 + 2 * self.log_std + np.log(2 * np.pi))\n return tf.reduce_sum(pre_sum, axis= -1)\n \n \n def entropy(self):\n \"\"\"Return Entropy of Policy Distribution\"\"\"\n entropy = tf.reduce_sum(self.log_std + 0.5 * np.log(2.0 * np.pi * np.e), axis=-1)\n return entropy\n \n \n# From stable baselines\ndef explained_variance(y_pred: np.ndarray, y_true: np.ndarray) -> np.ndarray:\n \"\"\"\n Computes fraction of variance that ypred explains about y.\n Returns 1 - Var[y-ypred] / Var[y]\n interpretation:\n ev=0 => might as well have predicted zero\n ev=1 => perfect prediction\n ev<0 => worse than just predicting zero\n :param y_pred: the prediction\n :param y_true: the expected value\n :return: explained variance of ypred and y\n \"\"\"\n var_y = np.var(y_true)\n return np.nan if var_y == 0 else 1 - np.var(y_true - y_pred) / var_y\n\n# Print iterations progress\ndef printProgressBar (iteration, total, prefix = '', suffix = '', decimals = 1, length = 100, fill = '█', printEnd = \"\\r\"):\n \"\"\"\n Call in a loop to create terminal progress bar\n @params:\n iteration - Required : current iteration (Int)\n total - Required : total iterations (Int)\n prefix - Optional : prefix string (Str)\n suffix - Optional : suffix string (Str)\n decimals - Optional : positive number of decimals in percent complete (Int)\n length - Optional : character length of bar (Int)\n fill - Optional : bar fill character (Str)\n printEnd - Optional : end character (e.g. \"\\r\", \"\\r\\n\") (Str)\n \"\"\"\n percent = (\"{0:.\" + str(decimals) + \"f}\").format(100 * (iteration / float(total)))\n filledLength = int(length * iteration // total)\n bar = fill * filledLength + '-' * (length - filledLength)\n print(f'\\r{prefix} |{bar}| {percent}% {suffix}', end = printEnd)\n # Print New Line on Complete\n if iteration == total: \n print()","sub_path":"agent/PPO.py","file_name":"PPO.py","file_ext":"py","file_size_in_byte":19070,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"102300225","text":"# # Summer of Code - Week 1\n# # Day 1\n# ###### https://github.com/mswann11/toolkitten/blob/master/summer-of-code/week-01/day1.md\n# ### Numbers\n\nimport math\nimport string\nimport os\nimport datetime\nimport random\n\n# Hours in a year. How many hours are in a year?\nprint(365*24)\n\n\n# Minutes in a decade. How many minutes are in a decade?\nprint(10*365*24*60)\n\n\n# Your age in seconds. How many seconds old are you? \nprint(((37*365)+(28-11)+31+30+31+30+20)*24*60*60)\n\n\n# How many days does it take for a 32-bit system to timeout, if it has a bug with integer overflow?\nprint(math.ceil(((((2**32)/1000)/60)/60)/24))\n\n\n# How about a 64-bit system?\nprint(math.ceil(((((2**64)/1000)/60)/60)/24))\n\n\n# Calculate your age accurately based on your birthday \n# (maybe use time of day e.g. 8:23am if you know it, use 12:00 noon midday)\n# You will need Python modules.\nx = datetime.datetime.now()\nprint(\"Now: \" + str(x))\ny = datetime.datetime(1981, 2, 11, 6, 30)\nprint(\"Birthday: \" + str(y))\nz = x-y\nseconds = z.days*24*60*60 + z.seconds\nyears = seconds/60/60/24/365\nprint(\"You are \" + str(round(years,2)) + \" years old!\")\ndays = z.days\nprint(\"You are \" + str(days) + \" days old!\")\nhours = z.days*24\nprint(\"You are \" + str(hours) + \" hours old!\")\nminutes = z.days*24*60\nprint(\"You are \" + str(minutes) + \" minutes old!\")\nseconds = z.days*24*60*60 + z.seconds\nprint(\"You are \" + str(seconds) + \" seconds old!\")\n\n\n# # Day 2\n# ###### https://github.com/mswann11/toolkitten/blob/master/summer-of-code/week-01/day2.md\n# ### Letters, Variables\n# No exercises assigned.\n\n\n# # Day 3\n# ###### https://github.com/mswann11/toolkitten/blob/master/summer-of-code/week-01/day3.md\n# ### Love Affair between Numbers and Letters\n\n# Full name greeting. Write a program that asks for a person’s first name, then middle, and then last. \n# Finally, it should greet the person using their full name.\nfirstName = input(\"Please enter your first name: \")\nmiddleName = input(\"Please enter your middle name: \")\nlastName = input(\"Please enter your last name: \")\nprint(\"Hello, \" + firstName + \" \" + middleName + \" \" + lastName + \"! \" + \"It's very nice to meet you!\")\n\n\n# Bigger, better favorite number. Write a program that asks for a person’s favorite number. \n# Have your program add 1 to the number, and then suggest the result as a bigger and better favorite number.\nfavoriteNumber = int(input(\"What is your favorite number? \"))\nfavoritePlusOne = favoriteNumber + 1\nprint(str(favoriteNumber) + \" is a good number, but don't you think \" + str(favoritePlusOne) + \" is better?\")\n\n\n# Angry boss. Write an angry boss program that rudely asks what you want. \n# Whatever you answer, the angry boss should yell it back to you and then fire you. \n# For example, if you type in I want a raise, it should yell back like this:\n# WHADDAYA MEAN \"I WANT A RAISE\"?!? YOU'RE FIRED!!\nanswer = input(\"WHAT DO YOU WANT?!? \")\nprint(\"WHADDAYA MEAN \\\"\"+ answer.upper() + \"\\\"?!? YOU'RE FIRED!!\")\n\n\n# Table of contents. Here’s something for you to do in order to play around more with center, \n# ljust, and rjust: write a program that will display a table of contents so that it looks like this:\n# Table of Contents\n# Chapter 1: Getting Started page 1 \n# Chapter 2: Numbers page 9 \n# Chapter 3: Letters page 13\ntitle = \"Table of Contents\"\nchapterNames = [\"Getting Started\", \"Numbers\", \"Letters\"]\npageNumbers = [\"page 1\", \"page 9\", \"page 13\"]\nfor x in range (1,4):\n chapter = \"Chapter \" + str(x) + \":\"\n print(chapter.ljust(12, \" \") + chapterNames[x-1].ljust(30,\" \") + pageNumbers[x-1].ljust(10, \" \"))\n\n\n# # Day 4\n# ###### https://github.com/mswann11/toolkitten/blob/master/summer-of-code/week-01/day4.md\n# ### Looping\n\n# Write a program that prints out the lyrics to that beloved classic, “99 Bottles of Beer on the Wall.”\ntitle = \"99 Bottles of Beer on the Wall\\n\"\nlyricLineOne = \" bottles of beer on the wall, \"\nlyricLineTwo = \" bottles of beer! \"\nlyricLineThree = \"Take one down, pass it around, \"\nlyricLineFour = \" bottles of beer on the wall!\"\nprint(title.center(100, \" \"))\nfor x in range(99,90,-1):\n print(str(x) + lyricLineOne + str(x) + lyricLineTwo + lyricLineThree + str(x-1) + lyricLineFour)\n\n\n# Deaf grandma. Whatever you say to Grandma (whatever you type in), she should respond with this: \n# HUH?! SPEAK UP, GIRL!,\n# unless you shout it (type in all capitals). If you shout, she can hear you (or at least she thinks so) and yells back:\n# NO, NOT SINCE 1938!\n# To make your program really believable, have Grandma shout a different year each time, \n# maybe any year at random between 1930 and 1950. \n# You can’t stop talking to Grandma until you shout BYE.\nanswer = input(\"What do you have to say? \")\nwhile answer != \"BYE\":\n if answer.isupper():\n print(\"NO, NOT SINCE \"+ str(random.randint(1938,1950)) + \"!\")\n answer = input(\"What else do you have to say? \")\n else:\n answer = input(\"HUH?! SPEAK UP, GIRL! \")\nprint(\"OH OKAY, BYE-BYE HONEY!\")\n\n\n# Deaf grandma extended. What if Grandma doesn’t want you to leave? When you shout BYE, she could pretend not to hear you. \n# Change your previous program so that you have to shout BYE three times in a row. \n# Make sure to test your program: if you shout BYE three times but not in a row, you should still be talking to Grandma.\nanswer = input(\"What do you have to say? \")\nbyeCount = 0\nwhile byeCount != 2:\n if (answer == \"BYE\"):\n byeCount += 1\n answer = input(\"\")\n elif answer.isupper():\n byeCount = 0\n print(\"NO, NOT SINCE \"+ str(random.randint(1938,1950)) + \"!\")\n answer = input(\"What else do you have to say? \")\n else:\n byeCount = 0\n answer = input(\"HUH?! SPEAK UP, GIRL! \")\nprint(\"OH OKAY, BYE-BYE HONEY!\")\n\n\n# Leap years. Write a program that asks for a starting year and an ending year and then puts \n# all the leap years between them (and including them, if they are also leap years). \n# Leap years are years divisible by 4 (like 1984 and 2004). However, years divisible by 100 are not leap years \n# (such as 1800 and 1900) unless they are also divisible by 400 (such as 1600 and 2000, which were in fact leap years). \n# What a mess!\nstartingYear = int(input(\"Enter starting year: \"))\nendingYear = int(input(\"Enter ending year: \"))\nleapYears = \"Leap years: \"\nfor y in range(startingYear, endingYear + 1):\n if y % 4 == 0:\n if y % 100 == 0:\n if y % 400 == 0:\n leapYears += str(y) + \" \"\n else:\n leapYears += str(y) + \" \"\nprint(leapYears)\n\n\n# Find something today in your life, that is a calculation. Go for a walk, look around the park, try to count something. \n# Anything! And write a program about it. e.g. number of stairs, steps, windows, leaves estimated in the park, \n# kids, dogs, estimate your books by bookshelf, toiletries, wardrobe.\n# Bookshelf with 6 shelves, each shelf is 3 feet wide, average width of each book is 1.5 inches. \n# How many books can the bookshelf hold?\nwidth = 3*12\ntotalSpace = width*6\nbooks = int(totalSpace/1.5)\nprint(\"The bookshelf can hold \" + str(books) + \" books.\")\n\n\n# ### Lists\n\n# Building and sorting an array. Write the program that asks us to type as many words as we want \n# (one word per line, continuing until we just press Enter on an empty line) and then repeats the words \n# back to us in alphabetical order. Make sure to test your program thoroughly; for example, \n# does hitting Enter on an empty line always exit your program? Even on the first line? And the second?\nwords = []\nnewWord = input(\"Enter words to add to your word list:\\n\")\nwhile(newWord != \"\"):\n words.append(newWord)\n newWord = input()\nif len(words) == 0:\n print(\"Your word list is empty.\")\nelse:\n words.sort()\n wordList = \"\"\n for w in words:\n wordList += w + \" \"\n print(\"Your sorted word list: \" + wordList)\n\n\n# Table of contents. Write a table of contents program here. Start the program with a list holding all \n# of the information for your table of contents (chapter names, page numbers, and so on). \n# Then print out the information from the list in a beautifully formatted table of contents. \n# Use string formatting such as left align, right align, center.\ntitle = \"Table of Contents\"\nchapters = [[\"Chapter 1:\",\"Getting Started\",\"page 1\"],\n [\"Chapter 2:\",\"Numbers\",\"page 9\"],\n [\"Chapter 3:\",\"Letters\",\"page 13\"]]\nfor c in chapters:\n print(c[0].ljust(12, \" \") + c[1].ljust(20, \" \") + c[2].rjust(20, \" \"))\n\n\n# ### Functions\n\n# Write a function that prints out \"moo\" n times.\ndef printMoo(n):\n for x in range(n):\n print(\"moo \")\nn = int(input(\"Pick a number: \"))\nprintMoo(n)\n\n\n# Old-school Roman numerals. In the early days of Roman numerals, the Romans didn’t bother \n# with any of this new-fangled subtraction “IX” nonsense.\n# No Mylady, it was straight addition, biggest to littlest—so 9 was written “VIIII,” and so on.\n# Write a method that when passed an integer between 1 and 3000 (or so) returns a string containing \n# the proper old-school Roman numeral. In other words, old_roman_numeral 4 should return 'IIII'. \n# Make sure to test your method on a bunch of different numbers.\n# Hint: Use the integer division and modulus methods.\n# For reference, these are the values of the letters used: \n# I = 1 V = 5 X = 10 L = 50 C = 100 D = 500 M = 1000\nnumber = int(input(\"Enter a number to convert to Roman numerals: \"))\n\ndef getThousand(n):\n m = \"\"\n r = n\n if(n>=1000):\n m_as_int = int(n/1000)\n r = n % 1000\n for j in range(m_as_int):\n m += \"M\"\n return (m,r)\n\ndef getFiveHundred(n):\n d = \"\"\n r = n\n if(n>=500):\n d_as_int = int(n/500)\n r = n % 500\n for j in range(d_as_int):\n d += \"D\"\n return (d,r)\n\ndef getHundred(n):\n c = \"\"\n r = n\n if(n>=100):\n c_as_int = int(n/100)\n r = n % 100\n for j in range(c_as_int):\n c += \"C\"\n return (c,r)\n\ndef getFifty(n):\n l = \"\"\n r = n\n if(n>=50):\n l_as_int = int(n/50)\n r = n % 50\n for j in range(l_as_int):\n l += \"L\"\n return (l,r)\n\ndef getTen(n):\n x = \"\"\n r = n\n if(n>=10):\n x_as_int = int(n/10)\n r = n % 10\n for j in range(x_as_int):\n x += \"X\"\n return (x,r)\n\ndef getFive(n):\n v = \"\"\n r = n\n if(n>=5):\n v_as_int = int(n/5)\n r = n % 5\n for j in range(v_as_int):\n v += \"V\"\n return (v,r)\n\ndef getOne(n):\n i = \"\"\n for j in range(n):\n i += \"I\"\n return i\n \n\n(thousand,remainderM) = getThousand(number)\n(fiveHundred,remainderD) = getFiveHundred(remainderM)\n(hundred,remainderC) = getHundred(remainderD)\n(fifty,remainderL) = getFifty(remainderC)\n(ten,remainderX) = getTen(remainderL)\n(five,remainderV) = getFive(remainderX)\none = getOne(remainderV)\n\nroman = thousand + fiveHundred + hundred + fifty + ten + five + one\nprint(\"Conversion: \" + roman)\n\n\n# “Modern” Roman numerals. Eventually, someone thought it would be terribly clever if putting \n# a smaller number before a larger one meant you had to subtract the smaller one. \n# As a result of this development, you must now suffer. \n# Rewrite your previous method to return the new-style Roman numerals\n# so when someone calls roman_numeral 4, it should return 'IV', 90 should be 'XC' etc.\nnumber = int(input(\"Enter a number to convert to Roman numerals: \"))\n\ndef getThousand(n):\n m = \"\"\n r = n\n c = \"\"\n if(n>=1000):\n m_as_int = int(n/1000)\n r = n % 1000\n for j in range(m_as_int):\n m += \"M\"\n if(r>=900):\n c = \"CM\"\n r = r-900\n return (m,r,c)\n\ndef getFiveHundred(n):\n d = \"\"\n r = n\n c = \"\"\n if(n>=500):\n d_as_int = int(n/500)\n r = n % 500\n for j in range(d_as_int):\n d += \"D\"\n if(r>=400):\n c = \"CD\"\n r = r-400\n return (d,r,c)\n\ndef getHundred(n):\n c = \"\"\n r = n\n x = \"\"\n if(n>=100):\n c_as_int = int(n/100)\n r = n % 100\n for j in range(c_as_int):\n c += \"C\"\n if(r>=90):\n x = \"XC\"\n r = r-90\n return (c,r,x)\n\ndef getFifty(n):\n l = \"\"\n r = n\n x = \"\"\n if(n>=50):\n l_as_int = int(n/50)\n r = n % 50\n for j in range(l_as_int):\n l += \"L\"\n if(r>=40):\n x = \"XL\"\n r = r-40\n return (l,r,x)\n\ndef getTen(n):\n x = \"\"\n r = n\n i = \"\"\n if(n>=10):\n x_as_int = int(n/10)\n r = n % 10\n for j in range(x_as_int):\n x += \"X\"\n if(r==9):\n i = \"IX\"\n r = 0\n return (x,r,i)\n\ndef getFive(n):\n v = \"\"\n r = n\n i = \"\"\n if(n>=5):\n v_as_int = int(n/5)\n r = n % 5\n for j in range(v_as_int):\n v += \"V\"\n if(r==4):\n i = \"IV\"\n r = 0\n return (v,r,i)\n\ndef getOne(n):\n i = \"\"\n for j in range(n):\n i += \"I\"\n return i\n\n(thousand,remainderM,mNegC) = getThousand(number)\n(fiveHundred,remainderD,dNegC) = getFiveHundred(remainderM)\n(hundred,remainderC,cNegX) = getHundred(remainderD)\n(fifty,remainderL,lNegX) = getFifty(remainderC)\n(ten,remainderX,xNegI) = getTen(remainderL)\n(five,remainderV,vNegI) = getFive(remainderX)\none = getOne(remainderV)\n\nroman = thousand + mNegC + fiveHundred + dNegC + hundred + cNegX + fifty + lNegX + ten + xNegI + five + vNegI + one\nprint(\"Conversion: \" + roman)","sub_path":"summer-of-code/week-01/wk1-homework-submissions/soc01hw-marianne-swann.py","file_name":"soc01hw-marianne-swann.py","file_ext":"py","file_size_in_byte":13393,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"307577772","text":"import numpy, itertools, pickle, warnings as _builtin_warnings, operator\nfrom nutils import evaluable, function, mesh, numeric, types, points, transformseq, transform, element\nfrom nutils.testing import *\n_ = numpy.newaxis\n\n\nclass Array(TestCase):\n\n def test_cast_ndim_mismatch(self):\n with self.assertRaises(ValueError):\n function.Array.cast([1,2], ndim=2)\n\n def test_cast_dtype_mismatch(self):\n with self.assertRaises(ValueError):\n function.Array.cast([1.2,2.3], dtype=int)\n\n def test_cast_invalid_argument(self):\n with self.assertRaises(ValueError):\n function.Array.cast('132')\n\n def test_ndim(self):\n self.assertEqual(function.Argument('a', (2,3)).ndim, 2)\n\n def test_shape(self):\n n = function.Argument('n', (), dtype=int)\n l1, l2, l3 = function.Argument('a', (2, function.Array.cast(3),n)).shape\n with self.subTest('int'):\n self.assertEqual(l1, 2)\n with self.subTest('const Array'):\n self.assertEqual(l2, 3)\n with self.subTest('unknown'):\n self.assertEqual(l3.prepare_eval(npoints=None).simplified, n.prepare_eval(npoints=None).simplified)\n\n def test_size_known(self):\n self.assertEqual(function.Argument('a', (2,3)).size, 6)\n\n def test_size_0d(self):\n self.assertEqual(function.Argument('a', ()).size, 1)\n\n def test_size_unknown(self):\n n = function.Argument('n', (), dtype=int)\n size = function.Argument('a', (2,n,3)).size\n self.assertIsInstance(size, function.Array)\n self.assertEqual(size.prepare_eval(npoints=None).simplified, (2*n*3).prepare_eval(npoints=None).simplified)\n\n def test_len_0d(self):\n with self.assertRaisesRegex(Exception, '^len\\\\(\\\\) of unsized object$'):\n len(function.Array.cast(0))\n\n def test_len_known(self):\n self.assertEqual(len(function.Array.cast([1,2])), 2)\n\n def test_len_unknown(self):\n with self.assertRaisesRegex(Exception, '^unknown length$'):\n len(function.Argument('a', [function.Argument('b', (), dtype=int)]))\n\n def test_iter_0d(self):\n with self.assertRaisesRegex(Exception, '^iteration over a 0-D array$'):\n iter(function.Array.cast(0))\n\n def test_iter_known(self):\n a, b = function.Array.cast([1,2])\n self.assertEqual(a.prepare_eval(npoints=None).eval(), 1)\n self.assertEqual(b.prepare_eval(npoints=None).eval(), 2)\n\n def test_iter_unknown(self):\n with self.assertRaisesRegex(Exception, '^iteration over array with unknown length$'):\n iter(function.Argument('a', [function.Argument('b', (), dtype=int)]))\n\n def test_binop_notimplemented(self):\n with self.assertRaises(TypeError):\n function.Argument('a', ()) + '1'\n\n def test_rbinop_notimplemented(self):\n with self.assertRaises(TypeError):\n '1' + function.Argument('a', ())\n\n def test_deprecated_simplified(self):\n with self.assertWarns(warnings.NutilsDeprecationWarning):\n function.Array.cast([1,2]).simplified\n\n\n@parametrize\nclass check(TestCase):\n\n def setUp(self):\n super().setUp()\n numpy.random.seed(0)\n\n def assertArrayAlmostEqual(self, actual, desired, decimal):\n if actual.shape != desired.shape:\n self.fail('shapes of actual {} and desired {} are incompatible.'.format(actual.shape, desired.shape))\n error = actual - desired if not actual.dtype.kind == desired.dtype.kind == 'b' else actual ^ desired\n approx = error.dtype.kind in 'fc'\n mask = numpy.greater_equal(abs(error), 1.5 * 10**-decimal) if approx else error\n indices = tuple(zip(*mask.nonzero())) if actual.ndim else ((),) if mask.any() else ()\n if not indices:\n return\n lines = ['arrays are not equal']\n if approx:\n lines.append(' up to {} decimals'.format(decimal))\n lines.append(' in {}/{} entries:'.format(len(indices), error.size))\n n = 5\n lines.extend('\\n {} actual={} desired={} difference={}'.format(index, actual[index], desired[index], error[index]) for index in indices[:n])\n if len(indices) > 2*n:\n lines.append('\\n ...')\n n = -n\n lines.extend('\\n {} actual={} desired={} difference={}'.format(index, actual[index], desired[index], error[index]) for index in indices[n:])\n self.fail(''.join(lines))\n\n def test_lower_eval(self):\n args = tuple((numpy.random.randint if self.dtype == int else numpy.random.uniform)(size=shape, low=self.low, high=self.high) for shape in self.shapes)\n actual = self.op(*args).prepare_eval(npoints=None).eval()\n desired = self.n_op(*args)\n self.assertArrayAlmostEqual(actual, desired, decimal=15)\n\ndef _check(name, op, n_op, shapes, low=None, high=None, dtype=float):\n if low is None:\n low = 0 if dtype == int else -1\n if high is None:\n high = 20 if dtype == int else 1\n check(name, op=op, n_op=n_op, shapes=shapes, low=low, high=high, dtype=dtype)\n\n_check('asarray', function.asarray, lambda a: a, [(2,4,2)])\n_check('zeros', lambda: function.zeros([1,4,3,4]), lambda: numpy.zeros([1,4,3,4]), [])\n_check('ones', lambda: function.ones([1,4,3,4]), lambda: numpy.ones([1,4,3,4]), [])\n_check('eye', lambda: function.eye(3), lambda: numpy.eye(3), [])\n\n_check('add', function.add, numpy.add, [(4,), (4,)])\n_check('Array_add', lambda a, b: function.Array.cast(a) + b, numpy.add, [(4,), (4,)])\n_check('Array_radd', lambda a, b: a + function.Array.cast(b), numpy.add, [(4,), (4,)])\n_check('subtract', function.subtract, numpy.subtract, [(4,), (4,)])\n_check('Array_sub', lambda a, b: function.Array.cast(a) - b, numpy.subtract, [(4,), (4,)])\n_check('Array_rsub', lambda a, b: a - function.Array.cast(b), numpy.subtract, [(4,), (4,)])\n_check('negative', function.negative, numpy.negative, [(4,)])\n_check('Array_neg', lambda a: -function.Array.cast(a), numpy.negative, [(4,)])\n_check('Array_pos', lambda a: +function.Array.cast(a), lambda a: a, [(4,)])\n_check('multiply', function.multiply, numpy.multiply, [(4,), (4,)])\n_check('Array_mul', lambda a, b: function.Array.cast(a) * b, numpy.multiply, [(4,), (4,)])\n_check('Array_rmul', lambda a, b: a * function.Array.cast(b), numpy.multiply, [(4,), (4,)])\n_check('divide', function.divide, numpy.divide, [(4,), (4,)])\n_check('Array_truediv', lambda a, b: function.Array.cast(a) / b, numpy.divide, [(4,), (4,)])\n_check('Array_rtruediv', lambda a, b: a / function.Array.cast(b), numpy.divide, [(4,), (4,)])\n_check('floor_divide', function.floor_divide, numpy.floor_divide, [(4,4,), (4,)], dtype=int, low=1, high=10)\n_check('Array_floordiv', lambda a, b: function.Array.cast(a) // b, numpy.floor_divide, [(4,4,), (4,)], dtype=int, low=1, high=10)\n_check('Array_rfloordiv', lambda a, b: a // function.Array.cast(b), numpy.floor_divide, [(4,4,), (4,)], dtype=int, low=1, high=10)\n_check('reciprocal', function.reciprocal, numpy.reciprocal, [(4,)])\n_check('power', function.power, numpy.power, [(4,), (4,)], low=1, high=2)\n_check('Array_pow', lambda a, b: function.Array.cast(a) ** b, numpy.power, [(4,), (4,)], low=1, high=2)\n_check('Array_rpow', lambda a, b: a ** function.Array.cast(b), numpy.power, [(4,), (4,)], low=1, high=2)\n_check('sqrt', function.sqrt, numpy.sqrt, [(4,)])\n_check('abs', function.abs, numpy.abs, [(4,)])\n_check('Array_abs', lambda a: abs(function.Array.cast(a)), numpy.abs, [(4,)])\n_check('sign', function.sign, numpy.sign, [(4,)])\n_check('mod', function.mod, numpy.mod, [(4,4), (4,)], dtype=int, low=1, high=10)\n_check('Array_mod', lambda a, b: function.Array.cast(a) % b, numpy.mod, [(4,4), (4,)], dtype=int, low=1, high=10)\n_check('Array_rmod', lambda a, b: a % function.Array.cast(b), numpy.mod, [(4,4), (4,)], dtype=int, low=1, high=10)\n\n_check('cos', function.cos, numpy.cos, [(4,)])\n_check('sin', function.sin, numpy.sin, [(4,)])\n_check('tan', function.tan, numpy.tan, [(4,)])\n_check('arccos', function.arccos, numpy.arccos, [(4,)])\n_check('arcsin', function.arcsin, numpy.arcsin, [(4,)])\n_check('arctan', function.arctan, numpy.arctan, [(4,)])\n_check('arctan2', function.arctan2, numpy.arctan2, [(4,1),(1,4)])\n_check('cosh', function.cosh, numpy.cosh, [(4,)])\n_check('sinh', function.sinh, numpy.sinh, [(4,)])\n_check('tanh', function.tanh, numpy.tanh, [(4,)])\n_check('arctanh', function.arctanh, numpy.arctanh, [(4,)])\n_check('exp', function.exp, numpy.exp, [(4,)])\n_check('log', function.log, numpy.log, [(4,)], low=0)\n_check('log2', function.log2, numpy.log2, [(4,)], low=0)\n_check('log10', function.log10, numpy.log10, [(4,)], low=0)\n\n_check('greater', function.greater, numpy.greater, [(4,1),(1,4)])\n_check('equal', function.equal, numpy.equal, [(4,1),(1,4)])\n_check('less', function.less, numpy.less, [(4,1),(1,4)])\n_check('min', function.min, numpy.minimum, [(4,4),(4,4)])\n_check('max', function.max, numpy.maximum, [(4,4),(4,4)])\n\n# TODO: opposite\n# TODO: mean\n# TODO: jump\n\n_check('sum', lambda a: function.sum(a,2), lambda a: a.sum(2), [(4,3,4)])\n_check('Array_sum', lambda a: function.Array.cast(a).sum(2), lambda a: a.sum(2), [(4,3,4)])\n_check('product', lambda a: function.product(a,2), lambda a: numpy.product(a,2), [(4,3,4)])\n_check('Array_prod', lambda a: function.Array.cast(a).prod(2), lambda a: numpy.product(a,2), [(4,3,4)])\n\n_check('dot', lambda a,b: function.dot(a,b,axes=2), lambda a,b: (a*b).sum(2), [(4,2,4),(4,2,4)])\n_check('Array_dot', lambda a,b: function.Array.cast(a).dot(b,axes=2), lambda a,b: (a*b).sum(2), [(4,2,4),(4,2,4)])\n_check('trace', function.trace, numpy.trace, [(3,3)])\n_check('norm2', function.norm2, lambda a: numpy.linalg.norm(a, axis=1), [(2,3)])\n_check('normalized', function.normalized, lambda a: a / numpy.linalg.norm(a, axis=1)[:,None], [(2,3)])\n_check('Array_normalized', lambda a: function.Array.cast(a).normalized(), lambda a: a / numpy.linalg.norm(a, axis=1)[:,None], [(2,3)])\n_check('inverse', lambda a: function.inverse(a+3*numpy.eye(3)), lambda a: numpy.linalg.inv(a+3*numpy.eye(3)), [(2,3,3)])\n_check('determinant', lambda a: function.determinant(a+3*numpy.eye(3)), lambda a: numpy.linalg.det(a+3*numpy.eye(3)), [(2,3,3)])\n_check('eigval', lambda a: function.eig(a)[0], lambda a: numpy.diag(numpy.linalg.eig(a)[0]), [(3,3)])\n_check('eigvec', lambda a: function.eig(a)[1], lambda a: numpy.linalg.eig(a)[1], [(3,3)])\n_check('eigval_symmetric', lambda a: function.eig(a+a.T)[0], lambda a: numpy.diag(numpy.linalg.eig(a+a.T)[0]), [(3,3)])\n_check('eigvec_symmetric', lambda a: function.eig(a+a.T)[1], lambda a: numpy.linalg.eig(a+a.T)[1], [(3,3)])\n_check('takediag', function.takediag, numpy.diag, [(3,3)])\n_check('diagonalize', function.diagonalize, numpy.diag, [(3,)])\n_check('cross', function.cross, numpy.cross, [(3,), (3,)])\n_check('outer', function.outer, lambda a, b: a[:,None]*b[None,:], [(2,3),(4,3)])\n_check('outer_self', function.outer, lambda a: a[:,None]*a[None,:], [(2,3)])\n\n_check('transpose', lambda a: function.transpose(a,[0,1,3,2]), lambda a: a.transpose([0,1,3,2]), [(1,2,3,4)], dtype=int)\n_check('Array_transpose', lambda a: function.Array.cast(a).transpose([0,1,3,2]), lambda a: a.transpose([0,1,3,2]), [(1,2,3,4)], dtype=int)\n_check('insertaxis', lambda a: function.insertaxis(a,2,3), lambda a: numpy.repeat(numpy.expand_dims(a,2), 3, 2), [(3,2,4)], dtype=int)\n_check('expand_dims', lambda a: function.expand_dims(a,1), lambda a: numpy.expand_dims(a,1), [(2,3)], dtype=int)\n_check('repeat', lambda a: function.repeat(a,3,1), lambda a: numpy.repeat(a,3,1), [(2,1,4)], dtype=int)\n_check('swapaxes', lambda a: function.swapaxes(a,1,2), lambda a: numpy.transpose(a, (0,2,1)), [(2,3,4)], dtype=int)\n_check('Array_swapaxes', lambda a: function.Array.cast(a).swapaxes(1,2), lambda a: numpy.transpose(a, (0,2,1)), [(2,3,4)], dtype=int)\n_check('ravel', lambda a: function.ravel(a,1), lambda a: numpy.reshape(a, (2,12,5)), [(2,3,4,5)], dtype=int)\n_check('unravel', lambda a: function.unravel(a,1,(3,4)), lambda a: numpy.reshape(a, (2,3,4,5)), [(2,12,5)], dtype=int)\n_check('take', lambda a: function.take(a, numpy.array([[0,2],[1,3]]), 1), lambda a: numpy.take(a, numpy.array([[0,2],[1,3]]), 1), [(3,4,5)], dtype=int)\n_check('take_bool', lambda a: function.take(a, numpy.array([False, True, False, True]), 1), lambda a: numpy.compress(numpy.array([False, True, False, True]), a, 1), [(3,4,5)], dtype=int)\n_check('get', lambda a: function.take(a, 1, 1), lambda a: numpy.take(a, 1, 1), [(3,4,5)], dtype=int)\n_check('inflate', lambda a: function.inflate(a,numpy.array([0,3]), 4, 1), lambda a: numpy.concatenate([a[:,:1], numpy.zeros_like(a), a[:,1:]], axis=1), [(4,2,4)])\n_check('kronecker', lambda a: function.kronecker(a,1,3,1), lambda a: numpy.stack([numpy.zeros_like(a), a, numpy.zeros_like(a)], axis=1), [(4,4)])\n_check('concatenate', lambda a, b: function.concatenate([a,b], axis=1), lambda a, b: numpy.concatenate([a,b], axis=1), [(4,2,1),(4,3,1)])\n_check('stack', lambda a,b: function.stack([a,b], 1), lambda a,b: numpy.stack([a,b], 1), [(4,2),(4,2)])\n\n_check('Array_getitem_scalar', lambda a: function.Array.cast(a)[0], lambda a: a[0], [(5,3,2)], dtype=int)\n_check('Array_getitem_scalar_scalar', lambda a: function.Array.cast(a)[0,1], lambda a: a[0,1], [(5,3,2)], dtype=int)\n_check('Array_getitem_slice_step', lambda a: function.Array.cast(a)[:,::2], lambda a: a[:,::2], [(5,3,2)], dtype=int)\n_check('Array_getitem_ellipsis_scalar', lambda a: function.Array.cast(a)[...,1], lambda a: a[...,1], [(5,3,2)], dtype=int)\n_check('Array_getitem_ellipsis_scalar_newaxis', lambda a: function.Array.cast(a)[...,1,None], lambda a: a[...,1,None], [(5,3,2)], dtype=int)\n\n_check('add_T', lambda a: function.add_T(a, (1, 2)), lambda a: a + a.transpose((0,2,1)), [(5,2,2)], dtype=int)\n_check('Array_add_T', lambda a: function.Array.cast(a).add_T((1, 2)), lambda a: a + a.transpose((0,2,1)), [(5,2,2)], dtype=int)\n\n\nclass broadcasting(TestCase):\n\n def test_singleton_expansion(self):\n a = function.Argument('a', (1,2,3))\n b = function.Argument('b', (3,1,3))\n c = function.Argument('b', (3,1,1))\n (a_, b_, c_), shape, dtype = function._broadcast(a, b, c)\n self.assertEqual(shape, (3,2,3))\n self.assertEqual(a_.shape, (3,2,3))\n self.assertEqual(b_.shape, (3,2,3))\n self.assertEqual(c_.shape, (3,2,3))\n\n def test_prepend_axes(self):\n a = function.Argument('a', (3,2,3))\n b = function.Argument('b', (3,))\n c = function.Argument('b', (2,3))\n (a_, b_, c_), shape, dtype = function._broadcast(a, b, c)\n self.assertEqual(shape, (3,2,3))\n self.assertEqual(a_.shape, (3,2,3))\n self.assertEqual(b_.shape, (3,2,3))\n self.assertEqual(c_.shape, (3,2,3))\n\n def test_both(self):\n a = function.Argument('a', (3,2,3))\n b = function.Argument('b', (3,))\n c = function.Argument('b', (1,1))\n (a_, b_, c_), shape, dtype = function._broadcast(a, b, c)\n self.assertEqual(shape, (3,2,3))\n self.assertEqual(a_.shape, (3,2,3))\n self.assertEqual(b_.shape, (3,2,3))\n self.assertEqual(c_.shape, (3,2,3))\n\n def test_incompatible_shape(self):\n a = function.Argument('a', (3,2,3))\n b = function.Argument('b', (4,))\n with self.assertRaisesRegex(Exception, 'incompatible lengths'):\n function._broadcast(a, b)\n\n def test_runtime_check(self):\n n = function.Argument('n', (), dtype=int)\n m = function.Argument('m', (), dtype=int)\n a = function.Argument('a', (n,), dtype=int)\n b = function.Argument('b', (m,), dtype=int)\n (a_, b_), shape, dtype = function._broadcast(a, b)\n with self.subTest('match'):\n self.assertEqual(shape[0].prepare_eval(npoints=None).eval(n=numpy.array(2), m=numpy.array(2)), 2)\n with self.subTest('mismatch'):\n with self.assertRaises(evaluable.EvaluationError):\n shape[0].prepare_eval(npoints=None).eval(n=numpy.array(2), m=numpy.array(3))\n\n\n@parametrize\nclass sampled(TestCase):\n\n def setUp(self):\n super().setUp()\n self.domain, geom = mesh.unitsquare(4, self.etype)\n basis = self.domain.basis('std', degree=1)\n numpy.random.seed(0)\n self.f = basis.dot(numpy.random.uniform(size=len(basis)))\n sample = self.domain.sample('gauss', 2)\n self.f_sampled = sample.asfunction(sample.eval(self.f))\n\n def test_isarray(self):\n self.assertTrue(function.isarray(self.f_sampled))\n\n def test_values(self):\n diff = self.domain.integrate(self.f - self.f_sampled, ischeme='gauss2')\n self.assertEqual(diff, 0)\n\n def test_pointset(self):\n with self.assertRaises(evaluable.EvaluationError):\n self.domain.integrate(self.f_sampled, ischeme='uniform2')\n\nfor etype in 'square', 'triangle', 'mixed':\n sampled(etype=etype)\n\n\n@parametrize\nclass piecewise(TestCase):\n\n def setUp(self):\n super().setUp()\n self.domain, self.geom = mesh.rectilinear([1])\n x, = self.geom\n if self.partition:\n left, mid, right = function.partition(x, .2, .8)\n self.f = left + function.sin(x) * mid + x**2 * right\n else:\n self.f = function.piecewise(x, [.2,.8], 1, function.sin(x), x**2)\n\n def test_evalf(self):\n f_ = self.domain.sample('uniform', 4).eval(self.f) # x=.125, .375, .625, .875\n assert numpy.equal(f_, [1, numpy.sin(.375), numpy.sin(.625), .875**2]).all()\n\n def test_deriv(self):\n g_ = self.domain.sample('uniform', 4).eval(function.grad(self.f, self.geom)) # x=.125, .375, .625, .875\n assert numpy.equal(g_, [[0], [numpy.cos(.375)], [numpy.cos(.625)], [2*.875]]).all()\n\npiecewise(partition=False)\npiecewise(partition=True)\n\n\nclass elemwise(TestCase):\n\n def setUp(self):\n super().setUp()\n self.domain, geom = mesh.rectilinear([5])\n self.index = self.domain.f_index\n self.data = tuple(map(types.frozenarray, (\n numpy.arange(1, dtype=float).reshape(1,1),\n numpy.arange(2, dtype=float).reshape(1,2),\n numpy.arange(3, dtype=float).reshape(3,1),\n numpy.arange(4, dtype=float).reshape(2,2),\n numpy.arange(6, dtype=float).reshape(3,2),\n )))\n self.func = function.Elemwise(self.data, self.index, float)\n\n def test_evalf(self):\n for i, trans in enumerate(self.domain.transforms):\n with self.subTest(i=i):\n numpy.testing.assert_array_almost_equal(self.func.prepare_eval(ndims=self.domain.ndims).eval(_transforms=(trans,), _points=points.SimplexGaussPoints(self.domain.ndims, 1)), self.data[i][_])\n\n def test_shape(self):\n for i, trans in enumerate(self.domain.transforms):\n with self.subTest(i=i):\n self.assertEqual(self.func.size.prepare_eval(ndims=self.domain.ndims).eval(_transforms=(trans,)), self.data[i].size)\n\n def test_derivative(self):\n self.assertTrue(evaluable.iszero(function.localgradient(self.func, self.domain.ndims).prepare_eval(ndims=self.domain.ndims)))\n\n def test_shape_derivative(self):\n self.assertEqual(function.localgradient(self.func, self.domain.ndims).shape, self.func.shape+(self.domain.ndims,))\n\n\nclass replace_arguments(TestCase):\n\n def test_array(self):\n a = function.Argument('a', (2,))\n b = function.Array.cast([1,2])\n self.assertEqual(function.replace_arguments(a, dict(a=b)).prepare_eval(npoints=None), b.prepare_eval(npoints=None))\n\n def test_argument(self):\n a = function.Argument('a', (2,))\n b = function.Argument('b', (2,))\n self.assertEqual(function.replace_arguments(a, dict(a=b)).prepare_eval(npoints=None), b.prepare_eval(npoints=None))\n\n def test_argument_array(self):\n a = function.Argument('a', (2,))\n b = function.Argument('b', (2,))\n c = function.Array.cast([1,2])\n self.assertEqual(function.replace_arguments(function.replace_arguments(a, dict(a=b)), dict(b=c)).prepare_eval(npoints=None), c.prepare_eval(npoints=None))\n\n def test_swap(self):\n a = function.Argument('a', (2,))\n b = function.Argument('b', (2,))\n self.assertEqual(function.replace_arguments(2*a+3*b, dict(a=b, b=a)).prepare_eval(npoints=None), (2*b+3*a).prepare_eval(npoints=None))\n\n def test_ignore_replaced(self):\n a = function.Argument('a', (2,))\n b = function.Array.cast([1,2])\n c = function.Array.cast([2,3])\n self.assertEqual(function.replace_arguments(function.replace_arguments(a, dict(a=b)), dict(a=c)).prepare_eval(npoints=None), b.prepare_eval(npoints=None))\n\n def test_ignore_recursion(self):\n a = function.Argument('a', (2,))\n self.assertEqual(function.replace_arguments(a, dict(a=2*a)).prepare_eval(npoints=None), (2*a).prepare_eval(npoints=None))\n\n\nclass namespace(TestCase):\n\n def test_set_scalar(self):\n ns = function.Namespace()\n ns.scalar = 1\n\n def test_set_array(self):\n ns = function.Namespace()\n ns.array = function.zeros([2,3])\n\n def test_set_scalar_expression(self):\n ns = function.Namespace()\n ns.scalar = '1'\n\n def test_set_array_expression(self):\n ns = function.Namespace()\n ns.foo = function.zeros([3,3])\n ns.array_ij = 'foo_ij + foo_ji'\n\n def test_set_readonly(self):\n ns = function.Namespace()\n with self.assertRaises(AttributeError):\n ns._foo = None\n\n def test_set_readonly_internal(self):\n ns = function.Namespace()\n with self.assertRaises(AttributeError):\n ns._attributes = None\n\n def test_del_existing(self):\n ns = function.Namespace()\n ns.foo = function.zeros([2,3])\n del ns.foo\n\n def test_del_readonly_internal(self):\n ns = function.Namespace()\n with self.assertRaises(AttributeError):\n del ns._attributes\n\n def test_del_nonexisting(self):\n ns = function.Namespace()\n with self.assertRaises(AttributeError):\n del ns.foo\n\n def test_get_nonexisting(self):\n ns = function.Namespace()\n with self.assertRaises(AttributeError):\n ns.foo\n\n def test_invalid_default_geometry_no_str(self):\n with self.assertRaises(ValueError):\n function.Namespace(default_geometry_name=None)\n\n def test_invalid_default_geometry_no_variable(self):\n with self.assertRaises(ValueError):\n function.Namespace(default_geometry_name='foo_bar')\n\n def assertEqualLowered(self, actual, desired, **lowerargs):\n return self.assertEqual(actual.prepare_eval(**lowerargs), desired.prepare_eval(**lowerargs))\n\n def test_default_geometry_property(self):\n ns = function.Namespace()\n ns.x = 1\n self.assertEqualLowered(ns.default_geometry, ns.x)\n ns = function.Namespace(default_geometry_name='y')\n ns.y = 2\n self.assertEqualLowered(ns.default_geometry, ns.y)\n\n def test_copy(self):\n ns = function.Namespace()\n ns.foo = function.zeros([2,3])\n ns = ns.copy_()\n self.assertTrue(hasattr(ns, 'foo'))\n\n def test_copy_change_geom(self):\n ns1 = function.Namespace()\n domain, ns1.y = mesh.rectilinear([2,2])\n ns1.basis = domain.basis('spline', degree=2)\n ns2 = ns1.copy_(default_geometry_name='y')\n self.assertEqual(ns2.default_geometry_name, 'y')\n self.assertEqualLowered(ns2.eval_ni('basis_n,i'), ns2.basis.grad(ns2.y), ndims=domain.ndims)\n\n def test_copy_preserve_geom(self):\n ns1 = function.Namespace(default_geometry_name='y')\n domain, ns1.y = mesh.rectilinear([2,2])\n ns1.basis = domain.basis('spline', degree=2)\n ns2 = ns1.copy_()\n self.assertEqual(ns2.default_geometry_name, 'y')\n self.assertEqualLowered(ns2.eval_ni('basis_n,i'), ns2.basis.grad(ns2.y), ndims=domain.ndims)\n\n def test_copy_fixed_lengths(self):\n ns = function.Namespace(length_i=2)\n ns = ns.copy_()\n self.assertEqual(ns.eval_ij('δ_ij').shape, (2,2))\n\n def test_copy_fallback_length(self):\n ns = function.Namespace(fallback_length=2)\n ns = ns.copy_()\n self.assertEqual(ns.eval_ij('δ_ij').shape, (2,2))\n\n def test_eval(self):\n ns = function.Namespace()\n ns.foo = function.zeros([3,3])\n ns.eval_ij('foo_ij + foo_ji')\n\n def test_eval_fixed_lengths(self):\n ns = function.Namespace(length_i=2)\n self.assertEqual(ns.eval_ij('δ_ij').shape, (2,2))\n\n def test_eval_fixed_lengths_multiple(self):\n ns = function.Namespace(length_jk=2)\n self.assertEqual(ns.eval_ij('δ_ij').shape, (2,2))\n self.assertEqual(ns.eval_ik('δ_ik').shape, (2,2))\n\n def test_eval_fallback_length(self):\n ns = function.Namespace(fallback_length=2)\n self.assertEqual(ns.eval_ij('δ_ij').shape, (2,2))\n\n def test_matmul_0d(self):\n ns = function.Namespace()\n ns.foo = 2\n self.assertEqualLowered('foo' @ ns, ns.foo)\n\n def test_matmul_1d(self):\n ns = function.Namespace()\n ns.foo = function.zeros([2])\n self.assertEqualLowered('foo_i' @ ns, ns.foo)\n\n def test_matmul_2d(self):\n ns = function.Namespace()\n ns.foo = function.zeros([2, 3])\n with self.assertRaises(ValueError):\n 'foo_ij' @ ns\n\n def test_matmul_nostr(self):\n ns = function.Namespace()\n with self.assertRaises(TypeError):\n 1 @ ns\n\n def test_matmul_fixed_lengths(self):\n ns = function.Namespace(length_i=2)\n self.assertEqual(('1_i δ_ij' @ ns).shape, (2,))\n\n def test_matmul_fallback_length(self):\n ns = function.Namespace(fallback_length=2)\n self.assertEqual(('1_i δ_ij' @ ns).shape, (2,))\n\n def test_replace(self):\n ns = function.Namespace(default_geometry_name='y')\n ns.foo = function.Argument('arg', [2,3])\n ns.bar_ij = 'sin(foo_ij) + cos(2 foo_ij)'\n ns = ns(arg=function.zeros([2,3]))\n self.assertEqualLowered(ns.foo, function.zeros([2,3]))\n self.assertEqual(ns.default_geometry_name, 'y')\n\n def test_pickle(self):\n orig = function.Namespace()\n domain, geom = mesh.unitsquare(2, 'square')\n orig.x = geom\n orig.v = function.stack([1, geom[0], geom[0]**2], 0)\n orig.u = 'v_n ?lhs_n'\n orig.f = 'cosh(x_0)'\n pickled = pickle.loads(pickle.dumps(orig))\n for attr in ('x', 'v', 'u', 'f'):\n self.assertEqualLowered(getattr(pickled, attr), getattr(orig, attr), ndims=domain.ndims)\n self.assertEqual(pickled.arg_shapes['lhs'], orig.arg_shapes['lhs'])\n\n def test_pickle_default_geometry_name(self):\n orig = function.Namespace(default_geometry_name='g')\n pickled = pickle.loads(pickle.dumps(orig))\n self.assertEqual(pickled.default_geometry_name, orig.default_geometry_name)\n\n def test_pickle_fixed_lengths(self):\n orig = function.Namespace(length_i=2)\n pickled = pickle.loads(pickle.dumps(orig))\n self.assertEqual(pickled.eval_ij('δ_ij').shape, (2,2))\n\n def test_pickle_fallback_length(self):\n orig = function.Namespace(fallback_length=2)\n pickled = pickle.loads(pickle.dumps(orig))\n self.assertEqual(pickled.eval_ij('δ_ij').shape, (2,2))\n\n def test_duplicate_fixed_lengths(self):\n with self.assertRaisesRegex(ValueError, '^length of index i specified more than once$'):\n function.Namespace(length_ii=2)\n\n def test_unexpected_keyword_argument(self):\n with self.assertRaisesRegex(TypeError, r\"^__init__\\(\\) got an unexpected keyword argument 'test'$\"):\n function.Namespace(test=2)\n\n def test_d_geom(self):\n ns = function.Namespace()\n topo, ns.x = mesh.rectilinear([1])\n self.assertEqualLowered(ns.eval_ij('d(x_i, x_j)'), function.grad(ns.x, ns.x), ndims=topo.ndims)\n\n def test_d_arg(self):\n ns = function.Namespace()\n ns.a = '?a'\n self.assertEqual(ns.eval_('d(2 ?a + 1, ?a)').prepare_eval().simplified, function.asarray(2).prepare_eval().simplified)\n\n def test_n(self):\n ns = function.Namespace()\n topo, ns.x = mesh.rectilinear([1])\n self.assertEqualLowered(ns.eval_i('n(x_i)'), function.normal(ns.x), ndims=topo.ndims)\n\n def test_functions(self):\n def sqr(a):\n return a**2\n def mul(*args):\n if len(args) == 2:\n return args[0][(...,)+(None,)*args[1].ndim] * args[1][(None,)*args[0].ndim]\n else:\n return mul(mul(args[0], args[1]), *args[2:])\n ns = function.Namespace(functions=dict(sqr=sqr, mul=mul))\n ns.a = numpy.array([1, 2, 3])\n ns.b = numpy.array([4, 5])\n ns.A = numpy.array([[6, 7, 8], [9, 10, 11]])\n l = lambda f: f.prepare_eval(npoints=None).simplified\n self.assertEqual(l(ns.eval_i('sqr(a_i)')), l(sqr(ns.a)))\n self.assertEqual(l(ns.eval_ij('mul(a_i, b_j)')), l(ns.eval_ij('a_i b_j')))\n self.assertEqual(l(ns.eval_('mul(b_i, A_ij, a_j)')), l(ns.eval_('b_i A_ij a_j')))\n\n def test_builtin_functions(self):\n ns = function.Namespace()\n domain, ns.x = mesh.rectilinear([1]*2)\n ns.a = numpy.array([1, 2, 3])\n ns.A = numpy.array([[6, 7, 8], [9, 10, 11]])\n l = lambda f: f.prepare_eval(npoints=4, ndims=2).simplified\n self.assertEqual(l(ns.eval_('norm2(a)')), l(function.norm2(ns.a)))\n self.assertEqual(l(ns.eval_i('sum:j(A_ij)')), l(function.sum(ns.A, 1)))\n self.assertEqual(l(ns.eval_('J:x')), l(function.jacobian(ns.x)))\n\nclass eval_ast(TestCase):\n\n def setUp(self):\n super().setUp()\n domain, x = mesh.rectilinear([2,2])\n self.ns = function.Namespace()\n self.ns.x = x\n self.ns.altgeom = function.concatenate([self.ns.x, [0]], 0)\n self.ns.basis = domain.basis('spline', degree=2)\n self.ns.a = 2\n self.ns.a2 = numpy.array([1,2])\n self.ns.a3 = numpy.array([1,2,3])\n self.ns.a22 = numpy.array([[1,2],[3,4]])\n self.ns.a32 = numpy.array([[1,2],[3,4],[5,6]])\n self.x = function.Argument('x',())\n\n def assertEqualLowered(self, s, f):\n self.assertEqual((s @ self.ns).prepare_eval(ndims=2).simplified, f.prepare_eval(ndims=2).simplified)\n\n def test_group(self): self.assertEqualLowered('(a)', self.ns.a)\n def test_arg(self): self.assertEqualLowered('a2_i ?x_i', function.dot(self.ns.a2, function.Argument('x', [2]), axes=[0]))\n def test_substitute(self): self.assertEqualLowered('(?x_i^2)(x_i=a2_i)', self.ns.a2**2)\n def test_multisubstitute(self): self.assertEqualLowered('(a2_i + ?x_i + ?y_i)(x_i=?y_i, y_i=?x_i)', self.ns.a2 + function.Argument('y', [2]) + function.Argument('x', [2]))\n def test_call(self): self.assertEqualLowered('sin(a)', function.sin(self.ns.a))\n def test_call2(self): self.assertEqual(self.ns.eval_ij('arctan2(a2_i, a3_j)').prepare_eval().simplified, function.arctan2(self.ns.a2[:,None], self.ns.a3[None,:]).prepare_eval().simplified)\n def test_eye(self): self.assertEqualLowered('δ_ij a2_i', function.dot(function.eye(2), self.ns.a2, axes=[0]))\n def test_normal(self): self.assertEqualLowered('n_i', self.ns.x.normal())\n def test_getitem(self): self.assertEqualLowered('a2_0', self.ns.a2[0])\n def test_trace(self): self.assertEqualLowered('a22_ii', function.trace(self.ns.a22, 0, 1))\n def test_sum(self): self.assertEqualLowered('a2_i a2_i', function.sum(self.ns.a2 * self.ns.a2, axis=0))\n def test_concatenate(self): self.assertEqualLowered('_i', function.concatenate([self.ns.a[None],self.ns.a[None]], axis=0))\n def test_grad(self): self.assertEqualLowered('basis_n,0', self.ns.basis.grad(self.ns.x)[:,0])\n def test_surfgrad(self): self.assertEqualLowered('surfgrad(basis_0, altgeom_i)', function.grad(self.ns.basis[0], self.ns.altgeom, len(self.ns.altgeom)-1))\n def test_derivative(self): self.assertEqualLowered('d(exp(?x), ?x)', function.derivative(function.exp(self.x), self.x))\n def test_append_axis(self): self.assertEqualLowered('a a2_i', self.ns.a[None]*self.ns.a2)\n def test_transpose(self): self.assertEqualLowered('a22_ij a22_ji', function.dot(self.ns.a22, self.ns.a22.T, axes=[0,1]))\n def test_jump(self): self.assertEqualLowered('[a]', function.jump(self.ns.a))\n def test_mean(self): self.assertEqualLowered('{a}', function.mean(self.ns.a))\n def test_neg(self): self.assertEqualLowered('-a', -self.ns.a)\n def test_add(self): self.assertEqualLowered('a + ?x', self.ns.a + self.x)\n def test_sub(self): self.assertEqualLowered('a - ?x', self.ns.a - self.x)\n def test_mul(self): self.assertEqualLowered('a ?x', self.ns.a * self.x)\n def test_truediv(self): self.assertEqualLowered('a / ?x', self.ns.a / self.x)\n def test_pow(self): self.assertEqualLowered('a^2', self.ns.a**2)\n\n def test_unknown_opcode(self):\n with self.assertRaises(ValueError):\n function._eval_ast(('invalid-opcode',), {})\n\n def test_call_invalid_shape(self):\n with self.assertRaisesRegex(ValueError, '^expected an array with shape'):\n function._eval_ast(('call', (None, 'f'), (None, 0), (None, 0), (None, function.zeros((2,), float)), (None, function.zeros((3,), float))),\n dict(f=lambda a, b: a[None,:] * b[:,None])) # result is transposed\n\n def test_surfgrad_deprecated(self):\n with self.assertWarns(warnings.NutilsDeprecationWarning):\n self.assertEqualLowered('basis_n;altgeom_0', function.grad(self.ns.basis, self.ns.altgeom, len(self.ns.altgeom)-1)[:,0])\n\n def test_derivative_deprecated(self):\n with self.assertWarns(warnings.NutilsDeprecationWarning):\n self.assertEqualLowered('exp(?x)_,?x', function.derivative(function.exp(self.x), self.x))\n\nclass jacobian(TestCase):\n\n def setUp(self):\n super().setUp()\n self.domain, self.geom = mesh.unitsquare(1, 'square')\n self.basis = self.domain.basis('std', degree=1)\n arg = function.Argument('dofs', [4])\n self.v = self.basis.dot(arg)\n self.X = (self.geom[numpy.newaxis,:] * [[0,1],[-self.v,0]]).sum(-1) # X_i = _i\n self.J = function.J(self.X)\n self.dJ = function.derivative(self.J, arg)\n\n def test_shape(self):\n self.assertEqual(self.J.shape, ())\n self.assertEqual(self.dJ.shape, (4,))\n\n def test_value(self):\n values = self.domain.sample('uniform', 2).eval(self.J, dofs=[2]*4)\n numpy.testing.assert_almost_equal(values, [2]*4)\n values1, values2 = self.domain.sample('uniform', 2).eval([self.J,\n self.v + self.v.grad(self.geom)[0] * self.geom[0]], dofs=[1,2,3,10])\n numpy.testing.assert_almost_equal(values1, values2)\n\n def test_derivative(self):\n values1, values2 = self.domain.sample('uniform', 2).eval([self.dJ,\n self.basis + self.basis.grad(self.geom)[:,0] * self.geom[0]], dofs=[1,2,3,10])\n numpy.testing.assert_almost_equal(values1, values2)\n\n def test_zeroderivative(self):\n otherarg = function.Argument('otherdofs', (10,))\n values = self.domain.sample('uniform', 2).eval(function.derivative(self.dJ, otherarg))\n self.assertEqual(values.shape[1:], self.dJ.shape + otherarg.shape)\n self.assertAllEqual(values, 0)\n\n@parametrize\nclass derivative(TestCase):\n\n def assertEvalAlmostEqual(self, topo, factual, fdesired):\n actual, desired = topo.sample('uniform', 2).eval([function.asarray(factual), function.asarray(fdesired)])\n self.assertAllAlmostEqual(actual, desired)\n\n def test_grad_0d(self):\n domain, (x,) = mesh.rectilinear([1])\n x = 2*x-0.5\n self.assertEvalAlmostEqual(domain, self.grad(x**2, x), 2*x)\n\n def test_grad_1d(self):\n domain, x = mesh.rectilinear([1]*2)\n x = 2*x-0.5\n self.assertEvalAlmostEqual(domain, self.grad([x[0]**2*x[1], x[1]**2], x), [[2*x[0]*x[1], x[0]**2], [0, 2*x[1]]])\n\n def test_grad_2d(self):\n domain, x = mesh.rectilinear([1]*4)\n x = 2*x-0.5\n x = function.unravel(x, 0, (2, 2))\n self.assertEvalAlmostEqual(domain, self.grad(x, x), numpy.eye(4, 4).reshape(2, 2, 2, 2))\n\n def test_grad_3d(self):\n domain, x = mesh.rectilinear([1]*4)\n x = 2*x-0.5\n x = function.unravel(function.unravel(x, 0, (2, 2)), 0, (2, 1))\n self.assertEvalAlmostEqual(domain, self.grad(x, x), numpy.eye(4, 4).reshape(2, 1, 2, 2, 1, 2))\n\n def test_div(self):\n domain, x = mesh.rectilinear([1]*2)\n x = 2*x-0.5\n self.assertEvalAlmostEqual(domain, self.div([x[0]**2+x[1], x[1]**2-x[0]], x), 2*x[0]+2*x[1])\n\n def test_laplace(self):\n domain, x = mesh.rectilinear([1]*2)\n x = 2*x-0.5\n self.assertEvalAlmostEqual(domain, self.laplace(x[0]**2*x[1]-x[1]**2, x), 2*x[1]-2)\n\n def test_symgrad(self):\n domain, x = mesh.rectilinear([1]*2)\n x = 2*x-0.5\n self.assertEvalAlmostEqual(domain, self.symgrad([x[0]**2*x[1], x[1]**2], x), [[2*x[0]*x[1], 0.5*x[0]**2], [0.5*x[0]**2, 2*x[1]]])\n\n def test_normal_0d(self):\n domain, (x,) = mesh.rectilinear([1])\n x = 2*x-0.5\n self.assertEvalAlmostEqual(domain.boundary['right'], self.normal(x), 1)\n self.assertEvalAlmostEqual(domain.boundary['left'], self.normal(x), -1)\n\n def test_normal_1d(self):\n domain, x = mesh.rectilinear([1]*2)\n x = 2*x-0.5\n for bnd, n in ('right', [1, 0]), ('left', [-1, 0]), ('top', [0, 1]), ('bottom', [0, -1]):\n self.assertEvalAlmostEqual(domain.boundary[bnd], self.normal(x), n)\n\n def test_normal_2d(self):\n domain, x = mesh.rectilinear([1]*2)\n x = 2*x-0.5\n x = function.unravel(x, 0, [2, 1])\n for bnd, n in ('right', [1, 0]), ('left', [-1, 0]), ('top', [0, 1]), ('bottom', [0, -1]):\n self.assertEvalAlmostEqual(domain.boundary[bnd], self.normal(x), numpy.array(n)[:,_])\n\n def test_normal_3d(self):\n domain, x = mesh.rectilinear([1]*2)\n x = 2*x-0.5\n x = function.unravel(function.unravel(x, 0, [2, 1]), 0, [1, 2])\n for bnd, n in ('right', [1, 0]), ('left', [-1, 0]), ('top', [0, 1]), ('bottom', [0, -1]):\n self.assertEvalAlmostEqual(domain.boundary[bnd], self.normal(x), numpy.array(n)[_,:,_])\n\n def test_dotnorm(self):\n domain, x = mesh.rectilinear([1]*2)\n x = 2*x-0.5\n for bnd, desired in ('right', 1), ('left', -1), ('top', 0), ('bottom', 0):\n self.assertEvalAlmostEqual(domain.boundary[bnd], self.dotnorm([1, 0], x), desired)\n\n def test_tangent(self):\n domain, x = mesh.rectilinear([1]*2)\n x = 2*x-0.5\n for bnd, desired in ('right', [0, 1]), ('left', [0, 1]), ('top', [-1, 0]), ('bottom', [-1, 0]):\n self.assertEvalAlmostEqual(domain.boundary[bnd], self.tangent(x, [-1, 1]), desired)\n\n def test_ngrad(self):\n domain, x = mesh.rectilinear([1]*2)\n x = 2*x-0.5\n for bnd, desired in ('right', [2*x[0]*x[1], 0]), ('left', [-2*x[0]*x[1], 0]), ('top', [x[0]**2, 2*x[1]]), ('bottom', [-x[0]**2, -2*x[1]]):\n self.assertEvalAlmostEqual(domain.boundary[bnd], self.ngrad([x[0]**2*x[1], x[1]**2], x), desired)\n\n def test_nsymgrad(self):\n domain, x = mesh.rectilinear([1]*2)\n x = 2*x-0.5\n for bnd, desired in ('right', [2*x[0]*x[1], 0.5*x[0]**2]), ('left', [-2*x[0]*x[1], -0.5*x[0]**2]), ('top', [0.5*x[0]**2, 2*x[1]]), ('bottom', [-0.5*x[0]**2, -2*x[1]]):\n self.assertEvalAlmostEqual(domain.boundary[bnd], self.nsymgrad([x[0]**2*x[1], x[1]**2], x), desired)\n\nderivative('function',\n normal=function.normal,\n tangent=function.tangent,\n dotnorm=function.dotnorm,\n grad=function.grad,\n div=function.div,\n laplace=function.laplace,\n symgrad=function.symgrad,\n ngrad=function.ngrad,\n nsymgrad=function.nsymgrad)\nderivative('method',\n normal=lambda geom: function.Array.cast(geom).normal(),\n tangent=lambda geom, vec: function.Array.cast(geom).tangent(vec),\n dotnorm=lambda vec, geom: function.Array.cast(vec).dotnorm(geom),\n grad=lambda arg, geom: function.Array.cast(arg).grad(geom),\n div=lambda arg, geom: function.Array.cast(arg).div(geom),\n laplace=lambda arg, geom: function.Array.cast(arg).laplace(geom),\n symgrad=lambda arg, geom: function.Array.cast(arg).symgrad(geom),\n ngrad=lambda arg, geom: function.Array.cast(arg).ngrad(geom),\n nsymgrad=lambda arg, geom: function.Array.cast(arg).nsymgrad(geom))\n\nclass deprecations(TestCase):\n\n def test_simplified(self):\n with self.assertWarns(warnings.NutilsDeprecationWarning):\n function.simplified(function.Argument('a', ()))\n\n def test_iszero(self):\n with self.assertWarns(warnings.NutilsDeprecationWarning):\n function.iszero(function.Argument('a', ()))\n\nclass CommonBasis:\n\n @staticmethod\n def mk_index_coords(coorddim, transforms):\n index = function.transforms_index(transforms)\n coords = function.transforms_coords(transforms, coorddim)\n return index, coords\n\n def setUp(self):\n super().setUp()\n self.checknelems = len(self.checkcoeffs)\n self.checksupp = [[] for i in range(self.checkndofs)]\n for ielem, dofs in enumerate(self.checkdofs):\n for dof in dofs:\n self.checksupp[dof].append(ielem)\n assert len(self.checkcoeffs) == len(self.checkdofs)\n assert all(len(c) == len(d) for c, d in zip(self.checkcoeffs, self.checkdofs))\n\n def test_shape(self):\n self.assertEqual(self.basis.shape, (self.checkndofs,))\n\n def test_get_coeffshape(self):\n for ielem in range(self.checknelems):\n self.assertAllEqual(self.basis.get_coeffshape(ielem), numpy.shape(self.checkcoeffs[ielem])[1:])\n\n def test_get_coefficients_pos(self):\n for ielem in range(self.checknelems):\n self.assertEqual(self.basis.get_coefficients(ielem).tolist(), self.checkcoeffs[ielem])\n\n def test_get_coefficients_neg(self):\n for ielem in range(-self.checknelems, 0):\n self.assertEqual(self.basis.get_coefficients(ielem).tolist(), self.checkcoeffs[ielem])\n\n def test_get_coefficients_outofbounds(self):\n with self.assertRaises(IndexError):\n self.basis.get_coefficients(-self.checknelems-1)\n with self.assertRaises(IndexError):\n self.basis.get_coefficients(self.checknelems)\n\n def test_get_dofs_scalar_pos(self):\n for ielem in range(self.checknelems):\n self.assertEqual(self.basis.get_dofs(ielem).tolist(), self.checkdofs[ielem])\n\n def test_get_dofs_scalar_neg(self):\n for ielem in range(-self.checknelems, 0):\n self.assertEqual(self.basis.get_dofs(ielem).tolist(), self.checkdofs[ielem])\n\n def test_get_dofs_scalar_outofbounds(self):\n with self.assertRaises(IndexError):\n self.basis.get_dofs(-self.checknelems-1)\n with self.assertRaises(IndexError):\n self.basis.get_dofs(self.checknelems)\n\n def test_get_ndofs(self):\n for ielem in range(self.checknelems):\n self.assertEqual(self.basis.get_ndofs(ielem), len(self.checkdofs[ielem]))\n\n def test_dofs_array(self):\n for mask in itertools.product(*[[False, True]]*self.checknelems):\n mask = numpy.array(mask, dtype=bool)\n indices, = numpy.where(mask)\n for value in mask, indices:\n with self.subTest(tuple(value)):\n self.assertEqual(self.basis.get_dofs(value).tolist(), list(sorted(set(itertools.chain.from_iterable(self.checkdofs[i] for i in indices)))))\n\n def test_dofs_intarray_outofbounds(self):\n for i in [-1, self.checknelems]:\n with self.assertRaises(IndexError):\n self.basis.get_dofs(numpy.array([i], dtype=int))\n\n def test_dofs_intarray_invalidndim(self):\n with self.assertRaises(IndexError):\n self.basis.get_dofs(numpy.array([[0]], dtype=int))\n\n def test_dofs_boolarray_invalidshape(self):\n with self.assertRaises(IndexError):\n self.basis.get_dofs(numpy.array([True]*(self.checknelems+1), dtype=bool))\n with self.assertRaises(IndexError):\n self.basis.get_dofs(numpy.array([[True]*self.checknelems], dtype=bool))\n\n def test_get_support_scalar_pos(self):\n for dof in range(self.checkndofs):\n self.assertEqual(self.basis.get_support(dof).tolist(), self.checksupp[dof])\n\n def test_get_support_scalar_neg(self):\n for dof in range(-self.checkndofs, 0):\n self.assertEqual(self.basis.get_support(dof).tolist(), self.checksupp[dof])\n\n def test_get_support_scalar_outofbounds(self):\n with self.assertRaises(IndexError):\n self.basis.get_support(-self.checkndofs-1)\n with self.assertRaises(IndexError):\n self.basis.get_support(self.checkndofs)\n\n def test_get_support_array(self):\n for mask in itertools.product(*[[False, True]]*self.checkndofs):\n mask = numpy.array(mask, dtype=bool)\n indices, = numpy.where(mask)\n for value in mask, indices:\n with self.subTest(tuple(value)):\n self.assertEqual(self.basis.get_support(value).tolist(), list(sorted(set(itertools.chain.from_iterable(self.checksupp[i] for i in indices)))))\n\n def test_get_support_intarray_outofbounds(self):\n for i in [-1, self.checkndofs]:\n with self.assertRaises(IndexError):\n self.basis.get_support(numpy.array([i], dtype=int))\n\n def test_get_support_intarray_invalidndim(self):\n with self.assertRaises(IndexError):\n self.basis.get_support(numpy.array([[0]], dtype=int))\n\n def test_get_support_boolarray(self):\n for mask in itertools.product(*[[False, True]]*self.checkndofs):\n mask = numpy.array(mask, dtype=bool)\n indices, = numpy.where(mask)\n with self.subTest(tuple(indices)):\n self.assertEqual(self.basis.get_support(mask).tolist(), list(sorted(set(itertools.chain.from_iterable(self.checksupp[i] for i in indices)))))\n\n def test_get_support_boolarray_invalidshape(self):\n with self.assertRaises(IndexError):\n self.basis.get_support(numpy.array([True]*(self.checkndofs+1), dtype=bool))\n with self.assertRaises(IndexError):\n self.basis.get_support(numpy.array([[True]*self.checkndofs], dtype=bool))\n\n def test_getitem_array(self):\n for mask in itertools.product(*[[False, True]]*self.checkndofs):\n mask = numpy.array(mask, dtype=bool)\n indices, = numpy.where(mask)\n for value in mask, indices:\n with self.subTest(tuple(value)):\n maskedbasis = self.basis[value]\n self.assertIsInstance(maskedbasis, function.Basis)\n for ielem in range(self.checknelems):\n m = numpy.asarray(numeric.sorted_contains(indices, self.checkdofs[ielem]))\n self.assertEqual(maskedbasis.get_dofs(ielem).tolist(), numeric.sorted_index(indices, numpy.compress(m, self.checkdofs[ielem], axis=0)).tolist())\n self.assertEqual(maskedbasis.get_coefficients(ielem).tolist(), numpy.compress(m, self.checkcoeffs[ielem], axis=0).tolist())\n\n def checkeval(self, ielem, points):\n result = numpy.zeros((points.npoints, self.checkndofs,), dtype=float)\n numpy.add.at(result, (slice(None),numpy.array(self.checkdofs[ielem], dtype=int)), numeric.poly_eval(numpy.array(self.checkcoeffs[ielem], dtype=float), points.coords))\n return result.tolist()\n\n def test_lower(self):\n ref = element.PointReference() if self.basis.coords.shape[0] == 0 else element.LineReference()**self.basis.coords.shape[0]\n points = ref.getpoints('bezier', 4)\n lowered = self.basis.prepare_eval(ndims=points.ndims)\n with _builtin_warnings.catch_warnings():\n _builtin_warnings.simplefilter('ignore', category=evaluable.ExpensiveEvaluationWarning)\n for ielem in range(self.checknelems):\n value = lowered.eval(_transforms=(self.checktransforms[ielem],), _points=points)\n if value.shape[0] == 1:\n value = numpy.tile(value, (points.npoints, 1))\n self.assertEqual(value.tolist(), self.checkeval(ielem, points))\n\n def test_f_ndofs(self):\n for ielem in range(self.checknelems):\n a = self.basis.get_ndofs(ielem)\n b = int(self.basis.f_ndofs(ielem).eval()[()])\n self.assertEqual(a, b)\n\n def test_f_dofs(self):\n for ielem in range(self.checknelems):\n a = self.basis.get_dofs(ielem)\n b = self.basis.f_dofs(ielem).eval()\n self.assertAllEqual(a, b)\n\n def test_f_coefficients(self):\n for ielem in range(self.checknelems):\n a = self.basis.get_coefficients(ielem)\n b = self.basis.f_coefficients(ielem).eval()\n self.assertAllEqual(a, b)\n\nclass PlainBasis(CommonBasis, TestCase):\n\n def setUp(self):\n self.checktransforms = transformseq.PlainTransforms([(transform.Identifier(0,k),) for k in 'abcd'], 0)\n index, coords = self.mk_index_coords(0, self.checktransforms)\n self.checkcoeffs = [[1],[2,3],[4,5],[6]]\n self.checkdofs = [[0],[2,3],[1,3],[2]]\n self.basis = function.PlainBasis(self.checkcoeffs, self.checkdofs, 4, index, coords)\n self.checkndofs = 4\n super().setUp()\n\nclass DiscontBasis(CommonBasis, TestCase):\n\n def setUp(self):\n self.checktransforms = transformseq.PlainTransforms([(transform.Identifier(0,k),) for k in 'abcd'], 0)\n index, coords = self.mk_index_coords(0, self.checktransforms)\n self.checkcoeffs = [[1],[2,3],[4,5],[6]]\n self.basis = function.DiscontBasis(self.checkcoeffs, index, coords)\n self.checkdofs = [[0],[1,2],[3,4],[5]]\n self.checkndofs = 6\n super().setUp()\n\nclass MaskedBasis(CommonBasis, TestCase):\n\n def setUp(self):\n self.checktransforms = transformseq.PlainTransforms([(transform.Identifier(0,k),) for k in 'abcd'], 0)\n index, coords = self.mk_index_coords(0, self.checktransforms)\n parent = function.PlainBasis([[1],[2,3],[4,5],[6]], [[0],[2,3],[1,3],[2]], 4, index, coords)\n self.basis = function.MaskedBasis(parent, [0,2])\n self.checkcoeffs = [[1],[2],[],[6]]\n self.checkdofs = [[0],[1],[],[1]]\n self.checkndofs = 2\n super().setUp()\n\nclass PrunedBasis(CommonBasis, TestCase):\n\n def setUp(self):\n parent_transforms = transformseq.PlainTransforms([(transform.Identifier(0,k),) for k in 'abcd'], 0)\n parent_index, parent_coords = self.mk_index_coords(0, parent_transforms)\n indices = types.frozenarray([0,2])\n self.checktransforms = parent_transforms[indices]\n index, coords = self.mk_index_coords(0, self.checktransforms)\n parent = function.PlainBasis([[1],[2,3],[4,5],[6]], [[0],[2,3],[1,3],[2]], 4, parent_index, parent_coords)\n self.basis = function.PrunedBasis(parent, indices, index, coords)\n self.checkcoeffs = [[1],[4,5]]\n self.checkdofs = [[0],[1,2]]\n self.checkndofs = 3\n super().setUp()\n\nclass StructuredBasis1D(CommonBasis, TestCase):\n\n def setUp(self):\n self.checktransforms = transformseq.StructuredTransforms(transform.Identifier(1, 'test'), [transformseq.DimAxis(0,4,False)], 0)\n index, coords = self.mk_index_coords(1, self.checktransforms)\n self.basis = function.StructuredBasis([[[[1],[2]],[[3],[4]],[[5],[6]],[[7],[8]]]], [[0,1,2,3]], [[2,3,4,5]], [5], [4], index, coords)\n self.checkcoeffs = [[[1],[2]],[[3],[4]],[[5],[6]],[[7],[8]]]\n self.checkdofs = [[0,1],[1,2],[2,3],[3,4]]\n self.checkndofs = 5\n super().setUp()\n\nclass StructuredBasis1DPeriodic(CommonBasis, TestCase):\n\n def setUp(self):\n self.checktransforms = transformseq.StructuredTransforms(transform.Identifier(1, 'test'), [transformseq.DimAxis(0,4,True)], 0)\n index, coords = self.mk_index_coords(1, self.checktransforms)\n self.basis = function.StructuredBasis([[[[1],[2]],[[3],[4]],[[5],[6]],[[7],[8]]]], [[0,1,2,3]], [[2,3,4,5]], [4], [4], index, coords)\n self.checkcoeffs = [[[1],[2]],[[3],[4]],[[5],[6]],[[7],[8]]]\n self.checkdofs = [[0,1],[1,2],[2,3],[3,0]]\n self.checkndofs = 4\n super().setUp()\n\nclass StructuredBasis2D(CommonBasis, TestCase):\n\n def setUp(self):\n self.checktransforms = transformseq.StructuredTransforms(transform.Identifier(2, 'test'), [transformseq.DimAxis(0,2,False),transformseq.DimAxis(0,2,False)], 0)\n index, coords = self.mk_index_coords(2, self.checktransforms)\n self.basis = function.StructuredBasis([[[[1],[2]],[[3],[4]]],[[[5],[6]],[[7],[8]]]], [[0,1],[0,1]], [[2,3],[2,3]], [3,3], [2,2], index, coords)\n self.checkcoeffs = [[[[5]],[[6]],[[10]],[[12]]],[[[7]],[[8]],[[14]],[[16]]],[[[15]],[[18]],[[20]],[[24]]],[[[21]],[[24]],[[28]],[[32]]]]\n self.checkdofs = [[0,1,3,4],[1,2,4,5],[3,4,6,7],[4,5,7,8]]\n self.checkndofs = 9\n super().setUp()\n","sub_path":"tests/test_function.py","file_name":"test_function.py","file_ext":"py","file_size_in_byte":50256,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"29843198","text":"#!/usr/bin/python\n# -*- coding: utf-8 -*-\nfrom tkinter import *\n\n# Used to create a blank window.\n\nroot = Tk()\n\n# Changing the title.\n\nroot.title(\"test's Lab\")\n\n# Name text definition.\n\nname = 'test test test '\n\n# Major text definition.\n\nmajor = 'Not a Computer Science Major'\n\nnameLabel = Label(root, text=name) # Setting the NAME label up in root.\nmajorLabel = Label(root, text=major) # Doing the same with MAJOR.\nnameLabel.grid(row=0, column=0, padx=(15, 15), pady=(15, 0)) # Grid layout and spacing definitions.\nmajorLabel.grid(row=1, column=0, padx=(15, 15), pady=(5, 15))\nroot.mainloop() # Keeping the GUI open forever! At least until we close it.\n\n","sub_path":".idea/tkinter_basic.py","file_name":"tkinter_basic.py","file_ext":"py","file_size_in_byte":659,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"548673013","text":"from backtest.simulator import Simulator\nfrom backtest.env import Env\nfrom strategy.simpleSMA import SimpleSMA\nfrom order.order import Order\nfrom tqdm import tqdm\nimport pandas as pd\n\n\n\n'''\n Simple SMA Sample\n backtest.simulator을 상속\n'''\nclass SimulatorSimpleSma(Simulator):\n\n def __init__(self):\n super(__class__, self).__init__()\n\n '''\n data : pandas Dataframe\n '''\n def run(self):\n\n e = Env()\n with tqdm(total=self.futDf.shape[0]) as pbar:\n for index, fut in self.futDf.iterrows():\n\n # save index\n e.getEnvValue('index').append(index)\n\n # get other data\n itt = self.ittDf[self.ittDf.index == index.strftime('%Y-%m-%d %H:%M:%S')]\n prog = self.progDf[self.progDf.index == index.strftime('%Y-%m-%d %H:%M:%S')]\n\n # time check\n self.checkTradingTime(index, e)\n\n # strategy\n tradingSignal = SimpleSMA.strategyFut4(fut, itt, prog, e)\n\n # order\n Order.simpleOrder(tradingSignal, e, fut)\n\n # benefit\n self.makeBenefitResult(e)\n\n # stop Loss\n #self.checkStopLoss(e)\n\n # update\n pbar.update(1)\n\n #print(e.getEnvValue('futMarkSignal'), e.getEnvValue('optMarkSignal'), e.getEnvValue('progSignal'))\n\n\n # show chart\n #self.showPriceChart(e, self.futDf)\n #self.showListChart(e, ['macd','signal','hist'])\n self.showSignalChart(e)\n self.showResultChart(e)\n\n\n '''\n 시뮬레이션할 데이터를 준비한다.\n 선물, 투자자매매동향, 프로그램매매\n '''\n def initData(self, date):\n\n # Future\n futDf = super().getFutData(date, date)\n self.futDf = futDf[['TIMESTAMP', 'PRICE_CUR', 'BASIS', 'BEST_ASK', 'BEST_BID', 'BEST_ASK_VOL', 'BEST_BID_VOL', 'ACCUM_ASK', 'ACCUM_BID', 'ASK_BID_TYPE']]\n\n # InvTradingTrend\n ittKospiDf = super().getInvTradingTrendData(date, date, 'kospi')\n ittFutDf = super().getInvTradingTrendData(date, date, 'fut')\n ittCallDf = super().getInvTradingTrendData(date, date, 'call')\n ittPutDf = super().getInvTradingTrendData(date, date, 'put')\n\n ittKospiDf2 = pd.DataFrame(ittKospiDf['TIMESTAMP'])\n ittKospiDf2['KOSPI_GEIN_AMOUNT'] = ittKospiDf['GEIN_BUY_AMOUNT'] - ittKospiDf['GEIN_SELL_AMOUNT']\n ittKospiDf2['KOSPI_FORE_AMOUNT'] = ittKospiDf['FOREIGNER_BUY_AMOUNT'] - ittKospiDf['FOREIGNER_SELL_AMOUNT']\n ittKospiDf2['KOSPI_AGEN_AMOUNT'] = ittKospiDf['AGENCY_BUY_AMOUNT'] - ittKospiDf['AGENCY_SELL_AMOUNT']\n\n ittFutDf2 = pd.DataFrame(ittFutDf['TIMESTAMP'])\n ittFutDf2['FUT_GEIN_AMOUNT'] = ittFutDf['GEIN_BUY_AMOUNT'] - ittFutDf['GEIN_SELL_AMOUNT']\n ittFutDf2['FUT_FORE_AMOUNT'] = ittFutDf['FOREIGNER_BUY_AMOUNT'] - ittFutDf['FOREIGNER_SELL_AMOUNT']\n ittFutDf2['FUT_AGEN_AMOUNT'] = ittFutDf['AGENCY_BUY_AMOUNT'] - ittFutDf['AGENCY_SELL_AMOUNT']\n\n ittCallDf2 = pd.DataFrame(ittCallDf['TIMESTAMP'])\n ittCallDf2['CALL_GEIN_AMOUNT'] = ittCallDf['GEIN_BUY_AMOUNT'] - ittCallDf['GEIN_SELL_AMOUNT']\n ittCallDf2['CALL_FORE_AMOUNT'] = ittCallDf['FOREIGNER_BUY_AMOUNT'] - ittCallDf['FOREIGNER_SELL_AMOUNT']\n ittCallDf2['CALL_AGEN_AMOUNT'] = ittCallDf['AGENCY_BUY_AMOUNT'] - ittCallDf['AGENCY_SELL_AMOUNT']\n\n ittPutDf2 = pd.DataFrame(ittPutDf['TIMESTAMP'])\n ittPutDf2['PUT_GEIN_AMOUNT'] = ittPutDf['GEIN_BUY_AMOUNT'] - ittPutDf['GEIN_SELL_AMOUNT']\n ittPutDf2['PUT_FORE_AMOUNT'] = ittPutDf['FOREIGNER_BUY_AMOUNT'] - ittPutDf['FOREIGNER_SELL_AMOUNT']\n ittPutDf2['PUT_AGEN_AMOUNT'] = ittPutDf['AGENCY_BUY_AMOUNT'] - ittPutDf['AGENCY_SELL_AMOUNT']\n\n ittKospiDf3 = ittKospiDf2.resample('1S').mean()\n ittKospiDf3 = ittKospiDf3['2017-09-25 09:00:00':]\n ittKospiDf3 = ittKospiDf3.dropna()\n\n ittFutDf3 = ittFutDf2.resample('1S').mean()\n ittFutDf3 = ittFutDf3['2017-09-25 09:00:00':]\n ittFutDf3 = ittFutDf3.dropna()\n\n ittCallDf3 = ittCallDf2.resample('1S').mean()\n ittCallDf3 = ittCallDf3['2017-09-25 09:00:00':]\n ittCallDf3 = ittCallDf3.dropna()\n\n ittPutDf3 = ittPutDf2.resample('1S').mean()\n ittPutDf3 = ittPutDf3['2017-09-25 09:00:00':]\n ittPutDf3 = ittPutDf3.dropna()\n\n ittDf = pd.concat([ittKospiDf3, ittFutDf3, ittCallDf3, ittPutDf3], axis=1)\n ittDf = ittDf.resample('1S').mean()\n self.ittDf = ittDf.dropna(how='all')\n\n\n # KospiProgram\n progDf = sim_obj.getKospiProgramTradeData(date, date)\n\n progDf = progDf.resample('1S').mean()\n progDf = progDf['2017-09-25 09:00:00':].dropna()\n self.progDf = progDf.dropna()\n\n\n\n\n\nif __name__ == \"__main__\":\n\n date = '20171117'\n\n sim_obj = SimulatorSimpleSma()\n #sim_obj.showFutCandleChart('20171010', '20171020', '60Min')\n\n sim_obj.initData(date)\n sim_obj.run()\n","sub_path":"backtest/simulator_daesony.py","file_name":"simulator_daesony.py","file_ext":"py","file_size_in_byte":5012,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"425867132","text":"\nfrom keras.applications.mobilenet import MobileNet\nfrom keras.preprocessing import image\nfrom keras.models import Model\nfrom keras.layers import Flatten\nfrom keras.layers import Dense, GlobalAveragePooling2D\nfrom keras import backend as K\nfrom keras.utils import plot_model\nfrom keras.preprocessing.image import ImageDataGenerator\nfrom keras.callbacks import TensorBoard\nimport matplotlib.pyplot as plt\n\nprint(\"Checkpoint 1\")\n\ntrain_data_dir='../../Databases/MIT_split/train'\nval_data_dir='../../Databases/MIT_split/test'\ntest_data_dir='../../Databases/MIT_split/test'\nimg_width = 224\nimg_height=224\nbatch_size=32\nnumber_of_epoch=5\nvalidation_samples=807\n\nprint(\"Checkpoint 2\")\n\ndef preprocess_input(x, dim_ordering='default'):\n if dim_ordering == 'default':\n dim_ordering = K.image_data_format()\n assert dim_ordering in {'channels_first', 'channels_last'}\n\n if dim_ordering == 'channels_first':\n # 'RGB'->'BGR'\n x = x[ ::-1, :, :]\n # Zero-center by mean pixel\n x[ 0, :, :] -= 103.939\n x[ 1, :, :] -= 116.779\n x[ 2, :, :] -= 123.68\n else:\n # 'RGB'->'BGR'\n x = x[:, :, ::-1]\n # Zero-center by mean pixel\n x[:, :, 0] -= 103.939\n x[:, :, 1] -= 116.779\n x[:, :, 2] -= 123.68\n return x\n\nprint(\"Checkpoint 3\")\n# create the base pre-trained model\nbase_model = MobileNet(weights='imagenet', dropout=0.5)\nplot_model(base_model, to_file='modelVGG16a.png', show_shapes=True, show_layer_names=True)\n\nx = base_model.layers[-2].output\nx = Dense(8, activation='softmax',name='predictions')(x)\n\nmodel = Model(inputs=base_model.input, outputs=x)\nplot_model(model, to_file='modelVGG16b.png', show_shapes=True, show_layer_names=True)\n\n\nlayers = len(model.layers)\nfor layer in model.layers:\n layer.trainable = False\nfor layer in model.layers[layers-2:]:\n layer.trainable = True\n\nprint(\"Checkpoint 4\")\n \nmodel.compile(loss='categorical_crossentropy',optimizer='adadelta', metrics=['accuracy'])\nprint(\"Checkpoint 5\")\nfor layer in model.layers:\n print(layer.name, layer.trainable)\n\nprint(\"Checkpoint 6\")\n\n#preprocessing_function=preprocess_input,\ndatagen = ImageDataGenerator(featurewise_center=False,\n samplewise_center=False,\n featurewise_std_normalization=False,\n samplewise_std_normalization=False,\n\tpreprocessing_function=preprocess_input,\n rotation_range=0.,\n width_shift_range=0.,\n height_shift_range=0.,\n shear_range=0.,\n zoom_range=0.,\n channel_shift_range=0.,\n fill_mode='nearest',\n cval=0.,\n horizontal_flip=False,\n vertical_flip=False,\n rescale=None)\n\nprint(\"Checkpoint 7\")\n\ntrain_generator = datagen.flow_from_directory(train_data_dir,\n target_size=(img_width, img_height),\n batch_size=batch_size,\n class_mode='categorical')\n\ntest_generator = datagen.flow_from_directory(test_data_dir,\n target_size=(img_width, img_height),\n batch_size=batch_size,\n class_mode='categorical')\n\nvalidation_generator = datagen.flow_from_directory(val_data_dir,\n target_size=(img_width, img_height),\n batch_size=batch_size,\n class_mode='categorical')\n\ntbCallBack = TensorBoard(log_dir='./outs/1', histogram_freq=0, write_graph=True)\nhistory=model.fit_generator(train_generator,\n steps_per_epoch=(int(400//batch_size)+1),\n nb_epoch=number_of_epoch,\n validation_data=validation_generator,\n validation_steps= (int(validation_samples//batch_size)+1), callbacks=[tbCallBack])\n\n\n# result = model.evaluate_generator(test_generator, val_samples=validation_samples)\nprint(\"Checkpoint 8\")\n\n# print( result)\n\n\n# list all data in history\n\nprint(\"History: \",history.history)\n\nif True:\n # summarize history for accuracy\n plt.plot(history.history['accuracy'])\n plt.plot(history.history['val_accuracy'])\n plt.title('model accuracy')\n plt.ylabel('accuracy')\n plt.xlabel('epoch')\n plt.legend(['train', 'validation'], loc='upper left')\n plt.savefig('accuracy.jpg')\n plt.close()\n # summarize history for loss\n plt.plot(history.history['loss'])\n plt.plot(history.history['val_loss'])\n plt.title('model loss')\n plt.ylabel('loss')\n plt.xlabel('epoch')\n plt.legend(['train', 'validation'], loc='upper left')\n plt.savefig('loss.jpg')\n","sub_path":"Scripts/week4/w4.py","file_name":"w4.py","file_ext":"py","file_size_in_byte":4246,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"488882257","text":"import pytest\n\nfrom src.model.jsonprovider import ChampionJsonProvider\nfrom src.model.jsonprovider import InvalidPatchOrRegionError\n\n\nPATCH: str = '9.3.1'\nREGION: str = 'ja_JP'\n\n\ndef test_happypath():\n json_provider = ChampionJsonProvider()\n champion_json = json_provider.provide(PATCH, REGION)\n with open('{0}.json'.format(PATCH)) as patch_json:\n assert champion_json == patch_json.read()\n\n\ndef test_invalid_patch():\n with pytest.raises(InvalidPatchOrRegionError):\n ChampionJsonProvider().provide('0.0.0', REGION)\n\n\ndef test_invalid_region():\n with pytest.raises(InvalidPatchOrRegionError):\n ChampionJsonProvider().provide(PATCH, 'NA>EU')\n","sub_path":"src/test/test_jsonprovider.py","file_name":"test_jsonprovider.py","file_ext":"py","file_size_in_byte":676,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"111910667","text":"#!/usr/bin/env pybricks-micropython\nfrom pybricks.hubs import EV3Brick\nfrom pybricks.ev3devices import (Motor, TouchSensor, ColorSensor,\n InfraredSensor, UltrasonicSensor, GyroSensor)\nfrom pybricks.parameters import Port, Stop, Direction, Button, Color\nfrom pybricks.tools import wait, StopWatch, DataLog\nfrom pybricks.robotics import DriveBase\nfrom pybricks.media.ev3dev import SoundFile, ImageFile\n\n\n# This program requires LEGO EV3 MicroPython v2.0 or higher.\n# Click \"Open user guide\" on the EV3 extension tab for more information.\n \n\n# Create your objects here.\nev3 = EV3Brick()\n\n\n\ndef waitButtons():\n while True:\n ev3.light.on(Color.GREEN)\n if Button.UP in ev3.buttons.pressed(): \n RedMission1()\n if Button.LEFT in ev3.buttons.pressed():\n YellowMission()\n if Button.DOWN in ev3.buttons.pressed():\n BlueMission()\n if Button.RIGHT in ev3.buttons.pressed():\n BlackandGreen()\n\ndef YellowMission():\n \n #!/usr/bin/env pybricks-micropython\n from pybricks.hubs import EV3Brick\n from pybricks.ev3devices import (Motor, TouchSensor, ColorSensor,\n InfraredSensor, UltrasonicSensor, GyroSensor)\n from pybricks.parameters import Port, Stop, Direction, Button, Color\n from pybricks.tools import wait, StopWatch, DataLog\n from pybricks.robotics import DriveBase\n from pybricks.media.ev3dev import SoundFile, ImageFile\n\n\n # This program requires LEGO EV3 MicroPython v2.0 or higher.\n # Click \"Open user guide\" on the EV3 extension tab for more information.\n\n\n # Create your objects here.\n ev3 = EV3Brick()\n left_motor = Motor(Port.C)\n right_motor = Motor(Port.B)\n medium_motor = Motor(Port.A)\n front_largeMotor = Motor(Port.D)\n wheel_diameter = 56\n axle_track = 115\n\n robot = DriveBase(left_motor, right_motor, wheel_diameter, axle_track)\n # Initialize the color sensor.\n line_sensor = ColorSensor(Port.S2)\n line_sensor2 = ColorSensor(Port.S3)\n\n robot.straight(110)\n\n # Calculate the light threshold. Choose values based on your measurements.\n BLACK = 9\n WHITE = 85\n threshold = (BLACK + WHITE) / 2\n\n # Set the drive speed at 100 millimeters per second.\n DRIVE_SPEED = 100\n\n # Set the gain of the proportional line controller. This means that for every\n # percentage point of light deviating from the threshold, we set the turn\n # rate of the drivebase to 1.2 degrees per second.\n\n # For example, if the light value deviates from the threshold by 10, the robot\n # steers at 10*1.2 = 12 degrees per second.\n PROPORTIONAL_GAIN = 1.2\n runWhile = True\n # Start following the line endlessly.\n while runWhile:\n # Calculate the deviation from the threshold.\n deviation = line_sensor.reflection() - threshold\n\n # Calculate the turn rate.\n turn_rate = PROPORTIONAL_GAIN * deviation\n\n # Set the drive base speed and turn rate.\n robot.drive(DRIVE_SPEED, turn_rate)\n\n if robot.distance() == 800:\n runWhile = False\n\n robot.stop(Stop.BRAKE)\n\n robot.drive(100, 0)\n if line_sensor2 and cl.Color() == Color.BLACK:\n robot.stop(Stop.BRAKE)\n \n \n\n # robot stops after finishing up line following code\n robot.stop(Stop.BRAKE)\n\n # robot turns after finishing up line following code\n robot.turn(-103.5)\n # robot goes straight as it heads towards the mission\n robot.straight(138)\n # robot turns right for 90 degrees\n robot.turn(80)\n # robot goes straight towards the mission to line the attachment to the wheel\n robot.straight(97)\n # large motor attachment goes down to trap the wheel in\n front_largeMotor.run_angle(60, 162)\n # robot moves backwards to bring wheel outside of the large circle\n robot.straight (-115)\n # large motor releases the trapped tire\n front_largeMotor.run_angle(60, -148)\n # robot moves straight to get closer the wheel\n robot.straight (38)\n # robot turns so the wheel can get into the smaller target\n robot.turn (-40)\n robot.stop (Stop.BRAKE)\n # robot goes backwards to leave the target and the wheel inside of it\n robot.straight (-110)\n # robot turns towards the weight machine\n robot.turn (-30)\n # going straight from row machine to weight machine\n robot.straight(505)\n # stopping for accuracy.\n robot.stop(Stop.BRAKE)\n # turning towards the weight machine.\n robot.turn(30)\n # robot goes straight to get closer to the weight machine\n robot.straight(145)\n # large motor going down to complete mission (weight machine).\n front_largeMotor.run_angle(120, 130)\n # going backwards away from the weight machine\n robot.straight(-120)\n # large motor goes back up \n # front_largeMotor.run_angle(50, -100)\n ## The robot is turning away from the Weight Machine and towards the Boccia. \n robot.turn(-127)\n ## The robot is moving straight towards the Boccia Mission.\n robot.straight(290)\n # the robot turns right to turn the aim boccia with the yellow axle on the bottom of the bot. \n robot.turn(60)\n # robot.straight(-10)\n # robot.turn(15)\n # front_largeMotor.run_angle(50, 60)\n # robot.straight(55)\n # the large motor goes up to push the yellow cube down into the target area.\n front_largeMotor.run_angle(50, -50)\n robot.straight(-100)\n robot.turn(-45)\n robot.straight(900)\n robot.turn(25)\n robot.straight(700)\n\ndef BlueMission():\n \n #!/usr/bin/env pybricks-micropython\n from pybricks.hubs import EV3Brick\n from pybricks.ev3devices import (Motor, TouchSensor, ColorSensor,\n InfraredSensor, UltrasonicSensor, GyroSensor)\n from pybricks.parameters import Port, Stop, Direction, Button, Color\n from pybricks.tools import wait, StopWatch, DataLog\n from pybricks.robotics import DriveBase\n from pybricks.media.ev3dev import SoundFile, ImageFile\n\n\n # This program requires LEGO EV3 MicroPython v2.0 or higher.\n # Click \"Open user guide\" on the EV3 extension tab for more information.\n\n #define your variables\n ev3 = EV3Brick()\n left_motor = Motor(Port.C)\n right_motor = Motor(Port.B)\n medium_motor = Motor(Port.A)\n large_motor = Motor(Port.D)\n wheel_diameter = 56\n axle_track = 115 \n line_sensor = ColorSensor(Port.S2)\n line_sensor1 = ColorSensor(Port.S3)\n robot = DriveBase(left_motor, right_motor, wheel_diameter, axle_track)\n\n #go front towards the step counter\n robot.straight(650)\n robot.stop(Stop.BRAKE)\n wait(20)\n\n #makes the robot go slower \n robot.settings(40)\n\n #slowly pushes the step counter by going back and front 2 times\n robot.straight(140)\n robot.stop(Stop.BRAKE)\n robot.straight(-45)\n robot.stop(Stop.BRAKE)\n robot.straight(120)\n robot.stop(Stop.BRAKE)\n robot.settings(100)\n robot.straight(-30)\n robot.stop(Stop.BRAKE)\n #the robot then turns and goes backwards\n robot.turn(45)\n robot.straight(-100)\n # the robot then goes back until the right color sensor detects back\n while True:\n robot.drive(-30,0)\n if line_sensor.color() == Color.BLACK:\n robot.stop(Stop.BRAKE)\n break \n #the large motor attatchment comes down at the same time the robot takes a turn towards the black line underneath the pull up bar\n large_motor.run_angle(50,170,then=Stop.HOLD, wait=False)\n left_motor.run_angle(50,-300,then=Stop.HOLD, wait=True)\n #the robot then goes straight towards that line\n robot.straight(120)\n robot.stop(Stop.BRAKE)\n #robot continues to go forwards until the left color sensor detects black\n while True:\n robot.drive(30,0)\n if line_sensor.color() == Color.BLACK:\n robot.stop(Stop.BRAKE)\n break \n right_motor.run_angle(50,150,then=Stop.HOLD, wait=True)\n #the robot then turns with the right motor until it detects black\n while True:\n right_motor.run(85)\n if line_sensor.color() == Color.BLACK:\n robot.stop(Stop.BRAKE)\n break\n #follows the line underneath the pull up bar until the leftsensor detects black\n BLACK = 9\n WHITE = 85\n threshold = (BLACK + WHITE) / 2\n # Set the drive speed at 100 millimeters per second.\n DRIVE_SPEED = 100\n # Set the gain of the proportional line controller. This means that for every\n PROPORTIONAL_GAIN = 1.2\n runWhile = True\n robot.reset()\n while True:\n # Calculate the deviation from the threshold.\n deviation = line_sensor.reflection() - threshold\n # Calculate the turn rate.\n turn_rate = PROPORTIONAL_GAIN * deviation\n # Set the drive base speed and turn rate.\n robot.drive(DRIVE_SPEED, turn_rate)\n wait(10)\n print(line_sensor.color())\n if line_sensor1.color() == Color.BLACK:\n robot.stop(Stop.BRAKE)\n break\n #the robot then turns towards the boccia aim and moves straight to push it towards the target and finishes the misison \n robot.straight(100) #after line following, it goes straight for 100 mm\n robot.turn(50)\n robot.straight(100)\n robot.straight(-30)\n large_motor.run_angle(100,-65)\n robot.straight(-60)\n #the robot then takes a turn (at the same time bringing the attatchment down) towards the slide mission and completes the mission\n large_motor.run_angle(50,80,then=Stop.HOLD, wait=False)\n robot.turn(-195)\n robot.straight(165)\n large_motor.run_angle(300, -120, then=Stop.HOLD, wait=True)\n robot.straight(-30)\n large_motor.run_angle(200, 120, then=Stop.HOLD, wait=True)\n ## The robot moves straight towards the mission, getting ready to attempt to push the slide figures off once more. (In case it didn't work before.)\n robot.straight(30)\n large_motor.run_angle(300, -120, then=Stop.HOLD, wait=True)\n robot.straight(-50)\n '''\n #the robot then goes back to base after finishing all of the designated missions\n robot.turn(60)\n robot.straight(60)\n robot.turn(30)\n robot.straight(120)\n robot.turn(-80)\n robot.straight(500)\n robot.turn(-70)\n robot.straight(600)\n'''\n\ndef BlackandGreen():\n\n #!/usr/bin/env pybricks-micropython\n from pybricks.hubs import EV3Brick\n from pybricks.ev3devices import (Motor, TouchSensor, ColorSensor,\n InfraredSensor, UltrasonicSensor, GyroSensor)\n from pybricks.parameters import Port, Stop, Direction, Button, Color\n from pybricks.tools import wait, StopWatch, DataLog\n from pybricks.robotics import DriveBase\n from pybricks.media.ev3dev import SoundFile, ImageFile\n\n\n # This program requires LEGO EV3 MicroPython v2.0 or higher.\n # Click \"Open user guide\" on the EV3 extension tab for more information.\n\n #define your variables\n ev3 = EV3Brick()\n left_motor = Motor(Port.C)\n right_motor = Motor(Port.B)\n medium_motor = Motor(Port.A)\n large_motor = Motor(Port.D)\n wheel_diameter = 56\n axle_track = 115 \n line_sensor = ColorSensor(Port.S2)\n line_sensor1 = ColorSensor(Port.S3)\n robot = DriveBase(left_motor, right_motor, wheel_diameter, axle_track)\n #follows the line underneath the pull up bar until the leftsensor detects black\n BLACK = 9\n WHITE = 85\n threshold = (BLACK + WHITE) / 2\n # Set the drive speed at 100 millimeters per second.\n DRIVE_SPEED = 100\n # Set the gain of the proportional line controller. This means that for every\n PROPORTIONAL_GAIN = 1.2\n runWhile = True\n #goes straight to get ready for line following then resets the distance\n robot.straight(250)\n robot.reset()\n #starts to follow the line towards the replay logo\n while True:\n # Calculate the deviation from the threshold.\n deviation = line_sensor.reflection() - threshold\n # Calculate the turn rate.\n turn_rate = PROPORTIONAL_GAIN * deviation\n # Set the drive base speed and turn rate.\n robot.drive(DRIVE_SPEED, turn_rate)\n wait(10)\n print(robot.distance())\n if(robot.distance ()>= 450):\n robot.stop(Stop.BRAKE)\n break\n #the robot pushes the phone into the replay logo and moves back to get ready to drop the health units into the replay logo\n robot.straight(-75)\n robot.stop(Stop.BRAKE)\n #the robot then turns so it is going to be perfectly into the replay logo\n robot.turn(-35) \n #the robot drops the health units\n large_motor.run_angle(100,150) \n #then turns to an angle to go back to base\n robot.turn(50)\n robot.straight(-1000) \n\n wait(50)\n\n #!/usr/bin/env pybricks-micropython\n from pybricks.hubs import EV3Brick\n from pybricks.ev3devices import (Motor, TouchSensor, ColorSensor,\n InfraredSensor, UltrasonicSensor, GyroSensor)\n from pybricks.parameters import Port, Stop, Direction, Button, Color\n from pybricks.tools import wait, StopWatch, DataLog\n from pybricks.robotics import DriveBase\n from pybricks.media.ev3dev import SoundFile, ImageFile\n\n\n # This program requires LEGO EV3 MicroPython v2.0 or higher.\n # Click \"Open user guide\" on the EV3 extension tab for more information.\n\n\n # Create your objects here.\n ev3 = EV3Brick()\n\n left_motor = Motor(Port.C)\n right_motor = Motor(Port.B)\n medium_motor = Motor(Port.A)\n front_largeMotor = Motor(Port.D)\n\n wheel_diameter = 56\n axle_track = 114.3 \n\n robot = DriveBase(left_motor, right_motor, wheel_diameter, axle_track)\n\n ## Write your code here: \n\n ## The robot goes straight until the Boccia Mission's target. \n robot.straight(1060)\n\n ## The robot moves the large motor down to drop the cubes in the target. \n front_largeMotor.run_angle(80, 70, then=Stop.HOLD, wait=True)\n front_largeMotor.run_angle(-80, 70, then=Stop.HOLD, wait=True)\n\n\n ## Dance Mission\n\n ## The robot moves backwards to reach the Dance Floor so it can Dance as the last mission. \n robot.straight(-185)\n robot.turn(-70)\n robot.straight(138) \n\n\n ## The following code is all the dance moves we do for the Dance Mission. \n\n robot.turn(160)\n robot.turn(-160)\n robot.straight(60)\n front_largeMotor.run_target(500, 60)\n front_largeMotor.run_target(500, -40)\n robot.straight(-60)\n robot.turn(260)\n robot.turn(-260)\n robot.turn(100)\n robot.straight(40)\n robot.turn(100)\n front_largeMotor.run_angle(500, 30)\n\ndef RedMission1(): \n \n #!/usr/bin/env pybricks-micropython\n from pybricks.hubs import EV3Brick\n from pybricks.ev3devices import (Motor, TouchSensor, ColorSensor,\n InfraredSensor, UltrasonicSensor, GyroSensor)\n from pybricks.parameters import Port, Stop, Direction, Button, Color\n from pybricks.tools import wait, StopWatch, DataLog\n from pybricks.robotics import DriveBase\n from pybricks.media.ev3dev import SoundFile, ImageFile\n\n\n # This program requires LEGO EV3 MicroPython v2.0 or higher.\n # Click \"Open user guide\" on the EV3 extension tab for more information.\n\n\n # Create your objects here.\n ev3 = EV3Brick()\n\n left_motor = Motor(Port.C)\n right_motor = Motor(Port.B)\n wheel_diameter = 56\n axle_track = 115\n\n robot = DriveBase(left_motor, right_motor, wheel_diameter, axle_track)\n\n Medium_Motor = Motor(Port.A)\n Large_Motor = Motor(Port.D)\n\n leftcolorsensor = ColorSensor(Port.S3)\n rightcolorsensor = ColorSensor(Port.S2)\n\n #####\n\n BLACK = 9\n WHITE = 85\n threshold = (BLACK + WHITE) / 2\n\n ######\n\n robot.straight(320)\n robot.turn(110)\n \n while True:\n robot.drive(90,0)\n if leftcolorsensor.reflection() <= 9:\n robot.stop(Stop.BRAKE)\n break \n\n robot.turn(-110)\n\n robot.straight(200)\n\n # Calculate the light threshold. Choose values based on your measurements.\n BLACK = 6\n WHITE = 85\n threshold = (BLACK + WHITE) / 2\n\n # Set the drive speed at 100 millimeters per second.\n DRIVE_SPEED = 110\n\n # Set the gain of the proportional line controller. This means that for every\n # percentage point of light deviating from the threshold, we set the turn\n # rate of the drivebase to 1.2 degrees per second.\n\n # For example, if the light value deviates from the threshold by 10, the robot\n # steers at 10*1.2 = 12 degrees per second.\n PROPORTIONAL_GAIN = 1.2\n runWhile = True\n # Start following the line endlessly.\n while runWhile:\n # Calculate the deviation from the threshold.\n deviation = rightcolorsensor.reflection() - threshold\n\n # Calculate the turn rate.\n turn_rate = PROPORTIONAL_GAIN * deviation\n\n # Set the drive base speed and turn rate.\n robot.drive(DRIVE_SPEED, turn_rate)\n\n if robot.distance() == 1000:\n runWhile = False\n\n # robot stops after finishing up line following code\n\n robot.stop(Stop.BRAKE)\n\n robot.straight(-40)\n\n robot.turn(-50)\n robot.straight(145)\n Large_Motor.run_angle(50,90,then = Stop.HOLD, wait = True)\n\n #robot continues run, to do Boccia mission\n\n while True:\n robot.drive(-80,0)\n if leftcolorsensor.reflection() <= 10:\n robot.stop(Stop.BRAKE)\n break \n\n robot.straight(80)\n robot.turn(60)\n robot.straight(100)\n\n\n Large_Motor.run_angle(-50,150,then = Stop.HOLD, wait = True) \n robot.straight(-40)\n Large_Motor.run_angle(50,150,then = Stop.HOLD, wait = True) \n\n robot.straight(-40)\n\n while True:\n robot.drive(-80,0)\n if leftcolorsensor.reflection() <= 9:\n robot.stop(Stop.BRAKE)\n break\n\n robot.straight(40)\n robot.turn(-85)\n\n robot.straight(340)\n robot.turn(165)\n\n robot.straight(55)\n Large_Motor.run_angle(-50,150,then = Stop.HOLD, wait = True)\n\n robot.straight(20)\n\n Medium_Motor.run_angle(150,250,then = Stop.HOLD, wait = True)\n robot.turn(70)\n Medium_Motor.run_angle(-150,250,then = Stop.HOLD, wait = True)\n robot.turn(-20)\n robot.straight(-35)\n Medium_Motor.run_angle(150,250,then = Stop.HOLD, wait = True)\n\n robot.turn(30)\n robot.straight(-130)\n\nwaitButtons()","sub_path":"CopyMain.py","file_name":"CopyMain.py","file_ext":"py","file_size_in_byte":18245,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"524614968","text":"from lib.log_helper import PipelineLogger\nfrom proto.pipeline.attribute_pb2 import PipelineAttrUInt\nfrom squirrel.pipeline import Release\nfrom squirrel.runner import run\n\n\nclass AttDebtSize(Release):\n IMPORT = [\"snapshot.data\"]\n EXPORT = [\"att.debt.size\"]\n\n def run(self, cache, mode):\n read_stream = cache.stream_reader(\"snapshot.data\")\n write_stream = cache.stream_writer(\"att.debt.size\")\n counter = 0\n\n for snapshot in read_stream.get_iterator():\n total = 0\n for debt in snapshot.history.data.debts:\n total += debt.data.balance.principal_cents\n total -= debt.data.balance.prepayment_cents\n\n write_stream.append_pobj(\n PipelineAttrUInt(\n snapshot_id=snapshot.snapshot_id,\n val=total,\n )\n )\n\n # log progress\n counter += 1\n PipelineLogger.counter(\"snapshots\", counter, mode)\n\n # return number of records examined\n return counter\n\n\nif __name__ == \"__main__\":\n run(AttDebtSize, __file__)\n","sub_path":"pipeline/src/transform/attributes/att_debt_size.py","file_name":"att_debt_size.py","file_ext":"py","file_size_in_byte":1115,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"370862297","text":"from PyPDF2 import PdfFileReader\r\nimport re\r\nimport nltk\r\nfrom nltk import sent_tokenize, ne_chunk, word_tokenize\r\nfrom nltk.tag import pos_tag, pos_tag_sents\r\nfrom nltk.tree import Tree\r\n\r\ndocument = 'd:\\\\ICISA_DE.pdf'\r\n#Pre-processing1: Converting PDF to Text\r\n\r\ndef extractText(path):\r\n text = ''\r\n with open(path, 'rb') as f:\r\n pdf = PdfFileReader(f)\r\n num_pages = pdf.getNumPages();\r\n\r\n for pg in range(num_pages):\r\n page = pdf.getPage(pg)\r\n text += page.extractText()\r\n return text\r\n\r\n#Pre-processing2:Cleaning the input text\r\ndef cleanupText(text):\r\n text = re.sub('(\\.\\ ?){2,}', ' ', text)\r\n text = re.sub('\\n', ' ', text)\r\n text = re.sub('\\ {2,}', ' ', text)\r\n\r\n return text\r\n\r\n#NLP Based Text processing1:Tokenization and Parts of speech Tagger\r\ndef tagText(text):\r\n sents = [word_tokenize(s) for s in sent_tokenize(text)]\r\n\r\n taggedSents = pos_tag_sents(sents)\r\n\r\n return taggedSents\r\n\r\n#NLP Based Text processing2:NP Chunking for identification of concepts\r\n\r\ndef neChunk(sents):\r\n newSents = []\r\n for sent in sents:\r\n newSent = []\r\n for i in ne_chunk(sent):\r\n if (type(i) == Tree):\r\n entity_name = ' '.join([c[0] for c in i.leaves()])\r\n else:\r\n entity_name = i[0]\r\n newSent.append(entity_name)\r\n\r\n newSents.append(newSent)\r\n\r\n\r\ndef chunk(sentence):\r\n chunkToExtract = \"\"\"\r\n NP: {*}\r\n\t\t{
??}\r\n\t\t{}\"\"\"\r\n parser = nltk.RegexpParser(chunkToExtract)\r\n result = parser.parse(sentence)\r\n sent = []\r\n for subtree in result.subtrees():\r\n if subtree.label() == 'NP':\r\n t = subtree\r\n t = ' '.join(word for word, pos in t.leaves())\r\n sent.append(t)\r\n\r\n return sent\r\n# Creating a vocabulary of concepts for creating an ontology\r\n\r\ndef extractVocab(taggedsents):\r\n dict = {word: 0 for sent in taggedSents for word in chunk(sent)}\r\n\r\n vocabulary = list(dict.keys())\r\n\r\n return vocabulary\r\n\r\n\r\ntext = extractText(document)\r\ncleanedText = cleanupText(text)\r\ntaggedSents = tagText(cleanedText)\r\n\r\nvocabulary = extractVocab(taggedSents)\r\n\r\nprint (vocabulary)","sub_path":"Ontology_Preprocessing_Processing.py","file_name":"Ontology_Preprocessing_Processing.py","file_ext":"py","file_size_in_byte":2210,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"16309279","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import models, migrations\nimport apps.casos.thumbs\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('casos', '0003_caso_fkmunicipio'),\n ]\n\n operations = [\n migrations.CreateModel(\n name='Foto',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('imagen', apps.casos.thumbs.ImageWithThumbsField(upload_to=b'fotoscaso', blank=True)),\n ],\n ),\n migrations.RemoveField(\n model_name='caso',\n name='foto',\n ),\n ]\n","sub_path":"apps/casos/migrations/0004_auto_20160108_1607.py","file_name":"0004_auto_20160108_1607.py","file_ext":"py","file_size_in_byte":692,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"525227305","text":"\"\"\"test_level3_dithers: Test of spectrographic rules.\"\"\"\nfrom __future__ import absolute_import\nfrom glob import glob\nimport pytest\nimport re\n\nfrom .helpers import (\n BasePoolRule,\n PoolParams,\n combine_pools,\n generate_params,\n t_path\n)\n\nfrom .. import (AssociationRegistry, generate)\nfrom ..main import constrain_on_candidates\n\n\nclass TestLevel3Spectrographic(BasePoolRule):\n\n pools = [\n PoolParams(\n path=glob(t_path('data/pool_*_spec_*.csv')),\n n_asns=7,\n n_orphaned=0\n ),\n ]\n\n valid_rules = [\n 'Asn_MIRI_LRS_FIXEDSLIT',\n 'Asn_NIR_SO_SLITLESS',\n 'Asn_NRS_FIXEDSLIT',\n 'Asn_NRS_MSA',\n 'Asn_MIRI_MRS',\n 'Asn_NRS_IFU'\n ]\n\n\n@pytest.fixture(\n scope='module',\n params=[\n (\n 'o001',\n 'spec',\n 'jw99009-o001_spec_\\d{3}_asn',\n 'jw99009-o001_t001_nirspec_f100lp-g140m',\n ),\n (\n 'o002',\n 'spec',\n 'jw99009-o002_spec_\\d{3}_asn',\n 'jw99009-o002_t003_nirspec_f100lp-g140h',\n ),\n (\n 'o003',\n 'nrsifu',\n 'jw99009-o003_nrsifu_\\d{3}_asn',\n 'jw99009-o003_t002_nirspec_g235h'\n ),\n ]\n)\ndef nirspec_params(request):\n cid, asn_type, asn_name, product_name = request.param\n pool = combine_pools(t_path('data/pool_006_spec_nirspec.csv'))\n gc = {\n 'asn_candidate': constrain_on_candidates((cid,))\n }\n rules = AssociationRegistry(global_constraints=gc)\n asns, orphaned = generate(pool, rules)\n return asns, asn_type, asn_name, product_name\n\nclass TestLevel3SpectrographicSpecifics(object):\n\n def test_nirspec_modes(self, nirspec_params):\n asns, asn_type, asn_name, product_name = nirspec_params\n\n assert len(asns) == 1\n asn = asns[0]\n assert asn['asn_type'] == asn_type\n assert re.match(asn_name, asn.asn_name)\n assert asn['products'][0]['name'] == product_name\n","sub_path":"jwst/associations/tests/test_level3_spectrographic.py","file_name":"test_level3_spectrographic.py","file_ext":"py","file_size_in_byte":2011,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"77170064","text":"from autobahn.twisted.websocket import WebSocketServerProtocol, WebSocketServerFactory, listenWS\nimport os\nimport json\nimport subprocess\nimport sys\nfrom queue import Queue, Empty\nfrom threading import Thread\nfrom twisted.python import log\nfrom twisted.internet import reactor\n\n\nclass DarcMailConvert(WebSocketServerProtocol):\n WS_FOLDER_LIST = 1\n WS_RECV_PACKAGE = 2\n WS_PROG_ON = 4\n WS_PROG_OFF = 5\n WS_SEND = 3\n\n def __init__(self):\n super().__init__()\n self.server_name = \"DarcMailConverter\"\n self.on_posix = 'posix' in sys.builtin_module_names\n self.cur_folder = None\n self.stitch = None\n self.chunk = None\n self.chunk_size = None\n self.from_eml = None\n self.transfer_name = None\n self.build_opts = []\n self.production = True\n self.file_tree = []\n if self.production:\n self.dm_exec = '/usr/src/app/docker_dmc/DarcMailCLI.py'\n self.base_package_location = \"/home/tomes/data\"\n else:\n self.dm_exec = 'D:\\\\Development\\\\Python\\\\DockerComposeStruct\\\\devel\\\\tomes_docker_app\\\\Servers\\\\darcm_server\\\\docker_dmc\\\\DarcMailCLI.py'\n self.base_package_location = 'E:\\\\RESOURCES\\\\TEST_RESOURCES\\\\tomes\\\\data'\n\n def onConnect(self, request):\n print(\"{}: Connected\".format(self.server_name))\n headers = {'Access-Control-Allow-Origin': '*'}\n return None, headers\n\n def onOpen(self):\n s = self._get_folder_tree()\n self.sendMessage(self.get_message_for_sending(DarcMailConvert.WS_FOLDER_LIST, s))\n self.sendMessage(self.get_message_for_sending(DarcMailConvert.WS_SEND, 'Client connected!'))\n\n def _get_folder_tree(self):\n children = os.listdir(os.path.join(self.base_package_location, 'mboxes'))\n nc = []\n for c in children:\n nc.append({'name': c})\n self.file_tree.append({'name': \"Mime Sources\", 'children': nc})\n return json.dumps(self.file_tree)\n\n def onMessage(self, payload, isBinary):\n payload = json.loads(bytes.decode(payload, encoding='utf-8'))\n if isBinary:\n pass\n else:\n if payload['o'] == DarcMailConvert.WS_RECV_PACKAGE:\n self.cur_folder = payload['data']['fldr']\n self.stitch = payload['data']['stitch']\n self.chunk = payload['data']['chunk']\n self.chunk_size = payload['data']['chunk_size']\n self.from_eml = payload['data']['from_eml']\n self.transfer_name = payload['data']['trans_name']\n self.build_convert_opts()\n # callInThread necessary to prevent blocking\n reactor.callInThread(self.convert)\n if payload['o'] == 5:\n self.get(payload['data']['fldr'])\n\n def find_folder(self, folder):\n for root, dirs, files in os.walk(self.base_package_location):\n for d in dirs:\n #self.sendMessage(self.get_message_for_sending(2, \"Fldrs: {}\".format(d)))\n if d == folder:\n return os.path.join(root, d)\n\n def onClose(self, wasClean, code, reason):\n print(\"WebSocket connection closed: {0}\".format(reason))\n\n def get(self, fldr) -> str:\n # Get a suggested transfer_name\n #self.sendMessage(self.get_message_for_sending(2, \"Base package is {}\".format(self.base_package_location)))\n for root, dirs, files in os.walk(self.base_package_location):\n for d in dirs:\n if d == fldr:\n root_split = root.split(os.path.sep)\n i = root_split.index('data') + 2\n final = root_split[i:] + [d]\n final = '_'.join(final)\n final = final.replace(\" \", \"_\")\n self.sendMessage(self.get_message_for_sending(5, final))\n\n def build_convert_opts(self):\n self.build_opts = ['python', self.dm_exec]\n package_location = self.find_folder(self.cur_folder)\n\n # BEGIN REQUIRED These are required\n self.build_opts.append('-a')\n self.build_opts.append(self.transfer_name)\n self.build_opts.append(\"-d\")\n self.build_opts.append(package_location)\n self.build_opts.append(\"-tt\")\n # End REQUIRED\n\n # BEGIN NOT REQUIRED These are NOT Required but recommended\n self.build_opts.append('-c')\n if self.chunk:\n self.build_opts.append('{}'.format(self.chunk_size))\n else:\n self.build_opts.append('{}'.format(0))\n\n if self.stitch:\n self.build_opts.append('-st')\n # END NOT REQUIRED\n\n # BEGIN OPTIONS: These are options\n if self.from_eml:\n # Requested Structure is EML\n self.build_opts.append('-fe')\n\n # END OPTIONS\n\n for i in range(len(self.build_opts)):\n self.build_opts[i] = str(self.build_opts[i])\n\n def enqueue_out(self, out, queue):\n for line in iter(out.readline, b''):\n queue.put(line)\n out.close()\n\n def get_message_for_sending(self, router, message):\n l = json.dumps({'router': router, 'data': message})\n return l.encode('utf-8')\n\n def convert(self):\n p = subprocess.Popen(self.build_opts, stdout=subprocess.PIPE, bufsize=1, close_fds=self.on_posix)\n q = Queue()\n t = Thread(target=self.enqueue_out, args=(p.stdout, q))\n t.daemon = True\n self.sendMessage(self.get_message_for_sending(DarcMailConvert.WS_SEND, \"Processing: {}\".format(self.cur_folder)))\n t.start()\n line = None\n self.sendMessage(self.get_message_for_sending(DarcMailConvert.WS_PROG_ON, ''))\n while t.is_alive():\n try:\n # Wait for a line to be generated.\n line = q.get_nowait()\n except Empty:\n # if the queue is empty but not complete continue\n pass\n else:\n l = bytes.decode(line, encoding='utf-8')\n sender = json.dumps({'router': DarcMailConvert.WS_SEND, 'data': l.strip()})\n self.sendMessage(sender.encode('utf-8'))\n\n self.sendMessage(self.get_message_for_sending(DarcMailConvert.WS_SEND, \"Complete\"))\n self.sendMessage(self.get_message_for_sending(DarcMailConvert.WS_PROG_OFF, ''))\n\n\nif __name__ == \"__main__\":\n log.startLogging(sys.stdout)\n factory = WebSocketServerFactory()\n factory.protocol = DarcMailConvert\n reactor.listenTCP(9001, factory)\n reactor.run()","sub_path":"Servers/darcm_server/DarcMailServer.py","file_name":"DarcMailServer.py","file_ext":"py","file_size_in_byte":6558,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"370170680","text":"def General_condition_query(asn,domain_list,app_list,time):\n\tdomain_condition = \" \".join(\"(*{}*)\".format(domain) for domain in domain_list)\n\tquery = {\n \t\"size\": 0,\n \t\"query\": {\"bool\": {\"must\": [\n \t{\"range\": {\"date\": time}},\n \t{\"terms\": { \"geoasn.asn\": asn}},\n \t{\"terms\": {\"app.app_id\": app_list}},\n \t{\"query_string\": {\"query\": domain_condition,\"default_field\": \"domain_name.keyword\"}},\n \t]}},\n \t\"aggs\": {\"distinct ip\": {\"terms\": {\"field\": \"ip\",\"size\": 10000}}}\n \n\t}\n\treturn query\n\ndef Dns_resolved_check_query(ip_list,root_dns_list, time):\n size = len(ip_list)\n query = {\n \"size\": 0,\n \"query\": {\"bool\": {\"must\": [\n {\"range\": {\"date\": time}},\n {\"terms\": {\"ip\": ip_list }}\n ]}},\n\"aggs\": {\n \"ip\": {\n \"terms\": {\n \"field\": \"ip\",\n \"size\": size\n }, \"aggs\": {\n \"dns\": {\n \"terms\": {\n \"field\": \"domain_name.keyword\",\n \"size\": 1000,\n \"script\": {\n \"source\": \"\"\"\n def a=doc['domain_name.keyword'].value;\n def len=a.length();\n def split_path=a.splitOnToken('.');\n def rr=split_path.length;\n def sw=split_path[rr-1];\n def port=sw.indexOf(':'); \n def dns_list = [];\n dns_list = {dns};\n def result = [];\n \n if(port>0){{ len=port; sw=sw.substring(0,len) }} \n def final='';\n final+=split_path[rr-2];\n final+='.';\n final+=sw; \n \n for(int i=0;i0;a--){{path.add(org.substring(a-1,a))}} firstIndex=path.indexOf('.'); \n s2=org.substring(firstIndex+1,len); le=s2.length(); for(int b=le;b>0;b--){{path2.add(org.substring(b-1,b));}} \n secondIndex=path2.indexOf('.'); g=firstIndex+secondIndex+1; g=len-g; port=org.indexOf(':'); if(port>0){{len=port}} \n if(secondIndex==-1 || firstIndex==0){{g=0}} for(int b=g;b\n\nCOLOR_LIST = ['b',\n 'g',\n 'r',\n 'c',\n 'm',\n 'y',\n 'k',\n 'b',\n 'g',\n 'r',\n 'c',\n 'm',\n 'y',\n 'k'\n ]\n\n# used for legend\nLINE = 'line'\nPATCH = 'patch'\nSCATTER = 'scatter'\n\n# from matplotlib import cbook\n\n# class DataCursor(object):\n# \"\"\"A simple data cursor widget that displays the x,y location of a\n# matplotlib artist when it is selected.\"\"\"\n# def __init__(self, artists, tolerance=5, offsets=(-20, 20), \n# template='x: %0.2f\\ny: %0.2f', display_all=False):\n# \"\"\"Create the data cursor and connect it to the relevant figure.\n# \"artists\" is the matplotlib artist or sequence of artists that will be \n# selected. \n# \"tolerance\" is the radius (in points) that the mouse click must be\n# within to select the artist.\n# \"offsets\" is a tuple of (x,y) offsets in points from the selected\n# point to the displayed annotation box\n# \"template\" is the format string to be used. Note: For compatibility\n# with older versions of python, this uses the old-style (%) \n# formatting specification.\n# \"display_all\" controls whether more than one annotation box will\n# be shown if there are multiple axes. Only one will be shown\n# per-axis, regardless. \n# \"\"\"\n# self.template = template\n# self.offsets = offsets\n# self.display_all = display_all\n# if not cbook.iterable(artists):\n# artists = [artists]\n# self.artists = artists\n# self.axes = tuple(set(art.axes for art in self.artists))\n# self.figures = tuple(set(ax.figure for ax in self.axes))\n# \n# self.annotations = {}\n# for ax in self.axes:\n# self.annotations[ax] = self.annotate(ax)\n# \n# for artist in self.artists:\n# artist.set_picker(tolerance)\n# for fig in self.figures:\n# fig.canvas.mpl_connect('pick_event', self)\n# \n# def annotate(self, ax):\n# \"\"\"Draws and hides the annotation box for the given axis \"ax\".\"\"\"\n# annotation = ax.annotate(self.template, xy=(0, 0), ha='right',\n# xytext=self.offsets, textcoords='offset points', va='bottom',\n# bbox=dict(boxstyle='round,pad=0.5', fc='yellow', alpha=1.0),\n# arrowprops=dict(arrowstyle='->', connectionstyle='arc3,rad=0')\n# )\n# annotation.set_visible(False)\n# return annotation\n# \n# def __call__(self, event):\n# \"\"\"Intended to be called through \"mpl_connect\".\"\"\"\n# # Rather than trying to interpolate, just display the clicked coords\n# # This will only be called if it's within \"tolerance\", anyway.\n# selected = None\n# \n# if isinstance(event.artist, mpl.collections.PathCollection):\n# print event.artist.get_paths()\n# \n# print selected\n# x, y = event.mouseevent.xdata, event.mouseevent.ydata\n# annotation = self.annotations[event.artist.axes]\n# if x is not None:\n# if not self.display_all:\n# # Hide any other annotation boxes...\n# for ann in self.annotations.values():\n# ann.set_visible(False)\n# # Update the annotation in the current axis..\n# annotation.xy = x, y\n# annotation.set_text(self.template % (x, y))\n# annotation.set_visible(True)\n# event.canvas.draw()\n\ndef make_legend(categories,\n ax,\n ncol=3,\n legend_type=LINE,\n alpha=1):\n '''\n Helper function responsible for making the legend\n\n Parameters\n ----------\n categories : str or tuple\n the categories in the legend\n ax : axes instance \n the axes with which the legend is associated\n ncol : int\n the number of columns to use\n legend_type : {LINES, SCATTER, PATCH}\n whether the legend is linked to lines, patches, or scatter \n plots\n alpha : float\n the alpha of the artists\n \n '''\n \n some_identifiers = []\n labels = []\n for i, category in enumerate(categories):\n if legend_type == LINE: \n artist = plt.Line2D([0,1], [0,1], color=COLOR_LIST[i], \n alpha=alpha) #TODO\n elif legend_type == SCATTER:\n# marker_obj = mpl.markers.MarkerStyle('o')\n# path = marker_obj.get_path().transformed(\n# marker_obj.get_transform())\n# artist = mpl.collections.PathCollection((path,),\n# sizes = [20],\n# facecolors = COLOR_LIST[i],\n# edgecolors = 'k',\n# offsets = (0,0)\n# )\n # TODO work arround, should be a proper proxyartist for scatter legends\n artist = mpl.lines.Line2D([0],[0], linestyle=\"none\", c=COLOR_LIST[i], marker = 'o')\n\n elif legend_type == PATCH:\n artist = plt.Rectangle((0,0), 1,1, edgecolor=COLOR_LIST[i],\n facecolor=COLOR_LIST[i], alpha=alpha)\n\n some_identifiers.append(artist)\n \n if type(category) == tuple:\n label = '%.2f - %.2f' % category \n else:\n label = category\n \n labels.append(str(label))\n \n ax.legend(some_identifiers, labels, ncol=ncol,\n loc=3, borderaxespad=0.1,\n mode='expand', bbox_to_anchor=(0., 1.1, 1., .102))\n\n\n\n\n","sub_path":"prim/plotting_util.py","file_name":"plotting_util.py","file_ext":"py","file_size_in_byte":6142,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"44845556","text":"from ROOT import *\nfrom sys import argv\nimport CMS_lumi, tdrstyle\n\n#change the CMS_lumi variables (see CMS_lumi.py)\nCMS_lumi.lumi_13TeV = \"2.3 fb^{-1}\"\nCMS_lumi.writeExtraText = 1\nCMS_lumi.extraText = \"Preliminary\"\nCMS_lumi.lumi_sqrtS = \"13 TeV\" # used with iPeriod = 0, e.g. for simulation-only plots (default is an empty string)\niPos = 33\nif( iPos==0 ): CMS_lumi.relPosX = 0.12\n\nH_ref = 600;\nW_ref = 800;\nW = W_ref\nH = H_ref\n\niPeriod = 4\n\n# references for T, B, L, R\nT = 0.08*H_ref\nB = 0.12*H_ref \nL = 0.12*W_ref\nR = 0.04*W_ref\n\ncanvas = TCanvas(\"c2\",\"c2\",50,50,W,H)\ncanvas.SetFillColor(0)\ncanvas.SetBorderMode(0)\ncanvas.SetFrameFillStyle(0)\ncanvas.SetFrameBorderMode(0)\ncanvas.SetLeftMargin( L/W )\ncanvas.SetRightMargin( R/W )\ncanvas.SetTopMargin( T/H )\ncanvas.SetBottomMargin( B/H )\ncanvas.SetTickx(0)\ncanvas.SetTicky(0)\nframe = canvas.GetFrame()\n\n\n#f = TFile(\"StOpt_ADD_plot.root\")\nf = TFile(\"StOpt_ADDv2_plot.root\")\nf2 = TFile(\"StOpt_RS1_plot.root\")\n#QBHADD_n1 = f.Get(\"QBH_ADD_n1\")\nQBHADD_n1 = f2.Get(\"QBH_RS1_n1\")\nQBHADD_n2 = f.Get(\"QBH_ADD_n2\")\nQBHADD_n3 = f.Get(\"QBH_ADD_n3\")\nQBHADD_n4 = f.Get(\"QBH_ADD_n4\")\nQBHADD_n5 = f.Get(\"QBH_ADD_n5\")\nQBHADD_n6 = f.Get(\"QBH_ADD_n6\")\n\ngraphs = [QBHADD_n1,QBHADD_n2,QBHADD_n3,QBHADD_n4,QBHADD_n5,QBHADD_n6]\nLColor =[kBlue, kGreen, kOrange, kRed, kViolet, 12]\nFColor =[kBlue, kGreen, kOrange, kRed, kViolet, 12]\nMStyle =[kFullCircle,kFullSquare, kFullTriangleUp,kOpenSquare,kOpenCircle,kOpenSquare]\n \niGraphs=0\nfor g in graphs:\n\tg.SetLineColor( LColor[iGraphs])\n\tg.SetFillColor( FColor[iGraphs])\n\tg.SetMarkerStyle(MStyle[iGraphs])\n\tg.SetMarkerColor(FColor[iGraphs])\n\tg.SetLineWidth(2)\n\tiGraphs+=1\n\nmg = TMultiGraph()\n\nmg.Add(QBHADD_n1)\nmg.Add(QBHADD_n2)\nmg.Add(QBHADD_n3)\nmg.Add(QBHADD_n4)\nmg.Add(QBHADD_n5)\nmg.Add(QBHADD_n6)\n\nmg.SetMinimum(5)\nmg.SetMaximum(10)\n\nmg.Draw(\"ALP\")\nmg.GetXaxis().SetTitle(\"MD (TeV)\")\nmg.GetYaxis().SetTitle(\"Excluded M_{BH}^{min} (TeV)\")\nmg.SetTitle(\"\")\n\nCMS_lumi.CMS_lumi(canvas, iPeriod, iPos)\ncanvas.cd()\ncanvas.Update()\ncanvas.RedrawAxis()\nframe = canvas.GetFrame()\nframe.Draw()\n\nleg= TLegend(0.15,0.15,0.4,0.4, \"QBH\", \"brNDC\")\nleg.AddEntry(QBHADD_n1,\"RS1\",\"pl\")\nleg.AddEntry(QBHADD_n2,\"ADD n=2\",\"pl\")\nleg.AddEntry(QBHADD_n3,\"ADD n=3\",\"pl\")\nleg.AddEntry(QBHADD_n4,\"ADD n=4\",\"pl\")\nleg.AddEntry(QBHADD_n5,\"ADD n=5\",\"pl\")\nleg.AddEntry(QBHADD_n6,\"ADD n=6\",\"pl\")\nleg.SetBorderSize(0)\nleg.Draw()\nleg.SetTextFont(42)\nleg.SetTextSize(0.045)\n\ncanvas.SaveAs(\"ADD_RS1_limit_final.pdf\")\n","sub_path":"plots/drawADD.py","file_name":"drawADD.py","file_ext":"py","file_size_in_byte":2455,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"96187648","text":"# Write a program which will find all such numbers which are divisible by 7 but are not a multiple of 5,\n# between 2000 and 3200 (both included).\n# The numbers obtained should be printed in a comma-separated sequence on a single line.\n\n\n\ndef main():\n min_limit = 2000\n max_limit = 3200\n\n output_list = []\n for i in range(min_limit, max_limit+1):\n if (i % 7 == 0) and (i % 5 != 0):\n print(i, end=\", \")\n\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"day1/problem1.py","file_name":"problem1.py","file_ext":"py","file_size_in_byte":472,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"362861445","text":"import time\n\nfrom selenium import webdriver\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.support import expected_conditions\nfrom selenium.webdriver.support.wait import WebDriverWait\n\ndriver = webdriver.Chrome(executable_path=\"C:\\\\Users\\\\indrasen\\\\Documents\\\\chromedriver_win32\\\\chromedriver.exe\")\ndriver.get(\"https://rahulshettyacademy.com/seleniumPractise/#/\")\ndriver.find_element_by_css_selector(\"input.search-keyword\").send_keys(\"ber\")\ntime.sleep(4)\ncount = len(driver.find_elements_by_xpath(\"//div[@class='products']/div\"))\nassert count == 3\nbuttons = driver.find_elements_by_xpath(\"//div[@class='product-action']/button\")\n\nfor i in buttons:\n i.click()\n\ndriver.find_element_by_css_selector(\"img[alt='Cart']\").click()\ndriver.find_element_by_xpath(\"//button[text()='PROCEED TO CHECKOUT']\").click()\nwait = WebDriverWait(driver, 8)\nwait.until(expected_conditions.presence_of_element_located((By.CSS_SELECTOR, \"input.promoCode\")))\ndriver.find_element_by_css_selector(\"input.promoCode\").send_keys(\"rahulshettyacademy\")\ndriver.find_element_by_css_selector(\"button.promoBtn\").click()\nwait.until(expected_conditions.presence_of_element_located((By.CSS_SELECTOR, \"span.promoInfo\")))\nprint(driver.find_element_by_css_selector(\"span.promoInfo\").text)","sub_path":"PracticePrograms/explicitwait.py","file_name":"explicitwait.py","file_ext":"py","file_size_in_byte":1268,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"6133200","text":"import json\nimport os\n\nimport contextlib2\nfrom requests_toolbelt import MultipartEncoder\nimport trafaret as t\n\nfrom datarobot._compat import Int, String\nfrom datarobot.models.api_object import APIObject\nfrom datarobot.models.custom_model_version import CustomDependency, CustomModelFileItem\nfrom datarobot.utils import encode_utf8_if_py2\nfrom datarobot.utils.pagination import unpaginate\n\n\nclass CustomTaskFileItem(CustomModelFileItem):\n \"\"\"A file item attached to a DataRobot custom task version.\n\n .. versionadded:: v2.26\n\n Attributes\n ----------\n id: str\n id of the file item\n file_name: str\n name of the file item\n file_path: str\n path of the file item\n file_source: str\n source of the file item\n created_at: str\n ISO-8601 formatted timestamp of when the version was created\n \"\"\"\n\n _converter = t.Dict(\n {\n t.Key(\"id\"): String(),\n t.Key(\"file_name\"): String(),\n t.Key(\"file_path\"): String(),\n t.Key(\"file_source\"): String(),\n t.Key(\"created\") >> \"created_at\": String(),\n }\n ).ignore_extra(\"*\")\n\n schema = _converter\n\n\nclass CustomTaskVersion(APIObject):\n \"\"\"A version of a DataRobot custom task.\n\n .. versionadded:: v2.26\n\n Attributes\n ----------\n id: str\n id of the custom task version\n custom_task_id: str\n id of the custom task\n version_minor: int\n a minor version number of custom task version\n version_major: int\n a major version number of custom task version\n label: str\n short human readable string to label the version\n created_at: str\n ISO-8601 formatted timestamp of when the version was created\n is_frozen: bool\n a flag if the custom task version is frozen\n items: List[CustomTaskFileItem]\n a list of file items attached to the custom task version\n description: str, optional\n custom task version description\n required_metadata: Dict[str, str]\n Additional parameters required by the execution environment. The required keys are\n defined by the fieldNames in the base envionment's requiredMetadataKeys. Once set,\n they cannot be changed. If you want to change them, make a new version.\n base_environment_id: str, optional\n id of the environment to use with the task\n base_environment_version_id: str, optional\n id of the environment version to use with the task\n dependencies: List[CustomDependency]\n the parsed dependencies of the custom task version if the\n version has a valid requirements.txt file\n \"\"\"\n\n _path = \"customTasks/{}/versions/\"\n\n _converter = t.Dict(\n {\n t.Key(\"id\"): String(),\n t.Key(\"custom_task_id\"): String(),\n t.Key(\"version_major\"): Int(),\n t.Key(\"version_minor\"): Int(),\n t.Key(\"label\"): String(),\n t.Key(\"created\") >> \"created_at\": String(),\n t.Key(\"is_frozen\"): t.Bool(),\n t.Key(\"items\"): t.List(CustomTaskFileItem.schema),\n # because `from_server_data` scrubs Nones, this must be optional here.\n t.Key(\"description\", optional=True): String(max_length=10000, allow_blank=True)\n | t.Null(),\n t.Key(\"required_metadata\", optional=True): t.Mapping(String(), String()),\n t.Key(\"base_environment_id\", optional=True): String() | t.Null(),\n t.Key(\"base_environment_version_id\", optional=True): String() | t.Null(),\n t.Key(\"dependencies\", optional=True): t.List(CustomDependency.schema),\n }\n ).ignore_extra(\"*\")\n\n schema = _converter\n\n def __init__(\n self,\n id,\n custom_task_id,\n version_major,\n version_minor,\n label,\n created_at,\n is_frozen,\n items,\n description=None,\n required_metadata=None,\n base_environment_id=None,\n base_environment_version_id=None,\n dependencies=None,\n ):\n if required_metadata is None:\n required_metadata = {}\n if dependencies is None:\n dependencies = []\n\n self.id = id\n self.custom_task_id = custom_task_id\n self.description = description\n self.version_major = version_major\n self.version_minor = version_minor\n self.label = label\n self.created_at = created_at\n self.is_frozen = is_frozen\n self.items = [CustomTaskFileItem(**data) for data in items]\n\n self.required_metadata = required_metadata\n self.base_environment_id = base_environment_id\n self.base_environment_version_id = base_environment_version_id\n self.dependencies = [CustomDependency(**data) for data in dependencies]\n\n def __repr__(self):\n return encode_utf8_if_py2(\n u\"{}({!r})\".format(self.__class__.__name__, self.label or self.id)\n )\n\n def _update_values(self, new_response):\n # type (CustomTaskVersion) -> None\n for attr in self._fields():\n new_value = getattr(new_response, attr)\n setattr(self, attr, new_value)\n\n @classmethod\n def _all_versions_path(cls, task_id):\n # type: (str) -> str\n return cls._path.format(task_id)\n\n @classmethod\n def _single_version_path(cls, task_id, version_id):\n # type: (str, str) -> str\n return cls._all_versions_path(task_id) + \"{}/\".format(version_id)\n\n @classmethod\n def from_server_data(cls, data, keep_attrs=None):\n initial = super(CustomTaskVersion, cls).from_server_data(data, keep_attrs)\n # from_server_data will make the keys in requiredMetadata lowercase,\n # which is not OK. we need to preserve case\n initial.required_metadata = data.get(\"requiredMetadata\")\n return initial\n\n @classmethod\n def create_clean(\n cls,\n custom_task_id,\n base_environment_id,\n is_major_update=True,\n folder_path=None,\n required_metadata=None,\n ):\n \"\"\"Create a custom task version without files from previous versions.\n\n .. versionadded:: v2.26\n\n Parameters\n ----------\n custom_task_id: str\n the id of the custom task\n base_environment_id: str\n the id of the base environment to use with the custom task version\n is_major_update: bool, optional\n if the current version is 2.3, `True` would set the new version at `3.0`.\n `False` would set the new version at `2.4`.\n Default to `True`\n folder_path: str, optional\n the path to a folder containing files to be uploaded.\n Each file in the folder is uploaded under path relative\n to a folder path\n required_metadata: Dict[str, str]\n Additional parameters required by the execution environment. The required keys are\n defined by the fieldNames in the base envionment's requiredMetadataKeys. Once set,\n they cannot be changed. If you to change them, make a new version.\n\n Returns\n -------\n CustomTaskVersion\n created custom task version\n\n Raises\n ------\n datarobot.errors.ClientError\n if the server responded with 4xx status\n datarobot.errors.ServerError\n if the server responded with 5xx status\n \"\"\"\n return cls._create(\n \"post\",\n custom_task_id,\n is_major_update,\n base_environment_id,\n folder_path,\n required_metadata=required_metadata,\n )\n\n @classmethod\n def create_from_previous(\n cls,\n custom_task_id,\n base_environment_id,\n is_major_update=True,\n folder_path=None,\n files_to_delete=None,\n required_metadata=None,\n ):\n \"\"\"Create a custom task version containing files from a previous version.\n\n .. versionadded:: v2.26\n\n Parameters\n ----------\n custom_task_id: str\n the id of the custom task\n base_environment_id: str\n the id of the base environment to use with the custom task version\n is_major_update: bool, optional\n if the current version is 2.3, `True` would set the new version at `3.0`.\n `False` would set the new version at `2.4`.\n Default to `True`\n folder_path: str, optional\n the path to a folder containing files to be uploaded.\n Each file in the folder is uploaded under path relative\n to a folder path\n files_to_delete: list, optional\n the list of a file items ids to be deleted\n Example: [\"5ea95f7a4024030aba48e4f9\", \"5ea6b5da402403181895cc51\"]\n required_metadata: Dict[str, str]\n Additional parameters required by the execution environment. The required keys are\n defined by the fieldNames in the base envionment's requiredMetadataKeys. Once set,\n they cannot be changed. If you to change them, make a new version.\n\n Returns\n -------\n CustomTaskVersion\n created custom task version\n\n Raises\n ------\n datarobot.errors.ClientError\n if the server responded with 4xx status\n datarobot.errors.ServerError\n if the server responded with 5xx status\n \"\"\"\n return cls._create(\n \"patch\",\n custom_task_id,\n is_major_update,\n base_environment_id,\n folder_path,\n files_to_delete=files_to_delete,\n required_metadata=required_metadata,\n )\n\n @classmethod\n def _create(\n cls,\n method,\n custom_task_id,\n is_major_update,\n base_environment_id,\n folder_path=None,\n files_to_delete=None,\n required_metadata=None,\n ):\n url = cls._all_versions_path(custom_task_id)\n\n upload_data = [\n (\"isMajorUpdate\", str(is_major_update)),\n (\"baseEnvironmentId\", base_environment_id),\n ]\n if files_to_delete:\n upload_data += [(\"filesToDelete\", file_id) for file_id in files_to_delete]\n if required_metadata:\n upload_data.append((\"requiredMetadata\", json.dumps(required_metadata)))\n\n cls._verify_folder_path(folder_path)\n\n with contextlib2.ExitStack() as stack:\n if folder_path:\n for dir_name, _, file_names in os.walk(folder_path):\n for file_name in file_names:\n file_path = os.path.join(dir_name, file_name)\n file = stack.enter_context(open(file_path, \"rb\"))\n\n upload_data.append((\"file\", (os.path.basename(file_path), file)))\n upload_data.append((\"filePath\", os.path.relpath(file_path, folder_path)))\n\n encoder = MultipartEncoder(fields=upload_data)\n headers = {\"Content-Type\": encoder.content_type}\n response = cls._client.request(method, url, data=encoder, headers=headers)\n return cls.from_server_data(response.json())\n\n @staticmethod\n def _verify_folder_path(folder_path):\n if folder_path and not os.path.exists(folder_path):\n raise ValueError(\"The folder: {} does not exist.\".format(folder_path))\n\n @classmethod\n def list(cls, custom_task_id):\n \"\"\"List custom task versions.\n\n .. versionadded:: v2.26\n\n Parameters\n ----------\n custom_task_id: str\n the id of the custom task\n\n Returns\n -------\n List[CustomTaskVersion]\n a list of custom task versions\n\n Raises\n ------\n datarobot.errors.ClientError\n if the server responded with 4xx status\n datarobot.errors.ServerError\n if the server responded with 5xx status\n \"\"\"\n url = cls._all_versions_path(custom_task_id)\n data = unpaginate(url, None, cls._client)\n return [cls.from_server_data(item) for item in data]\n\n @classmethod\n def get(cls, custom_task_id, custom_task_version_id):\n \"\"\"Get custom task version by id.\n\n .. versionadded:: v2.26\n\n Parameters\n ----------\n custom_task_id: str\n the id of the custom task\n custom_task_version_id: str\n the id of the custom task version to retrieve\n\n Returns\n -------\n CustomTaskVersion\n retrieved custom task version\n\n Raises\n ------\n datarobot.errors.ClientError\n if the server responded with 4xx status.\n datarobot.errors.ServerError\n if the server responded with 5xx status.\n \"\"\"\n path = cls._single_version_path(custom_task_id, custom_task_version_id)\n return cls.from_location(path)\n\n def download(self, file_path):\n \"\"\"Download custom task version.\n\n .. versionadded:: v2.26\n\n Parameters\n ----------\n file_path: str\n path to create a file with custom task version content\n\n Raises\n ------\n datarobot.errors.ClientError\n if the server responded with 4xx status.\n datarobot.errors.ServerError\n if the server responded with 5xx status.\n \"\"\"\n\n response = self._client.get(\n self._single_version_path(self.custom_task_id, self.id) + \"download/\"\n )\n with open(file_path, \"wb\") as f:\n f.write(response.content)\n\n def update(self, description=None, required_metadata=None):\n \"\"\"Update custom task version properties.\n\n .. versionadded:: v2.26\n\n Parameters\n ----------\n description: str\n new custom task version description\n required_metadata: Dict[str, str]\n Additional parameters required by the execution environment. The required keys are\n defined by the fieldNames in the base envionment's requiredMetadataKeys. Once set,\n they cannot be changed. If you to change them, make a new version.\n\n Raises\n ------\n datarobot.errors.ClientError\n if the server responded with 4xx status.\n datarobot.errors.ServerError\n if the server responded with 5xx status.\n \"\"\"\n payload = {}\n if description:\n payload.update({\"description\": description})\n if required_metadata:\n payload.update({\"requiredMetadata\": required_metadata})\n\n url = self._path.format(self.custom_task_id)\n path = \"{}{}/\".format(url, self.id)\n\n response = self._client.patch(path, data=payload)\n\n data = response.json()\n new_version = CustomTaskVersion.from_server_data(data)\n self._update_values(new_version)\n\n def refresh(self):\n \"\"\"Update custom task version with the latest data from server.\n\n .. versionadded:: v2.26\n\n Raises\n ------\n datarobot.errors.ClientError\n if the server responded with 4xx status\n datarobot.errors.ServerError\n if the server responded with 5xx status\n \"\"\"\n\n new_object = self.get(self.custom_task_id, self.id)\n self._update_values(new_object)\n","sub_path":"datarobot/models/custom_task_version.py","file_name":"custom_task_version.py","file_ext":"py","file_size_in_byte":15291,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"227354613","text":"from __future__ import annotations\n\nimport contextlib\nimport typing\nimport uuid\n\nfrom django.core.exceptions import ObjectDoesNotExist\nfrom django.utils.translation import gettext_lazy as _\nfrom rest_framework.fields import IntegerField, UUIDField\nfrom rest_framework.pagination import BasePagination\nfrom rest_framework.serializers import Serializer\nfrom rest_framework.utils.urls import replace_query_param, remove_query_param\nfrom rest_framework.exceptions import NotFound\n\nfrom restdoctor.constants import DEFAULT_PAGE_SIZE, DEFAULT_MAX_PAGE_SIZE\nfrom restdoctor.rest_framework.response import ResponseWithMeta\n\nif typing.TYPE_CHECKING:\n from django.db.models import QuerySet\n from rest_framework.request import Request\n from rest_framework.views import APIView\n\n from restdoctor.rest_framework.schema.custom_types import OpenAPISchema\n\n OptionalList = typing.Optional[typing.List[typing.Any]]\n Lookup = typing.Dict[str, typing.Any]\n OptionalLookup = typing.Optional[Lookup]\n\n\nclass PerPageSerializerBase(Serializer):\n per_page = IntegerField(default=DEFAULT_PAGE_SIZE, allow_null=True,\n help_text='Количество элементов на странице')\n\n def __init__(\n self, max_per_page: int = 200,\n *args: typing.Any, **kwargs: typing.Any,\n ) -> None:\n super().__init__(*args, **kwargs)\n self.max_per_page = max_per_page\n\n def validate_per_page(self, value: typing.Optional[int]) -> typing.Optional[int]:\n if value and value > self.max_per_page:\n return self.max_per_page\n return value\n\n\nclass PaginatorSerializer(PerPageSerializerBase):\n page = IntegerField(min_value=1, default=1, help_text='Выбранная страница, начиная с 1')\n\n\nclass PageNumberPagination(BasePagination):\n use_count = True\n page_query_param = 'page'\n page_size_query_param = 'per_page'\n serializer_class = PaginatorSerializer\n\n max_page_size = DEFAULT_MAX_PAGE_SIZE\n\n invalid_page_message = _('Invalid page.')\n\n def paginate_queryset(\n self, queryset: QuerySet, request: Request, view: APIView = None,\n ) -> OptionalList:\n serializer = self.serializer_class(data=request.query_params, max_per_page=self.max_page_size)\n serializer.is_valid(raise_exception=False)\n\n self.per_page = serializer.validated_data.get('per_page')\n self.page = serializer.validated_data.get('page', 1)\n\n if not self.per_page:\n return None\n\n self.has_next = False\n self.has_prev = (self.page > 1)\n\n base_url = request.build_absolute_uri()\n self.base_url = replace_query_param(base_url, self.page_size_query_param, self.per_page)\n self.request = request\n\n start_offset = (self.page - 1) * self.per_page\n stop_offset = start_offset + self.per_page + 1\n\n if self.use_count:\n self.total = len(queryset) if isinstance(queryset, list) else queryset.count()\n if self.total:\n self.pages, rem = divmod(self.total, self.per_page)\n if rem:\n self.pages += 1\n else:\n self.pages = 1\n if self.page > self.pages:\n msg = self.invalid_page_message.format(page_number=self.page)\n raise NotFound(msg)\n\n paginated = list(queryset[start_offset:stop_offset])\n\n if len(paginated) > self.per_page:\n self.has_next = True\n del paginated[-1]\n\n return paginated\n\n def get_page_link_tmpl(self) -> str:\n url_tmpl = self.request.build_absolute_uri()\n url_tmpl = replace_query_param(url_tmpl, self.page_size_query_param, self.per_page)\n return url_tmpl\n\n def get_page_link(self, page: typing.Any = 1) -> typing.Optional[str]:\n if page:\n return replace_query_param(self.base_url, self.page_query_param, page)\n\n def get_paginated_response(self, data: typing.Sequence[typing.Any]) -> ResponseWithMeta:\n meta = {\n self.page_query_param: self.page,\n self.page_size_query_param: self.per_page,\n 'url': self.get_page_link(page=self.page),\n }\n if self.use_count:\n meta['total'] = self.total\n\n if self.use_count and self.pages > 1:\n meta['last_url'] = self.get_page_link(page=self.pages)\n meta['next_url'] = self.get_page_link(page=self.page + 1) if self.has_next else None\n meta['prev_url'] = self.get_page_link(page=self.page - 1) if self.has_prev else None\n\n return ResponseWithMeta(data=data, meta=meta)\n\n def get_paginated_response_schema(self, schema: OpenAPISchema) -> OpenAPISchema:\n meta = schema['properties'].get('meta', {'type': 'object', 'properties': {}})\n meta['properties'] = {\n self.page_query_param: {\n 'type': 'integer',\n },\n self.page_size_query_param: {\n 'type': 'integer',\n 'example': 20,\n 'maximum': self.max_page_size,\n },\n 'total': {\n 'type': 'integer',\n 'example': 100500,\n },\n 'last_url': {\n 'type': 'string',\n 'nullable': True,\n },\n 'next_url': {\n 'type': 'string',\n 'nullable': True,\n },\n 'prev_url': {\n 'type': 'string',\n 'nullable': True,\n },\n }\n schema['properties']['meta'] = meta\n return schema\n\n\nclass PageNumberUncountedPagination(PageNumberPagination):\n use_count = False\n\n\nclass CursorUUIDSerializer(PerPageSerializerBase):\n after = UUIDField(required=False, allow_null=True, help_text=_('After UUID'))\n before = UUIDField(required=False, allow_null=True, help_text=_('Before UUID'))\n\n\ndef get_order(default_order: str, serializer_keys: typing.Sequence[str]) -> str:\n if 'after' in serializer_keys:\n return 'after'\n if 'before' in serializer_keys:\n return 'before'\n return default_order\n\n\ndef get_cursor(\n queryset: QuerySet,\n after_uuid: uuid.UUID = None,\n before_uuid: uuid.UUID = None,\n default_order: str = None,\n) -> typing.Tuple[typing.Any, str]:\n cursor_obj = None\n if after_uuid is not None:\n with contextlib.suppress(ObjectDoesNotExist):\n cursor_obj = queryset.get(uuid=after_uuid)\n order = 'after'\n elif before_uuid is not None:\n with contextlib.suppress(ObjectDoesNotExist):\n cursor_obj = queryset.get(uuid=before_uuid)\n order = 'before'\n if cursor_obj is None:\n order = default_order or ''\n return cursor_obj, order\n\n\nclass CursorUUIDPagination(BasePagination):\n use_count = True\n\n after_query_param = 'after'\n before_query_param = 'before'\n page_size_query_param = 'per_page'\n\n lookup_by_field = 'timestamp'\n order_by_field = 'timestamp'\n default_order = 'before'\n\n serializer_class = CursorUUIDSerializer\n\n max_page_size = DEFAULT_MAX_PAGE_SIZE\n\n def get_lookup(self) -> OptionalLookup:\n if self.cursor_obj:\n lookup_operator = 'gt' if self.order == 'after' else 'lt'\n lookup_keyword = f'{self.lookup_by_field}__{lookup_operator}'\n return {lookup_keyword: getattr(self.cursor_obj, self.lookup_by_field)}\n\n def paginate_queryset(\n self, queryset: QuerySet, request: Request, view: APIView = None,\n ) -> OptionalList:\n serializer = self.serializer_class(data=request.query_params, max_per_page=self.max_page_size)\n serializer.is_valid(raise_exception=True)\n\n self.per_page = serializer.validated_data.get(self.page_size_query_param)\n\n if not self.per_page:\n return None\n\n after_uuid = serializer.validated_data.get(self.after_query_param)\n before_uuid = serializer.validated_data.get(self.before_query_param)\n\n order = get_order(self.default_order, serializer.validated_data.keys())\n self.cursor_obj, self.order = get_cursor(queryset, after_uuid, before_uuid, order)\n\n lookup = self.get_lookup()\n if lookup:\n queryset = queryset.filter(**lookup)\n\n order_sign = '-' if self.order == 'before' else ''\n order_keyword = f'{order_sign}{self.order_by_field}'\n queryset = queryset.order_by(order_keyword)\n\n base_url = request.build_absolute_uri()\n self.base_url = replace_query_param(base_url, self.page_size_query_param, self.per_page)\n self.request = request\n self.has_next = False\n\n start_offset = 0\n stop_offset = start_offset + self.per_page + 1\n\n if self.use_count:\n self.total = queryset.count()\n\n paginated = list(queryset[:stop_offset])\n\n if len(paginated) > self.per_page:\n self.has_next = True\n del paginated[-1]\n\n if paginated:\n self.page_boundaries = (\n paginated[0].uuid,\n paginated[-1].uuid,\n )\n elif self.cursor_obj:\n self.page_boundaries = (self.cursor_obj.uuid, self.cursor_obj.uuid)\n else:\n self.page_boundaries = (None, None)\n\n return paginated\n\n def get_page_link_tmpl(self) -> str:\n url_tmpl = self.request.build_absolute_uri()\n url_tmpl = replace_query_param(url_tmpl, self.page_size_query_param, self.per_page)\n return url_tmpl\n\n def get_page_link(self, after: typing.Any = None, before: typing.Any = None) -> typing.Optional[str]:\n if after is not None:\n base_url = remove_query_param(self.base_url, self.before_query_param)\n return replace_query_param(base_url, self.after_query_param, after)\n if before is not None:\n base_url = remove_query_param(self.base_url, self.after_query_param)\n return replace_query_param(base_url, self.before_query_param, before)\n\n def get_paginated_response(self, data: typing.Sequence[typing.Any]) -> ResponseWithMeta:\n meta = {\n self.page_size_query_param: self.per_page,\n 'has_next': self.has_next,\n }\n cursor_uuid = None\n if self.cursor_obj:\n cursor_uuid = self.cursor_obj.uuid\n meta[self.order] = cursor_uuid\n meta['url'] = self.get_page_link(**{self.order: cursor_uuid or ''})\n\n if self.use_count:\n meta['total'] = self.total\n\n if self.page_boundaries[0]:\n after_idx, before_idx = 0, 1\n if self.order == 'after':\n after_idx, before_idx = 1, 0\n\n meta['after_url'] = self.get_page_link(\n **{self.after_query_param: self.page_boundaries[after_idx]})\n meta['before_url'] = self.get_page_link(\n **{self.before_query_param: self.page_boundaries[before_idx]})\n\n return ResponseWithMeta(data=data, meta=meta)\n\n def get_paginated_response_schema(self, schema: OpenAPISchema) -> OpenAPISchema:\n meta = schema['properties'].get('meta', {'type': 'object', 'properties': {}})\n meta['properties'] = {\n self.page_size_query_param: {\n 'type': 'integer',\n 'maximum': self.max_page_size,\n 'example': 20,\n },\n 'has_next': {\n 'type': 'boolean',\n 'example': True,\n },\n 'before': {\n 'type': 'uuid',\n 'nullable': True,\n 'required': False,\n },\n 'after': {\n 'type': 'uuid',\n 'nullable': True,\n 'required': False,\n },\n 'total': {\n 'type': 'integer',\n 'example': 123,\n 'required': False,\n },\n 'url': {\n 'type': 'string',\n 'nullable': False,\n },\n 'last_url': {\n 'type': 'string',\n 'nullable': True,\n },\n 'after_url': {\n 'type': 'string',\n 'nullable': True,\n },\n 'before_url': {\n 'type': 'string',\n 'nullable': True,\n },\n }\n schema['properties']['meta'] = meta\n return schema\n\n\nclass CursorUUIDUncountedPagination(PageNumberPagination):\n use_count = False\n","sub_path":"restdoctor/rest_framework/pagination.py","file_name":"pagination.py","file_ext":"py","file_size_in_byte":12475,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"94062651","text":"#!coding=utf-8\r\nfrom flask import Flask,jsonify,render_template\r\n\r\n\r\napp = Flask(__name__)\r\n\r\n@app.route('/')\r\ndef homework():\r\n return render_template('index.html')\r\n\r\n@app.route('/data')\r\ndef putdata():\r\n somebody=[\r\n {'name':'冯七','sex':'male','actor':'Michael Emerson','img':'feng7'},\r\n {'name':'root','sex':'female','actor':'Amy Acker','img':'amy'},\r\n {'name':'李四','sex':'male','actor':'James Patrick Caviezel','img':'li4'},\r\n {'name':'肖','sex':'female','actor':'Sarah Shahi','img':'shaw'},\r\n\r\n ]\r\n return jsonify(somebody=somebody)\r\n\r\nif __name__ == '__main__':\r\n app.run(port=8080)\r\n","sub_path":"homework.py","file_name":"homework.py","file_ext":"py","file_size_in_byte":674,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"368037634","text":"#!/usr/bin/env python\n##############################################################################\n# Copyright (c) 2020 Orange, Inc. and others. All rights reserved.\n#\n# All rights reserved. This program and the accompanying materials\n# are made available under the terms of the Apache License, Version 2.0\n# which accompanies this distribution, and is available at\n# http://www.apache.org/licenses/LICENSE-2.0\n##############################################################################\n\nimport os\n\nSIMS = {\n 'xpdra': {'port': '17840', 'configfile': 'oper-XPDRA.xml', 'logfile': 'oper-XPDRA.log'},\n 'roadma': {'port': '17841', 'configfile': 'oper-ROADMA.xml', 'logfile': 'oper-ROADMA.log'},\n 'roadmb': {'port': '17842', 'configfile': 'oper-ROADMB.xml', 'logfile': 'oper-ROADMB.log'},\n 'roadmc': {'port': '17843', 'configfile': 'oper-ROADMC.xml', 'logfile': 'oper-ROADMC.log'},\n 'roadmd': {'port': '17847', 'configfile': 'oper-ROADMD.xml', 'logfile': 'oper-ROADMD.log'},\n 'xpdrc': {'port': '17844', 'configfile': 'oper-XPDRC.xml', 'logfile': 'oper-XPDRC.log'},\n 'spdra': {'port': '17845', 'configfile': 'oper-SPDRA.xml', 'logfile': 'oper-SPDRA.log'},\n 'spdrc': {'port': '17846', 'configfile': 'oper-SPDRC.xml', 'logfile': 'oper-SPDRC.log'}\n}\n\nHONEYNODE_EXECUTABLE = os.path.join(\n os.path.dirname(os.path.realpath(__file__)),\n \"..\", \"..\", \"honeynode\", \"2.2.1\", \"honeynode-simulator\", \"honeycomb-tpce\")\nSAMPLES_DIRECTORY = os.path.join(\n os.path.dirname(os.path.realpath(__file__)),\n \"..\", \"..\", \"sample_configs\", \"openroadm\", \"2.2.1\")\n","sub_path":"tests/transportpce_tests/2.2.1/simulators.py","file_name":"simulators.py","file_ext":"py","file_size_in_byte":1576,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"479348564","text":"import pandas as pd\nimport tushare as ts\nimport pyecharts as pec\nimport os, time, datetime\nimport concurrent.futures\nimport json, pickle\n\n\n# pickle can be done by\n# explicit pickle every property and make them a dictionary, then call pickle\n# this could lead to a pre-processor and post-processor for property pickle\n# reference page is\n# https://docs.python.org/2.7/library/pickle.html#module-pickle\n# https://www.ibm.com/developerworks/cn/linux/l-pypers/index.html\n# http://www.cnblogs.com/itech/archive/2012/01/10/2318293.html\n# https://python.freelycode.com/contribution/detail/460\n\nclass PickleEnabler(object):\n 'define the interfaces to implement the pickle protocols'\n def __init__(self):\n self.pickle_storage={}\n\n # build pickle storage dictionary\n def pre_process_pickle(self):\n pass\n\n # restore pickle storage dictionary\n def post_process_pickle(self):\n pass\n\n def __getstate__(self):\n self.pre_process_pickle()\n return self.pickle_storage\n\n def __setstate__(self, state):\n self.pickle_storage = state\n self.post_process_pickle()\n del self.pickle_storage\n\nclass PickleDataTest(PickleEnabler):\n def __init__(self):\n self.df=None\n self.code=\"\"\n super(PickleDataTest, self).__init__()\n\n def pre_process_pickle(self):\n self.pickle_storage[\"df\"]=self.df.to_dict()\n self.pickle_storage[\"code\"]=self.code\n\n def post_process_pickle(self):\n if \"df\" in self.pickle_storage.keys():\n self.df = pd.DataFrame.from_dict(self.pickle_storage[\"df\"])\n if \"code\" in self.pickle_storage.keys():\n self.code = self.pickle_storage[\"code\"]\n\nclass DailySequentialStatus(object):\n def __init__(self, data_tuple=()):\n self.open = 0.0\n self.close = 0.0\n self.high = 0.0\n self.low = 0.0\n self.volume = 0\n self.total = 0.0\n self.zdf = 0.0\n self.code = \"\"\n\n # sampling price across the day\n self.sampling = []\n\n # load data if available\n if len(data_tuple) == 9:\n self.load_data(data_tuple)\n\n def dump_data(self):\n return (self.open, self.close, self.high, self.low,\n self.volume, self.total, self.zdf, self.code,\n self.sampling)\n\n def load_data(self, data_tuple=()):\n if len(data_tuple) == 9:\n (self.open, self.close, self.high,\n self.low, self.volume, self.total,\n self.zdf, self.code, self.sampling) = data_tuple\n\n # super(StkHelperData, self).__init__()\n\nclass StkHelperData(PickleEnabler):\n 'calculate and store the calculated statistics, for given stock'\n\n def __init__(self):\n # properties go here\n self.stk_code = \"\"\n\n # date->DailySequentialStatus\n self.seqential_status_map={}\n\n super(StkHelperData, self).__init__()\n\n # calculate the helper data by transaction data\n # input is the 5 minute series system\n def calculate_data(self, df=None):\n\n date_str_list = []\n [date_str_list.append(date_str) for date_str in df.index.get_level_values('date').unique()]\n\n for date_current in date_str_list:\n\n df_current = df.loc[date_current]\n\n sequential_status = DailySequentialStatus()\n sequential_status.open = df_current.iloc[0].open\n sequential_status.close = df_current.iloc[-1].close\n sequential_status.low = df_current['low'].min(axis=0)\n sequential_status.high = df_current['high'].max(axis=0)\n sequential_status.volume = df_current['volume'].sum(axis=0)\n sequential_status.total = df_current['total'].sum(axis=0)\n\n sequential_status.sampling = df_current['close'].tolist()\n\n date_current_index = date_str_list.index(date_current)\n if date_current_index >= 1:\n last_close = self.seqential_status_map[date_str_list[date_current_index-1]].close\n sequential_status.zdf = sequential_status.close/last_close - 1.0\n self.seqential_status_map[date_current] = sequential_status\n\n def pre_process_pickle(self):\n self.pickle_storage[\"stk_code\"] = self.stk_code\n temp_map = {}\n for key in self.seqential_status_map.keys():\n temp_map[key] = self.seqential_status_map[key].dump_data()\n self.pickle_storage[\"sequential_status_map\"] = temp_map\n\n def post_process_pickle(self):\n if \"stk_code\" in self.pickle_storage.keys():\n self.stk_code = self.pickle_storage[\"stk_code\"]\n if \"sequential_status_map\" in self.pickle_storage.keys():\n temp_map = self.pickle_storage[\"sequential_status_map\"]\n self.seqential_status_map={}\n for key in temp_map.keys():\n self.seqential_status_map[key] = DailySequentialStatus(temp_map[key])\n\n # save data\n def save_data(self, filename=\"\"):\n try:\n with open(filename, 'w') as f:\n pickle.dump((self.stk_code, self.seqential_status_map), f)\n return True\n except:\n return False\n\n # load data\n def load_data(self, filename=\"\"):\n try:\n with open(filename, 'r') as f:\n self.stk_code, self.seqential_status_map = pickle.load(filename)\n return True\n except:\n return False\n\n # update data with recent transactions\n def update_data_batch(self, df=None):\n pass\n\n # update data with most recent transaction,\n # one by one\n def update_data_single(self, single_transaction=None):\n pass\n\n # sample of future queries\n def is_zhangting(self, date=\"\"):\n pass\n\n def is_dieting(self, date=\"\"):\n pass\n\nclass StkDataKeeper(object):\n 'read/write/process/hold data'\n def __init__(self, code_list_file=\"\", helper_data_folder=\"\"):\n\n # properties\n self.helper_data={} # code -> StkHelperData\n self.stock_basics=None\n self.stock_list=[]\n if code_list_file != \"\":\n self.load_stock_list(code_list_file)\n\n # to implement - load data from folder\n\n def load_stock_list(self, code_list_file=\"\"):\n if code_list_file != \"\":\n self.stock_basics = self.get_stock_basics_file(code_list_file)\n else:\n self.stock_basics = self.get_stock_basics_tu()\n self.stock_list = self.stock_basics.index.tolist()\n\n\n\n def save_to_folder(self, data_folder=\"\"):\n pass\n\n\n def splitDateTime(self, df=None):\n if len(df.index) == 0: pass\n\n def splitDate(x):\n return x.split(\" \")[0]\n\n def splitTime(x):\n return x.split(\" \")[1]\n\n series_date = df.date.apply(splitDate)\n series_time = df.date.apply(splitTime)\n\n df[\"date\"] = series_date\n df[\"time\"] = series_time\n\n\n # get data from given csv\n # return a formatted DataFrame object\n def read_csv(self, filename=\"\", with_head=True, head_names=[], index=\"\", ):\n try:\n # if the original data has no index definition, then needs to set the index, else just honor the existing index\n if with_head:\n result_df = pd.read_csv(filename, dtype={\"code\":str}, encoding=\"utf-8\")\n\n else:\n if head_names == []:\n head_names = ['date', 'time', 'open', 'high', 'low', 'close', 'volume', 'total']\n result_df = pd.read_csv(filename, names=head_names, dtype={\"code\":str}, encoding=\"utf-8\")\n if index != \"\":\n result_df.set_index(index, inplace=True)\n\n except:\n return None\n\n return result_df\n\n\n # date open close high low volume code\n # 2014-11-17 14:55 21.946 22.305 22.465 21.047 33923.0 300191\n #\n # return formatted date & time indexed dataframe, with total estimation\n def read_csv_tu_5min(self, filename=\"\"):\n try:\n df = self.read_csv(filename, True)\n self.splitDateTime(df)\n # simulate the total with calculation\n df[\"total\"] = df[\"volume\"] * 100 * (df[\"open\"] + df[\"close\"] + df[\"high\"] + df[\"low\"]) / 4\n df[\"date\"] = [c.replace('-', '/') for c in df[\"date\"]] # this doesnt' work - df[\"date\"].replace('-', '/')\n df[\"code\"] = [(\"0\"*(6-len(c))+c) for c in df[\"code\"]] # add missing \"0\" if any\n\n df.set_index([\"date\", \"time\"], inplace=True)\n\n # df.index = pd.MultiIndex.from_tuples([(x[0].replace('/', '-'), x[1]) for x in df.index])\n except:\n return None\n\n return df\n\n\n # date open close high low volume code\n # 2014-11-17 21.946 22.305 22.465 21.047 33923.0 300191\n #\n # return: date indexed DataFrame\n def read_csv_tu_daily(self, filename=\"\"):\n try:\n df = self.read_csv(filename, True, index=\"date\")\n df[\"total\"] = df[\"volume\"] * 100 * (df[\"open\"] + df[\"close\"] + df[\"high\"] + df[\"low\"]) / 4\n except:\n return None\n\n return df\n\n\n # date time open high low close volume total\n # 2015/1/5 9:35 16.47 16.47 16.18 16.2 2355 3838604\n def read_csv_hist_5min(self, filename=\"\"):\n df = self.read_csv(filename, with_head=True, index=[\"date\", \"time\"])\n return df\n\n\n # get the stock list from online interface, and store it to given file\n # return DataFrame\n def get_stock_basics_tu(self, filename=\"\"):\n if not (self.stock_basics is None):\n if filename != \"\":\n self.stock_basics.to_csv(filename, encoding=\"utf-8\")\n return self.stock_basics\n else:\n self.stock_basics = ts.get_stock_basics()\n if filename != \"\":\n self.stock_basics.to_csv(filename, encoding=\"utf-8\")\n return self.stock_basics\n\n\n def get_stock_basics_file(self, filename=\"\"):\n try:\n self.stock_basics = self.read_csv(filename, True)\n self.stock_basics.set_index(\"code\", inplace=True)\n return self.stock_basics\n except:\n return None\n\n def get_stock_outstanding(self, stk_code):\n try:\n if self.stock_basics is None:\n self.load_stock_list()\n return self.stock_basics.loc[stk_code].outstanding * 100000000 / 100\n except:\n return 0.0\n\n def get_stock_data(self, sk_code=\"300191\", source_file=\"\", daily_T_fivemin_F=True, tail=0):\n df = None\n try:\n if source_file == \"\":\n if daily_T_fivemin_F:\n df = ts.get_k_data(sk_code)\n else:\n df = ts.get_k_data(sk_code, ktype='5')\n df.set_index(\"date\", inplace=True)\n else:\n if daily_T_fivemin_F:\n self.read_csv_tu_daily(source_file)\n else:\n self.read_csv_hist_5min(source_file)\n\n # trim the data\n if tail != 0:\n df = df[-(tail):]\n\n return df\n\n except:\n if df == None: return None\n\n\n # merge data for data maintenance\n # if daily data then index = [\"date\"]\n # if time transaction data then index = [\"date\", \"time\"]\n def merge_csv(self, base_file=\"\", new_file=\"\", target_file=\"\", index=[\"date\", \"time\"]):\n try:\n new_pd = self.read_csv(new_file, index=index)\n old_pd = self.read_csv(base_file, index=index)\n\n new_pd = old_pd.append(new_pd)\n new_pd = self.drop_duplicate(new_pd)\n new_pd.to_csv(target_file)\n\n return True\n\n except:\n print(\"error: \" + new_file)\n return False\n\n\n def merge_df(self, df_base, df_new, filename=\"\"):\n try:\n merged_df = df_base.append(df_new)\n merged_df = self.drop_duplicate(merged_df)\n merged_df.to_csv(filename)\n except:\n return False\n\n return True\n\n\n # add the code column according to the filename. Maintenance for the purchased data\n def add_code_single(self, input_filename=\"\", target_filename=\"\", stock_only=False, stock_record_file=\"stock_basics.csv\"):\n try:\n stk_keeper = sd.StkDataKeeper()\n code = input_filename.split(\".\")[0][-6:]\n if stock_only:\n stock_df = stk_keeper.load_stock_list(stock_record_file)\n stock_list = stock_df.index.tolist()\n if code not in stock_list:\n return (\"cannot find this stock: \" + input_filename)\n\n df = stk_keeper.read_csv_hist_5min(input_filename)\n df[\"code\"] = code\n df.to_csv(target_filename, encoding=\"utf-8\")\n return \"done\"\n\n except:\n return (\"fail: \" + input_filename)\n\n\n # add code column for all files under given folder. Maintenance for the purchased data\n def add_code_folder(self, base_dir=\"\", target_dir=\"\"):\n\n file_list = os.listdir(base_dir)\n\n result = []\n with concurrent.futures.ProcessPoolExecutor(max_workers=15) as executor:\n for file_name in file_list:\n base_file = os.path.join(base_dir, file_name)\n target_file = os.path.join(target_dir, file_name)\n\n obj = executor.submit(self.add_code_single, base_file, target_file)\n result.append(obj)\n\n for obj in result:\n if obj.result() != \"done\":\n print(obj.result())\n\n\n def drop_duplicate(self, df):\n return df[~df.index.duplicated(keep='last')]\n\n\n def merge_hist_with_daily_single(self, hist_file=\"\", daily_file=\"\", target_file=\"\", isIncrementalTu=True):\n inline_debug = False\n if target_file==\"\": return [hist_file, daily_file, target_file]\n\n try:\n # if only one source is provided, then save it directly\n if hist_file==\"\" or daily_file==\"\":\n if daily_file!=\"\":\n if isIncrementalTu:\n df = self.read_csv_tu_5min(daily_file)\n else:\n df = self.read_csv_hist_5min(daily_file)\n else:\n df = self.read_csv_hist_5min(hist_file)\n df.to_csv(target_file)\n\n # else all three inputs are ready\n else:\n hist_df = self.read_csv_hist_5min(hist_file)\n if isIncrementalTu:\n daily_df = self.read_csv_tu_5min(daily_file)\n else:\n daily_df = self.read_csv_hist_5min(daily_file)\n\n if inline_debug:# debug code goes here\n hist_df.to_csv(\"hist_df.csv\")\n daily_df.to_csv(\"daily_df.csv\")\n\n new_df = hist_df.append(daily_df)\n\n if inline_debug:\n print (len(hist_df.index), len(daily_df.index), len(new_df.index))\n new_df.to_csv(target_file+\".csv\")\n\n new_df = self.drop_duplicate(new_df)\n # new_df.drop_duplicates(inplace=True)\n\n if inline_debug:\n print(len(new_df.index))\n\n new_df.to_csv(target_file)\n return []\n except:\n return [hist_file, daily_file, target_file]\n\n # isIncrementalSource = True means the source is from TuShare so the format is converted\n # isIncrementalSource = False means the source is also in format of history, which is data merge operation\n def merge_hist_with_daily_folder(self, hist_dir, daily_dir, target_dir, isIncrementalSource=True):\n\n if self.stock_list == []:\n self.load_stock_list()\n\n hist_file_list = os.listdir(hist_dir)\n daily_files_list = os.listdir(daily_dir)\n\n hist_map = {}\n for hist_file in hist_file_list:\n code = hist_file[-10:-4]\n if code in self.stock_list:\n if ((is_SH(code) and hist_file[:2]==\"SH\")\n or (is_SZ(code) and hist_file[:2]==\"SZ\")):\n hist_map[code] = hist_file\n # else is something else\n\n daily_map = {}\n for daily_file in daily_files_list:\n code = daily_file[-10:-4]\n daily_map[code] = daily_file\n\n results = []\n with concurrent.futures.ProcessPoolExecutor(max_workers=15) as executor:\n for code in daily_map.keys():\n daily_file = os.path.join(daily_dir, daily_map[code])\n prefix = \"SH\" if is_SH(code) else \"SZ\"\n target_file = os.path.join(target_dir, prefix+code+'.csv')\n\n if code in hist_map.keys():\n hist_file = os.path.join(hist_dir, hist_map[code])\n else:\n hist_file = \"\"\n\n # self.merge_hist_with_daily_single(hist_file, daily_file, target_file)\n obj = executor.submit(self.merge_hist_with_daily_single, hist_file, daily_file, target_file, isIncrementalSource)\n results.append(obj)\n\n\n for obj in results:\n if obj.result() != []:\n print(obj.result())\n\n # get realtime transaction\n # for specific code, or all when code = \"\"\n def get_realtime_transaction(self, code=\"\"):\n if code == \"\":\n df = ts.get_today_all()\n else:\n df = ts.get_realtime_quotes(code)\n return df\n\n\n # update realtime transaction\n # append the recent transaction to the analysis\n def update_realtime_transaction(self, code=\"\"):\n pass\n\n\n # Update the helper data with additional transaction calculation results\n # inout is either file of new daily transaction or realtime data\n def load_helper_data(self, folder_name=\"\", df=None):\n pass\n\nclass StkDiagram(object):\n 'Utility class that accepts the dataframe and paint set of klines'\n\n def __init__(self):\n pass\n\n # Known limitation - cannot paint double axis diagrams\n def paint_grid(self, diagram_coll=[], column=3, margin = 3.0, unit_width=600, unit_height=400):\n\n if len(diagram_coll) == 0:\n return None\n\n # every cell is grid_top, grid_bottom, grid_left, grid_right\n positioning = []\n pos_unit = 100 / column\n height_unit = 100 / row\n for i_row in range(row):\n for j_col in range(column):\n positioning.append([\"{0:.0f}%\".format(height_unit * i_row + margin),\n \"{0:.0f}%\".format(100 - height_unit * (i_row + 1) + margin),\n \"{0:.0f}%\".format(pos_unit * j_col + margin),\n \"{0:.0f}%\".format(100 - pos_unit * (j_col + 1) + margin)])\n\n grid = pec.Grid(width=unit_width*column, height=unit_height*row)\n for i, diagram in enumerate(diagram_coll):\n grid.add(diagram,\n grid_top=positioning[i][0],\n grid_bottom=positioning[i][1],\n grid_left=positioning[i][2],\n grid_right=positioning[i][3])\n grid.render(\"C:\\\\Users\\\\samx\\\\PycharmProjects\\\\index.html\")\n return grid\n\n\n def paint_grid_helper(self, cell_numbers=0, diagram_per_stk=1, column=3, margin = 3.0):\n\n if cell_numbers == 0: return []\n\n row = cell_numbers // column + (1 if cell_numbers % column != 0 else 0)\n pos_unit = 100 / column\n height_unit = 100 / row\n\n overall_positioning = []\n\n # loop for every type of diagram\n for i in range(diagram_per_stk):\n diagram_positioning = []\n\n first_diagram_ratio = 2\n\n if i == 0:\n reserve_up = 0\n # first is larger than rest diagrams\n # reserve room for rest diagrams\n reserve_down = (height_unit - (margin*2)) / (diagram_per_stk+first_diagram_ratio-1) * (diagram_per_stk-i-1)\n else:\n reserve_up = (height_unit - (margin*2))/(diagram_per_stk+first_diagram_ratio-1)*(i+first_diagram_ratio-1)\n reserve_down = (height_unit - (margin*2))/(diagram_per_stk+first_diagram_ratio-1)*(diagram_per_stk-i-1)\n\n # every cell is grid_top, grid_bottom, grid_left, grid_right\n for i_row in range(row):\n for j_col in range(column):\n diagram_positioning.append([\"{0:.1f}%\".format(height_unit * i_row + margin + reserve_up),\n \"{0:.1f}%\".format(100 - height_unit * (i_row + 1) + margin + reserve_down),\n \"{0:.1f}%\".format(pos_unit * j_col + margin),\n \"{0:.1f}%\".format(100 - pos_unit * (j_col + 1) + margin)])\n overall_positioning.append(diagram_positioning)\n\n return overall_positioning\n\n # Known limitation - cannot paint double axis diagrams\n def paint_grid_enhanced(self,\n kline_coll=[], volume_coll=[], three_day_coll=[],\n column=3, margin=1.0, unit_width=600, unit_height=600):\n\n\n\n if len(kline_coll) == 0 or len(volume_coll) == 0:\n return None\n row = len(kline_coll) // column + (1 if len(kline_coll) % column != 0 else 0)\n\n # every cell is grid_top, grid_bottom, grid_left, grid_right\n positioning = self.paint_grid_helper(len(kline_coll), 3, column, margin)\n\n # positioning = []\n # pos_unit = 100 / column\n # height_unit = 100 / row\n # for i_row in range(row):\n # for j_col in range(column):\n # positioning.append([\"{0:.0f}%\".format(height_unit * i_row + margin),\n # \"{0:.0f}%\".format(100 - height_unit * (i_row + 1) + margin),\n # \"{0:.0f}%\".format(pos_unit * j_col + margin),\n # \"{0:.0f}%\".format(100 - pos_unit * (j_col + 1) + margin)])\n\n grid = pec.Grid(width=unit_width * column, height=unit_height * row)\n\n for i, diagram in enumerate(kline_coll):\n grid.add(diagram,\n grid_top=positioning[0][i][0],\n grid_bottom=positioning[0][i][1],\n grid_left=positioning[0][i][2],\n grid_right=positioning[0][i][3])\n grid.add(volume_coll[i],\n grid_top=positioning[1][i][0],\n grid_bottom=positioning[1][i][1],\n grid_left=positioning[1][i][2],\n grid_right=positioning[1][i][3])\n grid.add(three_day_coll[i],\n grid_top=positioning[2][i][0],\n grid_bottom=positioning[2][i][1],\n grid_left=positioning[2][i][2],\n grid_right=positioning[2][i][3])\n\n return grid\n\n\n\n def paint_page(self, diagram_coll=[]):\n page = pec.Page()\n [page.add(diagram) for diagram in diagram_coll]\n return page\n\n def paint_date_kline(self, sk_code=\"300191\", sk_name=\"\", target_file=\"\", tail=24, with_volume=False, title_top=\"0%\", title_pos=\"0%\"):\n stk_keeper = StkDataKeeper()\n df = stk_keeper.get_stock_data(sk_code, target_file, True, tail)\n\n return self.paint_kline(df, with_volume, title_top, title_pos, sk_name)\n\n def paint_date_volume(self, sk_code=\"300191\", sk_name=\"\", target_file=\"\", tail=24, title_top=\"0%\", title_pos=\"0%\"):\n stk_keeper = StkDataKeeper()\n df = stk_keeper.get_stock_data(sk_code, target_file, True, tail)\n\n return self.paint_volume(df, title_top, title_pos, sk_name)\n\n def paint_time_kline(self, sk_code=\"300191\", sk_name=\"\", target_file=\"\", tail=48, with_volume=False, title_top=\"0%\", title_pos=\"0%\"):\n stk_keeper = StkDataKeeper()\n df = stk_keeper.get_stock_data(sk_code, target_file, False, tail)\n\n return self.paint_kline(df, with_volume, title_top, title_pos, sk_name)\n\n def paint_volume(self, df, title_top=\"0%\", title_pos=\"0%\", stock_name=\"\"):\n sk_code = df.iloc[-1].code\n\n v_label = []\n v_volume = []\n for index in df.index:\n v_label.append(index)\n v_volume.append(df.loc[index].volume)\n\n bar = pec.Bar(sk_code+\" \"+stock_name, title_top=title_top, title_pos=title_pos)\n bar.add(\"\", v_label, v_volume)\n\n return bar\n\n def paint_kline(self, df, with_volume=False, title_top=\"0%\", title_pos=\"0%\", stock_name=\"\"):\n sk_code = df.iloc[-1].code\n\n v_label = []\n v_kline = []\n v_line = []\n v_volume = []\n for index in df.index:\n v_kline.append([df.loc[index].open,\n df.loc[index].close,\n df.loc[index].low,\n df.loc[index].high])\n v_label.append(index)\n v_volume.append(df.loc[index].volume)\n v_line.append(df.loc[index].close)\n\n kline = pec.Kline(sk_code+\" \"+stock_name, title_top=title_top, title_pos=title_pos)\n kline.add(\"\", v_label, v_kline)\n # kline.render(\"C:\\\\Users\\\\samx\\\\PycharmProjects\\\\kline.html\")\n\n if with_volume:\n line = pec.Line(sk_code)\n line.add(\"\", v_label, v_line, yaxis_min=min(v_line))\n #line.render(\"C:\\\\Users\\\\samx\\\\PycharmProjects\\\\line.html\")\n bar = pec.Bar(sk_code)\n bar.add(\"\", v_label, v_volume, yaxis_max=max(v_volume)*5)\n #bar.render(\"C:\\\\Users\\\\samx\\\\PycharmProjects\\\\bar.html\")\n\n overlap = pec.Overlap()\n overlap.add(line)\n overlap.add(kline)\n overlap.add(bar, is_add_yaxis=True, yaxis_index=1)\n return overlap\n else:\n return kline\n\n def paint_klines(self, stock_list, stock_basics_file=\"\", unit_width=600, unit_height=600):\n\n positioning = self.paint_grid_helper(len(stock_list), 3, 3, 1.0)\n\n stk = StkDataKeeper()\n stk.load_stock_list(stock_basics_file)\n\n kline_collection = []\n volume_collection = []\n time_collection = []\n for i, stock in enumerate(stock_list):\n name_prefix = stock[:2]\n stock = stock[-6:]\n try:\n stk_name = name_prefix + stk.stock_basics.loc[stock][0]\n except:\n stk_name = name_prefix\n\n kline = self.paint_date_kline(stock, stk_name + \" \" + str(i), with_volume=False, title_top=positioning[0][i][0],\n title_pos=positioning[0][i][2])\n kline_collection.append(kline)\n volume = self.paint_date_volume(stock, stk_name, title_top=positioning[1][i][0],\n title_pos=positioning[1][i][2])\n volume_collection.append(volume)\n fenshi = self.paint_time_kline(stock, stk_name, with_volume=False, title_top=positioning[2][i][0],\n title_pos=positioning[2][i][2])\n time_collection.append(fenshi)\n\n grid = self.paint_grid_enhanced(kline_collection, volume_collection, time_collection, margin=1.0,\n unit_width=unit_width,\n unit_height=unit_height)\n return grid\n\ndef is_SH(code=\"\"):\n if len(code) != 6: return False\n return True if code[:2]==\"60\" else False\n\ndef is_SZ(code=\"\"):\n if len(code) != 6: return False\n return True if code[:2]==\"00\" or code[:3]==\"300\" else False\n\ndef testPickle():\n pickle_test = PickleDataTest()\n data_source = StkDataKeeper()\n pickle_test.df = data_source.get_realtime_transaction(\"000001\")\n pickle_test.code = \"300191\"\n p1 = pickle.dumps(pickle_test)\n pickle_test_new = pickle.loads(p1)\n print(pickle_test.df)\n print(\"------------------------------\")\n print(pickle_test_new.df)\n df = pickle_test.df.append(pickle_test_new.df).drop_duplicates()\n print(df)\n\ndef test_pickle_help_data():\n data_keeper = StkDataKeeper()\n # df = data_keeper.read_csv(\"stksample\\\\20170929_150000.csv\", index=\"code\")\n # print(df)\n df = data_keeper.read_csv_hist_5min(\"stksample//SZ300191.csv\")\n print(df)\n\n helper_data = StkHelperData()\n helper_data.calculate_data(df)\n\n p1 = pickle.dumps(helper_data)\n helper_data_new = pickle.loads(p1)\n print(helper_data_new.seqential_status_map.keys())\n\ndef test_csv_readers():\n\n sample_dir = os.path.abspath(\"stksample\")\n\n data_keeper = StkDataKeeper()\n test_file = os.path.join(sample_dir, \"SZ300191.csv\")\n df = data_keeper.read_csv(test_file, index=\"date\")\n df = df.set_index(\"time\", append=True)\n print(df.head())\n\n test_file = os.path.join(sample_dir, \"5min_300191.csv\")\n df = data_keeper.read_csv_tu_5min(test_file)\n print(df.head())\n\n test_file = os.path.join(sample_dir, \"day_300191.csv\")\n df = data_keeper.read_csv_tu_daily(test_file)\n print(df.head())\n\n test_file = os.path.join(sample_dir, \"SZ300191.csv\")\n df = data_keeper.read_csv_hist_5min(test_file)\n print(df.head())\n\ndef test_merge_df():\n\n sample_dir = os.path.abspath(\"stksample\")\n\n data_keeper = StkDataKeeper()\n test_file_base = os.path.join(sample_dir, \"SZ300191.csv\")\n test_file_new = os.path.join(sample_dir, \"5min_300191.csv\")\n df_base = data_keeper.read_csv_hist_5min(test_file_base)\n df_new = data_keeper.read_csv_tu_5min(test_file_new)\n data_keeper.merge_df(df_base, df_new, \"result.csv\")\n\n df = data_keeper.read_csv_hist_5min(\"result.csv\")\n print(df.head(), df.tail())\n\n data_keeper.merge_df(df_new, df_base, \"result.csv\")\n df = data_keeper.read_csv_hist_5min(\"result.csv\")\n print(df.head(), df.tail())\n\ndef test_stk_stock_basics():\n stk_keeper = StkDataKeeper()\n df = stk_keeper.get_stock_basics_tu(\"stock_basics.csv\")\n print(df.head(), df.tail())\n df1 = stk_keeper.get_stock_basics_file(\"stock_basics.csv\")\n print(df1.head(), df1.tail())\n\ndef test_stk_daily_batch_merge():\n stk_keeper = StkDataKeeper(code_list_file=\"stock_basics.csv\")\n hist_dir = \"D://stock//stk_new\"\n daily_dir = \"D://stock//accumulated_data//20170930//fivemin\"\n target_dir = \"D://stock//stk_new\"\n now = datetime.datetime.now()\n\n stk_keeper.merge_hist_with_daily_folder(hist_dir, daily_dir, target_dir)\n time.sleep(3)\n print((datetime.datetime.now() - now))\n\ndef test_stk_diagram():\n stk_diagram = StkDiagram()\n stk_list = ['000418', '002194', '002846', '300176', '300425', '300707']\n diagram_list = []\n for stk in stk_list:\n kline = stk_diagram.paint_kline(stk, no_volume=True)\n # kline.render(stk+\".html\")\n diagram_list.append(kline)\n grid = stk_diagram.paint_grid(diagram_list)\n grid.render()\n\ndef set_pandas_format():\n pd.set_option('display.max_columns', None)\n pd.set_option('display.width', None)\n\nif __name__ == \"__main__\":\n\n set_pandas_format()\n\n # mark_done_get = datetime.datetime.now()\n #\n # hist_dir = os.path.abspath(\"D:\\stock\\stk_new_update\")\n # daily_dir = os.path.abspath(\"D:\\stock\\stk_update_incremental\")\n # target_dir = os.path.abspath(\"D:\\stock\\stk_new_merge\")\n #\n # stk_keeper = StkDataKeeper()\n # stk_keeper.load_stock_list()\n # stk_keeper.merge_hist_with_daily_folder(hist_dir, daily_dir, target_dir, False)\n # print(\"Refresh data in: \" + str(datetime.datetime.now() - mark_done_get))\n\n # stk_keeper = StkDataKeeper()\n # print(stk_keeper.get_stock_basics_tu().head())\n # print(stk_keeper.stock_basics.tail())\n\n painter = StkDiagram()\n stock_list = ['002156', '002409', '002848', '300176', '300220', '300474', '300531', '300706', '603466', '603533', '603559', '603929', '603986', '002806', '603683', '603131']\n\n\n grid = painter.paint_klines(stock_list, \"stock_basics.csv\", 300, 400)\n grid.render(\"C:\\\\Users\\\\samx\\\\PycharmProjects\\\\index.html\")\n\n","sub_path":"notebooks/StkDataKeeper.py","file_name":"StkDataKeeper.py","file_ext":"py","file_size_in_byte":31981,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"83925307","text":"# import the msmt class\nimport numpy as np\nimport qt\nfrom measurement.lib.measurement2.adwin_ssro import pulsar_msmt\n\nSAMPLE = qt.exp_params['samples']['current']\nSAMPLE_CFG = qt.exp_params['protocols']['current']\n\ntemperature_sensor = qt.instruments['kei2000']\nmagnet_Z_scanner = qt.instruments['conex_scanner_Z']\n\ndef darkesr(name, ms = 'msp', range_MHz = 6, pts = 81, reps = 1000, freq=0, \n pulse_length = 2e-6, ssbmod_amplitude = None, mw_power = 20, mw_switch=False):\n if mw_switch:\n m = pulsar_msmt.DarkESR_Switch(name)\n else:\n m = pulsar_msmt.DarkESR(name)\n\n\n m.params.from_dict(qt.exp_params['samples'][SAMPLE])\n m.params.from_dict(qt.exp_params['protocols']['AdwinSSRO'])\n m.params.from_dict(qt.exp_params['protocols'][SAMPLE_CFG]['AdwinSSRO'])\n m.params.from_dict(qt.exp_params['protocols'][SAMPLE_CFG]['AdwinSSRO-integrated'])\n m.params.from_dict(qt.exp_params['protocols']['AdwinSSRO+espin'])\n m.params.from_dict(qt.exp_params['protocols']['111_1_sil18']['pulses']) #Added to include the MW switch MA\n\n m.params['mw_power'] = mw_power\n m.params['temp'] = temperature_sensor.get_readlastval()\n m.params['magnet_position'] = magnet_Z_scanner.GetPosition()\n\n if ms == 'msp':\n m.params['mw_frq'] = m.params['ms+1_cntr_frq']-43e6 #MW source frequency\n m.params['pulse_length'] = pulse_length\n \n if ssbmod_amplitude == None:\n m.params['ssbmod_amplitude'] = 0.025\n else:\n m.params['ssbmod_amplitude'] = ssbmod_amplitude\n\n elif ms == 'msm':\n m.params['mw_frq'] = m.params['ms-1_cntr_frq'] - 43e6\n m.params['pulse_length'] = pulse_length\n \n if ssbmod_amplitude == None:\n m.params['ssbmod_amplitude'] = 0.010\n else:\n m.params['ssbmod_amplitude'] = ssbmod_amplitude\n \n if freq != 0:\n m.params['mw_frq'] = freq - 43e6\n \n m.params['repetitions'] = reps\n\n m.params['ssbmod_frq_start'] = 43e6 - range_MHz*1e6 \n m.params['ssbmod_frq_stop'] = 43e6 + range_MHz*1e6\n m.params['pts'] = pts\n\n m.params['sweep_pts'] = (np.linspace(m.params['ssbmod_frq_start'],\n m.params['ssbmod_frq_stop'], m.params['pts']) \n + m.params['mw_frq'])*1e-9\n\n m.autoconfig()\n m.generate_sequence(upload=True)\n m.run()\n m.save()\n m.finish()\n\nif __name__ == '__main__':\n darkesr()\n\n","sub_path":"scripts/QEC/magnet/DESR_msmt.py","file_name":"DESR_msmt.py","file_ext":"py","file_size_in_byte":2422,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"119236229","text":"expressions = {\n 'equal': lambda a, b: a == b,\n 'contains': lambda a, b: b in a,\n 'not_contains': lambda a, b: b not in a,\n 'more': lambda a, b: a > b,\n 'less': lambda a, b: a < b,\n 'in': lambda a, b: a in b,\n 'not_in': lambda a, b: a not in b\n}\n\n\nclass ObjectMeta(type):\n classes = {}\n\n def __new__(cls, name, bases, attrs):\n api_name = attrs['api_name']\n c = super(ObjectMeta, cls).__new__(cls, name, bases, attrs)\n\n if api_name is not None:\n cls.classes[api_name] = c\n\n return c\n\n\ndef get_object_class(name: str):\n \"\"\"Return class of api 'object' entity by its name\"\"\"\n return ObjectMeta.classes[name]\n\n\nclass ObjectBase(metaclass=ObjectMeta):\n api_name = None\n data = None\n allowed_expressions = {}\n\n def __init__(self, data):\n self.data = data\n\n def check(self, prop: str, expression: str, value) -> bool:\n if expression not in self.allowed_expressions.get(prop, ()):\n raise ValueError('Property-expression combination is not allowed')\n\n f = expressions[expression]\n return f(getattr(self, prop), value)\n\n\nclass TextObject(ObjectBase):\n api_name = 'text'\n allowed_expressions = {\n 'content': {'contains', 'not_contains'},\n 'length': {'more', 'less', 'equal'}\n }\n\n @property\n def length(self):\n return len(self.data)\n\n @property\n def content(self):\n return self.data\n\n\nclass CategoryObject(ObjectBase):\n api_name = 'category'\n allowed_expressions = {\n 'title': {'equal', 'in', 'not_in'}\n }\n\n @property\n def title(self):\n return \"Новости\" # Hardcoded, as proposed\n","sub_path":"entities.py","file_name":"entities.py","file_ext":"py","file_size_in_byte":1679,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"617654292","text":"from hmmlearn import hmm\nfrom python_speech_features import mfcc\nfrom scipy.io import wavfile\nimport numpy as np\nimport joblib\nimport RPi.GPIO as GPIO\nimport time\n\n# 特征提取,feat = compute_mfcc(wadict[wavid])\nwavdict={'1_1': '1_1.wav', '1_2': '1_2.wav','1_3': '1_3.wav', '1_4': '1_4.wav','1_5':'1_5.wav',\n '2_1': '2_1.wav', '2_2': '2_2.wav','2_3': '2_3.wav', '2_4': '1_4.wav','2_5':'2_5.wav',\n '3_1': '3_1.wav', '3_2': '3_2.wav','3_3': '3_3.wav', '3_4': '3_4.wav','3_5':'3_5.wav',\n '4_1': '4_1.wav', '4_2': '4_2.wav','4_3': '4_3.wav', '4_4': '4_4.wav','4_5':'4_5.wav'\n }\nlabeldict={'1_1': '1', '1_2': '1', '1_3': '1', '1_4': '1','1_5':'1',\n '2_1': '2', '2_2': '2', '2_3': '2', '2_4': '2','2_5':'2',\n '3_1': '3', '3_2': '3', '3_3': '3', '3_4': '3','3_5':'3',\n '4_1': '4', '4_2': '4', '4_3': '4', '4_4': '4','4_5':'4'}\n\nLED=26\nGPIO.setmode(GPIO.BCM)\n\ndef compute_mfcc(file):\n fs, audio = wavfile.read(file)\n mfcc_feat = mfcc(audio)\n return mfcc_feat\n\n\n\nclass Model():\n def __init__(self, CATEGORY=None, n_comp=3, n_mix = 3, cov_type='diag', n_iter=1000):\n super(Model, self).__init__()\n self.CATEGORY = CATEGORY\n self.category = len(CATEGORY)\n self.n_comp = n_comp\n self.n_mix = n_mix\n self.cov_type = cov_type\n self.n_iter = n_iter\n # 关键步骤,初始化models,返回特定参数的模型的列表\n self.models = []\n for k in range(self.category):\n model = hmm.GMMHMM(n_components=self.n_comp, n_mix = self.n_mix, covariance_type=self.cov_type, n_iter=self.n_iter)\n self.models.append(model)\n \n def train(self,wavdict=None,labeldict=None):\n print(\"start training\")\n for k in range(len(self.CATEGORY)):\n model=self.models[k]\n for x in wavdict:\n if labeldict[x]==self.CATEGORY[k]:\n # 提取声学特征\n mfcc_feat = compute_mfcc(wavdict[x])\n # hmm-gmm 模型训练\n model.fit(mfcc_feat)\n \n def test(self,filepath):\n result=[]\n for k in range(self.category):\n model=self.models[k]\n mfcc_feat=compute_mfcc(filepath)\n # 生成每个数据在当前模型下的得分情况\n re = model.score(mfcc_feat)\n result.append(re)\n #选取得分最高的种类\n result=np.array(result).argmax()\n print(\"result:\",self.CATEGORY[result])\n return self.CATEGORY[result]\n \n def save(self,path=\"model.pkl\"):\n joblib.dump(self.models,path)\n \n def load(self,path=\"model.pkl\"):\n self.models=joblib.load(path)\n \n\nx=Model(['1','2','3','4'])\n#x.train(wavdict,labeldict)\n#x.save()\nx.load()\nx.test(\"test2.wav\")\n\n\n\n\n \n","sub_path":"Lab8/hmm_gmm.py","file_name":"hmm_gmm.py","file_ext":"py","file_size_in_byte":2949,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"349161890","text":"import riak\n\nclass riak_machine:\n def get_riak_instance(self):\n client = riak.RiakClient(host=\"18.220.160.111\")\n return client\n\n\n def write_to_riak(self, bucket_name, key,DATA):\n self.__delete(bucket_name,key)\n bucket = self.get_riak_instance().bucket(bucket_name)\n trust_data = bucket.new(key, data=DATA)\n trust_data.store()\n print(\"Write Success\")\n \n\n def __delete(self, bucket_name, key):\n bucket = self.get_riak_instance().bucket(bucket_name)\n bucket.delete(key)\n return True\n","sub_path":"NHS.Spark/spark-warehouse/riak_machine.py","file_name":"riak_machine.py","file_ext":"py","file_size_in_byte":562,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"500440432","text":"import cv2\nimport numpy as np\n\ncapture = cv2.VideoCapture(0)\n\n\nkernel_2 = np.ones((2,2),np.uint8)#2x2的卷积核\nkernel_3 = np.ones((3,3),np.uint8)#3x3的卷积核\nkernel_4 = np.ones((4,4),np.uint8)#4x4的卷积核\nkernel_8 = np.ones((8,8),np.uint8)#8x8的卷积核\nkernel_20 = np.ones((20,20),np.uint8)#20x20的卷积核\n\n# erosion_count = 2 #腐蚀的次数\n# dilation_count = 2 #膨胀的次数\n\ndef Rgb_convert_Hsv(rgb=[0,0,0]):\n R,G,B = rgb[0]/255.0,rgb[1]/255.0,rgb[2]/255.0\n max_val = max(R,G,B)\n min_val = min(R,G,B) \n if (max_val-min_val) != 0:\n if R == max_val:\n H = (G-B)/float(max_val-min_val)\n if G == max_val:\n H = 2 + (B-R)/float(max_val-min_val)\n if B == max_val:\n H = 4 + (R-G)/float(max_val-min_val)\n\n H = int(H * 30)\n if H < 0:\n H = H + 180\n V=int(max(R,G,B)*255)\n S=int((max_val-min_val)/max_val*255)\n \n # HSV_list = []\n # HSV_list.append(H)\n # HSV_list.append(int(S*255))\n # HSV_list.append(int(V*255))\n # return HSV_list\n return H,S,V\n else:\n return 0,0,max_val\n\ndef color_div(color_num=6):\n return int(180.0/color_num)\n\n\n\ndef string_convert_hsv(color_default = 'blue'):\n # color_basic = color_div()\n kernel_4 = np.ones((4,4),np.uint8)#20x20的卷积核\n\n erosion_count = 1 #腐蚀的次数\n dilation_count = 1 #膨胀的次数\n\n color_dict = {'red':[0,4],'orange':[7,20],'yellow':[21,37],'green':[42,85],'blue':[92,107],'purple':[115,160]}\n # color_dict = {'red':[0,4],'orange':[7,20],'yellow':[21,37],'green':[42,85],'blue':[100,124],'purple':[115,160]}\n\n lower_color = np.array([min(color_dict[color_default]), 105, 90]) \n upper_color = np.array([max(color_dict[color_default]), 255, 255])\n\n # 蓝色的范围,不同光照条件下不一样,可灵活调整 H:色度,S:饱和度 v:明度\n\n while(True):\n \n ret, frame = capture.read() # 1.捕获视频中的一帧\n \n hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV) # 2.从BGR转换到HSV\n \n mask = cv2.inRange(hsv, lower_color, upper_color) # 3.inRange():介于lower/upper之间的为白色,其余黑色 \n \n mask = cv2.GaussianBlur(mask, (7, 7), 0) #高斯滤波\n\n erosion = cv2.erode(mask,kernel_4,iterations = erosion_count) #腐蚀\n dilation = cv2.dilate(erosion,kernel_4,iterations = dilation_count) #膨胀 \n \n res = cv2.bitwise_and(frame, frame, mask=dilation) ####与操作,只保留原图中的蓝色部分\n\n ret, binary = cv2.threshold(dilation,127,255,cv2.THRESH_BINARY) ####把图片变为二值图放在binary里面\n\n contours, hierarchy = cv2.findContours(binary,cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE) ####在binary中发现轮廓,轮廓按照面积从小到大排列\n # p=0\n for i in contours: #遍历所有的轮廓\n x,y,w,h = cv2.boundingRect(i) #将轮廓分解为识别对象的左上角坐标和宽、高\n #在图像上画上矩形(图片、左上角坐标、右下角坐标、颜色、线条宽度)\n if w > 15 and h > 15: \n cv2.rectangle(frame,(x,y),(x+w,y+h),(0,255,0),3)\n #给识别对象写上标号\n font=cv2.FONT_HERSHEY_SIMPLEX\n cv2.putText(frame,color_default,(x-10,y+10), font, 1,(0,0,255),2)#加减10是调整字符位置\n # p +=1\n\n cv2.imshow('frame', frame)\n cv2.imshow('mask', mask)\n cv2.imshow('res', binary)\n if cv2.waitKey(1) == ord('q'):\n break\n\nif __name__=='__main__':\n string_convert_hsv('blue')\n\n","sub_path":"code/color_direct.py","file_name":"color_direct.py","file_ext":"py","file_size_in_byte":3848,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"90416129","text":"from django.contrib import admin\nfrom django.urls import path, include\n\nurlpatterns = [\n path('admin/', admin.site.urls),\n path('', include('index_app.urls')),\n path('membership_app/', include('membership_app.urls')),\n path('my/', include('personal_app.urls')),\n # path('accounts/', include('accounts.urls')),\n]\n","sub_path":"jekal_membership_project/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":327,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"187566311","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# @File : 买卖股票的最佳时期2.py\n# @Author: smx\n# @Date : 2020/2/22\n# @Desc :\n\n# 1. 暴力遍历每种情况\n# 2. 贪心算法,每次只要有正数就买入加\n# 3. 动态规划,计算到第i天的收益,问题是不知道怎么计算收益,买入的时候收益-股票价格,卖出的时候收益+股票价格!\nclass Solution:\n def maxProfit(self, arrs):\n if not arrs: return 0\n n = len(arrs)\n dp = [[0, 0] for _ in range(n)]\n dp[0][1] = -arrs[0]\n for i in range(1, n):\n dp[i][0] = max(dp[i - 1][0], dp[i - 1][1] + arrs[i])\n dp[i][1] = max(dp[i - 1][1], dp[i - 1][0] - arrs[i])\n return max(dp[n - 1])\n\n\nif __name__ == '__main__':\n arrs = [7, 1, 5, 3, 6, 4]\n print(Solution().maxProfit(arrs))\n","sub_path":"target_offer/dfs+bfs+动态规划/数字--线性动规/买卖股票的最佳时期2.py","file_name":"买卖股票的最佳时期2.py","file_ext":"py","file_size_in_byte":837,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"463732021","text":"# Copyright 2016-present, Facebook, Inc.\n# All rights reserved.\n#\n# This source code is licensed under the BSD-style license found in the\n# LICENSE file in the root directory of this source tree. An additional grant\n# of patent rights can be found in the PATENTS file in the same directory.\n\nload(\"@bazel_skylib//lib:collections.bzl\", \"collections\")\nload(\"@bazel_skylib//lib:paths.bzl\", \"paths\")\nload(\"@fbcode_macros//build_defs/config:read_configs.bzl\", \"read_boolean\", \"read_list\")\nload(\"@fbcode_macros//build_defs/lib:target_utils.bzl\", \"target_utils\")\nload(\"@fbcode_macros//build_defs/lib:third_party.bzl\", \"third_party\")\nload(\"@fbcode_macros//build_defs:custom_rule.bzl\", \"get_project_root_from_gen_dir\")\nload(\"@fbcode_macros//build_defs:sanitizers.bzl\", \"sanitizers\")\nload(\"@fbsource//tools/build_defs:fb_native_wrapper.bzl\", \"fb_native\")\nload(\"@fbsource//tools/build_defs:type_defs.bzl\", \"is_list\", \"is_tuple\")\n\n_GENERATED_LIB_SUFFIX = \"__generated-lib__\"\n\ndef _read_hs_debug():\n return read_boolean(\"fbcode\", \"hs_debug\", False)\n\ndef _read_hs_eventlog():\n return read_boolean(\"fbcode\", \"hs_eventlog\", False)\n\ndef _read_hs_profile():\n return read_boolean(\"fbcode\", \"hs_profile\", False)\n\ndef _read_extra_ghc_compiler_flags():\n return read_list(\"haskell\", \"extra_compiler_flags\", [], \" \")\n\ndef _read_extra_ghc_linker_flags():\n return read_list(\"haskell\", \"extra_linker_flags\", [], \" \")\n\ndef _dll_needed_syms_list_rule(name, dlls, visibility):\n \"\"\"\n Creates the genrule to pull symbols from a list of dll dependencies\n\n Args:\n name: The name of the original rule\n dlls: A list of string labels that point to dll to extract symbols from\n visibility: The visibility of the genrule\n\n Returns:\n A package relative target with the name of the generated rule\n \"\"\"\n cmd = \"nm -gPu {} | awk '{{print $1}}' | grep -v '^BuildInfo_k' | sort > $OUT\".format(\n \" \".join([\"$(location \" + dll + \")\" for dll in dlls]),\n )\n rule_name = name + \"-syms\"\n fb_native.cxx_genrule(\n name = rule_name,\n out = \"symbols.txt\",\n visibility = visibility,\n cmd = cmd,\n )\n return \":\" + rule_name\n\ndef _dll_syms_linker_script_rule(name, symbols_rule, visibility):\n \"\"\"\n Creates the genrule to take extracted symbols, and turn it into a linker script\n\n Args:\n name: The name of the original rule\n symbols_rule: The target of the symbols rule from _dll_needed_syms_list_rule\n visibility: The visibility of the genrule\n\n Returns:\n A package relative target with the name of the generated rule\n \"\"\"\n rule_name = name + \"-syms-linker-script\"\n fb_native.cxx_genrule(\n name = rule_name,\n visibility = visibility,\n out = \"extern_symbols.txt\",\n cmd = '''awk '{{print \"EXTERN(\"$1\")\"}}' $(location {}) > \"$OUT\"'''.format(symbols_rule),\n )\n return \":\" + rule_name\n\ndef _dll_rules(\n name,\n lib_name,\n dll_root,\n rule_type_filter,\n rule_name_filter,\n dll_type,\n fbcode_dir,\n visibility):\n \"\"\"\n Create a rule to link a DLL\n\n Args:\n name: The name of the rule\n lib_name: The name of the output artifact\n rule_type_filter: A regular expression for filtering types of rules that ldflags come from (or None)\n rule_name_filter: A regular expression for filtering names of rules that ldflags come from (or None)\n dll_type: The type of library that is being referenced.\n One of 'static', 'static-pic', or 'shared'\n visibility: The visibility for the rule\n \"\"\"\n\n cmd = [\"$(ld)\"]\n\n # Build a shared library.\n if dll_type == \"static\" or dll_type == \"static-pic\":\n cmd.append(\"-r\")\n elif dll_type == \"shared\":\n cmd.append(\"-shared\")\n else:\n fail(\"dll_type must be one of static, static-pic or shared\")\n cmd.append(\"-nostdlib\")\n cmd.extend([\"-o\", \"$OUT\"])\n\n # When GHC links DSOs, it sets this flag to prevent non-PIC symbols\n # from leaking to the dynamic symbol table, as it breaks linking.\n cmd.append(\"-Wl,-Bsymbolic\")\n\n # Add-in the macro to add the transitive deps to the link line. For\n # shared link styles, we do a shared link, but for anything else (i.e.\n # static, static-pic), we always do a `static` link, as we need to\n # support profiled builds with DSOs and this requires that we issue\n # an `-hisuf p_hi`, which we can't supply in addition to the 'dyn_hi'\n # suffix that a `-dynamic -fPIC` (i.e. static-pic) compilation rquires.\n # This is fine for GHC-built DSOs. To quote https://fburl.com/ze4ni010:\n # \"Profiled code isn't yet really position-independent even when -fPIC\n # is specified. Building profiled dynamic libraries therefore fails on\n # Mac OS X (Linux silently accepts relocations - it's just slightly bad\n # for performance).\" We also set a \"filter\" here so we only get haskell\n # rules in the link.\n if dll_type == \"shared\" or dll_type == \"static-pic\":\n dll_type_filter = \"ldflags-static-pic-filter\"\n else: # 'static'\n dll_type_filter = \"ldflags-static-filter\"\n cmd.append(\n \"$({} ^{}[(]{}[)]$ {})\"\n .format(\n dll_type_filter,\n rule_type_filter or \".*\",\n rule_name_filter or \".*\",\n dll_root,\n ),\n )\n\n # TODO: Linker script must be run from repo root for now. This should probably changed\n cmd = \"cd {} && {}\".format(paths.join(\"$GEN_DIR\", fbcode_dir), \" \".join(cmd))\n\n fb_native.cxx_genrule(\n name = name,\n visibility = visibility,\n out = lib_name,\n cmd = cmd,\n )\n\n# TODO: Remove the default value when haskell rules get converted\ndef _convert_dlls(\n name,\n platform,\n buck_platform,\n dlls,\n visibility):\n \"\"\"\n Creates a genrule that generates DLLs for haskell\n\n Args:\n name: The name of the genrule, and base name for intermediate rules\n platform: The fbcode platform to use for generating the deps query\n buck_platform: The buck platform to use for generating the deps query\n dlls: A dictionary of:\n ->\n (dll_root, type_filter, name_filter, dll_type) where dll_root is the\n target that provides the library, type_filter is a regex to filter\n what type of rules to grab symbols from, name_filter is a regex for\n names to grab symbols from, and dll_type is one of \"shared\", \"static\",\n or \"static-pic\"\n visibility: The visibility for the rule\n\n Returns:\n A tuple of (\n [dependencies to use generated dlls],\n [ldflags to use when linking with the dlls],\n [queries that can be used with deps_query attributes],\n )\n \"\"\"\n\n base_path = native.package_name()\n if not dlls:\n fail(\"No dlls were provided\")\n\n deps = []\n ldflags = []\n dep_queries = []\n\n # Generate the rules that link the DLLs.\n dll_targets = {}\n for dll_lib_name, (dll_root, type_filter, name_filter, dll_type) in dlls.items():\n dll_name = name + \".\" + dll_lib_name\n dll_targets[dll_lib_name] = \":\" + dll_name\n _dll_rules(\n dll_name,\n dll_lib_name,\n dll_root + \"-dll-root\",\n type_filter,\n name_filter,\n dll_type,\n get_project_root_from_gen_dir(),\n visibility,\n )\n\n # Create the rule which extracts the symbols from all DLLs.\n sym_target = _dll_needed_syms_list_rule(name, dll_targets.values(), visibility)\n\n # Create the rule which sets up a linker script with all missing DLL\n # symbols marked as extern.\n syms_linker_script_target = _dll_syms_linker_script_rule(name, sym_target, visibility)\n ldflags.append(\"$(location {})\".format(syms_linker_script_target))\n\n # Make sure all symbols needed by the DLLs are exported to the binary's\n # dynamic symbol table.\n ldflags.append(\"-Xlinker\")\n ldflags.append(\"--export-dynamic\")\n\n # Form a sub-query which matches all deps relevant to the current\n # platform.\n first_order_dep_res = [\n # Match any non-third-party deps.\n \"((?!//third-party-buck/.{0,100}).*)\",\n # Match any third-party deps for the current platform.\n \"(//third-party-buck/{0}/.*)\".format(platform),\n ]\n\n # Form a sub-query to exclude all of the generated-lib deps, in particular\n # sanitizer-configuration libraries\n generated_lib = \"(?//TARGETS)\n - except those that are superseded by newer versions in stackage\n \"\"\"\n packages = [\n \"array\",\n \"base\",\n \"binary\",\n \"bytestring\",\n \"Cabal\",\n \"containers\",\n \"deepseq\",\n \"directory\",\n \"filepath\",\n \"ghc\",\n \"ghci\",\n \"ghc-boot\",\n \"ghc-boot-th\",\n \"ghc-prim\",\n \"hpc\",\n \"integer-gmp\",\n \"pretty\",\n \"process\",\n \"rts\",\n \"template-haskell\",\n \"terminfo\",\n \"time\",\n \"transformers\",\n \"unix\",\n ]\n\n if _get_ghc_version(platform) == \"8.4.4\":\n packages.extend([\n \"ghc-compact\",\n \"mtl\",\n \"parsec\",\n \"stm\",\n \"text\",\n \"xhtml\",\n ])\n else:\n packages.extend([\n \"compact\",\n \"hoopl\",\n ])\n\n return packages\n\ndef _get_dep_for_package(package, platform):\n \"\"\"\n Convert arguments in the `package` parameter to actual deps.\n \"\"\"\n\n if is_list(package) or is_tuple(package):\n package, _ = package\n\n # TODO: ghc-8.4.4\n if (package == \"compact\" and\n _get_ghc_version(platform) == \"8.4.4\"):\n package = \"ghc-compact\"\n if package in _get_internal_ghc_packages(platform):\n project = \"ghc\"\n else:\n project = \"stackage-lts\"\n\n return target_utils.ThirdPartyRuleTarget(project, package)\n\nhaskell_common = struct(\n convert_dlls = _convert_dlls,\n get_compiler_flags = _get_compiler_flags,\n get_dep_for_package = _get_dep_for_package,\n get_ghc_version = _get_ghc_version,\n get_language_options = _get_language_options,\n get_warnings_flags = _get_warnings_flags,\n read_extra_ghc_compiler_flags = _read_extra_ghc_compiler_flags,\n read_extra_ghc_linker_flags = _read_extra_ghc_linker_flags,\n read_hs_debug = _read_hs_debug,\n read_hs_eventlog = _read_hs_eventlog,\n read_hs_profile = _read_hs_profile,\n)\n","sub_path":"infra_macros/fbcode_macros/build_defs/lib/haskell_common.bzl","file_name":"haskell_common.bzl","file_ext":"bzl","file_size_in_byte":18430,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"369340974","text":"# Kevin enario\n# yelp dataset - business\n# transformation\n\n# native imports\nimport json\n\n# third party imports\nimport pandas as pd\nimport matplotlib.pyplot as plt\n\n# engineer data\ndef main():\n df = pd.read_csv('csv/yelp_business_dataset_cleaned.csv') \n \n df['review_count'] = get_max_min(df['review_count']) \n df.to_csv('yelp_business_dataset_transformed.csv', index=False)\n\n print('')\n print('Data transformation')\n\ndef get_max_min(df):\n df = df.map(lambda x: (x - df.min()) / (df.max() - df.min()))\n \n return df\n\n##################################################### run main ############################################\nif __name__ == '__main__':\n main()","sub_path":"dataPreprocessing/yelpBusinessDataset/businessDataTransformation.py","file_name":"businessDataTransformation.py","file_ext":"py","file_size_in_byte":677,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"213972749","text":"\"\"\"Boggle word check.\n\nGiven a 5x5 boggle board, see if you can find a given word in it.\n\nIn Boggle, you can start with any letter, then move in any NEWS direction.\nYou can continue to change directions, but you cannot use the exact same\ntile twice.\n\nSo, for example::\n\n N C A N E\n O U I O P\n Z Q Z O N\n F A D P L\n E D E A Z\n \nIn this grid, you could find `NOON* (start at the `N` in the top\nrow, head south, and turn east in the third row). You cannot find\nthe word `CANON` --- while you can find `CANO` by starting at the\ntop-left `C`, you can 't re-use the exact same `N` tile on the\nfront row, and there's no other `N` you can reach.\n\nFor example::\n\n >>> board = make_board('''\n ... N C A N E\n ... O U I O P\n ... Z Q Z O N\n ... F A D P L\n ... E D E A Z\n ... ''')\n\n`NOON` should be found (0, 3) -> (1, 3) -> (2, 3) -> (2, 4)::\n \n >>> find(board, \"NOON\")\n True\n\n`NOPE` should be found (0, 3) -> (1, 3) -> (1, 4) -> (0, 4)::\n\n >>> find(board, \"NOPE\")\n True\n\n`CANON` can't be found (`CANO` starts at (0, 1) but can't find\nthe last `N` and can't re-use the N)::\n\n >>> find(board, \"CANON\")\n False\n\nYou cannot travel diagonally in one move, which would be required\nto find `QUINE`::\n\n >>> find(board, \"QUINE\")\n False\n\nWe can recover if we start going down a false path (start 3, 0)::\n\n >>> find(board, \"FADED\")\n True\n\"\"\"\n\n\ndef make_board(board_string):\n \"\"\"Make a board from a string.\n\n For example::\n\n >>> board = make_board('''\n ... N C A N E\n ... O U I O P\n ... Z Q Z O N\n ... F A D P L\n ... E D E A Z\n ... ''')\n\n >>> len(board)\n 5\n\n >>> board[0]\n ['N', 'C', 'A', 'N', 'E']\n \"\"\"\n\n\ndef find(board, word):\n \"\"\"Can word be found in board?\"\"\"\n\n #through the entire board, 25 letters\n for i in range(5): \n for j in range(5):\n\n if used_squares( board, word, [(i, j)] ):\n return True\n\n return False #common pattern to return False after exhausting a loop\n\n\n\ndef used_squares(board, word, past_positions):\n \"\"\"Must also keep track of the history of the game.\"\"\"\n\n # explicitly looping through the entire board\n # conditions: \n # 1. do i see the letter im sitting on\n # 2. if its adjacent ot the prev letter\n # 3. whether if its already seen in my history\n\n if word == \"\":\n return True\n\n prev = past_positions[-1] # position letter we *just* saw\n\n for i in range(5):\n for j in range(5):\n\n if (word[0] == board[i][j]) \\\n and ((i, j) not in past_positions) \\\n and ( abs(i - pre[0]) + abs(j - prev[1]) ) == 1: #abs val must sum up to 1, if any only if you moved one step horz/vert\n\n past_positions.append((i, j))\n\n if use_squares(board, word[1:], past_positions):\n return True\n\n return False\n","sub_path":"coding_exercise.py","file_name":"coding_exercise.py","file_ext":"py","file_size_in_byte":2916,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"368639806","text":"class workspace:\n def __init__( self, name, ranges=[[-100,100],[-100,100],[-100,100]] ):\n self._contents = []\n self._name = name\n self._axes_ranges = ranges\n\n def addObject( self, object_, coordinates ):\n self._contents.append( object_ )\n object_.place(coordinates)\n\n def show( self ):\n import numpy as np\n import matplotlib as mpl\n import matplotlib.pyplot as plt\n from mpl_toolkits.mplot3d import Axes3D\n from mpl_toolkits.mplot3d.art3d import Poly3DCollection\n mpl.rcParams['legend.fontsize'] = 10\n fig = plt.figure()\n ax = fig.add_subplot(111,projection='3d')\n ax.set_xlim(*self._axes_ranges[0])\n ax.set_ylim(*self._axes_ranges[1])\n ax.set_zlim(*self._axes_ranges[2])\n ax.grid(which='major')\n for object_ in self._contents:\n to_plot = object_.plot()\n for line in to_plot:\n ax.plot(*line, color=object_._colour)\n plt.show()\n\nif __name__ in \"__main__\":\n from plane import plane\n from cylinder import cylinder\n from math import pi\n ws = workspace('workspace', ranges=[[-20,20],[-20,20],[-20,20]])\n box_1 = plane( 0.5, 5, 5, colour='g', rotation=[pi/2.,0,0] )\n ws.addObject(box_1, [0,0,0])\n # box_2 = plane( 0.5, 6, 6, colour= 'greenyellow' )\n # ws.addObject(box_2, [0,1.5,0])\n # box_2 = plane( 0.5, 7, 7, colour= 'g' )\n # ws.addObject(box_2, [0,3.,0])\n # box_2 = plane( 0.5, 8, 8, colour= 'greenyellow' )\n # ws.addObject(box_2, [0,4.5,0])\n # box_2 = plane( 0.5, 9, 9, colour= 'g' )\n # ws.addObject(box_2, [0,6,0])\n ws.show()\n","sub_path":"pymatplotcad/workspace.py","file_name":"workspace.py","file_ext":"py","file_size_in_byte":1672,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"70246336","text":"from django.shortcuts import render\nfrom .forms import FoodForm, MultipleFoodForm\nfrom django.forms import formset_factory\nfrom .models import Food\n\ndef home(request):\n return render(request, 'order/home.html')\n\ndef order(request):\n multiple_form = MultipleFoodForm()\n if request.method == 'POST':\n filled_form = FoodForm(request.POST) # , request.FILES\n if filled_form.is_valid():\n created_food = filled_form.save()\n created_food_pk = created_food.id\n note = 'Thanks for ordering. Your {0} {1} and {2} food is on its way!'.\\\n format(filled_form.cleaned_data['size'],\n filled_form.cleaned_data['topping1'], filled_form.cleaned_data['topping2'])\n filled_form = FoodForm()\n else:\n created_food_pk = None\n note = 'Pizza order has failed, try again!'\n return render(request, 'order/order.html',\n {\n 'created_food_pk': created_food_pk,\n 'foodform': filled_form, 'note': note, 'multiple_form': multiple_form\n })\n else:\n form = FoodForm()\n return render(request, 'order/order.html',\n {\n 'foodform': form, 'multiple_form': multiple_form\n })\n\n\ndef foods(request):\n number_of_foods = 2\n filled_multiple_food_form = MultipleFoodForm(request.GET)\n if filled_multiple_food_form.is_valid():\n number_of_foods = filled_multiple_food_form.cleaned_data['number']\n FoodFormSet = formset_factory(FoodForm, extra=number_of_foods)\n formset = FoodFormSet()\n if request.method == 'POST':\n filled_formset = FoodFormSet(request.POST)\n if filled_formset.is_valid():\n for form in filled_formset:\n print(form.cleaned_data['topping1'])\n note = 'Foods have been ordered!'\n else:\n note = 'Order was not created. Please, try again'\n return render(request, 'order/foods.html', {'note': note, 'formset': formset})\n else:\n return render(request, 'order/foods.html', {'formset': formset})\n\ndef edit_order(request, pk):\n food = Food.objects.get(pk=pk)\n form = FoodForm(instance=food)\n if request.method == 'POST':\n filled_form = FoodForm(request.POST, instance=food)\n if filled_form.is_valid():\n filled_form.save()\n form = filled_form\n note = 'Order has been updated!'\n return render(request, 'order/edit_order.html', {'foodform': form, 'food': food, 'note': note})\n return render(request, 'order/edit_order.html', {'foodform': form, 'food': food})\n\n","sub_path":"order/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2726,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"192666097","text":"#author=Liujun Chen\n#create time 2020-11-30 13:54:48\n\nimport numpy as np\nfrom Externals import calculate_T\nfrom Externals import calculate_gamma_new\nfrom single_estimate import single_worker\n\ndef DC_rho(x, n, m, k_n,k_rho, tau):\n rho = np.zeros(m)\n M1_1,M1_2=np.zeros(m),np.zeros(m)\n\n for i in range(int(m)):\n x_temp = x[(i*n):(i * n + n)].copy() # cut the data into different machines\n # append the gamma in each machine\n M1_1[i],M1_2[i],M2_1,M2_2,M2_3 = single_worker(x_temp,k_n,k_rho)\n T= calculate_T(M2_1,M2_2,M2_3,tau[0])\n rho[i] = -3 * np.abs( (T-1) / (T-3) )\n M1_1, M1_2,rho = np.mean(M1_1), np.mean(M1_2),np.mean(rho)\n res_gamma=calculate_gamma_new(M1_1,M1_2,rho,k_n)\n return res_gamma\n\n\n","sub_path":"EVA2021/program/src/DC_rho.py","file_name":"DC_rho.py","file_ext":"py","file_size_in_byte":750,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"144201551","text":"import numpy as np\nfrom mazelab import ObjectDirectory\nfrom mazelab.generators import BaseGenerator\nfrom mazelab.generators import random_maze\nfrom mazelab import DeepMindColor as color\nimport matplotlib.pyplot as plt\nfrom mazelab import Object\nfrom mazelab import BaseNavigationEnv\nfrom mazelab import Maze\nfrom mazelab import Motion\nfrom gym.wrappers import Monitor\nfrom mazelab.solvers import dijkstra_solver\nimport matplotlib.pyplot as plt\nfrom mazelab import Motion\nimport cv2\n\nclass Generator(BaseGenerator):\n def make_objects(self):\n obj_dir = ObjectDirectory(['value', 'color'])\n obj_dir.add_object('obstacle', 1, color.obstacle, True)\n obj_dir.add_object('free', 0, color.free, False)\n\n return obj_dir\n\n def __call__(self):\n x = random_maze(width=81, height=51, complexity=.75, density=.75)\n out = x.tolist()\n\n # print(out)\n\n for h, w in np.dstack(np.where(x == 1))[0]:\n out[h][w] = self.obstacle\n for h, w in np.dstack(np.where(x == 0))[0]:\n out[h][w] = self.free\n\n return out\n\n\ngenerator = Generator()\nmaze = Maze(generator)\nmaze.to_value()\n\n# print(maze.to_value())\n# for i in maze.to_value():\n# print(i)\nprint(len(maze.to_value()))\n\nmotion = Motion()\nmotion.add('north', [-1, 0])\nmotion.add('south', [1, 0])\nmotion.add('west', [0, -1])\nmotion.add('east', [0, 1])\n\n\nclass Env(BaseNavigationEnv):\n def step(self, action):\n action_name, delta = self.motion[action]\n\n current_position = self.state.positions[0] # single agent\n new_position = [current_position[0] + delta[0], current_position[1] + delta[1]]\n\n valid = self.is_valid(new_position)\n if valid:\n self.state.positions[0] = new_position # single agent\n\n if self.is_goal(new_position):\n reward = +1\n done = True\n elif not valid:\n reward = -1\n done = False\n else:\n reward = -0.01\n done = False\n\n info = {}\n\n return self.get_observation(), reward, done, info\n\n def reset(self):\n self.state = self.make_state()\n self.goal = self.make_goal()\n\n return self.get_observation()\n\n def make_state(self):\n state = Object('state', 2, color.agent, True, [[1, 1]])\n\n return state\n\n def make_goal(self):\n goal = Object('goal', 3, color.goal, False, [[49, 79]])\n # print(goal)\n return goal\n\n def is_valid(self, position):\n nonnegative = position[0] >= 0 and position[1] >= 0\n\n size = maze.size\n within_edge = position[0] < size[0] and position[1] < size[1]\n\n passable = not maze.to_impassable()[position[0]][position[1]]\n\n return nonnegative and within_edge and passable\n\n def is_goal(self, position):\n out = False\n for goal_position in self.goal.positions:\n if position[0] == goal_position[0] and position[1] == goal_position[1]:\n out = True\n\n return out\n\n\nenv = Env(maze, motion)\nimg = env.render('rgb_array')\n\n# cv2.imshow(\"show\", img)\n# cv2.waitKey(0)\n\n\n\nactions = dijkstra_solver(np.array(env.maze.to_impassable()), env.motion, env.state.positions[0], env.goal.positions[0])\n\n# print(actions)\n# print(actions)\n# #\n# # env = Monitor(env, directory='./', force=True)\n# # env.reset()\n# # for action in actions:\n# # env.step(action)\n# env.close()","sub_path":"hard_maze.py","file_name":"hard_maze.py","file_ext":"py","file_size_in_byte":3409,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"610415480","text":"import os,sys,inspect\npkg = \"~/public_html/oop/codesnips\"\nsys.path.append(os.path.dirname(os.path.expanduser(pkg)))\nfrom Post import *\n\nclass Comment(Post):\n\tdef __init__(self, id, userId, upvotes, downvotes, lastChanged, snippetId, message):\n\t\tPost.__init__(self, id, userId, upvotes, downvotes, lastChanged)\n\t\tself.snippetId = snippetId\n\t\tself.message = message\n\nclass NullComment(object):\n\tdef __init__(self):\n\t\tself.isNull = True","sub_path":"codesnips/models/Comment.py","file_name":"Comment.py","file_ext":"py","file_size_in_byte":433,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"467123639","text":"\"\"\"\nService related utilities which don't require knowledge of the schema.\n\"\"\"\nimport itertools\nfrom datetime import datetime\nfrom typing import Optional, no_type_check\nimport pyarrow as pa\nimport strawberry.asgi\nfrom starlette.middleware import base\nfrom strawberry.utils.str_converters import to_camel_case\nfrom .core import Table as T\nfrom .inputs import Projections\nfrom .models import Column, doc_field\nfrom .scalars import Long\n\n\ndef references(node):\n \"\"\"Generate every possible column reference.\"\"\"\n if hasattr(node, 'name'):\n yield node.name.value\n value = getattr(node, 'value', None)\n yield getattr(value, 'value', value)\n nodes = itertools.chain(\n getattr(node, 'arguments', []),\n getattr(node, 'fields', []),\n getattr(value, 'fields', []),\n getattr(value, 'values', []),\n getattr(getattr(node, 'selection_set', None), 'selections', []),\n )\n for node in nodes:\n yield from references(node)\n\n\nclass TimingMiddleware(base.BaseHTTPMiddleware):\n async def dispatch(self, request, call_next): # pragma: no cover\n start = datetime.now()\n try:\n return await call_next(request)\n finally:\n end = datetime.now()\n print(f\"[{end.replace(microsecond=0)}]: {end - start}\")\n\n\nclass GraphQL(strawberry.asgi.GraphQL):\n def __init__(self, root_value, **kwargs):\n schema = strawberry.Schema(type(root_value), types=Column.__subclasses__())\n super().__init__(schema, **kwargs)\n self.root_value = root_value\n\n async def get_root_value(self, request):\n return self.root_value\n\n\n@strawberry.interface\nclass AbstractTable:\n def __init__(self, table: pa.Table):\n self.table = table\n self.case_map = {to_camel_case(name): name for name in getattr(table, 'column_names', [])}\n\n def to_snake_case(self, name):\n return self.case_map.get(name, name)\n\n def select(self, info) -> pa.Table:\n \"\"\"Return table with only the columns necessary to proceed.\"\"\"\n names = set(map(self.to_snake_case, references(*info.field_nodes)))\n return self.table.select(names & set(self.table.column_names))\n\n @doc_field\n def length(self) -> Long:\n \"\"\"number of rows\"\"\"\n return len(self.table) # type: ignore\n\n @doc_field\n @no_type_check\n def column(self, name: str, apply: Optional[Projections] = ()) -> Column:\n \"\"\"Return column of any type by name, with optional projection.\n This is typically only needed for aliased columns added by `apply` or `aggregate`.\n If the column is in the schema, `columns` can be used instead.\"\"\"\n column = self.table[self.to_snake_case(name)]\n for func, name in dict(apply).items():\n column = T.projected[func](column, self.table[self.to_snake_case(name)])\n return Column.cast(column)\n","sub_path":"graphique/middleware.py","file_name":"middleware.py","file_ext":"py","file_size_in_byte":2873,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"515871416","text":"clears = []\nunclears = []\nanswers = []\n\nthing = input()\nif thing[0] == 'C':\n clears.append(1)\nelif thing[0] == 'U':\n unclears.append(1)\nif thing[1] == 'C':\n clears.append(2)\nelif thing[1] == 'U':\n unclears.append(2)\nif thing[2] == 'C':\n clears.append(3)\nelif thing[2] == 'U':\n unclears.append(3)\nthing = input()\nif thing[0] == 'C':\n clears.append(4)\nelif thing[0] == 'U':\n unclears.append(4)\nif thing[1] == 'C':\n clears.append(5)\nelif thing[1] == 'U':\n unclears.append(5)\nif thing[2] == 'C':\n clears.append(6)\nelif thing[2] == 'U':\n unclears.append(6)\nthing = input()\nif thing[0] == 'C':\n clears.append(7)\nelif thing[0] == 'U':\n unclears.append(7)\nif thing[1] == 'C':\n clears.append(8)\nelif thing[1] == 'U':\n unclears.append(8)\nif thing[2] == 'C':\n clears.append(9)\nelif thing[2] == 'U':\n unclears.append(9)\nthing = input()\nif thing[1] == 'C':\n clears.append(0)\nelif thing[1] == 'U':\n unclears.append(0)\n\n\n\n\nfor i in (clears + unclears):\n for j in (clears + unclears):\n for k in (clears + unclears):\n for l in (clears + unclears):\n # print(i)\n # print(j)\n # print(k)\n # print(l)\n asdf = True\n for c in clears:\n if c not in [i, j, k, l]:\n asdf = False\n if asdf:\n if i * 10 + j == (k * 10 + l) * (k * 10 + l):\n answers.append(str(i) + str(j) + str(k) + str(l))\nif (len(answers) > 3):\n print('WILL NOT WIN BET')\nelif (len(answers) == 0):\n print('COULD NOT DETERMINE CODE')\nelif (len(answers) == 1):\n print(f'CODE IS: {answers[0]}')\nelse:\n for i in answers:\n print(f'POSSIBLE MATCH: {i}')","sub_path":"CodeWars/2019/prob20.py3","file_name":"prob20.py3","file_ext":"py3","file_size_in_byte":1773,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"610042769","text":"import unittest\nimport os\n\nfrom replus import Engine\n\n__HERE__ = os.path.dirname(os.path.abspath(__file__))\n\ntest_models_path = os.path.join(__HERE__, \"test_models\")\nengine = Engine(test_models_path)\n\n\nclass TestEngine(unittest.TestCase):\n\n def test_parser_regex(self):\n patterns = [p.pattern for k, p, t in engine.patterns if k == \"tests\"]\n expected = [\n r\"This is an unnamed number group: (?:\\d).\",\n r\"I can match (?Palpha|beta|gamma) and (?Palpha|beta|gamma), and then re-match the last (?P=abg_1) or the second last (?P=abg_0)\",\n ]\n for i, p in enumerate(patterns):\n self.assertEqual(p, expected[i])\n\n def test_match(self):\n matches = engine.parse(\"Today it's january 1st 1970\")\n self.assertEqual(len(matches), 1)\n date = matches[0]\n self.assertEqual(date.value, \"january 1st 1970\")\n month = date.group(\"month_name\")\n self.assertEqual(month.value, \"january\")\n day = date.group(\"day\")\n self.assertEqual(day.value, \"1\")\n year = date.group(\"year\")\n self.assertEqual(year.value, \"1970\")\n\n\nif __name__ == \"__main__\":\n unittest.main(verbosity=2)\n","sub_path":"tests/tests.py","file_name":"tests.py","file_ext":"py","file_size_in_byte":1198,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"560945322","text":"\"\"\"\n707. Design Linked List\n- Doubly Linked List\n\n# Using return\nThis is used the same reason as break. \nThe return value doesn't matter and you only want to exit the whole function.\n\ndef noReturnFunction():\n return\n\nResult: 260 ms\n\"\"\"\n\n\nclass Node(object): # Node class to be used for linked list\n\n def __init__(self, val):\n self.val = val # Value of current node\n self.next = None # Pointer to the next node\n self.prev = None # Pointer to the prev node\n\n\nclass MyLinkedList: # Initializes the MyLinkedList object\n\n def __init__(self):\n \"\"\"\n Initialize your data structure here.\n \"\"\"\n self.head = None # Pointer to the head\n self.size = 0 # head size = 0\n\n def get(self, index: int) -> int:\n \"\"\"\n Get the value of the index-th node in the linked list. \n If the index is invalid, return -1.\n \"\"\"\n if self.head is None or index >= self.size:\n return -1\n\n curr = self.head # Start at head\n for i in range(index):\n curr = curr.next # Move to index-th node\n\n return curr.val\n\n def addAtHead(self, val: int) -> None:\n \"\"\"\n Add a node of value val before the first element of the linked list. \n After the insertion, the new node will be the first node of the linked list.\n \"\"\"\n node = Node(val) # Initialize a new node\n node.next = self.head # Point node.next to current head\n self.head = node # Point self.head to the new node\n self.prev = node # Point self.prev to the new node\n\n self.size += 1 # Increase size by 1\n\n def addAtTail(self, val: int) -> None:\n \"\"\"\n Append a node of value val to the last element of the linked list.\n \"\"\"\n node = Node(val) # Initialize a new node\n curr = self.head # Start at the head\n if curr is None: # If head is none, current head is val\n self.head = node\n else:\n while curr.next is not None: # Move to the end of the linked list\n curr = curr.next\n curr.next = node # Add at the tail\n node.prev = curr # Point node.prev to the current node\n\n self.size += 1 # Increase size by 1\n\n def addAtIndex(self, index: int, val: int) -> None:\n \"\"\"\n Add a node of value val before the index-th node in the linked list. \n If index equals to the length of linked list, the node will be appended to the end of linked list. \n If index is greater than the length, the node will not be inserted.\n \"\"\"\n if index > self.size: # If index is out of bound, nothing happens\n return # Similar to break\n\n curr = self.head\n if index == 0: # 0-th index is head\n self.addAtHead(val)\n else:\n for i in range(index - 1): # Move to one before the index-th node\n curr = curr.next\n node = Node(val) # Initialize a new node\n node.next = curr.next # Point new node.next to curr.next\n curr.next = node # Point curr.next to the new node\n node.prev = curr # Point node.prev to the current node\n\n self.size += 1\n\n def deleteAtIndex(self, index: int) -> None:\n \"\"\"\n Delete the index-th node in the linked list, if the index is valid.\n \"\"\"\n if index < 0 or index >= self.size: # If index is out of bound, nothing happens\n return # Similar to break\n\n curr = self.head\n if index == 0: # 0-th index is head\n self.head = curr.next # The new head is now curr.next\n else:\n for i in range(index - 1): # Move to one before the index-th node\n curr = curr.next\n curr.next.prev = curr # Point curr.next.prev to current node\n curr.next = curr.next.next # Point curr.next to curr.next.next\n\n self.size -= 1\n\n# Your MyLinkedList object will be instantiated and called as such:\n# obj = MyLinkedList()\n# param_1 = obj.get(index)\n# obj.addAtHead(val)\n# obj.addAtTail(val)\n# obj.addAtIndex(index,val)\n# obj.deleteAtIndex(index)\n","sub_path":"Linked-List/0707_MyLinkedList_2.py","file_name":"0707_MyLinkedList_2.py","file_ext":"py","file_size_in_byte":4706,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"45261832","text":"#!/bin/env python3\n# Differentially private Bayesian linear regression \n# Arttu Nieminen 2016-2017\n# University of Helsinki Department of Computer Science\n# Helsinki Institute of Information Technology HIIT\n\n# GDSC/drug sensitivity data\n# Test each sensible split with given synthetic data and noise sample\n# that were generated using budgetsplit_pre.py (ln data sets and ln^2 noise samples)\n\n# Run (on a computer cluster): python3 budgetsplit_test.py i j k\n# where\n# - i = 0..ln-1 (specifies data)\n# - j = 0..ln-1 (together with i specifies noise)\n# - k = 0..17 (specifies budget split for nxx)\n# Should be run for each tuple (i,j,k) in {0..ln-1}x{0..ln-1}x{0..17}\n# Here ln = 5\n\nimport sys\nimport os\n\n# Create a new Theano compile directory on local node (used in cluster computing)\nif len(sys.argv) > 3:\n\tv1 = int(sys.argv[1])\n\tv2 = int(sys.argv[2])\n\tv3 = int(sys.argv[3])\n\tmypath1 = \"theano\"\n\tmypath2 = mypath1+\"/theano-tmp-\"+str(v1)+\"-\"+str(v2)+\"-\"+str(v3)\n\tif not os.path.exists(mypath1):\n\t\tos.mkdir(mypath1)\n\tif not os.path.exists(mypath2):\n\t\tos.mkdir(mypath2)\n\tos.environ[\"THEANO_FLAGS\"] = \"base_compiledir=\"+mypath1+\",compiledir=\"+mypath2\n\nimport diffpri as dp\nimport numpy as np\nimport csv\n\n# Same parameters as in budgetsplit_pre.py:\nn = 500\t\t# number of samples in synthetic data sets\nd = 10\t\t# dimensionality of synthetic data sets\neps = 2.0\t# privacy budget used in tests\nl0 = 1\t\t# precision parameters ..\nl = 1\t\t# .. (correspond to the means of the gamma hyperpriors)\nln = 5\t\t# average results over ln synthetic data sets and ln noise samples for each data set\n\ndatapath = ''\t# TODO: set input/output file path\n\nnp.random.seed(42) # for reproducibility\n\n# Arguments\nif len(sys.argv) > 3:\n\ti = int(sys.argv[1])\n\tj = int(sys.argv[2])\n\tk = int(sys.argv[3])\nelse: # default\n\ti = 0\n\tj = 0\n\tk = 0\n\n# Import ith data\nf = np.load(datapath+'budgetsplit-data.npz')\nx = f['xdata'][i]\ny = f['ydata'][i]\nsx = f['sxdata'][i]\nsy = f['sydata'][i]\nf.close()\n\n# Import jth noise for ith data\njj = ln*i+j\nf = np.load(datapath+'budgetsplit-noise.npz')\nW = f['wnoise'][jj]\nL = f['lnoise'][jj]\nV = f['vnoise'][jj]\nf.close()\n\n# Define and test splits\np = np.arange(0.05,0.95,0.05)\nlenp = len(p)\nminp = 0.03\nmaxp = 0.97\n\nerr = np.zeros((lenp,lenp),dtype=np.float64)\n\nfor m in range(lenp):\n\n\t# Budget split\n\tp1 = p[k]\n\tp2 = p[m]\n\tp3 = 1.0-p1-p2\n\t\n\t# Check if split is sensible\n\tt1 = minp <= p1 and p1 <= maxp\n\tt2 = minp <= p2 and p2 <= maxp\n\tt3 = minp <= p3 and p3 <= maxp\n\n\tif not all([t1,t2,t3]):\n\t\tcontinue\n\n\t# Clipping omega and thresholds\n\tw_x,w_y = dp.omega(n,d,eps,True,ln=ln,p1=p1,p2=p2,p3=p3)\n\tc1 = sx * w_x\n\tc2 = sy * w_y\n\n\t# Clip data\n\txc,yc = dp.clip(x,y,c1,c2)\n\n\t# Perturbed suff.stats.\n\txx = dp.nxx(xc) + W*(c1**2.0)/p1\n\txy = dp.nxy(xc,yc) + L*c1*c2/p2\n\tyy = dp.nyy(yc) + V*(c2**2.0)/p3\n\n\t# Prediction\n\tpred = dp.doADVI(n,xx,xy,yy,x)\n\n\t# Precision\n\terr[k,m] = dp.precision(pred,y)\n\n# Save result\ncsvpath = datapath+'budgetsplit-result-'+str(i)+'-'+str(j)+'-'+str(k)+'.csv'\nnp.savetxt(csvpath,err,delimiter=',')\n","sub_path":"python/gdscdata/budgetsplit_test.py","file_name":"budgetsplit_test.py","file_ext":"py","file_size_in_byte":3015,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"594250010","text":"# -*- coding: utf-8 -*-\n# Copyright 2021, SERTIT-ICube - France, https://sertit.unistra.fr/\n# This file is part of eoreader project\n# https://github.com/sertit/eoreader\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\"\"\" Product, superclass of all EOReader satellites products \"\"\"\n# pylint: disable=W0107\nfrom __future__ import annotations\n\nimport datetime as dt\nimport logging\nimport os\nimport platform\nimport tempfile\nfrom abc import abstractmethod\nfrom enum import unique\nfrom pathlib import Path\nfrom typing import Any, Callable, Union\n\nimport geopandas as gpd\nimport numpy as np\nimport rasterio\nimport validators\nimport xarray as xr\nfrom affine import Affine\nfrom cloudpathlib import AnyPath, CloudPath\nfrom lxml import etree\nfrom rasterio import crs as riocrs\nfrom rasterio import transform, warp\nfrom rasterio.crs import CRS\nfrom rasterio.enums import Resampling\nfrom sertit import files, misc, rasters, strings\nfrom sertit.misc import ListEnum\nfrom sertit.rasters import XDS_TYPE\nfrom sertit.snap import MAX_CORES\n\nfrom eoreader import utils\nfrom eoreader.bands import index\nfrom eoreader.bands.alias import *\nfrom eoreader.bands.bands import BandNames\nfrom eoreader.env_vars import CI_EOREADER_BAND_FOLDER, DEM_PATH\nfrom eoreader.exceptions import InvalidProductError\nfrom eoreader.reader import Platform, Reader\nfrom eoreader.utils import EOREADER_NAME\n\nLOGGER = logging.getLogger(EOREADER_NAME)\nPRODUCT_FACTORY = Reader()\n\n\n@unique\nclass SensorType(ListEnum):\n \"\"\"\n Sensor type of the products, optical or SAR\n \"\"\"\n\n OPTICAL = \"Optical\"\n \"\"\"For optical data\"\"\"\n\n SAR = \"SAR\"\n \"\"\"For SAR data\"\"\"\n\n\nclass Product:\n \"\"\"Super class of EOReader Products\"\"\"\n\n def __init__(\n self,\n product_path: Union[str, CloudPath, Path],\n archive_path: Union[str, CloudPath, Path] = None,\n output_path: Union[str, CloudPath, Path] = None,\n remove_tmp: bool = False,\n ) -> None:\n self.path = AnyPath(product_path)\n \"\"\"Usable path to the product, either extracted or archived path, according to the satellite.\"\"\"\n\n self.name = files.get_filename(self.path)\n \"\"\"Product name (its filename without any extension).\"\"\"\n\n self.split_name = self._get_split_name()\n \"\"\"\n Split name, to retrieve every information from its filename (dates, tile, product type...).\n **WARNING**: Use it with caution as EOReader accepts products with modified names !\n \"\"\"\n\n self.archive_path = AnyPath(archive_path) if archive_path else self.path\n \"\"\"Archive path, same as the product path if not specified.\n Useful when you want to know where both the extracted and archived version of your product are stored.\"\"\"\n\n self.is_archived = self.path.is_file()\n \"\"\" Is the archived product is processed\n (a products is considered as archived if its products path is a directory).\"\"\"\n\n self.needs_extraction = True\n \"\"\"Does this products needs to be extracted to be processed ? (`True` by default).\"\"\"\n\n # The output will be given later\n if output_path:\n self._tmp_output = None\n self._output = AnyPath(output_path)\n else:\n self._tmp_output = tempfile.TemporaryDirectory()\n self._output = AnyPath(self._tmp_output.name)\n \"\"\"Output directory of the product, to write orthorectified data for example.\"\"\"\n\n # Store metadata\n metadata, namespaces = self._read_mtd()\n self._metadata = metadata\n self._namespaces = namespaces\n\n # Get the products date and datetime\n self.date = self.get_date(as_date=True)\n \"\"\"Acquisition date.\"\"\"\n self.datetime = self.get_datetime(as_datetime=True)\n \"\"\"Acquisition datetime.\"\"\"\n\n self.tile_name = None\n \"\"\"Tile if possible (for data that can be piled, for example S2 and Landsats).\"\"\"\n\n self.sensor_type = None\n \"\"\"Sensor type, SAR or optical.\"\"\"\n\n self.product_type = None\n \"\"\"Product type, satellite-related field, such as L1C or L2A for Sentinel-2 data.\"\"\"\n\n self.band_names = None\n \"\"\"Band mapping between band wrapping names such as `GREEN` and band real number such as `03` for Sentinel-2.\"\"\"\n\n self.is_reference = False\n \"\"\"If the product is a reference, used for algorithms that need pre and post data, such as fire detection.\"\"\"\n\n self.corresponding_ref = []\n \"\"\"The corresponding reference products to the current one\n (if the product is not a reference but has a reference data corresponding to it).\n A list because of multiple ref in case of non-stackable products (S3, S1...)\"\"\"\n\n self.nodata = -9999\n \"\"\" Product nodata, set to 0 by default. Please do not touch this or all index will fail. \"\"\"\n\n # Mask values\n self._mask_true = 1\n self._mask_false = 0\n\n self.platform = self._get_platform()\n \"\"\"Product platform, such as Sentinel-2\"\"\"\n\n # Post initialization\n self._post_init()\n\n # Set product type, needs to be done after the post-initialization\n self._set_product_type()\n\n # Set the resolution, needs to be done when knowing the product type\n self.resolution = self._set_resolution()\n \"\"\"\n Default resolution in meters of the current product.\n For SAR product, we use Ground Range resolution as we will automatically orthorectify the tiles.\n \"\"\"\n\n self.condensed_name = self._get_condensed_name()\n \"\"\"\n Condensed name, the filename with only useful data to keep the name unique\n (ie. `20191215T110441_S2_30TXP_L2A_122756`).\n Used to shorten names and paths.\n \"\"\"\n\n self.sat_id = self.platform.name\n \"\"\"Satellite ID, i.e. `S2` for Sentinel-2\"\"\"\n\n # Temporary files path (private)\n self._tmp_process = self._output.joinpath(f\"tmp_{self.condensed_name}\")\n os.makedirs(self._tmp_process, exist_ok=True)\n self._remove_tmp_process = remove_tmp\n\n # TODO: manage self.needs_extraction\n\n def __del__(self):\n \"\"\"Cleaning up _tmp directory\"\"\"\n if self._tmp_output:\n self._tmp_output.cleanup()\n\n elif self._remove_tmp_process:\n files.remove(self._tmp_process)\n\n @abstractmethod\n def _post_init(self) -> None:\n \"\"\"\n Function used to post_init the products\n (setting sensor type, band names and so on)\n \"\"\"\n raise NotImplementedError(\"This method should be implemented by a child class\")\n\n def footprint(self) -> gpd.GeoDataFrame:\n \"\"\"\n Get UTM footprint of the products (without nodata, *in french == emprise utile*)\n\n .. code-block:: python\n\n >>> from eoreader.reader import Reader\n >>> path = r\"S2A_MSIL1C_20200824T110631_N0209_R137_T30TTK_20200824T150432.SAFE.zip\"\n >>> prod = Reader().open(path)\n >>> prod.footprint()\n index geometry\n 0 0 POLYGON ((199980.000 4500000.000, 199980.000 4...\n\n Returns:\n gpd.GeoDataFrame: Footprint as a GeoDataFrame\n \"\"\"\n def_band = self.get_default_band()\n default_xda = self.load(def_band)[\n def_band\n ] # Forced to load as the nodata may not be positioned by default\n return rasters.get_footprint(default_xda).to_crs(self.crs())\n\n @abstractmethod\n def extent(self) -> gpd.GeoDataFrame:\n \"\"\"\n Get UTM extent of the tile\n\n .. code-block:: python\n\n >>> from eoreader.reader import Reader\n >>> path = r\"S2A_MSIL1C_20200824T110631_N0209_R137_T30TTK_20200824T150432.SAFE.zip\"\n >>> prod = Reader().open(path)\n >>> prod.utm_extent()\n geometry\n 0 POLYGON ((309780.000 4390200.000, 309780.000 4...\n\n Returns:\n gpd.GeoDataFrame: Footprint in UTM\n \"\"\"\n raise NotImplementedError(\"This method should be implemented by a child class\")\n\n @abstractmethod\n def crs(self) -> riocrs.CRS:\n \"\"\"\n Get UTM projection of the tile\n\n .. code-block:: python\n\n >>> from eoreader.reader import Reader\n >>> path = r\"S2A_MSIL1C_20200824T110631_N0209_R137_T30TTK_20200824T150432.SAFE.zip\"\n >>> prod = Reader().open(path)\n >>> prod.utm_crs()\n CRS.from_epsg(32630)\n\n Returns:\n crs.CRS: CRS object\n \"\"\"\n raise NotImplementedError(\"This method should be implemented by a child class\")\n\n def _get_band_folder(self) -> Union[CloudPath, Path]:\n \"\"\"\n Manage the case of CI SNAP Bands\n\n Returns:\n Union[CloudPath, Path]: Band folder\n \"\"\"\n band_folder = self._tmp_process\n\n # Manage CI SNAP band\n ci_band_folder = os.environ.get(CI_EOREADER_BAND_FOLDER)\n if ci_band_folder:\n ci_band_folder = AnyPath(ci_band_folder)\n if ci_band_folder.is_dir():\n band_folder = ci_band_folder\n\n return band_folder\n\n @abstractmethod\n def _set_resolution(self) -> float:\n \"\"\"\n Set product default resolution (in meters)\n \"\"\"\n raise NotImplementedError(\"This method should be implemented by a child class\")\n\n @abstractmethod\n def _set_product_type(self) -> None:\n \"\"\"\n Set product type\n \"\"\"\n raise NotImplementedError(\"This method should be implemented by a child class\")\n\n @classmethod\n def _get_platform(cls) -> Platform:\n class_module = cls.__module__.split(\".\")[-1]\n sat_id = class_module.split(\"_\")[0].upper()\n return getattr(Platform, sat_id)\n\n @abstractmethod\n def _get_condensed_name(self) -> str:\n \"\"\"\n Set product condensed name.\n\n Returns:\n str: Condensed name\n \"\"\"\n raise NotImplementedError(\"This method should be implemented by a child class\")\n\n def _get_split_name(self) -> list:\n \"\"\"\n Get split name (erasing empty strings in it by precaution, especially for S1 and S3 data)\n\n Returns:\n list: Split products name\n \"\"\"\n return utils.get_split_name(self.name)\n\n @abstractmethod\n def get_datetime(self, as_datetime: bool = False) -> Union[str, dt.datetime]:\n \"\"\"\n Get the product's acquisition datetime, with format `YYYYMMDDTHHMMSS` <-> `%Y%m%dT%H%M%S`\n\n .. code-block:: python\n\n >>> from eoreader.reader import Reader\n >>> path = r\"S2A_MSIL1C_20200824T110631_N0209_R137_T30TTK_20200824T150432.SAFE.zip\"\n >>> prod = Reader().open(path)\n >>> prod.get_datetime(as_datetime=True)\n datetime.datetime(2020, 8, 24, 11, 6, 31)\n >>> prod.get_datetime(as_datetime=False)\n '20200824T110631'\n\n Args:\n as_datetime (bool): Return the date as a datetime.datetime. If false, returns a string.\n\n Returns:\n Union[str, datetime.datetime]: Its acquisition datetime\n \"\"\"\n raise NotImplementedError(\"This method should be implemented by a child class\")\n\n def get_date(self, as_date: bool = False) -> Union[str, dt.date]:\n \"\"\"\n Get the product's acquisition date.\n\n .. code-block:: python\n\n >>> from eoreader.reader import Reader\n >>> path = r\"S2A_MSIL1C_20200824T110631_N0209_R137_T30TTK_20200824T150432.SAFE.zip\"\n >>> prod = Reader().open(path)\n >>> prod.get_date(as_date=True)\n datetime.datetime(2020, 8, 24, 0, 0)\n >>> prod.get_date(as_date=False)\n '20200824'\n\n Args:\n as_date (bool): Return the date as a datetime.date. If false, returns a string.\n\n Returns:\n str: Its acquisition date\n \"\"\"\n date = self.get_datetime().split(\"T\")[0]\n\n if as_date:\n date = strings.str_to_date(date, date_format=\"%Y%m%d\")\n\n return date\n\n @abstractmethod\n def get_default_band_path(self) -> Union[CloudPath, Path]:\n \"\"\"\n Get default band path (among the existing ones).\n\n Usually `GREEN` band for optical data and the first existing one between `VV` and `HH` for SAR data.\n\n .. code-block:: python\n\n >>> from eoreader.reader import Reader\n >>> path = r\"S2A_MSIL1C_20200824T110631_N0209_R137_T30TTK_20200824T150432.SAFE.zip\"\n >>> prod = Reader().open(path)\n >>> prod.get_default_band_path()\n 'zip+file://S2A_MSIL1C_20200824T110631_N0209_R137_T30TTK_20200824T150432.SAFE.zip!/S2A_MSIL1C_20200824T110631_N0209_R137_T30TTK_20200824T150432.SAFE/GRANULE/L1C_T30TTK_A027018_20200824T111345/IMG_DATA/T30TTK_20200824T110631_B03.jp2'\n\n Returns:\n Union[CloudPath, Path]: Default band path\n \"\"\"\n raise NotImplementedError(\"This method should be implemented by a child class\")\n\n @abstractmethod\n def get_default_band(self) -> BandNames:\n \"\"\"\n Get default band:\n Usually `GREEN` band for optical data and the first existing one between `VV` and `HH` for SAR data.\n\n .. code-block:: python\n\n >>> from eoreader.reader import Reader\n >>> path = r\"S2A_MSIL1C_20200824T110631_N0209_R137_T30TTK_20200824T150432.SAFE.zip\"\n >>> prod = Reader().open(path)\n >>> prod.get_default_band()\n \n\n\n Returns:\n str: Default band\n \"\"\"\n raise NotImplementedError(\"This method should be implemented by a child class\")\n\n def get_existing_bands(self) -> list:\n \"\"\"\n Return the existing bands.\n\n .. code-block:: python\n\n >>> from eoreader.reader import Reader\n >>> path = r\"S2A_MSIL1C_20200824T110631_N0209_R137_T30TTK_20200824T150432.SAFE.zip\"\n >>> prod = Reader().open(path)\n >>> prod.get_existing_bands()\n [,\n ,\n ,\n ,\n ,\n ,\n ,\n ,\n ,\n ,\n ,\n ,\n ]\n\n Returns:\n list: List of existing bands in the products\n \"\"\"\n raise NotImplementedError(\"This method should be implemented by a child class\")\n\n @abstractmethod\n def get_existing_band_paths(self) -> dict:\n \"\"\"\n Return the existing band paths.\n\n .. code-block:: python\n\n >>> from eoreader.reader import Reader\n >>> path = r\"S2A_MSIL1C_20200824T110631_N0209_R137_T30TTK_20200824T150432.SAFE.zip\"\n >>> prod = Reader().open(path)\n >>> prod.get_existing_band_paths()\n {\n : 'zip+file://S2A_MSIL1C_20200824T110631_N0209_R137_T30TTK_20200824T150432.SAFE.zip!/S2A_MSIL1C_20200824T110631_N0209_R137_T30TTK_20200824T150432.SAFE/GRANULE/L1C_T30TTK_A027018_20200824T111345/IMG_DATA/T30TTK_20200824T110631_B01.jp2',\n ...,\n : 'zip+file://S2A_MSIL1C_20200824T110631_N0209_R137_T30TTK_20200824T150432.SAFE.zip!/S2A_MSIL1C_20200824T110631_N0209_R137_T30TTK_20200824T150432.SAFE/GRANULE/L1C_T30TTK_A027018_20200824T111345/IMG_DATA/T30TTK_20200824T110631_B12.jp2'\n }\n\n Returns:\n dict: Dictionary containing the path of each queried band\n \"\"\"\n raise NotImplementedError(\"This method should be implemented by a child class\")\n\n def get_band_paths(self, band_list: list, resolution: float = None) -> dict:\n \"\"\"\n Return the paths of required bands.\n\n .. code-block:: python\n\n >>> from eoreader.reader import Reader\n >>> from eoreader.bands.alias import *\n >>> path = r\"S2A_MSIL1C_20200824T110631_N0209_R137_T30TTK_20200824T150432.SAFE.zip\"\n >>> prod = Reader().open(path)\n >>> prod.get_band_paths([GREEN, RED])\n {\n : 'zip+file://S2A_MSIL1C_20200824T110631_N0209_R137_T30TTK_20200824T150432.SAFE.zip!/S2A_MSIL1C_20200824T110631_N0209_R137_T30TTK_20200824T150432.SAFE/GRANULE/L1C_T30TTK_A027018_20200824T111345/IMG_DATA/T30TTK_20200824T110631_B03.jp2',\n : 'zip+file://S2A_MSIL1C_20200824T110631_N0209_R137_T30TTK_20200824T150432.SAFE.zip!/S2A_MSIL1C_20200824T110631_N0209_R137_T30TTK_20200824T150432.SAFE/GRANULE/L1C_T30TTK_A027018_20200824T111345/IMG_DATA/T30TTK_20200824T110631_B04.jp2'\n }\n\n Args:\n band_list (list): List of the wanted bands\n resolution (float): Band resolution\n\n Returns:\n dict: Dictionary containing the path of each queried band\n \"\"\"\n raise NotImplementedError(\"This method should be implemented by a child class\")\n\n @abstractmethod\n def _read_mtd(self) -> Any:\n \"\"\"\n Read metadata and outputs the metadata XML root and its namespaces as a dict most of the time,\n except from L8-collection 1 data which outputs a `pandas.DataFrame`\n\n Returns:\n Any: Metadata XML root and its namespace or pd.DataFrame\n \"\"\"\n raise NotImplementedError(\"This method should be implemented by a child class\")\n\n def _read_mtd_xml(self, mtd_from_path: str, mtd_archived: str = None):\n \"\"\"\n Read metadata and outputs the metadata XML root and its namespaces as a dicts as a dict\n\n Args:\n mtd_from_path (str): Metadata regex (glob style) to find from extracted product\n mtd_archived (str): Metadata regex (re style) to find from archived product\n\n Returns:\n (etree._Element, dict): Metadata XML root and its namespaces\n\n \"\"\"\n if self.is_archived:\n root = files.read_archived_xml(self.path, f\".*{mtd_archived}\")\n else:\n # ONLY FOR COLLECTION 2\n try:\n mtd_file = next(self.path.glob(f\"**/*{mtd_from_path}\"))\n if isinstance(mtd_file, CloudPath):\n mtd_file = mtd_file.fspath\n else:\n mtd_file = str(mtd_file)\n\n # pylint: disable=I1101:\n # Module 'lxml.etree' has no 'parse' member, but source is unavailable.\n xml_tree = etree.parse(mtd_file)\n root = xml_tree.getroot()\n except StopIteration as ex:\n raise InvalidProductError(\n f\"Metadata file ({mtd_from_path}) not found in {self.path}\"\n ) from ex\n\n # Get namespaces map (only useful ones)\n nsmap = {key: f\"{{{ns}}}\" for key, ns in root.nsmap.items()}\n pop_list = [\"xsi\", \"xs\", \"xlink\"]\n for ns in pop_list:\n if ns in nsmap.keys():\n nsmap.pop(ns)\n\n return root, nsmap\n\n def read_mtd(self) -> Any:\n \"\"\"\n Read metadata and outputs the metadata XML root and its namespaces as a dict most of the time,\n except from L8-collection 1 data which outputs a `pandas.DataFrame`\n\n .. code-block:: python\n\n >>> from eoreader.reader import Reader\n >>> path = r\"S1A_IW_GRDH_1SDV_20191215T060906_20191215T060931_030355_0378F7_3696.zip\"\n >>> prod = Reader().open(path)\n >>> prod.read_mtd()\n (, '')\n\n Returns:\n Any: Metadata XML root and its namespace or pd.DataFrame\n \"\"\"\n if self._metadata is not None:\n return (self._metadata, self._namespaces)\n else:\n return self._read_mtd()\n\n # pylint: disable=W0613\n def _read_band(\n self,\n path: Union[CloudPath, Path],\n band: BandNames = None,\n resolution: Union[tuple, list, float] = None,\n size: Union[list, tuple] = None,\n ) -> XDS_TYPE:\n \"\"\"\n Read band from disk.\n\n .. WARNING::\n For optical data, invalid pixels are not managed here\n\n Args:\n path (Union[CloudPath, Path]): Band path\n band (BandNames): Band to read\n resolution (Union[tuple, list, float]): Resolution of the wanted band, in dataset resolution unit (X, Y)\n size (Union[tuple, list]): Size of the array (width, height). Not used if resolution is provided.\n Returns:\n XDS_TYPE: Band xarray\n\n \"\"\"\n raise NotImplementedError(\"This method should be implemented by a child class\")\n\n @abstractmethod\n def _load_bands(\n self, band_list: list, resolution: float = None, size: Union[list, tuple] = None\n ) -> dict:\n \"\"\"\n Load bands as numpy arrays with the same resolution (and same metadata).\n\n Args:\n band_list (list): List of the wanted bands\n resolution (int): Band resolution in meters\n size (Union[tuple, list]): Size of the array (width, height). Not used if resolution is provided.\n Returns:\n dict: Dictionary {band_name, band_xarray}\n \"\"\"\n raise NotImplementedError(\"This method should be implemented by a child class\")\n\n def _load_dem(\n self, band_list: list, resolution: float = None, size: Union[list, tuple] = None\n ) -> dict:\n \"\"\"\n Load bands as numpy arrays with the same resolution (and same metadata).\n\n Args:\n band_list (list): List of the wanted bands\n resolution (int): Band resolution in meters\n size (Union[tuple, list]): Size of the array (width, height). Not used if resolution is provided.\n Returns:\n dict: Dictionary {band_name, band_xarray}\n \"\"\"\n dem_bands = {}\n if band_list:\n dem_path = os.environ.get(DEM_PATH) # We already checked if it exists\n for band in band_list:\n assert is_dem(band)\n if band == DEM:\n path = self._warp_dem(dem_path, resolution=resolution, size=size)\n elif band == SLOPE:\n path = self._compute_slope(\n dem_path, resolution=resolution, size=size\n )\n elif band == HILLSHADE:\n path = self._compute_hillshade(\n dem_path, resolution=resolution, size=size\n )\n else:\n raise InvalidTypeError(f\"Unknown DEM band: {band}\")\n\n dem_bands[band] = rasters.read(\n path, resolution=resolution, size=size\n ).astype(np.float32)\n\n return dem_bands\n\n def load(\n self,\n bands: Union[list, BandNames, Callable],\n resolution: float = None,\n size: Union[list, tuple] = None,\n ) -> dict:\n \"\"\"\n Open the bands and compute the wanted index.\n\n The bands will be purged of nodata and invalid pixels,\n the nodata will be set to 0 and the bands will be masked arrays in float.\n\n Bands that come out this function at the same time are collocated and therefore have the same shapes.\n This can be broken if you load data separately. Its is best to always load DEM data with some real bands.\n\n .. code-block:: python\n\n >>> from eoreader.reader import Reader\n >>> from eoreader.bands.alias import *\n >>> path = r\"S2A_MSIL1C_20200824T110631_N0209_R137_T30TTK_20200824T150432.SAFE.zip\"\n >>> prod = Reader().open(path)\n >>> bands = prod.load([GREEN, NDVI], resolution=20)\n >>> bands\n {\n : \n array([[[0.949506 , 0.92181516, 0.9279379 , ..., 1.8002278 ,\n 1.5424857 , 1.6747767 ],\n [0.95369846, 0.91685396, 0.8957871 , ..., 1.5847116 ,\n 1.5248713 , 1.5011379 ],\n [2.9928885 , 1.3031474 , 1.0076253 , ..., 1.5969834 ,\n 1.5590671 , 1.5018653 ],\n ...,\n [1.4245619 , 1.6115025 , 1.6201663 , ..., 1.2387121 ,\n 1.4025431 , 1.800678 ],\n [1.5627214 , 1.822388 , 1.7245892 , ..., 1.1694248 ,\n 1.2573677 , 1.5767351 ],\n [1.653781 , 1.6424649 , 1.5923225 , ..., 1.3072611 ,\n 1.2181134 , 1.2478763 ]]], dtype=float32)\n Coordinates:\n * band (band) int32 1\n * y (y) float64 4.5e+06 4.5e+06 4.5e+06 ... 4.39e+06 4.39e+06\n * x (x) float64 2e+05 2e+05 2e+05 ... 3.097e+05 3.098e+05 3.098e+05\n spatial_ref int32 0,\n : \n array([[[0.0615 , 0.061625, 0.061 , ..., 0.12085 , 0.120225,\n 0.113575],\n [0.061075, 0.06045 , 0.06025 , ..., 0.114625, 0.119625,\n 0.117625],\n [0.06475 , 0.06145 , 0.060925, ..., 0.111475, 0.114925,\n 0.115175],\n ...,\n [0.1516 , 0.14195 , 0.1391 , ..., 0.159975, 0.14145 ,\n 0.127075],\n [0.140325, 0.125975, 0.131875, ..., 0.18245 , 0.1565 ,\n 0.13015 ],\n [0.133475, 0.1341 , 0.13345 , ..., 0.15565 , 0.170675,\n 0.16405 ]]], dtype=float32)\n Coordinates:\n * band (band) int32 1\n * y (y) float64 4.5e+06 4.5e+06 4.5e+06 ... 4.39e+06 4.39e+06\n * x (x) float64 2e+05 2e+05 2e+05 ... 3.097e+05 3.098e+05 3.098e+05\n spatial_ref int32 0\n }\n\n Args:\n bands (Union[list, BandNames, Callable]): Band list\n resolution (float): Resolution of the band, in meters\n size (Union[tuple, list]): Size of the array (width, height). Not used if resolution is provided.\n\n Returns:\n dict: {band_name, band xarray}\n \"\"\"\n if not resolution and not size:\n resolution = self.resolution\n\n # Check if all bands are valid\n if not isinstance(bands, list):\n bands = [bands]\n\n band_dict = self._load(bands, resolution, size)\n\n # Manage the case of arrays of different size -> collocate arrays if needed\n band_dict = self._collocate_bands(band_dict)\n\n # Convert to xarray dataset when all the bands have the same size\n # TODO: cannot convert as we have non-string index\n # xds = xr.Dataset(band_dict)\n\n # Sort bands to the asked order\n # xds.reindex({\"band\": bands})\n\n # Rename all bands\n for key, val in band_dict.items():\n band_name = to_str(key)[0]\n renamed_val = val.rename(band_name)\n renamed_val.attrs[\"long_name\"] = band_name\n band_dict[key] = renamed_val\n\n return band_dict\n\n @abstractmethod\n def _load(\n self, bands: list, resolution: float = None, size: Union[list, tuple] = None\n ) -> dict:\n \"\"\"\n Core function loading data bands\n\n Args:\n bands (list): Band list\n resolution (float): Resolution of the band, in meters\n size (Union[tuple, list]): Size of the array (width, height). Not used if resolution is provided.\n\n Returns:\n Dictionary {band_name, band_xarray}\n \"\"\"\n raise NotImplementedError(\"This method should be implemented by a child class\")\n\n def has_band(self, band: Union[BandNames, Callable]) -> bool:\n \"\"\"\n Does this products has the specified band ?\n\n By band, we mean:\n\n - satellite band\n - index\n - DEM band\n - cloud band\n\n .. code-block:: python\n\n >>> from eoreader.reader import Reader\n >>> from eoreader.bands.alias import *\n >>> path = r\"S2A_MSIL1C_20200824T110631_N0209_R137_T30TTK_20200824T150432.SAFE.zip\"\n >>> prod = Reader().open(path)\n >>> prod.has_band(GREEN)\n True\n >>> prod.has_band(TIR_2)\n False\n >>> prod.has_band(NDVI)\n True\n >>> prod.has_band(SHADOWS)\n False\n >>> prod.has_band(HILLSHADE)\n True\n\n Args:\n band (Union[obn, sbn]): Optical or SAR band\n\n Returns:\n bool: True if the products has the specified band\n \"\"\"\n if is_dem(band):\n if self.sensor_type == SensorType.SAR and band == HILLSHADE:\n has_band = False\n else:\n has_band = True\n elif is_clouds(band):\n has_band = self._has_cloud_band(band)\n elif is_index(band):\n has_band = self._has_index(band)\n else:\n has_band = band in self.get_existing_bands()\n\n return has_band\n\n def _has_cloud_band(self, band: BandNames) -> bool:\n \"\"\"\n Does this products has the specified cloud band ?\n\n .. code-block:: python\n\n >>> from eoreader.reader import Reader\n >>> from eoreader.bands.alias import *\n >>> path = r\"S2A_MSIL1C_20200824T110631_N0209_R137_T30TTK_20200824T150432.SAFE.zip\"\n >>> prod = Reader().open(path)\n >>> prod.has_cloud_band(CLOUDS)\n True\n \"\"\"\n raise NotImplementedError(\"This method should be implemented by a child class\")\n\n def _has_index(self, idx: Callable) -> bool:\n \"\"\"\n Cen the specified index be computed from this products ?\n\n .. code-block:: python\n\n >>> from eoreader.reader import Reader\n >>> from eoreader.bands.alias import *\n >>> path = r\"S2A_MSIL1C_20200824T110631_N0209_R137_T30TTK_20200824T150432.SAFE.zip\"\n >>> prod = Reader().open(path)\n >>> prod.has_index(NDVI)\n True\n\n Args:\n idx (Callable): Index\n\n Returns:\n bool: True if the specified index can be computed with this product's bands\n \"\"\"\n index_bands = index.get_needed_bands(idx)\n return all(np.isin(index_bands, self.get_existing_bands()))\n\n def __gt__(self, other: Product) -> bool:\n \"\"\"\n Overload greater than for eoreader -> compare the dates:\n The greater products is the one acquired the last.\n\n Args:\n other (Product): Other products to be compared with this one\n\n Returns:\n bool: True if this products has been acquired after the other\n\n \"\"\"\n return self.date > other.date\n\n def __ge__(self, other: Product) -> bool:\n \"\"\"\n Overload greater than for eoreader -> compare the dates:\n The greater products is the one acquired the last.\n\n Args:\n other (Product): Other products to be compared with this one\n\n Returns:\n bool: True if this products has been acquired after or in the same time than the other\n\n \"\"\"\n return self.date >= other.date\n\n def __eq__(self, other: Product) -> bool:\n \"\"\"\n Overload greater than for eoreader -> compare the dates:\n The greater products is the one acquired the last.\n\n Args:\n other (Product): Other products to be compared with this one\n\n Returns:\n bool: True if this products has been acquired in the same time than the other\n\n \"\"\"\n return self.date == other.date\n\n def __ne__(self, other: Product) -> bool:\n \"\"\"\n Overload greater than for eoreader -> compare the dates:\n The greater products is the one acquired the last.\n\n Args:\n other (Product): Other products to be compared with this one\n\n Returns:\n bool: True if this products has been acquired not in the same time than the other\n\n \"\"\"\n return self.date != other.date\n\n def __le__(self, other: Product) -> bool:\n \"\"\"\n Overload greater than for eoreader -> compare the dates:\n The greater products is the one acquired the last.\n\n Args:\n other (Product): Other products to be compared with this one\n\n Returns:\n bool: True if this products has been acquired before or in the same time than the other\n\n \"\"\"\n return self.date <= other.date\n\n def __lt__(self, other: Product) -> bool:\n \"\"\"\n Overload greater than for eoreader -> compare the dates:\n The greater products is the one acquired the last.\n\n Args:\n other (Product): Other products to be compared with this one\n\n Returns:\n bool: True if this products has been acquired before the other\n\n \"\"\"\n return self.date < other.date\n\n @property\n def output(self) -> Union[CloudPath, Path]:\n \"\"\"Output directory of the product, to write orthorectified data for example.\"\"\"\n return self._output\n\n @output.setter\n def output(self, value: str):\n \"\"\"Output directory of the product, to write orthorectified data for example.\"\"\"\n # Remove old output if existing\n if self._tmp_output:\n self._tmp_output.cleanup()\n self._tmp_output = None\n\n if self._output.exists() and self._remove_tmp_process:\n files.remove(self._tmp_process)\n\n # Set the new output\n self._output = AnyPath(value)\n if not isinstance(self._output, CloudPath):\n self._output = self._output.resolve()\n\n self._tmp_process = self._output.joinpath(f\"tmp_{self.condensed_name}\")\n os.makedirs(self._tmp_process, exist_ok=True)\n\n def _warp_dem(\n self,\n dem_path: str = \"\",\n resolution: Union[float, tuple] = None,\n size: Union[list, tuple] = None,\n resampling: Resampling = Resampling.bilinear,\n ) -> str:\n \"\"\"\n Get this products DEM, warped to this products footprint and CRS.\n\n If no DEM is giving (or non existing or non intersecting the products):\n\n - Using EUDEM over Europe\n - Using MERIT DEM everywhere else\n\n .. code-block:: python\n\n >>> from eoreader.reader import Reader\n >>> from eoreader.bands.alias import *\n >>> path = r\"S2A_MSIL1C_20200824T110631_N0209_R137_T30TTK_20200824T150432.SAFE.zip\"\n >>> prod = Reader().open(path)\n >>> prod.warp_dem(resolution=20) # In meters\n '/path/to/20200824T110631_S2_T30TTK_L1C_150432_DEM.tif'\n\n Args:\n dem_path (str): DEM path, using EUDEM/MERIT DEM if none\n resolution (Union[float, tuple]): Resolution in meters. If not specified, use the product resolution.\n resampling (Resampling): Resampling method\n size (Union[tuple, list]): Size of the array (width, height). Not used if resolution is provided.\n\n Returns:\n str: DEM path (as a VRT)\n \"\"\"\n warped_dem_path = self._get_band_folder().joinpath(\n f\"{self.condensed_name}_DEM.tif\"\n )\n if warped_dem_path.is_file():\n LOGGER.debug(\"Already existing DEM for %s. Skipping process.\", self.name)\n else:\n LOGGER.debug(\"Warping DEM for %s\", self.name)\n\n # Allow S3 HTTP Urls only on Linux because rasterio bugs on Windows\n if validators.url(dem_path) and platform.system() == \"Windows\":\n raise Exception(\n f\"URLs to DEM like {dem_path} are not supported on Windows! Use Docker or Linux instead\"\n )\n\n # Check existence (SRTM)\n if not validators.url(dem_path):\n dem_path = AnyPath(dem_path)\n if not dem_path.is_file():\n raise FileNotFoundError(f\"DEM file does not exist here: {dem_path}\")\n\n # Reproject DEM into products CRS\n LOGGER.debug(\"Using DEM: %s\", dem_path)\n def_tr, def_w, def_h, def_crs = self.default_transform()\n with rasterio.open(str(dem_path)) as dem_ds:\n # Get adjusted transform and shape (with new resolution)\n if size is not None and resolution is None:\n try:\n\n # Get destination transform\n out_h = size[1]\n out_w = size[0]\n\n # Get destination transform\n coeff_x = def_w / out_w\n coeff_y = def_h / out_h\n dst_tr = def_tr\n dst_tr *= dst_tr.scale(coeff_x, coeff_y)\n\n except (TypeError, KeyError):\n raise ValueError(\n f\"Size should exist (as resolution is None)\"\n f\" and castable to a list: {size}\"\n )\n\n else:\n # Refine resolution\n if resolution is None:\n resolution = self.resolution\n\n bounds = transform.array_bounds(def_h, def_w, def_tr)\n dst_tr, out_w, out_h = rasterio.warp.calculate_default_transform(\n def_crs,\n self.crs(),\n def_w,\n def_h,\n *bounds,\n resolution=resolution,\n )\n\n # Get empty output\n reprojected_array = np.zeros(\n (dem_ds.count, out_h, out_w), dtype=np.float32\n )\n\n # Write reprojected DEM: here do not use utils.write()\n out_meta = {\n \"driver\": \"GTiff\",\n \"dtype\": reprojected_array.dtype,\n \"nodata\": self.nodata,\n \"width\": out_w,\n \"height\": out_h,\n \"count\": dem_ds.count,\n \"crs\": self.crs(),\n \"transform\": dst_tr,\n }\n with rasterio.open(str(warped_dem_path), \"w\", **out_meta) as out_dst:\n out_dst.write(reprojected_array)\n\n # Reproject\n warp.reproject(\n source=rasterio.band(dem_ds, range(1, dem_ds.count + 1)),\n destination=rasterio.band(out_dst, range(1, out_dst.count + 1)),\n resampling=resampling,\n num_threads=MAX_CORES,\n dst_transform=dst_tr,\n dst_crs=self.crs(),\n src_crs=dem_ds.crs,\n src_transform=dem_ds.transform,\n )\n\n return warped_dem_path\n\n @abstractmethod\n def _compute_hillshade(\n self,\n dem_path: str = \"\",\n resolution: Union[float, tuple] = None,\n size: Union[list, tuple] = None,\n resampling: Resampling = Resampling.bilinear,\n ) -> str:\n \"\"\"\n Compute Hillshade mask\n\n Args:\n dem_path (str): DEM path, using EUDEM/MERIT DEM if none\n resolution (Union[float, tuple]): Resolution in meters. If not specified, use the product resolution.\n size (Union[tuple, list]): Size of the array (width, height). Not used if resolution is provided.\n resampling (Resampling): Resampling method\n\n Returns:\n str: Hillshade mask path\n\n \"\"\"\n raise NotImplementedError(\"This method should be implemented by a child class\")\n\n def _compute_slope(\n self,\n dem_path: str = \"\",\n resolution: Union[float, tuple] = None,\n size: Union[list, tuple] = None,\n resampling: Resampling = Resampling.bilinear,\n ) -> str:\n \"\"\"\n Compute slope mask\n\n Args:\n dem_path (str): DEM path, using EUDEM/MERIT DEM if none\n resolution (Union[float, tuple]): Resolution in meters. If not specified, use the product resolution.\n size (Union[tuple, list]): Size of the array (width, height). Not used if resolution is provided.\n resampling (Resampling): Resampling method\n\n Returns:\n str: Slope mask path\n\n \"\"\"\n # Warp DEM\n warped_dem_path = self._warp_dem(dem_path, resolution, size, resampling)\n\n # Get slope path\n slope_dem = self._get_band_folder().joinpath(f\"{self.condensed_name}_SLOPE.tif\")\n if slope_dem.is_file():\n LOGGER.debug(\n \"Already existing slope DEM for %s. Skipping process.\", self.name\n )\n else:\n LOGGER.debug(\"Computing slope for %s\", self.name)\n cmd_slope = [\n \"gdaldem\",\n \"--config\",\n \"NUM_THREADS\",\n MAX_CORES,\n \"slope\",\n \"-compute_edges\",\n strings.to_cmd_string(warped_dem_path),\n strings.to_cmd_string(slope_dem),\n \"-p\",\n ]\n\n # Run command\n try:\n misc.run_cli(cmd_slope)\n except RuntimeError as ex:\n raise RuntimeError(\"Something went wrong with gdaldem!\") from ex\n\n return slope_dem\n\n @staticmethod\n def _collocate_bands(bands: dict, master_xds: XDS_TYPE = None) -> dict:\n \"\"\"\n Collocate all bands from a dict if needed (if a raster shape is different)\n\n Args:\n bands (dict): Dict of bands to collocate if needed\n\n Returns:\n dict: Collocated bands\n \"\"\"\n for band_id, band in bands.items():\n if master_xds is None:\n master_xds = band # Master array is the first one in this case\n\n if band.shape != master_xds.shape:\n bands[band_id] = rasters.collocate(\n master_xds=master_xds, slave_xds=band\n )\n\n bands[band_id] = bands[band_id].assign_coords(\n {\n \"x\": master_xds.x,\n \"y\": master_xds.y,\n }\n ) # Bug for now, tiny difference in coords\n\n return bands\n\n # pylint: disable=R0913\n # Too many arguments (6/5)\n def stack(\n self,\n bands: list,\n resolution: float = None,\n size: Union[list, tuple] = None,\n stack_path: Union[str, CloudPath, Path] = None,\n save_as_int: bool = False,\n **kwargs,\n ) -> xr.DataArray:\n \"\"\"\n Stack bands and index of a products.\n\n .. code-block:: python\n\n >>> from eoreader.reader import Reader\n >>> from eoreader.bands.alias import *\n >>> path = r\"S2A_MSIL1C_20200824T110631_N0209_R137_T30TTK_20200824T150432.SAFE.zip\"\n >>> prod = Reader().open(path)\n >>> stack = prod.stack([NDVI, MNDWI, GREEN], resolution=20) # In meters\n >>> stack\n \n array([[[ 0.949506 , 0.92181516, 0.9279379 , ..., 1.8002278 ,\n 1.5424857 , 1.6747767 ],\n [ 0.95369846, 0.91685396, 0.8957871 , ..., 1.5847116 ,\n 1.5248713 , 1.5011379 ],\n [ 2.9928885 , 1.3031474 , 1.0076253 , ..., 1.5969834 ,\n 1.5590671 , 1.5018653 ],\n ...,\n [ 1.4245619 , 1.6115025 , 1.6201663 , ..., 1.2387121 ,\n 1.4025431 , 1.800678 ],\n [ 1.5627214 , 1.822388 , 1.7245892 , ..., 1.1694248 ,\n 1.2573677 , 1.5767351 ],\n [ 1.653781 , 1.6424649 , 1.5923225 , ..., 1.3072611 ,\n 1.2181134 , 1.2478763 ]],\n [[ 0.27066118, 0.23466069, 0.18792598, ..., -0.4611526 ,\n -0.49751845, -0.4865216 ],\n [ 0.22425456, 0.28004232, 0.27851456, ..., -0.5032771 ,\n -0.501796 , -0.502669 ],\n [-0.07466951, 0.06360884, 0.1207174 , ..., -0.50617427,\n -0.50219285, -0.5034222 ],\n [-0.47076276, -0.4705828 , -0.4747971 , ..., -0.32138503,\n -0.36619243, -0.37428448],\n [-0.4826967 , -0.5032287 , -0.48544118, ..., -0.278925 ,\n -0.31404778, -0.36052078],\n [-0.488381 , -0.48253912, -0.4697526 , ..., -0.38105175,\n -0.30813277, -0.27739233]],\n [[ 0.0615 , 0.061625 , 0.061 , ..., 0.12085 ,\n 0.120225 , 0.113575 ],\n [ 0.061075 , 0.06045 , 0.06025 , ..., 0.114625 ,\n 0.119625 , 0.117625 ],\n [ 0.06475 , 0.06145 , 0.060925 , ..., 0.111475 ,\n 0.114925 , 0.115175 ],\n ...,\n [ 0.1516 , 0.14195 , 0.1391 , ..., 0.159975 ,\n 0.14145 , 0.127075 ],\n [ 0.140325 , 0.125975 , 0.131875 , ..., 0.18245 ,\n 0.1565 , 0.13015 ],\n [ 0.133475 , 0.1341 , 0.13345 , ..., 0.15565 ,\n 0.170675 , 0.16405 ]]], dtype=float32)\n Coordinates:\n * y (y) float64 4.5e+06 4.5e+06 4.5e+06 ... 4.39e+06 4.39e+06\n * x (x) float64 2e+05 2e+05 2e+05 ... 3.097e+05 3.098e+05 3.098e+05\n spatial_ref int32 0\n * z (z) MultiIndex\n - variable (z) object 'NDVI' 'MNDWI' 'GREEN'\n - band (z) int64 1 1 1\n -Attributes:\n long_name: ['NDVI', 'MNDWI', 'GREEN']\n\n Args:\n bands (list): Bands and index combination\n resolution (float): Stack resolution. . If not specified, use the product resolution.\n size (Union[tuple, list]): Size of the array (width, height). Not used if resolution is provided.\n stack_path (Union[str, CloudPath, Path]): Stack path\n save_as_int (bool): Convert stack to uint16 to save disk space (and therefore multiply the values by 10.000)\n **kwargs: Other arguments passed to `rioxarray.to_raster()` such as `compress`\n\n Returns:\n xr.DataArray: Stack as a DataArray\n \"\"\"\n if not isinstance(bands, list):\n bands = [bands]\n\n if not resolution and not size:\n resolution = self.resolution\n\n # Create the analysis stack\n band_dict = self.load(bands, resolution=resolution, size=size)\n\n # Convert into dataset with str as names\n xds = xr.Dataset(\n data_vars={\n to_str(key)[0]: (val.coords.dims, val.data)\n for key, val in band_dict.items()\n },\n coords=band_dict[bands[0]].coords,\n )\n\n # Force nodata\n stack = xds.to_stacked_array(new_dim=\"z\", sample_dims=(\"x\", \"y\"))\n stack = stack.transpose(\"z\", \"y\", \"x\")\n\n # Save as integer\n dtype = np.float32\n if save_as_int:\n if np.min(stack) < 0:\n LOGGER.warning(\n \"Cannot convert the stack to uint16 as it has negative values. Keeping it in float32.\"\n )\n else:\n # SCALING\n # NOT ALL bands need to be scaled, only:\n # - Satellite bands\n # - index\n for id, band in enumerate(band_dict.keys()):\n if is_band(band) or is_index(band):\n stack[id, ...] = stack[id, ...] * 10000\n\n # CONVERSION\n dtype = np.uint16\n stack = stack.fillna(65535).astype(\n dtype\n ) # Scale to uint16, fill nan and convert to uint16\n\n if dtype == np.float32:\n # Convert dtype if needed\n if stack.dtype != dtype:\n stack = stack.astype(dtype)\n\n # Set nodata if needed\n if stack.rio.encoded_nodata != self.nodata:\n stack = stack.rio.write_nodata(\n self.nodata, encoded=True, inplace=True\n ) # NaN values are already set\n\n # Some updates\n band_list = to_str(list(band_dict.keys()))\n stack.attrs[\"long_name\"] = band_list\n stack = stack.rename(\"_\".join(band_list))\n\n # Write on disk\n if stack_path:\n stack_path = AnyPath(stack_path)\n if not stack_path.parent.exists():\n os.makedirs(str(stack_path.parent), exist_ok=True)\n rasters.write(stack, stack_path, dtype=dtype, **kwargs)\n\n # Close datasets\n for val in band_dict.values():\n val.close()\n\n return stack\n\n @staticmethod\n def _check_dem_path() -> None:\n \"\"\" Check if DEM is set and exists\"\"\"\n if DEM_PATH not in os.environ:\n raise ValueError(\n f\"Dem path not set, unable to compute DEM bands! \"\n f\"Please set the environment variable {DEM_PATH}.\"\n )\n else:\n dem_path = os.environ.get(DEM_PATH)\n # URLs and file paths are required\n if not validators.url(dem_path):\n dem_path = AnyPath(dem_path)\n if not dem_path.is_file():\n raise FileNotFoundError(\n f\"{dem_path} is not a file! \"\n f\"Please set the environment variable {DEM_PATH} to an existing file.\"\n )\n\n def default_transform(self) -> (Affine, int, int, CRS):\n \"\"\"\n Returns default transform data of the default band (UTM),\n as the `rasterio.warp.calculate_default_transform` does:\n - transform\n - width\n - height\n - crs\n\n Returns:\n Affine, int, int: transform, width, height\n\n \"\"\"\n with rasterio.open(str(self.get_default_band_path())) as dst:\n return dst.transform, dst.width, dst.height, dst.crs\n\n def _resolution_from_size(self, size: Union[list, tuple] = None) -> tuple:\n \"\"\"\n Compute the corresponding resolution to a given size (positive resolution)\n\n Args:\n dst (rasterio.DatasetReader): Dataset\n size (Union[list, tuple]): Size\n\n Returns:\n tuple: Resolution as a tuple (x, y)\n \"\"\"\n def_tr, def_w, def_h, def_crs = self.default_transform()\n bounds = transform.array_bounds(def_h, def_w, def_tr)\n\n # Manage WGS84 case\n if not def_crs.is_projected:\n utm_tr, utm_w, utm_h = warp.calculate_default_transform(\n def_crs,\n self.crs(),\n def_w,\n def_h,\n *bounds,\n resolution=self.resolution,\n )\n resolution = (\n abs(utm_tr.a * utm_w / size[0]),\n abs(utm_tr.e * utm_h / size[1]),\n )\n # Manage UTM case\n else:\n resolution = (\n abs(def_tr.a * def_w / size[0]),\n abs(def_tr.e * def_h / size[1]),\n )\n\n return resolution\n\n def clean_tmp(self):\n \"\"\"\n Clean the temporary directory of the current product\n \"\"\"\n if self._tmp_process.exists():\n for tmp_file in self._tmp_process.glob(\"*\"):\n files.remove(tmp_file)\n","sub_path":"eoreader/products/product.py","file_name":"product.py","file_ext":"py","file_size_in_byte":53053,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"3718228","text":"#!/usr/bin/env python3\nimport os\nimport logics\nimport games_db\n\nplayer1 = logics.Player()\nplayer2 = logics.Player()\ngame = logics.Engine()\n\n\ndef set_player1(name):\n player1.name = name\n game.player1 = player1.name\n\n\ndef set_player2(name):\n player2.name = name\n game.player2 = player2.name\n\n\ndef set_game_id():\n game.gid = [player1.name, player2.name]\n\n\ndef set_cards(val):\n player1.cards = val\n player2.cards = val\n\n\ndef get_cards(name):\n if name == player1.name:\n return player1.cards\n else:\n return player2.cards\n\n\ndef set_choice(name, val):\n if name == player1.name:\n if player1.subtraction_cards(val):\n player1.choice = val\n return True\n else:\n return False\n else:\n player2.choice = val\n if player2.subtraction_cards(val):\n player2.choice = val\n return True\n else:\n return False\n\n\ndef get_choice(name):\n if name == player1.name:\n return player1.choice\n else:\n return player2.choice\n\n\ndef check_pl_cards(name):\n if name == player1.name:\n return player1.check_cards()\n else:\n return player2.check_cards()\n\n\ndef compare_step_count():\n if player1.step_count == player2.step_count:\n return True\n else:\n return False\n\n\ndef increment_step_count(name):\n if name == player1.name:\n player1.step_count += 1\n else:\n player2.step_count += 1\n\n\ndef decrement_step_count(name):\n if name == player1.name:\n player1.step_count -= 1\n else:\n player2.step_count -= 1\n\n\ndef show_step_count(name):\n if name == player1.name:\n return player1.step_count\n else:\n return player2.step_count\n\n\ndef winner():\n if player1.win_count > player2.win_count:\n return player1.name\n elif player1.win_count < player2.win_count:\n return player2.name\n else:\n return \"DRAW\"\n\n\ndef show_result(name):\n result = game.compare(player1.choice, player2.choice)\n\n if result == \"WIN\" and name == player1.name:\n player1.win_count += 1\n elif result == \"LOSE\" and name == player2.name:\n player2.win_count += 1\n\n return game.result(player1.name,\n player1.choice,\n player2.name,\n player2.choice,\n result)\n\n\ndef start_db():\n filename = os.path.join(os.path.dirname(__file__), \"games.db\")\n db = None\n try:\n db = games_db.connect(filename)\n if games_db.get_game_by_id(db, game.gid):\n return games_db.get_game_by_id(db, game.gid)\n else:\n games_db.add_game(db, game.gid, player1.name,\n player2.name, winner())\n return games_db. get_all_games(db)\n finally:\n if db is not None:\n db.close()\n","sub_path":"scripts/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":2853,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"80547847","text":"# -*- coding: utf8 -*-\n\nfrom time import time\nimport heapq\n\n__author__ = 'sergey'\n\nclass StorageTimeSize(object):\n\n # Maximum seconds after that cache is expired for writed blocks\n _max_write_ttl = 5\n\n # Maximum cache size in bytes for block that writed recently\n _max_write_cache_size = 256*1024*1024\n _cur_write_cache_size = 0\n\n # Maximum seconds after that cache is expired for readed blocks\n _max_read_ttl = 10\n\n # Maximum cache size in bytes for block that accessed recently\n _max_read_cache_size = 256*1024*1024\n _cur_read_cache_size = 0\n\n # Expired maximum cache size in %\n _max_size_trsh = 5\n\n _inodes = None\n _block_size = 128*1024\n\n def __init__(self):\n self._inodes = {}\n pass\n\n def __len__(self):\n s = 0\n for inode in self._inodes:\n s += len(self._inodes[inode])\n return s\n\n def setBlockSize(self, in_bytes):\n self._block_size = in_bytes\n return self\n\n def setMaxWriteCacheSize(self, in_bytes):\n self._max_write_cache_size = in_bytes\n return self\n\n def setMaxReadCacheSize(self, in_bytes):\n self._max_read_cache_size = in_bytes\n return self\n\n def setMaxWriteTtl(self, seconds):\n self._max_write_ttl = seconds\n return self\n\n def setMaxReadTtl(self, seconds):\n self._max_read_ttl = seconds\n return self\n\n def set(self, inode, block_number, block, writed=False):\n \"\"\"\n @type inode: int\n @type block_number: int\n @type block: BytesIO\n @type writed: bool\n \"\"\"\n\n inode = str(inode)\n block_number = str(block_number)\n\n new = False\n if inode not in self._inodes:\n self._inodes[ inode ] = {}\n new = True\n\n inode_data = self._inodes[inode]\n\n if block_number not in inode_data:\n inode_data[ block_number ] = {\n \"size\" : 0,\n \"w\" : writed\n }\n new = True\n\n block_data = inode_data[block_number]\n\n blockSize = len(block.getvalue())\n\n if not new:\n # Not new block\n oldBlockSize = block_data[\"size\"]\n if writed:\n # If it now writed\n if not block_data[\"w\"]:\n # But not was\n self._cur_read_cache_size -= oldBlockSize\n else:\n self._cur_write_cache_size -= oldBlockSize\n else:\n self._cur_read_cache_size -= oldBlockSize\n\n if writed:\n self._cur_write_cache_size += blockSize\n else:\n self._cur_read_cache_size += blockSize\n\n block_data[\"time\"] = time()\n block_data[\"block\"] = block\n block_data[\"size\"] = blockSize\n\n if writed:\n block_data[\"w\"] = True\n\n return self\n\n def get(self, inode, block_number, default=None):\n\n inode = str(inode)\n block_number = str(block_number)\n\n now = time()\n\n inode_data = self._inodes.get(inode, {})\n\n block_data = inode_data.get(block_number, {\n \"time\" : now\n })\n\n if not block_data:\n return default\n\n val = block_data.get(\"block\", default)\n\n t = block_data[\"time\"]\n if now - t > self._max_write_ttl:\n return val\n\n # update last request time\n block_data[\"time\"] = time()\n\n return val\n\n def getCachedSize(self, writed=False):\n size = 0\n for inode in self._inodes.keys():\n for block_data in self._inodes[inode].values():\n if block_data[\"w\"] != writed:\n continue\n\n block_data[\"block\"].seek(0, 2)\n size += block_data[\"block\"].tell()\n block_data[\"block\"].seek(0, 0)\n return size\n\n\n def isWritedCacheFull(self):\n if self._max_write_cache_size < 0:\n return False\n filled = 100.0 * self._cur_write_cache_size / self._max_write_cache_size\n max_fill = 100 + self._max_size_trsh\n return filled > max_fill\n\n def isReadCacheFull(self):\n if self._max_read_cache_size < 0:\n return False\n filled = 100.0 * self._cur_read_cache_size / self._max_read_cache_size\n max_fill = 100 + self._max_size_trsh\n return filled > max_fill\n\n def forget(self, inode):\n inode = str(inode)\n if inode in self._inodes:\n del self._inodes[inode]\n return\n\n def expire(self, inode):\n inode = str(inode)\n if inode in self._inodes:\n inode_data = self._inodes[inode]\n for bn in tuple(inode_data.keys()):\n inode_data[bn][\"time\"] = 0\n self._inodes[inode] = inode_data\n return\n\n def expired(self, writed=False):\n now = time()\n\n if writed:\n old_inodes = {}\n else:\n old_inodes = 0\n\n for inode in tuple(self._inodes.keys()):\n\n inode_data = self._inodes[inode]\n\n for bn in tuple(inode_data.keys()):\n block_data = inode_data[bn]\n\n t = block_data[\"time\"]\n if block_data[\"w\"] != writed:\n continue\n\n if now - t > self._max_write_ttl:\n if writed:\n old_inode_data = old_inodes.get(inode, {})\n old_inode_data[bn] = block_data.copy()\n old_inodes[inode] = old_inode_data\n\n self._cur_write_cache_size -= block_data[\"size\"]\n else:\n old_inodes += 1\n\n self._cur_read_cache_size -= block_data[\"size\"]\n\n del inode_data[bn]\n\n if not inode_data and inode in self._inodes:\n del self._inodes[inode]\n\n return old_inodes\n\n def expireByCount(self, writed=False):\n now = time()\n\n # 1. Fill heap\n\n heap = []\n\n inodesKeys = tuple(self._inodes.keys())\n\n for inode in inodesKeys:\n\n inode_data = self._inodes[inode]\n\n for bn in inode_data.keys():\n block_data = inode_data[bn]\n\n t = block_data[\"time\"]\n if block_data[\"w\"] != writed:\n continue\n\n heapq.heappush(\n heap, (\n int((now - t)*10**6),\n inode,\n bn,\n len(block_data[\"block\"].getvalue())\n )\n )\n\n # 2. Sort heap\n\n if writed:\n currentSize = self._cur_write_cache_size\n maxSize = self._max_write_cache_size\n else:\n currentSize = self._cur_read_cache_size\n maxSize = self._max_read_cache_size\n\n needMaxSize = maxSize * (100 - self._max_size_trsh) / 100\n\n nget = int((currentSize - needMaxSize) / self._block_size)\n\n mostrecent = []\n while True:\n needSize = currentSize\n mostrecent = heapq.nsmallest(nget, heap)\n for dt, inode, bn, bsize in mostrecent:\n needSize -= bsize\n if needSize <= needMaxSize:\n break\n nget += 1\n\n # 3. Convert data\n\n heap_inodes = {}\n for dt, inode, bn, bsize in mostrecent:\n if inode not in heap_inodes:\n heap_inodes[ inode ] = ()\n heap_inodes[ inode ] += (bn,)\n\n del heap\n del mostrecent\n\n # 4. Expire cache, filter by new data\n\n if writed:\n old_inodes = {}\n else:\n old_inodes = 0\n\n for inode in inodesKeys:\n\n inode_data = self._inodes[inode]\n\n for bn in tuple(inode_data.keys()):\n\n block_data = inode_data[bn]\n\n if block_data[\"w\"] != writed:\n continue\n\n # Expire inodes that in heap or by block numbers\n if inode not in heap_inodes or\\\n bn not in heap_inodes[ inode ]:\n\n if writed:\n old_inode_data = old_inodes.get(inode, {})\n old_inode_data[bn] = block_data.copy()\n old_inodes[inode] = old_inode_data\n\n self._cur_write_cache_size -= block_data[\"size\"]\n else:\n old_inodes += 1\n\n self._cur_read_cache_size -= block_data[\"size\"]\n\n del inode_data[bn]\n\n if not inode_data and inode in self._inodes:\n del self._inodes[inode]\n\n return old_inodes\n\n def clear(self):\n old_inodes = self._inodes.copy()\n self._inodes = {}\n return old_inodes\n","sub_path":"dedupsqlfs/lib/cache/storage.py","file_name":"storage.py","file_ext":"py","file_size_in_byte":8841,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"237877335","text":"class Solution(object):\r\n def intersect(self, nums1, nums2):\r\n \"\"\"\r\n :type nums1: List[int]\r\n :type nums2: List[int]\r\n :rtype: List[int]\r\n \"\"\"\r\n ans = []\r\n nums1.sort()\r\n nums2.sort()\r\n i = j = 0\r\n while i < len(nums1) and j < len(nums2):\r\n if nums1[i] < nums2[j]:\r\n i += 1\r\n elif nums1[i] > nums2[j]:\r\n j += 1\r\n else:\r\n ans.append(nums1[i])\r\n i += 1\r\n j += 1\r\n \r\n return ans\r\n \r\n \r\n \r\n \"\"\"使用两个字典记录下两个数组中元素出现的次数\"\"\"\r\nclass Solution(object):\r\n def intersect(self, nums1, nums2):\r\n \"\"\"\r\n :type nums1: List[int]\r\n :type nums2: List[int]\r\n :rtype: List[int]\r\n \"\"\"\r\n dic1,dic2 = dict(),dict()\r\n for num in nums1:\r\n dic1[num] = dic1.get(num,0) + 1\r\n for num in nums2:\r\n dic2[num] = dic2.get(num,0) + 1\r\n return [x for x in dic2 for j in range(min(dic1.get(x,0),dic2.get(x,0)))]\r\n\r\n\"\"\"但是python内置了Counter类型数组,可以方便实现计数功能\"\"\"\r\nimport collections\r\n\r\nclass Solution(object):\r\n def intersect(self, nums1, nums2):\r\n \"\"\"\r\n :type nums1: List[int]\r\n :type nums2: List[int]\r\n :rtype: List[int]\r\n \"\"\"\r\n c1,c2 = collections.Counter(nums1),collections.Counter(nums2)\r\n return [i for i in c1.keys() for j in range(min([c1[i], c2[i]]))]\r\n","sub_path":"350.intersection-of-two-arrays-ii/intersection-of-two-arrays-ii.py","file_name":"intersection-of-two-arrays-ii.py","file_ext":"py","file_size_in_byte":1550,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"103961148","text":"\"\"\"\nUtility methods to make life easier.\n\"\"\"\nimport os\nimport uuid\nimport warnings\nwarnings.simplefilter(action='ignore', category=UserWarning) # lgb compiler warning\n\nimport numpy as np\nfrom sklearn.ensemble import RandomForestClassifier, GradientBoostingClassifier\nfrom sklearn.metrics import accuracy_score, log_loss, roc_auc_score\n\n\ndef get_classifier(model, n_estimators=20, max_depth=None, learning_rate=0.03, random_state=69):\n \"\"\"Returns a tree ensemble classifier.\"\"\"\n\n # create model\n if model == 'lgb':\n import lightgbm\n max_depth = -1 if max_depth is None else max_depth\n clf = lightgbm.LGBMClassifier(random_state=random_state, n_estimators=n_estimators,\n max_depth=max_depth)\n elif model == 'cb':\n import catboost\n train_dir = os.path.join('.catboost_info', str(uuid.uuid4()))\n os.makedirs(train_dir, exist_ok=True)\n clf = catboost.CatBoostClassifier(random_state=random_state, n_estimators=n_estimators,\n max_depth=max_depth, verbose=False, train_dir=train_dir)\n elif model == 'rf':\n max_depth = None if max_depth == 0 else max_depth\n clf = RandomForestClassifier(random_state=random_state, n_estimators=n_estimators,\n max_depth=max_depth)\n elif model == 'gbm':\n max_depth = 3 if max_depth is None else max_depth # gbm default\n clf = GradientBoostingClassifier(random_state=random_state, n_estimators=n_estimators,\n max_depth=max_depth)\n elif model == 'xgb':\n import xgboost\n max_depth = 3 if max_depth is None else max_depth # xgb default\n clf = xgboost.XGBClassifier(random_state=random_state, n_estimators=n_estimators,\n max_depth=max_depth)\n else:\n exit('{} model not supported!'.format(model))\n\n return clf\n\n\ndef fidelity(y1, y2, return_difference=False):\n \"\"\"Returns an (overlap, difference) tuple.\"\"\"\n\n overlap = np.where(y1 == y2)[0]\n difference = np.where(y1 != y2)[0]\n\n if return_difference:\n result = overlap, difference\n else:\n result = overlap\n\n return result\n\n\ndef missed_instances(y1, y2, y_true):\n \"\"\"Returns indexes missed by both y1 and y2.\"\"\"\n\n both_ndx = np.where((y1 == y2) & (y1 != y_true))[0]\n return both_ndx\n\n\ndef performance(model, X_train=None, y_train=None, X_test=None, y_test=None,\n validate=False, logger=None):\n \"\"\"Displays train and test performance for a learned model.\"\"\"\n\n if not logger:\n return\n\n logger.info('')\n\n if validate:\n model_type = validate_model(model)\n logger.info('model ({})'.format(model_type))\n\n acc, auc, logloss = -1, -1, -1\n\n if X_train is not None and y_train is not None:\n y_hat_pred = model.predict(X_train).flatten()\n acc = accuracy_score(y_train, y_hat_pred)\n\n if hasattr(model, 'predict_proba'):\n y_hat_proba = model.predict_proba(X_train)\n logloss = log_loss(y_train, y_hat_proba)\n\n if len(np.unique(y_train)) == 2:\n auc = roc_auc_score(y_train, y_hat_proba[:, 1])\n\n if hasattr(model, 'decision_function') and len(np.unique(y_train)) == 2:\n y_hat_proba = model.decision_function(X_train)\n auc = roc_auc_score(y_train, y_hat_proba)\n\n s = 'train acc: {:.3f}, auc: {:.3f}, logloss: {:.3f}'\n logger.info(s.format(acc, auc, logloss))\n\n if X_test is not None and y_test is not None:\n y_hat_pred = model.predict(X_test).flatten()\n acc = accuracy_score(y_test, y_hat_pred)\n\n if hasattr(model, 'predict_proba'):\n y_hat_proba = model.predict_proba(X_test)\n logloss = log_loss(y_test, y_hat_proba)\n\n if len(np.unique(y_test)) == 2:\n auc = roc_auc_score(y_test, y_hat_proba[:, 1])\n\n if hasattr(model, 'decision_function') and len(np.unique(y_test)) == 2:\n y_hat_proba = model.decision_function(X_test)\n auc = roc_auc_score(y_test, y_hat_proba)\n\n s = 'test acc: {:.3f}, auc: {:.3f}, logloss: {:.3f}'\n logger.info(s.format(acc, auc, logloss))\n\n\ndef validate_model(model):\n \"\"\"Make sure the model is a supported model type.\"\"\"\n\n model_type = str(model).split('(')[0]\n if 'RandomForestClassifier' in str(model):\n model_type = 'RandomForestClassifier'\n elif 'GradientBoostingClassifier' in str(model):\n model_type = 'GradientBoostingClassifier'\n elif 'LGBMClassifier' in str(model):\n model_type = 'LGBMClassifier'\n elif 'CatBoostClassifier' in str(model):\n model_type = 'CatBoostClassifier'\n elif 'XGBClassifier' in str(model):\n model_type = 'XGBClassifier'\n elif model_type == 'OneVsRestClassifier':\n model_type = 'OneVsRestClassifier'\n elif model_type == 'SVC':\n model_type = 'SVC'\n elif 'TreeExplainer' in str(model):\n model_type = 'trex'\n else:\n exit('{} model not currently supported!'.format(str(model)))\n\n return model_type\n\n\ndef positive_class_proba(labels, probas):\n \"\"\"\n Given the predicted label of each sample and the probabilities for each class for each sample,\n return the probabilities of the positive class for each sample.\n \"\"\"\n\n assert labels.ndim == 1, 'labels is not 1d!'\n assert probas.ndim == 2, 'probas is not 2d!'\n assert len(labels) == len(probas), 'num samples do not match between labels and probas!'\n y_pred = probas[np.arange(len(labels)), labels]\n assert y_pred.ndim == 1, 'y_pred is not 1d!'\n return y_pred\n","sub_path":"scripts/utility/model_util.py","file_name":"model_util.py","file_ext":"py","file_size_in_byte":5660,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"336193902","text":"\r\n# -*- coding: utf-8 -*-\r\nimport cartopy.crs as ccrs##绘地图用包\r\nimport matplotlib.pyplot as plt\r\nimport numpy as np\r\nimport re\r\nimport pickle\r\nimport os\r\nimport pandas as pd\r\n\r\ndata = pickle.load(open('D:/dataV1.txt', 'rb'))\r\n\r\ndef distance(latA,lngA,latB,lngB):\r\n r=6400\r\n latA=latA*np.pi/180\r\n lngA=lngA*np.pi/180\r\n latB=latB*np.pi/180\r\n lngB=lngB*np.pi/180\r\n \r\n D=r*np.arccos(np.cos(latA)*np.cos(latB)\\\r\n *np.cos(lngA-lngB)+np.sin(latA)*np.sin(latB))\r\n return int(D)\r\n\r\ndef largestDistance(dat):\r\n largest=0\r\n for i in range(len(dat)):\r\n if i ==0: continue\r\n else:\r\n flat=dat[i-1][0]\r\n flng=dat[i-1][1]\r\n tlat=dat[i][0]\r\n tlng=dat[i][1]\r\n if abs(flat-tlat)+abs(flng-tlng)>2:\r\n dist=distance(flat,flng,tlat,tlng)\r\n if dist>largest:\r\n largest=dist\r\n if largest<50:\r\n largest=0 \r\n return largest\r\n \r\nuid=[] \r\ndist=[]\r\nfor i in data:\r\n uid.append(i[0])\r\n dist.append(largestDistance(i[1]))\r\n \r\n \r\nDat=pd.DataFrame({\"largestdance\":dist},index=uid)\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\nx=pd.read_csv(\"mapD.csv\")\r\nx=x.set_index([\"lat\",\"lng\"])\r\ndi=x.to_dict()\r\ndi=di.get(\"country_code\")\r\n\r\n\r\ndef FindCoutry(dat):\r\n listx=[]\r\n for i in dat:\r\n lng=int(i[1])\r\n lat=int(i[0])\r\n code=di.get((lat,lng),-1)\r\n if code != -1:\r\n listx.append(code)\r\n \r\n return list(set(listx))\r\n\r\n\r\nfor i in data:\r\n i.append(FindCoutry(i[1])) \r\n \r\n \r\npickle.dump(data, open('D:/dataV1.txt', 'wb'))\r\n\r\ncountrycode=[]\r\nfor i in data:\r\n countrycode.append(i[3])\r\n \r\n \r\ntwocountrycode=[]\r\nfor i in countrycode:\r\n if len(i)>=2:\r\n twocountrycode.append(i)","sub_path":"localdataqpreprocess.txt/distance.py","file_name":"distance.py","file_ext":"py","file_size_in_byte":1800,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"359393196","text":"import os\nimport numpy as np\nimport time\nimport torch\nimport torch.nn.functional as F\nimport cv2\nfrom PIL import Image\n\ndef getContourAndCalculateArea(imgOrg, imgMask, bin_thread = 125, color_contour = (0, 0, 255), text_contour = (0, 255, 0)):\n imgMaskGray = cv2.GaussianBlur(imgMask, (3, 3), 0)\n _, binary = cv2.threshold(imgMaskGray, bin_thread, 255, cv2.THRESH_BINARY)\n _, contours, _ = cv2.findContours(binary, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)\n\n h_ratio, w_ratio = imgOrg.shape[0] / imgMask.shape[0], imgOrg.shape[1] / imgMask.shape[1]\n idx = 0\n for contour in contours:\n area = cv2.contourArea(contour)\n if(area < 100):\n continue\n contour = contour * (w_ratio, h_ratio)\n bbox = contour.astype('int32').reshape(-1)\n if len(bbox) <= 4:\n continue\n cv2.drawContours(imgOrg, [bbox.reshape(int(bbox.shape[0] / 2), 2)], -1, color_contour, 5)\n index = \"{0}\".format(idx)\n idx += 1\n font = cv2.FONT_HERSHEY_SIMPLEX # 定义字体\n _ = cv2.putText(imgOrg, index, (bbox[0], bbox[1]), font, 2, text_contour, 3)\n return imgOrg\n\nclass SolverTest(object):\n def __init__(self, config, test_loader, build_model_path, road_model_path):\n\n self.test_loader = test_loader\n self.device = torch.device('cuda:{0}'.format(config.gpu_id) if config.gpu_id != -1 and torch.cuda.is_available() else 'cpu')\n self.unet_build = torch.jit.load(build_model_path, map_location=self.device)\n self.unet_road = torch.jit.load(road_model_path, map_location=self.device)\n self.result_path = config.result_path\n\n def test(self):\n for _, (images, filename) in enumerate(self.test_loader):\n print(filename[0])\n imgOrg = cv2.imread(\"./images/\" + filename[0])\n startTime = time.time()\n imgTensor = images.to(self.device)\n buildTensor = F.sigmoid(self.unet_build(imgTensor))\n roadTensor = F.sigmoid(self.unet_road(imgTensor))\n buildTensor = buildTensor.squeeze(0).squeeze(0)\n roadTensor = roadTensor.squeeze(0).squeeze(0)\n buildTensor = buildTensor.cpu().data\n roadTensor = roadTensor.cpu().data\n build_mask = buildTensor.numpy() * 255\n road_mask = roadTensor.numpy() * 255\n print(\"Use Time: {0:0.3f}s\".format(time.time() - startTime))\n build_mask = Image.fromarray(build_mask.astype(np.uint8))\n road_mask = Image.fromarray(road_mask.astype(np.uint8))\n build_mask = np.asarray(build_mask)\n road_mask = np.asarray(road_mask)\n build_mask = build_mask.reshape(build_mask.shape[0], build_mask.shape[1], 1)\n imgOut_Build = getContourAndCalculateArea(imgOrg, build_mask, bin_thread=125, color_contour=(0, 0, 255), text_contour=(0, 255, 0))\n imgOut = getContourAndCalculateArea(imgOut_Build, road_mask, bin_thread=75, color_contour=(255, 0, 0), text_contour=(0, 255, 255))\n cv2.imwrite(self.result_path + \"/\" + filename[0], imgOut)","sub_path":"Version/aerial_release/solver.py","file_name":"solver.py","file_ext":"py","file_size_in_byte":3087,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"442310241","text":"import os\nimport hashlib\nfrom pathlib import Path\nimport random\nimport platform\n\nimport pytest\nimport cloudpickle as cp\n\nfrom .utils import multiply, raise_xeq1\nfrom ..helpers import (\n hash_value,\n hash_function,\n get_available_cpus,\n save,\n load_and_run,\n position_sort,\n)\nfrom .. import helpers_file\nfrom ..specs import File, Directory\nfrom ..core import Workflow\n\n\ndef test_save(tmpdir):\n outdir = Path(tmpdir)\n with pytest.raises(ValueError):\n save(tmpdir)\n foo = multiply(name=\"mult\", x=1, y=2)\n # save task\n save(outdir, task=foo)\n del foo\n # load saved task\n task_pkl = outdir / \"_task.pklz\"\n foo = cp.loads(task_pkl.read_bytes())\n assert foo.name == \"mult\"\n assert foo.inputs.x == 1 and foo.inputs.y == 2\n # execute task and save result\n res = foo()\n assert res.output.out == 2\n save(outdir, result=res)\n del res\n # load saved result\n res_pkl = outdir / \"_result.pklz\"\n res = cp.loads(res_pkl.read_bytes())\n assert res.output.out == 2\n\n\ndef test_hash_file(tmpdir):\n outdir = Path(tmpdir)\n with open(outdir / \"test.file\", \"wt\") as fp:\n fp.write(\"test\")\n assert (\n helpers_file.hash_file(outdir / \"test.file\")\n == \"9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08\"\n )\n\n\ndef test_hashfun_float():\n import math\n\n pi_50 = 3.14159265358979323846264338327950288419716939937510\n pi_15 = 3.141592653589793\n pi_10 = 3.1415926536\n # comparing for x that have the same x.as_integer_ratio()\n assert (\n math.pi.as_integer_ratio()\n == pi_50.as_integer_ratio()\n == pi_15.as_integer_ratio()\n )\n assert hash_function(math.pi) == hash_function(pi_15) == hash_function(pi_50)\n # comparing for x that have different x.as_integer_ratio()\n assert math.pi.as_integer_ratio() != pi_10.as_integer_ratio()\n assert hash_function(math.pi) != hash_function(pi_10)\n\n\ndef test_hash_value_dict():\n dict1 = {\"a\": 10, \"b\": 5}\n dict2 = {\"b\": 5, \"a\": 10}\n assert (\n hash_value(dict1)\n == hash_value(dict2)\n == [[\"a\", hash_value(10)], [\"b\", hash_value(5)]]\n == [[\"a\", 10], [\"b\", 5]]\n )\n\n\ndef test_hash_value_list_tpl():\n lst = [2, 5.6, \"ala\"]\n tpl = (2, 5.6, \"ala\")\n assert hash_value(lst) == [hash_value(2), hash_value(5.6), hash_value(\"ala\")] == lst\n assert hash_value(lst) == hash_value(tpl)\n\n\ndef test_hash_value_list_dict():\n lst = [2, {\"a\": \"ala\", \"b\": 1}]\n hash_value(lst)\n assert (\n hash_value(lst)\n == [hash_value(2), hash_value([[\"a\", \"ala\"], [\"b\", 1]])]\n == [2, [[\"a\", \"ala\"], [\"b\", 1]]]\n )\n\n\ndef test_hash_value_files(tmpdir):\n file_1 = tmpdir.join(\"file_1.txt\")\n file_2 = tmpdir.join(\"file_2.txt\")\n with open(file_1, \"w\") as f:\n f.write(\"hello\")\n with open(file_2, \"w\") as f:\n f.write(\"hello\")\n\n assert hash_value(file_1, tp=File) == hash_value(file_2, tp=File)\n assert hash_value(file_1, tp=str) != hash_value(file_2, tp=str)\n assert hash_value(file_1) != hash_value(file_2)\n assert hash_value(file_1, tp=File) == helpers_file.hash_file(file_1)\n\n\ndef test_hash_value_files_list(tmpdir):\n file_1 = tmpdir.join(\"file_1.txt\")\n file_2 = tmpdir.join(\"file_2.txt\")\n with open(file_1, \"w\") as f:\n f.write(\"hello\")\n with open(file_2, \"w\") as f:\n f.write(\"hi\")\n\n assert hash_value([file_1, file_2], tp=File) == [\n hash_value(file_1, tp=File),\n hash_value(file_2, tp=File),\n ]\n\n\ndef test_hash_value_dir(tmpdir):\n file_1 = tmpdir.join(\"file_1.txt\")\n file_2 = tmpdir.join(\"file_2.txt\")\n with open(file_1, \"w\") as f:\n f.write(\"hello\")\n with open(file_2, \"w\") as f:\n f.write(\"hi\")\n\n test_sha = hashlib.sha256()\n for fx in [file_1, file_2]:\n test_sha.update(helpers_file.hash_file(fx).encode())\n\n bad_sha = hashlib.sha256()\n for fx in [file_2, file_1]:\n bad_sha.update(helpers_file.hash_file(fx).encode())\n\n orig_hash = helpers_file.hash_dir(tmpdir)\n\n assert orig_hash == test_sha.hexdigest()\n assert orig_hash != bad_sha.hexdigest()\n assert orig_hash == hash_value(tmpdir, tp=Directory)\n\n\ndef test_hash_value_nested(tmpdir):\n hidden = tmpdir.mkdir(\".hidden\")\n nested = tmpdir.mkdir(\"nested\")\n file_1 = tmpdir.join(\"file_1.txt\")\n file_2 = hidden.join(\"file_2.txt\")\n file_3 = nested.join(\".file_3.txt\")\n file_4 = nested.join(\"file_4.txt\")\n\n test_sha = hashlib.sha256()\n for fx in [file_1, file_2, file_3, file_4]:\n with open(fx, \"w\") as f:\n f.write(str(random.randint(0, 1000)))\n test_sha.update(helpers_file.hash_file(fx).encode())\n\n orig_hash = helpers_file.hash_dir(tmpdir)\n\n assert orig_hash == test_sha.hexdigest()\n assert orig_hash == hash_value(tmpdir, tp=Directory)\n\n nohidden_hash = helpers_file.hash_dir(\n tmpdir, ignore_hidden_dirs=True, ignore_hidden_files=True\n )\n nohiddendirs_hash = helpers_file.hash_dir(tmpdir, ignore_hidden_dirs=True)\n nohiddenfiles_hash = helpers_file.hash_dir(tmpdir, ignore_hidden_files=True)\n\n assert orig_hash != nohidden_hash\n assert orig_hash != nohiddendirs_hash\n assert orig_hash != nohiddenfiles_hash\n\n file_3.remove()\n assert helpers_file.hash_dir(tmpdir) == nohiddenfiles_hash\n hidden.remove()\n assert helpers_file.hash_dir(tmpdir) == nohidden_hash\n\n\ndef test_get_available_cpus():\n assert get_available_cpus() > 0\n try:\n import psutil\n\n has_psutil = True\n except ImportError:\n has_psutil = False\n\n if hasattr(os, \"sched_getaffinity\"):\n assert get_available_cpus() == len(os.sched_getaffinity(0))\n\n if has_psutil and platform.system().lower() != \"darwin\":\n assert get_available_cpus() == len(psutil.Process().cpu_affinity())\n\n if platform.system().lower() == \"darwin\":\n assert get_available_cpus() == os.cpu_count()\n\n\ndef test_load_and_run(tmpdir):\n \"\"\" testing load_and_run for pickled task\"\"\"\n task_pkl = Path(tmpdir.join(\"task_main.pkl\"))\n\n task = multiply(name=\"mult\", x=[1, 2], y=10).split(\"x\")\n task.state.prepare_states(inputs=task.inputs)\n task.state.prepare_inputs()\n with task_pkl.open(\"wb\") as fp:\n cp.dump(task, fp)\n\n resultfile_0 = load_and_run(task_pkl=task_pkl, ind=0)\n resultfile_1 = load_and_run(task_pkl=task_pkl, ind=1)\n # checking the result files\n result_0 = cp.loads(resultfile_0.read_bytes())\n result_1 = cp.loads(resultfile_1.read_bytes())\n assert result_0.output.out == 10\n assert result_1.output.out == 20\n\n\ndef test_load_and_run_exception_load(tmpdir):\n \"\"\" testing raising exception and saving info in crashfile when when load_and_run\"\"\"\n task_pkl = Path(tmpdir.join(\"task_main.pkl\"))\n task = raise_xeq1(name=\"raise\", x=[1, 2]).split(\"x\")\n with pytest.raises(FileNotFoundError) as excinfo:\n task_0 = load_and_run(task_pkl=task_pkl, ind=0)\n\n\ndef test_load_and_run_exception_run(tmpdir):\n \"\"\" testing raising exception and saving info in crashfile when when load_and_run\"\"\"\n task_pkl = Path(tmpdir.join(\"task_main.pkl\"))\n\n task = raise_xeq1(name=\"raise\", x=[1, 2]).split(\"x\")\n task.state.prepare_states(inputs=task.inputs)\n task.state.prepare_inputs()\n\n with task_pkl.open(\"wb\") as fp:\n cp.dump(task, fp)\n\n with pytest.raises(Exception) as excinfo:\n task_0 = load_and_run(task_pkl=task_pkl, ind=0)\n assert \"i'm raising an exception!\" in str(excinfo.value)\n # checking if the crashfile has been created\n assert \"crash\" in str(excinfo.value)\n errorfile = Path(str(excinfo.value).split(\"here: \")[1][:-2])\n assert errorfile.exists()\n\n resultfile = errorfile.parent / \"_result.pklz\"\n assert resultfile.exists()\n # checking the content\n result_exception = cp.loads(resultfile.read_bytes())\n assert result_exception.errored is True\n\n # the second task should be fine\n resultfile = load_and_run(task_pkl=task_pkl, ind=1)\n result_1 = cp.loads(resultfile.read_bytes())\n assert result_1.output.out == 2\n\n\ndef test_load_and_run_wf(tmpdir):\n \"\"\" testing load_and_run for pickled task\"\"\"\n wf_pkl = Path(tmpdir.join(\"wf_main.pkl\"))\n\n wf = Workflow(name=\"wf\", input_spec=[\"x\", \"y\"])\n wf.add(multiply(name=\"mult\", x=wf.lzin.x, y=wf.lzin.y))\n wf.split(\"x\")\n wf.inputs.x = [1, 2]\n wf.inputs.y = 10\n\n wf.set_output([(\"out\", wf.mult.lzout.out)])\n\n # task = multiply(name=\"mult\", x=[1, 2], y=10).split(\"x\")\n wf.state.prepare_states(inputs=wf.inputs)\n wf.state.prepare_inputs()\n wf.plugin = \"cf\"\n\n with wf_pkl.open(\"wb\") as fp:\n cp.dump(wf, fp)\n\n resultfile_0 = load_and_run(ind=0, task_pkl=wf_pkl)\n resultfile_1 = load_and_run(ind=1, task_pkl=wf_pkl)\n # checking the result files\n result_0 = cp.loads(resultfile_0.read_bytes())\n result_1 = cp.loads(resultfile_1.read_bytes())\n assert result_0.output.out == 10\n assert result_1.output.out == 20\n\n\n@pytest.mark.parametrize(\n \"pos_args\",\n [\n [(2, \"b\"), (1, \"a\"), (3, \"c\")],\n [(-2, \"b\"), (1, \"a\"), (-1, \"c\")],\n [(None, \"b\"), (1, \"a\"), (-1, \"c\")],\n [(-3, \"b\"), (None, \"a\"), (-1, \"c\")],\n [(None, \"b\"), (1, \"a\"), (None, \"c\")],\n ],\n)\ndef test_position_sort(pos_args):\n final_args = position_sort(pos_args)\n assert final_args == [\"a\", \"b\", \"c\"]\n","sub_path":"pydra/engine/tests/test_helpers.py","file_name":"test_helpers.py","file_ext":"py","file_size_in_byte":9344,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"268532319","text":"#!/usr/bin/env python\n\"\"\"\ngit.py - Github Post-Receive Hooks Module\n\"\"\"\n\nimport atexit\nfrom fnmatch import fnmatch\nimport http.server\nfrom io import StringIO\nimport json\nimport logging\nimport os\nimport re\nimport signal\nfrom threading import Lock, Thread\nimport time\nimport urllib.parse\n\nfrom modules import more\nfrom tools import generate_report, PortReuseTCPServer, truncate\nimport web\n\nlogger = logging.getLogger('phenny')\n\n# githooks port\nPORT = 1234\n\n# module-global variables\nhttpd = None\nthread = None\nlock = Lock()\n\n\ndef close_socket():\n global httpd, thread\n\n with lock:\n if httpd:\n httpd.shutdown()\n httpd.server_close()\n httpd = None\n\n if thread:\n thread.join()\n thread = None\n\n MyHandler.phenny = None\n\natexit.register(close_socket)\n\ndef signal_handler(signal, frame):\n close_socket()\n\nsignal.signal(signal.SIGINT, signal_handler)\nsignal.signal(signal.SIGQUIT, signal_handler)\nsignal.signal(signal.SIGTERM, signal_handler)\n\n\n# githooks handler\nclass MyHandler(http.server.SimpleHTTPRequestHandler):\n phenny = None\n\n def return_data(self, site, data, commit):\n '''Generates a report for the specified site and commit.'''\n\n # fields = project name, author, commit message, modified files, added\n # files, removed files, revision\n fields = []\n if site == \"github\":\n fields = [\n data['repository']['name'],\n data['pusher']['name'],\n commit['message'],\n commit['modified'],\n commit['added'],\n commit['removed'],\n commit['id'][:7],\n ]\n elif site == \"googlecode\":\n fields = [\n data['project_name'],\n commit['author'],\n commit['message'],\n commit['modified'],\n commit['added'],\n commit['removed'],\n commit['revision'],\n ]\n elif site == \"bitbucket\":\n files = self.getBBFiles(commit['files'])\n fields = [\n 'turkiccorpora',\n commit['author'],\n commit['message'],\n files['modified'],\n files['added'],\n files['removed'],\n commit['node'],\n ]\n # the * is for unpacking\n return generate_report(*fields)\n\n # return error code because a GET request is meaningless\n def do_GET(self):\n parsed_params = urllib.parse.urlparse(self.path)\n query_parsed = urllib.parse.parse_qs(parsed_params.query)\n self.send_response(405)\n self.end_headers()\n\n def do_POST(self):\n '''Handles POST requests for all hooks.'''\n receive_time = time.time()\n\n try:\n # read and decode data\n logger.debug('payload received; headers: '+str(self.headers))\n length = int(self.headers['Content-Length'])\n indata = self.rfile.read(length)\n post_data = urllib.parse.parse_qs(indata.decode('utf-8'))\n\n if len(post_data) == 0:\n post_data = indata.decode('utf-8')\n if \"payload\" in post_data:\n data = json.loads(post_data['payload'][0])\n else:\n data = json.loads(post_data)\n except Exception as error:\n logger.error('Error 400 (no valid payload)')\n logger.error(str(error))\n\n # 400 Bad Request\n self.send_response(400)\n self.end_headers()\n\n for channel in self.phenny.config.channels:\n self.phenny.msg(channel, 'Webhook received malformed payload')\n\n return\n\n try:\n result = self.do_POST_unsafe(data)\n except Exception as error:\n logger.error(str(error))\n result = None\n\n if result:\n status = 200 # OK\n else:\n status = 500 # Internal Server Error\n\n self.send_response(status)\n self.end_headers()\n self.finish()\n self.connection.close()\n\n send_time = time.time()\n respond_time = send_time - receive_time\n logger.debug(\"responded '{:}' in {:.2f}s\".format(status, respond_time))\n\n if result:\n # post all messages to all channels\n channels, messages = result\n\n for channel in channels:\n more.add_messages(self.phenny, channel, messages)\n\n return\n\n logger.error(str(data))\n\n try:\n commits = [commit['url'] for commit in data['commits']]\n logger.error('Internal Error (commits were ' + ', '.join(commits) + ')')\n except:\n logger.error('Internal Error (commits unknown or malformed)')\n\n for channel in self.phenny.config.channels:\n self.phenny.msg(channel, 'Webhook received problematic payload')\n\n def do_POST_unsafe(self, data):\n '''Runs once per event. One repository. One event type.'''\n config = self.phenny.config\n\n default_channels = config.git_channels.get('*', config.channels)\n channels = default_channels\n\n # both commit reports and error reports\n messages = []\n\n repo = ''\n event = None\n\n # handle GitHub triggers\n if 'GitHub' in self.headers['User-Agent']:\n event = self.headers['X-Github-Event']\n user = data['sender']['login']\n\n if 'repository' in data:\n repo = data['repository']['name']\n elif 'organization' in data:\n repo = data['organization']['login'] + ' (org)'\n\n if config.git_events:\n full_name = data['repository']['full_name']\n event_types = []\n\n for key, value in config.git_events.items():\n if fnmatch(full_name, key):\n event_types = value\n else:\n event_types = None\n\n event_in_config = False\n if 'action' in data:\n for event_type in event_types:\n if (event + '_' + data['action'] == event_type) or (event == event_type):\n event_in_config = True\n\n if (event_types is not None) and ((event not in event_types) and (not event_in_config)):\n return [], []\n\n if config.git_channels:\n full_name = data['repository']['full_name']\n channels = []\n\n for key, value in config.git_channels.items():\n if fnmatch(full_name, key):\n channels = value\n\n if event == 'commit_comment':\n commit = data['comment']['commit_id'][:7]\n url = data['comment']['html_url']\n url = url[:url.rfind('/') + 7]\n action = data['action']\n\n if action == 'deleted':\n template = '{:}: {:} * comment deleted on commit {:}: {:}'\n messages.append(template.format(repo, user, commit, url))\n else:\n template = '{:}: {:} * comment {:} on commit {:}: {:} {:}'\n messages.append(truncate(\n data['comment']['body'],\n template.format(repo, user, action, commit, '{}', url)\n ))\n elif event == 'create' or event == 'delete':\n template = '{:}: {:} * {:} {:} {:}d {:}'\n ref = data['ref']\n type_ = data['ref_type']\n messages.append(template.format(repo, user, type_, ref, event))\n elif event == 'fork':\n template = '{:}: {:} forked this repo {:}'\n url = data['forkee']['html_url']\n messages.append(template.format(repo, user, url))\n elif event == 'issue_comment':\n if 'pull_request' in data['issue']:\n url = data['issue']['pull_request']['html_url']\n text = 'pull request'\n else:\n url = data['issue']['html_url']\n text = 'issue'\n\n number = data['issue']['number']\n action = data['action']\n\n if action == 'deleted':\n template = '{:}: {:} * comment deleted on {:} #{:}: {:}'\n messages.append(template.format(repo, user, text, number, url))\n else:\n template = '{:}: {:} * comment {:} on {:} #{:}: {:} {:}'\n messages.append(truncate(\n data['comment']['body'],\n template.format(repo, user, action, text, number, '{}', url)\n ))\n elif event == 'issues':\n template = '{:}: {:} * issue #{:} \"{:}\" {:} {:} {:}'\n\n number = data['issue']['number']\n title = data['issue']['title']\n action = data['action']\n url = data['issue']['html_url']\n opt = ''\n\n if data['issue']['assignee']:\n opt += 'assigned to ' + data['issue']['assignee']['login']\n elif 'label' in data:\n opt += 'with ' + data['label']['name']\n\n messages.append(template.format(repo, user, number, title, action, opt, url))\n elif event == 'member':\n template = '{:}: {:} * user {:} {:} as collaborator {:}'\n new_user = data['member']['login']\n action = data['action']\n messages.append(template.format(repo, user, new_user, action))\n elif event == 'membership':\n template = '{:}: user {:} {:} {:} {:} {:} {:}'\n new_user = data['member']['login']\n action = data['action']\n prep = ['to', 'from'][int(action == 'removed')]\n scope = data['scope']\n name = data['team']['name']\n messages.append(template.format(repo, new_user, action, prep, scope, name))\n elif event == 'pull_request':\n template = '{:}: {:} * pull request #{:} \"{:}\" {:} {:} {:}'\n number = data['number']\n title = data['pull_request']['title']\n action = data['action']\n url = data['pull_request']['html_url']\n opt = ''\n\n if data['pull_request']['assignee']:\n opt = 'to ' + data['pull_request']['assignee']\n\n messages.append(template.format(repo, user, number, title, action, opt, url))\n elif event == 'pull_request_review_comment':\n template = '{:}: {:} * review comment deleted on pull request #{:}: {:}'\n number = data['pull_request']['number']\n url = data['comment']['html_url']\n action = data['action']\n if action == 'deleted':\n messages.append(template.format(repo, user, number, url))\n else:\n template = '{:}: {:} * review comment {:} on pull request #{:}: {:} {:}'\n try:\n blacklist_pull_request_comment_users = config.blacklist_pull_request_comment_users\n except AttributeError:\n blacklist_pull_request_comment_users = ()\n if user not in blacklist_pull_request_users:\n messages.append(truncate(\n data['comment']['body'],\n template.format(repo, user, action, number, '{}', url)\n ))\n elif event == 'push':\n pusher_name = data['pusher']['name']\n\n if pusher_name in config.gitbots:\n return [], []\n\n ref = data['ref'].split('/')[-1]\n repo_fullname = data['repository']['full_name']\n fork = data['repository']['fork']\n\n if (ref != 'master' and ref != 'main') or fork:\n try:\n channels = config.branch_channels[repo_fullname][ref]\n except:\n return [], []\n\n template = '{:}: {:} [ {:} ] {:}: {:}'\n\n out_messages = []\n out_commithashes = []\n out_files = set()\n\n for commit in data['commits']:\n out_commithashes.append(commit['id'][:7])\n out_files.update(commit['modified'], commit['added'])\n out_messages.append(commit['message'])\n\n messages.append(truncate(\" * \".join(out_messages), template.format(\n data['repository']['name'],\n pusher_name,\n ' '.join(out_commithashes),\n ', '.join(out_files),\n '{}'\n )))\n\n elif event == 'release':\n template = '{:}: {:} * release {:} {:} {:}'\n tag = data['release']['tag_name']\n action = data['action']\n url = data['release']['html_url']\n messages.append(template.format(repo, user, tag, action, url))\n elif event == 'repository':\n template = 'new repository {:} {:} by {:} {:}'\n name = data['repository']['name']\n action = data['action']\n url = data['repository']['url']\n messages.append(template.format(name, action, user, url, url))\n elif event == 'team_add':\n template = 'repository {:} added to team {:} {:}'\n name = data['repository']['full_name']\n team = data['team']['name']\n messages.append(template.format(name, team))\n elif event == 'ping':\n template = 'ping from {:}, org: {:}'\n\n if 'organization' in data:\n org = data['organization']\n else:\n org = \"no org specified!\"\n\n sender = data['sender']['login']\n messages.append(template.format(sender, org))\n\n elif 'Jenkins' in self.headers['User-Agent']:\n messages.append('Jenkins: {}'.format(data['message']))\n # not github or Jenkins\n elif \"commits\" in data:\n for commit in data['commits']:\n try:\n if \"author\" in commit:\n # for bitbucket\n message = self.return_data(\"bitbucket\", data, commit)\n messages.append(message)\n else:\n # we don't know which site\n message = \"unsupported data: \" + str(commit)\n messages.append(message)\n except Exception:\n logger.warning(\"unsupported data: \" + str(commit))\n\n if not messages:\n # we couldn't get anything\n channels = default_channels\n\n if event:\n messages.append(\"Don't know about '\" + event + \"' events\")\n else:\n messages.append(\"Unable to deal with unknown event\")\n\n return channels, messages\n\n def getBBFiles(self, filelist):\n '''Sort filelist into added, modified, and removed files\n (only for bitbucket).'''\n\n toReturn = {\"added\": [], \"modified\": [], \"removed\": []}\n for onefile in filelist:\n toReturn[onefile['type']].append(onefile['file'])\n return toReturn\n\n\ndef setup_server(phenny):\n '''Set up and start hooks server.'''\n\n global httpd, thread\n\n with lock:\n if httpd:\n return\n\n MyHandler.phenny = phenny\n httpd = PortReuseTCPServer((\"\", PORT), MyHandler)\n thread = Thread(target=httpd.serve_forever)\n thread.daemon = True\n thread.start()\n\n\ndef auto_start(phenny, input):\n if input.nick != phenny.nick:\n return\n\n if phenny.config.githook_autostart:\n setup_server(phenny)\nauto_start.rule = '(.*)'\nauto_start.event = 'JOIN'\nauto_start.thread = False\n\ndef manual_start(phenny, input):\n phenny.reply(\"gonna try to setup_server and see if it crashes\")\n phenny.teardown()\n setup_server(phenny)\n\nmanual_start.name = \"manual_start\"\nmanual_start.rule = \".manualstart\"\nmanual_start.thread = False\n\n\ndef teardown(phenny):\n phenny.say(\"TEARING DOWN SERVER!\")\n lock.release()\n thread.stop()\n close_socket()\n\n\ndef gitserver(phenny, input):\n '''Control git server. Possible commands are:\n .gitserver status (all users)\n .gitserver start (admins only)\n .gitserver stop (admins only)'''\n\n global httpd\n\n command = input.group(1).strip()\n if input.admin:\n # we're admin\n # everwhere below, 'httpd' being None indicates that the server is not\n # running at the moment\n if command == \"stop\":\n if httpd is not None:\n teardown(phenny)\n else:\n phenny.reply(\"Server is already down!\")\n elif command == \"start\":\n if httpd is None:\n setup_server(phenny)\n else:\n phenny.reply(\"Server is already up!\")\n elif command == \"status\":\n if httpd is None:\n phenny.reply(\"Server is down! Start using '.gitserver start'\")\n else:\n phenny.reply(\"Server is up! Stop using '.gitserver stop'\")\n else:\n phenny.reply(\"Usage '.gitserver [status | start | stop]'\")\n else:\n if command == \"status\":\n if httpd is None:\n phenny.reply(\"Server is down! (Only admins can start it up)\")\n else:\n phenny.reply((\"Server is up and running! \"\n \"(Only admins can shut it down)\"))\n else:\n phenny.reply(\"Usage '.gitserver [status]'\")\n# command metadata and invocation\ngitserver.name = \"gitserver\"\ngitserver.rule = ('.gitserver', '(.*)')\ngitserver.thread = False\n\n\ndef to_commit(phenny, input):\n api = \"https://api.github.com/search/commits?q=%s\"\n # currently experimental API\n headers = { \"Accept\": \"application/vnd.github.cloak-preview\" }\n\n sha = input.group(1)\n commit_json = web.get(api % sha, headers=headers)\n data = json.loads(commit_json)\n\n item = data[\"items\"][0]\n html_url = item[\"html_url\"]\n\n phenny.reply(html_url)\nto_commit.name = \"to_commit\"\nto_commit.rule = '!commit ([0-9a-f]{7,40})'\n\n\ndef get_commit_info(phenny, repo, sha):\n '''Get commit information for a given repository and commit identifier.'''\n\n repoUrl = phenny.config.git_repositories[repo]\n if repoUrl.find(\"code.google.com\") >= 0:\n locationurl = '/source/detail?r=%s'\n elif repoUrl.find(\"api.github.com\") >= 0:\n locationurl = '/commits/%s'\n elif repoUrl.find(\"bitbucket.org\") >= 0:\n locationurl = ''\n html = web.get(repoUrl + locationurl % sha)\n # get data\n data = json.loads(html)\n author = data['commit']['committer']['name']\n comment = data['commit']['message']\n\n # create summary of commit\n modified_paths = []\n added_paths = []\n removed_paths = []\n for file in data['files']:\n if file['status'] == 'modified':\n modified_paths.append(file['filename'])\n elif file['status'] == 'added':\n added_paths.append(file['filename'])\n elif file['status'] == 'removed':\n removed_paths.append(file['filename'])\n # revision number is first seven characters of commit indentifier\n rev = sha[:7]\n # format date\n date = time.strptime(data['commit']['committer']['date'],\n \"%Y-%m-%dT%H:%M:%SZ\")\n date = time.strftime(\"%d %b %Y %H:%M:%S\", date)\n\n url = data['html_url']\n\n return (author, comment, modified_paths, added_paths, removed_paths,\n rev, date), url\n\n\ndef get_recent_commit(phenny, input):\n '''Get recent commit information for each repository Begiak monitors. This\n command is called as 'begiak: recent'.'''\n\n for repo in phenny.config.git_repositories:\n html = web.get(phenny.config.git_repositories[repo] + '/commits')\n data = json.loads(html)\n # the * is for unpacking\n info, url = get_commit_info(phenny, repo, data[0]['sha'])\n msg = generate_report(repo, *info)\n # the URL is truncated so that it has at least 6 sha characters\n url = url[:url.rfind('/') + 7]\n phenny.say(truncate(msg, '{} ' + url))\n# command metadata and invocation\nget_recent_commit.rule = ('$nick', 'recent')\nget_recent_commit.priority = 'medium'\nget_recent_commit.thread = True\n\n\ndef retrieve_commit(phenny, input):\n '''Retreive commit information for a given repository and revision. This\n command is called as 'begiak: info '.'''\n\n # get repo and rev with regex\n data = input.group(1).split(' ')\n\n if len(data) != 2:\n phenny.reply(\"Invalid number of parameters.\")\n return\n\n repo = data[0]\n rev = data[1]\n\n if repo in phenny.config.svn_repositories:\n # we don't handle SVN; see modules/svnpoller.py for that\n return\n if repo not in phenny.config.git_repositories:\n phenny.reply(\"That repository is not monitored by me!\")\n return\n try:\n info, url = get_commit_info(phenny, repo, rev)\n except:\n phenny.reply(\"Invalid revision value!\")\n return\n # the * is for unpacking\n msg = generate_report(repo, *info)\n # the URL is truncated so that it has at least 6 sha characters\n url = url[:url.rfind('/') + 7]\n phenny.say(truncate(msg, '{} ' + url))\n# command metadata and invocation\nretrieve_commit.rule = ('$nick', 'info(?: +(.*))')\n","sub_path":"modules/git.py","file_name":"git.py","file_ext":"py","file_size_in_byte":21895,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"148860672","text":"# -*- coding: utf-8 -*-\n# Copyright 2019 The Blueoil 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\nimport numpy as np\nimport tensorflow as tf\nfrom easydict import EasyDict\n\nfrom lmnet.common import Tasks\nfrom lmnet.data_processor import Sequence\nfrom lmnet.networks.optical_flow_estimation.flownet_s_v3 import (\n FlowNetSV3\n)\nfrom lmnet.datasets.optical_flow_estimation import (\n FlyingChairs, ChairsSDHom\n)\nfrom lmnet.networks.optical_flow_estimation.data_augmentor import (\n Brightness, Color, Contrast, Gamma, GaussianBlur, GaussianNoise, Hue,\n FlipLeftRight, FlipTopBottom, Scale, Rotate, Translate\n)\nfrom lmnet.networks.optical_flow_estimation.pre_processor import (\n DevideBy255\n)\n\nNETWORK_CLASS = FlowNetSV3\nDATASET_CLASS = FlyingChairs\n\nIMAGE_SIZE = [384, 512]\nDATA_FORMAT = \"NHWC\"\nTASK = Tasks.OPTICAL_FLOW_ESTIMATION\nCLASSES = DATASET_CLASS.classes\n\nIS_DEBUG = False\nMAX_STEPS = 1200000\nSAVE_CHECKPOINT_STEPS = 5000\nKEEP_CHECKPOINT_MAX = 20\nTEST_STEPS = 250\nSUMMARISE_STEPS = 1000\nBATCH_SIZE = 8\n\n# for debugging\n# IS_DEBUG = True\n# MAX_STEPS = 10\n# BATCH_SIZE = 31\n# SAVE_CHECKPOINT_STEPS = 2\n# KEEP_CHECKPOINT_MAX = 5\n# TEST_STEPS = 10\n# SUMMARISE_STEPS = 2\n\n# pretrain\nIS_PRETRAIN = False\nPRETRAIN_VARS = []\nPRETRAIN_DIR = \"\"\nPRETRAIN_FILE = \"\"\n\n# distributed training\nIS_DISTRIBUTION = False\n\nPRE_PROCESSOR = Sequence([\n DevideBy255(),\n])\nPOST_PROCESSOR = None\n\nNETWORK = EasyDict()\nNETWORK.OPTIMIZER_CLASS = tf.train.AdamOptimizer\nNETWORK.OPTIMIZER_KWARGS = {\"beta1\": 0.9, \"beta2\": 0.999}\nNETWORK.LEARNING_RATE_FUNC = tf.train.piecewise_constant\nNETWORK.LEARNING_RATE_KWARGS = {\n \"values\": [0.0001, 0.00005, 0.000025, 0.0000125, 0.00000625],\n \"boundaries\": [400000, 600000, 800000, 1000000],\n}\nNETWORK.WEIGHT_DECAY_RATE = 0.0004\nNETWORK.IMAGE_SIZE = IMAGE_SIZE\nNETWORK.BATCH_SIZE = BATCH_SIZE\nNETWORK.DATA_FORMAT = DATA_FORMAT\n\n# dataset\nDATASET = EasyDict()\nDATASET.BATCH_SIZE = BATCH_SIZE\nDATASET.DATA_FORMAT = DATA_FORMAT\nDATASET.TRAIN_ENABLE_PREFETCH = True\nDATASET.TRAIN_PROCESS_NUM = 10\nDATASET.TRAIN_QUEUE_SIZE = 1000\nDATASET.VALIDATION_ENABLE_PREFETCH = False\nDATASET.VALIDATION_PRE_LOAD = False\nDATASET.VALIDATION_PROCESS_NUM = 1\nDATASET.VALIDATION_QUEUE_SIZE = 500\nDATASET.VALIDATION_RATE = 0.1\nDATASET.VALIDATION_SEED = 2019\n\n# TODO I use default values because the metrics used in the paper are different.\n# I didn't add Gaussian Blur because it's different from Gaussian Noise.\n# Augmentation is not available in pytorch repo\n\n# NOTE (by KI-42) in the FlowNetS paper, the following augmentations were used.\n# Geometric transformation\n# translation U([-20 %, +20 %])\n# rotation U([-17 deg, +17 deg])\n# scaling U([0.9, 2.0])\n# Pixel-Wise transformation\n# Gaussian noise N(0, 1) * U([0.0, 0.04 * (255)])\n# contrast U([0.2, 1.4])\n# color U([0.5, 2.0])\n# gamma U([0.7, 1.5])\n# brightness 1 + 0.2 * N(0, 1)\n\n# NOTE (by KI-42) in this setup, I modified the augmentation setup described above a little bit.\n# hue U([-128 deg, 128 deg])\n# brightness U(0.6, 1.4)\n\nDATASET.AUGMENTOR = Sequence([\n # Geometric transformation\n FlipLeftRight(0.5),\n FlipTopBottom(0.5),\n Translate(-0.2, 0.2),\n Rotate(-17, +17),\n Scale(1.0, 2.0),\n # Pixel-wise augmentation\n Brightness(0.6, 1.4),\n Contrast(0.2, 1.4),\n Color(0.5, 2.0),\n Gamma(0.7, 1.5),\n # Hue(-128.0, 128.0),\n GaussianNoise(10.0)\n # GaussianBlur(0.0, 2.0)\n])\nDATASET.PRE_PROCESSOR = PRE_PROCESSOR\n","sub_path":"lmnet/configs/core/optical_flow_estimation/flownet_s_v3.py","file_name":"flownet_s_v3.py","file_ext":"py","file_size_in_byte":4127,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"36904244","text":"# pylint: skip-file\n\nclass YeditException(Exception):\n ''' Exception class for Yedit '''\n pass\n\nclass Yedit(object):\n ''' Class to modify yaml files '''\n\n def __init__(self, filename=None, content=None):\n self.content = content\n self.filename = filename\n self.__yaml_dict = content\n if self.filename and not self.content:\n self.get()\n elif self.filename and self.content:\n self.write()\n\n @property\n def yaml_dict(self):\n ''' getter method for yaml_dict '''\n return self.__yaml_dict\n\n @yaml_dict.setter\n def yaml_dict(self, value):\n ''' setter method for yaml_dict '''\n self.__yaml_dict = value\n\n @staticmethod\n def remove_entry(data, keys):\n ''' remove an item from a dictionary with key notation a.b.c\n d = {'a': {'b': 'c'}}}\n keys = a.b\n item = c\n '''\n if \".\" in keys:\n key, rest = keys.split(\".\", 1)\n if key in data.keys():\n Yedit.remove_entry(data[key], rest)\n else:\n del data[keys]\n\n @staticmethod\n def add_entry(data, keys, item):\n ''' Add an item to a dictionary with key notation a.b.c\n d = {'a': {'b': 'c'}}}\n keys = a.b\n item = c\n '''\n if \".\" in keys:\n key, rest = keys.split(\".\", 1)\n if key not in data:\n data[key] = {}\n\n if not isinstance(data, dict):\n raise YeditException('Invalid add_entry called on a [%s] of type [%s].' % (data, type(data)))\n else:\n Yedit.add_entry(data[key], rest, item)\n\n else:\n data[keys] = item\n\n\n @staticmethod\n def get_entry(data, keys):\n ''' Get an item from a dictionary with key notation a.b.c\n d = {'a': {'b': 'c'}}}\n keys = a.b\n return c\n '''\n if keys and \".\" in keys:\n key, rest = keys.split(\".\", 1)\n if not isinstance(data[key], dict):\n raise YeditException('Invalid get_entry called on a [%s] of type [%s].' % (data, type(data)))\n\n else:\n return Yedit.get_entry(data[key], rest)\n\n else:\n return data.get(keys, None)\n\n\n def write(self):\n ''' write to file '''\n if not self.filename:\n raise YeditException('Please specify a filename.')\n\n with open(self.filename, 'w') as yfd:\n yfd.write(yaml.safe_dump(self.yaml_dict, default_flow_style=False))\n\n def read(self):\n ''' write to file '''\n # check if it exists\n if not self.exists():\n return None\n\n contents = None\n with open(self.filename) as yfd:\n contents = yfd.read()\n\n return contents\n\n def exists(self):\n ''' return whether file exists '''\n if os.path.exists(self.filename):\n return True\n\n return False\n\n def get(self):\n ''' return yaml file '''\n contents = self.read()\n\n if not contents:\n return None\n\n # check if it is yaml\n try:\n self.yaml_dict = yaml.load(contents)\n except yaml.YAMLError as _:\n # Error loading yaml\n return None\n\n return self.yaml_dict\n\n def delete(self, key):\n ''' put key, value into a yaml file '''\n try:\n entry = Yedit.get_entry(self.yaml_dict, key)\n except KeyError as _:\n entry = None\n if not entry:\n return (False, self.yaml_dict)\n\n Yedit.remove_entry(self.yaml_dict, key)\n self.write()\n return (True, self.get())\n\n def put(self, key, value):\n ''' put key, value into a yaml file '''\n try:\n entry = Yedit.get_entry(self.yaml_dict, key)\n except KeyError as _:\n entry = None\n\n if entry == value:\n return (False, self.yaml_dict)\n\n Yedit.add_entry(self.yaml_dict, key, value)\n self.write()\n return (True, self.get())\n\n def create(self, key, value):\n ''' create the file '''\n if not self.exists():\n self.yaml_dict = {key: value}\n self.write()\n return (True, self.get())\n\n return (False, self.get())\n","sub_path":"roles/lib_yaml_editor/build/src/yedit.py","file_name":"yedit.py","file_ext":"py","file_size_in_byte":4326,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"647766039","text":"# -*- coding:utf-8 -*-\r\n__author__ = 'changjie.fan'\r\n\r\n\"\"\"\"\"\"\r\nimport json\r\nfrom datetime import datetime\r\n\r\nfrom flask import render_template, redirect, url_for, request, flash, current_app, session\r\nfrom flask.ext.login import login_required, current_user\r\n\r\nfrom . import qa\r\nfrom models import *\r\nfrom tms.qa.views import need_test_version\r\n\r\n\r\n@qa.route('/test_case_page')\r\n@login_required\r\n@need_test_version()\r\ndef test_case_page():\r\n \"\"\"用例页面\"\"\"\r\n session['breadcrumbs'] = [session['breadcrumbs'][0]]\r\n session['breadcrumbs'].append({'text': '我的用例', 'url': url_for('qa.test_case_page')})\r\n session['menu_path'] = ['用例管理', '我的用例']\r\n\r\n return render_template('qa/test_case_page.html')\r\n\r\n\r\n@qa.route('/test_case_data')\r\n@login_required\r\ndef test_case_data():\r\n \"\"\"用例页面表格数据\"\"\"\r\n\r\n start = int(request.args.get('start', 0))\r\n length = int(request.args.get('length', 10))\r\n is_all = request.args.get('is_all', 'false')\r\n\r\n if is_all:\r\n all_count = TestCase.query.filter(TestCase.activate == True).count()\r\n test_case = TestCase.query.filter(TestCase.activate == True).all()[start: start+length]\r\n else:\r\n # 默认现在用例负责人是我的用例\r\n all_count = TestCase.query.filter(\r\n db.and_(TestCase.activate == True, TestCase.add_user_id == current_user.id)).count()\r\n test_case = TestCase.query.filter(\r\n db.and_(TestCase.activate == True,\r\n TestCase.add_user_id == current_user.id)).all()[start: start+length]\r\n\r\n records = []\r\n index = start + 1\r\n for record in test_case:\r\n records.append({\r\n \"id\": record.id,\r\n \"index\": index,\r\n \"number\": record.number,\r\n \"level\": record.level,\r\n \"test_type\": record.test_type,\r\n \"module_name\": record.module_name,\r\n \"test_fun\": record.test_fun,\r\n \"class_name\": record.class_name,\r\n \"method_name\": record.method_name,\r\n \"test_target\": record.test_target,\r\n \"standard_sdk\": record.standard_sdk,\r\n \"test_init\": record.test_init,\r\n \"test_step\": record.test_step,\r\n \"expect_result\": record.expect_result,\r\n \"activate\": record.activate,\r\n \"add_user\": record.add_user.display_name,\r\n \"add_time\": str(record.add_time),\r\n \"last_user\": record.last_user.display_name,\r\n \"last_update_time\": str(record.last_update_time),\r\n })\r\n index += 1\r\n\r\n return '{\"recordsTotal\": %s ,\"recordsFiltered\": %s,\"data\":%s}' % (all_count, all_count, json.dumps(records))\r\n\r\n\r\n@qa.route('/edit_test_case', defaults={'id': None}, methods=['GET', 'POST'])\r\n@qa.route('/edit_test_case/', methods=['GET', 'POST'])\r\n@login_required\r\n@need_test_version()\r\ndef edit_test_case(id):\r\n \"\"\"添加或修改测试用例\"\"\"\r\n\r\n if id:\r\n test_case_obj = TestCase.query.filter(TestCase.id == id).first()\r\n else:\r\n test_case_obj = None\r\n\r\n if request.method == 'POST':\r\n number = request.form.get('number', '').strip()\r\n other_test_case = TestCase.query.filter(TestCase.number == number).first()\r\n if other_test_case and other_test_case.id != id:\r\n flash(u'相同编号的测试用例已存在', 'dange')\r\n else:\r\n if id:\r\n message = u'修改成功'\r\n else:\r\n test_case_obj = TestCase()\r\n message = u'添加成功!'\r\n\r\n test_case_history = TestCaseLog()\r\n test_case_obj.number = number\r\n test_case_obj.level = request.form.get('level', '').strip()\r\n test_case_obj.test_type = request.form.get('test_type', '').strip()\r\n test_case_obj.module_name = request.form.get('module_name', '').strip()\r\n test_case_obj.class_name = request.form.get('class_name', '').strip()\r\n test_case_obj.method_name = request.form.get('method_name', '').strip()\r\n test_case_obj.test_fun = request.form.get('test_fun', '').strip()\r\n test_case_obj.test_target = request.form.get('test_target', '').strip()\r\n if request.form.get('standard_sdk', '') == 'on':\r\n test_case_obj.standard_sdk = True\r\n else:\r\n test_case_obj.standard_sdk = False\r\n test_case_obj.test_init = request.form.get('test_init', '').strip()\r\n test_case_obj.test_step = request.form.get('test_step', '').strip()\r\n test_case_obj.expect_result = request.form.get('expect_result', '').strip()\r\n if request.form.get('activate', '') == 'on':\r\n test_case_obj.activate = True\r\n else:\r\n test_case_obj.activate = False\r\n\r\n if not id:\r\n test_case_obj.add_user_id = current_user.id\r\n test_case_obj.add_time = datetime.now()\r\n test_case_history.content = u'新增测试用例,编号:{0},模块:{1},类名:{2},方法名:{3}' \\\r\n u''.format(test_case_obj.number, test_case_obj.module_name,\r\n test_case_obj.class_name, test_case_obj.method_name)\r\n else:\r\n test_case_history.content = u'修改测试用例,编号:{0},模块:{1},类名:{2},方法名:{3}' \\\r\n u''.format(test_case_obj.number, test_case_obj.module_name,\r\n test_case_obj.class_name, test_case_obj.method_name)\r\n\r\n test_case_obj.last_user_id = current_user.id\r\n test_case_obj.last_update_time = datetime.now()\r\n\r\n db.session.add(test_case_obj)\r\n db.session.commit()\r\n test_case_history.test_case = test_case_obj\r\n test_case_history.user_id = current_user.id\r\n test_case_history.update_time = datetime.now()\r\n db.session.add(test_case_history)\r\n db.session.commit()\r\n\r\n flash(message, 'info')\r\n return redirect(url_for('qa.test_case_page'))\r\n\r\n if session['user']['role_name'] == 'os_test':\r\n permission = True\r\n else:\r\n permission = False\r\n case_level = ['S', 'A', 'B', 'C']\r\n test_type = [u'功能测试', u'冒烟测试']\r\n return render_template('qa/edit_test_case.html', test_case=test_case_obj, permission=permission,\r\n case_level=case_level, test_type=test_type)\r\n\r\n\r\n\r\n","sub_path":"tms/qa/testCaseViews.py","file_name":"testCaseViews.py","file_ext":"py","file_size_in_byte":6589,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"111009218","text":"#!/usr/bin/env python\r\n\r\nfrom __future__ import print_function\r\nimport sys\r\nimport re\r\nimport time\r\n\r\n# run program as:\r\n# find-quad-denovo.py (type \"dad\" \"mom\" \"child\", or \"child2\")\r\n# \"child\" will be the one compared against the parents\r\n# \"child2\" will be ignored\r\n\r\n\r\ndef main():\r\n startTime = time.time()\r\n inFileName = sys.argv[1]\r\n momIdx = sys.argv.index(\"mom\") #user inputs the order of the family member columns\r\n dadIdx = sys.argv.index(\"dad\")\r\n childIdx = sys.argv.index(\"child\")\r\n child2Idx = sys.argv.index(\"child2\")\r\n\r\n variant_count = 0 #counts phased and unphased variants\r\n unphased_count = 0 #separate counter for variants with all lines treated as unphased\r\n have_data = True\r\n\r\n with open (inFileName, 'r') as infile: #when you use \"with open\" you don't have to close the file later\r\n with open (inFileName + \".variants\", \"w\") as variantFile: \r\n with open (inFileName + \".variants.as.unphased\", \"w\") as unphasedFile: \r\n for line in infile:\r\n if line.startswith(\"#\"): # header and info lines start with \"#\"\r\n variantFile.write(line) \r\n unphasedFile.write(line) \r\n else:\r\n (is_variant, is_unphased, have_data) = process_line(line, dadIdx-2, momIdx-2, childIdx-2, child2Idx-2, variant_count, unphased_count)\r\n if have_data:\r\n if is_variant:\r\n variant_count += 1\r\n variantFile.write(line) #variants with phased and unphased lines treated separately\r\n\r\n if is_unphased:\r\n unphased_count += 1\r\n unphasedFile.write(line) #variants with all lines treated as unphased\r\n\r\n completion_msg = \"\\nThe script took {0} minutes\\n\".format((time.time() - startTime)/60)\r\n\r\n variantFile.write(completion_msg)\r\n variantFile.write(\"{0} phased and unphased variants were found\".format(variant_count))\r\n\r\n unphasedFile.write(completion_msg)\r\n unphasedFile.write(\"{0} variants were found when all lines were treated as unphased\".format(unphased_count))\r\n\r\n\r\ndef process_line(line, dadIdx, momIdx, childIdx, child2Idx, variant_count, unphased_count):\r\n is_unphased = False\r\n is_variant = False\r\n have_data = True\r\n\r\n (chrom, pos, ID, ref, alt, qual, Filter, info, format, samples) = line.strip(\"\\n\").split(\"\\t\", 9)\r\n samples = samples.split(\"\\t\")\r\n dadgeno = samples[dadIdx]\r\n momgeno = samples[momIdx]\r\n childgeno = samples[childIdx]\r\n\r\n (dadAlleles, dadPhased) = extract_genes(dadgeno)\r\n (momAlleles, momPhased) = extract_genes(momgeno)\r\n (childAlleles, childPhased) = extract_genes(childgeno)\r\n\r\n #check to see if genotype information is missing\r\n if \".\" in dadAlleles or \".\" in momAlleles or \".\" in childAlleles:\r\n have_data = False\r\n\r\n # assumes that delimiter on dadGeno is same as momGeno and childGeno\r\n if dadPhased != momPhased or dadPhased != childPhased:\r\n print(\"Family phasing doesn't match!\")\r\n exit(1)\r\n\r\n phased = dadPhased\r\n\r\n child_in_dad = child_in_parent(childAlleles, dadAlleles)\r\n child_in_mom = child_in_parent(childAlleles, momAlleles)\r\n\r\n #Treat all lines as unphased and record variants in second output file\r\n if ((not child_in_dad[0] and not child_in_mom[0]) or # variant because child1 not in either parent\r\n (not child_in_dad[1] and not child_in_mom[1]) or # variant because child2 not in either parent\r\n (not child_in_dad[0] and not child_in_dad[1]) or # variant because neither child allele in dad\r\n (not child_in_mom[0] and not child_in_mom[1])): # variant because neither child allele in mom\r\n is_unphased = True #every line treated as unphased; just needs to meet above conditions\r\n\r\n # When a line is truly unphased(\"/\"), phased = false, is_variant = True. Will print to both files.\r\n is_variant = not phased\r\n\r\n # Variant conditions if the data is phased, to print only to phased/unphased file\r\n if (phased and (not child_in_dad[0] or not child_in_mom[1])): # variant because one or both parents\r\n is_variant = True # didn't contribute an allele to the child\r\n\r\n return (is_variant, is_unphased, have_data)\r\n\r\ndef extract_genes(unparsed_geno):\r\n # split the data by \":\", to access only the genotype\r\n # first element of the list is the genotype when format is Genotype:Quality:ReadDepth:etc.\r\n geno = unparsed_geno.split(\":\")[0]\r\n\r\n # split the genotypes into individual alleles - split on \"/\" or \"|\"\r\n alleles = re.split(r\"/|\\|\", geno)\r\n\r\n # checks which delimiter was used. | = phased vs / = unphased\r\n phased = geno.find(\"|\") > -1 #phased is a boolean. true/false = phased/unphased\r\n\r\n return [alleles, phased]\r\n\r\ndef child_in_parent(childAlleles, parentAlleles):\r\n child_in_parent = []\r\n for idx, childAllele in enumerate(childAlleles):\r\n child_in_parent.insert(idx, childAllele in parentAlleles)\r\n\r\n return child_in_parent\r\n\r\nif __name__ == '__main__':\r\n\tmain()\r\n","sub_path":"find-quad-denovo.py","file_name":"find-quad-denovo.py","file_ext":"py","file_size_in_byte":5621,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"57123057","text":"from flask import Blueprint, render_template, url_for, request, redirect\nfrom backend.dbConnector import connectDB, executeQuery\n\ntrainRoute = Blueprint('trainRoute', __name__)\n\n@trainRoute.route('/trainers/')\ndef trainers():\n DBConnect = connectDB()\n\n #Select query for shelterFKs\n sFKQuery = \"SELECT shelter_id, shelter_name, address_city, address_state FROM shelters ORDER BY address_state;\"\n sFKResult = executeQuery(DBConnect, sFKQuery).fetchall()\n \n \n\n #Select all for list\n query = \"SELECT * FROM trainers ORDER BY last_name\"\n result = executeQuery(DBConnect, query).fetchall()\n return render_template('trainers.html', title='Trainers', allTrainers=result, sheltersData=sFKResult)\n\n\n@trainRoute.route('/trainers/', methods=[\"POST\"])\ndef addTrainer():\n DBConnect = connectDB()\n\n #data from addTrainerForm\n trainerFName = request.form['trainerFName']\n trainerLName = request.form['trainerLName']\n trainerSpecialty = request.form['trainerSpecialty']\n\n query = \"INSERT INTO `trainers` (`first_name`, `last_name`, `animal_specialty`) VALUES (%s, %s, %s)\"\n data = (trainerFName, trainerLName, trainerSpecialty)\n executeQuery(DBConnect, query, data)\n\n #data for shelterTrainer MM relationship\n trainerShelterID = request.form['trainerShelterID']\n\n if trainerShelterID != \" \":\n addNewTrainerShelterMM(trainerShelterID, trainerFName, trainerLName)\n return redirect('/trainers/')\n\n\n# Add new row into shelters_trainers MM table\ndef addNewTrainerShelterMM(shelterID, trainerFName, trainerLName):\n DBConnect = connectDB()\n\n #INSERT into shelters_trainers_MM\n query = \"INSERT INTO `shelters_trainers` (shelter_id, trainer_id) VALUES (%s, (SELECT trainer_id FROM trainers WHERE first_name = %s AND last_name = %s ORDER BY trainer_id DESC LIMIT 1))\"\n data = (shelterID, trainerFName, trainerLName)\n executeQuery(DBConnect, query, data)\n\n\n# Add new row into shelters_trainers MM table\ndef addNewTrainerShelterMM(shelterID, trainerFName, trainerLName):\n DBConnect = connectDB()\n\n #INSERT into shelters_trainers_MM\n query = \"INSERT INTO `shelters_trainers` (shelter_id, trainer_id) VALUES (%s, (SELECT trainer_id FROM trainers WHERE first_name = %s AND last_name = %s ORDER BY trainer_id DESC LIMIT 1))\"\n data = (shelterID, trainerFName, trainerLName)\n executeQuery(DBConnect, query, data)\n\n@trainRoute.route(\"/trainers/delete/\", methods=[\"POST\"])\ndef deleteTrainer(id):\n DBConnect = connectDB()\n data = (id,)\n query = \"DELETE FROM animals_trainers WHERE trainer_id = %s\"\n executeQuery(DBConnect, query, data)\n query = \"DELETE FROM shelters_trainers WHERE trainer_id = %s\"\n executeQuery(DBConnect, query, data)\n query = \"DELETE FROM trainers WHERE trainer_id = %s\"\n \n executeQuery(DBConnect, query, data)\n\n return redirect(\"/trainers/\")\n\n# Displays trainer info on Profile\n@trainRoute.route(\"/trainerProfile/\")\ndef trainerProfile(trainerId):\n DBConnect = connectDB() \n\n #Select trainer info\n trainerQuery = \"SELECT * FROM trainers WHERE trainer_id = %s\"\n tid = (trainerId,)\n trainerResult = executeQuery(DBConnect, trainerQuery, tid).fetchone()\n\n #Select query for animalsFK's\n animalsFKQuery = \"SELECT animal_id, name FROM animals ORDER BY name\"\n animalsFKResult = executeQuery(DBConnect, animalsFKQuery).fetchall()\n\n # Select trainer info for dropdown to input FK\n sheltersFKQuery = \"SELECT shelter_id, shelter_name, address_street, address_city, address_state, address_zip FROM shelters ORDER BY address_state;\"\n sheltersFKResult = executeQuery(DBConnect, sheltersFKQuery).fetchall()\n\n # trainers_shelters query\n TSMMquery = \"SELECT shelters_trainers.shelter_id, shelter_name, address_street, address_city, address_state, address_zip FROM `shelters_trainers` INNER JOIN `shelters` ON shelters_trainers.shelter_id = shelters.shelter_id WHERE trainer_id = %s ORDER BY address_state;\"\n TSMMresult = executeQuery(DBConnect, TSMMquery, tid).fetchall()\n\n # trainers_animals query\n TAMMquery = \"SELECT animals.animal_id, animals.name FROM animals_trainers INNER JOIN animals ON animals_trainers.animal_id = animals.animal_id WHERE animals_trainers.trainer_id = %s ORDER BY animals.name;\"\n TAMMquery = executeQuery(DBConnect, TAMMquery, tid).fetchall()\n\n return render_template('trainerProfile.html', title='Trainer Profile', animalsFKData=animalsFKResult, trainerAnimals=TAMMquery, trainer=trainerResult, sheltersFKData=sheltersFKResult, trainerShelters=TSMMresult)\n\n# remove from shelters_trainers\n@trainRoute.route(\"/trainers-shelters/delete/\", methods=[\"POST\"])\ndef deleteTrainersShelters(id):\n DBConnect = connectDB()\n\n trainerID = request.form['trainerID']\n\n query = \"DELETE FROM shelters_trainers WHERE shelter_id = %s AND trainer_id = %s\"\n data = (id, trainerID )\n executeQuery(DBConnect, query, data)\n\n redirectRoute = \"/trainerProfile/\" + trainerID\n return redirect(redirectRoute)\n\n@trainRoute.route(\"/trainers-animals/delete/\", methods=[\"POST\"])\ndef deleteTrainersAnimals(id):\n DBConnect = connectDB()\n\n trainerID = request.form['trainerID']\n\n query = \"DELETE FROM animals_trainers WHERE animal_id = %s AND trainer_id = %s\"\n data = (id, trainerID )\n executeQuery(DBConnect, query, data)\n\n redirectRoute = \"/trainerProfile/\" + trainerID\n return redirect(redirectRoute)\n\n@trainRoute.route(\"/animal-trainers/add\", methods=[\"POST\"])\ndef addTrainersAnimals():\n DBConnect = connectDB()\n\n trainerID = request.form['trainerID']\n animalID = request.form['animalID']\n\n query = \"INSERT INTO `animals_trainers`(`animal_id`, `trainer_id`) VALUES (%s, %s);\"\n data = (animalID, trainerID)\n executeQuery(DBConnect, query, data)\n return redirect('/trainerProfile/%s'%(trainerID))","sub_path":"app/trainerRoutes.py","file_name":"trainerRoutes.py","file_ext":"py","file_size_in_byte":5853,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"17154790","text":"class Node:\n def __init__(self,dataval=None):\n self.dataval = dataval\n self.nextval = None\n \n\nclass SLinkedList:\n def __init__(self):\n self.headval = None\n \n \n def Inbetween(self,middle_node,newdata):\n if middle_node is None:\n print(\"The mentioned node is absent\")\n return\n\n NewNode = Node(newdata)\n NewNode.nextval = middle_node.nextval\n middle_node.nextval = NewNode\n \n def listprint(self):\n printval = self.headval\n \n while printval is not None:\n print(printval.dataval)\n printval = printval.nextval\n \n\nlist1 = SLinkedList()\nlist1.headval = Node('Man')\ne2 = Node('Tue')\ne3 = Node('Thur')\n\nlist1.headval.nextval = e2\ne2.nextval = e3\nlist1.Inbetween(list1.headval.nextval,\"Fri\")\nlist1.listprint()\n\n\n\n ","sub_path":"linke_list_linsertion_between/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":866,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"533305325","text":"import requests\nimport json\nimport os\n\naccessToken = os.environ['ACCESS_TOKEN']\nadminId = os.environ['ADMIN_ID']\n\n\n\ndef sendNote(convId, message):\n url = \"https://api.intercom.io/conversations/\" + convId + \"/reply\"\n bearer = \"Bearer \" + accessToken\n headers = {\n \"Authorization\": bearer,\n \"Content-type\": \"application/json\",\n \"Accept\": \"application/json\"\n }\n payload = {\n \"body\": message ,\n \"type\": \"admin\",\n \"admin_id\": adminId,\n \"message_type\": \"note\"\n }\n r = requests.post(url, data=json.dumps(payload), headers=headers)\n respObj = r.json()\n print (\"Send Note Responce: \")\n print (respObj)\n print (\"==========================================================================\")\n\ndef sendMessage(convId, message):\n url = \"https://api.intercom.io/conversations/\" + convId + \"/reply\"\n bearer = \"Bearer \" + accessToken\n headers = {\n \"Authorization\": bearer,\n \"Content-type\": \"application/json\",\n \"Accept\": \"application/json\"\n }\n payload = {\n \"body\": message ,\n \"type\": \"admin\",\n \"admin_id\": adminId,\n \"message_type\": \"open\"\n }\n r = requests.post(url, data=json.dumps(payload), headers=headers)\n respObj = r.json()\n print (\"Send Message Responce: \")\n print (respObj)\n print (\"==========================================================================\")\n\n\ndef buildNote(message, lang, translation):\n response = \"Original Message: \"+message+ \"\\nLanguage Code: \"+lang+\"\\nTranslation: \" + translation + \"\\n\\n To start translate mode, make an internal note saying '/translate language_code '\\nExample: /translate fr\"\n return response\n","sub_path":"microservices/bot/app/src/intercom.py","file_name":"intercom.py","file_ext":"py","file_size_in_byte":1695,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"238184878","text":"from django.db.models import Max\nfrom app.models import *\nfrom app.utils.logUtils import *\n\n\n# 关于团队管理的工具集\n# by kahsolt\n\n\n# 发起组队\ndef createTeam(user, name):\n if not isinstance(user, User):\n return None\n if user.role != 'student':\n log('不是学生', 'teamutils', LOG_LEVEL.ERROR)\n return False\n if Member.objects.filter(user=user).count() > 0:\n log('已经是队长或成员', 'teamutils', LOG_LEVEL.ERROR)\n return False\n\n team = Team()\n team.course = Enroll.objects.get(user=user).course\n team.name = name\n team.status = 'incomplete'\n team.save()\n member = Member()\n member.user = user\n member.team = team\n member.role = 'leader'\n member.save()\n return team, member\n\n\n# 解散团队\ndef dismissTeam(team):\n if not isinstance(team, Team):\n return None\n if team.status == 'passed':\n log('团队已通过审核', 'teamutils', LOG_LEVEL.ERROR)\n return False\n\n members = Member.objects.filter(team=team)\n for member in members:\n member.delete()\n team.delete()\n return True\n\n\n# 加入团队\ndef joinTeam(user, team):\n if not isinstance(team, Team) or not isinstance(user, User):\n return None\n if team.status != 'incomplete' or user.role != 'student':\n log('团队已冻结/不是学生', 'teamutils', LOG_LEVEL.ERROR)\n return False\n if Member.objects.filter(user=user).count() > 0:\n log('已经是队长或成员', 'teamutils', LOG_LEVEL.ERROR)\n return False\n\n member = Member()\n member.user = user\n member.team = team\n member.role = 'member'\n member.save()\n return member\n\n\n# 离开团队\ndef leaveTeam(user):\n if not isinstance(user, User):\n return None\n member = Member.objects.filter(user=user)\n if not member:\n log('未加入任何团队', 'teamutils', LOG_LEVEL.ERROR)\n return False\n\n member.delete()\n return True\n\n\n# 转让组长\ndef transferLeadership(team, user):\n if not isinstance(team, Team) or not isinstance(user, User):\n return None\n if user.role != 'student':\n log('不是学生', 'teamutils', LOG_LEVEL.ERROR)\n return False\n\n Member.user.objects.filter(team=team, role='leader').update(role='member')\n Member.user.objects.filter(team=team, user=user).update(role='leader')\n return True\n\n\n# 维护团队信息\ndef updateInfo(team, **kwargs):\n if not isinstance(team, Team):\n return None\n\n if kwargs.get('name') is not None:\n team.name = kwargs.get('name')\n team.save()\n if kwargs.get('info') is not None:\n team.info = kwargs.get('info')\n team.save()\n return team\n\n\n# 完成组队:冻结join\ndef completeTeam(team):\n if not isinstance(team, Team):\n return None\n\n team.status = 'unsubmitted'\n team.save()\n return team\n\n\n# 提交组队申请\ndef submitTeam(team):\n if not isinstance(team, Team):\n return None\n if team.status != 'unsubmitted':\n log('未审核且已冻结的团队才能提交申请', 'teamutils', LOG_LEVEL.ERROR)\n return False\n num = Member.objects.filter(team=team).count()\n if num < team.course.teamMeta.minNum or num > team.course.teamMeta.maxNum:\n log('不在人数限制范围', 'teamutils', LOG_LEVEL.ERROR)\n return False\n num = Member.user.objects.filter(gender='female')\n if num != 1:\n log('性别要求不合', 'teamutils', LOG_LEVEL.ERROR)\n return False\n\n team.status = 'auditing'\n team.save()\n return team\n\n\n# 审核团队:通过\ndef auditTeamPassed(team):\n if not isinstance(team, Team):\n return None\n if team.status != 'auditing':\n log('未提交申请', 'teamutils', LOG_LEVEL.ERROR)\n return False\n\n id = 1\n if Team.objects.filter(course=team.course).count() > 0:\n id = Team.objects.filter(course=team.course).aggregate(Max('serialNum')) + 1\n team.status = 'passed'\n team.serialNum = id\n team.save()\n return team\n\n\n# 审核团队:拒绝\ndef auditTeamRejected(team, info):\n if not isinstance(team, Team):\n return None\n if team.status != 'auditing':\n log('未提交申请', 'teamutils', LOG_LEVEL.ERROR)\n return False\n\n team.status = 'rejected'\n team.info = info\n team.save()\n return team\n\n\n# 设置队员贡献值\ndef setContribution(user, contribution):\n def validateContribution(c):\n # Method 1:\n return c >= 0.4 and c <= 1.6\n # Method 2:\n # C = [0.4, 0.6, 0.8, 1.0, 1.2]\n # return c in C\n\n if not isinstance(user, User):\n return None\n if not validateContribution(contribution):\n log('设定的个人贡献比例不在值范围', 'teamutils', LOG_LEVEL.ERROR)\n return False\n\n enroll = Enroll.objects.filter(user=user).first()\n team = Team.objects.filter(course=enroll.course).first()\n members = Member.objects.filter(team=team)\n maxContrib = members.count()\n curContrib = 0\n curContrib += contribution\n if curContrib > maxContrib:\n log('团队总贡献度超额', 'teamutils', LOG_LEVEL.ERROR)\n return False\n\n Member.objects.filter(user=user).update(contribution=contribution)\n log('setContribution OK', 'teamutils', LOG_LEVEL.INFO)\n return curContrib + contribution\n","sub_path":"app/utils/teamUtils.py","file_name":"teamUtils.py","file_ext":"py","file_size_in_byte":5340,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"164044038","text":"from twython import Twython\nfrom twython import TwythonRateLimitError\nfrom langdetect import detect\nfrom langdetect.detector import LangDetectException\nfrom time import sleep\nfrom twython import Twython\nfrom twython import TwythonAuthError\nfrom twython import TwythonRateLimitError\nfrom twython import TwythonError\nfrom warnings import warn\nfrom datetime import datetime\n\n\ndef getTweets(screen_name=None, user_id=None, num = 0, include_rts = False):\n\tconsumer_key = \"MLGdNZCfmzGthHTAyJU4KFvbU\"\n\tconsumer_secret =\"Tfp7DIZcJLbnS8BR5CWQmZklrhsbtc3fMfssKPT4SZoYsPiQKw\"\n\taccess_token =\"2383540880-s2C8xPgA4ITF7QnLRFnHK1es2UEbmW8qHQ87sX5\"\n\taccess_token_secret =\"kLYgBTPeslLgaFugCx0PoiBpPIKnyCBEVfqqJCkjsSKpP\"\n\ttwitter = Twython(consumer_key, consumer_secret,access_token,access_token_secret )\n\n\ttweets = None\n\twhile(tweets == None):\n\t\ttry:\n\t\t\tif screen_name == None:\n\t\t\t\ttweets = twitter.get_user_timeline(user_id = user_id, count = 200, trim_user = False, include_rts = include_rts )\n\t\t\telse:\n\t\t\t\ttweets = twitter.get_user_timeline(screen_name = screen_name, count = 200, trim_user = False, include_rts = include_rts )\n\t\texcept TwythonRateLimitError:\n\t\t\twarn(\"Fall asleep\")\n\t\t\tsleep(300)\n\t\t\tpass\n\t\texcept TwythonAuthError:\n\t\t\twarn(\"Bad Authentication\")\n\t\t\treturn []\n\t\texcept TwythonError:\n\t\t\twarn(\"404 not found\")\n\t\t\treturn []\n\n\ttotalTweets = tweets\n\twhile len(tweets) >= 2:\n\t\tmax_id = tweets[-1][\"id\"]\n\t\ttry:\n\t\t\tif screen_name == None:\n\t\t\t\ttweets = twitter.get_user_timeline(user_id = user_id, max_id = max_id, count = 200, trim_user = False, include_rts = include_rts )\n\t\t\telse:\n\t\t\t\ttweets = twitter.get_user_timeline(screen_name = screen_name, max_id = max_id, count = 200, trim_user = False, include_rts = include_rts )\n\n\t\texcept TwythonRateLimitError:\n\t\t\tprint(\"Fall asleep\")\n\t\t\tsleep(300)\n\t\t\tcontinue\n\n\t\tif len(tweets) > 1:\n\t\t\ttotalTweets += tweets[1:]\n\t\telif num > 0 and len(tweets) >= num :\n\t\t\tbreak\n\t\t\n\n\tfor i in range(len(totalTweets)):\n\t\tdate = totalTweets[i][\"created_at\"]\n\t\ttotalTweets[i][\"created_at\"] = datetime.strptime(date, '%a %b %d %H:%M:%S +0000 %Y')\n\t\n\tif num == 0:\n\t\treturn totalTweets\n\telse:\n\t\treturn totalTweets[:num]\n\n\n\ndef langDetect(tweets ,lang, threshold, method = \"simple\"):\n\tif len(tweets) == 0:\n\t\treturn False\n\tlangCount = 0\n\tif method == \"simple\":\n\t\tfor tweet in tweets:\n\t\t\ttry:\n\t\t\t\tif lang == tweet[\"lang\"]:\n\t\t\t\t\tlangCount += 1\n\t\t\texcept LangDetectException:\n\t\t\t\tpass\n\telse:\n\t\tfor tweet in tweets:\n\t\t\ttry:\n\t\t\t\tif lang == detect(tweet[\"text\"]):\n\t\t\t\t\tlangCount += 1\n\t\t\texcept LangDetectException:\n\t\t\t\tpass\n\tlangRatio = langCount / len(tweets)\n\tprint(langRatio)\n\n\n\treturn langRatio > threshold\n\n\n\ndef userLangDetect(screen_name=None, user_id=None, lang=\"en\", threshold=0.9, num = 200):\n\tif screen_name == None:\n\t\ttweets = getTweets(screen_name=None,user_id=user_id)\n\telse:\n\t\ttweets = getTweets(screen_name)\n\treturn langDetect(tweets,lang,threshold)\n\n\ndef getFollowers(screen_name):\n\tconsumer_key = \"MLGdNZCfmzGthHTAyJU4KFvbU\"\n\tconsumer_secret =\"Tfp7DIZcJLbnS8BR5CWQmZklrhsbtc3fMfssKPT4SZoYsPiQKw\"\n\taccess_token =\"2383540880-s2C8xPgA4ITF7QnLRFnHK1es2UEbmW8qHQ87sX5\"\n\taccess_token_secret =\"kLYgBTPeslLgaFugCx0PoiBpPIKnyCBEVfqqJCkjsSKpP\"\n\ttwitter = Twython(consumer_key, consumer_secret,access_token,access_token_secret )\n\n\n\twhile(True):\n\t\ttry:\n\t\t\tfollowers = twitter.get_followers_ids(screen_name = screen_name)\t\n\t\t\tfollowers_id = followers['ids']\n\t\t\treturn followers_id\t\t\n\t\texcept TwythonRateLimitError:\n\t\t\tprint(\"Fall asleep\")\n\t\t\tsleep(300)\n\t\t\tpass\n\t\texcept wythonError:\n\t\t\tprint(\"404 not found\")\n\t\t\treturn []\n\t\texcept TwythonAuthError:\n\t\t\tprint(\"Bad Authentication\")\n\t\t\treturn []\n\n\ndef getUserProfile(user_id=None, screen_name=None):\n\n\tif user_id is None and screen_name is None:\n\t\treturn None\n\n\tconsumer_key = \"MLGdNZCfmzGthHTAyJU4KFvbU\"\n\tconsumer_secret =\"Tfp7DIZcJLbnS8BR5CWQmZklrhsbtc3fMfssKPT4SZoYsPiQKw\"\n\taccess_token =\"2383540880-s2C8xPgA4ITF7QnLRFnHK1es2UEbmW8qHQ87sX5\"\n\taccess_token_secret =\"kLYgBTPeslLgaFugCx0PoiBpPIKnyCBEVfqqJCkjsSKpP\"\n\ttwitter = Twython(consumer_key, consumer_secret,access_token,access_token_secret)\n\n\tif screen_name:\n\t\twhile(True):\n\t\t\ttry:\n\t\t\t\tuser_profile = twitter.show_user(screen_name=screen_name)\n\t\t\t\treturn user_profile\n\t\t\texcept TwythonRateLimitError:\n\t\t\t\tprint(\"Fall asleep\")\n\t\t\t\tsleep(300)\n\t\t\t\tpass\n\t\t\texcept TwythonAuthError:\n\t\t\t\tprint(\"Bad Authentication\")\n\t\t\t\treturn []\n\t\t\texcept TwythonError:\n\t\t\t\tprint(\"404 not found\")\n\t\t\t\treturn []\n\telse:\n\t\twhile(True):\n\t\t\ttry:\n\t\t\t\tuser_profile = twitter.show_user(id = user_id)\n\t\t\t\treturn user_profile\n\t\t\texcept TwythonRateLimitError:\n\t\t\t\tprint(\"Fall asleep\")\n\t\t\t\tsleep(300)\n\t\t\t\tpass\n\t\t\texcept TwythonAuthError:\n\t\t\t\tprint(\"Bad Authentication\")\n\t\t\t\treturn []\n\t\t\texcept TwythonError:\n\t\t\t\tprint(\"404 not found\")\n\t\t\t\treturn []\n\t\t\n\nif __name__ == '__main__':\n\t#print(getTweets(screen_name=\"BigDataBlogs\", num =10))\n\tprint(getUserProfile(screen_name=\"omarsar0\"))\n\t\n","sub_path":"5_interface/idCrawler.py","file_name":"idCrawler.py","file_ext":"py","file_size_in_byte":4875,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"462687365","text":"# coding=utf-8\n\nfrom unityagents import UnityEnvironment\nimport numpy as np\n\nenv = UnityEnvironment(file_name=\"./Soccer_Windows_x86_64/Soccer.exe\")\n\n\n# print the brain names\nprint(env.brain_names)\n\n# set the goalie brain\ng_brain_name = env.brain_names[0]\ng_brain = env.brains[g_brain_name]\n\n# set the striker brain\ns_brain_name = env.brain_names[1]\ns_brain = env.brains[s_brain_name]\n\n# reset the environment\nenv_info = env.reset(train_mode=True)\n\n# number of agents\nnum_g_agents = len(env_info[g_brain_name].agents)\nprint('Number of goalie agents:', num_g_agents)\nnum_s_agents = len(env_info[s_brain_name].agents)\nprint('Number of striker agents:', num_s_agents)\n\n# number of actions\ng_action_size = g_brain.vector_action_space_size\nprint('Number of goalie actions:', g_action_size)\ns_action_size = s_brain.vector_action_space_size\nprint('Number of striker actions:', s_action_size)\n\n# examine the state space\ng_states = env_info[g_brain_name].vector_observations\ng_state_size = g_states.shape[1]\nprint('There are {} goalie agents. Each receives a state with length: {}'.format(g_states.shape[0], g_state_size))\ns_states = env_info[s_brain_name].vector_observations\ns_state_size = s_states.shape[1]\nprint('There are {} striker agents. Each receives a state with length: {}'.format(s_states.shape[0], s_state_size))\n\nfor i in range(2): # play game for 2 episodes\n env_info = env.reset(train_mode=False) # reset the environment\n g_states = env_info[g_brain_name].vector_observations # get initial state (goalies)\n s_states = env_info[s_brain_name].vector_observations # get initial state (strikers)\n g_scores = np.zeros(num_g_agents) # initialize the score (goalies)\n s_scores = np.zeros(num_s_agents) # initialize the score (strikers)\n while True:\n # select actions and send to environment\n g_actions = np.random.randint(g_action_size, size=num_g_agents)\n s_actions = np.random.randint(s_action_size, size=num_s_agents)\n actions = dict(zip([g_brain_name, s_brain_name],\n [g_actions, s_actions]))\n env_info = env.step(actions)\n\n # get next states\n g_next_states = env_info[g_brain_name].vector_observations\n s_next_states = env_info[s_brain_name].vector_observations\n\n # get reward and update scores\n g_rewards = env_info[g_brain_name].rewards\n s_rewards = env_info[s_brain_name].rewards\n g_scores += g_rewards\n s_scores += s_rewards\n\n # check if episode finished\n done = np.any(env_info[g_brain_name].local_done)\n\n # roll over states to next time step\n g_states = g_next_states\n s_states = s_next_states\n\n # exit loop if episode finished\n if done:\n break\n print('Scores from episode {}: {} (goalies), {} (strikers)'.format(i + 1, g_scores, s_scores))\n\nenv.close()\n\n","sub_path":"p3_collab-compet/ckj_soccer.py","file_name":"ckj_soccer.py","file_ext":"py","file_size_in_byte":2869,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"452066392","text":"# coding:utf-8\n'''\n@Copyright:LintCode\n@Author: monolake\n@Problem: http://www.lintcode.com/problem/search-a-2d-matrix-ii\n@Language: Python\n@Datetime: 16-10-26 01:05\n'''\n\nclass Solution:\n \"\"\"\n @param matrix: An list of lists of integers\n @param target: An integer you want to search in matrix\n @return: An integer indicates the total occurrence of target in the given matrix\n \"\"\"\n def searchMatrix(self, matrix, target):\n # write your code here\n if len(matrix) == 0:\n return 0\n m = len(matrix)\n n = len(matrix[0])\n x = m - 1\n y = 0\n count = 0\n while x >= 0 and y <= n - 1:\n if target == matrix[x][y]:\n count += 1\n x -= 1\n y += 1\n elif target < matrix[x][y]:\n x -= 1\n else:\n y += 1\n return count\n \n \n ","sub_path":"38_search-a-2d-matrix-ii/search-a-2d-matrix-ii.py","file_name":"search-a-2d-matrix-ii.py","file_ext":"py","file_size_in_byte":932,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"237540862","text":"# 페르마의 크리스마스 정리\n# 구현 아이디어 : 에라토스테네스의 체, 소수 % 4 == 1 개수\n\nimport sys\nfrom bisect import bisect_left as bl, bisect_right as br\ninput = sys.stdin.readline\n\ndef primeNum():\n pNum = list(range(1000000))\n pNum[0], pNum[1] = 0, 0\n for i in range(int(1000000 ** 0.5 + 1)):\n if not pNum[i]:\n continue\n for j in range(i + i, 1000000, i):\n pNum[j] = 0\n pNum = list(filter(None, pNum))\n return pNum\n\ndef solution(pN):\n s = \"\"\n while 1:\n cnt1, cnt2 = 0, 0\n l, u = map(int, input().split())\n if l == u == -1: \n break\n ans = pN[bl(pN, l) : br(pN, u)]\n cnt1 = len(ans)\n for i in ans:\n if i % 4 == 1:\n cnt2 += 1\n if l <= 2 and u >= 2: \n cnt2 += 1\n # print(l, u, cnt1, cnt2)\n s += str(l) + \" \" + str(u) + \" \" + str(cnt1) + \" \" + str(cnt2) + \"\\n\"\npN = primeNum()\nsolution(pN)","sub_path":"November,2020~July,2021/2020-12-25/4913_이승민_페르마의크리스마스정리.py","file_name":"4913_이승민_페르마의크리스마스정리.py","file_ext":"py","file_size_in_byte":983,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"175182608","text":"'''\nCreated on Aug 26, 2014\n\n@author: huhe\n'''\n\nfrom main.define import Define\nfrom lib.util import Util\nfrom lib.ucsm import UCSM\n\n\nif __name__ == '__main__':\n \n '''\n eth0: pxe vlan10\n eth1: medusa vlan2000\n '''\n vlan_id_list = range(122, 128)\n vlan_id_list.append(113)\n vlan_id_list.append(2000)\n \n ucsm = UCSM(Define.UCSM_HOSTNAME);\n file_text_step = Define.PATH_SNIC_TEXT_UCSM + \"vlan.txt\" \n \n for vlan_id in vlan_id_list: \n param = {\"tag_vlan_name\": \"vlan\"+str(vlan_id), \"tag_vlan_id\": str(vlan_id)}\n Util.run_text_step(ucsm.get_ssh(), file_text_step, param)\n \n ucsm.exit()\n \n\n \n \n ","sub_path":"nj-sinc-2/src/cmd/ucsm/system/vlan.py","file_name":"vlan.py","file_ext":"py","file_size_in_byte":670,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"22165839","text":"# coding=utf-8\n# --------------------------------------------------------------------------\n# Copyright (c) Microsoft Corporation. All rights reserved.\n# Licensed under the MIT License. See License.txt in the project root for license information.\n# Code generated by Microsoft (R) AutoRest Code Generator.\n# Changes may cause incorrect behavior and will be lost if the code is regenerated.\n# --------------------------------------------------------------------------\n\nfrom azure.identity import DefaultAzureCredential\nfrom azure.mgmt.hdinsightcontainers import HDInsightContainersMgmtClient\n\n\"\"\"\n# PREREQUISITES\n pip install azure-identity\n pip install azure-mgmt-hdinsightcontainers\n# USAGE\n python patch_cluster.py\n\n Before run the sample, please set the values of the client ID, tenant ID and client secret\n of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID,\n AZURE_CLIENT_SECRET. For more info about how to get the value, please see:\n https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal\n\"\"\"\n\n\ndef main():\n client = HDInsightContainersMgmtClient(\n credential=DefaultAzureCredential(),\n subscription_id=\"10e32bab-26da-4cc4-a441-52b318f824e6\",\n )\n\n response = client.clusters.begin_update(\n resource_group_name=\"hiloResourcegroup\",\n cluster_pool_name=\"clusterpool1\",\n cluster_name=\"cluster1\",\n cluster_patch_request={\n \"location\": \"West US 2\",\n \"properties\": {\n \"clusterProfile\": {\n \"authorizationProfile\": {\"userIds\": [\"Testuser1\", \"Testuser2\"]},\n \"autoscaleProfile\": {\n \"autoscaleType\": \"ScheduleBased\",\n \"enabled\": True,\n \"gracefulDecommissionTimeout\": -1,\n \"scheduleBasedConfig\": {\n \"defaultCount\": 3,\n \"schedules\": [\n {\n \"count\": 3,\n \"days\": [\"Monday, Tuesday, Wednesday\"],\n \"endTime\": \"12:00\",\n \"startTime\": \"00:00\",\n },\n {\"count\": 3, \"days\": [\"Sunday\"], \"endTime\": \"12:00\", \"startTime\": \"00:00\"},\n ],\n \"timeZone\": \"Cen. Australia Standard Time\",\n },\n },\n \"logAnalyticsProfile\": {\n \"applicationLogs\": {\"stdErrorEnabled\": True, \"stdOutEnabled\": True},\n \"enabled\": True,\n \"metricsEnabled\": True,\n },\n \"serviceConfigsProfiles\": [\n {\n \"configs\": [\n {\n \"component\": \"TestComp1\",\n \"files\": [\n {\n \"fileName\": \"TestFile1\",\n \"values\": {\"Test.config.1\": \"1\", \"Test.config.2\": \"2\"},\n },\n {\n \"fileName\": \"TestFile2\",\n \"values\": {\"Test.config.3\": \"3\", \"Test.config.4\": \"4\"},\n },\n ],\n },\n {\n \"component\": \"TestComp2\",\n \"files\": [\n {\"content\": \"TestContent\", \"fileName\": \"TestFile3\", \"path\": \"TestPath\"},\n {\n \"fileName\": \"TestFile4\",\n \"values\": {\"Test.config.7\": \"7\", \"Test.config.8\": \"8\"},\n },\n ],\n },\n ],\n \"serviceName\": \"TestService1\",\n },\n {\n \"configs\": [\n {\n \"component\": \"TestComp3\",\n \"files\": [{\"fileName\": \"TestFile5\", \"values\": {\"Test.config.9\": \"9\"}}],\n }\n ],\n \"serviceName\": \"TestService2\",\n },\n ],\n \"sshProfile\": {\"count\": 2},\n }\n },\n },\n ).result()\n print(response)\n\n\n# x-ms-original-file: specification/hdinsight/resource-manager/Microsoft.HDInsight/HDInsightOnAks/preview/2023-06-01-preview/examples/PatchCluster.json\nif __name__ == \"__main__\":\n main()\n","sub_path":"sdk/hdinsight/azure-mgmt-hdinsightcontainers/generated_samples/patch_cluster.py","file_name":"patch_cluster.py","file_ext":"py","file_size_in_byte":5115,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"452510244","text":"'''\nhttps://leetcode.com/problems/sort-array-by-parity/submissions/\nRuntime: 92ms\nMemory: 14.4 MB\nYour runtime beats 83.54 % of python3 submissions.\nYour memory beats 5.19 % of python3 submissions.\n'''\nclass Solution:\n def sortArrayByParity(self, A: List[int]) -> List[int]:\n e = [] ; o = []\n for x in A:\n if not x % 2:\n e.append(x)\n else:\n o.append(x)\n for x in o:\n e.append(x)\n return e\n","sub_path":"easy/array_by_parity.py","file_name":"array_by_parity.py","file_ext":"py","file_size_in_byte":483,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"135372807","text":"import matplotlib.pyplot as plt\nimport numpy as np\nimport pandas as pd\n\nLD_ONES_CENTER = (-2.0, -2.0)\nRU_ONES_CENTER = (2.0, 2.0)\n\nLU_ZEROS_CENTER = (-2.0, 2.0)\nRD_ZEROS_CENTER = (2.0, -2.0)\n\nVAR = 1.0\n\nLEARNING_RATE = 0.01\nLR = LEARNING_RATE\n\nSAMPLE_SIZE = 100\n\n\ndef draw_sample(sample_size=SAMPLE_SIZE):\n def draw(mean, covar, ssize):\n return np.random.multivariate_normal(mean, covar, sample_size)\n \n cov = np.array([\n [VAR, 0.0],\n [0.0, VAR]\n ])\n\n x = np.vstack([\n draw(LD_ONES_CENTER, cov, sample_size),\n draw(RU_ONES_CENTER, cov, sample_size),\n draw(LU_ZEROS_CENTER, cov, sample_size),\n draw(RD_ZEROS_CENTER, cov, sample_size)\n ])\n y = np.append(np.ones(2 * sample_size), np.zeros(2 * sample_size))\n\n return x, y\n\n\ndef sigmoid(x):\n return 1 / (1 + np.exp(-x))\n\ndef relu(x):\n x[x < 0] = 0\n return x\n\ndef draw_params(size):\n return np.random.normal(0.0, 0.1, size)\n\n\ndef plot_classifier_gradient(big_x, big_y, W_1, W_2, b_1, b_2):\n from_x, to_x = -7.0, 7.0\n res = 100\n\n fake_x = np.array([[x, y]\n for y in -np.linspace(from_x, to_x, res)\n for x in np.linspace(from_x, to_x, res)])\n\n a = np.dot(fake_x, W_1.T) + b_1.T\n y_1 = relu(a)\n fake_y = sigmoid(np.dot(y_1, W_2.T) + b_2.T)\n\n # That's our classification function\n img = fake_y.reshape((res, res))\n\n # make the actual plot\n ones = big_x[big_y == 1]\n zeros = big_x[big_y == 0]\n plt.scatter(ones[:, 0], ones[:, 1], c='b', marker='o')\n plt.scatter(zeros[:, 0], zeros[:, 1], c='r', marker='x')\n\n plt.xlim([-7, 7])\n plt.ylim([-7, 7])\n\n plotlim = plt.xlim() + plt.ylim()\n plt.imshow(img, cmap=plt.cm.coolwarm_r,\n interpolation='bicubic', alpha=1, extent=plotlim)\n plt.title('Sample classification - one layer neural net')\n plt.savefig('img/one-layer-two-class-nn.png')\n plt.close()\n\n\ndef main():\n W_1 = draw_params((4, 2))\n b_1 = draw_params((4, 1))\n W_2 = draw_params((1, 4))\n b_2 = draw_params((1, 1))\n\n i = 0\n\n err_acc = []\n\n for i in range(5000):\n x, y = draw_sample()\n\n # forward pass\n a = np.dot(x, W_1.T) + b_1.T\n y_1 = relu(a)\n y_hat = sigmoid(np.dot(y_1, W_2.T) + b_2.T)\n\n err = y_hat[:, 0] - y\n\n pred = (y_hat > 0.5).astype(float)[:, 0]\n err_rate = ((y - pred)** 2).mean()\n err_acc.append(err_rate)\n\n # backward pass\n dW_2 = np.dot(err[:, np.newaxis].T, y_1) / y_1.shape[0]\n db_2 = err.mean()\n\n dy_1 = np.dot(err[:, np.newaxis], W_2)\n da = dy_1 * (a > 0).astype(float)\n\n dW_1 = np.dot(da.T, x) / x.shape[0]\n db_1 = da.mean()\n\n W_1 -= LR * dW_1\n b_1 -= LR * db_1\n\n W_2 -= LR * dW_2\n b_2 -= LR * db_2\n\n plot_classifier_gradient(x, y, W_1, W_2, b_1, b_2)\n\n pd.Series(err_acc).plot()\n plt.savefig('img/one-layer-two-class-nn-error.png')\n plt.close()\n\n\nif __name__ == '__main__':\n main()\n\n","sub_path":"one-layer-two-class-nn.py","file_name":"one-layer-two-class-nn.py","file_ext":"py","file_size_in_byte":3021,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"419936717","text":"import base64\nimport zlib\nimport urllib.parse as uparse\nimport re\n\n\nf=open('input.xml')\ndata=f.read()\ndata=re.search('\\(.+)\\<\\/diagram\\>',data).group(1)\n# print(data)\ndata=base64.b64decode(data)\ndata=zlib.decompress(data,-15);\ndata=uparse.unquote(str(data))\ndata=data.replace('&amp;','&')\nstates={};\nfor c,i in enumerate(re.finditer(\"\\\",data)):\n print(\"Match {0}:\".format(c))\n \n states[i.group(0)]={\n 'name':re.split('\\[|\\]',i.group(1))\n \n };\n for j in i.groups():\n print(j);\n \n ","sub_path":"deprecated/demo-misc/smacherplusplus.py","file_name":"smacherplusplus.py","file_ext":"py","file_size_in_byte":635,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"554763322","text":"import gdal\nimport numpy as np\nimport numpy.ma as ma\nimport sys\nsys.path.insert(0,'python')\nfrom readSent import *\nimport kernels\nfrom geo_trans import *\nfrom scipy.interpolate import griddata\nfrom fast_rw import *\n\n\nmodis_filenames = gdal.Open('m_data/MCD43A1.A2016105.h27v05.005.2016122100738.hdf').GetSubDatasets()\nmodisQA = gdal.Open(\"m_data/MCD43A2.A2016105.h27v05.005.2016122100739.hdf\").GetSubDatasets()\nh=27\nv=5\nfhead = 'data/50SMG20164100'\n\ndef get_coords(h,v):\n mgrss = get_lon_lat(27, 5).ravel()\n\n mgrss = np.array([(i[:5],i[-8:-4],i[-4:]) for i in mgrss]).reshape(2400,2400,3)\n\n index = np.where(mgrss[:,:,0]=='50SMG')\n Scoords = [9999-mgrss[index[0], index[1],2].astype('int'), mgrss[index[0], index[1],1].astype('int')]\n return index, Scoords\n\ndef r_modis(fname):\n g = gdal.Open(fname)\n if g is None:\n raise IOError\n else:\n return g.ReadAsArray()\n\n\ndef ScaleExtent(data, shape): # used for unifine different array,\n\n re = int(shape[0]/(data.shape[0]))\n\n a = np.repeat(np.repeat(data, re, axis = 1), re, axis =0)\n \n if re*(data.shape[0]-shape[0]) != 0:\n extended = np.zeros(shape)\n extended[:re*(data.shape[0]),:re*(data.shape[0])] = a\n extended[re*(data.shape[0]):,re*(data.shape[0]):] = a[re*(data.shape[0])-shape[0]:, re*(data.shape[0])-shape[0]]\n return extended\n else:\n return a\n#bands = [2,3,4,8,13,11,12]\n\n\ndef get_kk(fhead):\n mete = readxml('%smetadata.xml'%fhead)\n vZa = np.array([i+ np.zeros((23,23)) for i in mete['mVz']])\n vAa = np.array([i+ np.zeros((23,23)) for i in mete['mVa']])\n\n ks = []\n for i in [2,3,4,8,11,12]:\n if i ==8:\n i -= 1\n kk = kernels.Kernels(vZa[i] ,mete['SAG_Z'],mete['SAG_A']-vAa[i],\\\n RossHS=False,MODISSPARSE=True,\\\n RecipFlag=True,normalise=1,\\\n doIntegrals=False,LiType='Dense',RossType='Thick')\n ks.append(kk)\n kk = kernels.Kernels(vZa[i+1] ,mete['SAG_Z'],mete['SAG_A']-vAa[i+1],\\\n RossHS=False,MODISSPARSE=True,\\\n RecipFlag=True,normalise=1,\\\n doIntegrals=False,LiType='Dense',RossType='Thick')\n ks.append(kk)\n\n else:\n i -= 1\n kk = kernels.Kernels(vZa[i] ,mete['SAG_Z'],mete['SAG_A']-vAa[i],\\\n RossHS=False,MODISSPARSE=True,\\\n RecipFlag=True,normalise=1,\\\n doIntegrals=False,LiType='Dense',RossType='Thick')\n ks.append(kk)\n return ks\n\n\n\ndef get_rs(modisQA, modis_filenames, fhead):\n \n ks = get_kk(fhead)\n \n brdfs = []\n brdfms = []\n\n QA = r_modis(modisQA[0][0])\n\n for i in [2,3,0,1,5,6]:\n br = r_modis(modis_filenames[i][0])\n brdfs.append(br)\n brdfms.append((br[0] > 32766) | (br[1] > 32766) |(br[2] > 32766)| (QA>1))\n\n\n Rs = []\n for i,j in enumerate(brdfs):\n if i == 3:\n kk = ks[i]\n ross = kk.Ross\n li = kk.Li\n iso = kk.Isotropic\n k_vol = ScaleExtent(ross, (2400, 2400)); k_geo = ScaleExtent(li, (2400,2400))\n Rs.append(j[0] + j[1]*k_vol + j[2]*k_geo)\n\n kk = ks[i+1]\n ross = kk.Ross\n li = kk.Li\n iso = kk.Isotropic\n k_vol = ScaleExtent(ross, (2400, 2400)); k_geo = ScaleExtent(li, (2400,2400))\n Rs.append(j[0] + j[1]*k_vol + j[2]*k_geo)\n elif i>3:\n i +=1\n kk = ks[i]\n ross = kk.Ross\n li = kk.Li\n iso = kk.Isotropic\n k_vol = ScaleExtent(ross, (2400, 2400)); k_geo = ScaleExtent(li, (2400,2400))\n Rs.append(j[0] + j[1]*k_vol + j[2]*k_geo)\n else:\n kk = ks[i]\n ross = kk.Ross\n li = kk.Li\n iso = kk.Isotropic\n k_vol = ScaleExtent(ross, (2400, 2400)); k_geo = ScaleExtent(li, (2400,2400))\n Rs.append(j[0] + j[1]*k_vol + j[2]*k_geo)\n return Rs, brdfms\n\ndef inter_modis(modisQA, modis_filenames, fhead, h, v):\n \n Rs, brdfms = get_rs(modisQA, modis_filenames, fhead)\n\n grid_x, grid_y = np.mgrid[0:10980, 0:10980]\n index, Scoords = get_coords(h,v)\n for i in xrange(6):\n mask = brdfms[i]\n sentm = np.zeros((10980,10980))\n\n values = Rs[i][index[0],index[1]]\n inter_sent = griddata(np.array(zip(Scoords[0],Scoords[1])), values, (grid_x, grid_y), method='nearest')\n sentm[Scoords[0], Scoords[1]] = mask[index[0],index[1]]\n inter_sent = ma.array(inter_sent, mask=sentm)\n parallel_rw_pkl(inter_sent.data, 'inter_sent%i'%i, 'w')\n parallel_rw_pkl(inter_sent.mask, 'inter_sentm%i'%i, 'w')\ninter_modis(modisQA, modis_filenames, fhead, h, v)\n","sub_path":"scripts/test5.py","file_name":"test5.py","file_ext":"py","file_size_in_byte":4899,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"234113763","text":"import math\nimport os\n\nimport crypto_utils as utils\n\n# Implementation of DSA based on\n# http://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.186-4.pdf\n\ndef is_prime(p):\n\treturn utils.is_probable_prime(p)\n\ndef gen_DSA_primes(L, N, seedlen, Hash, outlen):\n\tacceptable_pairs = [(1024, 160), (2048, 224), (2048, 256), (3072, 256)]\n\n\tif (L, N) not in acceptable_pairs:\n\t\treturn False, None, None\n\n\tif seedlen < N:\n\t\treturn False, None, None\n\n\tn = int(math.ceil(float(L) / float(outlen)) - 1)\n\tb = L - 1 - n * outlen\n\n\twhile True:\n\t\tdomain_parameter_seed = utils.string_to_integer(os.urandom(seedlen / 8))\n\t\tU = utils.string_to_integer(Hash(utils.integer_to_string(domain_parameter_seed))) % 2 ** (N - 1)\n\t\tq = 2 ** (N - 1) + U + 1 - (U % 2)\n\t\n\t\tif not is_prime(q):\n\t\t\tcontinue\n\n\t\toffset = 1\n\t\n\t\tfor counter in range(4 * L):\n\t\t\tV = {}\n\t\n\t\t\tfor j in range(n + 1):\n\t\t\t\tV[j] = utils.string_to_integer(Hash(utils.integer_to_string((domain_parameter_seed + offset + j) % 2 ** seedlen)))\n\t\n\t\t\tW = sum([V[j] * 2 ** (j * outlen) for j in range(n - 1)]) + (V[n] % 2 ** b) * 2 ** (n * outlen)\n\t\t\tX = W + 2 ** (L - 1)\n\t\t\tc = X % (2 * q)\n\t\t\tp = X - (c - 1)\n\t\n\t\t\tif p < 2 ** (L - 1):\n\t\t\t\toffset = offset + n + 1\n\t\t\t\tcontinue\n\t\n\t\t\tif is_prime(p):\n\t\t\t\treturn True, p, q\n\n\t\t\toffset = offset + n + 1\n\n\treturn False, None, None\n\ndef gen_DSA_generator(p, q):\n\te = (p - 1) / q\n\th = 2\n\n\twhile h < p - 1:\n\t\tg = pow(h, e, p)\n\n\t\tif g != 1:\n\t\t\treturn g\n\n\t\th += 1\n\n\treturn None\n\ndef DSA_gen_domain_params(L, N, seedlen, Hash, outlen):\n\tstatus, p, q = gen_DSA_primes(L, N, seedlen, Hash, outlen)\n\n\tif status == False:\n\t\treturn False, None, None, None\n\n\tg = gen_DSA_generator(p, q)\n\n\treturn True, p, q, g\n\ndef DSA_gen_per_user_keys(p, q, g):\n\tacceptable_pairs = [(1024, 160), (2048, 224), (2048, 256), (3072, 256)]\n\n\tN = len(bin(q)[2:])\n\tL = len(bin(p)[2:])\n\n\tif (L, N) not in acceptable_pairs:\n\t\treturn False, None, None\n\n\tc = utils.string_to_integer(os.urandom((N + 64) / 8))\n\tx = c % (q - 1) + 1\n\ty = pow(g, x, p)\n\n\treturn True, x, y\n\ndef gen_DSA_per_message_secret(p, q, g):\n\tacceptable_pairs = [(1024, 160), (2048, 224), (2048, 256), (3072, 256)]\n\n\tN = len(bin(q)[2:])\n\tL = len(bin(p)[2:])\n\n\tif (L, N) not in acceptable_pairs:\n\t\treturn False, None, None\n\n\tc = utils.string_to_integer(os.urandom((N + 64) / 8))\n\tk = c % (q - 1) + 1\n\n\tk_inv = utils.invmod(k, q)\n\treturn True, k, k_inv\n\ndef DSA_gen_signature(p, q, g, x, M, Hash, outlen):\n\tN = len(bin(q)[2:])\n\n\twhile True:\n\t\tstatus, k, k_inv = gen_DSA_per_message_secret(p, q, g)\n\t\t\n\t\tif status == False:\n\t\t\treturn False, None, None\n\t\n\t\tr = pow(g, k, p) % q\n\t\n\t\tif r == 0:\n\t\t\tcontinue\n\n\t\tz = utils.string_to_integer(Hash(M)[: min(N, outlen) / 8])\t# Leftmost min(N, outlen) bits of Hash(M)\n\t\ts = (k_inv * (z + x * r)) % q\n\n\t\tif s == 0:\n\t\t\tcontinue\n\n\t\tbreak\n\n\treturn True, r, s\n\ndef DSA_verify_signature(p, q, g, y, M, r, s, Hash, outlen):\n\tN = len(bin(q)[2:])\n\n\tif r <= 0 or r >= q or s <= 0 or s >= q:\n\t\treturn False\n\n\tw = utils.invmod(s, q)\n\tz = utils.string_to_integer(Hash(M)[: min(N, outlen) / 8])\n\tu1 = (z * w) % q\n\tu2 = (r * w) % q\n\tv = ((pow(g, u1, p) * pow(y, u2, p)) % p) % q\n\n\tif v == r:\n\t\treturn True\n\n\treturn False\n","sub_path":"Set6 - RSA and DSA/Challenge43 - DSA key recovery from nonce/dsa.py","file_name":"dsa.py","file_ext":"py","file_size_in_byte":3141,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"294044411","text":"from typing import Dict, List, Optional, Tuple\n\nimport yaml\n\n\nclass ProxyList:\n \"\"\"\n Parser to retrieve list of proxies from the configuration file in format\n matching the proxy.py ProxyPoolPlugin\n\n Attributes:\n proxy_list: list of proxies\n\n \"\"\"\n\n proxy_list: List[Dict[str, Tuple[str, int]]]\n\n def __init__(self) -> None:\n self.proxy_list = []\n\n def _get_proxies_from_file(self) -> None:\n with open(\"config/proxy_list.yaml\", 'r') as stream:\n try:\n proxies = yaml.safe_load(stream).get(\"proxies\", {})\n for i, (key, value) in enumerate(proxies.items()):\n proxy = self._get_proxy_item(key=key, item=value)\n if proxy not in self.proxy_list:\n self.proxy_list.append(proxy)\n except yaml.YAMLError as error:\n raise ValueError(\"Improperly configured YAML file => %s\" % error)\n\n @staticmethod\n def _validate_proxy_item(item: List[Dict[str, int]]):\n if item[0].get(\"ip\", None) is None:\n return False\n if item[1].get(\"port\", None) is None \\\n or not isinstance(item[1].get(\"port\", None), int):\n return False\n return True\n\n def _get_proxy_item(\n self, key: str, item: List[Dict[str, int]]\n ) -> Optional[Dict[str, Tuple[str, int]]]:\n if self._validate_proxy_item(item=item):\n return {\n key: (item[0][\"ip\"], item[1][\"port\"])\n }\n return None\n\n def get_proxies(self) -> List[Dict[str, Tuple[str, int]]]:\n \"\"\"Get list of proxies defined in a YAML configuration file\"\"\"\n\n self._get_proxies_from_file()\n return self.proxy_list\n","sub_path":"utils/proxy_list_parser.py","file_name":"proxy_list_parser.py","file_ext":"py","file_size_in_byte":1733,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"386570635","text":"# -*- coding: UTF-8 -*-\nimport connexion\nfrom datetime import date, datetime\nfrom typing import List, Dict\n\nimport xlsxwriter\nimport xlwt\nfrom six import iteritems\n\n# from swagger_server.utitl.all_dict import area_list\nfrom swagger_server.utitl.all_dict import *\nfrom ..util import deserialize_date, deserialize_datetime\nfrom swagger_server.utitl.mysqlset import MySQL\nfrom swagger_server.utitl.db import *\nfrom flask import json, jsonify\nfrom flask import Response, request\nfrom swagger_server.utitl.excleutil import ExcleUtil1\nimport os, sys\nimport time\nimport math\nimport socket\nimport random\nimport tarfile\nimport zipfile\nimport datetime\nimport os\nfrom multiprocessing import Process, Queue, Array, RLock\nimport multiprocessing\n\n\ndef get_statistics_list():\n '''\n re\n :return:\n '''\n try:\n resultdict = {}\n mysql = MySQL(2)\n mysql.mysql_connect()\n\n choose_city = 'all'\n\n colour = '红'\n sta_list = []\n if colour == '' or colour == '全部':\n sql = \"select sta_num,`type`,mean from xgld_load_abnormal ORDER BY mean desc\"\n print('--sql--1--', sql)\n elif colour == '红':\n if choose_city == 'all':\n sql = \"select sta_num,`type`,mean from xgld_load_abnormal WHERE (`type` = '基站未工作' or `type` = '负荷过高' or `type` = '负荷曲线连续三个月以上基本无变化' or `type` = '跳变异常' or `type` = '反季节变化') ORDER BY mean desc\"\n else:\n sql = \"select sta_num,`type`,mean from xgld_load_abnormal WHERE sta_num in (SELECT sta_no FROM basic_city_list WHERE city='{}') AND (`type` = '基站未工作' or `type` = '负荷过高' or `type` = '负荷曲线连续三个月以上基本无变化' or `type` = '跳变异常' or `type` = '反季节变化') ORDER BY mean desc\".format(\n choose_city)\n\n print('--sql--2--', sql)\n elif colour == '黄':\n sql = \"select sta_num,`type`,mean from xgld_load_abnormal WHERE `type` = '反季节变化' ORDER BY mean desc\"\n print('--sql-3---', sql)\n elif colour == '绿':\n sql = \"select sta_num,`type`,mean from xgld_load_abnormal WHERE `type` = '正常' ORDER BY mean desc\"\n print('--sql--4--', sql)\n else:\n print('colour err!')\n\n # 正常: 正常\n # 警告:反季节变化\n # 异常:基站未工作、负荷过高、负荷曲线连续三个月以上基本无变化、跳变异常\n\n result = mysql.query(sql)\n print('sql:80 ', sql)\n print('result:80 ', result)\n result_sta_num = []\n for i in range(len(result)):\n result_sta_num.append(result[i][0])\n print('result_sta_num:80 ', result_sta_num)\n if len(result) > 0:\n if len(result) == 1:\n sql = \"select sta_num,sta_name from basic_sta_list WHERE sta_num='{}'\".format(result_sta_num[0][0])\n else:\n sql = \"select sta_num,sta_name from basic_sta_list WHERE sta_num in {}\".format(tuple(result_sta_num))\n\n result_1 = mysql.query(sql)\n print('--sql--9--', sql)\n print('--result_1--9--', result_1)\n for i in range(len(result)):\n sta_list.append(list(result[i]))\n if result[i][1] == '正常':\n sta_list[i].append('green')\n elif result[i][1] == '反季节变化':\n sta_list[i].append('yellow')\n elif result[i][1] == '基站未工作' or result[i][1] == '负荷过高' or result[i][1] == '负荷曲线连续三个月以上基本无变化' or result[i][\n 1] == '跳变异常' or result[i][1] == '反季节变化':\n sta_list[i].append('red')\n for i in range(len(sta_list)):\n for j in range(len(result)):\n if sta_list[i][0] == result_1[j][0]:\n sta_list[i][0] = str(result_1[j][0]) + '_' + str(result_1[j][1])\n\n sta_list = sta_list[:10]\n mysql.mysql_close()\n result = [{\"station\": item[0],\n \"type\": item[1],\n \"load\": str(item[2]),\n \"color\": item[3]} for item in sta_list]\n return result\n ''' # sta_list.insert(0, ['基站', '异常类型', '负荷', '颜色'])#往0号位置插入\n # print('--sta_list--9--', sta_list)\n # \n # resultdict['sta_list'] = sta_list\n # print('完')\n # \n # reps = jsonify(resultdict)\n # reps.headers[\"Access-Control-Allow-Origin\"] = \"*\"\n # return reps'''\n\n return {\"code\": 0, \"msg\": 'success', \"result\": result}\n except Exception as e:\n print(e)\n return {\"code\": \"-1\", \"msg\": \"error\"}\n\n\n# p z s e area name money yijiao desc\ndef get_statistics_inspect(page='1', size='10', starttime='', endtime='',\n area='',\n name='',\n money='',\n yijiao='',\n desc='', ):\n if area != '':\n area = get_keys(area_dict, area)\n if endtime != '':\n endtime = endtime + ' 00:00:00'\n if starttime != '':\n starttime = starttime + ' 00:00:00'\n\n data = _filter(AXgdlInspect,\n starttime=starttime,\n endtime=endtime,\n area=area,\n\n type=money,\n tower=yijiao,\n )\n # station = name,\n if name != '':\n like = \"%\" + name + \"%\"\n data = data.where(AXgdlInspect.station % like)\n\n if desc != '':\n like = \"%\" + desc + \"%\"\n data = data.where(AXgdlInspect.desc % like)\n # desc = desc, 做成keyword\n\n\n total = data.count()\n data = data.paginate(int(page), int(size))\n # pass # p z s e area name money yijiao desc\n result = [{\n # ax.create(\n # posttime=int(time.time()),\n # company=row_data[1],\n # area=row_data[2],\n # station=row_data[3],\n # desc=row_data[4],\n # typr=row_data[5],\n # inspect=get_keys(if_dict, row_data[9]),\n # month='5',\n # tower=row_data[6],\n # rank=get_keys(if_dict, row_data[8])\n #\n # )\n\n\n 'company': item.company,\n 'area': area_dict[item.area],\n 'station': item.station,\n 'desc': item.desc,\n 'type': item.type,\n 'tower': item.tower,\n 'month': item.month,\n 'rank': if_dict[item.rank],\n 'inspect': if_dict[item.inspect],\n 'posttime': utc_timestamp_to_str(item.posttime),\n } for item in data]\n return {\"code\": 0, \"msg\": \"success\", \"total\": total, \"result\": result}\n\n\n# company\n# area\n# station\n# desc\n# type\n# tower\n# month\n# rank\n# inspect\n# posttime\n\n\ndef get_statistics_inspect_export(page='1', size='10', starttime='', endtime='',\n area='',\n name='',\n money='',\n yijiao='',\n desc='', ):\n # data = [['a', 'b', 'c', 'd'], ['a', 'b', 'c', 'd'], ['a', 'b', 'c', 'd'], ['a', 'b', 'c', 'd'],\n # ['a', 'b', 'c', 'd']]\n #\n # exprort(data, 'text', 'style4', 'A', 'B', 'C', 'D')\n if area != '':\n area = get_keys(area_dict, area)\n if endtime != '':\n endtime = endtime + ' 00:00:00'\n if starttime != '':\n starttime = starttime + ' 00:00:00'\n data = _filter(AXgdlInspect,\n starttime=starttime,\n endtime=endtime,\n area=area,\n # station=name,\n type=money,\n tower=yijiao,\n )\n if name != '':\n like = \"%\" + name + \"%\"\n data = data.where(AXgdlInspect.station % like)\n\n\n if desc != '':\n like = \"%\" + desc + \"%\"\n data = data.where(AXgdlInspect.desc % like)\n result = [[\n\n # 'company': item.company,\n # 'area': area_dict[item.area],\n # 'station': item.station,\n # 'desc': item.desc,\n # 'type': item.type,\n # 'tower': item.tower,\n # 'month': item.month,\n # 'rank': if_dict[item.rank],\n # 'inspect': if_dict[item.inspect],\n # 'posttime': utc_timestamp_to_str(item.posttime),\n\n item.company,\n area_dict[item.area],\n item.station,\n item.desc,\n item.type,\n item.tower,\n item.month+'月',\n if_dict[item.rank],\n if_dict[item.inspect],\n utc_timestamp_to_str(item.posttime)]\n for item in data]\n name_list = ['代维公司', '县市', '基站名称', '基站设备明细'\n , '费用核算类型', '是否移交铁塔', '交维月份', '是否高级站点'\n , '1-4月份是否巡检', '巡检时间']\n filename = exprort(result, '巡检报表', 'style1', '代维公司', '县市', '基站名称', '基站设备明细'\n , '费用核算类型', '是否移交铁塔', '交维月份', '是否高级站点'\n , '1-4月份是否巡检', '巡检时间')\n\n return {\n \"msg\": \"msg\",\n \"code\": 0,\n \"url\": \"192.168.188.178:86/xiaogan/{}\".format(filename),\n }\n\n\n# 有不用 名称和地区\n# p z s e area name money yijiao desc\ndef get_statistics_reading_export(page='1', size='10', starttime='', endtime='',\n area='',\n name='',\n money='',\n yijiao='',\n desc='', ):\n name_list = ['县市', '基站名称', '基站编号', '经度',\n '纬度', '示数', '抄表时间', '照片']\n if endtime != '':\n endtime =endtime+' 00:00:00'\n if starttime != '':\n starttime = starttime + ' 00:00:00'\n\n if area != '':\n area = get_keys(area_dict, area)\n data = _filter(AXgdlReading,\n starttime=starttime,\n endtime=endtime,\n area=area,\n # name=name,\n )\n if name != '':\n like = \"%\" + name + \"%\"\n data = data.where(AXgdlReading.name % like)\n\n\n\n result = [[\n area_dict[item.area],\n item.name,\n item.number,\n item.x_code,\n item.y_code,\n item.meter,\n utc_timestamp_to_str(item.posttime) ,\n item.pic\n ] for item in data]\n\n filename = make_report(result, '抄表报表', 'style4', '县市', '基站名称', '基站编号', '经度',\n '纬度', '示数', '抄表时间', '照片')\n\n return {\n \"msg\": \"msg\",\n \"code\": 0,\n \"url\": \"192.168.188.178:86/xiaogan/{}\".format(filename),\n }\n\n\n# page size area name type tower desc\ndef get_statistics_reading(page='1', size='10', starttime='', endtime='',\n area='',\n name='',\n money='',\n yijiao='',\n desc='', ):\n if area != '':\n area = get_keys(area_dict, area)\n if endtime != '':\n endtime = endtime + ' 00:00:00'\n if starttime != '':\n starttime = starttime + ' 00:00:00'\n\n data = _filter(AXgdlReading,\n starttime=starttime,\n endtime=endtime,\n area=area,\n # name=name,\n )\n if name != '':\n like = \"%\" + name + \"%\"\n data = data.where(AXgdlReading.name % like)\n total = data.count()\n data = data.order_by(AXgdlReading.posttime.desc()).paginate(int(page), int(size))\n # pass # p z s e area name money yijiao desc\n result = [{\n 'area': area_dict[item.area],\n 'name': item.name,\n 'number': item.number,\n 'x_code': item.x_code,\n 'y_code': item.y_code,\n 'meter': item.meter,\n 'posttime': utc_timestamp_to_str(item.posttime),\n 'pic': item.pic\n } for item in data]\n return {\"code\": 0, \"msg\": \"success\", \"total\": total, \"result\": result}\n\n\n# pa siz star end\n\n\n# area\n# station\n# ground\n# 地理位置\n# produce\n# frame\n# 型号\n# cap\n# 容量\n# transmission\n# 传输基站公用\n# 1\n# ifmonitoring\n# 是否安装单体监控\n# 2\n# ktpower\n# 功率3\n# kttype\n# people\n\n\n# area produce cap name type tower desc\ndef get_statistics_inventory(page='',\n size='',\n starttime='',\n endtime='',\n id='',\n area='',\n station='',\n ground='',\n produce='',\n frame='',\n cap='',\n transmission='',\n ifmonitoring='',\n ktpower='',\n kttype='',\n people=''\n ):\n if area != '':\n area = get_keys(area_dict, area)\n if endtime != '':\n endtime = endtime + ' 00:00:00'\n if starttime != '':\n starttime = starttime + ' 00:00:00'\n data = _filter(AXgdlEquipment,\n starttime=starttime,\n endtime=endtime,\n id=id,\n area=area,\n # station=station,\n ground=ground,\n produce=produce,\n frame=frame,\n cap=cap,\n transmission=transmission,\n ifmonitoring=ifmonitoring,\n ktpower=ktpower,\n kttype=kttype,\n peoplep=people,\n )\n if station != '':\n like = \"%\" + station + \"%\"\n data = data.where(AXgdlEquipment.station % like)\n total = data.count()\n print(total)\n data = data.paginate(int(page), int(size))\n # for item in data:\n #\n # result=json.dumps(item,default=lambda o:o.__dict__)\n # # result=data.__dict__\n # print(result)\n result = [{\n 'type': item.type or '暂无数据',\n 'area': item.area or '暂无数据',\n 'station': item.station or '暂无数据',\n 'number': item.number or '暂无数据',\n 'node': item.node or '暂无数据',\n 'ground': item.ground or '暂无数据',\n 'produce': item.produce or '暂无数据',\n 'frame': item.frame or '暂无数据',\n 'cap': item.cap or '暂无数据',\n 'starttime': item.starttime or '暂无数据',\n 'monitoring': item.monitoring or '暂无数据',\n 'rectification': item.rectification or '暂无数据',\n 'renumber': item.renumber or '暂无数据',\n 'modulecap': item.modulecap or '暂无数据',\n 'loadele': item.loadele or '暂无数据',\n 'transmission': item.transmission or '暂无数据',\n 'powerdown': item.powerdown or '暂无数据',\n 'oil': item.oil or '暂无数据',\n 'pic': item.pic or '暂无数据',\n 'desc': item.desc or '暂无数据',\n 'people': item.people or '暂无数据',\n 'phone': item.phone or '暂无数据',\n 'tid': item.tid or '暂无数据',\n 'group': item.group or '暂无数据',\n 'brand': item.brand or '暂无数据',\n 'changebox': item.changebox or '暂无数据',\n 'jifang': item.jifang or '暂无数据',\n 'kttype': item.kttype or '暂无数据',\n 'ktpower': item.ktpower or '暂无数据',\n 'ifmonitoring': item.ifmonitoring or '暂无数据',\n 'hbtime': item.hbtime or '暂无数据',\n 'iftransmission': item.iftransmission or '暂无数据',\n 'ifpowerdown': item.ifpowerdown or '暂无数据',\n 'ifstatus': item.ifstatus or '暂无数据',\n 'xuhao': item.xuhao or '暂无数据',\n 'posttime': item.posttime or '暂无数据',\n } for item in data]\n\n return {\"code\": 0, \"msg\": \"success\", \"total\": total, \"result\": result}\n\n\n# powerdown 二次下电 和什么在一起 meishi ifpowerdown\n# page\n# area produce cap name type tower desc\ndef get_statistics_inventory_export(page='',\n size='',\n starttime='',\n endtime='',\n id='',\n area='',\n station='',\n\n ground='',\n produce='',\n frame='',\n cap='',\n transmission='',\n ifmonitoring='',\n ktpower='',\n\n kttype='',\n people=''\n ):\n if area != '':\n area = get_keys(area_dict, area)\n if endtime != '':\n endtime = endtime + ' 00:00:00'\n if starttime != '':\n starttime = starttime + ' 00:00:00'\n data = _filter(AXgdlEquipment,\n starttime=starttime,\n endtime=endtime,\n id=id,\n area=area,\n # station=station,\n ground=ground,\n produce=produce,\n frame=frame,\n cap=cap,\n transmission=transmission,\n ifmonitoring=ifmonitoring,\n ktpower=ktpower,\n kttype=kttype,\n peoplep=people,\n )\n if station != '':\n like = \"%\" + station + \"%\"\n data = data.where(AXgdlInspect.station % like)\n if id == '1':\n result = [[\n item.area,\n item.station,\n item.number,\n item.node,\n item.ground,\n item.produce,\n item.frame,\n item.cap,\n item.starttime,\n item.monitoring,\n item.rectification,\n item.renumber,\n item.modulecap,\n item.loadele,\n item.transmission,\n item.powerdown,\n item.ifstatus,\n item.ifpowerdown,\n item.oil,\n item.desc,\n item.people,\n item.phone,\n\n ] for item in data]\n filename = exprort(result, '开关电源报表', 'style4', '县市',\n '基站名称',\n '基站编码',\n '节点类型',\n '基站地理位置',\n '生产厂家',\n '机架型号',\n '机架容量(A)',\n '开始使用时间',\n '监控模块型号',\n '整流模块型号',\n '整流模块数量(块)',\n '模块容量',\n '负载电流(A)',\n '传输及基站是否共用',\n '是否有二次下电功能',\n '目前运行状态是否正常',\n '是否属于本地区停电频繁基站',\n '该站是否配置了固定自启动油机',\n '备注',\n '填报人',\n '联系电话', )\n return {\n \"msg\": \"msg\",\n \"code\": 0,\n \"url\": \"192.168.188.178:86/xiaogan/{}\".format(filename),\n }\n name_list1 = [\n '县市',\n '基站名称',\n '基站编码',\n '节点类型',\n '基站地理位置',\n '生产厂家',\n '机架型号',\n '机架容量(A)',\n '开始使用时间',\n '监控模块型号',\n '整流模块型号',\n '整流模块数量(块)',\n '模块容量',\n '负载电流(A)',\n '传输及基站是否共用',\n '是否有二次下电功能',\n '目前运行状态是否正常',\n '是否属于本地区停电频繁基站',\n '该站是否配置了固定自启动油机',\n '备注',\n '填报人',\n '联系电话',\n ]\n # area\n # station\n # number\n # node\n # ground\n # produce\n # frame\n # cap\n # starttime\n # monitoring\n # rectification\n # renumber\n # modulecap\n # loadele\n # transmission\n # powerdown\n # ifstatus\n # ifpowerdown\n # oil\n # desc\n # people\n # phone\n if id == '2':\n result = [[\n item.area,\n item.station,\n item.number,\n item.node,\n item.ground,\n item.produce,\n item.frame,\n item.cap,\n item.group,\n item.ifmonitoring,\n item.starttime,\n item.loadele,\n item.hbtime,\n item.ifpowerdown,\n item.oil,\n item.desc,\n item.people,\n item.phone,\n\n ] for item in data]\n filename = exprort(result, '蓄电池报表', 'style4', '县市',\n '基站名称',\n '基站编码',\n '节点类型',\n '基站地理位置',\n '厂家',\n '型号',\n '容量(A)',\n '组数',\n '是否安装单体监控',\n '开始使用时间',\n '当前负载(A)',\n '经放电测试大约后备时长(小时)',\n '是否属于本地区停电频繁基站',\n '该站是否配置了固定自启动油机',\n '备注',\n '填报人',\n '联系电话', )\n return {\n \"msg\": \"msg\",\n \"code\": 0,\n \"url\": \"192.168.188.178:86/xiaogan/{}\".format(filename),\n }\n\n name_list2 = [\n '县市',\n '基站名称',\n '基站编码',\n '节点类型',\n '基站地理位置',\n '厂家',\n '型号',\n '容量(A)',\n '组数',\n '是否安装单体监控',\n '开始使用时间',\n '当前负载(A)',\n '经放电测试大约后备时长(小时)',\n '是否属于本地区停电频繁基站',\n '该站是否配置了固定自启动油机',\n '备注',\n '填报人',\n '联系电话',\n ]\n\n # area\n # station\n # number\n # node\n # ground\n # produce\n # frame\n # cap\n # group\n # ifmonitoring\n # starttime\n # loadele\n # hbtime\n # ifpowerdown\n # oil\n # desc\n # people\n # phone\n if id == '3':\n result = [[\n item.area,\n item.station,\n item.number,\n item.node,\n item.produce,\n item.frame,\n item.ktpower,\n item.kttype,\n item.starttime,\n item.desc,\n item.people,\n item.phone,\n\n ] for item in data]\n filename = exprort(result, '空调报表', 'style4', '县市',\n '基站名称',\n '基站编码',\n '节点类型',\n '厂家'\n '型号'\n '功率(匹)'\n '类型'\n '开始使用时间'\n '备注',\n '填报人',\n '联系电话', )\n return {\n \"msg\": \"msg\",\n \"code\": 0,\n \"url\": \"192.168.188.178:86/xiaogan/{}\".format(filename),\n }\n\n name_list3 = [\n '县市',\n '基站名称',\n '基站编码',\n '节点类型',\n '厂家'\n '型号'\n '功率(匹)'\n '类型'\n '开始使用时间'\n '备注',\n '填报人',\n '联系电话',\n ]\n # area\n # station\n # number\n # node\n # produce\n # frame\n # ktpower\n # kttype\n # starttime\n # desc\n # people\n # phone\n\n if id == '4':\n result = [[\n item.area,\n item.station,\n item.number,\n item.node,\n item.produce,\n item.frame,\n item.renumber,\n item.starttime,\n item.desc,\n item.people,\n item.phone,\n\n ] for item in data]\n filename = exprort(result, '交流配配电箱报表', 'style4', '县市',\n '基站名称',\n '基站编码',\n '节点类型',\n '厂家'\n '型号'\n '数量'\n '开始使用时间'\n '备注',\n '填报人',\n '联系电话',)\n return {\n \"msg\": \"msg\",\n \"code\": 0,\n \"url\": \"192.168.188.178:86/xiaogan/{}\".format(filename),\n }\n\n name_list4 = [\n '县市',\n '基站名称',\n '基站编码',\n '节点类型',\n '厂家'\n '型号'\n '数量'\n '开始使用时间'\n '备注',\n '填报人',\n '联系电话',\n ]\n\n # area\n # station\n # number\n # node\n # produce\n # frame\n # renumber\n # starttime\n # desc\n # people\n # phone\n if id == '5':\n result = [[\n item.area,\n item.station,\n item.number,\n item.produce,\n item.frame,\n item.renumber,\n item.starttime,\n item.desc,\n item.people,\n item.phone,\n ] for item in data]\n filename = exprort(result, '拉远站(交转直)报表', 'style4', '县市',\n '基站名称',\n '基站编码',\n '厂家'\n '型号'\n '数量'\n '开始使用时间'\n '备注',\n '填报人',\n '联系电话', )\n return {\n \"msg\": \"msg\",\n \"code\": 0,\n \"url\": \"192.168.188.178:86/xiaogan/{}\".format(filename),\n }\n\n name_list5 = [\n '县市',\n '基站名称',\n '基站编码',\n '厂家'\n '型号'\n '数量'\n '开始使用时间'\n '备注',\n '填报人',\n '联系电话',\n ]\n # area\n # station\n # number\n # produce\n # frame\n # renumber\n # starttime\n # desc\n # people\n # phone\n if id == '6':\n result = [[\n item.area,\n item.station,\n item.number,\n item.node,\n item.produce,\n item.frame,\n item.monitoring,\n item.ktpower,\n item.rectification,\n item.renumber,\n item.starttime,\n item.desc,\n item.people,\n item.phone,\n\n ] for item in data]\n filename = exprort(result, '直流远供局端报表', 'style4', '县市',\n '基站名称',\n '基站编码',\n '节点类型',\n '厂家',\n '局端型号',\n '监控型号',\n '功率(KW)',\n '模块型号',\n '模块数量',\n '开始使用时间',\n '备注',\n '填报人',\n '联系电话', )\n return {\n \"msg\": \"msg\",\n \"code\": 0,\n \"url\": \"192.168.188.178:86/xiaogan/{}\".format(filename),\n }\n\n name_list6 = [\n '县市',\n '基站名称',\n '基站编码',\n '节点类型',\n '厂家',\n '局端型号',\n '监控型号',\n '功率(KW)',\n '模块型号',\n '模块数量',\n '开始使用时间',\n '备注',\n '填报人',\n '联系电话',\n ]\n\n # area\n # station\n # number\n # node\n # produce\n # frame\n # monitoring\n # ktpower\n # rectification\n # renumber\n # starttime\n # desc\n # people\n # phone\n if id == '7':\n result = [[\n item.area,\n item.station,\n item.number,\n item.node,\n item.produce,\n item.frame,\n item.starttime,\n item.renumber,\n item.desc,\n item.people,\n item.phone,\n ] for item in data]\n filename = exprort(result, '一体化柜机报表', 'style4', '县市',\n '基站名称',\n '基站编码',\n '节点类型',\n '厂家',\n '型号',\n '开始使用时间',\n '数量',\n '备注',\n '填报人',\n '联系电话', )\n return {\n \"msg\": \"msg\",\n \"code\": 0,\n \"url\": \"192.168.188.178:86/xiaogan/{}\".format(filename),\n }\n\n name_list7 = [\n '县市',\n '基站名称',\n '基站编码',\n '节点类型',\n '厂家',\n '型号',\n '开始使用时间',\n '数量',\n '备注',\n '填报人',\n '联系电话',\n ]\n # area\n # station\n # number\n # node\n # produce\n # frame\n # starttime\n # renumber\n # desc\n # people\n # phone\n if id == '8':\n result = [[\n item.area,\n item.ground,\n item.produce,\n item.frame,\n item.ktpower,\n item.starttime,\n item.renumber,\n item.desc,\n item.people,\n item.phone,\n ] for item in data]\n filename = exprort(result, '变压器报表', 'style4', '县市',\n '地点',\n '厂家'\n '型号'\n '功率(KVA)'\n '开始使用时间'\n '数量',\n '备注',\n '填报人',\n '联系电话', )\n return {\n \"msg\": \"msg\",\n \"code\": 0,\n \"url\": \"192.168.188.178:86/xiaogan/{}\".format(filename),\n }\n\n name_list8 = [\n '县市',\n '地点',\n '厂家'\n '型号'\n '功率(KVA)'\n '开始使用时间'\n '数量',\n '备注',\n '填报人',\n '联系电话',\n ]\n # area\n # ground\n # produce\n # frame\n # ktpower\n # starttime\n # renumber\n # desc\n # people\n # phone\n if id == '9':\n result = [[\n item.area,\n item.produce,\n item.frame,\n item.ktpower,\n item.starttime,\n item.renumber,\n item.ground,\n item.desc,\n item.people,\n item.phone,\n\n ] for item in data]\n filename = exprort(result, '应急油机报表', 'style4', '县市',\n '厂家'\n '型号'\n '功率(KW)'\n '开始使用时间'\n '数量'\n '存放地点'\n '备注',\n '填报人',\n '联系电话',)\n return {\n \"msg\": \"msg\",\n \"code\": 0,\n \"url\": \"192.168.188.178:86/xiaogan/{}\".format(filename),\n }\n\n name_list9 = [\n '县市',\n '厂家'\n '型号'\n '功率(KW)'\n '开始使用时间'\n '数量'\n '存放地点'\n '备注',\n '填报人',\n '联系电话',\n ]\n # area\n # produce\n # frame\n # ktpower\n # starttime\n # renumber\n # ground\n # desc\n # people\n # phone\n\n\n# s e p s area 机房 铁塔类型 基站类型\ndef get_statistics_tower(id, starttime='', endtime='', page=1, size=10,\n area='', stationtype='', ttpye='', stype=''):\n print(type(id))\n\n if area != '':\n area = get_keys(area_dict, area)\n if endtime != '':\n endtime = endtime + ' 00:00:00'\n if starttime != '':\n starttime = starttime + ' 00:00:00'\n if id == '2':\n if area != '':\n area = get_keys(area_dict, area)\n data = _filter(AXgdlTowerCount,\n starttime=starttime,\n endtime=endtime,\n area=area,\n )\n total = data.count()\n data = data.paginate(int(page), int(size))\n result = [{\n 'area': item.area,\n 'totle': item.totle,\n 'yijiao': item.yijiao,\n 'yijiaotower': item.yijiaotower,\n 'yijiaojifan': item.yijiaojifan,\n 'nowtower': item.nowtower,\n 'noyijiao': item.noyijiao,\n 'biaoyijiao': item.biaoyijiao,\n 'desc': item.desc,\n 'piccount': item.piccount,\n 'posttime': item.posttime,\n # 'phone':item.phone\n\n } for item in data]\n return {\"code\": 0, \"msg\": \"success\", \"total\": total, \"result\": result}\n\n if area != '':\n area = get_keys(area_dict, area)\n if stationtype != '':\n stationtype = get_keys(jifan_dict, stationtype)\n if ttpye != '':\n ttpye = get_keys(tower_dict, ttpye)\n if stype != '':\n stype = get_keys(jizhan_dict, stype)\n\n data = _filter(AXgdlTower,\n starttime=starttime,\n endtime=endtime,\n area=area,\n stationtype=stationtype,\n ttpye=ttpye,\n stype=stype,\n )\n total = data.count()\n data = data.paginate(int(page), int(size))\n # pass # p z s e area name money yijiao desc\n for item in data:\n print(item.station)\n\n result = [{\n 'area': area_dict[item.area],\n 'station': item.station,\n 'address': item.address,\n 'tnumber': item.tnumber,\n 'stype': jizhan_dict[item.stype],\n 'money': item.money,\n 'ttpye': tower_dict[item.ttpye],\n 'hight': item.hight,\n 'stationtype': jifan_dict[item.stationtype],\n 'transfer': item.transfer,\n 'share': item.share,\n 'tshare': item.tshare,\n 'sharelist': item.sharelist,\n 'sharenumber': item.sharenumber,\n 'sharedesc': item.sharedesc,\n 'elesharelist': item.elesharelist,\n 'rru': item.rru,\n 'antenna': item.antenna,\n 'pic': item.pic,\n 'reading': item.reading,\n 'phone': item.phone,\n 'posttime': utc_timestamp_to_str(item.posttime),\n 'tsharelist': item.tsharelist,\n\n } for item in data]\n return {\"code\": 0, \"msg\": \"success\", \"total\": total, \"result\": result}\n\n\n# s e p s area\ndef get_statistics_tower_export(id, starttime='', endtime='', page=1, size=10,\n area='', stationtype='', ttpye='', stype=''):\n\n if area != '':\n area = get_keys(area_dict, area)\n if endtime != '':\n endtime = endtime + ' 00:00:00'\n if starttime != '':\n starttime = starttime + ' 00:00:00'\n if id == '2':\n if area != '':\n area = get_keys(area_dict, area)\n data = _filter(AXgdlTowerCount,\n starttime=starttime,\n endtime=endtime,\n area=area,\n )\n name_list = [\n '县市',\n '站点总数',\n '全部移交',\n '移交铁塔',\n '移交机房',\n '铁塔新建站',\n '未移交',\n '备注'\n\n ]\n\n result = [[\n item.area,\n item.totle,\n item.yijiao,\n item.yijiaotower,\n item.yijiaojifan,\n item.nowtower,\n item.noyijiao,\n # item.biaoyijiao,\n item.desc,\n item.piccount,\n item.posttime,\n\n ] for item in data]\n filename = exprort(result, '铁塔总数报表', 'style4', '县市',\n '站点总数',\n '全部移交',\n '移交铁塔',\n '移交机房',\n '铁塔新建站',\n '未移交',\n '备注')\n return {\n \"msg\": \"msg\",\n \"code\": 0,\n \"url\": \"192.168.188.178:86/{}\".format(filename),\n }\n\n if area != '':\n area = get_keys(area_dict, area)\n if stationtype != '':\n stationtype = get_keys(jifan_dict, stationtype)\n if ttpye != '':\n ttpye = get_keys(tower_dict, ttpye)\n if stype != '':\n stype = get_keys(jizhan_dict, stype)\n\n data = _filter(AXgdlTower,\n starttime=starttime,\n endtime=endtime,\n area=area,\n stationtype=stationtype,\n ttpye=ttpye,\n stype=stype,\n )\n # total = data.count()\n # data = data.paginate(int(page), int(size))\n # pass # p z s e area name money yijiao desc\n result = [[\n\n # 'area':\n # 'station': item.station,\n # 'address': item.address,\n # 'tnumber': item.tnumber,\n # 'stype':\n # 'money': item.money,\n # 'ttpye':\n # 'hight': item.hight,\n # 'stationtype':\n area_dict[item.area],\n item.station,\n item.address,\n item.tnumber,\n jizhan_dict[item.stype],\n item.money,\n tower_dict[item.ttpye],\n item.hight,\n jifan_dict[item.stationtype],\n item.transfer,\n item.share,\n item.tshare,\n item.tsharelist,\n item.sharenumber,\n item.sharelist,\n item.sharedesc,\n item.elesharelist,\n item.rru,\n item.antenna,\n item.pic,\n # item.reading, 导出不用抄表人和联系方式\n # item.phone,\n utc_timestamp_to_str(item.posttime),\n\n ] for item in data]\n name_list = ['县市', '基站名称', '详细地点描述', '公司编码',\n '基站类型', '是否支付', '铁塔类型', '铁塔高度',\n '机房类型', '移交类型', '是否共享', '铁塔共享用户数',\n '铁塔共享清单', '机房共享用户数', '机房共享清单', '电表共享情况',\n '电表共享清单', 'RRU', '天线数量', '照片', '日期', ]\n filename = exprort(result, '铁塔报表', 'style4', '县市', '基站名称', '详细地点描述', '公司编码',\n '基站类型', '是否支付', '铁塔类型', '铁塔高度',\n '机房类型', '移交类型', '是否共享', '铁塔共享用户数',\n '铁塔共享清单', '机房共享用户数', '机房共享清单', '电表共享情况',\n '电表共享清单', 'RRU', '天线数量', '照片', '日期', )\n return {\n \"msg\": \"msg\",\n \"code\": 0,\n \"url\": \"192.168.188.178:86/{}\".format(filename),\n }\n\n\n# area rank station tower gtype transfer\ndef get_statistics_clean(starttime='', endtime='', page=1, size=10,\n area='', rank='', station=''\n , tower='', gtype='', transfer=''):\n #字典里面加一个空对空\n if endtime != '':\n endtime = endtime + ' 00:00:00'\n if starttime != '':\n starttime = starttime + ' 00:00:00'\n if area != '':\n area = get_keys(area_dict, area)\n if rank != '':\n rank = get_keys(rank_dict, rank)\n if station != '':\n jifan = get_keys(jifan_dict, station)\n else:\n jifan = ''\n if tower != '':\n tower = get_keys(tower_dict, tower)\n if gtype != '':\n jizhan = get_keys(jizhan_dict, gtype)\n else:\n jizhan = ''\n if transfer != '':\n transfer = get_keys(transfer_dict, transfer)\n\n data = _filter(AXgdlClean, area=area, rank=rank, jifan=jifan,\n tower=tower, jizhan=jizhan, transfer=transfer,\n starttime=starttime, endtime=endtime)\n total = data.count()\n # jia area\n data = data.paginate(int(page), int(size))\n\n result = [{\n 'name': item.name,\n 'number': item.number,\n 'address': item.address,\n 'rank': rank_dict[item.rank],\n 'jifan': jifan_dict[item.jifan],\n 'tower': tower_dict[item.tower],\n 'height': item.height,\n 'jizhan': jizhan_dict[item.jizhan],\n 'transfer': transfer_dict[item.transfer],\n 'share': share_dict[item.share],\n 'area': area_dict[item.area]\n } for item in data]\n\n return {\"code\": 0, \"msg\": \"success\", \"total\": total, \"result\": result}\n\n\ndef get_statistics_clean_export(starttime='', endtime='', page=1, size=10,\n area='', rank='', station=''\n , tower='', gtype='', transfer=''):\n\n if endtime != '':\n endtime = endtime + ' 00:00:00'\n if starttime != '':\n starttime = starttime + ' 00:00:00'\n if area != '':\n area = get_keys(area_dict, area)\n if rank != '':\n rank = get_keys(rank_dict, rank)\n if station != '':\n jifan = get_keys(jifan_dict, station)\n else:\n jifan = ''\n if tower != '':\n tower = get_keys(tower_dict, tower)\n if gtype != '':\n jizhan = get_keys(jizhan_dict, gtype)\n else:\n jizhan = ''\n if transfer != '':\n transfer = get_keys(transfer_dict, transfer)\n\n data = _filter(AXgdlClean, area=area, rank=rank, jifan=jifan,\n tower=tower, jizhan=jizhan, transfer=transfer,\n starttime=starttime, endtime=endtime)\n name_list = ['县市', '基站名称', '基站编号', '详细地点描述', '维护级别'\n , '机房类型', '铁塔类型', '铁塔高度', '基站类型', '是否移交', '共享家数']\n result = [[\n area_dict[item.area],\n item.name,\n item.number,\n item.address,\n rank_dict[item.rank],\n jifan_dict[item.jifan],\n tower_dict[item.tower],\n item.height,\n jizhan_dict[item.jizhan],\n transfer_dict[item.transfer],\n share_dict[item.share],\n\n ] for item in data]\n\n filename = exprort(result, '基站清理报表', 'style4', '区县', '基站名称', '基站编号', '详细地点描述', '维护级别'\n , '机房类型', '铁塔类型', '铁塔高度', '基站类型', '是否移交', '共享家数')\n return {\n \"msg\": \"msg\",\n \"code\": 0,\n \"url\": \"192.168.188.178:86/xiaogan/{}\".format(filename),\n }\n # name\n # number\n # address\n # rank\n # jifan\n # tower\n # height\n # jizhan\n # transfer\n # share\n\n\n# def get_statistics_chart():\n# pass\n#\n# def get_statistics_chart_export():\n# pass\n\n\n\ndef one_filter(data, db, k, val):\n date = data\n if val != None and val != '':\n print(db)\n\n # AXgdlEquipment,\n # starttime = starttime,\n # endtime = endtime,\n # id = id,\n # area = area,\n # station = station,\n # ground = ground,\n # produce = produce,\n # frame = frame,\n # cap = cap,\n # transmission = transmission,\n # ifmonitoring = ifmonitoring,\n # ktpower = ktpower,\n # kttype = kttype,\n # peoplep = people,\n\n if db == AXgdlEquipment:\n if k == 'starttime':\n starttime = utc_str_to_timestamp(val)\n data = date.where(starttime <= db.posttime)\n if k == 'endtime':\n endtime = utc_str_to_timestamp(val)\n data = date.where(db.posttime <= endtime)\n if k == 'id':\n data = date.where(db.type == val)\n if k == 'area':\n data = date.where(db.area == val)\n if k == 'station':\n data = date.where(db.station == val)\n if k == 'ground':\n data = date.where(db.ground == val)\n if k == 'produce':\n data = date.where(db.produce == val)\n if k == 'frame':\n data = date.where(db.frame == val)\n if k == 'cap':\n data = date.where(db.cap == val)\n if k == 'transmission':\n data = date.where(db.transmission == val)\n if k == 'ifmonitoring':\n data = date.where(db.ifmonitoring == val)\n if k == 'ktpower':\n data = date.where(db.ktpower == val)\n if k == 'peoplep':\n data = date.where(db.peoplep == val)\n if k == 'kttype':\n data = date.where(db.kttype == val)\n\n if db == AXgdlTower:\n print('keyijinru')\n if k == 'stationtype':\n data = date.where(db.stationtype == val)\n if k == 'ttype':\n data = date.where(db.ttype == val)\n if k == 'stype':\n data = date.where(db.stype == val)\n if k == 'starttime':\n starttime = utc_str_to_timestamp(val)\n data = date.where(starttime <= db.posttime)\n if k == 'endtime':\n endtime = utc_str_to_timestamp(val)\n data = date.where(db.posttime <= endtime)\n if k == 'area':\n try:\n data = date.where(db.area == val)\n except:\n data = date.where(db.address == val)\n\n # data = _filter(AXgdlTower,\n # starttime=starttime,\n # endtime=endtime,\n # area=area,\n # stationtype=stationtype,\n # ttpye=ttpye,\n # stype=stype,\n # )\n if db == AXgdlInspect:\n print('keyijinru')\n if k == 'tower':\n data = date.where(db.tower == val)\n if k == 'starttime':\n starttime = utc_str_to_timestamp(val)\n data = date.where(starttime <= db.posttime)\n if k == 'endtime':\n endtime = utc_str_to_timestamp(val)\n data = date.where(db.posttime <= endtime)\n if k == 'area':\n try:\n data = date.where(db.area == val)\n except:\n data = date.where(db.address == val)\n if k == 'station':\n data = date.where(db.station == val)\n\n if k == 'type':\n data = date.where(db.type == val)\n\n\n\n\n else:\n if k == 'starttime':\n starttime = utc_str_to_timestamp(val)\n data = date.where(starttime <= db.posttime)\n if k == 'endtime':\n endtime = utc_str_to_timestamp(val)\n data = date.where(db.posttime <= endtime)\n if k == 'name':\n data = date.where(db.name == val)\n if k == 'area':\n try:\n data = date.where(db.area == val)\n except:\n data = date.where(db.address == val)\n\n if k == 'jifan':\n data = date.where(db.jifan == val)\n if k == 'jizhan':\n data = date.where(db.jizhan == val)\n\n if k == 'rank':\n data = date.where(db.rank == val)\n if k == 'station':\n try:\n data = date.where(db.station == val)\n except:\n data = date.where(db.jifan == val)\n if k == 'tower':\n data = date.where(db.tower == val)\n if k == 'gtype':\n data = date.where(db.jizhan == val)\n if k == 'transfer':\n data = date.where(db.transfer == val)\n print(data.count())\n return data\n\n\ndef _filter(db, **kw):\n date = db.select()\n for k, val in kw.items():\n if val != None and val != '':\n date = one_filter(date, db, k, val)\n print(date.count())\n num = 0\n for val in kw.values():\n if val == None or val == '':\n num += 1\n if num == len(kw):\n date = db.select()\n return date\n\n\ndef utc_str_to_timestamp(dt):\n timeArray = time.strptime(dt, \"%Y-%m-%d %H:%M:%S\")\n # 转换成时间戳\n timestamp = time.mktime(timeArray)\n return (int(timestamp))\n\n\ndef utc_timestamp_to_str(dt):\n # 时间戳变成字符串\n timeArray = time.localtime(dt)\n otherStyleTime = time.strftime(\"%Y-%m-%d %H:%M:%S\", timeArray)\n return otherStyleTime\n\n\ndef get_keys(d, value):\n a = [k for k, v in d.items() if v == value]\n return a[0]\n\n\ndef exprort(data, name, style, *args):\n workbook_m = xlwt.Workbook(encoding='utf-8')\n xlsheet = workbook_m.add_sheet(name, cell_overwrite_ok=True)\n # 格式1 (有自动换行)\n style1 = xlwt.easyxf('pattern: pattern solid, fore_colour white')\n style1.font.height = 200\n style1.font.name = u'文泉驿点阵正黑'\n style1.font.colour_index = 0\n style1.borders.left = xlwt.Borders.THIN\n style1.borders.right = xlwt.Borders.THIN\n style1.borders.top = xlwt.Borders.THIN\n style1.borders.bottom = xlwt.Borders.THIN\n # style1.font.bold = True\n style1.alignment.wrap = xlwt.Alignment.WRAP_AT_RIGHT\n style1.alignment.horz = xlwt.Alignment.HORZ_CENTER\n\n # 格式2 (没有自动换行)\n style2 = xlwt.easyxf('pattern: pattern solid, fore_colour white')\n style2.font.height = 200\n style2.font.name = u'文泉驿点阵正黑'\n style2.font.colour_index = 0\n style2.borders.left = xlwt.Borders.THIN\n style2.borders.right = xlwt.Borders.THIN\n style2.borders.top = xlwt.Borders.THIN\n style2.borders.bottom = xlwt.Borders.THIN\n # style2.font.bold = True\n # style2.alignment.wrap = xlwt.Alignment.WRAP_AT_RIGHT\n # style2.alignment.horz = xlwt.Alignment.HORZ_CENTER\n\n # 格式3 黄色背景色\n style3 = xlwt.easyxf('pattern: pattern solid, fore_colour yellow')\n style3.font.height = 200\n style3.font.name = u'文泉驿点阵正黑'\n style3.font.colour_index = 0\n # style3.borders.left = xlwt.Borders.THIN\n # style3.borders.right = xlwt.Borders.THIN\n # style3.borders.top = xlwt.Borders.THIN\n # style3.borders.bottom = xlwt.Borders.THIN\n\n # style4 格式4 0.00%\n style4 = xlwt.easyxf('pattern: pattern solid, fore_colour white')\n style4.font.height = 200\n style4.font.name = u'文泉驿点阵正黑'\n style4.font.colour_index = 0\n style4.borders.left = xlwt.Borders.THIN\n style4.borders.right = xlwt.Borders.THIN\n style4.borders.top = xlwt.Borders.THIN\n style4.borders.bottom = xlwt.Borders.THIN\n # style4.font.bold = True\n style4.alignment.wrap = xlwt.Alignment.WRAP_AT_RIGHT\n style4.alignment.horz = xlwt.Alignment.HORZ_CENTER\n style4.num_format_str = '0.00%'\n\n # style2.font.bold = True\n # style2.alignment.wrap = xlwt.Alignment.WRAP_AT_RIGHT\n # style2.alignment.horz = xlwt.Alignment.HORZ_CENTER\n # 写excel表头\n # 设置单元格\n style_dict = {\n 'style1': style1,\n 'style2': style2,\n 'style3': style3,\n 'style4': style4,\n }\n # enumerate 这是对list遍历的\n for i, val in enumerate(args):\n xlsheet.write(0, i, val, style_dict[style])\n\n number = 0\n for item in data:\n number += 1\n for j, val in enumerate(item):\n # if type(val)==str and val.startswith('http://'):\n # # xlsheet.insert_image(number, j, '/var/www/downfile/xiaogan/{}'.format(val))\n # print(val)\n # vals=val.replace('http://192.168.188.178:86/xiaogan/','')\n # # xlsheet.insert_bitmap('/var/www/downfile/xiaogan/{}'.format(vals),number,j)\n # else:\n\n\n xlsheet.write(number, j, val)\n # for j in range(0,len(item)):\n # xlsheet.write(number, j, item['j'])\n xlsname = name + utc_timestamp_to_str(int(time.time()))\n workbook_m.save('/var/www/downfile/xiaogan/{}.xls'.format(xlsname))\n return xlsname+'.xls'\n\n\n # data = [['a', 'b', 'c', 'd'], ['a', 'b', 'c', 'd'], ['a', 'b', 'c', 'd'], ['a', 'b', 'c', 'd'],\n # ['a', 'b', 'c', 'd']]\n #\n # exprort(data, 'text', 'style4', 'A', 'B', 'C', 'D')\n\ndef make_report(data, name, style, *args):\n xlsname = name + utc_timestamp_to_str(int(time.time()))\n workbook = xlsxwriter.Workbook('/var/www/downfile/xiaogan/{}.xls'.format(xlsname)) # 建立文件\n\n\n # style = xlsxwriter.XFStyle() # 初始化样式\n #\n # font = xlsxwriter.Font() # 为样式创建字体\n # font.name = 'Times New Roman' # 'Times New Roman'\n # # font.bold = bold\n # font.color_index = 4\n # font.height = 18\n\n # borders= xlwt.Borders()\n # borders.left= 6\n # borders.right= 6\n # borders.top= 6\n # borders.bottom= 6\n\n worksheet = workbook.add_worksheet(name)\n\n worksheet.set_column('A:G', 15)\n worksheet.set_column('H:H', 38)\n worksheet.set_default_row(55)\n for i, val in enumerate(args):\n worksheet.write(0, i, val)\n number = 0\n for item in data:\n number += 1\n for j, val in enumerate(item):\n if type(val)==str and val.startswith('http://'):\n vals = val.replace('http://192.168.188.178:86/xiaogan/', '')\n print(vals)\n worksheet.insert_image(number, j, '/var/www/downfile/xiaogan/{}'.format(vals),{'x_scale': 0.79, 'y_scale': 0.25})\n # print(val)\n # vals=val.replace('http://192.168.188.178:86/xiaogan/','')\n # # xlsheet.insert_bitmap('/var/www/downfile/xiaogan/{}'.format(vals),number,j)\n else:\n\n worksheet.write(number, j, val)\n\n\n # # worksheet = workbook.add_sheet('sheet1')\n # bold = workbook.add_format({'bold': True})\n\n # worksheet.write(0, 0, '开关编号',bold)\n # worksheet.write(0, 1, '开关状态',bold)\n # worksheet.write(0, 2, '事件时间',bold)\n # worksheet.write(0, 3, '线路名称',bold)\n # worksheet.write(0, 4, '站点名称',bold)\n # worksheet.write(0, 5, '类型',bold)\n # worksheet.write(0, 6, '监控图片',bold)\n #\n #\n #\n # data =Elelog.select()\n # print(data.count())\n # if starttime != None:\n # print(starttime)\n # starttime = utc_str_to_timestamp(starttime)\n # data = data.where(starttime <= Elelog.starttime)\n # if endtime != None:\n # endtime = utc_str_to_timestamp(endtime)\n # data = data.where(Elelog.starttime <= endtime)\n # if status != None:\n # data = data.where(\n # Elelog.status == int(status))\n # if line != None:\n # data = data.where(Elelog.line == line)\n #\n #\n # num = 1\n # number = 0\n # for item in data:\n # num += 1\n #\n # if num >= 0:\n # number += 1\n # worksheet.write(number, 0, item.uid)\n # worksheet.write(number, 1, item.status)\n # #什么时间格式\n # starttime= utc_timestamp_to_str(item.starttime)\n # worksheet.write(number, 2, starttime)\n # worksheet.write(number, 3, item.line)\n # worksheet.write(number, 4, item.station)\n # worksheet.write(number, 5, item.type)\n # if item.status == 0:\n # worksheet.insert_image(number, 6, '0.jpg',{'x_scale': 0.79, 'y_scale': 0.25})\n # elif item.status == 1:\n # worksheet.insert_image(number, 6, '1.jpg' ,{'x_scale': 0.79, 'y_scale': 0.25})\n\n\n workbook.close()\n # result={}\n # result['name']='{}.xlsx'.format(name)\n # result['times']=times\n return xlsname+'.xls'\n # return result","sub_path":"python-flask-server/swagger_server/controllers/xgdl_statistics.py","file_name":"xgdl_statistics.py","file_ext":"py","file_size_in_byte":56097,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"416222087","text":"import datetime\nfrom typing import Tuple\n\nfrom blist import sortedlist\nfrom elastalert.utils.util import new_get_event_ts\n\n\nclass EventWindow:\n \"\"\" A container for hold event counts for rules which need a chronological ordered event window. \"\"\"\n\n def __init__(\n self,\n timeframe: datetime.timedelta,\n on_removed: callable = None,\n get_timestamp: callable = new_get_event_ts(\"@timestamp\"),\n ):\n self.timeframe = timeframe\n self.on_removed = on_removed\n self.get_ts = get_timestamp\n self.data = sortedlist(key=self.get_ts)\n self.running_count = 0\n\n def clear(self):\n \"\"\"Clears the event window\"\"\"\n self.data = sortedlist(key=self.get_ts)\n self.running_count = 0\n\n def clean_old_events(self):\n \"\"\"Removes old events\"\"\"\n while self.data and self.duration() >= self.timeframe:\n oldest = self.data[0]\n self.data.remove(oldest)\n self.running_count -= oldest[1]\n self.on_removed and self.on_removed(oldest)\n\n def append(self, event: Tuple[dict, int]):\n \"\"\" Add an event to the window. Event should be of the form (dict, count).\n This will also pop the oldest events and call onRemoved on them until the\n window size is less than timeframe. \"\"\"\n self.data.add(event)\n self.running_count += event[1]\n self.clean_old_events()\n\n def duration(self) -> datetime.timedelta:\n \"\"\" Get the size in timedelta of the window. \"\"\"\n if not self.data:\n return datetime.timedelta(0)\n return self.get_ts(self.data[-1]) - self.get_ts(self.data[0])\n\n\nclass CountEventWindow(EventWindow):\n \"\"\" A container for hold event counts for rules which need a chronological ordered event window. \"\"\"\n\n def count(self):\n \"\"\" Count the number of events in the window. \"\"\"\n return self.running_count\n","sub_path":"elastalert/utils/event_window.py","file_name":"event_window.py","file_ext":"py","file_size_in_byte":1916,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"220644544","text":"# coding=utf-8\n# --------------------------------------------------------------------------\n# Copyright (c) Microsoft Corporation. All rights reserved.\n# Licensed under the MIT License. See License.txt in the project root for\n# license information.\n#\n# Code generated by Microsoft (R) AutoRest Code Generator.\n# Changes may cause incorrect behavior and will be lost if the code is\n# regenerated.\n# --------------------------------------------------------------------------\n\nfrom msrest.serialization import Model\n\n\nclass CreateKbDTO(Model):\n \"\"\"Post body schema for CreateKb operation.\n\n All required parameters must be populated in order to send to Azure.\n\n :param name: Required. Friendly name for the knowledgebase.\n :type name: str\n :param qna_list: List of Q-A (QnADTO) to be added to the knowledgebase.\n Q-A Ids are assigned by the service and should be omitted.\n :type qna_list:\n list[~azure.cognitiveservices.knowledge.qnamaker.models.QnADTO]\n :param urls: List of URLs to be used for extracting Q-A.\n :type urls: list[str]\n :param files: List of files from which to Extract Q-A.\n :type files:\n list[~azure.cognitiveservices.knowledge.qnamaker.models.FileDTO]\n :param enable_hierarchical_extraction: Enable hierarchical extraction of\n Q-A from files and urls. Value to be considered False if this field is not\n present.\n :type enable_hierarchical_extraction: bool\n :param default_answer_used_for_extraction: Text string to be used as the\n answer in any Q-A which has no extracted answer from the document but has\n a hierarchy. Required when EnableHierarchicalExtraction field is set to\n True.\n :type default_answer_used_for_extraction: str\n :param language: Language of the knowledgebase. Please find the list of\n supported languages here.\n :type language: str\n :param enable_multiple_languages: Set to true to enable creating KBs in\n different languages for the same resource.\n :type enable_multiple_languages: bool\n :param default_answer: Default answer sent to user if no good match is\n found in the KB.\n :type default_answer: str\n \"\"\"\n\n _validation = {\n 'name': {'required': True, 'max_length': 100, 'min_length': 1},\n 'default_answer_used_for_extraction': {'max_length': 300, 'min_length': 1},\n 'language': {'max_length': 100, 'min_length': 1},\n 'default_answer': {'max_length': 300, 'min_length': 1},\n }\n\n _attribute_map = {\n 'name': {'key': 'name', 'type': 'str'},\n 'qna_list': {'key': 'qnaList', 'type': '[QnADTO]'},\n 'urls': {'key': 'urls', 'type': '[str]'},\n 'files': {'key': 'files', 'type': '[FileDTO]'},\n 'enable_hierarchical_extraction': {'key': 'enableHierarchicalExtraction', 'type': 'bool'},\n 'default_answer_used_for_extraction': {'key': 'defaultAnswerUsedForExtraction', 'type': 'str'},\n 'language': {'key': 'language', 'type': 'str'},\n 'enable_multiple_languages': {'key': 'enableMultipleLanguages', 'type': 'bool'},\n 'default_answer': {'key': 'defaultAnswer', 'type': 'str'},\n }\n\n def __init__(self, *, name: str, qna_list=None, urls=None, files=None, enable_hierarchical_extraction: bool=None, default_answer_used_for_extraction: str=None, language: str=None, enable_multiple_languages: bool=None, default_answer: str=None, **kwargs) -> None:\n super(CreateKbDTO, self).__init__(**kwargs)\n self.name = name\n self.qna_list = qna_list\n self.urls = urls\n self.files = files\n self.enable_hierarchical_extraction = enable_hierarchical_extraction\n self.default_answer_used_for_extraction = default_answer_used_for_extraction\n self.language = language\n self.enable_multiple_languages = enable_multiple_languages\n self.default_answer = default_answer\n","sub_path":"sdk/cognitiveservices/azure-cognitiveservices-knowledge-qnamaker/azure/cognitiveservices/knowledge/qnamaker/models/create_kb_dto_py3.py","file_name":"create_kb_dto_py3.py","file_ext":"py","file_size_in_byte":3949,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"152871884","text":"\"\"\"This script was set up to run and plot different interventions.\"\"\"\nimport copy\nimport os\n\nimport matplotlib.pyplot as plt\nimport numpy as np\n\nfrom main import params_vec_to_dict, initialize_region_list, excel_to_region_list, opioid_system\nfrom Parameter_Search.run_search import region_lists, num_regions\n\nsubdirectory = os.path.dirname(os.path.dirname(__file__))\n\ndef float_range(start, stop, step):\n \"\"\"Alternative to range, allows for float values at 'step' increments between start an stop\"\"\"\n float_list = []\n i = start\n while i <= stop:\n float_list.append(i)\n i += step\n return float_list\n\n\ndef calculate_params(t, time_divisions, parameter_list):\n \"\"\"Determines the parameters based on the current time. Necessary to accommodate for different \"\"\"\n params = np.empty_like(parameter_list[0])\n if t == time_divisions[0][0]:\n params = parameter_list[0]\n elif t == time_divisions[-1][1]:\n params = parameter_list[-1]\n else:\n for increment in time_divisions:\n if t >= increment[0] and t < increment[1]:\n index = time_divisions.index(increment)\n if index == (len(time_divisions)-1):\n params = parameter_list[-1]\n else:\n params = parameter_list[index]\n params = params_vec_to_dict(params)\n return params\n\n\ndef run_system(region_list, time_divisions, dt, parameter_list):\n \"\"\"Accepts region data in the form of a list of region objects, the initial year, final year, desired time step,\n and parameters. Differs from the region list in main because it returns misuse population, heroin population, etc.\"\"\"\n initial_year = time_divisions[0][0]\n if len(time_divisions[-1]) == 2:\n final_year = time_divisions[-1][1]\n else:\n final_year = time_divisions[-1][0]\n\n timelist = float_range(initial_year, final_year, dt)\n for i in range(len(timelist)):\n params = calculate_params(i, time_divisions, parameter_list)\n for region in region_list:\n pop_growth = (region.end_population - region.start_population)/len(timelist)\n misuse_adjacents = sum(element.rlist[i] for element in region.neighbors)\n misuse_adjacent_susceptibles = sum(\n element.ulist[i] + element.vlist[i] + element.wlist[i] for element in region.neighbors)\n heroin_adjacents = sum(element.slist[i] for element in region.neighbors)\n heroin_adjacent_susceptibles = sum(\n element.ulist[i] + element.vlist[i] + element.wlist[i] + element.rlist[i] for element in\n region.neighbors)\n population = region.ulist[i] + region.vlist[i] + region.wlist[i] + region.rlist[i] + region.slist[i]\n opioid_system(region, region.ulist[i], region.vlist[i], region.wlist[i], region.rlist[i], region.slist[i],\n region.xlist[i], region.zlist[i], misuse_adjacents, misuse_adjacent_susceptibles,\n heroin_adjacent_susceptibles, heroin_adjacents, params, population, dt, pop_growth)\n deaths_by_region = {}\n misuse_by_region = {}\n heroin_by_region = {}\n for region in region_list:\n deaths_by_region[region.name] = region.totdeath\n misuse_by_region[region.name] = region.rlist\n heroin_by_region[region.name] = region.slist\n output = [deaths_by_region, misuse_by_region, heroin_by_region]\n return output\n\n\n\ndef run(state, years, intervention_years, dt, params, intervention_params, proportions):\n \"\"\"Runs the model with and without interventions\"\"\"\n region_list_with_intervention = excel_to_region_list(subdirectory + region_lists[state], num_regions[state])\n region_list_without_intervention = excel_to_region_list(subdirectory + region_lists[state], num_regions[state])\n\n region_list_with_intervention = initialize_region_list(region_list_with_intervention, proportions)\n region_list_without_intervention = initialize_region_list(region_list_without_intervention, proportions)\n\n region_with_intervention = run_system(region_list_with_intervention, intervention_years,\n dt, intervention_params)\n region_without_intervention = run_system(region_list_without_intervention, years, dt, params)\n return region_with_intervention, region_without_intervention\n\n\ndef quantify_interventions(region_with_intervention, region_without_intervention):\n \"\"\"Given two region lists, one with interventions and one without, compares the system and returns change in deaths,\n misuse, heroin use, and the respective percentage changes\"\"\"\n deaths_by_region_with_intervention = region_with_intervention[0]\n misuse_with_intervention = region_with_intervention[1]\n heroin_with_intervention = region_with_intervention[2]\n\n deaths_by_region_without_intervention = region_without_intervention[0]\n misuse_without_intervention = region_without_intervention[1]\n heroin_without_intervention = region_without_intervention[2]\n\n\n with_intervention_death_sum = 0\n with_intervention_misuse_sum= 0\n with_intervention_heroin_sum = 0\n without_intervention_death_sum = 0\n without_intervention_misuse_sum= 0\n without_intervention_heroin_sum = 0\n for region in deaths_by_region_with_intervention.keys():\n with_intervention_death_sum += deaths_by_region_with_intervention[region][-1]\n with_intervention_misuse_sum += misuse_with_intervention[region][-1]\n with_intervention_heroin_sum += heroin_with_intervention[region][-1]\n\n without_intervention_death_sum += deaths_by_region_without_intervention[region][-1]\n without_intervention_misuse_sum += misuse_without_intervention[region][-1]\n without_intervention_heroin_sum += heroin_without_intervention[region][-1]\n change_deaths = with_intervention_death_sum - without_intervention_death_sum\n percent_change_death = (with_intervention_death_sum - without_intervention_death_sum)*100/ without_intervention_death_sum\n change_misuse = with_intervention_misuse_sum - without_intervention_misuse_sum\n percent_change_misuse = (with_intervention_misuse_sum - without_intervention_misuse_sum)*100 / without_intervention_misuse_sum\n change_heroin = with_intervention_heroin_sum - without_intervention_heroin_sum\n percent_change_heroin = (with_intervention_heroin_sum - without_intervention_heroin_sum)*100 / without_intervention_heroin_sum\n return change_deaths, percent_change_death, change_misuse, percent_change_misuse, change_heroin, percent_change_heroin\n\n\n\ndef run_and_plot(state, years, intervention_years, dt, params, intervention_params, proportions):\n \"\"\"Will run and plot the interventions; however, if using this function it will be necessary to change the\n plotting parameters below\"\"\"\n region_with_intervention, region_without_intervention = run(state, years, intervention_years,\n dt, params, intervention_params,\n proportions)\n deaths_by_region_with_intervention = region_with_intervention[0]\n deaths_by_region_without_intervention = region_without_intervention[0]\n num_deaths, percent_change_death, num_misuse, percent_change_misuse, num_heroin, percent_change_heroin = \\\n quantify_interventions(region_with_intervention, region_without_intervention)\n print(intervention_years)\n\n summed_deaths = np.zeros(intervention_years[-1][1] - years[0][0]+1)\n for i in range(len(summed_deaths)):\n sum = 0\n for key in deaths_by_region_with_intervention.keys():\n sum += deaths_by_region_with_intervention[key][i]\n summed_deaths[i] = sum\n\n #PRINT OUT METRICS\n print( 'num deaths', num_deaths )\n print( '% change death', percent_change_death)\n print( 'num_misuse', num_misuse)\n print('% change misuse', percent_change_misuse)\n print( 'num_heroin', num_heroin)\n print('% change heroin', percent_change_heroin)\n\n #PLOT\n fig = plt.figure()\n ax = fig.add_axes([0.1, 0.1, 0.6, 0.75])\n year_float = float_range(years[0][0]+2000, years[-1][1]+2000, dt) #MAY NEED TO CHANGE THE 2000 HERE\n for region in deaths_by_region_with_intervention.keys():\n color = np.random.rand(3, )\n ax.plot(year_float, deaths_by_region_with_intervention[region], c=color, ls='-', label=region)\n ax.plot(year_float, deaths_by_region_without_intervention[region], c=color, ls='--')\n\n ax.legend(bbox_to_anchor=(1.05, 1), ncol=1, loc=2, borderaxespad=0., fontsize='x-large')\n ax.set_xlabel('Year', size=20)\n ax.set_ylabel('Opioid Related Deaths', size=20)\n plt.axis([2000,2025,0,3500]) #MAY NEED TO CHANGE THE BOUNDS HERE\n\n plt.show()\n\n\n\ndef calculate_intervention_parameters(parameter_vector, intervention_parameter_adjustment):\n \"\"\"Adjusts the parameter vector to accommodate intervention values.\n Parameter_vector : list of floats\n Intervention_parameter_adjustment: string indices with adjustment proportion\"\"\"\n new_params = copy.copy(parameter_vector)\n parameter_key = intervention_parameter_adjustment.keys()\n for key in parameter_key:\n if key == 'ap':\n new_params[0] = new_params[0] * intervention_parameter_adjustment[key]\n if key == 'cp':\n new_params[1] = new_params[1] * intervention_parameter_adjustment[key]\n if key == 'hr':\n new_params[2] = new_params[2] * intervention_parameter_adjustment[key]\n if key == 'mr':\n new_params[3] = new_params[3] * intervention_parameter_adjustment[key]\n if key == 'amt':\n new_params[4] = new_params[4] * intervention_parameter_adjustment[key]\n if key == 'ct':\n new_params[5] = new_params[5] * intervention_parameter_adjustment[key]\n if key == 'cmt':\n new_params[6] = new_params[6] * intervention_parameter_adjustment[key]\n if key == 'hor':\n new_params[7] = new_params[7] * intervention_parameter_adjustment[key]\n if key == 'mor':\n new_params[8] = new_params[8] * intervention_parameter_adjustment[key]\n if key == 'hs':\n new_params[9] = new_params[9] * intervention_parameter_adjustment[key]\n if key == 'ms':\n new_params[10] = new_params[10] * intervention_parameter_adjustment[key]\n if key == 'ds':\n new_params[11] = new_params[11] * intervention_parameter_adjustment[key]\n if key == 'ri':\n new_params[12] = new_params[12] * intervention_parameter_adjustment[key]\n return new_params\n\n\ndef run_and_plot_interventions(state, years, dt, params, proportions, intervention_parameter_adjustment,\n intervention_years):\n print(years)\n\n new_params = calculate_intervention_parameters(params[-1], intervention_parameter_adjustment)\n intervention_params = params + [new_params]\n intervention_years = copy.copy(years) + [copy.copy(intervention_years)]\n print(intervention_years)\n new_years = copy.copy(years)\n new_years[-1][1]= intervention_years[-1][1]\n run_and_plot(state, new_years, intervention_years, dt, params, intervention_params, proportions)\n\n\n\ndef plot_multi_interventions(intervention_dict, years):\n \"\"\"Plots multiple interventions, stored in a dictionary. Dictionaries have labels as the keys and adjusted\n parameters as values\"\"\"\n fig = plt.figure()\n ax = fig.add_axes([0.1, 0.1, 0.6, 0.75])\n year_range = range(years[0], years[1])\n colors = ['lime', 'blue', 'orangered', 'magenta', 'gold', 'cyan']\n color_index =0\n for intervention in intervention_dict.keys():\n color = colors[color_index]\n ax.plot(year_range, intervention_dict[intervention], c=color, ls='-', label=intervention, linewidth=2.5)\n color_index +=1\n\n ax.legend(bbox_to_anchor=(1.03, 1), ncol=1, loc=2, borderaxespad=0., fontsize='x-large')\n ax.set_xlabel('Year', size=30)\n ax.set_ylabel('Opioid Related Deaths', size=30)\n ax.tick_params(axis='both', labelsize=20)\n plt.show()\n\n\nif __name__ == \"__main__\":\n ###PARAMETERS AND INTERVENTIONS BELOW DEPENDENT UPON ANTIQUATED PARAMETERS\n state = 'Mass'\n years = [[0, 11], [12, 17]]\n params1 = [0.050854915254237291, 0.016958305084745762, 0.1186528813559322, 0.44068355932203396, 0.04238203389830509,\n 0.45762796610169493, 0.059330847457627116, 0.016958983050847459, 1.0000000000000001e-05,\n 3813.7966101694915,\n 2644.1864406779659, 0.22034677966101698, 0.77966322033898305]\n params2 = [0.16271372881355933, 0.10508949152542373, 0.033907966101694921, 0.33898966101694922,\n 0.0084844067796610162,\n 0.35593508474576269, 0.050856440677966103, 1.0000000000000001e-05, 0.033907966101694921, 1.0,\n 560.13559322033893, 0.44068355932203396, 0.033907966101694921]\n params = [params1, params2]\n proportions = [0.10218644067796612, 0.17638983050847459, 0.003399491525423729, 0.076273559322033904]\n dt = 1\n intervention_parameter_adjustment = {'mr': 1.5, 'hr': 1.5}\n intervention_years = [18, 25]\n\n\n\n run_and_plot_interventions(state, years, dt, params, proportions, intervention_parameter_adjustment,\n intervention_years)\n\"\"\"\n intervention_dict = {'50% reduction in acute prescriptions': [369.87248122, 399.39991623, 431.66045787,\n 467.20231498, 506.12754712, 548.59503991, 594.81342612,\n 562.87574014, 556.53454772, 541.23283661, 532.10138619,\n 522.47889239, 573.92776441, 785.01485144, 1272.27157836,\n 1371.03139168, 1529.17044983, 1554.54394717,\n 1582.09884325, 1581.12200301, 1472.39113022,\n 1570.14405754, 1534.13153587, 1529.77009562,\n 1502.23313231, 1475.61015036],\n '50% reduction in chronic prescriptions': [369.87248122, 399.39991623, 431.66045787,\n 467.20231498, 506.12754712, 548.59503991,\n 594.81342612, 562.87574014, 556.53454772,\n 541.23283661, 532.10138619, 522.47889239,\n 573.92776441, 785.01485144, 1272.27157836,\n 1371.03139168, 1529.17044983, 1554.54394717,\n 1582.09884325, 1581.12200301, 1178.23872749,\n 1113.1760919, 1008.26816181, 966.34308548,\n 927.04392723, 900.32625103],\n '50% increase treatment effectiveness/access': [369.87248122, 399.39991623, 431.66045787,\n 467.20231498, 506.12754712,\n 548.59503991, 594.81342612, 562.87574014,\n 556.53454772, 541.23283661,\n 532.10138619, 522.47889239, 573.92776441,\n 785.01485144,\n 1272.27157836, 1371.03139168, 1529.17044983,\n 1554.54394717,\n 1582.09884325, 1313.1238007, 1451.79364269,\n 1361.96828795,\n 1387.48970186, 1347.12343035, 1338.20311648,\n 1309.6580502],\n '50% decrease in overdose risk': [369.87248122, 399.39991623, 431.66045787, 467.20231498,\n 506.12754712, 548.59503991, 594.81342612, 562.87574014,\n 556.53454772, 541.23283661, 532.10138619, 522.47889239,\n 573.92776441, 785.01485144, 1272.27157836, 1371.03139168,\n 1529.17044983, 1554.54394717, 791.04942163, 803.96358594,\n 795.9646524, 790.32207727, 780.36809275, 769.18869454,\n 756.18665873, 741.84046459],\n '200% increase in acute prescriptions': [369.87248122, 399.39991623, 431.66045787, 467.20231498,\n 506.12754712, 548.59503991, 594.81342612, 562.87574014,\n 556.53454772, 541.23283661, 532.10138619, 522.47889239,\n 573.92776441, 785.01485144, 1272.27157836,\n 1371.03139168, 1529.17044983, 1554.54394717,\n 1582.09884325, 3161.97057641, 1395.45925499,\n 1563.64390403, 1619.87139155, 1430.16210277,\n 1515.33326628, 1411.6776189],\n '200% increase in chronic prescriptions': [369.87248122, 399.39991623, 431.66045787,\n 467.20231498, 506.12754712, 548.59503991,\n 594.81342612, 562.87574014, 556.53454772,\n 541.23283661, 532.10138619, 522.47889239,\n 573.92776441, 785.01485144, 1272.27157836,\n 1371.03139168, 1529.17044983, 1554.54394717,\n 1582.09884325, 3161.97057641, 2572.30991638,\n 3133.76154788, 3082.66986178, 3091.98209732,\n 3042.52600773, 2984.30893713]}\n plot_multi_interventions(intervention_dict, [2000,2026])\n\"\"\"","sub_path":"Intervention/intervention_plots.py","file_name":"intervention_plots.py","file_ext":"py","file_size_in_byte":19261,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"430374519","text":"# coding=utf-8\nimport tornado.httpserver\nimport tornado.ioloop\nimport tornado.options\nimport tornado.web\nfrom tornado.options import define, options\nfrom ocs.OCSClient import OCSClient\nfrom ocs.OSCConfig import OCSConfig\nfrom get_history_data import get_qc_by_udid\n\ndefine(\"port\", default=12345, help=\"run on the given port\", type=int)\n\nocs_client = OCSClient()\nocs_client.set_config(OCSConfig())\nocs_client.init_mc()\n\nclass IndexHandler(tornado.web.RequestHandler):\n\n # ocs_client = OCSClient()\n # ocs_client.set_config(OCSConfig())\n\n def get(self):\n post_data = {}\n for key in self.request.arguments:\n post_data[key] = self.get_arguments(key)\n udid = post_data['udid'][0]\n city_id = post_data['city_id'][0]\n qc = get_qc_by_udid(ocs_client, city_id, udid)\n # print type(qc)\n data_list = []\n for data in qc.data_lists:\n j_data = {}\n j_data['cityId'] = data.city_id\n j_data['lineId'] = data.line_id\n j_data['lineNo'] = data.line_no\n j_data['stopId'] = data.stop_id\n j_data['stationName'] = data.stop_name\n j_data['targetOrder'] = data.order\n j_data['lng'] = data.lng\n j_data['lat'] = data.lat\n j_data['targetOrder'] = data.target_order\n j_data['segment'] = data.time_segment\n j_data['workday'] = data.is_workday\n j_data['count'] = data.count\n j_data['countDetail'] = data.count_detail\n j_data['account_id'] = data.account_id\n data_list.append(j_data)\n\n result = {'udid': udid, 'data': data_list}\n self.write(result)\n\nif __name__ == \"__main__\":\n tornado.options.parse_command_line()\n app = tornado.web.Application(handlers=[(r\"/\", IndexHandler)])\n http_server = tornado.httpserver.HTTPServer(app)\n http_server.listen(options.port)\n tornado.ioloop.IOLoop.instance().start()\n","sub_path":"ocs_server.py","file_name":"ocs_server.py","file_ext":"py","file_size_in_byte":1952,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"91648931","text":"earning = int(input(\"Выручка: \"))\ncosts = int(input(\"Издержки: \"))\n\nif costs > earning:\n print(\"Убыток.\")\nelif earning > costs:\n print(\"Прибыль.\")\n profitability = round((earning - costs) / earning, 2)\n print(f\"Рентабельность: {profitability}\")\n empl_count = int(input(\"Количество штатных сотрудников: \"))\n profit_per_empl = round((earning - costs) / empl_count, 2)\n print(f\"Прибыль фирмы в расчете на одного сотрудника:{profit_per_empl}\")\nelif earning == costs:\n print(\"Финансовый результат = 0\")\n","sub_path":"hw5.py","file_name":"hw5.py","file_ext":"py","file_size_in_byte":649,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"199032611","text":"import xml.etree.ElementTree as et\nimport os, sys\n\nif __name__ == '__main__':\n if (len(sys.argv)!=2):\n print(\"usage: p.py file.xml\")\n filepath = sys.argv[1]\n root = et.parse(filepath).getroot()\n tagnames = set()\n for n in root.iter():\n if not(n.tag in tagnames):\n tagnames.add(n.tag)\n print(\"tag: \" + n.tag)\n","sub_path":"print_tags.py","file_name":"print_tags.py","file_ext":"py","file_size_in_byte":359,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"514030283","text":"num = int(input(\"ENTER NUMBER\"))\npower = int(input(\"ENTER THE POWER\"))\nnum1= num\nwhile(power-1>0):\n\tnum1 = num*num1 \n\tpower = power -1\n\nprint(num1)\n\n'''dpl4-5@dpl45-ThinkCentre-M72e:~/Desktop$ python3 power.py\nENTER NUMBER5\nENTER THE POWER3\n125'''\n\n","sub_path":"Python Clg/COLLEGE/Exp2/power.py","file_name":"power.py","file_ext":"py","file_size_in_byte":250,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"203009503","text":"# Copyright 2016 Google Inc.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nfrom Area import DerivedArea\nfrom File import File\nfrom imagelib.tools.GbbUtility import GbbUtility\nfrom imagelib.tools.Tool import FileHarness\n\nimport binascii\n\nclass Gbb(DerivedArea):\n # The flags in this dictionary will be turned into independent members of\n # the class programatically after the class definition is complete.\n AllFlags = {\n \"DevScreenShortDelay\": 0x00000001,\n \"LoadOptionRoms\": 0x00000002,\n \"EnableAlternateOs\": 0x00000004,\n \"ForceDevSwitchOn\": 0x00000008,\n \"ForceDevBootUsb\": 0x00000010,\n \"DisableFwRollbackCheck\": 0x00000020,\n \"EnterTriggersTonorm\": 0x00000040,\n \"ForceDevBootLegacy\": 0x00000080,\n \"FaftKeyOverride\": 0x00000100,\n \"DisableEcSoftwareSync\": 0x00000200,\n \"DefaultDevBootLegacy\": 0x00000400,\n \"DisablePdSoftwareSync\": 0x00000800,\n \"ForceDevBootFastbootFullCap\": 0x00002000,\n }\n\n\n @staticmethod\n def hwid(hwid):\n checksum = (binascii.crc32(hwid) & 0xffffffff) % 10000\n return \"%s %d\" % (hwid, checksum)\n\n def __init__(self, hwid, flags=None, bmpfv=None,\n rootkey=None, recoverykey=None):\n self._hwid = hwid\n if flags is None:\n flags = 0\n self._flags = flags\n if bmpfv is None:\n bmpfv = File(\"bmpblk.bin\")\n self._bmpfv = bmpfv\n if rootkey is None:\n rootkey = File(\"root_key.vbpubk\")\n self._rootkey = rootkey\n if recoverykey is None:\n recoverykey = File(\"recovery_key.vbpubk\")\n self._recoverykey = recoverykey\n\n self._data = None\n\n super(Gbb, self).__init__(bmpfv, rootkey, recoverykey)\n\n def write(self):\n gbb_utility = GbbUtility()\n with FileHarness(None, self._bmpfv.write(), self._rootkey.write(),\n self._recoverykey.write()) as files:\n gbb, bmpfv, rootkey, recoverykey = files\n sizes = [0x100, 0x1000, self.placed_size - 0x2180, 0x1000]\n gbb_utility.create(sizes, gbb)\n gbb_utility.set(self._hwid, self._flags, bmpfv,\n rootkey, recoverykey)\n\n with open(gbb, \"rb\") as data:\n return data.read()\n\n def log_get_additional_properties(self):\n props = [\"hwid=\\\"%s\\\"\" % self._hwid]\n props.extend([name for name, val in Gbb.AllFlags.iteritems()\n if val & self._flags])\n return props\n\n def log_area_content(self, indent):\n child_areas = {\n \"Bitmap block\": self._bmpfv,\n \"Root key\": self._rootkey,\n \"Recovery key\": self._recoverykey,\n }\n return self.log_child_props(indent, child_areas)\n\nfor name, val in Gbb.AllFlags.iteritems():\n setattr(Gbb, name, val)\n","sub_path":"src/image/imagelib/components/Gbb.py","file_name":"Gbb.py","file_ext":"py","file_size_in_byte":3365,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"487741071","text":"import random, os\ndef get_word():\n words = open(\"./files/data.txt\", encoding=\"utf-8\").read().splitlines()\n return random.choice(words) \n\n\ndef print_word(word):\n simbols = \"\"\n for letter in word:\n simbols = simbols + \" _ \"\n print(simbols)\n\ndef print_aux_word(aux_word): \n word = \"\"\n for letter in aux_word: \n if letter == \" _ \":\n word = word + \" _ \"\n else:\n word = word + letter\n print(word + \"\\n\")\n\n\n\ndef get_letter():\n letter = input(\"Enter a letter, please:\")\n while (len(letter) >1) or (letter.isnumeric()):\n print(\"Only one letter and no numbers\")\n letter = input(\"Enter a letter, please:\")\n return letter\n\n\ndef is_letter_in_word(word, letter, aux_word):\n for i in range(len(word)):\n if word[i] == letter:\n aux_word[i] = letter \n return aux_word \n\n\ndef is_word_guessed(word, aux_word):\n for letter in word:\n if letter not in aux_word:\n return False\n print(\"You guessed the word!\")\n\n\ndef run():\n os.system(\"clear\")\n print(\"----------------\")\n print(\"WELCOME TO MELERO'S HANGMAN GAME\") \n word = get_word() \n aux_word = [\" _ \" for i in range(0, len(word))]\n print(len(aux_word))\n print_word(word)\n print(\"\\n\")\n while is_word_guessed(word,aux_word) == False:\n letter = get_letter()\n aux_word = is_letter_in_word(word, letter, aux_word) \n print_aux_word(aux_word)\n \n \n\n\n\n\n\nif __name__ == '__main__':\n run()","sub_path":"hangman.py","file_name":"hangman.py","file_ext":"py","file_size_in_byte":1553,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"184597811","text":"import numpy as np\nimport warnings\nimport h5py\n\nimport astropy.units as u\nimport astropy.constants as consts\nfrom astropy.io import fits\nfrom astropy.time import Time\nfrom astropy._erfa.core import ErfaWarning\n\nimport matplotlib as mpl\nimport matplotlib.pyplot as plt\nfrom matplotlib.collections import LineCollection\nimport matplotlib.colors as colors\n\nimport corner\n\nimport orbitize.kepler as kepler\nimport orbitize.system\n\n\n# define modified color map for default use in orbit plots\ncmap = mpl.cm.Purples_r\ncmap = colors.LinearSegmentedColormap.from_list(\n 'trunc({n},{a:.2f},{b:.2f})'.format(n=cmap.name, a=0.0, b=0.7),\n cmap(np.linspace(0.0, 0.7, 1000.))\n)\n\nclass Results(object):\n \"\"\"\n A class to store accepted orbital configurations from the sampler\n\n Args:\n sampler_name (string): name of sampler class that generated these results (default: None).\n post (np.array of float): MxN array of orbital parameters\n (posterior output from orbit-fitting process), where M is the\n number of orbits generated, and N is the number of varying orbital\n parameters in the fit (default: None).\n lnlike (np.array of float): M array of log-likelihoods corresponding to\n the orbits described in ``post`` (default: None).\n tau_ref_epoch (float): date (in days, typically MJD) that tau is defined relative to\n\n The ``post`` array is in the following order::\n\n semimajor axis 1, eccentricity 1, inclination 1,\n argument of periastron 1, position angle of nodes 1,\n epoch of periastron passage 1,\n [semimajor axis 2, eccentricity 2, etc.],\n [parallax, total mass]\n\n where 1 corresponds to the first orbiting object, 2 corresponds\n to the second, etc.\n\n Written: Henry Ngo, Sarah Blunt, 2018\n \"\"\"\n def __init__(self, sampler_name=None, post=None, lnlike=None, tau_ref_epoch=None):\n self.sampler_name = sampler_name\n self.post = post\n self.lnlike = lnlike\n self.tau_ref_epoch = tau_ref_epoch\n\n def add_samples(self, orbital_params, lnlikes):\n \"\"\"\n Add accepted orbits and their likelihoods to the results\n\n Args:\n orbital_params (np.array): add sets of orbital params (could be multiple) to results\n lnlike (np.array): add corresponding lnlike values to results\n\n Written: Henry Ngo, 2018\n \"\"\"\n # If no exisiting results then it is easy\n if self.post is None and self.lnlike is None:\n self.post = orbital_params\n self.lnlike = lnlikes\n # Otherwise, need to append properly\n else:\n self.post = np.vstack((self.post,orbital_params))\n self.lnlike = np.append(self.lnlike,lnlikes)\n\n def _set_sampler_name(self, sampler_name):\n \"\"\"\n internal method to set object's sampler_name attribute\n \"\"\"\n self.sampler_name = sampler_name\n\n def save_results(self, filename, format='hdf5'):\n \"\"\"\n Save results.Results object to a file\n\n Args:\n filename (string): filepath to save to\n format (string): either \"hdf5\" (default), or \"fits\"\n\n Both formats (HDF5 and FITS) save the ``sampler_name``, ``post``, and ``lnlike``\n attributes from the ``results.Results`` object. Note that currently, only the\n MCMC sampler has the ``lnlike`` attribute set. For OFTI, ``lnlike`` is None and\n it is not saved.\n\n HDF5: ``sampler_name`` and ``tau_ref_epcoh`` are attributes of the root group.\n ``post`` and ``lnlike`` are datasets that are members of the root group.\n\n FITS: Data is saved as Binary FITS Table to the *first extension* HDU.\n After reading with something like ``hdu = astropy.io.fits.open(file)``,\n ``hdu[1].header['SAMPNAME']`` returns the ``sampler_name``.\n ``hdu[1].header['TAU_REF']`` returns the ``tau_ref_epoch``.\n ``hdu[1].data`` returns a ``Table`` with two columns. The first column\n contains the post array, and the second column contains the lnlike array\n\n Written: Henry Ngo, 2018\n \"\"\"\n if format.lower()=='hdf5':\n hf = h5py.File(filename,'w') # Creates h5py file object\n # Add sampler_name as attribute of the root group\n hf.attrs['sampler_name']=self.sampler_name\n hf.attrs['tau_ref_epoch'] = self.tau_ref_epoch\n # Now add post and lnlike from the results object as datasets\n hf.create_dataset('post', data=self.post)\n if self.lnlike is not None: # This property doesn't exist for OFTI\n hf.create_dataset('lnlike', data=self.lnlike)\n hf.close() # Closes file object, which writes file to disk\n elif format.lower()=='fits':\n n_params = self.post.shape[1]\n # Create column from post array. Each cell is a 1-d array of n_params length\n post_format_string = '{}D'.format(n_params) # e.g. would read '8D' for 8 parameter fit\n col_post = fits.Column(name='post', format=post_format_string, array=self.post)\n if self.lnlike is not None: # This property doesn't exist for OFTI\n # Create lnlike column\n col_lnlike = fits.Column(name='lnlike', format='D', array=self.lnlike)\n # Create the Binary Table HDU\n hdu = fits.BinTableHDU.from_columns([col_post,col_lnlike])\n else:\n # Create the Binary Table HDU\n hdu = fits.BinTableHDU.from_columns([col_post])\n # Add sampler_name to the hdu's header\n hdu.header['SAMPNAME'] = self.sampler_name\n hdu.header['TAU_REF'] = self.tau_ref_epoch\n # Write to fits file\n hdu.writeto(filename)\n else:\n raise Exception('Invalid format {} for Results.save_results()'.format(format))\n\n def load_results(self, filename, format='hdf5', append=False):\n \"\"\"\n Populate the ``results.Results`` object with data from a datafile\n\n Args:\n filename (string): filepath where data is saved\n format (string): either \"hdf5\" (default), or \"fits\"\n append (boolean): if True, then new data is added to existing object.\n If False (default), new data overwrites existing object\n\n See the ``save_results()`` method in this module for information on how the\n data is structured.\n\n Written: Henry Ngo, 2018\n \"\"\"\n if format.lower()=='hdf5':\n hf = h5py.File(filename,'r') # Opens file for reading\n # Load up each dataset from hdf5 file\n sampler_name = np.str(hf.attrs['sampler_name'])\n post = np.array(hf.get('post'))\n lnlike = np.array(hf.get('lnlike'))\n # get the tau reference epoch\n try:\n tau_ref_epoch = float(hf.attrs['tau_ref_epoch'])\n except KeyError:\n # probably a old results file when reference epoch was fixed at MJD = 0\n tau_ref_epoch = 0\n\n hf.close() # Closes file object\n elif format.lower()=='fits':\n hdu_list = fits.open(filename) # Opens file as HDUList object\n table_hdu = hdu_list[1] # Table data is in first extension\n\n # Get sampler_name from header\n sampler_name = table_hdu.header['SAMPNAME']\n\n # get tau reference epoch\n if 'TAU_REF' in table_hdu.header:\n tau_ref_epoch = table_hdu.header['TAU_REF']\n else:\n # this is most likely an older results file where it was fixed to MJD=0\n tau_ref_epoch = 0\n\n # Get post and lnlike arrays from column names\n post = table_hdu.data.field('post')\n # (Note: OFTI does not have lnlike so it won't be saved)\n if 'lnlike' in table_hdu.data.columns.names:\n lnlike = table_hdu.data.field('lnlike')\n else:\n lnlike = None\n # Closes HDUList object\n hdu_list.close()\n else:\n raise Exception('Invalid format {} for Results.load_results()'.format(format))\n\n # Adds loaded data to object as per append keyword\n if append:\n # if no sampler_name set, use the input file's value\n if self.sampler_name is None:\n self._set_sampler_name(sampler_name)\n # otherwise only proceed if the sampler_names match\n elif self.sampler_name != sampler_name:\n raise Exception('Unable to append file {} to Results object. sampler_name of object and file do not match'.format(filename))\n\n # if no tau reference epoch is set, use input file's value\n if self.tau_ref_epoch is None:\n self.tau_ref_epoch = tau_ref_epoch\n # otherwise, only proceed if they are identical\n elif self.tau_ref_epoch != tau_ref_epoch:\n raise ValueError(\"Loaded data has tau reference epoch of {0} while Results object has already been initialized to {1}\".format(tau_ref_epoch, self.tau_ref_epoch))\n\n # Now append post and lnlike\n self.add_samples(post,lnlike)\n else:\n # Only proceed if object is completely empty\n if self.sampler_name is None and self.post is None and self.lnlike is None and self.tau_ref_epoch is None:\n self._set_sampler_name(sampler_name)\n self.add_samples(post,lnlike)\n self.tau_ref_epoch = tau_ref_epoch\n else:\n raise Exception('Unable to load file {} to Results object. append is set to False but object is not empty'.format(filename))\n\n\n def plot_corner(self, param_list=[], **corner_kwargs):\n \"\"\"\n Make a corner plot of posterior on orbit fit from any sampler\n\n Args:\n param_list (list of strings): each entry is a name of a parameter to include.\n Valid strings::\n\n sma1: semimajor axis\n ecc1: eccentricity\n inc1: inclination\n aop1: argument of periastron\n pan1: position angle of nodes\n epp1: epoch of periastron passage\n [repeat for 2, 3, 4, etc if multiple objects]\n mtot: total mass\n plx: parallax\n\n **corner_kwargs: any remaining keyword args are sent to ``corner.corner``.\n See `here `_.\n Note: default axis labels used unless overwritten by user input.\n\n Return:\n ``matplotlib.pyplot.Figure``: corner plot\n\n .. Note:: **Example**: Use ``param_list = ['sma1,ecc1,inc1,sma2,ecc2,inc2']`` to only\n plot posteriors for semimajor axis, eccentricity and inclination\n of the first two companions\n\n Written: Henry Ngo, 2018\n \"\"\"\n # Define a dictionary to look up index of certain parameters\n dict_of_indices = {\n 'sma': 0,\n 'ecc': 1,\n 'inc': 2,\n 'aop': 3,\n 'pan': 4,\n 'epp': 5\n }\n # Define array of default axis labels (overwritten if user specifies list)\n default_labels = [\n 'a [au]',\n 'ecc',\n 'inc [rad]',\n '$\\omega$ [rad]',\n '$\\Omega$ [rad]',\n '$\\\\tau$',\n '$\\pi$ [mas]',\n '$M_T$ [Msol]'\n ]\n if len(param_list)>0: # user chose to plot specific parameters only\n num_orb_param = self.post.shape[1] # number of orbital parameters (+ mass, parallax)\n num_objects,remainder = np.divmod(num_orb_param,6)\n have_mtot_and_plx = remainder == 2\n param_indices = []\n for param in param_list:\n if param=='plx':\n if have_mtot_and_plx:\n param_indices.append(num_orb_param-2) # the 2nd last index\n elif param=='mtot':\n if have_mtot_and_plx:\n param_indices.append(num_orb_param-1) # the last index\n elif len(param)==4: # to prevent invalid, short param names breaking\n if param[0:3] in dict_of_indices:\n object_id = np.int(param[3])\n index = dict_of_indices[param[0:3]] + 6*(object_id-1)\n param_indices.append(index)\n else:\n pass # skip unrecognized parameter\n\n samples = self.post[:,param_indices] # Keep only chains for selected parameters\n if 'labels' not in corner_kwargs: # Use default labels if user didn't already supply them\n # Necessary to index a list with another list\n reduced_labels_list = [default_labels[i] for i in param_indices]\n corner_kwargs['labels'] = reduced_labels_list\n else:\n samples = self.post\n if 'labels' not in corner_kwargs: # Use default labels if user didn't already supply them\n corner_kwargs['labels'] = default_labels\n\n figure = corner.corner(samples, **corner_kwargs)\n return figure\n\n\n def plot_orbits(self, parallax=None, total_mass=None, object_mass=0,\n object_to_plot=1, start_mjd=51544.,\n num_orbits_to_plot=100, num_epochs_to_plot=100,\n square_plot=True, show_colorbar=True, cmap=cmap,\n sep_pa_color='lightgrey', sep_pa_end_year=2025.0,\n cbar_param='epochs'):\n\n \"\"\"\n Plots one orbital period for a select number of fitted orbits\n for a given object, with line segments colored according to time\n\n Args:\n parallax (float): parallax (in mas), however, if plx_err was passed\n to system, then this is ignored and the posterior samples for\n plx will be used instead (default: None)\n total_mass (float): total mass of system in solar masses, however,\n if mass_err was passed to system, then this is ignored and the\n posterior samples for mtot will be used instead (default: None)\n object_mass (float): mass of the object, in solar masses (default: 0)\n Note: this input has no effect at this time\n object_to_plot (int): which object to plot (default: 1)\n start_mjd (float): MJD in which to start plotting orbits (default: 51544,\n the year 2000)\n num_orbits_to_plot (int): number of orbits to plot (default: 100)\n num_epochs_to_plot (int): number of points to plot per orbit (default: 100)\n square_plot (Boolean): Aspect ratio is always equal, but if\n square_plot is True (default), then the axes will be square,\n otherwise, white space padding is used\n show_colorbar (Boolean): Displays colorbar to the right of the plot [True]\n cmap (matplotlib.cm.ColorMap): color map to use for making orbit tracks\n (default: modified Purples_r)\n sep_pa_color (string): any valid matplotlib color string, used to set the\n color of the orbit tracks in the Sep/PA panels (default: 'lightgrey').\n sep_pa_end_year (float): decimal year specifying when to stop plotting orbit\n tracks in the Sep/PA panels (default: 2025.0).\n cbar_param (string): options are the following: epochs, sma1, ecc1, inc1, aop1,\n pan1, tau1. Number can be switched out. Default is epochs.\n\n Return:\n ``matplotlib.pyplot.Figure``: the orbit plot if input is valid, ``None`` otherwise\n\n\n (written): Henry Ngo, Sarah Blunt, 2018\n Additions by Malena Rice, 2019\n\n \"\"\"\n\n with warnings.catch_warnings():\n warnings.simplefilter('ignore', ErfaWarning)\n\n dict_of_indices = {\n 'sma': 0,\n 'ecc': 1,\n 'inc': 2,\n 'aop': 3,\n 'pan': 4,\n 'tau': 5\n }\n\n if cbar_param == 'epochs':\n pass\n elif cbar_param[0:3] in dict_of_indices:\n try:\n object_id = np.int(cbar_param[3:])\n except ValueError:\n object_id = 1\n\n index = dict_of_indices[cbar_param[0:3]] + 6*(object_id-1)\n else:\n raise Exception('Invalid input; acceptable inputs include epochs, sma1, ecc1, inc1, aop1, pan1, tau1, sma2, ecc2, ...')\n\n\n # Split the 2-D post array into series of 1-D arrays for each orbital parameter\n num_objects, remainder = np.divmod(self.post.shape[1],6)\n if object_to_plot > num_objects:\n return None\n\n sma = self.post[:,dict_of_indices['sma']]\n ecc = self.post[:,dict_of_indices['ecc']]\n inc = self.post[:,dict_of_indices['inc']]\n aop = self.post[:,dict_of_indices['aop']]\n pan = self.post[:,dict_of_indices['pan']]\n tau = self.post[:,dict_of_indices['tau']]\n\n # Then, get the other parameters\n if remainder == 2: # have samples for parallax and mtot\n plx = self.post[:,-2]\n mtot = self.post[:,-1]\n else: # otherwise make arrays out of user provided value\n if total_mass is not None:\n mtot = np.ones(len(sma))*total_mass\n else:\n raise Exception('results.Results.plot_orbits(): total mass must be provided if not part of samples')\n if parallax is not None:\n plx = np.ones(len(sma))*parallax\n else:\n raise Exception('results.Results.plot_orbits(): parallax must be provided if not part of samples')\n mplanet = np.ones(len(sma))*object_mass\n\n # Select random indices for plotted orbit\n if num_orbits_to_plot > len(sma):\n num_orbits_to_plot = len(sma)\n choose = np.random.randint(0, high=len(sma), size=num_orbits_to_plot)\n\n raoff = np.zeros((num_orbits_to_plot, num_epochs_to_plot))\n deoff = np.zeros((num_orbits_to_plot, num_epochs_to_plot))\n epochs = np.zeros((num_orbits_to_plot, num_epochs_to_plot))\n\n # Loop through each orbit to plot and calcualte ra/dec offsets for all points in orbit\n # Need this loops since epochs[] vary for each orbit, unless we want to just plot the same time period for all orbits\n for i in np.arange(num_orbits_to_plot):\n orb_ind = choose[i]\n # Compute period (from Kepler's third law)\n period = np.sqrt(4*np.pi**2.0*(sma*u.AU)**3/(consts.G*(mtot*u.Msun)))\n period = period.to(u.day).value\n # Create an epochs array to plot num_epochs_to_plot points over one orbital period\n epochs[i,:] = np.linspace(start_mjd, float(start_mjd+period[orb_ind]), num_epochs_to_plot)\n\n # Calculate ra/dec offsets for all epochs of this orbit\n raoff0, deoff0, _ = kepler.calc_orbit(\n epochs[i,:], sma[orb_ind], ecc[orb_ind], inc[orb_ind], aop[orb_ind], pan[orb_ind],\n tau[orb_ind], plx[orb_ind], mtot[orb_ind], mass=mplanet[orb_ind], tau_ref_epoch=self.tau_ref_epoch\n )\n\n raoff[i,:] = raoff0\n deoff[i,:] = deoff0\n\n # Create a linearly increasing colormap for our range of epochs\n if cbar_param != 'epochs':\n cbar_param_arr = self.post[:,index]\n norm = mpl.colors.Normalize(vmin=np.min(cbar_param_arr), vmax=np.max(cbar_param_arr))\n norm_yr = mpl.colors.Normalize(vmin=np.min(cbar_param_arr), vmax=np.max(cbar_param_arr))\n\n elif cbar_param == 'epochs':\n norm = mpl.colors.Normalize(vmin=np.min(epochs), vmax=np.max(epochs[-1,:]))\n\n norm_yr = mpl.colors.Normalize(\n vmin=np.min(Time(epochs,format='mjd').decimalyear),\n vmax=np.max(Time(epochs,format='mjd').decimalyear)\n )\n\n\n # Create figure for orbit plots\n fig = plt.figure(figsize=(14,6))\n\n ax = plt.subplot2grid((2, 14), (0, 0), rowspan=2, colspan=6)\n\n # Plot each orbit (each segment between two points coloured using colormap)\n for i in np.arange(num_orbits_to_plot):\n points = np.array([raoff[i,:], deoff[i,:]]).T.reshape(-1,1,2)\n segments = np.concatenate([points[:-1], points[1:]], axis=1)\n lc = LineCollection(\n segments, cmap=cmap, norm=norm, linewidth=1.0\n )\n if cbar_param != 'epochs':\n lc.set_array(np.ones(len(epochs[0]))*cbar_param_arr[i])\n elif cbar_param == 'epochs':\n lc.set_array(epochs[i,:])\n ax.add_collection(lc)\n\n # modify the axes\n if square_plot:\n adjustable_param='datalim'\n else:\n adjustable_param='box'\n ax.set_aspect('equal', adjustable=adjustable_param)\n ax.set_xlabel('$\\Delta$RA [mas]')\n ax.set_ylabel('$\\Delta$Dec [mas]')\n ax.locator_params(axis='x', nbins=6)\n ax.locator_params(axis='y', nbins=6)\n\n # add colorbar\n if show_colorbar:\n cbar_ax = fig.add_axes([0.47, 0.15, 0.015, 0.7]) # xpos, ypos, width, height, in fraction of figure size\n cbar = mpl.colorbar.ColorbarBase(cbar_ax, cmap=cmap, norm=norm_yr, orientation='vertical', label=cbar_param)\n\n # plot sep/PA zoom-in panels\n ax1 = plt.subplot2grid((2, 14), (0, 9), colspan=6)\n ax2 = plt.subplot2grid((2, 14), (1, 9), colspan=6)\n ax2.set_ylabel('PA [$^{{\\\\circ}}$]')\n ax1.set_ylabel('$\\\\rho$ [mas]')\n ax2.set_xlabel('Epoch')\n\n epochs_seppa = np.zeros((num_orbits_to_plot, num_epochs_to_plot))\n\n for i in np.arange(num_orbits_to_plot):\n\n orb_ind = choose[i]\n\n\n epochs_seppa[i,:] = np.linspace(\n start_mjd,\n Time(sep_pa_end_year, format='decimalyear').mjd,\n num_epochs_to_plot\n )\n\n # Calculate ra/dec offsets for all epochs of this orbit\n raoff0, deoff0, _ = kepler.calc_orbit(\n epochs_seppa[i,:], sma[orb_ind], ecc[orb_ind], inc[orb_ind], aop[orb_ind], pan[orb_ind],\n tau[orb_ind], plx[orb_ind], mtot[orb_ind], mass=mplanet[orb_ind], tau_ref_epoch=self.tau_ref_epoch\n )\n\n raoff[i,:] = raoff0\n deoff[i,:] = deoff0\n\n yr_epochs = Time(epochs_seppa[i,:],format='mjd').decimalyear\n plot_epochs = np.where(yr_epochs <= sep_pa_end_year)[0]\n yr_epochs = yr_epochs[plot_epochs]\n\n seps, pas = orbitize.system.radec2seppa(raoff[i,:], deoff[i,:])\n\n plt.sca(ax1)\n plt.plot(yr_epochs, seps, color=sep_pa_color)\n\n plt.sca(ax2)\n plt.plot(yr_epochs, pas, color=sep_pa_color)\n\n ax1.locator_params(axis='x', nbins=6)\n ax1.locator_params(axis='y', nbins=6)\n ax2.locator_params(axis='x', nbins=6)\n ax2.locator_params(axis='y', nbins=6)\n\n return fig\n","sub_path":"orbitize/results.py","file_name":"results.py","file_ext":"py","file_size_in_byte":23781,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"148632262","text":"import copy\n\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport os\nimport shelve\nfrom openpyxl.worksheet.worksheet import Worksheet\nfrom openpyxl.worksheet.table import Table, TableStyleInfo\nfrom openpyxl.utils.dataframe import dataframe_to_rows\nfrom openpyxl import Workbook\nimport sys\n\npd.options.mode.chained_assignment = None\n\n\ndef get_excel_style(row, col):\n \"\"\" Convert given row and column number to an Excel-style cell name. \"\"\"\n\n LETTERS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'\n\n result = []\n while col:\n col, rem = divmod(col - 1, 26)\n result[:0] = LETTERS[rem]\n return ''.join(result) + str(row)\n\n\ndef create_excel_table_from_df(df: pd.DataFrame, sheet_: Worksheet, row_ini: 1, table_name):\n \"\"\"Crea tabla de Excel en la hoja indicada a partir de un pandas DataFrame.\n\n Parametros:\n df: pandas DataFrame\n row_ini: fila inicial, por default 1\n sheet_: Worksheet object openpyxl\n table_name: nombre de la tabla\"\"\"\n\n col_last = get_excel_style(1, df.shape[1])[:-1]\n\n # Crear tabla de Excel\n tabla_excel = Table(displayName=table_name,\n ref=f\"A{row_ini}:{col_last}{df.shape[0] + row_ini}\") # nombre y tamaño\n\n # declarar estilos a la tabla\n style = TableStyleInfo(name=\"TableStyleMedium2\", showRowStripes=False)\n\n # asignar el estilo\n tabla_excel.tableStyleInfo = style\n\n # agregar tabla a la hoja\n sheet_.add_table(tabla_excel)\n\n\ndef df_to_excel(wb: Workbook, df: pd.DataFrame, sheet_: Worksheet, row_ini: 1, as_table: False, **kwargs):\n \"\"\"Agregar pandas DataFrame a hoja de Excel.\n\n Parametros:\n df: pandas DataFrame\n sheet_: Worksheet object openpyxl\n row_ini: fila inicial, por default 1\n as_table: boolean, crear Tabla de Excel\"\"\"\n\n # Agregar dataframe de Python a Excel\n rows = dataframe_to_rows(df, index=False, header=True)\n\n # agregar filas a Excel\n for r_idx, row in enumerate(rows, row_ini):\n for c_idx, value in enumerate(row, 1):\n sheet_.cell(row=r_idx, column=c_idx, value=value)\n\n if as_table:\n try:\n table_name = kwargs['table_name']\n create_excel_table_from_df(df, sheet_, row_ini, table_name)\n except KeyError:\n raise ValueError('A table name must be specified if as_table is True.')\n try:\n for sheet in ['Sheet', 'Hoja', 'Hoja1']:\n wb.remove(wb[sheet])\n\n except KeyError:\n pass\n\n\ndef resource_path(relative_path):\n \"\"\" Get absolute path to resource, works for dev and for PyInstaller \"\"\"\n try:\n # PyInstaller creates a temp folder and stores path in _MEIPASS\n base_path = sys._MEIPASS\n except Exception:\n base_path = os.path.abspath(\".\")\n\n return os.path.join(base_path, relative_path)\n\n\nclass FilePathShelf:\n @staticmethod\n def close_shelf(shelf: shelve):\n\n shelf.close()\n\n def __init__(self, _path):\n\n # path to save the shelve files\n self._path = _path\n\n # open shelve\n paths_shelf = shelve.open(self._path)\n\n # set keys list\n self._shelve_keys = ['Export',\n 'Orders',\n 'Anomaly_Model',\n 'Last_Update',\n 'Temp',\n 'Export_FileName']\n\n # try to get value from key, if empty initialize\n for _path in self._shelve_keys:\n try:\n paths_shelf[_path]\n\n except KeyError:\n paths_shelf[_path] = ''\n\n # close shelf\n paths_shelf.close()\n\n def open_shelf(self):\n paths_shelf = shelve.open(self._path)\n\n return paths_shelf\n\n def write_to_shelf(self, file_name, path_):\n \"\"\"Set value (path_) to key (file_name).\"\"\"\n\n # open saved values\n paths_shelf = self.open_shelf()\n\n if file_name not in self._shelve_keys:\n raise ValueError(f'You tried to save {file_name} to the dictionary. '\n f'The accepted values are {self._shelve_keys}.')\n\n # set value to key\n paths_shelf[file_name] = path_\n\n # save and close shelf\n self.close_shelf(paths_shelf)\n\n def print_shelf(self):\n \"\"\"Print the shelf.\"\"\"\n\n shelf = self.open_shelf()\n\n for key, value in shelf.items():\n print(key, ': ', value)\n\n if key is None or value is None:\n pass\n\n # save and close shelf\n self.close_shelf(shelf)\n\n def send_path(self, file_name):\n \"\"\"Return path from key (file_name).\"\"\"\n\n paths_shelf = self.open_shelf()\n\n if file_name not in self._shelve_keys:\n raise ValueError(f'{file_name} is not a valid file name.')\n\n path = paths_shelf[file_name]\n\n # save and close shelf\n self.close_shelf(paths_shelf)\n\n return path\n\n\nclass AnomalyApp:\n\n @staticmethod\n def calculate_min_max(df):\n\n try:\n df['Fecha'] = pd.to_datetime(df['Fecha'])\n except ValueError:\n df['Fecha'] = pd.to_datetime(df['Fecha'], format='%d/%m/%Y')\n\n group_cols = ['Cliente_Cod',\n 'Producto_Cod']\n\n df_25 = df.groupby(group_cols)['Cantidad'].quantile(0.05).reset_index()\n df_25 = df_25.rename(columns={'Cantidad': 'Min'})\n df_75 = df.groupby(group_cols)['Cantidad'].quantile(0.95).reset_index()\n df_75 = df_75.rename(columns={'Cantidad': 'Max'})\n\n df = df.merge(df_25, on=group_cols, how='left')\n df = df.merge(df_75, on=group_cols, how='left')\n\n df = df.drop_duplicates(subset=['Cliente_Cod', 'Producto_Cod'])\n df = df[['Cliente_Cod', 'Producto_Cod', 'Min', 'Max']]\n df.loc[df['Min'] < 0, 'Min'] = 0\n\n return df\n\n def __init__(self, path_):\n # installation path, located in Appdata/Roaming\n self.path_ = path_\n self.path_config_shelf = os.path.join(path_, 'config')\n self.path_file_paths = os.path.join(path_, 'paths')\n\n # attributes to save the tables created after the anomaly check\n self.df_normal = None\n self.df_anomalies = None\n self.df_missing = None\n\n # read the original model and save as a dataframe\n if os.path.exists(os.path.join(self.path_, 'Anomalas_Modelo.csv')):\n # If the model has been updated by the user, the model is located in the Appdata folder.\n self.df_original_model = pd.read_csv(os.path.join(self.path_, 'Anomalas_Modelo.csv'))\n else:\n\n # If the model has not been updated by the user, the model is bundled with the executable.\n path_ = resource_path(r'data/Anomalas_Modelo.csv')\n self.df_original_model = pd.read_csv(path_)\n\n # Anomaly count\n self.anomaly_count = 0\n\n # initial routine\n if not self.check_if_installed():\n self.setup()\n\n # shelves for storing data in computer memory\n self.file_paths_shelf = FilePathShelf(self.path_file_paths)\n\n def setup(self):\n \"\"\"\n Sets up the fixed path of the program.\n \"\"\"\n if not os.path.exists(self.path_):\n print('Instalando el programa.')\n os.makedirs(self.path_)\n\n def check_if_installed(self):\n \"\"\"\n Checks if the fixed path of the program exists or not.\n \"\"\"\n if os.path.exists(self.path_):\n return True\n else:\n return False\n\n def set_path(self, filename, path):\n \"\"\"Set path to the paths shelf.\"\"\"\n\n self.file_paths_shelf.write_to_shelf(filename, path)\n\n def get_path(self, filename):\n \"\"\"Get path from the paths shelf.\"\"\"\n\n return self.file_paths_shelf.send_path(filename)\n\n def read_new_data(self, file):\n \"\"\"\n Returns pandas dataframe with raw orders data.\n \"\"\"\n\n # Get the Orders path from paths shelf\n path = self.file_paths_shelf.send_path(file)\n\n # Read the file into a pandas dataframe.\n # Change the function used depending on the extension file.\n if path.endswith('xlsx'):\n df = pd.read_excel(path)\n else:\n df = pd.read_csv(path)\n\n return df\n\n def clean_new_data(self, file):\n \"\"\"Clean the raw orders data.\"\"\"\n\n # Read the new data.\n df = self.read_new_data(file)\n\n if df.shape[1] != 11:\n raise ValueError('El archivo indicado no tiene la cantidad de columnas esperada.\\n'\n f'Cantidad de columnas: {df.shape[1]}.\\n'\n f'Cantidad esperada: {11}.')\n\n # Keep columns by index.\n df = df.iloc[:, [2, 4, 5, 6, 7, 8, 9]]\n\n # Change column names.\n df.columns = ['Orden',\n 'Fecha',\n 'Cliente_Cod',\n 'Cliente_Nombre',\n 'Producto_Cod',\n 'Producto_Nombre',\n 'Cantidad']\n\n # Keep columns with non null \"Cantidad\" field.\n df = df[df['Cantidad'].notnull()]\n\n return df\n\n def anomaly_check(self):\n \"\"\"\n Compare each client-product combination from the new orders with the anomaly model.\n Client-product combinations that are out of the range (specified by the model) must be marked as anomalies.\n Return three tables:\n df_normal = with the normal orders\n df_anomalies = with combinations that are out of range\n df_missing = with combinations that don't exist in the existing model\n \"\"\"\n\n # Read and clean the new orders data.\n df_sales = self.clean_new_data('Orders')\n self.order_count = df_sales.shape[0]\n\n # Create a dataframe with the new orders and the minimum and maximum acceptable values for each client-product\n # combination.\n df_verification = df_sales.merge(self.df_original_model,\n on=['Cliente_Cod', 'Producto_Cod'],\n how='left')\n\n # If the \"Cantidad\" field is less than the minimum or greater than the maximum, the alert must be raised.\n df_verification['Alerta'] = 0\n df_verification.loc[(df_verification['Cantidad'] < df_verification['Min']) |\n (df_verification['Cantidad'] > df_verification['Max']), 'Alerta'] = 1\n\n # Create a table with all the found alerts.\n df_anomalies = df_verification[df_verification['Alerta'] == 1]\n cols_to_drop = ['Min', 'Max', 'Alerta']\n df_anomalies.drop(columns=cols_to_drop, inplace=True)\n\n # The amount of rows in the alerts table is the amount of anomalies found.\n self.anomaly_count = df_anomalies.shape[0]\n\n # Create a table with all the missing alerts, with all the client-product combinations that don't exist in the\n # model.\n df_missing = df_verification[df_verification['Min'].isna()]\n df_missing.drop(columns=cols_to_drop, inplace=True)\n\n self.missing_count = df_missing.shape[0]\n\n # Create a table with all the normal orders.\n df_normal = df_verification[(df_verification['Alerta'] == 0) & (df_verification['Min'].notna())]\n df_normal.drop(columns=cols_to_drop, inplace=True)\n\n # Calculate metrics\n self.oea_with_missing = ((self.order_count - self.anomaly_count) / self.order_count) * 100\n order_count_without_missing = self.order_count - self.missing_count\n self.oea_without_missing = ((\n order_count_without_missing - self.anomaly_count) / order_count_without_missing) * 100\n\n # save tables as attributes\n self.df_normal = df_normal\n self.df_anomalies = df_anomalies\n self.df_missing = df_missing\n\n return df_normal, df_anomalies, df_missing\n\n def export_anomaly_check(self):\n\n # Declare excel workbook and three sheets for the three different tables\n wb = Workbook()\n\n df_normal = copy.deepcopy(self.df_normal)\n df_anomalies = copy.deepcopy(self.df_anomalies)\n df_missing = copy.deepcopy(self.df_missing)\n\n for df in [df_normal, df_anomalies, df_missing]:\n df.columns = ['Orden',\n 'Fecha',\n 'Codigo Cliente',\n 'Nombre Cliente',\n 'Codigo Producto',\n 'Nombre Producto',\n 'Cantidad']\n\n letters = 'ABCDEFG'\n sizes_list = [12, 12, 16, 40, 16, 40, 15]\n if not df_normal.empty:\n sheet_normal = wb.create_sheet('Correctas')\n df_to_excel(wb, df_normal, sheet_normal, 1, as_table=True, table_name='Normales')\n self.change_col_sizes(sheet_normal, letters, sizes_list)\n\n if not df_anomalies.empty:\n sheet_anomalies = wb.create_sheet('Anomalias')\n df_to_excel(wb, df_anomalies, sheet_anomalies, 1, as_table=True, table_name='Anomalias')\n self.change_col_sizes(sheet_anomalies, letters, sizes_list)\n\n if not df_missing.empty:\n sheet_missing = wb.create_sheet('Nuevos clientes')\n df_to_excel(wb, df_missing, sheet_missing, 1, as_table=True, table_name='Nuevos')\n self.change_col_sizes(sheet_missing, letters, sizes_list)\n\n path_ = self.file_paths_shelf.send_path('Export')\n file_name_ = self.file_paths_shelf.send_path('Export_FileName') + '.xlsx'\n full_path_ = os.path.join(path_, file_name_)\n wb.save(full_path_)\n wb.close()\n\n @staticmethod\n def change_col_sizes(sheet, letters: str, sizes_list: list):\n\n letters_list = [let for let in letters]\n\n for col, size in zip(letters_list, sizes_list):\n sheet.column_dimensions[col].width = size\n\n def update_model(self):\n \"\"\"\n Update the model with new data.\n The old minimums are replaced by lower minimums and old maximums are replaced by higher maximums.\n \"\"\"\n\n # Read the data provided by the user.\n df_new = self.clean_new_data('Anomaly_Model')\n\n # Calculate new range for the provided data.\n df_new = self.calculate_min_max(df_new)\n\n # Create a copy of the original model data\n df_old = copy.deepcopy(self.df_original_model)\n\n # Change the column names of the data provided by the user.\n df_new.columns = ['Cliente_Cod', 'Producto_Cod', 'Min_new', 'Max_new']\n\n # Create new table with old and new data\n df = df_old.merge(df_new, on=['Cliente_Cod', 'Producto_Cod'], how='outer')\n\n # If new min is less than original min, replace with the new min.\n # If new max is greater than original max, replace with the new max.\n df.loc[df['Min_new'] < df['Min'], 'Min'] = df['Min_new']\n df.loc[df['Max_new'] > df['Max'], 'Max'] = df['Max_new']\n\n # If there is new data, update the original columns.\n df.loc[df['Min'].isna(), 'Min'] = df['Min_new']\n df.loc[df['Max'].isna(), 'Max'] = df['Max_new']\n\n # Drop the new data columns.\n df.drop(columns=['Min_new', 'Max_new'], inplace=True)\n\n # If the min is equal to the max, drop the line.\n df = df[df['Min'] != df['Max']]\n\n # Save the updated model to the %APPDATA% path.\n df.to_csv(os.path.join(self.path_, 'Anomalas_Modelo.csv'),\n index=False)\n\n return df\n","sub_path":"anomalas_back_end.py","file_name":"anomalas_back_end.py","file_ext":"py","file_size_in_byte":15495,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"447883448","text":"# Copyright 2018 The TensorFlow Constrained Optimization Authors. All Rights\n# Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"); you may not\n# use this file except in compliance with the License. You may obtain a copy of\n# 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 under\n# the License.\n# ==============================================================================\n\"\"\"Tests for loss.py.\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport numpy as np\nimport tensorflow as tf\n\nfrom tensorflow_constrained_optimization.python import graph_and_eager_test_case\nfrom tensorflow_constrained_optimization.python.rates import loss\n# Placeholder for internal import.\n\n\ndef binary_zero_one_loss(predictions):\n \"\"\"Expected binary classification zero-one loss.\"\"\"\n return (np.sign(predictions) + 1.0) / 2.0\n\n\ndef binary_hinge_loss(margin):\n \"\"\"Expected binary classification hinge loss with given margin.\"\"\"\n return lambda predictions: np.maximum(0.0, margin + predictions)\n\n\ndef binary_softmax_loss(predictions):\n \"\"\"Expected binary classification softmax loss.\"\"\"\n numerator = np.exp(predictions)\n return numerator / (1 + numerator)\n\n\ndef binary_softmax_cross_entropy_loss(predictions):\n \"\"\"Expected binary classification softmax cross-entropy loss.\"\"\"\n return np.log(1 + np.exp(predictions))\n\n\n# @run_all_tests_in_graph_and_eager_modes\nclass LossTest(graph_and_eager_test_case.GraphAndEagerTestCase):\n \"\"\"Tests for `Loss` classes.\"\"\"\n\n def __init__(self, *args, **kwargs):\n super(LossTest, self).__init__(*args, **kwargs)\n\n # We use a fixed fake dataset to make sure that the tests are reproducible.\n # The code for generating this random dataset is:\n #\n # size = 20\n #\n # self._predictions = np.random.randn(size)\n # self._weights = np.random.randn(size, 2)\n #\n # The dataset itself is:\n self._predictions = np.array([\n 0.584512341999, -0.55015387642, 0.0903356546458, 0.633426692118,\n -0.882615385953, -0.3678706889, 1.04663484707, 0.0344508924989,\n 0.216541984044, -0.717996402915, -0.600528960814, -0.337885591055,\n -0.49071694553, 0.446409688644, 0.113508013003, -2.28022263467,\n -1.74425324236, -0.0132548715691, -0.923112276794, 1.11681572053\n ])\n self._weights = np.array([\n [-0.452099600241, 1.07725936148],\n [0.703368020437, -1.4504981454],\n [-0.0980201564317, 0.92831478234],\n [0.258419891287, -2.09698564434],\n [0.0658564429054, 1.41984871297],\n [-0.788784248269, -1.18654649943],\n [-1.73866936442, -0.0590830456781],\n [-0.23615112839, -1.75620893231],\n [0.676139218764, -0.0408724788464],\n [-0.618938863154, -0.296080582242],\n [-2.25835513009, -0.0213691762614],\n [0.0766053894937, -1.13339177424],\n [2.36519239138, 0.681535742442],\n [-0.229637659991, -2.26443855249],\n [0.171883509387, -0.112264766436],\n [-0.499339463268, 0.202125957361],\n [-0.134112250792, -0.355461297829],\n [0.608786974973, -0.324075441957],\n [0.814526800499, 2.17971326555],\n [-0.665005832144, 1.76628797184],\n ])\n\n def _binary_loss_helper(self, expected_loss, actual_loss):\n minimum_weights = np.minimum(self._weights[:, 0], self._weights[:, 1])\n expected = minimum_weights + (\n expected_loss(self._predictions) *\n (self._weights[:, 0] - minimum_weights) +\n expected_loss(-self._predictions) *\n (self._weights[:, 1] - minimum_weights))\n\n with self.wrapped_session() as session:\n actual = session.run(\n actual_loss.evaluate_binary_classification(\n tf.constant(self._predictions), tf.constant(self._weights)))\n\n self.assertAllClose(expected, actual, rtol=0, atol=1e-6)\n\n def test_convert_to_binary_classification_predictions(self):\n \"\"\"Tests the \"_convert_to_binary_classification_predictions\" function.\"\"\"\n # A non-Tensor isn't a valid set of binary predictions.\n with self.assertRaises(TypeError):\n _ = loss._convert_to_binary_classification_predictions(\n [1.0, 2.0, 3.0, 4.0])\n\n # An integer Tensor isn't a valid set of binary predictions.\n tensor = tf.convert_to_tensor([1, 2, 3, 4], dtype=tf.int32)\n with self.assertRaises(TypeError):\n _ = loss._convert_to_binary_classification_predictions(tensor)\n\n # A rank-2 Tensor isn't a valid set of binary predictions.\n tensor = tf.convert_to_tensor([[1.0, 2.0], [3.0, 4.0]])\n with self.assertRaises(ValueError):\n _ = loss._convert_to_binary_classification_predictions(tensor)\n\n # A floating-point Tensor of shape (1,4,1) is a valid set of binary\n # predictions (it's floating-point, and only has one \"nontrivial\"\n # dimension).\n expected_predictions = [1.0, 2.0, 3.0, 4.0]\n tensor = tf.convert_to_tensor([[[1.0], [2.0], [3.0], [4.0]]],\n dtype=tf.float32)\n with self.wrapped_session() as session:\n actual_predictions = session.run(\n loss._convert_to_binary_classification_predictions(tensor))\n self.assertAllClose(\n expected_predictions, actual_predictions, rtol=0, atol=1e-6)\n\n def test_binary_zero_one_loss(self):\n self._binary_loss_helper(binary_zero_one_loss, loss.ZeroOneLoss())\n\n def test_binary_hinge_loss(self):\n for margin in [0.5, 1.0, 1.3]:\n self._binary_loss_helper(\n binary_hinge_loss(margin), loss.HingeLoss(margin))\n\n def test_binary_softmax_loss(self):\n self._binary_loss_helper(binary_softmax_loss, loss.SoftmaxLoss())\n\n def test_binary_softmax_cross_entropy_loss(self):\n self._binary_loss_helper(binary_softmax_cross_entropy_loss,\n loss.SoftmaxCrossEntropyLoss())\n\n\nif __name__ == \"__main__\":\n tf.test.main()\n","sub_path":"tensorflow_constrained_optimization/python/rates/loss_test.py","file_name":"loss_test.py","file_ext":"py","file_size_in_byte":6157,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"414990991","text":"import logging\n\nlogger = logging.getLogger(__name__)\n\nlogger.setLevel(logging.DEBUG)\n\nhandler = logging.StreamHandler()\n\nformatter = logging.Formatter(\n \"%(name)s - %(levelname)s - %(asctime)s - %(message)s\", datefmt=\"%d/%m/%Y %H:%M:%S\"\n)\nhandler.setFormatter(formatter)\n\nlogger.addHandler(handler)\n","sub_path":"logger/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":302,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"453236299","text":"#!/usr/bin/python\nimport math\n\ndef isPrime(num):\n\tif (num%2==0):\n\t\treturn False\n\t\t#print(\"It is not prime\")\t\t\n\telse:\n\t\tfor x in range(3,int(math.sqrt(num))+1,2):\n\t\t\tif (num%x==0):\n\t\t\t\treturn True\n\t\t\telse:\n\t\t\t\treturn False\n\n\ndef main():\n\tnum=eval(input(\"Enter the Number :\"))\n\tif isPrime(num):\n\t\tprint(\"no is prime\")\n\telse:\n\t\tprint(\"no is not prime\")\n\n\nif __name__=='__main__':\n\tmain()\n","sub_path":"Basic_Programs/17_isPrime.py","file_name":"17_isPrime.py","file_ext":"py","file_size_in_byte":385,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"60928020","text":"import os\nimport json\nimport time\nimport yaml\nimport argparse\nimport requests\n\n\ndef check_status(host):\n try:\n status = requests.get('http://{}/status'.format(host))\n return {'success': True, 'data': json.loads(status.text)}\n except Exception as e:\n print('Error in checking', e)\n return {'success': False, 'data': None}\n\n\ndef local_stop(sudo):\n os.system(sudo + 'docker-compose stop')\n\n\ndef server_stop(runtime_config):\n import paramiko\n for m_name in runtime_config['machines']:\n\n ssh = paramiko.SSHClient()\n ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())\n\n host = runtime_config['machines'][m_name]['host']\n port = runtime_config['machines'][m_name]['port']\n user_name = runtime_config['machines'][m_name]['user_name']\n remote_path = runtime_config['machines'][m_name]['dir']\n\n key_file = runtime_config['machines'][m_name]['key']\n ssh.connect(hostname=host, port=port, username=user_name, key_filename=key_file)\n\n ssh = paramiko.SSHClient()\n ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())\n ssh.connect(hostname=host, port=port, username=user_name, key_filename=key_file)\n if m_name == 'server':\n stdin, stdout, stderr = ssh.exec_command('cd {};'.format(remote_path) + sudo +\n 'docker-compose -f docker-compose-server.yml stop')\n else:\n stdin, stdout, stderr = ssh.exec_command('cd {};'.format(remote_path) + sudo +\n 'docker-compose -f docker-compose-{}.yml stop'.format(m_name))\n\n print(''.join(stdout.readlines()))\n print(''.join(stderr.readlines()))\n\n\ndef upload_to_server(runtime_config, file_list=()):\n if len(file_list) > 0:\n scp_orders = ['scp -P {} -i {} -r ' + e + ' {}@{}:{}' for e in file_list]\n\n for m_name in runtime_config['machines']:\n host = runtime_config['machines'][m_name]['host']\n port = runtime_config['machines'][m_name]['port']\n user_name = runtime_config['machines'][m_name]['user_name']\n remote_path = runtime_config['machines'][m_name]['dir']\n key_file = runtime_config['machines'][m_name]['key']\n for instruction in scp_orders:\n os.system(instruction.format(port, key_file, user_name, host, remote_path))\n\n\nif __name__ == '__main__':\n\n args_parser = argparse.ArgumentParser()\n args_parser.add_argument('--exec', choices=('run', 'stop', 'upload'), required=True,\n help=\"Please specify the exec type: run, stop, or upload\")\n args_parser.add_argument('--mode', choices=('local', 'server'), required=True,\n help=\"local for running on local Linux machine, set to server if you want to use \"\n \"remote server\")\n args_parser.add_argument('--file', default='',\n help='[Only work when mode=server] '\n 'Files listed here will be automatically '\n 'uploaded to the remote server in the config, '\n 'e.g., --file FedEval,tf_wrapper,*.py '\n 'leave the param empty if you already synced the files.')\n args_parser.add_argument('--config', help='Path to the config files (1_data_config.yml, 2.., 3..)', required=True)\n args_parser.add_argument('--dataset', default='mnist', help='dataset name, default to be mnist')\n args_parser.add_argument('--ml_model', default='LeNet', help='machine learning model name, default to be LeNet')\n args_parser.add_argument('--fed_model', default='FedSGD', help='federated model name, default to be FedSGD')\n args_parser.add_argument('--optimizer', default='adam')\n args_parser.add_argument('--upload_optimizer', default='False')\n args_parser.add_argument('--upload_sparsity', default=1.0, type=float)\n args_parser.add_argument('--upload_dismiss', default='')\n args_parser.add_argument('--lazy_update', default='True')\n args_parser.add_argument('--B', type=int, default=1)\n args_parser.add_argument('--C', type=float, default=1.0)\n args_parser.add_argument('--E', type=int, default=1)\n args_parser.add_argument('--num_tolerance', type=int, default=20)\n args_parser.add_argument('--num_clients', type=int, default=100)\n args_parser.add_argument('--max_epochs', type=int, default=1000)\n args_parser.add_argument('--non-iid', type=int, default=0)\n args_parser.add_argument('--non-iid-strategy', default='iid')\n args_parser.add_argument('--lr', default=5e-4)\n args_parser.add_argument('--output', default='experiment_result.csv')\n args_parser.add_argument('--sudo', default='True')\n\n current_path = os.path.abspath('./')\n args = args_parser.parse_args()\n\n sudo = 'sudo ' if args.sudo == 'True' else ''\n\n with open(os.path.join(args.config, '1_data_config.yml'), 'r') as f:\n data_config = yaml.load(f)\n\n with open(os.path.join(args.config, '2_model_config.yml'), 'r') as f:\n model_config = yaml.load(f)\n\n with open(os.path.join(args.config, '3_runtime_config.yml'), 'r') as f:\n runtime_config = yaml.load(f)\n\n if args.exec == 'stop':\n if args.mode == 'local':\n local_stop(sudo)\n if args.mode == 'server':\n server_stop(runtime_config)\n exit(0)\n\n if args.mode == 'server' and args.exec == 'upload':\n upload_to_server(runtime_config, args.file.split(','))\n exit(0)\n\n data_config['dataset'] = args.dataset\n data_config['non-iid'] = args.non_iid\n data_config['non-iid-strategy'] = args.non_iid_strategy\n\n model_config['MLModel']['name'] = args.ml_model\n model_config['MLModel'][args.ml_model]['optimizer'] = args.optimizer\n model_config['MLModel'][args.ml_model]['lr'] = args.lr\n model_config['FedModel']['name'] = args.fed_model\n model_config['FedModel']['upload_strategy']['upload_sparsity'] = args.upload_sparsity\n model_config['FedModel']['upload_strategy']['upload_optimizer'] = eval(args.upload_optimizer)\n model_config['FedModel']['train_strategy']['max_num_rounds'] = args.max_epochs\n model_config['FedModel']['train_strategy']['B'] = args.B\n model_config['FedModel']['train_strategy']['C'] = args.C\n model_config['FedModel']['train_strategy']['E'] = args.E\n model_config['FedModel']['train_strategy']['lazy_update'] = args.lazy_update\n model_config['FedModel']['train_strategy']['num_tolerance'] = args.num_tolerance\n\n if len(args.upload_dismiss) > 0 and args.upload_dismiss.lower != 'none':\n model_config['FedModel']['upload_strategy']['upload_dismiss'] = args.upload_dismiss.split(',')\n else:\n model_config['FedModel']['upload_strategy']['upload_dismiss'] = []\n\n if args.mode == 'local':\n runtime_config['server']['host'] = 'server'\n runtime_config['server']['listen'] = 'server'\n if args.mode == 'server':\n runtime_config['server']['host'] = runtime_config['machines']['server']['host']\n runtime_config['server']['listen'] = '0.0.0.0'\n runtime_config['server']['num_clients'] = args.num_clients\n\n with open(os.path.join(args.config, '1_data_config.yml'), 'w') as f:\n yaml.dump(data_config, f)\n\n with open(os.path.join(args.config, '2_model_config.yml'), 'w') as f:\n yaml.dump(model_config, f)\n\n with open(os.path.join(args.config, '3_runtime_config.yml'), 'w') as f:\n yaml.dump(runtime_config, f)\n\n if args.mode == 'local':\n os.system(\n sudo + 'docker run -it --rm -v {0}:{0} -w {0} '\n '{1} python3 -m FedEval.run -f data -c {2}'\n .format(current_path, runtime_config['docker']['image'], args.config)\n )\n os.system(\n sudo + 'docker run -it --rm -v {0}:{0} -w {0} '\n '{1} python3 -m FedEval.run -f compose-local -c {2}'\n .format(current_path, runtime_config['docker']['image'], args.config)\n )\n os.system(sudo + 'docker-compose up -d')\n\n if args.mode == 'server':\n\n import paramiko\n\n # Upload files if provided\n upload_to_server(runtime_config, args.file.split(','))\n\n machine_name_list = list(runtime_config['machines'].keys())\n machine_name_list.remove('server')\n\n for m_name in ['server'] + machine_name_list:\n\n ssh = paramiko.SSHClient()\n ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())\n\n host = runtime_config['machines'][m_name]['host']\n port = runtime_config['machines'][m_name]['port']\n user_name = runtime_config['machines'][m_name]['user_name']\n remote_path = runtime_config['machines'][m_name]['dir']\n\n key_file = runtime_config['machines'][m_name]['key']\n ssh.connect(hostname=host, port=port, username=user_name, key_filename=key_file)\n\n if m_name != 'server':\n _, stdout, stderr = ssh.exec_command(\n sudo + 'docker run -i --rm -v {0}:{0} -w {0} '\n '{1} python3 -m FedEval.run -f data -c {2}'\n .format(remote_path, runtime_config['docker']['image'], args.config)\n )\n print(''.join(stdout.readlines()))\n print(''.join(stderr.readlines()))\n\n _, stdout, stderr = ssh.exec_command(\n sudo + 'docker run -i --rm -v {0}:{0} -w {0} '\n '{1} python3 -m FedEval.run -f compose-server -c {2}'\n .format(remote_path, runtime_config['docker']['image'], args.config)\n )\n print(''.join(stdout.readlines()))\n print(''.join(stderr.readlines()))\n\n if m_name == 'server':\n print('Start Server')\n _, stdout, stderr = ssh.exec_command(\n 'cd {};'.format(remote_path) + sudo +\n 'docker-compose -f docker-compose-server.yml up -d')\n else:\n print('Start Clients', m_name)\n _, stdout, stderr = ssh.exec_command(\n 'cd {};'.format(remote_path) + sudo +\n 'docker-compose -f docker-compose-{}.yml up -d'.format(m_name))\n\n print(''.join(stdout.readlines()))\n print(''.join(stderr.readlines()))\n\n print('Start success')\n\n time.sleep(20)\n\n host = '127.0.0.1' if args.mode == 'local' else runtime_config['server']['host']\n port = runtime_config['server']['port']\n\n check_status_result = check_status(host + ':' + str(port))\n\n while True:\n if check_status_result['success']:\n if not check_status_result['data'].get('status', False):\n print('Running at Round %s' % check_status_result['data'].get('rounds', -2))\n time.sleep(10)\n else:\n break\n else:\n print('Check failed, try later')\n time.sleep(10)\n check_status_result = check_status(host + ':' + str(port))\n\n status_data = check_status_result['data']\n if status_data is not None:\n\n log_dir = status_data['log_dir']\n log_file = log_dir + '/train.log'\n result_file = log_dir + '/results.json'\n\n if args.mode == 'server':\n os.makedirs(log_dir, exist_ok=True)\n server = runtime_config['machines']['server']\n os.system('scp -P {} -i {} {}@{}:{} ./{}'.format(\n server['port'], server['key'], server['user_name'],\n server['host'], server['dir'] + '/' + result_file, log_dir)\n )\n os.system('scp -P {} -i {} {}@{}:{} ./{}'.format(\n server['port'], server['key'], server['user_name'],\n server['host'], server['dir'] + '/' + log_file, log_dir)\n )\n with open(result_file, 'r') as f:\n results = json.load(f)\n else:\n with open(result_file, 'r') as f:\n results = json.load(f)\n\n best_test_accuracy = '%.5f' % results['best_metric']['test_accuracy']\n\n total_time = results['total_time']\n total_rounds = results['total_rounds']\n server_send = results['server_send']\n server_receive = results['server_receive']\n\n result_list = [\n args.config, args.fed_model, args.dataset, args.ml_model, args.lazy_update, args.optimizer,\n args.upload_optimizer, args.upload_sparsity, args.upload_dismiss,\n args.non_iid, args.non_iid_strategy,\n args.B, args.C, args.E, args.lr, args.num_tolerance, 'None', 'None',\n best_test_accuracy, total_time\n ]\n\n result_list += ['%.5f' % e for e in eval(results['time_detail'])]\n result_list += [total_rounds, server_send, server_receive, result_file]\n # result_list += ['%.5f' % e for e in results['best_metric_full']['test_accuracy']]\n\n result_list = [str(e) for e in result_list]\n\n headers = [\n 'Config', 'FedModel', 'dataset', 'ml-model', 'lazy_update', 'optimizer',\n 'upload_optimizer', 'upload_sparsity', 'upload_dismiss',\n 'IID', 'IID-Strategy', 'B', 'C', 'E', 'lr', 'ESPat', 'LocalAcc', 'CentralAcc', 'FLAcc',\n 'TimeAll', 'Init', 'TrainReq', 'TrainRun', 'TrainSync', 'TrainAgg',\n 'EvalReq', 'EvalRun', 'EvalSync', 'EvalAgg',\n 'CommRound', 'CommAmount(SOut)', 'CommAmount(SIn)', 'ResultFile'\n ]\n\n if os.path.isfile(args.output) is False:\n with open(args.output, 'w') as f:\n f.write(', '.join(headers) + '\\n')\n\n with open(args.output, 'a+') as f:\n f.write(', '.join(result_list) + '\\n')\n\n if args.mode == 'local':\n local_stop(sudo)\n\n if args.mode == 'server':\n server_stop(runtime_config)\n","sub_path":"FedEval/run_util.py","file_name":"run_util.py","file_ext":"py","file_size_in_byte":13920,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"297182022","text":"import numpy as np\n\n#funkcija f(x,y) = cos(x) + 100sin2(y)\ndef f(x):\n return np.sin(x[0]) + (x[1])**2 #+ 100*np.sin(x[1])**2\n\n#gradijent funkcije\ndef grad(x):\n g = np.array([], dtype = float)\n g = np.append(g, np.cos(x[0]))\n g = np.append(g, 2 * x[1])\n #g = np.append(g, 200 * np.sin(x[1])*np.cos(x[1]))\n return g\n\ndef shift(a):\n for i in range(len(a)-1):\n a[i] = a[i+1]\n return a\n\n#lbfgs parametri\neps = 1e-5\nmin_step = 1e-20\nmax_step = 1e20\nmax_linesearch = 10\nc1 = 1e-4\nc2 = 0.9\nm = 10\n\ndef linesearch(fx, x, g, d, step, xp, gp, c1, c2, min_step, max_step, max_linesearch):\n count = 0\n dec = 0.5\n inc = 2.1\n\n result = {'status':0,'fx':fx,'step':step,'x':x, 'g':g}\n\n dginit = np.dot(g, d)\n\n if 0 < dginit:\n result['status'] = -1\n return result\n\n finit = fx\n dgtest = c1 * dginit\n\n while True:\n x = xp\n x = x + d * step\n \n fx = f(x)\n g = grad(x)\n \n count = count + 1\n # Armijo condition\n if fx > finit + (step * dgtest):\n width = dec\n else:\n # check the wolfe condition\n dg = np.dot(g, d)\n if dg < c2 * dginit:\n width = inc\n else:\n # check the strong wolfe condition\n if dg > -c1 * dginit:\n width = dec\n else:\n result = {'status':0, 'fx':fx, 'step':step, 'x':x, 'g':g}\n return result\n if step < min_step:\n result['status'] = -1\n return result\n\n if step > max_step:\n result['status'] = -1\n return result\n \n if max_linesearch <= count:\n result = {'status':0, 'fx':fx, 'step':step, 'x':x, 'g':g}\n return result\t\n\n step = step * width\n\n\n \ndef lbfgs(x):\n n = len(x)\n\n s = np.zeros((m,n), dtype = float)\n y = np.zeros((m,n), dtype = float)\n\n alfa = np.zeros(m, dtype = float)\n\n g = grad(x)\n\n fx = f(x)\n\n d = -1 * g\n\n gnorm = np.sqrt(np.dot(g,g))\n xnorm = np.sqrt(np.dot(x,x))\n\n if xnorm < 1.0:\n xnorm = 1.0\n if gnorm / xnorm <= eps:\n print(\"[INFO] vec minimizovano\")\n return x\n\n step = 1.0 / np.sqrt(np.dot(d, d))\n\n k = 1\n\n while True:\n xp = x.copy()\n\n gp = g.copy()\n\n ls = linesearch(fx, x, g, d, step, xp, gp, c1, c2, min_step, max_step, max_linesearch)\n\n if ls['status'] < 0:\n x = np.copy(xp)\n g = np.copy(gp)\n return x\n\n fx = ls['fx']\n step = ls['step']\n x = ls['x']\n g = ls['g']\n \n xnorm = np.sqrt(np.dot(x, x))\n gnorm = np.sqrt(np.dot(g, g))\n \n if xnorm < 1.0:\n xnorm = 1.0\n if gnorm / xnorm <= eps:\n return x\n\n br = min(m, k) - 1\n\n if k >= m:\n s = shift(s)\n s[br] = x - xp\n\n if k >= m:\n y = shift(y)\n y[br] = g - gp \n\n ys = np.dot(y[br], s[br])\n yy = np.dot(y[br], y[br])\n\n d = -1 * g\n\n for i in range(br, 0, -1):\n alfa[i] = np.dot(s[i], d) / np.dot(y[i], s[i])\n d -= alfa[i] * y[i]\n\n d *= (ys/yy)\n\n for i in range(0, br):\n beta = np.dot(y[i], d) / np.dot(y[i], s[i])\n d += s[i] * (alfa[i] - beta)\n\n step = 1.0\n \n k += 1\n\nx = np.array([1,1], dtype = float)\nxmin = lbfgs(x)\nprint(xmin)\nprint(f(xmin))","sub_path":"lbfgs2.py","file_name":"lbfgs2.py","file_ext":"py","file_size_in_byte":3508,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"257268112","text":"\"\"\"\n E S B E N 2.0\n \n P = SUBJ VERB [NOT] (ADJ|NAME|COMP|ING|NAME)\n ING = VERB-\"ing\" P\n COMP = \"More\"|\"Less\"|ADJ-\"er\" \"than\" (NAME|ING) || \"The\" ADJ-\"st\"|((\"Best\"|\"Worst\")NAME|ADJ-\"er\")\n VERB = \"Am\"|\"Are\"|\"Is\"|\"Have\"|\"Can\"|...\n SUBJ = \"I\"|\"You\"|\"He\"|\"She\"|\"It\"|\"We\"|\"They\"|\"His\"|\"Her\"|NAME\n NAME = ... | ADJ\n\"\"\"\nimport words as w\n# ======= PARSER =======\ndef nxt():\n global ph,i,word\n if i < len(ph):\n i+= 1\n word = ph[i].lower()\n\nph,i,word = [],-1,\"\"\n# ======= # =======\nsubj = {\"is\":[],\"has\":[]}\nmyself = {\"am\":[\"Esben 2.0\"],\"have\":[],\"know\":[\"everything\"]}\nthings = {}\n\npron_pers = [\"i\",\"you\",\"he\",\"she\",\"it\",\"we\",\"they\"]\nperson = \"0x\"\nideal = {\"subj\":\"\"}\n\ndef Phrase():\n global t_subj\n nxt()\n Subject()\n Verb()\n \n\ndef Subject():\n global person, things\n ret = \"\"\n if word in pron_pers:\n if word == \"i\": person = \"1s\"\n elif word == \"you\": person = \"2s\"\n elif word in (\"he\",\"she\",\"it\"): person = \"3s\"\n elif word == \"we\": person = \"1p\"\n else: person = \"3p\"\n else:\n if not word in w.names: w.names.append(word)\n # Add the subject to THINGS\n if not word in (\"i\",\"you\"):\n if not word in things: things[word] = {\"is\":[],\"has\":[]}\n ideal[\"subj\"] = word\n nxt()\n\ntobe = {\"am\":(\"i\"), \"are\":(\"you\",\"we\",\"they\"),\"is\":(\"he\",\"she\",\"it\")}\n\ndef Verb():\n global subj,word\n subject = ideal[\"subj\"]\n if word[-1] == \"s\" and person == \"3s\":\n # 3rd person singular present\n # Add verb to its attr\n if not word in alpha: things[subj][word] = []\n elif word in tobe:\n if not tobe[word] == subj: print(\"-- Grammatical Error\")\n if subject == \"i\":\n # I am --> subj is\n if word == \"am\": word = \"is\"\n elif word == \"have\": word = \"has\"\n elif word == \"do\": word = \"does\"\n if not word in subj: subj[word] = []\n elif subject == \"you\":\n # you are --> I (myself) am\n if word == \"are\": subj[\"am\"]+= []\n if not word in myself: myself[word] = []\n elif not word in thing[subject]: thing[subject][word] = []\n ideal[\"verb\"] = word\n nxt()\n\n\nph = str(input(\"> \"))\nif ph != \"\":\n ph = ph.split()\n Phrase()\n print(subj)\n print(myself)\n print(things)","sub_path":"Esben2/Esben2.py","file_name":"Esben2.py","file_ext":"py","file_size_in_byte":2259,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"640499706","text":"'''\r\nCreated on Dec 2, 2016\r\n\r\n@author: Dragos Stefanescu\r\n'''\r\n\r\nclass StatisticsController:\r\n def __init__(self, student_controller , course_controller , grades_controller , average_controller ):\r\n \r\n # ASA NU: self.__controller = Controller()\r\n self.__ctrl_students = student_controller\r\n self.__ctrl_courses = course_controller\r\n self.__ctrl_grades = grades_controller\r\n self.__ctrl_average = average_controller\r\n \r\n \r\n def top_grades(self):\r\n '''\r\n Functie ce returneaza o lista cu numele si media primilor 20 % dintre studenti \r\n '''\r\n lista = []\r\n \r\n self.__ctrl_average.calc_average_for_students() \r\n # all_average = self.__ctrl_average.getAll()\r\n \r\n all_average = self.__ctrl_average.sort_average_grades()\r\n all_students = self.__ctrl_students.getAll()\r\n\r\n nr_afis = int(len(all_average) / 5)\r\n \r\n \r\n for i,average in enumerate(all_average):\r\n if i < nr_afis :\r\n for student in all_students:\r\n if student.id == average.id:\r\n lista.append([student.nume,average.avg])\r\n break\r\n else:\r\n break\r\n \r\n return lista \r\n \r\n \r\n def order_students_by_name(self,idc):\r\n '''\r\n Functie ce returneaza o lista cu studentii ordonati dupa nume , pentru o disciplina data\r\n \r\n + idc : int , id-ul disciplinei\r\n '''\r\n lista = []\r\n \r\n IDList = self.__ctrl_grades.find_students_order_name(idc) \r\n NameList = self.__ctrl_students.find_NameList(IDList)\r\n sorted_NameList = self.__ctrl_students.sort_NameList(NameList)\r\n all_grades = self.__ctrl_grades.getAll()\r\n all_students = self.__ctrl_students.getAll()\r\n \r\n for name in sorted_NameList:\r\n for student in all_students:\r\n if student.nume == name:\r\n for grade in all_grades:\r\n if grade.IDStudent == student.id and grade.IDCourse == idc:\r\n lista.append([student.nume , grade.nota])\r\n \r\n return lista \r\n \r\n def order_students_by_grade(self,idc):\r\n '''\r\n Functie ce returneaza o lista cu studentii ordonati dupa note la o anumita disciplina\r\n \r\n + idc : id-ul disciplinei\r\n '''\r\n lista = []\r\n \r\n ordered_list = self.__ctrl_grades.find_students_order_grades(idc)\r\n all_students = self.__ctrl_students.getAll()\r\n \r\n for i,grade in reversed(list(enumerate(ordered_list))):\r\n if grade != []:\r\n for id in grade:\r\n for student in all_students:\r\n if student.id == id:\r\n lista.append([student.nume , i])\r\n break\r\n \r\n return lista \r\n \r\n \r\n def getAll(self):\r\n '''\r\n Returneaza o lista cu toti pilotii.\r\n '''\r\n return self.__average_repo.getAll()\r\n","sub_path":"lab10/controller/statistics.py","file_name":"statistics.py","file_ext":"py","file_size_in_byte":3164,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"147632401","text":"# -*- coding: utf-8 -*-\n# ------------------------------------------------------------\n# TheGroove360 / XBMC Plugin\n# Canale \n# ------------------------------------------------------------\n\nimport re\n\nfrom core import config\nfrom core import httptools\nfrom core import scrapertools\nfrom core import servertools\nfrom core.item import Item\nfrom core.tmdb import infoSod\nfrom platformcode import logger\n\n__channel__ = \"serietvu\"\n\nhost = \"https://www.serietvu.online\"\n\nheaders = [['Referer', host]]\n\n\n# ----------------------------------------------------------------------------------------------------------------\ndef mainlist(item):\n logger.info(\"[SerieTVU.py]==> mainlist\")\n itemlist = [Item(channel=__channel__,\n action=\"lista_serie\",\n title=color(\"Nuove serie TV\", \"orange\"),\n url=\"%s/category/serie-tv\" % host,\n thumbnail=\"http://orig03.deviantart.net/6889/f/2014/079/7/b/movies_and_popcorn_folder_icon_by_matheusgrilo-d7ay4tw.png\"),\n Item(channel=__channel__,\n action=\"latestep\",\n title=color(\"Nuovi Episodi\", \"azure\"),\n url=\"%s/ultimi-episodi\" % host,\n thumbnail=\"http://orig03.deviantart.net/6889/f/2014/079/7/b/movies_and_popcorn_folder_icon_by_matheusgrilo-d7ay4tw.png\"),\n Item(channel=__channel__,\n action=\"lista_serie\",\n title=color(\"Serie TV Aggiornate\", \"azure\"),\n url=\"%s/ultimi-episodi\" % host,\n thumbnail=\"http://orig03.deviantart.net/6889/f/2014/079/7/b/movies_and_popcorn_folder_icon_by_matheusgrilo-d7ay4tw.png\"),\n Item(channel=__channel__,\n action=\"categorie\",\n title=color(\"Categorie\", \"azure\"),\n url=host,\n thumbnail=\"http://orig03.deviantart.net/6889/f/2014/079/7/b/movies_and_popcorn_folder_icon_by_matheusgrilo-d7ay4tw.png\"),\n Item(channel=__channel__,\n action=\"search\",\n title=color(\"Cerca ...\", \"yellow\"),\n extra=\"serie\",\n thumbnail=\"http://dc467.4shared.com/img/fEbJqOum/s7/13feaf0c8c0/Search\")]\n\n return itemlist\n\n\n# ================================================================================================================\n\n# ----------------------------------------------------------------------------------------------------------------\ndef newest(categoria):\n logger.info(\"[SerieTVU.py]==> newest\" + categoria)\n itemlist = []\n item = Item()\n try:\n if categoria == \"series\":\n item.url = host + \"/ultimi-episodi\"\n item.action = \"latestep\"\n itemlist = latestep(item)\n\n if itemlist[-1].action == \"latestep\":\n itemlist.pop()\n\n # Continua la ricerca in caso di errore \n except:\n import sys\n for line in sys.exc_info():\n logger.error(\"{0}\".format(line))\n return []\n\n return itemlist\n\n\n# ================================================================================================================\n\n# ----------------------------------------------------------------------------------------------------------------\ndef search(item, texto):\n logger.info(\"[SerieTVU.py]==> search\")\n item.url = host + \"/?s=\" + texto\n try:\n return lista_serie(item)\n # Continua la ricerca in caso di errore \n except:\n import sys\n for line in sys.exc_info():\n logger.error(\"%s\" % line)\n return []\n\n\n# ================================================================================================================\n\n# ----------------------------------------------------------------------------------------------------------------\ndef categorie(item):\n logger.info(\"[SerieTVU.py]==> categorie\")\n itemlist = []\n\n data = httptools.downloadpage(item.url, headers=headers).data\n blocco = scrapertools.get_match(data, r'

Sfoglia

\\s*
    (.*?)
\\s*')\n patron = r'
  • ([^<]+)
  • '\n matches = re.compile(patron, re.DOTALL).findall(blocco)\n\n for scrapedurl, scrapedtitle in matches:\n itemlist.append(\n Item(channel=__channel__,\n action=\"lista_serie\",\n title=scrapedtitle,\n contentType=\"tv\",\n url=\"%s%s\" % (host, scrapedurl),\n thumbnail=item.thumbnail,\n folder=True))\n\n return itemlist\n\n\n# ================================================================================================================\n\n# ----------------------------------------------------------------------------------------------------------------\ndef latestep(item):\n logger.info(\"[SerieTVU.py]==> latestep\")\n itemlist = []\n\n data = httptools.downloadpage(item.url, headers=headers).data\n\n patron = r'
    \\s*'\n patron += r'[^>]+>[^>]+>[^>]+>[^>]+>([^<]+)([^<]+)<'\n matches = re.compile(patron, re.DOTALL).findall(data)\n\n for scrapedurl, scrapedimg, scrapedtitle, scrapedinfo in matches:\n scrapedtitle = scrapertools.decodeHtmlentities(scrapedtitle.strip())\n episodio = re.compile(r'(\\d+)x(\\d+)', re.DOTALL).findall(scrapedinfo)\n title = \"%s %s\" % (scrapedtitle, scrapedinfo)\n itemlist.append(infoSod(\n Item(channel=__channel__,\n action=\"findepisodevideo\",\n title=title,\n fulltitle=scrapedtitle,\n url=scrapedurl,\n extra=episodio,\n thumbnail=scrapedimg,\n show=title,\n folder=True), tipo=\"tv\"))\n return itemlist\n\n\n# ================================================================================================================\n\n# ----------------------------------------------------------------------------------------------------------------\ndef lista_serie(item):\n logger.info(\"[SerieTVU.py]==> lista_serie\")\n itemlist = []\n\n data = httptools.downloadpage(item.url, headers=headers).data\n\n patron = r'' % value\n blocco = scrapertools.find_single_match(data, patron)\n\n patron = r'()[^>]+>[^>]+>([^<]+)
    '\n matches = re.compile(patron, re.DOTALL).findall(blocco)\n for scrapedextra, scrapedurl, scrapedimg, scrapedtitle in matches:\n number = scrapertools.decodeHtmlentities(scrapedtitle.replace(\"Episodio\", \"\")).strip()\n itemlist.append(\n Item(channel=__channel__,\n action=\"findvideos\",\n title=value + \"x\" + number.zfill(2),\n fulltitle=scrapedtitle,\n contentType=\"episode\",\n url=scrapedurl,\n thumbnail=scrapedimg,\n extra=scrapedextra,\n folder=True))\n\n if config.get_library_support() and len(itemlist) != 0:\n itemlist.append(\n Item(channel=__channel__,\n title=\"Aggiungi alla libreria\",\n url=item.url,\n action=\"add_serie_to_library\",\n extra=\"episodios\",\n show=item.show))\n\n return itemlist\n\n\n# ================================================================================================================\n\n# ----------------------------------------------------------------------------------------------------------------\ndef findvideos(item):\n logger.info(\"[SerieTVU.py]==> findvideos\")\n itemlist = servertools.find_video_items(data=item.extra)\n\n for videoitem in itemlist:\n server = re.sub(r'[-\\[\\]\\s]+', '', videoitem.title).capitalize()\n videoitem.title = \"\".join([\"[%s] \" % color(server, 'orange'), item.title])\n videoitem.fulltitle = item.fulltitle\n videoitem.thumbnail = item.thumbnail\n videoitem.show = item.show\n videoitem.plot = item.plot\n videoitem.channel = __channel__\n\n return itemlist\n\n\n# ================================================================================================================\n\n# ----------------------------------------------------------------------------------------------------------------\ndef findepisodevideo(item):\n logger.info(\"[SerieTVU.py]==> findepisodevideo\")\n\n # Download Pagina\n data = httptools.downloadpage(item.url, headers=headers).data\n\n # Prendo il blocco specifico per la stagione richiesta\n patron = r'
    (.*?)
    \\s*' % item.extra[0][0]\n blocco = scrapertools.find_single_match(data, patron)\n\n # Estraggo l'episodio\n patron = r'
    ' % item.extra[0][1].lstrip(\"0\")\n matches = re.compile(patron, re.DOTALL).findall(blocco)\n\n itemlist = servertools.find_video_items(data=matches[0][0])\n\n for videoitem in itemlist:\n server = re.sub(r'[-\\[\\]\\s]+', '', videoitem.title).capitalize()\n videoitem.title = \"\".join([\"[%s] \" % color(server, 'orange'), item.title])\n videoitem.fulltitle = item.fulltitle\n videoitem.thumbnail = item.thumbnail\n videoitem.show = item.show\n videoitem.plot = item.plot\n videoitem.channel = __channel__\n\n return itemlist\n\n\n# ================================================================================================================\n\n# ----------------------------------------------------------------------------------------------------------------\ndef HomePage(item):\n import xbmc\n xbmc.executebuiltin(\"ReplaceWindow(10024,plugin://plugin.video.Stefano/)\")\n\n\ndef color(text, color):\n return \"[COLOR \" + color + \"]\" + text + \"[/COLOR]\"\n\n# ================================================================================================================\n","sub_path":"channels/serietvu.py","file_name":"serietvu.py","file_ext":"py","file_size_in_byte":12080,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"641163742","text":"#Algoritme werkt enkel op gebruikt van ladders\n#Beter algoritme zoeken\n\ndef count():\n dimensie = int(input())\n\n tot = int(input())\n\n ladders = {}\n slangen = {}\n for _ in range(tot):\n x, y = input().split()\n if int(x) < int(y):\n ladders[int(x)] = int(y)\n else:\n slangen[int(x)] = int(y)\n\n return lds(dimensie, ladders, slangen)\n\n\ndef lds(d, l, s):\n pos = 0\n\n c = 0\n\n einde = d * d\n\n while pos < einde:\n tmp = pos\n for i in range(1, 7):\n if pos + i in l and pos + i not in s:\n tmp = l[pos + i] if l[pos + i] > tmp else tmp\n if pos + i not in s and pos + i > tmp:\n tmp = pos + i\n\n if pos == tmp:\n for i in range(1, 7):\n if pos + i not in s:\n tmp = pos + i\n c += 1\n\n pos = tmp\n\n return c\n\n\nfor i in range(1, int(input()) + 1):\n print(\"{} {}\".format(i, count()))\n\n \n","sub_path":"2016/4 - Ladderspel.py","file_name":"4 - Ladderspel.py","file_ext":"py","file_size_in_byte":975,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"42535785","text":"#!/usr/bin/env python\r\n# -*- encoding: utf-8 -*-\r\n# Created on 2015\r\n# Project: Parsing_cknufa\r\n\r\nfrom pyspider.libs.base_handler import *\r\nimport selen\r\nimport re\r\nfrom datetime import datetime, date, time\r\ninformation = []\r\nd = {}\r\nc = {}\r\nclass Handler(BaseHandler):\r\n crawl_config = {\r\n }\r\n\r\n @every(minutes=2 * 6)\r\n def on_start(self):\r\n self.crawl('http://cknufa.ru/search/9oaaa_x_a_n_n_n_z/', callback=self.index_page)\r\n for page in range(1, 15):\r\n self.crawl('http://cknufa.ru/search/9oaaa_x_a_n_n_n_z/' + str(page) + \"/\", callback=self.index_page)\r\n\r\n\r\n @config(age=10 * 24 * 60 * 60)\r\n def index_page(self, response):\r\n\r\n context = response.doc('.search_result')\r\n\r\n\r\n for item in context('tr').items():\r\n location = item.attr('onclick')\r\n if location:\r\n link = 'http://cknufa.ru'+location.split(\"'\")[1]\r\n self.crawl(link, callback=self.ofis)\r\n\r\n def url_photo(resp_photo):\r\n all_photo = []\r\n for photos in resp_photo:\r\n all_photo.append(photos.attr.href)\r\n return all_photo\r\n\r\n def today(resp_date):\r\n date_today = date.today()\r\n if 'сегодня' in resp_date:\r\n return str(date_today)\r\n elif 'вчера' in resp_date:\r\n return str(date_today.replace(day=date_today.day - 1))\r\n else:\r\n return resp_date\r\n\r\n @config()\r\n def ofis(self, response):\r\n #inf = response.doc('tr')\r\n #for item in inf('tr').text():\r\n # information.append(item)\r\n for item in response.doc('div.main_side > table > tr').items():\r\n information = item\r\n key = information('td:first').text()\r\n value = information('td:last').text()\r\n d[key] = value\r\n i = 0\r\n for item in response.doc('div.contact_card > div > p').items():\r\n information = item\r\n key = i\r\n value = information('p:last').text()\r\n c[key] = value\r\n i = i + 1\r\n\r\n #information = response.doc('td.l_col').text()\r\n #sdelka = information.split(' ')[0]\r\n #ploschad = information.split(' ')[1:5]\r\n #floor = information.split(' ')[4:7]\r\n #rayon = information.split(' ')[6]\r\n return {\r\n \"path_screen\": selen.screen_cknufa(response.url),\r\n \"Номер объекта\": d.get('Номер объекта'),\r\n \"Цена\": d.get(''),\r\n \"Парковка\": d.get('Парковка'),\r\n \"Владелец\": d.get('Владелец'),\r\n \"Высота потолка\": d.get('Высота потолка'),\r\n \"Электричество\": d.get('Электричество'),\r\n \"Окружение\": d.get('Окружение'),\r\n \"Район\": d.get('Район'),\r\n \"Адрес\": d.get('Адрес'),\r\n \"Сделка\": d.get('Сделка'),\r\n \"Этаж\": d.get('Этаж'),\r\n \"Площадь\": d.get('Площадь'),\r\n \"Месторасположение\": d.get('Месторасположение'),\r\n \"Расположение\": d.get('Расположение'),\r\n \"Отделка\": d.get('Отделка'),\r\n \"Коммуникации\": d.get('Коммуникации'),\r\n \"Назначение\": d.get('Назначение'),\r\n \"Остановка о/т\": d.get('Остановка о/т'),\r\n \"Собственник\": d.get('Собственник'),\r\n \"Телефон\": c[2].split(\":\")[1].split(\" \")[1],\r\n \"ФИО\": c[1],\r\n \"E-mail\": c[3].split(\":\")[1].split(\" \")[1],\r\n \"Photo\": Handler.url_photo(response.doc('a.a_img').items()),\r\n\r\n\r\n }","sub_path":"parsing_cknufa.py","file_name":"parsing_cknufa.py","file_ext":"py","file_size_in_byte":3858,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"410328877","text":"import torch\nfrom models.Siam_unet import SiamUNet, SiamUNetU\nfrom models.deeplabv3 import DeepLabV3\nfrom torch.autograd import Variable\nimport utils.dataset_deeplab as my_dataset\nimport cv2\nimport numpy as np\nimport config.rssia_config as cfg\nimport os\nimport preprocessing.transforms as trans\nfrom torch.utils.data import DataLoader\nfrom preprocessing.crop_img import splitimage\nfrom PIL import Image\n\n# def img_process(img1, img2, lbl, flag='test'):\n# img1 = img1[:, :, ::-1] # RGB -> BGR\n# img1 = img1.astype(np.float64)\n# img1 -= cfg.T0_MEAN_VALUE\n# img1 = img1.transpose(2, 0, 1)\n# img1 = torch.from_numpy(img1).float()\n# img2 = img2[:, :, ::-1] # RGB -> BGR\n# img2 = img2.astype(np.float64)\n# img2 -= cfg.T1_MEAN_VALUE\n# img2 = img2.transpose(2, 0, 1)\n# img2 = torch.from_numpy(img2).float()\n# if flag != 'test':\n# lbl = np.expand_dims(lbl, axis=0)\n# lbl = torch.from_numpy(np.where(lbl > 128, 1.0, 0.0)).float()\n# return img1,img2\ndef prediction( weight):\n\n best_metric = 0\n train_transform_det = trans.Compose([\n trans.Scale(cfg.TRANSFROM_SCALES),\n ])\n val_transform_det = trans.Compose([\n trans.Scale(cfg.TRANSFROM_SCALES),\n ])\n test_transform_det = trans.Compose([\n trans.Scale((960,960)),\n ])\n model = DeepLabV3(model_id=1,project_dir=cfg.BASE_PATH)\n # model=torch.nn.DataParallel(model)\n if torch.cuda.is_available():\n model.cuda()\n # model.load_state_dict({k.replace('module.', ''): v for k, v in torch.load(weight).items()})\n # model.load_state_dict(torch.load(weight))\n checkpoint = torch.load(weight)\n model.load_state_dict(checkpoint['state_dict'])\n\n # test_data = my_dataset.Dataset(cfg.TEST_DATA_PATH, '',cfg.TEST_TXT_PATH, 'test', transform=True, transform_med=test_transform_det)\n test_data = my_dataset.Dataset(cfg.VAL_DATA_PATH, cfg.VAL_LABEL_PATH,cfg.VAL_TXT_PATH, 'val', transform=True, transform_med=test_transform_det)\n # test_data = my_dataset.Dataset(cfg.TRAIN_DATA_PATH, cfg.TRAIN_LABEL_PATH,cfg.TRAIN_TXT_PATH, 'train', transform=True, transform_med=test_transform_det)\n test_dataloader = DataLoader(test_data, batch_size=cfg.TEST_BATCH_SIZE, shuffle=False, num_workers=8, pin_memory=True)\n crop = 0\n\n for batch_idx, val_batch in enumerate(test_dataloader):\n model.eval()\n #\n # batch_x1, batch_x2, _, filename, h, w, green_mask1, green_mask2 = val_batch\n batch_det_img, _, filename, h, w,_,green_mask2 = val_batch\n # green_mask1 = green_mask1.view(output_w, output_h, -1).data.cpu().numpy()\n filename = filename[0].split('/')[-1].replace('image','mask_2017')\n if crop:\n pass\n # outputs = np.zeros((cfg.TEST_BATCH_SIZE,1,960, 960))\n #\n # while (i + w // rows <= w):\n # j = 0\n # while (j + h // cols <= h):\n # batch_x1_ij = batch_x1[0, :, i:i + w // rows, j:j + h // cols]\n # batch_x2_ij = batch_x2[0, :, i:i + w // rows, j:j + h // cols]\n # # batch_y_ij = batch_y[batch_idx,: , i:i + w // rows, j:j + h // cols]\n # batch_x1_ij = np.expand_dims(batch_x1_ij, axis=0)\n # batch_x2_ij = np.expand_dims(batch_x2_ij, axis=0)\n # batch_x1_ij, batch_x2_ij = Variable(torch.from_numpy(batch_x1_ij)).cuda(), Variable(\n # torch.from_numpy(batch_x2_ij)).cuda()\n # with torch.no_grad():\n # output = model(batch_x1_ij, batch_x2_ij)\n # output_w, output_h = output.shape[-2:]\n # output = torch.sigmoid(output).view(-1, output_w, output_h)\n #\n # output = output.data.cpu().numpy() # .resize([80, 80, 1])\n # output = np.where(output > cfg.THRESH, 255, 0)\n # outputs[0, :, i:i + w // rows, j:j + h // cols] = output\n #\n # j += h // cols\n # i += w // rows\n #\n #\n # if not os.path.exists('./change'):\n # os.mkdir('./change')\n # print('./change/{}'.format(filename))\n # cv2.imwrite('./change/crop_{}'.format(filename), outputs[0,0,:,:])\n else:\n batch_det_img = Variable(batch_det_img).cuda()\n with torch.no_grad():\n outputs = model(batch_det_img)\n\n output_w, output_h = outputs[0].shape[-2:]\n\n # green_mask2 = green_mask2.view(output_w, output_h, -1).data.cpu().numpy()\n\n output = torch.sigmoid(outputs).view(output_w, output_h, -1).data.cpu().numpy()\n # print(output.min(),output.max())\n output = np.where((output > cfg.THRESH) , 255, 0)\n if not os.path.exists('./change'):\n os.mkdir('./change')\n\n print('./change/{}'.format(filename))\n cv2.imwrite('./change/{}'.format(filename), output)\nif __name__ == \"__main__\":\n\n # weight=\"weights/CE_loss/model_tif_last.pth\"\n # weight=\"weights/model20_1.pth\"\n weight=\"weights/CE_loss/model_tif_deeplab18_bce_240*240_50.pth\"\n prediction(weight)","sub_path":"prediction_deeplab.py","file_name":"prediction_deeplab.py","file_ext":"py","file_size_in_byte":5228,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"397650012","text":"# -*- coding: utf-8 -*-\nfrom django.views.decorators.csrf import csrf_exempt\nfrom adaptor_zabbix.tasks import zabbixcallback\nfrom tools.log_tool import get_logger\nfrom tools.api_tool import log_params, api_except, json_response\n\nlogger = get_logger()\n\n\n@csrf_exempt\n@api_except\n@log_params\ndef zabbix_callback(request):\n try:\n zabbixcallback.delay(request.body)\n return json_response({'status': 0})\n except Exception as e:\n logger.info('zabbix_callback error: %s' % str(e))\n return json_response({'status': -1, 'error': str(e)})\n","sub_path":"WiseEye/alert/adaptor_zabbix/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":563,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"288913037","text":"from typing import List, Type, Optional, Dict, Tuple\n\nimport pytest\n\nfrom src.models.inventory import InventoryModel\nfrom tests.unit.models.test_discount import DATE_LATER\nfrom tests.unit.models.test_multibuy import GOODS, PERCENT, QUANTITY\n\nPRICE = 1.2\nVALID_VALUES: Tuple[Dict, Dict, Dict] = (\n {GOODS: PRICE},\n {GOODS: {\"percent\": PERCENT, \"since\": DATE_LATER, \"until\": DATE_LATER}},\n {GOODS: {\"quantity\": QUANTITY, \"discounts_goods\": GOODS, \"percent\": PERCENT}},\n)\n\n\nclass TestInventoryModel:\n @staticmethod\n def test_it_can_be_created_with_valid_data():\n InventoryModel(*VALID_VALUES)\n\n @staticmethod\n @pytest.mark.parametrize(\n \"init_params,expected_exception,exception_match\",\n [\n pytest.param(\n [[], VALID_VALUES[1], VALID_VALUES[2]], TypeError, None, id=\"non-dict goods\"\n ),\n pytest.param(\n [{1: PRICE}, VALID_VALUES[1], VALID_VALUES[2]],\n TypeError,\n None,\n id=\"non-string goods key\",\n ),\n pytest.param(\n [{\"\": PRICE, GOODS: PRICE}, VALID_VALUES[1], VALID_VALUES[2]],\n ValueError,\n \"not be empty\",\n id=\"empty string as goods key\",\n ),\n pytest.param(\n [{GOODS: 1}, VALID_VALUES[1], VALID_VALUES[2]],\n TypeError,\n None,\n id=\"integer price\",\n ),\n pytest.param(\n [{GOODS: -0.1}, VALID_VALUES[1], VALID_VALUES[2]],\n ValueError,\n \"Positive\",\n id=\"negative price\",\n ),\n pytest.param(\n [VALID_VALUES[0], {\"new\": VALID_VALUES[1][GOODS]}, VALID_VALUES[2]],\n ValueError,\n \"Unknown goods as key\",\n id=\"discounting unknown goods\",\n ),\n pytest.param(\n [VALID_VALUES[0], VALID_VALUES[1], {\"new\": VALID_VALUES[2][GOODS]}],\n ValueError,\n \"Unknown goods as key\",\n id=\"unknown multibuy goods keys\",\n ),\n pytest.param(\n [\n VALID_VALUES[0],\n VALID_VALUES[1],\n {\n GOODS: {\n \"quantity\": QUANTITY,\n \"discounts_goods\": \"new\",\n \"percent\": PERCENT,\n }\n },\n ],\n ValueError,\n \"Unknown goods as value\",\n id=\"unknown multibuy goods value\",\n ),\n ],\n )\n def test_it_refuses(\n init_params: List,\n expected_exception: Type[Exception],\n exception_match: Optional[str],\n ):\n match_args = {} if exception_match is None else {\"match\": exception_match}\n with pytest.raises(expected_exception, **match_args):\n InventoryModel(*init_params)\n","sub_path":"tests/unit/models/test_inventory.py","file_name":"test_inventory.py","file_ext":"py","file_size_in_byte":3041,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"520348343","text":"from rest_framework import serializers\nfrom .models import Post, Profile, Categories, Comments, User\nfrom account.serializers import UserSerializer\n\nclass PostSerializer(serializers.ModelSerializer):\n author = UserSerializer(read_only=True)\n comments= serializers.SerializerMethodField()\n category = serializers.SlugField(read_only=True)\n class Meta:\n model = Post\n fields = '__all__'\n\n def get_comments(self,obj):\n comments = Comments.objects.filter(post=obj.id)\n serializer = CommentSerializer(comments,many=True)\n return serializer.data\n\nclass ProfileSerializer(serializers.ModelSerializer):\n user = UserSerializer(read_only=True)\n class Meta:\n model = Profile\n fields = '__all__'\n\nclass CategoriesSerializer(serializers.ModelSerializer):\n Category_Post = PostSerializer(read_only=True, many=True)\n class Meta:\n model = Categories\n fields = ['id','category','Category_Post']\n\nclass CommentSerializer(serializers.ModelSerializer):\n user = serializers.SlugField(read_only=True)\n class Meta:\n model = Comments\n fields = '__all__'\n","sub_path":"api/serializers.py","file_name":"serializers.py","file_ext":"py","file_size_in_byte":1140,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"367678421","text":"# https://www.hackerrank.com/challenges/np-min-and-max/problem?isFullScreen=true\r\n# Problem : Compute the min along axis 1 and then print the max of that result. \r\n\r\n# Sample Input\r\n# 4 2\r\n# 2 5\r\n# 3 7\r\n# 1 3\r\n# 4 0\r\n\r\n# Sample Output\r\n# 3\r\n\r\nimport numpy as np\r\n\r\nN, M = map(int, input().split())\r\n\r\nmy_array = np.array([input().split() for _ in range(N)], int)\r\nmy_min = np.min(my_array, axis=1)\r\n\r\nprint( np.max(my_min) )","sub_path":"0_reference/Hackerrank/Practice Python/Numpy/Min and Max.py","file_name":"Min and Max.py","file_ext":"py","file_size_in_byte":424,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"470407632","text":"import uuid\n\nfrom django.core.exceptions import ValidationError\nfrom django.utils.translation import gettext_lazy as _\n\n\ndef validate_uuid4(value):\n \"\"\"\n Validate that a UUID string is in uuid4 format.\n \"\"\"\n try:\n uuid.UUID(value, version=4)\n except (AttributeError, ValueError):\n raise ValidationError(\n _(\"'%(value)s' is not a valid UUID.\"),\n params={'value': value},\n code='invalid',\n )\n","sub_path":"apps/utils/validators.py","file_name":"validators.py","file_ext":"py","file_size_in_byte":459,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"365180892","text":"class MonoAddinsGTK3Package (GitHubPackage):\n\tdef __init__ (self):\t\t\n\t\tGitHubPackage.__init__ (self, 'mono', 'mono-addins', '0.6.2',\n\t\t\trevision = 'fbe9f412705aa2f4adb0aafc56fcb15671f36fbe',\n\t\t\tconfigure_flags = [\n\t\t\t'--disable-docs',\n\t\t\t# disable gtk#2 and enable gtk#3\n\t\t\t'--disable-gui',\n\t\t\t'--enable-gui-gtk3'\n\t\t\t])\n\n\tdef prep (self):\n\t\tPackage.prep (self)\n\t\t# Force use of mcs instead of gmcs\n\t\tself.sh ('sed -ie \"s/gmcs/mcs/g\" \"configure.ac\"')\n\t\t# Run autogen, initially disabling gtk#2 \n\t\tself.sh ('./autogen.sh --prefix=\"%{prefix}\" --disable-gui')\n \nMonoAddinsGTK3Package ()","sub_path":"packages/mono-addins-gtk3.py","file_name":"mono-addins-gtk3.py","file_ext":"py","file_size_in_byte":582,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"29982688","text":"from NetworkDevices.exceptions.base import NotConnected\nfrom NetworkDevices.cisco.generic import CiscoGeneric\n\n\nclass CiscoSwitch(CiscoGeneric):\n def add_vlan(self, vlan_id, vlan_name):\n if not self.net_connect:\n raise NotConnected('There is no connection, please first create a connection')\n\n config_commands = ['vlan {0}'.format(vlan_id), 'name {0}'.format(vlan_name)]\n output = self.net_connect.send_config_set(config_commands)\n print(output)\n\n def add_vlan_to_trunk(self, vlan_id, ports):\n if not self.net_connect:\n raise NotConnected('There is no connection, please first create a connection')\n\n for port in ports:\n config_commands = ['interface {0}'.format(port), 'switchport trunk allowed vlan add {0}'.format(vlan_id)]\n self.net_connect.send_config_set(config_commands)\n","sub_path":"NetworkDevices/cisco/switch.py","file_name":"switch.py","file_ext":"py","file_size_in_byte":870,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"196760137","text":"from django.urls import path\nfrom . import views\n\nurlpatterns = [\n path('', views.landing, name='landing'),\n path('signup/', views.signup, name='signup'),\n path('logout/', views.logout_request, name='logout'),\n path('accounts/login/', views.login_request, name='login'),\n path('about/', views.about, name='about'),\n path('home/', views.home, name='home'),\n path('home/cooler/', views.cooler, name='cooler'),\n path('home/my_restaurants/', views.my_restaurants, name='my_restaurants'),\n path('discover/', views.discover, name='discover'),\n path('beers//', views.beer_detail, name='beer_detail'),\n path('cooler//add//', views.cooler_add, name='cooler_add'),\n path('cooler//remove//', views.cooler_remove, name='cooler_remove'),\n path('restaurants//', views.restaurant_detail, name='restaurant_detail'),\n path('restaurant//add//,', views.restaurant_add, name='restaurant_add'),\n path('restaurant//remove//', views.restaurant_remove, name=\"restaurant_remove\"),\n path('discover/search/', views.search, name='search'),\n path('beers//tap//', views.tap_to_rest, name=\"tap_to_rest\"),\n path('beers//untap//', views.untap_from_rest, name=\"untap_from_rest\"),\n path('beers//add_photo/', views.add_photo, name='add_photo'),\n]","sub_path":"main_app/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1492,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"467733720","text":"import json\nimport requests\nfrom flask import current_app as app\nimport jwt\nimport time\n\ntoken = None\n\n\ndef get_user_info_with_code(code):\n json_header = {'content-type': 'application/json'}\n\n token_url = \"https://{domain}/oauth/token\".format(domain=app.config[\"AUTH0_DOMAIN\"])\n token_payload = {\n 'client_id': app.config['AUTH0_CLIENT_ID'],\n 'client_secret': app.config['AUTH0_CLIENT_SECRET'],\n 'redirect_uri': app.config['AUTH0_CALLBACK_URL'],\n 'code': code,\n 'grant_type': 'authorization_code'\n }\n\n token_info = requests.post(token_url, data=json.dumps(token_payload), headers=json_header).json()\n user_url = \"https://{domain}/userinfo?access_token={access_token}\" \\\n .format(domain=app.config[\"AUTH0_DOMAIN\"], access_token=token_info['access_token'])\n\n response = requests.get(user_url)\n if response.ok:\n return response.json()\n else:\n return None\n\n\ndef get_user(user_id):\n headers = {'Authorization': \"Bearer {token}\".format(token=get_auth0_token(None)),\n 'content-type': \"application/json\"}\n url = \"{AUDIENCE}users/{user_id}\".format(AUDIENCE=app.config[\"AUTH0_API_AUDIENCE\"], user_id=user_id)\n response = requests.request(\"GET\", url, headers=headers)\n return response.json()\n\n\ndef update_user_secret(user_id):\n headers = {'Authorization': \"Bearer {token}\".format(token=get_auth0_token(None)),\n 'content-type': \"application/json\"}\n url = \"{AUDIENCE}users/{user_id}\".format(AUDIENCE=app.config[\"AUTH0_API_AUDIENCE\"], user_id=user_id)\n\n payload = {\"user_metadata\": {\"secret\": \"supersecret\"}}\n response = requests.request(\"PATCH\", url, data=json.dumps(payload), headers=headers)\n return response.json()\n\n\ndef get_auth0_token(jwt_token):\n if jwt_token is not None:\n token_payload = jwt.decode(jwt_token, verify=False)\n if int(time.time()) > int(token_payload['exp']):\n return jwt_token\n\n json_header = {'content-type': 'application/json'}\n\n token_url = \"https://{domain}/oauth/token\".format(domain=app.config[\"AUTH0_DOMAIN\"])\n\n token_payload = {\n 'client_id': app.config['AUTH0_CLIENT_ID'],\n 'client_secret': app.config['AUTH0_CLIENT_SECRET'],\n 'redirect_uri': app.config['AUTH0_CALLBACK_URL'],\n 'grant_type': 'client_credentials',\n 'audience': app.config['AUTH0_API_AUDIENCE']\n }\n token_info = requests.post(token_url, data=json.dumps(token_payload), headers=json_header).json()\n return token_info['access_token']\n","sub_path":"app/utils/auth0_helper.py","file_name":"auth0_helper.py","file_ext":"py","file_size_in_byte":2535,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"205941721","text":"import boto, os, sys\n\nAWS_ACCESS_KEY_ID = 'AKIAIG5NDQVLUQ3RYLKQ'\nAWS_SECRET_ACCESS_KEY = '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'\nbucket_name = 'global_metrics'\n\nconn = boto.connect_s3(AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY)\nbucket = conn.get_bucket(bucket_name) \n\n\ntotal_bytes = 0\nfor key in bucket:\n\ttotal_bytes += key.size\n\tprint(\"total Gbs: \"+str(total_bytes/1000000000))\nprint(\"total Gbs: \"+str(total_bytes/1000000000))","sub_path":"s3/testSize.py","file_name":"testSize.py","file_ext":"py","file_size_in_byte":429,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"185654783","text":"import os\nimport sys\nimport sklearn\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nfrom sklearn.metrics import accuracy_score\nfrom sklearn.naive_bayes import GaussianNB\nfrom sklearn.metrics import confusion_matrix\n\nsys.path.append('..')\nfrom utils.plotter import scatter_jitter, plot_confusion_matrix\n\n\npd.set_option('display.width',None)\n\n\n\n# ========== Question 2.1 --- [6 marks] ==========\n# Load the cleaned datasets train_20news.csv and test_20news.csv into pandas dataframes news_train and news_test\n# respectively. Using pandas summary methods, confirm that the data is similar in both sets.\n\ndata_path = os.path.join(os.getcwd(), 'datasets', 'train_20news.csv')\nnews_train = pd.read_csv(data_path,delimiter=',')\n\ndata_path = os.path.join(os.getcwd(), 'datasets', 'test_20news.csv')\nnews_test = pd.read_csv(data_path,delimiter=',')\n\n# print(news_train.describe())\n# print(news_train.shape)\n# print('#######################')\n# print(news_test.describe())\n# print(news_test.shape)\n\n\n# ========== Question 2.2 --- [4 marks] ==========\n# [Text] Answer (in brief) the following two questions:\n#\n# What is the assumption behing the Naive Bayes Model?\n# What would be the main issue we would have to face if we didn't make this assumption?\n\n#1,各个特征相互独立\n\n\n# ========== Question 2.3 --- [8 marks] ==========\n# [Code] By using the scatter_jitter function, display a scatter plot of the features w281_ico and w273_tek for the cleaned dataset A. Set the jitter value to an appropriate value for visualisation. Label axes appropriately.\n# [Text] What do you observe about these two features? Does this impact the validity of the Naive Bayes assumption? Why or why not?\n\n\n\nplt.figure()\nplt.subplot(111)\n\nscatter_jitter(news_train['w281_ico'],news_train['w273_tek'])\n\nplt.xlabel('w281_ico')\nplt.ylabel('w273_tek')\n\nplt.show()\n\n#有线性相关,非独立\n\n\n# ========== Question 2.4 --- [7 marks] ==========\n# [Text] What is a reasonable baseline against which to compare the classiffication performance?\n# Hint: What is the simplest classiffier you can think of?.\n# [Code] Estimate the baseline performance on the training data in terms of classification accuracy.\n\ncountFrame = news_train.groupby(\"class\").count()\n\nprint(countFrame)\n\nprint(countFrame.iloc[:,0].max())\nprint(sum(countFrame.iloc[:,0]))\n\nbasline = countFrame.iloc[:,0].max() / sum(countFrame.iloc[:,0])\n\n\n\nprint(basline)\n\n\n\n\n\n# ========== Question 2.5 --- [12 marks] ==========\n# [Code] Fit a Gaussian Naive Bayes model to the cleaned dataset.\n#\n# [Code] Report the classification accuracy on the training dataset and plot a Confusion Matrix for the result (labelling the axes appropriately).\n#\n# [Text] Comment on the performance of the model. Is the accuracy a reasonable metric to use for this dataset?\n#\n# Hint: You may make use of utility functions we provided, as well as an sklearn method for computing confusion matrices\n\n#\n#\nX = news_train.drop('class',axis=1)\n\ny = news_train['class']\n\n\n\ngnb = GaussianNB()\n\ngnb.fit(X=X,y=y)\n\ntr_pred = gnb.predict(X=X)\n\nprint(tr_pred)\n#\nca = accuracy_score(y, tr_pred)\n\ncm = confusion_matrix(y, tr_pred)\n\ncm_norm = cm/cm.sum(axis=1)[:, np.newaxis]\n\nplt.figure()\n\nplt.subplot(1,1,1)\n\nlabels = ['alt.atheism','comp.sys.ibm.pc.hardware','comp.sys.mac.hardware','rec.sport.baseball','rec.sport.hockey']\n\nsns.heatmap(cm_norm, xticklabels=labels, yticklabels=labels, vmin=0., vmax=1., annot=True)\n\nplt.title('Confusion matrix')\nplt.ylabel('True label')\nplt.xlabel('Predicted label')\n\nplt.show()\n\nprint('accuracy',ca)\n\nprint(cm)\n\n\n# ========== Question 2.6 --- [3 marks] ==========\n# [Text] Comment on the confusion matrix from the previous question. Does it look like what you would have expected? Explain.\n\n\n\n\n\n\n\n\n\n\n\n# ========== Question 2.7 --- [12 marks] ==========\n# Now we want to evaluate the generalisation of the classifier on new (i.e. unseen data).\n#\n# [Code] Use the classifier you trained in Question 2.5 (i.e. on the cleaned dataset) and test its performance on the test dataset.\n\n# Display classification accuracy and plot a confusion matrix of the performance on the test data.\n#\n# [Code] Also, reevaluate the performance of the baseline on the test data.\n#\n# [Text] In a short paragraph (3-4 sentences) compare and comment on the results with (a) the training data and (b) the baseline (on the test data).\n\n\n\n\n# labels = ['alt.atheism','comp.sys.ibm.pc.hardware','comp.sys.mac.hardware','rec.sport.baseball','rec.sport.hockey']\n#\n# X = news_train.drop('class',axis=1)\n#\n# y = news_train['class']\n#\ntestX = news_test.drop('class',axis=1)\n\ntesty = news_test['class']\n\ngnb = GaussianNB()\n\ngnb.fit(X=X,y=y)\n\ntr_pred = gnb.predict(X=testX)\n\nprint(tr_pred)\n\nca = accuracy_score(testy, tr_pred)\n\ncm = confusion_matrix(testy, tr_pred)\n\ncm_norm = cm/cm.sum(axis=1)[:, np.newaxis]\n\nplt.figure()\n\nplt.subplot(1,1,1)\n\nsns.heatmap(cm_norm, xticklabels=labels, yticklabels=labels, vmin=0., vmax=1., annot=True)\n\nplt.title('Confusion matrix')\nplt.ylabel('True label')\nplt.xlabel('Predicted label')\n\nplt.show()\n\nprint('accuracy',ca)\n\nprint(cm)\n\n\n\n###################\n\ntrainFrame = news_train.groupby(\"class\").count()\n\ncolumn = trainFrame.iloc[:,0]\n\nmaxIndex = column[column == column.max()].index.values[0]\n\ntestFrame = news_test.groupby(\"class\").count()\n\ntestMax = testFrame.iloc[4,0]\n\ntestBaseLine = testMax / sum(testFrame.iloc[:,0])\n\nprint(testBaseLine)\n\n#\n# print(countFrame.iloc[:,0].max())\n# print(sum(countFrame.iloc[:,0]))\n#\n# basline = countFrame.iloc[:,0].max() / sum(countFrame.iloc[:,0])\n\n\n\n\n# ========== Question 2.8 --- (LEVEL 11) --- [7 marks] ==========\n# [Code] Fit a Gaussian Naive Bayes model to the original raw dataset (including the outliers)\n# and test its performance on the test set.\n#\n# [Text] Comment on the output and explain why or why not cleaning affects the classifier.\n\n\n\ndata_path = os.path.join(os.getcwd(), 'datasets', 'raw_20news.csv')\nnews_raws = pd.read_csv(data_path,delimiter=',')\n\nX = news_raws.drop('class',axis=1)\n\ny = news_raws['class']\n\ntestX = news_test.drop('class',axis=1)\n\ntesty = news_test['class']\n\ngnb = GaussianNB()\n\ngnb.fit(X=X,y=y)\n\ntr_pred = gnb.predict(X=testX)\n\ncm = confusion_matrix(testy, tr_pred)\n\ncm_norm = cm/cm.sum(axis=1)[:, np.newaxis]\n\nplt.figure()\n\nplt.subplot(1,1,1)\n\nlabels = ['alt.atheism','comp.sys.ibm.pc.hardware','comp.sys.mac.hardware','rec.sport.baseball','rec.sport.hockey']\n\nsns.heatmap(cm_norm, xticklabels=labels, yticklabels=labels, vmin=0., vmax=1., annot=True)\n\nplt.title('Confusion matrix')\nplt.ylabel('True label')\nplt.xlabel('Predicted label')\n\nplt.show()\n\n\n\n\n\n","sub_path":"Assignments/NaiveBayes.py","file_name":"NaiveBayes.py","file_ext":"py","file_size_in_byte":6611,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"119764767","text":"from __future__ import absolute_import\n\nimport time\nimport logging\n\nfrom .tournament_manager_factory import (TournamentManagerFactory,\n ProbEndTournamentManagerFactory)\n\n\ndef timed_message(message, start_time):\n elapsed_time = time.time() - start_time\n return message + \" in %.1fs\" % elapsed_time\n\n\ndef setup_logging(logging_destination='console', verbosity='INFO'):\n \"\"\"Sets up logging. Call this outside of run_tournaments to avoid\n accumulating logging handlers.\"\"\"\n logHandlers = {\n 'console': logging.StreamHandler,\n 'none': logging.NullHandler,\n }\n if logging_destination == 'file':\n logHandler = logging.FileHandler('./axelrod.log')\n else:\n logHandler = logHandlers[logging_destination]()\n\n logFormatters = {\n 'console': '%(message)s',\n 'none': '',\n 'file': '%(asctime)s - %(name)s - %(levelname)s - %(message)s'\n }\n logFormatter = logging.Formatter(logFormatters[logging_destination])\n\n logHandler.setFormatter(logFormatter)\n logger = logging.getLogger('axelrod')\n logger.setLevel(verbosity.upper())\n logger.addHandler(logHandler)\n\n\ndef build_exclusions_dict(exclude_basic, exclude_ordinary,\n exclude_cheating, exclude_combined):\n \"\"\"A utility function to return a dictionary mapping tournament string names\n to booleans.\"\"\"\n return {\n 'basic_strategies': exclude_basic,\n 'ordinary_strategies': exclude_ordinary,\n 'cheating_strategies': exclude_cheating,\n 'strategies': exclude_combined}\n\n\ndef run_tournaments(cache_file='./cache.txt',\n output_directory='./',\n repetitions=10,\n turns=200,\n processes=None,\n no_ecological=False,\n rebuild_cache=False,\n exclude_combined=False,\n exclude_basic=False,\n exclude_cheating=False,\n exclude_ordinary=False,\n noise=0,\n image_format=\"svg\"):\n\n exclusions_dict = build_exclusions_dict(exclude_basic, exclude_ordinary,\n exclude_cheating, exclude_combined)\n\n exclusions = [key for key, value in exclusions_dict.items() if value]\n\n manager = TournamentManagerFactory.create_tournament_manager(\n output_directory=output_directory,\n no_ecological=no_ecological,\n rebuild_cache=rebuild_cache,\n cache_file=cache_file,\n exclusions=exclusions,\n processes=processes,\n turns=turns,\n repetitions=repetitions,\n noise=noise,\n image_format=image_format)\n\n manager.run_tournaments()\n\n\ndef run_prob_end_tournaments(cache_file='./cache.txt',\n output_directory='./',\n repetitions=10,\n prob_end=.01, # By default have mean of 100 rounds\n processes=None,\n no_ecological=False,\n rebuild_cache=False,\n exclude_combined=False,\n exclude_basic=False,\n exclude_cheating=False,\n exclude_ordinary=False,\n noise=0,\n image_format=\"svg\"):\n\n exclusions_dict = build_exclusions_dict(exclude_basic, exclude_ordinary,\n exclude_cheating, exclude_combined)\n\n exclusions = [key for key, value in exclusions_dict.items() if value]\n\n manager = ProbEndTournamentManagerFactory.create_tournament_manager(\n output_directory=output_directory,\n no_ecological=no_ecological,\n rebuild_cache=rebuild_cache,\n cache_file=cache_file,\n exclusions=exclusions,\n processes=processes,\n prob_end=prob_end,\n repetitions=repetitions,\n noise=noise,\n image_format=image_format)\n\n manager.run_tournaments()\n","sub_path":"axelrod/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":3991,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"302853772","text":"#!/usr/bin/env python2\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sun Dec 9 00:27:12 2018\n\n@author: mainampati\n\"\"\"\n\nimport os\nimport numpy as np\nimport cv2 as cv\nimport timeit\n\n\nstart = timeit.default_timer()\n\n\nmainFolder = '/home/mainampati/thesis/emodbupd/'\nresultFolder = '/home/mainampati/thesis/emodbupdRe/'\n\nnumkeypts = [100, 150, 200, 250, 391]\nforName = ['A', 'B', 'C', 'D', 'E']\n\ntotalSubfolds = os.listdir(mainFolder)\ntotalSubfolds.sort()\n\n\nfor t in range (0, len(totalSubfolds)):\n print(\" hey i am working on %s loop out of upper %s loops\" %\n ((t+1), len(totalSubfolds)))\n \n \n \n subfold = totalSubfolds[t]\n inputFolder = os.path.join(mainFolder, subfold)\n suffix = '.png'\n filename = os.listdir(inputFolder)\n \n for rname, keypoints in zip(forName, numkeypts):\n # you will get maxnNo_keypoints from maxKeypoints.py file\n maxNo_keypoints = keypoints\n \n #features = []\n final_features = np.zeros((1, maxNo_keypoints*32))\n \n L = len(filename)\n \n for i in range (0, L):\n base_filename = filename[i]\n name = os.path.join(inputFolder, base_filename)\n \n # print(name)\n img = cv.imread(name,0)\n # Initiate ORB detector\n orb = cv.ORB_create()\n # find the keypoints with ORB\n kp = orb.detect(img,None)\n # compute the descriptors with ORB\n kp, des = orb.compute(img, kp)\n\n # exracing the same length of keyponts on each file.\n \n short = des[0:maxNo_keypoints, :]\n short_flat = short.flatten('C')\n #short_flat1 = short_flat[:, np.newaxis].T\n short_flat2 = short_flat[np.newaxis, :]\n #print short_flat1.shape == short_flat2.shape\n final_features = np.r_[final_features, short_flat2]\n \n\n X_orginal = np.copy(final_features[1:, :])\n \n reName = os.path.join(resultFolder, (subfold + rname + '.npy'))\n \n np.save(reName, X_orginal)\n print(\" hey i am done with %s keypoints \" % rname)\n \n stop = timeit.default_timer()\n print(\"***** total programm excution time = %0.3f min\" % \n ((stop - start) / 60.0))","sub_path":"featureextractor1.py","file_name":"featureextractor1.py","file_ext":"py","file_size_in_byte":2258,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"137182308","text":"import unittest\nimport config\nfrom crypting.crypting import EncDec\nfrom terminal_integration.terminal_service import TerminalService\n\n\nclass TerminalServiceTest(unittest.TestCase):\n\n def setUp(self):\n self.jpg_file = \"http://domain.tld/i.jpg\"\n self.txt_file = \"http://domain.tld/i.txt\"\n\n def test_terminal_params(self):\n crypto = EncDec()\n ts1 = TerminalService(crypto.encrypt_string(self.jpg_file))\n ts2 = TerminalService(crypto.encrypt_string(self.txt_file))\n ts3 = TerminalService(crypto.encrypt_string(self.txt_file)[0:10])\n dict1 = ts1.prepare_terminal_input()\n dict2 = ts2.prepare_terminal_input()\n dict3 = ts3.prepare_terminal_input()\n assert self.jpg_file == dict1[\"file_url\"]\n assert config.extension_hash_mapper[\".jpg\"] == dict1[\"hash\"]\n assert self.txt_file == dict2[\"file_url\"]\n assert config.extension_hash_mapper[\".txt\"] == dict2[\"hash\"]\n assert dict3[\"error\"] is not None\n assert dict3[\"error\"] == \"Corrupted file URL\"\n\n\n","sub_path":"terminal_integration/test_terminal_service.py","file_name":"test_terminal_service.py","file_ext":"py","file_size_in_byte":1047,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"527207546","text":"from mod_gl import *\nfrom random import randint\n\n\nclass Gen_particules:\n\tdef __init__(__, nombre, regenere=False,\n\t\t\t\tcoords_min=(0, 0, 0), coords_max=(0, 0, 0),\n\t\t\t\tspeed_min=(-100, -100, -100), speed_max=(100, 100, 100),\n\t\t\t\tcouleur_min=(0, 0, 0), couleur_max=(255, 255, 255),\n\t\t\t\ttaille_min=2, taille_max=10,\n\t\t\t\talpha_min=1, alpha_max=255,\n\t\t\t\tperte_min=1, perte_max=254,\n\t\t\t\tgravite_min=(0, 0, 0), gravite_max=(0, 0, 0),\n\t\t\t\tlim_x=(), lim_y=(), lim_z=()):\n\n\t\t__.regenere = regenere\n\t\t__.nombre = nombre\n\n\t\t__.set_coords(coords_min, coords_max)\n\t\t__.set_speed(speed_min, speed_max)\n\t\t__.set_couleur(couleur_min, couleur_max)\n\t\t__.set_taille(taille_min, taille_max)\n\t\t__.set_alpha(alpha_min, alpha_max)\n\t\t__.set_perte(perte_min, perte_max)\n\t\t__.set_gravite(gravite_min, gravite_max)\n\t\t__.set_lim_x(lim_x)\n\t\t__.set_lim_y(lim_y)\n\t\t__.set_lim_z(lim_z)\n\t\t__.reinit_particules()\n\n\tdef reinit_particules(__): __.particules = [__.create_particule(__.Particule) for i in range(__.nombre)]\n\n\tdef _set_attr3_(__, c_min, c_max, couleur=False):\n\t\tc_min, c_max = list(c_min), list(c_max)\n\t\tfor i in range(3):\n\t\t\tif c_min[i] > c_max[i]: c_min[i], c_max[i] = c_max[i], c_min[i]\n\t\t\tif couleur: c_min[i], c_max[i] = int(c_min[i])%256, int(c_max[i])%256\n\t\t\telse: c_min[i], c_max[i] = int(c_min[i]), int(c_max[i])\n\t\treturn [c_min, c_max]\n\n\tdef _set_alpha_(__, Min, Max):\n\t\tMin, Max = int(Min)%256, int(Max)%256\n\t\tif not int(Min): Min = 1\n\t\tif Min > Max: Min, Max = Max, Min\n\t\treturn [Min, Max]\n\n\tdef _set_lim_(__, lim):\n\t\tlim = list(lim)\n\t\tif lim:\n\t\t\tif len(lim) == 1:\n\t\t\t\tif lim[0] < 0: lim.append(0)\n\t\t\t\telif lim[0] > 0: lim.insert(0, 0)\n\t\t\t\telse: lim = []\n\t\t\telse:\n\t\t\t\tif lim[0] > lim[1]: lim.reverse()\n\t\t\t\telif lim[0] == lim[1]: lim = []\n\t\telse: lim = []\n\t\treturn lim\n\n\tdef set_taille(__, Min, Max):\n\t\tMin, Max = int(Min), int(Max)\n\t\tif not int(Min): Min = 1\n\t\tif Min > Max: Min, Max = Max, Min\n\t\t__.taille = [Min, Max]\n\n\tdef set_alpha(__, Min, Max): __.alpha = __._set_alpha_(Min, Max)\n\tdef set_perte(__, Min, Max): __.perte = __._set_alpha_(Min, Max)\n\n\tdef set_lim_x(__, lim): __.lim_x = __._set_lim_(lim)\n\tdef set_lim_y(__, lim): __.lim_y = __._set_lim_(lim)\n\tdef set_lim_z(__, lim): __.lim_z = __._set_lim_(lim)\n\n\tdef set_coords(__, Min, Max): __.coords = __._set_attr3_(Min, Max)\n\tdef set_speed(__, Min, Max): __.speed = __._set_attr3_(Min, Max)\n\tdef set_gravite(__, Min, Max): __.gravite = __._set_attr3_(Min, Max)\n\tdef set_couleur(__, Min, Max): __.couleur = __._set_attr3_(Min, Max, True)\n\n\n\tdef create_particule(__, particule):\n\t\treturn particule(\n\t\t\t(\n\t\t\t\trandint(__.coords[0][0], __.coords[1][0]),\n\t\t\t\trandint(__.coords[0][1], __.coords[1][1]),\n\t\t\t\trandint(__.coords[0][2], __.coords[1][2])\n\t\t\t),\n\t\t\t(\n\t\t\t\trandint(__.speed[0][0], __.speed[1][0])/10.,\n\t\t\t\trandint(__.speed[0][1], __.speed[1][1])/10.,\n\t\t\t\trandint(__.speed[0][2], __.speed[1][2])/10.\n\t\t\t),\n\t\t\t(\n\t\t\t\trandint(__.couleur[0][0], __.couleur[1][0]),\n\t\t\t\trandint(__.couleur[0][1], __.couleur[1][1]),\n\t\t\t\trandint(__.couleur[0][2], __.couleur[1][2])\n\t\t\t),\n\t\t\trandint(__.taille[0], __.taille[1]),\n\t\t\trandint(__.alpha[0], __.alpha[1]),\n\t\t\trandint(__.perte[0], __.perte[1]),\n\t\t\t(\n\t\t\t\trandint(__.gravite[0][0], __.gravite[1][0])/10.,\n\t\t\t\trandint(__.gravite[0][1], __.gravite[1][1])/10.,\n\t\t\t\trandint(__.gravite[0][2], __.gravite[1][2])/10.\n\t\t\t)\n\t\t)\n\n\tdef draw(__):\n\t\tglEnable(GL_BLEND)\n\t\tglDisable(GL_DEPTH_TEST)\n\t\tfor i in __.particules:\n\t\t\ti.draw()\n\t\t\tif i.alpha:\n\t\t\t\tif __.lim_x:\n\t\t\t\t\tif not (__.lim_x[0] < i.x < __.lim_x[1]): i.alpha = 0\n\t\t\t\tif i.alpha and __.lim_y:\n\t\t\t\t\tif not (__.lim_y[0] < i.y < __.lim_y[1]): i.alpha = 0\n\t\t\t\tif i.alpha and __.lim_z:\n\t\t\t\t\tif not (__.lim_z[0] < i.z < __.lim_z[1]): i.alpha = 0\n\t\t\tif not i.alpha:\n\t\t\t\tif __.regenere: __.create_particule(i.__init__)\n\t\t\t\telse: __.particules.remove(i)\n\t\tglColor4ub(255, 255, 255, 255)\n\t\tglDisable(GL_BLEND)\n\t\tglEnable(GL_DEPTH_TEST)\n\n\tclass Particule:\n\t\tliste = glGenLists(1000)\n\t\tglNewList(liste, GL_COMPILE)\n\t\tglBegin(GL_POINTS)\n\t\tglVertex(0, 0, 0)\n\t\tglEnd()\n\t\tglEndList()\n\n\t\tdef __init__(__, coords, speed=(10, 10, 10), couleur=(255, 255, 255), taille=2, alpha=255, perte=1, gravite=(0, 0, 0)):\n\t\t\t__.x, __.y, __.z = coords\n\t\t\t__.xs, __.ys, __.zs = speed\n\t\t\t__.xg, __.yg, __.zg = gravite\n\t\t\t__.r, __.v, __.b = couleur\n\t\t\t__.taille = taille\n\t\t\t__.alpha = alpha\n\t\t\t__.perte = perte\n\n\t\tdef draw(__):\n\t\t\tglPointSize(__.taille)\n\t\t\tglPushMatrix()\n\t\t\tglColor4ub(__.r, __.v, __.b, __.alpha)\n\t\t\tglTranslatef(__.x, __.y, __.z)\n\t\t\tglCallList(__.liste)\n\t\t\tglPopMatrix()\n\t\t\t__.xs += __.xg\n\t\t\t__.ys += __.yg\n\t\t\t__.zs += __.zg\n\t\t\t__.x += __.xs + __.xg\n\t\t\t__.y += __.ys + __.yg\n\t\t\t__.z += __.zs + __.zg\n\t\t\t__.alpha -= __.perte\n\t\t\tif __.alpha < 0: __.alpha = 0\n","sub_path":"opengl/gen_particules.py","file_name":"gen_particules.py","file_ext":"py","file_size_in_byte":4668,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"312797433","text":"import json\nfrom datetime import datetime, timedelta, timezone\nfrom statistics import quantiles\n\nimport click\nfrom humanfriendly import parse_timespan\n\nfrom lain_cli.utils import RequestClientMixin, ensure_str, tell_cluster_info, warn\n\nLAIN_LINT_PROMETHEUS_QUERY_RANGE = '2d'\nLAIN_LINT_PROMETHEUS_QUERY_STEP = int(\n int(parse_timespan(LAIN_LINT_PROMETHEUS_QUERY_RANGE)) / 1440\n)\n\n\nclass Prometheus(RequestClientMixin):\n timeout = 20\n\n def __init__(self, endpoint=None):\n if not endpoint:\n cluster_info = tell_cluster_info()\n endpoint = cluster_info.get('prometheus')\n if not endpoint:\n raise click.Abort(f'prometheus not provided in cluster: {cluster_info}')\n\n self.endpoint = endpoint\n\n @staticmethod\n def format_time(dt):\n if isinstance(dt, str):\n return dt\n return dt.isoformat()\n\n def query_cpu(self, appname, proc_name, **kwargs):\n cluster_info = tell_cluster_info()\n query_template = cluster_info.get('pql_template', {}).get('cpu')\n if not query_template:\n raise ValueError('pql_template.cpu not configured in cluster_info')\n q = query_template.format(\n appname=appname, proc_name=proc_name, range=LAIN_LINT_PROMETHEUS_QUERY_RANGE\n )\n kwargs.setdefault('step', LAIN_LINT_PROMETHEUS_QUERY_STEP)\n kwargs['end'] = datetime.now(timezone.utc)\n res = self.query(q, **kwargs)\n return res\n\n def cpu_p95(self, appname, proc_name, **kwargs):\n cpu_result = self.query_cpu(appname, proc_name)\n # [{'metric': {}, 'value': [1595486084.053, '4.990567343235413']}]\n if cpu_result:\n cpu_top_list = [int(float(p[-1])) for p in cpu_result[0]['values']]\n cnt = len(cpu_top_list)\n if cpu_top_list.count(0) / cnt > 0.7:\n warn(f'lint suggestions might not be accurate for {proc_name}')\n\n cpu_top = int(quantiles(cpu_top_list, n=10)[-1])\n else:\n cpu_top = 5\n\n return max([cpu_top, 5])\n\n def memory_p95(self, appname, proc_name, **kwargs):\n cluster_info = tell_cluster_info()\n query_template = cluster_info.get('pql_template', {}).get('memory_p95')\n if not query_template:\n raise ValueError('pql_template.memory_p95 not configured in cluster_info')\n q = query_template.format(\n appname=appname, proc_name=proc_name, range=LAIN_LINT_PROMETHEUS_QUERY_RANGE\n )\n kwargs.setdefault('step', LAIN_LINT_PROMETHEUS_QUERY_STEP)\n res = self.query(q, **kwargs)\n if not res:\n return\n # [{'metric': {}, 'value': [1583388354.31, '744079360']}]\n memory_p95 = int(float(res[0]['value'][-1]))\n return memory_p95\n\n def query(self, query, start=None, end=None, step=None, timeout=20):\n # https://prometheus.io/docs/prometheus/latest/querying/api/#range-queries\n data = {\n 'query': query,\n 'timeout': timeout,\n }\n if start or end:\n if not start:\n start = end - timedelta(days=1)\n\n if not end:\n end = datetime.now(timezone.utc).isoformat()\n\n if not step:\n step = 60\n\n path = '/api/v1/query_range'\n data.update(\n {\n 'start': self.format_time(start),\n 'end': self.format_time(end),\n 'step': step,\n }\n )\n else:\n path = '/api/v1/query'\n\n res = self.post(path, data=data)\n try:\n responson = res.json()\n except json.decoder.JSONDecodeError as e:\n raise ValueError(\n 'cannot decode this shit: {}'.format(ensure_str(res.text))\n ) from e\n if responson.get('status') == 'error':\n raise ValueError(responson['error'])\n return responson['data']['result']\n","sub_path":"lain_cli/prometheus.py","file_name":"prometheus.py","file_ext":"py","file_size_in_byte":3976,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"186992189","text":"import os\nfrom flask import jsonify\nfrom app.libs.redprint import Redprint\nfrom app.config import setting as SETTING\napi = Redprint('tools')\n\n\n@api.route('/log', methods=['GET'])\ndef get_log():\n dataPath = SETTING.ROBOSAT_DATA_PATH\n logPath = dataPath+\"/model/log\"\n if not os.path.isfile(logPath):\n return \"未找到日志文件!,路径为:\"+logPath\n with open(logPath) as f:\n f = f.readlines()\n logContent = [\"这个是日志文件,路径为:\"+logPath, \"\", \"\"]\n for line in f:\n logContent.append(\"

    \"+line+\"

    \")\n logStr = \" \".join(logContent)\n return logStr\n\n\n@api.route('/log/clear', methods=['GET'])\ndef clear_log():\n dataPath = SETTING.ROBOSAT_DATA_PATH\n logPath = dataPath+\"/model/log\"\n if not os.path.isfile(logPath):\n return \"未找到日志文件!,路径为:\"+logPath\n open(logPath, \"w\").close()\n result = {\n \"code\": 1,\n \"msg\": \"log is clean now.\"\n }\n return jsonify(result)\n\n\ndef check_extent(extent, train_or_predict, set_maximum=False):\n result = {\n \"code\": 1,\n \"data\": None,\n \"msg\": \"ok\"\n }\n if not extent:\n result[\"code\"] = 0\n result[\"msg\"] = \"参数有误\"\n return result\n coords = extent.split(',')\n if len(coords) != 4:\n result[\"code\"] = 0\n result[\"msg\"] = \"参数有误\"\n return result\n if \"train\" in train_or_predict:\n if float(coords[2]) - float(coords[0]) < SETTING.MIN_T_EXTENT or float(coords[3]) - float(coords[1]) < SETTING.MIN_T_EXTENT:\n result[\"code\"] = 0\n result[\"msg\"] = \"Extent for training is too small. Training stopped.\"\n elif \"predict\" in train_or_predict:\n if float(coords[2]) - float(coords[0]) < SETTING.MIN_P_EXTENT or float(coords[3]) - float(coords[1]) < SETTING.MIN_P_EXTENT:\n result[\"code\"] = 0\n result[\"msg\"] = \"Extent for prediction is too small. Predicting stopped.\"\n elif float(coords[2]) - float(coords[0]) > SETTING.MAX_P_EXTENT or float(coords[3]) - float(coords[1]) > SETTING.MAX_P_EXTENT:\n result[\"code\"] = 0\n result[\"msg\"] = \"Extent for prediction is too small. Predicting stopped.\"\n elif set_maximum and float(coords[2]) - float(coords[0]) > 0.02 or float(coords[3]) - float(coords[1]) > 0.02:\n result[\"code\"] = 0\n result[\"msg\"] = \"Extent for prediction is too big. Predicting stopped.\"\n else:\n result[\"code\"] = 0\n result[\"msg\"] = \"got wrong params.\"\n return result\n","sub_path":"app/api/v1/tools.py","file_name":"tools.py","file_ext":"py","file_size_in_byte":2544,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"218543315","text":"from flask import render_template, request, jsonify, make_response\nfrom yummly import app\nfrom yummly import api\nimport random\n\n\n@app.route(\"/\", methods=[\"GET\", \"POST\"])\ndef index():\n \"\"\"\n 1. grab ingredient list\n 2. pass ingredients list to `get_ingredients()`\n 3. grab random result\n 3. return results to the template\n \"\"\"\n if request.method == \"POST\":\n ingredient_list = request.form.get('ingredient_list')\n recipe = []\n try:\n response = api.get_ingredients(ingredient_list)\n recipe = random.choice(response[\"matches\"])\n result = {\n \"recipe_id\": recipe[\"id\"],\n \"recipe_name\": recipe[\"recipeName\"],\n \"recipe_pic\": recipe['imageUrlsBySize']['90'].replace(\n 's90-c', 's230-c'\n )\n }\n code = 200\n except: # silencing all errors - bad!\n result = {\"sorry\": \"Something went terribly wrong!\"}\n code = 404\n return make_response(jsonify(result), code)\n else:\n return render_template(\"index.html\")\n","sub_path":"python/flask-yummly/yummly/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1112,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"197790246","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Jul 19 13:31:11 2018\n\n@author: lbrevaul\n\"\"\"\n\nimport numpy as np\nimport copy\nfrom openmdao.api import ExplicitComponent\nfrom scipy import interpolate, integrate\n\nfrom trajectory.Simulation_stage_1 import simulation_stage_1\nfrom trajectory.Simulation_stage_2 import simulation_stage_2\nfrom trajectory.Simulation_fallout_stage_1 import simulation_fallout_stage_1\n\nfrom trajectory.Event_meco import event_meco\nfrom trajectory.Event_fairing import event_fairing_jettison\nfrom trajectory.Event_command_stage_1 import event_command_stage_1_theta\nfrom trajectory.Event_seco import event_seco,event_seco_mass\nfrom trajectory.Event_impact import event_impact\n\nimport constants as Cst\nimport geopy.distance as dist\nimport specifications as Spec\n\n\nclass Trajectory_comp(ExplicitComponent):\n\n def setup(self):\n\n #Inputs\n self.add_input('Diameter_stage_1', val=4.6)\n self.add_input('Diameter_stage_2',val=4.6)\n self.add_input('Mass_flow_rate_stage_1', val=219.)\n self.add_input('Mass_flow_rate_stage_2', val=219.)\n self.add_input('N_eng_stage_1', val=7.)\n self.add_input('N_eng_stage_2', val=1.)\n self.add_input('OF_stage_1',val=3.)\n self.add_input('OF_stage_2',val=3.)\n self.add_input('Isp_stage_1',val=320.)\n self.add_input('Isp_stage_2',val=359.)\n self.add_input('Prop_mass_stage_1',val=350000.)\n self.add_input('Prop_mass_stage_2',val=75000.)\n self.add_input('Dry_mass_stage_1',val= 24000.)\n self.add_input('Dry_mass_stage_2',val=3994.)\n self.add_input('Pitch_over_duration',val=5.)\n self.add_input('thetacmd_i',val=2.72)\n self.add_input('thetacmd_f',val=20.)\n self.add_input('ksi',val=0.293)\n self.add_input('Exit_nozzle_area_stage_1',val = 0.82)\n self.add_input('Exit_nozzle_area_stage_2',val = 1.)\n self.add_input('Delta_vertical_phase',val=10.)\n self.add_input('Delta_theta_pitch_over',val = 1.) \n self.add_input('Table_CX_complete_ascent' ,shape = (20,15))\n self.add_input('Mach_table',val =np.ones(20)) \n self.add_input('AoA_table',val =np.ones(15)) \n self.add_input('command_stage_1_exo',val =np.array([1.,1.])) \n self.add_input('CX_fallout_stage_1',val = 1.) \n self.add_input('CZ_fallout_stage_1',val = 1.) \n self.add_input('is_fallout',val = 1.) \n\n \n ## Outputs\n self.add_output('T_ascent',shape = 4000) \n self.add_output('alt_ascent',shape = 4000)\n self.add_output('flux_ascent',shape = 4000)\n self.add_output('r_ascent',shape = 4000)\n self.add_output('V_ascent',shape = 4000)\n self.add_output('theta_ascent',shape = 4000)\n self.add_output('alpha_ascent',shape = 4000)\n self.add_output('nx_ascent',shape = 4000)\n self.add_output('alpha_cont',val= 10.)\n self.add_output('Nb_pt_ascent',val= 100.)\n self.add_output('m_ascent',shape = 4000)\n self.add_output('CX_ascent',shape = 4000)\n self.add_output('GLOW',val= 38000.)\n self.add_output('lat_ascent',shape = 4000)\n self.add_output('gamma_ascent',shape = 4000)\n self.add_output('longi_ascent',shape = 4000)\n self.add_output('thrust_ascent',shape = 4000)\n self.add_output('mass_flow_rate_ascent',shape = 4000)\n self.add_output('Mach_ascent',shape = 4000)\n self.add_output('pdyn_ascent',shape = 4000)\n self.add_output('rho_ascent',shape = 4000)\n self.add_output('distance_ascent',shape = 4000)\n \n self.add_output('T_fallout',shape = 1000) \n self.add_output('alt_fallout',shape = 1000)\n self.add_output('flux_fallout',shape = 1000)\n self.add_output('r_fallout',shape = 1000)\n self.add_output('V_fallout',shape = 1000)\n self.add_output('theta_fallout',shape = 1000)\n self.add_output('alpha_fallout',shape = 1000)\n self.add_output('nx_fallout',shape = 1000)\n self.add_output('Nb_pt_fallout',val= 1000)\n self.add_output('m_fallout',shape = 1000)\n self.add_output('CX_fallout',shape = 1000)\n self.add_output('CZ_fallout',shape = 1000)\n self.add_output('lat_fallout',shape = 1000)\n self.add_output('gamma_fallout',shape = 1000)\n self.add_output('longi_fallout',shape = 1000)\n self.add_output('thrust_fallout',shape = 1000)\n self.add_output('mass_flow_rate_fallout',shape = 1000)\n self.add_output('Mach_fallout',shape = 1000)\n self.add_output('pdyn_fallout',shape = 1000)\n self.add_output('rho_fallout',shape = 1000)\n self.add_output('distance_fallout',shape = 1000)\n \n \n self.add_output('state_separation_stage_1',shape=(5,)) \n self.add_output('max_pdyn_load_ascent_stage_1',val=40e3) \n\n def compute(self, inputs, outputs):\n \n #Integration parameters \n atol_integration =1e-4\n rtol_integration=1e-4\n integration_method = 'BDF' #Implicit method based on backward-differentiation formulas see Scipy for more details\n step=2.\n\n #Constant definition\n Constants = {}\n Constants['r0'] = Cst.r0\n Constants['V0'] = Cst.V0\n Constants['gamma0'] = Cst.gamma0\n Constants['longi0'] = Spec.specifications['launch_site']['longitude']*np.pi/180. \n\n Constants['longi_Kourou'] =Spec.specifications['launch_site']['longitude']\n Constants['lat_Kourou'] = Spec.specifications['launch_site']['latitude']\n Constants['Payload_mass'] = Spec.specifications['mission']['Payload_mass']\n Constants['Fairing_mass'] =Spec.specifications['stage_2_additional_masses']['Fairing_mass']\n\n Duration_stage_separation = Cst.Duration_stage_separation\n\n ######################## 1st stage definition ###################################\n #Mass and time definition\n tf1 = (inputs['Prop_mass_stage_1'])/(inputs['N_eng_stage_1']*inputs['Mass_flow_rate_stage_1']*0.8) #time of flight\n initial_mass = inputs['Dry_mass_stage_1'] + inputs['Dry_mass_stage_2'] +\\\n inputs['Prop_mass_stage_1'] + inputs['Prop_mass_stage_2']+\\\n Constants['Payload_mass'] + Constants['Fairing_mass'] #Gross Lift-Off Weight (GLOW)\n\n outputs['GLOW'] = initial_mass #Gross Lift-Off Weight (GLOW)\n final_mass_stage_1 = initial_mass -inputs['Prop_mass_stage_1'][0] #Supposed final mass after stage 1 propellant combustion\n #table_alt_theta_stage_1 = np.array([-1.,2000e3]) #table for pitch angle interpolation as a function of altitude\n #interp_theta_stage_1 = interpolate.interp1d(table_alt_theta_stage_1,inputs['command_stage_1_exo'],kind='linear') #interpolant for pitch angle control\n\n #Aerodynamics definition (table of Mach, Incidence (alpha), and resulting drag coefficient CX)\n Table_Mach_ = inputs['Mach_table'] \n Table_incidence = inputs['AoA_table']\n Interp2_CX_complete_launcher=interpolate.interp2d(Table_incidence,Table_Mach_,inputs['Table_CX_complete_ascent'])\n \n ######################## 2nd stage definition ###################################\n tf2 = inputs['Prop_mass_stage_2']/(inputs['Mass_flow_rate_stage_2'][0]*(1-(1-Cst.derating_stage_2))) #time of flight 2nd stage\n final_mass_stage_2 = inputs['Dry_mass_stage_2'] + Constants['Payload_mass'] #expected final mass of the 2nd stage\n\n ##################### Definition of parameter dictionary for 1st stage ###############\n param_integration_stage_1 = {} \n param_integration_stage_1['aero'] = {}\n param_integration_stage_1['aero']['Interp_CX_stage_1'] = Interp2_CX_complete_launcher\n \n param_integration_stage_1['propulsion'] = {}\n param_integration_stage_1['propulsion']['Mass_flow_rate']=inputs['Mass_flow_rate_stage_1'][0]\n param_integration_stage_1['propulsion']['Isp']=inputs['Isp_stage_1'][0] #specific impulse estimated by propulsion discipline\n param_integration_stage_1['propulsion']['N_eng']=inputs['N_eng_stage_1'][0] #number of engines\n \n param_integration_stage_1['masses'] = {}\n param_integration_stage_1['masses']['Mass_f']= final_mass_stage_1\n \n param_integration_stage_1['command'] = {}\n param_integration_stage_1['command']['Pitch_over_duration'] = inputs['Pitch_over_duration'][0] #duration of the pitch over manoeuver\n param_integration_stage_1['command']['Delta_theta_pitch_over'] = inputs['Delta_theta_pitch_over'][0] #angle of pitch for the pitch over manoeuver\n param_integration_stage_1['command']['Delta_vertical_phase'] = inputs['Delta_vertical_phase'][0] #duration of the vertical lift-off phase\n param_integration_stage_1['command']['Interp_theta_stage_1'] = 0.#interp_theta_stage_1\n \n param_integration_stage_1['geometry'] = {}\n param_integration_stage_1['geometry']['Exit_nozzle_area']=inputs['Exit_nozzle_area_stage_1'][0]\n param_integration_stage_1['geometry']['Diameter']=np.max([inputs['Diameter_stage_1'][0],inputs['Diameter_stage_2'][0]])\n \n param_integration_stage_1['simu'] = {}\n param_integration_stage_1['simu']['Mode_simu']= 1. #integration (1) or simulation (0)\n\n \n ############ structure for output data ###############\n data_simu = {}\n data_simu['T'] = np.empty((1)) #Time (s)\n data_simu['nx'] = np.empty((1)) #Axial load factor\n data_simu['Mach'] = np.empty((1)) #Mach \n data_simu['pdyn'] = np.empty((1)) #Dynamic pressure (W/m2)\n data_simu['flux'] = np.empty((1)) #Heat flux (kg m^-2 s^-1) \n data_simu['alt'] = np.empty((1)) #altitude (m) \n data_simu['alpha'] = np.empty((1)) #angle of attack (rad) \n data_simu['theta'] = np.empty((1)) #pitch angle (rad) \n data_simu['r'] = np.empty((1)) #altitude from the center of the Earth (m) \n data_simu['V'] = np.empty((1)) #norm of velocity (m/s) \n data_simu['gamma'] = np.empty((1)) #flight path angle (rad)\n data_simu['rho'] = np.empty((1)) #air density (kg/m3) \n data_simu['CX'] = np.empty((1)) #drag coefficient \n data_simu['thrust'] = np.empty((1)) #thrust (N) \n data_simu['mass_flow_rate'] = np.empty((1)) #mass flow rate (kg/s) \n data_simu['lat'] = np.empty((1)) #latitude (rad) \n data_simu['longi'] = np.empty((1)) #longitude (rad) \n data_simu['m'] = np.empty((1)) #launcher mass (kg)\n data_simu['distance'] = np.empty((1)) #distance from launch pad (m) \n\n \n # definition of considered events\n event_fairing_ = lambda t,x :event_fairing_jettison(t,x,param_integration_stage_1) #event jettison fairing if heat flux below 1135 (kg m^-2 s^-1) \n event_fairing_.terminal = True\n event_fairing_.direction = -1\n\n event_meco_ = lambda t,x :event_meco(t,x,param_integration_stage_1) #main engine cut-off if propellant mass = 0.\n event_meco_.terminal = True\n event_meco_.direction = -1 \n \n event_exo_flight_ = lambda t,x :event_command_stage_1_theta(t,x,param_integration_stage_1) #end of gravity turn\n event_exo_flight_.terminal = True\n event_exo_flight_.direction = -1 \n \n event_impact_ = lambda t,x :event_impact(t,x,param_integration_stage_1) #launcher impact the ground\n event_impact_.terminal = True\n event_impact_.direction = -1 \n \n fonction_ode_integration = lambda t,x :simulation_stage_1(t,x,param_integration_stage_1) #launcher simulation equations of motion\n \n param_simu_stage_1 = copy.deepcopy(param_integration_stage_1) \n param_simu_stage_1['simu']['Mode_simu']=0.\n \n fonction_ode_simu = lambda t,x :simulation_stage_1(t,x,param_simu_stage_1) #launcher simulation equations of motion\n\n initial_state = np.array([Constants['r0'],\\\n Constants['V0'],\\\n Constants['gamma0'],\\\n Constants['longi0'],\\\n initial_mass]) #initial state of launcher\n \n span_integration = (0.,tf1)\n \n #settings of event caracteristics\n dico_events_stage_1 = {}\n dico_events_stage_1['MECO'] = {}\n dico_events_stage_1['MECO']['actif'] = False\n dico_events_stage_1['MECO']['instant'] = 0.\n dico_events_stage_1['MECO']['state'] = 0.\n \n dico_events_stage_1['fairing'] = {}\n dico_events_stage_1['fairing']['actif'] = False\n dico_events_stage_1['fairing']['instant'] = 0.\n dico_events_stage_1['fairing']['state'] = 0.\n\n dico_events_stage_1['exo_flight'] = {}\n dico_events_stage_1['exo_flight']['actif'] = False\n dico_events_stage_1['exo_flight']['instant'] = 0. \n dico_events_stage_1['exo_flight']['state'] = 0. \n \n dico_events_stage_1['impact'] = {}\n dico_events_stage_1['impact']['actif'] = False\n dico_events_stage_1['impact']['instant'] = 0.\n dico_events_stage_1['impact']['state']= 0.\n \n dico_events_stage_1['list_name_events'] = ['MECO','fairing','exo_flight','impact']\n dico_events_stage_1['list_events'] = [event_meco_,event_fairing_,event_exo_flight_,event_impact_]\n\n num_phase = 0\n final_time = 0.\n ##### integration of stage 1 trajectory\n while dico_events_stage_1['MECO']['actif'] == False and dico_events_stage_1['impact']['actif'] == False and final_time 0:\n dico_events_stage_1[dico_events_stage_1['list_name_events'][j]]['actif'] = True \n dico_events_stage_1[dico_events_stage_1['list_name_events'][j]]['instant'] = current_sol.t_events[j][0] \n dico_events_stage_1[dico_events_stage_1['list_name_events'][j]]['state']= current_sol.y[:,-1].copy()\n \n if dico_events_stage_1['list_name_events'][j] == 'fairing': ### largage coiffe \n initial_state[-1] = initial_state[-1] - Constants['Fairing_mass']\n param_integration_stage_1['masses']['Mass_f']= final_mass_stage_1 - Constants['Fairing_mass']\n\n if dico_events_stage_1['list_name_events'][j]=='exo_flight':\n #creation of interpolation of theta_stage_1 for exo atmospheric phase\n table_m_theta_stage_1 = np.array([current_m[-1][0]+1e3,final_mass_stage_1[0]-50e3]) #table for pitch angle interpolation as a function of mass\n interp_theta_stage_1 = interpolate.interp1d(table_m_theta_stage_1,inputs['command_stage_1_exo'],kind='linear') #interpolant for pitch angle control\n param_integration_stage_1['command']['Interp_theta_stage_1'] = interp_theta_stage_1\n param_simu_stage_1['command']['Interp_theta_stage_1'] = interp_theta_stage_1\n \n # update of the list of events\n for k in reversed(range(len(dico_events_stage_1['list_events']))):\n if len(current_sol.t_events[k])>0:\n del dico_events_stage_1['list_events'][k]\n del dico_events_stage_1['list_name_events'][k]\n \n span_integration = (current_sol.t[-1],tf1)\n final_time = current_sol.t[-1]\n\n # save of trajectory data of the current phase \n if num_phase == 0:\n data_simu['T'] = np.array([current_T]).T\n data_simu['nx'] = current_NX\n data_simu['Mach'] = current_Mach \n data_simu['pdyn'] = current_Pdyn \n data_simu['flux'] = current_flux \n data_simu['r'] = current_r \n data_simu['alt'] = current_alt \n data_simu['alpha'] = current_alpha*180/np.pi\n data_simu['gamma'] = current_gamma*180/np.pi\n data_simu['theta'] = current_theta*180/np.pi\n data_simu['V'] = current_V\n data_simu['rho'] = current_rho\n data_simu['CX'] = current_CX\n data_simu['thrust'] = current_thrust\n data_simu['mass_flow_rate'] = current_mass_flow_rate\n data_simu['lat'] = current_lat*180/np.pi\n data_simu['longi'] = current_longi*180/np.pi\n data_simu['m'] =current_m\n data_simu['distance'] =current_distance\n\n\n else:\n data_simu['T'] = np.concatenate((data_simu['T'],np.array([current_T]).T))\n data_simu['nx'] = np.concatenate((data_simu['nx'],current_NX))\n data_simu['Mach'] = np.concatenate((data_simu['Mach'],current_Mach))\n data_simu['pdyn'] = np.concatenate((data_simu['pdyn'],current_Pdyn))\n data_simu['flux'] = np.concatenate((data_simu['flux'],current_flux))\n data_simu['alt'] = np.concatenate((data_simu['alt'],current_alt))\n data_simu['alpha'] = np.concatenate((data_simu['alpha'],current_alpha*180/np.pi))\n data_simu['gamma'] = np.concatenate((data_simu['gamma'],current_gamma*180/np.pi))\n data_simu['theta'] = np.concatenate((data_simu['theta'],current_theta*180/np.pi))\n data_simu['V'] = np.concatenate((data_simu['V'],current_V))\n data_simu['rho'] = np.concatenate((data_simu['rho'],current_rho))\n data_simu['CX'] = np.concatenate((data_simu['CX'],current_CX))\n data_simu['thrust'] = np.concatenate((data_simu['thrust'],current_thrust))\n data_simu['mass_flow_rate'] = np.concatenate((data_simu['mass_flow_rate'],current_mass_flow_rate))\n data_simu['lat'] = np.concatenate((data_simu['lat'],current_lat*180/np.pi))\n data_simu['longi'] = np.concatenate((data_simu['longi'],current_longi*180/np.pi))\n data_simu['m'] = np.concatenate((data_simu['m'],current_m))\n data_simu['distance'] =np.concatenate((data_simu['distance'],current_distance))\n data_simu['r'] =np.concatenate((data_simu['r'],current_r))\n\n num_phase = num_phase + 1\n \n state_separation_stage_1 = current_sol.y[:,-1].copy() \n outputs['state_separation_stage_1'] = state_separation_stage_1\n outputs['max_pdyn_load_ascent_stage_1'] = np.max(data_simu['pdyn'])\n \n####################################### 2nd stage ####################################################################\n\n instant_end_flight_stage_1 = current_sol.t[-1].copy()\n outputs['alpha_cont']=np.max(np.abs(data_simu['alpha']))\n\n\n if dico_events_stage_1['impact']['actif'] == False:\n ################ definition of parameters for 2nd stage ###############\n param_integration_stage_2 = {} \n param_integration_stage_2['aero'] = {}\n \n param_integration_stage_2['propulsion'] = {}\n param_integration_stage_2['propulsion']['Mass_flow_rate']=inputs['Mass_flow_rate_stage_2'][0]\n param_integration_stage_2['propulsion']['Isp']=inputs['Isp_stage_2'][0]\n param_integration_stage_2['propulsion']['N_eng']=inputs['N_eng_stage_2'][0]\n \n param_integration_stage_2['masses'] = {}\n param_integration_stage_2['masses']['Mass_f']=final_mass_stage_2\n \n param_integration_stage_2['command'] = {}\n param_integration_stage_2['command']['Theta_i']=inputs['thetacmd_i'][0]\n param_integration_stage_2['command']['Theta_f']=inputs['thetacmd_f'][0]\n param_integration_stage_2['command']['Ksi']=inputs['ksi'][0]\n \n param_integration_stage_2['geometry'] = {}\n param_integration_stage_2['geometry']['Exit_nozzle_area']=inputs['Exit_nozzle_area_stage_2'][0]\n param_integration_stage_2['geometry']['Diameter']=inputs['Diameter_stage_2'][0]\n \n param_integration_stage_2['simu'] = {}\n param_integration_stage_2['simu']['Mode_simu']= 1.#integration (1)ou simulation (0)\n param_integration_stage_2['simu']['Duration_separation'] = Duration_stage_separation\n param_integration_stage_2['simu']['Duration_flight'] = tf2\n \n initial_state_stage_2 = state_separation_stage_1.copy()\n \n ##### definition of events to be considered #####\n \n event_seco_ = lambda t,x :event_seco(t,x,param_integration_stage_2) #Second stage engine cut-off\n event_seco_.terminal = True\n event_seco_.direction = 1\n dico_events_stage_1\n event_fairing = lambda t,x :event_fairing_jettison(t,x,param_integration_stage_2) #Second stage fairing jettison\n event_fairing.terminal = True\n event_fairing.direction = -1 \n \n event_impact_ = lambda t,x :event_impact(t,x,param_integration_stage_2) ##Second stage Earth impact\n event_impact_.terminal = True\n event_impact_.direction = -1 \n \n fonction_ode_integration = lambda t,x :simulation_stage_2(t,x,param_integration_stage_2) #Simulation of the 2nd stage - equations of motion\n \n param_simu_stage_2 = copy.deepcopy(param_integration_stage_2) \n param_simu_stage_2['simu']['Mode_simu']=0.\n \n fonction_ode_simu = lambda t,x :simulation_stage_2(t,x,param_simu_stage_2) #Simulation of the 2nd stage - equations of motion\n \n dico_events_stage_2 = {}\n \n dico_events_stage_2['SECO'] = {}\n dico_events_stage_2['SECO']['actif'] = False\n dico_events_stage_2['SECO']['instant'] = 0.\n dico_events_stage_2['SECO']['state']= 0.\n \n dico_events_stage_2['impact'] = {}\n dico_events_stage_2['impact']['actif'] = False\n dico_events_stage_2['impact']['instant'] = 0.\n dico_events_stage_2['impact']['state']= 0.\n \n if dico_events_stage_1['fairing']['actif'] == False:\n \n dico_events_stage_2['fairing'] = {}\n dico_events_stage_2['fairing']['actif'] = False\n dico_events_stage_2['fairing']['instant'] = 0.\n dico_events_stage_2['fairing']['state'] = 0.\n \n initial_state_stage_2[-1]= inputs['Dry_mass_stage_2'] + inputs['Prop_mass_stage_2']+Constants['Payload_mass'] + Constants['Fairing_mass']\n \n dico_events_stage_2['list_name_events'] = ['SECO','fairing','impact']\n dico_events_stage_2['list_events'] = [event_seco_,event_fairing,event_impact_]\n else :\n initial_state_stage_2[-1]= inputs['Dry_mass_stage_2'] + inputs['Prop_mass_stage_2']+Constants['Payload_mass']\n dico_events_stage_2['list_name_events'] = ['SECO','impact']\n dico_events_stage_2['list_events'] = [event_seco_,event_impact_]\n \n span_integration = (0.,tf2)\n current_T = np.zeros(1)\n ##### integration of stage 2 trajectory #####\n while (dico_events_stage_2['SECO']['actif'] == False and dico_events_stage_2['impact']['actif'] == False) and current_T[-1]0:\n dico_events_stage_2[dico_events_stage_2['list_name_events'][j]]['actif'] = True \n dico_events_stage_2[dico_events_stage_2['list_name_events'][j]]['instant'] = current_sol.t_events[j][0]+instant_end_flight_stage_1\n dico_events_stage_2[dico_events_stage_2['list_name_events'][j]]['state'] = current_sol.y[:,-1].copy()\n \n if dico_events_stage_2['list_name_events'][j] == 'fairing': \n initial_state[-1] = initial_state[-1] - Constants['Fairing_mass']\n \n #update of list of events\n for k in reversed(range(len(dico_events_stage_2['list_events']))):\n if len(current_sol.t_events[k])>0:\n del dico_events_stage_2['list_events'][k]\n del dico_events_stage_2['list_name_events'][k]\n \n span_integration = (current_sol.t[-1],tf2)\n \n #save of trajectory data \n data_simu['T'] = np.concatenate((data_simu['T'],instant_end_flight_stage_1+np.array([current_T]).T))\n data_simu['nx'] = np.concatenate((data_simu['nx'],current_NX))\n data_simu['Mach'] = np.concatenate((data_simu['Mach'],current_Mach))\n data_simu['pdyn'] = np.concatenate((data_simu['pdyn'],current_Pdyn))\n data_simu['flux'] = np.concatenate((data_simu['flux'],current_flux))\n data_simu['alt'] = np.concatenate((data_simu['alt'],current_alt))\n data_simu['alpha'] = np.concatenate((data_simu['alpha'],current_alpha*180/np.pi))\n data_simu['gamma'] = np.concatenate((data_simu['gamma'],current_gamma*180/np.pi))\n data_simu['theta'] = np.concatenate((data_simu['theta'],current_theta*180/np.pi))\n data_simu['V'] = np.concatenate((data_simu['V'],current_V))\n data_simu['rho'] = np.concatenate((data_simu['rho'],current_rho))\n data_simu['CX'] = np.concatenate((data_simu['CX'],current_CX))\n data_simu['thrust'] = np.concatenate((data_simu['thrust'],current_thrust))\n data_simu['mass_flow_rate'] = np.concatenate((data_simu['mass_flow_rate'],current_mass_flow_rate))\n data_simu['lat'] = np.concatenate((data_simu['lat'],current_lat*180/np.pi))\n data_simu['longi'] = np.concatenate((data_simu['longi'],current_longi*180/np.pi))\n data_simu['m'] = np.concatenate((data_simu['m'],current_m))\n data_simu['distance'] =np.concatenate((data_simu['distance'],current_distance))\n data_simu['r'] =np.concatenate((data_simu['r'],current_r))\n \n \n #### Outputs data for OpenMDAO\n Nb_pt = len(data_simu['T'])\n outputs['Nb_pt_ascent'] = Nb_pt\n outputs['T_ascent'][0:Nb_pt] = data_simu['T'].T[0]\n outputs['r_ascent'][0:Nb_pt] = data_simu['r'].T[0]\n outputs['nx_ascent'][0:Nb_pt] = data_simu['nx'].T[0]\n outputs['Mach_ascent'][0:Nb_pt] = data_simu['Mach'].T[0] \n outputs['pdyn_ascent'][0:Nb_pt] = data_simu['pdyn'].T[0] \n outputs['flux_ascent'][0:Nb_pt] = data_simu['flux'].T[0] \n outputs['alt_ascent'][0:Nb_pt] = data_simu['alt'].T[0] \n outputs['alpha_ascent'][0:Nb_pt] = data_simu['alpha'].T[0]\n outputs['gamma_ascent'][0:Nb_pt] = data_simu['gamma'].T[0]\n outputs['theta_ascent'][0:Nb_pt] = data_simu['theta'].T[0]\n outputs['V_ascent'][0:Nb_pt] = data_simu['V'].T[0] \n outputs['rho_ascent'][0:Nb_pt] = data_simu['rho'].T[0] \n outputs['CX_ascent'][0:Nb_pt] = data_simu['CX'].T[0] \n outputs['thrust_ascent'][0:Nb_pt] = data_simu['thrust'].T[0]\n outputs['mass_flow_rate_ascent'][0:Nb_pt] = data_simu['mass_flow_rate'].T[0] \n outputs['lat_ascent'][0:Nb_pt] = data_simu['lat'].T[0] \n outputs['longi_ascent'][0:Nb_pt] = data_simu['longi'].T[0] \n outputs['m_ascent'][0:Nb_pt] = data_simu['m'].T[0] \n outputs['distance_ascent'][0:Nb_pt] = data_simu['distance'].T[0] \n\n #Definition of additional data for post-treatment\n self.data_events={}\n self.data_events['stage_1'] = dico_events_stage_1\n if dico_events_stage_1['impact']['actif'] == False:\n self.data_events['stage_2'] = dico_events_stage_2\n \n self.data_simu={}\n self.data_simu['ascent'] = data_simu\n \n\n\n \t### FALLOUT PHASE \n if inputs['is_fallout'][0] == 1.:\n \n step_fallout = 2\n #Definition of state_vector at meco and time\n initial_state_fallout = state_separation_stage_1.copy()\n initial_time_fallout = instant_end_flight_stage_1.copy()\n \n #Definition of ode parameters \n param_integration_fallout_stage_1 = {} \n param_integration_fallout_stage_1['aero'] = {}\n param_integration_fallout_stage_1['aero']['CX'] = inputs['CX_fallout_stage_1'][0]\n param_integration_fallout_stage_1['aero']['CZ'] = inputs['CZ_fallout_stage_1'][0]\n \n param_integration_fallout_stage_1['geometry'] = {}\n param_integration_fallout_stage_1['geometry']['Diameter']=inputs['Diameter_stage_1'][0]\n \n param_integration_fallout_stage_1['simu'] = {}\n param_integration_fallout_stage_1['simu']['Mode_simu']= 1. #integration (1) or simulation (0)\n \n param_simu_fallout_stage_1 = copy.deepcopy(param_integration_fallout_stage_1) \n param_simu_fallout_stage_1['simu']['Mode_simu']=0.\n fonction_ode_integration = lambda t,x :simulation_fallout_stage_1(t,x,param_integration_fallout_stage_1) #launcher simulation equations of motion\n \n fonction_ode_simu = lambda t,x :simulation_fallout_stage_1(t,x,param_simu_fallout_stage_1) #launcher simulation equations of motion\n \n dico_events_fallout_stage_1={}\n dico_events_fallout_stage_1['impact'] = {}\n dico_events_fallout_stage_1['impact']['actif'] = False\n dico_events_fallout_stage_1['impact']['instant'] = 0.\n dico_events_fallout_stage_1['impact']['state']= 0.\n \n event_impact_ = lambda t,x :event_impact(t,x,param_integration_fallout_stage_1) ##Second stage Earth impact\n event_impact_.terminal = True\n event_impact_.direction = -1\n \n span_integration = (initial_time_fallout,initial_time_fallout+1000)\n \n if dico_events_stage_1['fairing']['actif'] == False: # calcul de la masse de l'etage 1 a la separation\n \n initial_state_fallout[-1]= initial_state_fallout[-1] -(inputs['Dry_mass_stage_2'] + inputs['Prop_mass_stage_2']+Constants['Payload_mass'] + Constants['Fairing_mass'])\n else :\n initial_state_fallout[-1]= initial_state_fallout[-1] -(inputs['Dry_mass_stage_2'] + inputs['Prop_mass_stage_2']+Constants['Payload_mass'])\n \n \n dico_events_fallout_stage_1['list_name_events'] = ['impact']\n dico_events_fallout_stage_1['list_events'] = [event_impact_]\n \n current_sol_fallout = integrate.solve_ivp(fonction_ode_integration,span_integration, initial_state_fallout,\n atol=atol_integration,rtol=rtol_integration,\n dense_output = True,method=integration_method,\n events = dico_events_fallout_stage_1['list_events'])\n \n \n current_T_fallout = np.append(np.arange(current_sol_fallout.t[0],current_sol_fallout.t[-1],step_fallout),current_sol_fallout.t[-1])\n \n current_NX_fallout = np.zeros([len(current_T_fallout),1])\n current_Mach_fallout = np.zeros([len(current_T_fallout),1])\n current_Pdyn_fallout = np.zeros([len(current_T_fallout),1])\n current_flux_fallout = np.zeros([len(current_T_fallout),1])\n current_alt_fallout = np.zeros([len(current_T_fallout),1])\n current_alpha_fallout = np.zeros([len(current_T_fallout),1])\n current_gamma_fallout = np.zeros([len(current_T_fallout),1])\n current_theta_fallout = np.zeros([len(current_T_fallout),1])\n current_V_fallout = np.zeros([len(current_T_fallout),1])\n current_rho_fallout = np.zeros([len(current_T_fallout),1])\n current_CX_fallout = np.zeros([len(current_T_fallout),1])\n current_CZ_fallout = np.zeros([len(current_T_fallout),1])\n \n current_r_fallout = np.zeros([len(current_T_fallout),1])\n current_distance_fallout = np.zeros([len(current_T_fallout),1])\n current_thrust_fallout = np.zeros([len(current_T_fallout),1])\n current_lat_fallout = np.zeros([len(current_T_fallout),1])\n current_longi_fallout = np.zeros([len(current_T_fallout),1])\n current_m_fallout = np.zeros([len(current_T_fallout),1])\n current_mass_flow_rate_fallout = np.zeros([len(current_T_fallout),1])\n \n #Post traitment of the ODE integration to save the interesting data \n for i in range(len(current_T_fallout)):\n (current_r_fallout[i], current_V_fallout[i], current_gamma_fallout[i], current_longi_fallout[i], current_m_fallout[i], current_NX_fallout[i],\n current_Mach_fallout[i],current_Pdyn_fallout[i],current_flux_fallout[i],current_alt_fallout[i],current_alpha_fallout[i],current_theta_fallout[i],\n current_rho_fallout[i], current_CX_fallout[i],current_CZ_fallout[i],current_thrust_fallout[i],current_mass_flow_rate_fallout[i],\n current_distance_fallout[i],current_lat_fallout[i]) = fonction_ode_simu(current_T_fallout[i],current_sol_fallout.sol(current_T_fallout[i]))\n \n # save of trajectory data of the current phase \n data_simu_fallout = {}\n data_simu_fallout['T'] = np.array([current_T_fallout]).T\n data_simu_fallout['nx'] = current_NX_fallout\n data_simu_fallout['Mach'] = current_Mach_fallout \n data_simu_fallout['pdyn'] = current_Pdyn_fallout \n data_simu_fallout['flux'] = current_flux_fallout \n data_simu_fallout['r'] = current_r_fallout \n data_simu_fallout['alt'] = current_alt_fallout \n data_simu_fallout['alpha'] = current_alpha_fallout*180/np.pi\n data_simu_fallout['gamma'] = current_gamma_fallout*180/np.pi\n data_simu_fallout['theta'] = current_theta_fallout*180/np.pi\n data_simu_fallout['V'] = current_V_fallout\n data_simu_fallout['rho'] = current_rho_fallout\n data_simu_fallout['CX'] = current_CX_fallout\n data_simu_fallout['CZ'] = current_CZ_fallout\n data_simu_fallout['thrust'] = current_thrust_fallout\n data_simu_fallout['mass_flow_rate'] = current_mass_flow_rate_fallout\n data_simu_fallout['lat'] = current_lat_fallout*180/np.pi\n data_simu_fallout['longi'] = current_longi_fallout*180/np.pi\n data_simu_fallout['m'] =current_m_fallout\n data_simu_fallout['distance'] =current_distance_fallout\n \n Nb_pt_fallout = len(data_simu_fallout['T'])\n outputs['Nb_pt_fallout'] = Nb_pt_fallout\n outputs['T_fallout'][0:Nb_pt_fallout] = data_simu_fallout['T'].T[0]\n outputs['r_fallout'][0:Nb_pt_fallout] = data_simu_fallout['r'].T[0]\n outputs['nx_fallout'][0:Nb_pt_fallout] = data_simu_fallout['nx'].T[0]\n outputs['Mach_fallout'][0:Nb_pt_fallout] = data_simu_fallout['Mach'].T[0] \n outputs['pdyn_fallout'][0:Nb_pt_fallout] = data_simu_fallout['pdyn'].T[0] \n outputs['flux_fallout'][0:Nb_pt_fallout] = data_simu_fallout['flux'].T[0] \n outputs['alt_fallout'][0:Nb_pt_fallout] = data_simu_fallout['alt'].T[0] \n outputs['alpha_fallout'][0:Nb_pt_fallout] = data_simu_fallout['alpha'].T[0]\n outputs['gamma_fallout'][0:Nb_pt_fallout] = data_simu_fallout['gamma'].T[0]\n outputs['theta_fallout'][0:Nb_pt_fallout] = data_simu_fallout['theta'].T[0]\n outputs['V_fallout'][0:Nb_pt_fallout] = data_simu_fallout['V'].T[0] \n outputs['rho_fallout'][0:Nb_pt_fallout] = data_simu_fallout['rho'].T[0] \n outputs['CX_fallout'][0:Nb_pt_fallout] = data_simu_fallout['CX'].T[0] \n outputs['CZ_fallout'][0:Nb_pt_fallout] = data_simu_fallout['CZ'].T[0] \n \n outputs['thrust_fallout'][0:Nb_pt_fallout] = data_simu_fallout['thrust'].T[0]\n outputs['mass_flow_rate_fallout'][0:Nb_pt_fallout] = data_simu_fallout['mass_flow_rate'].T[0] \n outputs['lat_fallout'][0:Nb_pt_fallout] = data_simu_fallout['lat'].T[0] \n outputs['longi_fallout'][0:Nb_pt_fallout] = data_simu_fallout['longi'].T[0] \n outputs['m_fallout'][0:Nb_pt_fallout] = data_simu_fallout['m'].T[0] \n outputs['distance_fallout'][0:Nb_pt_fallout] = data_simu_fallout['distance'].T[0]\n ","sub_path":"trajectory/Trajectory.py","file_name":"Trajectory.py","file_ext":"py","file_size_in_byte":41851,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"455978172","text":"# Copyright 2014 Cloudera Inc.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport pytest\n\nimport ibis\n\nfrom ibis.compat import unittest\nimport ibis.expr.analysis as L\nimport ibis.expr.operations as ops\nimport ibis.common as com\n\nfrom ibis.tests.util import assert_equal\n\n\n# Place to collect esoteric expression analysis bugs and tests\n\n\ndef test_rewrite_substitute_distinct_tables(con):\n t = con.table('test1')\n tt = con.table('test1')\n\n expr = t[t.c > 0]\n expr2 = tt[tt.c > 0]\n\n metric = t.f.sum().name('metric')\n expr3 = expr.aggregate(metric)\n\n result = L.sub_for(expr3, [(expr2, t)])\n expected = t.aggregate(metric)\n\n assert_equal(result, expected)\n\n\ndef test_rewrite_join_projection_without_other_ops(con):\n # See #790, predicate pushdown in joins not supported\n\n # Star schema with fact table\n table = con.table('star1')\n table2 = con.table('star2')\n table3 = con.table('star3')\n\n filtered = table[table['f'] > 0]\n\n pred1 = table['foo_id'] == table2['foo_id']\n pred2 = filtered['bar_id'] == table3['bar_id']\n\n j1 = filtered.left_join(table2, [pred1])\n j2 = j1.inner_join(table3, [pred2])\n\n # Project out the desired fields\n view = j2[[filtered, table2['value1'], table3['value2']]]\n\n # Construct the thing we expect to obtain\n ex_pred2 = table['bar_id'] == table3['bar_id']\n ex_expr = (table.left_join(table2, [pred1])\n .inner_join(table3, [ex_pred2]))\n\n rewritten_proj = L.substitute_parents(view)\n op = rewritten_proj.op()\n\n assert not op.table.equals(ex_expr)\n\n\ndef test_rewrite_past_projection(con):\n table = con.table('test1')\n\n # Rewrite past a projection\n table3 = table[['c', 'f']]\n expr = table3['c'] == 2\n\n result = L.substitute_parents(expr)\n expected = table['c'] == 2\n assert_equal(result, expected)\n\n # Unsafe to rewrite past projection\n table5 = table[(table.f * 2).name('c'), table.f]\n expr = table5['c'] == 2\n result = L.substitute_parents(expr)\n assert result is expr\n\n\ndef test_multiple_join_deeper_reference():\n # Join predicates down the chain might reference one or more root\n # tables in the hierarchy.\n table1 = ibis.table({'key1': 'string', 'key2': 'string',\n 'value1': 'double'})\n table2 = ibis.table({'key3': 'string', 'value2': 'double'})\n table3 = ibis.table({'key4': 'string', 'value3': 'double'})\n\n joined = table1.inner_join(table2, [table1['key1'] == table2['key3']])\n joined2 = joined.inner_join(table3, [table1['key2'] == table3['key4']])\n\n # it works, what more should we test here?\n materialized = joined2.materialize()\n repr(materialized)\n\n\ndef test_filter_on_projected_field(con):\n # See #173. Impala and other SQL engines do not allow filtering on a\n # just-created alias in a projection\n region = con.table('tpch_region')\n nation = con.table('tpch_nation')\n customer = con.table('tpch_customer')\n orders = con.table('tpch_orders')\n\n fields_of_interest = [customer,\n region.r_name.name('region'),\n orders.o_totalprice.name('amount'),\n orders.o_orderdate\n .cast('timestamp').name('odate')]\n\n all_join = (\n region.join(nation, region.r_regionkey == nation.n_regionkey)\n .join(customer, customer.c_nationkey == nation.n_nationkey)\n .join(orders, orders.o_custkey == customer.c_custkey))\n\n tpch = all_join[fields_of_interest]\n\n # Correlated subquery, yikes!\n t2 = tpch.view()\n conditional_avg = t2[(t2.region == tpch.region)].amount.mean()\n\n # `amount` is part of the projection above as an aliased field\n amount_filter = tpch.amount > conditional_avg\n\n result = tpch.filter([amount_filter])\n\n # Now then! Predicate pushdown here is inappropriate, so we check that\n # it didn't occur.\n assert isinstance(result.op(), ops.Selection)\n assert result.op().table is tpch\n\n\ndef test_bad_join_predicate_raises():\n # Join predicate references a derived table, but we can salvage and\n # rewrite it to get the join semantics out\n # see ibis #74\n table = ibis.table([\n ('c', 'int32'),\n ('f', 'double'),\n ('g', 'string')\n ], 'foo_table')\n\n table2 = ibis.table([\n ('key', 'string'),\n ('value', 'double')\n ], 'bar_table')\n\n filter_pred = table['f'] > 0\n table3 = table[filter_pred]\n\n with pytest.raises(com.ExpressionError):\n table.inner_join(table2, [table3['g'] == table2['key']])\n\n # expected = table.inner_join(table2, [table['g'] == table2['key']])\n # assert_equal(result, expected)\n\n\ndef test_filter_self_join():\n # GH #667\n purchases = ibis.table([('region', 'string'),\n ('kind', 'string'),\n ('user', 'int64'),\n ('amount', 'double')], 'purchases')\n\n metric = purchases.amount.sum().name('total')\n agged = (purchases.group_by(['region', 'kind'])\n .aggregate(metric))\n\n left = agged[agged.kind == 'foo']\n right = agged[agged.kind == 'bar']\n\n cond = left.region == right.region\n joined = left.join(right, cond)\n\n # unmodified by analysis\n assert_equal(joined.op().predicates[0], cond)\n\n metric = (left.total - right.total).name('diff')\n what = [left.region, metric]\n projected = joined.projection(what)\n\n proj_exprs = projected.op().selections\n\n # proj exprs unaffected by analysis\n assert_equal(proj_exprs[0], left.region)\n assert_equal(proj_exprs[1], metric)\n\n\n# def test_fuse_filter_projection():\n# data = ibis.table([('kind', 'string'),\n# ('year', 'int64')], 'data')\n\n# pred = data.year == 2010\n\n# result = data.projection(['kind'])[pred]\n# expected = data.filter(pred).kind\n\n# assert isinstance(result, ops.Selection)\n# assert result.equals(expected)\n\n\n@pytest.mark.xfail\ndef test_fuse_projection_sort_by():\n assert False\n\n\n@pytest.mark.xfail\ndef test_fuse_filter_sort_by():\n assert False\n\n\n# Refactoring deadpool\n\ndef test_no_rewrite(con):\n table = con.table('test1')\n\n # Substitution not fully possible if we depend on a new expr in a\n # projection\n table4 = table[['c', (table['c'] * 2).name('foo')]]\n expr = table4['c'] == table4['foo']\n result = L.substitute_parents(expr)\n expected = table['c'] == table4['foo']\n assert_equal(result, expected)\n\n# def test_projection_with_join_pushdown_rewrite_refs():\n# # Observed this expression IR issue in a TopK-rewrite context\n# table1 = ibis.table([\n# ('a_key1', 'string'),\n# ('a_key2', 'string'),\n# ('a_value', 'double')\n# ], 'foo')\n\n# table2 = ibis.table([\n# ('b_key1', 'string'),\n# ('b_name', 'string'),\n# ('b_value', 'double')\n# ], 'bar')\n\n# table3 = ibis.table([\n# ('c_key2', 'string'),\n# ('c_name', 'string')\n# ], 'baz')\n\n# proj = (table1.inner_join(table2, [('a_key1', 'b_key1')])\n# .inner_join(table3, [(table1.a_key2, table3.c_key2)])\n# [table1, table2.b_name.name('b'), table3.c_name.name('c'),\n# table2.b_value])\n\n# cases = [\n# (proj.a_value > 0, table1.a_value > 0),\n# (proj.b_value > 0, table2.b_value > 0)\n# ]\n\n# for higher_pred, lower_pred in cases:\n# result = proj.filter([higher_pred])\n# op = result.op()\n# assert isinstance(op, ops.Selection)\n# new_pred = op.predicates[0]\n# assert_equal(new_pred, lower_pred)\n\n# def test_rewrite_expr_with_parent():\n# table = self.con.table('test1')\n\n# table2 = table[table['f'] > 0]\n\n# expr = table2['c'] == 2\n\n# result = L.substitute_parents(expr)\n# expected = table['c'] == 2\n# assert_equal(result, expected)\n\n# def test_rewrite_distinct_but_equal_objects():\n# t = self.con.table('test1')\n# t_copy = self.con.table('test1')\n\n# table2 = t[t_copy['f'] > 0]\n\n# expr = table2['c'] == 2\n\n# result = L.substitute_parents(expr)\n# expected = t['c'] == 2\n# assert_equal(result, expected)\n\n\ndef test_join_table_choice():\n # GH807\n x = ibis.table(ibis.schema([('n', 'int64')]), 'x')\n t = x.aggregate(cnt=x.n.count())\n predicate = t.cnt > 0\n assert L.sub_for(predicate, [(t, t.op().table)]).equals(predicate)\n","sub_path":"ibis/expr/tests/test_analysis.py","file_name":"test_analysis.py","file_ext":"py","file_size_in_byte":8863,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"45669436","text":"import virtool.db.utils\nimport virtool.processes\nimport virtool.utils\n\n\nasync def register(db, process_type, file_size=None):\n process_id = await virtool.db.utils.get_new_id(db.processes)\n\n document = {\n \"_id\": process_id,\n \"count\": 0,\n \"created_at\": virtool.utils.timestamp(),\n \"file_size\": file_size,\n \"progress\": 0,\n \"step\": virtool.processes.FIRST_STEPS[process_type],\n \"type\": process_type\n }\n\n await db.processes.insert_one(document)\n\n return virtool.utils.base_processor(document)\n\n\nasync def update(db, process_id, count=None, progress=None, step=None, file_progress=None, file_size=None, errors=None):\n update_dict = dict()\n\n if count is not None:\n update_dict[\"count\"] = count\n\n if progress is not None:\n update_dict[\"progress\"] = progress\n\n if step:\n update_dict[\"step\"] = step\n\n if file_progress:\n update_dict[\"file_progress\"] = file_progress\n\n if file_size:\n update_dict[\"file_size\"] = file_size\n\n if errors is not None:\n update_dict[\"errors\"] = errors\n\n document = await db.processes.find_one_and_update({\"_id\": process_id}, {\n \"$set\": update_dict\n })\n\n return virtool.utils.base_processor(document)\n\n\nasync def remove(db, process_id):\n await db.processes.delete_one({\"_id\": process_id})\n","sub_path":"virtool/db/processes.py","file_name":"processes.py","file_ext":"py","file_size_in_byte":1348,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"388905956","text":"import sys\n\nfrom deploy import logger\n\ntry:\n import maya.OpenMayaUI as apiUI\nexcept ImportError:\n pass\nfrom PySide import shiboken\nfrom PySide.QtGui import *\n\n##########################################################################\n# Logging Examples\n\n\n@logger.logged\ndef example_function(arg, log=None):\n \"\"\"\n Example function to test wrappers\n :param arg:\n :param log:\n :return:\n \"\"\"\n log.debug('This seems to be working')\n log.debug(arg)\n\n\n@logger.timed\ndef test_function():\n import time\n time.sleep(3)\n\n\n##########################################################################\n# Maya Workflow Example\n\n\ndef get_maya_window():\n \"\"\"\n Get the main Maya window as a QtGui.QMainWindow instance\n @return: QtGui.QMainWindow instance of the top level Maya windows\n \"\"\"\n ptr = apiUI.MQtUtil.mainWindow()\n if ptr is not None:\n return shiboken.wrapInstance(long(ptr), QMainWindow)\n\n\ndef show():\n maya = get_maya_window()\n for child in maya.children():\n if type(child).__name__ == ExampleClass.__name__: # isinstance doesn't work because of reloading\n child.show()\n return\n tool = ExampleClass()\n tool.show()\n\n\ndef run():\n maya = get_maya_window()\n for child in maya.children():\n if type(child).__name__ == ExampleClass.__name__: # isinstance doesn't work because of reloading\n child.deleteLater()\n tool = ExampleClass(parent=maya)\n tool.show()\n\n\nclass ExampleClass(QMainWindow):\n\n def __init__(self, parent=None):\n super(ExampleClass, self).__init__(parent)\n\n self.logger = logger.init_logging(self, unique=True)\n self.logger.info('Initializing {0}'.format(self))\n\n self.setWindowTitle('ExampleClass')\n\nif __name__ == '__main__':\n example_function('arg1')\n test_function()\n\n app = QApplication(sys.argv)\n ExampleClass()\n app.exec_()","sub_path":"python/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1909,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"592380809","text":"#!/usr/bin/python\n\nfrom __future__ import print_function\n\n\ndef main():\n \n print(\"O hai! How much change is owed? \", end=\"\")\n \n \n the_change = -1\n \n #Loop over until a valid floating point number is returned... Greater than zero \n while the_change < 0:\n \n the_change = getFloat()\n \n if the_change < 0:\n print(\"How much change is owed? \", end=\"\")\n \n #Get the number of coins \n num_coins = getCoins(the_change)\n \n print(num_coins)\n\n#END OF main()\n\n\ndef getFloat():\n# Gets and returns a floating point value from the user\n \n while True:\n try:\n the_input = float(raw_input())\n except:\n print(\"Retry: \", end=\"\")\n else:\n return the_input\n \n# END OF getFloat()\n\n\ndef getCoins(the_change):\n \n #Multiply by 100 for easier integer division\n the_change *= 100\n \n #Initial number of coins\n num_coins = 0\n \n #Get number of quarters\n num_coins += int(the_change / 25)\n \n #Get the remainder for calculating dimes\n the_change = the_change % 25\n \n #Get number of dimes (10 cents)\n num_coins += int(the_change / 10)\n \n #Get the remainder for calculating nickles\n the_change = the_change % 10\n \n #Get number of nickles (5 cents)\n num_coins += int(the_change / 5)\n \n #Get the remainder for calculating pennies\n the_change = the_change % 5\n \n #Add the remainder to the num_coins\n num_coins += the_change\n \n return int(num_coins)\n\n# END OF getCoins()\n\n\n\nif __name__ == \"__main__\": main()","sub_path":"Python/pset1/standard/greedy.py","file_name":"greedy.py","file_ext":"py","file_size_in_byte":1602,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"564433497","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nimport sys\nimport os\nimport time\nimport shutil\n\n\n# -------------------------------------------------------------\n# Help\n# -------------------------------------------------------------\n\ndef printHelp():\n usage = \"\"\"NAME:\n cchack - a patch for CocosCreator\n\nUSAGE:\n cchack [options] [creator_dir]\n\nVERSION:\n 0.0.1\n\nCOMMANDS:\n help, h Shows a list of commands or help for one command\n\nOPTIONS:\n --patch apply patch to CocosCreator\n --restore restore CocosCreator from restore folder\n you need to create a folder named 'restore'\n like 'restore/osx/...' or 'restore/win32/...'\n \"\"\"\n print(usage)\n exit(1)\n\n\ndef str_time():\n return time.strftime('%Y%m%d_%p%H%M%S', time.localtime())\n\n\n# -------------------------------------------------------------\n# Backup\n# -------------------------------------------------------------\n\ndef backup_osx(ccpath):\n files_to_backup = []\n for root, dirs, files in os.walk(\"patch\"):\n for name in files:\n if name.startswith(\".\") or name == \"cchacked\":\n continue\n patch_file = os.path.join(root, name)\n comp = patch_file.split(\"osx/\")\n comp = comp[len(comp) - 1]\n origin_file = os.path.join(ccpath, comp)\n if os.path.exists(origin_file):\n files_to_backup.append(origin_file)\n if len(files_to_backup) > 0:\n backup_dir = os.path.join(\"backup\", str_time(), \"osx\", \"Contents\")\n for f in files_to_backup:\n backup_file = f.split(\"Contents/\")[1]\n backup_file = os.path.join(backup_dir, backup_file)\n sub_dir = os.path.dirname(backup_file)\n if not os.path.exists(sub_dir):\n os.makedirs(sub_dir)\n print(\"backing up \" + f)\n shutil.copyfile(f, backup_file)\n\n\ndef backup(ccpath):\n backup_osx(ccpath)\n\n\n# -------------------------------------------------------------\n# Replace\n# -------------------------------------------------------------\n\ndef replace_osx(ccpath):\n for root, dirs, files in os.walk(\"patch\"):\n for name in files:\n if name.startswith(\".\"):\n continue\n patch_file = os.path.join(root, name)\n comp = patch_file.split(\"osx/\")\n comp = comp[len(comp) - 1]\n origin_file = os.path.join(ccpath, comp)\n print(\"patching \" + origin_file)\n shutil.copyfile(patch_file, origin_file)\n\n\ndef replace(ccpath):\n replace_osx(ccpath)\n\n\n# -------------------------------------------------------------\n# Patch\n# -------------------------------------------------------------\n\ndef patch(ccpath):\n patch_mark_path = os.path.join(ccpath, \"cchacked\")\n if os.path.exists(patch_mark_path):\n with open(patch_mark_path) as f:\n for line in f:\n print(\"target already patched with cchack \" + line)\n break\n f.close()\n exit(0)\n else:\n backup(ccpath)\n replace(ccpath)\n\n\n# -------------------------------------------------------------\n# Restore\n# -------------------------------------------------------------\n\ndef restore_osx(ccpath):\n restore_dir = os.path.join(\"restore\", \"osx\")\n for root, dirs, files in os.walk(restore_dir):\n for name in files:\n if name.startswith(\".\"):\n continue\n restore_file = os.path.join(root, name)\n target_file = root.split(\"osx/\")[1]\n target_file = os.path.join(ccpath, target_file, name)\n print(\"restoring \" + target_file)\n shutil.copyfile(restore_file, target_file)\n patch_mark_path = os.path.join(ccpath, \"cchacked\")\n print(\"remove flag\")\n os.unlink(patch_mark_path)\n\n\ndef restore(ccpath):\n patch_mark_path = os.path.join(ccpath, \"cchacked\")\n if not os.path.exists(patch_mark_path):\n print(\"target not patched, abort\")\n exit(0)\n if not os.path.exists(\"restore\"):\n print(\"restore folder not exists\")\n exit(0)\n restore_osx(ccpath)\n\n\n# -------------------------------------------------------------\n# Entry\n# -------------------------------------------------------------\n\ndef main(argv):\n if len(argv) < 2:\n printHelp()\n ccpath = argv[1]\n if not os.path.exists(ccpath):\n print(ccpath + \" not exists\")\n exit(0)\n\n if not os.path.exists(\"patch\"):\n print(\"patch missing\")\n exit(1)\n\n if argv[0] == \"--patch\" or argv[0] == \"-p\":\n patch(ccpath)\n elif argv[0] == \"--restore\" or argv[0] == \"-r\":\n restore(ccpath)\n\n\nif __name__ == \"__main__\":\n main(sys.argv[1:])\n","sub_path":"CCHack/cchack.py","file_name":"cchack.py","file_ext":"py","file_size_in_byte":4697,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"368303911","text":"import autocti as ac\nimport autofit as af\nfrom test_autocti.integration.tests import runner\n\ntest_type = \"parallel_x1__serial_x1\"\ntest_name = \"x1_species__x1_image__hyper\"\nci_data_type = \"ci_uniform\"\nci_data_model = \"parallel_x1__serial_x1\"\nresolution = \"patch\"\nci_normalizations = [10000.0, 84700.0]\n\n\nclocker = ac.Clocker(parallel_express=2, serial_express=2)\n\n\ndef make_pipeline(name, folders, search=af.DynestyStatic()):\n\n parallel_ccd = af.PriorModel(ac.CCD)\n\n parallel_ccd.full_well_depth = 8.47e4\n parallel_ccd.well_notch_depth = 1e-7\n\n serial_ccd = af.PriorModel(ac.CCD)\n\n serial_ccd.full_well_depth = 8.47e4\n serial_ccd.well_notch_depth = 1e-7\n\n phase1 = ac.PhaseCIImaging(\n name=\"phase_1\",\n folders=folders,\n search=search,\n parallel_traps=[af.PriorModel(ac.TrapInstantCapture)],\n parallel_ccd=parallel_ccd,\n serial_traps=[af.PriorModel(ac.TrapInstantCapture)],\n serial_ccd=serial_ccd,\n )\n\n phase2 = ac.PhaseCIImaging(\n name=\"phase_2\",\n folders=folders,\n parallel_traps=phase1.result.instance.parallel_trap,\n parallel_ccd=phase1.result.instance.parallel_ccd,\n serial_traps=phase1.result.instance.serial_traps,\n serial_ccd=phase1.result.instance.serial_ccd,\n hyper_noise_scalar_of_ci_regions=ac.ci.CIHyperNoiseScalar,\n hyper_noise_scalar_of_parallel_trails=ac.ci.CIHyperNoiseScalar,\n hyper_noise_scalar_of_serial_trails=ac.ci.CIHyperNoiseScalar,\n hyper_noise_scalar_of_serial_overscan_no_trails=ac.ci.CIHyperNoiseScalar,\n search=search,\n )\n\n phase3 = ac.PhaseCIImaging(\n name=\"phase_3\",\n folders=folders,\n parallel_traps=phase1.result.model.parallel_trap,\n parallel_ccd=phase1.result.model.parallel_ccd,\n serial_traps=phase1.result.model.serial_traps,\n serial_ccd=phase1.result.model.serial_ccd,\n hyper_noise_scalar_of_ci_regions=phase2.result.instance.hyper_noise_scalar_of_ci_regions,\n hyper_noise_scalar_of_parallel_trails=phase2.result.instance.hyper_noise_scalar_of_parallel_trails,\n hyper_noise_scalar_of_serial_trails=phase2.result.instance.hyper_noise_scalar_of_serial_trails,\n hyper_noise_scalar_of_serial_overscan_no_trails=phase2.result.instance.hyper_noise_scalar_of_serial_overscan_no_trails,\n search=search,\n )\n\n return ac.Pipeline(name, phase1, phase2, phase3)\n\n\nif __name__ == \"__main__\":\n\n import sys\n\n runner.run(sys.modules[__name__], clocker=clocker)\n","sub_path":"test_autocti/integration/tests/parallel_and_serial/x1_species__x2_image.py","file_name":"x1_species__x2_image.py","file_ext":"py","file_size_in_byte":2528,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"614128521","text":"import sys\nimport logging\nfrom collections import namedtuple\n\n\nlogging.basicConfig(stream=sys.stderr, level=logging.WARNING)\n\n\nclass Parser(object):\n def __init__(self, lemmas=False):\n self.lemmas = lemmas\n self.atom2token = {}\n self.cur_text = None\n\n # to be created by derived classes\n self.lang = None\n self.nlp = None\n\n # named tuple used to pass parser state internally\n self._ParseState = namedtuple('_ParseState',\n ['extra_edges', 'tokens', 'child_tokens',\n 'positions', 'children', 'entities'])\n\n def post_process(edge):\n raise NotImplementedError()\n\n def parse_token(token):\n raise NotImplementedError()\n\n def parse_sentence(self, sent):\n self.atom2token = {}\n main_edge, extra_edges = self.parse_token(sent.root)\n\n main_edge, _ = self.post_process(main_edge)\n return {'main_edge': main_edge,\n 'extra_edges': extra_edges,\n 'text': str(sent),\n 'spacy_sentence': sent}\n\n def parse(self, text):\n self.cur_text = text\n doc = self.nlp(text.strip())\n return tuple(self.parse_sentence(sent) for sent in doc.sents)\n","sub_path":"graphbrain/parsers/parser.py","file_name":"parser.py","file_ext":"py","file_size_in_byte":1270,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"171713412","text":"#!/usr/bin/env python\nimport socket, time,os, time\n\nclass Server():\n\tdef __init__(self,Adress=('',5000),MaxClient=1):\n\t\tself.s = socket.socket()\n\t\tself.s.bind(Adress)\n\t\tself.s.listen(MaxClient)\t\t\n\n\tdef WaitForConnection(self):\n\t\tself.Client, self.Adr=(self.s.accept())\t\t\n\t\tdata = self.Client.recv(4096)\t\t\n\t\tprint(time.strftime(\"%Y%m%d %H:%M:%S\") + ' Data >> ' + data)\n\t\nReceiver=Server()\t\n\nwhile 1 :\t\n\tReceiver.WaitForConnection()","sub_path":"Dev_CHIEF_Project/chief_receiver.py","file_name":"chief_receiver.py","file_ext":"py","file_size_in_byte":430,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"579180903","text":"'''print out the most common 7-mer and its GC percentage from all sequences'''\r\n\r\nimport argparse\r\n\r\ndef calc_gc_fasta(seq):\r\n at, gc = 0,0\r\n for base in seq.upper():\r\n if base in ('A', 'T'):\r\n at +=1\r\n elif base in ('G', 'C'):\r\n gc +=1\r\n else:\r\n raise ValueError ('Unexpected character found : {}. Only '\r\n 'ACTGs are allowed.'.format(base))\r\n\r\n \r\n try:\r\n return gc *100.0/(gc + at)\r\n except ZeroDivisionError:\r\n return 0.0\r\n\r\n \r\n\r\nif __name__ == '__main__':\r\n parser = argparse.ArgumentParser()\r\n parser.add_argument('input_file', type=str, help='Input file')\r\n args = parser.parse_args()\r\n input_file = open(args.input_file)\r\n kmerdict ={}\r\n for line in input_file:\r\n if line.startswith('>'):\r\n continue\r\n else:\r\n for i in range(len(line)):\r\n if i < len(line) -7:\r\n kmer = line[i:i+8]\r\n if kmer in kmerdict:\r\n kmerdict[kmer] = kmerdict[kmer] +1\r\n else:\r\n kmerdict.update({kmer:1})\r\n kmermax = max(kmerdict.values())\r\n for key in kmerdict.keys():\r\n value = kmerdict[key]\r\n if value == kmermax:\r\n print (\"The sequence '{}' has a %GC of {:.2f}\".format(key.strip(), kmermax, calc_gc_fasta(key.strip())))\r\n","sub_path":"LeoniAbe_day2.py","file_name":"LeoniAbe_day2.py","file_ext":"py","file_size_in_byte":1430,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"546989359","text":"from difflib import SequenceMatcher\nfrom dbconnection import *\nimport argparse\nconn=openConnection()\nmapping={'Fedora30':'fc30','Fedora29':'fc29'}\ndef similar(a, b):\n return SequenceMatcher(None, a, b).ratio()\ndef getEntry_PackageAndVersions(crashID,software):\n software=mapping[software]\n query='select component from crashes where crashID={}'.format(crashID)\n result=execute(query,conn)\n component=result[0]['component']\n\n query='''select * from relatedPackages\n where crashID={}\n and version like \"%{}\";'''.format(crashID,software)\n packages=execute(query,conn)\n\n dist=0\n target=None\n for item in packages:\n package=item['package']\n d=similar(component,package)\n if d>dist:\n dist=d\n target=package \n if target is None:\n #look for every software packages\n query='''select * from relatedPackages\n where crashID={};'''.format(crashID)\n packages=execute(query,conn)\n\n dist=0\n target=None\n for item in packages:\n package=item['package']\n d=similar(component,package)\n if d>dist:\n dist=d\n target=package \n print(crashID)\n return target\n\ndef fillupEntryPackage(software):\n query='''select distinct c.crashID from crashes c\n join softwares s\n on c.crashID=s.crashID\n join relatedPackages r \n on c.crashID =r.crashID\n where s.{}=1'''.format(software)\n crashIDs=execute(query,conn)\n\n for item in crashIDs:\n print(item['crashID'])\n package=getEntry_PackageAndVersions(item['crashID'],software)\n query='''insert into entryPackage values ({},\"{}\",\"{}\")'''.format(item['crashID'],software,package)\n execute(query,conn)\n\nif __name__=='__main__':\n parser=argparse.ArgumentParser()\n parser.add_argument('-s','--software',dest='software')\n args=parser.parse_args()\n fillupEntryPackage(args.software)\n\n","sub_path":"parseEntryPackage.py","file_name":"parseEntryPackage.py","file_ext":"py","file_size_in_byte":2014,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"557816074","text":"\n# coding: utf-8\n\n# In[1]:\n\n#991456\n\nimport pylab as P\nimport numpy as np\nplotDots=1\n# Define data\n# Define numBoxes\n\nP.figure()\nax = P.gca()\nax.set_xlabel('Neuron type')\nax.set_ylabel('Significance (p)')\n\n\n\nITMod = roiStats[roiStats['dataGroup']==1]['rankSumSig'].values\nPTMod = roiStats[roiStats['dataGroup']==0]['rankSumSig'].values\ndataSets={}\n\nITMod = ITMod.astype(np.float)\nPTMod = PTMod.astype(np.float)\ndataSets[0]= PTMod\ndataSets[1]= ITMod\nITMod = ITMod[:, np.newaxis]\nPTMod = PTMod[:,np.newaxis]\ndata = [PTMod, ITMod]\nfor i in range(2):\n \n \n bp = P.boxplot(data)\n y = dataSets[i]\n x = np.random.normal(1+i, 0.04, size=len(y))\n \n if (i==0):\n colorDot = 'r'\n elif(i==1):\n colorDot='b'\n if (plotDots ==1):\n P.plot(x, y, 'r.', alpha=0.2,color=colorDot)\n \n\nP.xticks([1, 2], ['PT', 'IT'])\n\n\nP.show()\n\nprint('The mean of PT is ' + str(np.mean(PTMod)))\nprint('The mean of IT is ' + str(np.mean(ITMod)))\n\nsigPT = np.shape(roiStats[(roiStats['dataGroup']==0)&(roiStats['rankSumSig']<0.05)])[0]\ntotalPT = np.shape(roiStats[(roiStats['dataGroup']==0)&(roiStats['rankSumSig']<5)])[0]\nsigIT = np.shape(roiStats[(roiStats['dataGroup']==1)&(roiStats['rankSumSig']<0.05)])[0]\ntotalIT = np.shape(roiStats[(roiStats['dataGroup']==1)&(roiStats['rankSumSig']<5)])[0]\n\nprint('Number of sigPT/TotalPT is ' + str(sigPT) + '/' + str(totalPT))\nprint('Number of sigIT/TotalIT is ' + str(sigIT) + '/' + str(totalIT))\n\nscipy.stats.ttest_ind(ITMod, PTMod, axis=0, equal_var=True)\n\ntTestCompSig = scipy.stats.ttest_ind(ITMod, PTMod, axis=0, equal_var=True)[1][0]\nprint('The significance of the difference is ' + str(tTestCompSig))\n\n\n\n# In[ ]:\n\n#819961 ExplainVarPlotter\nimport plotly.plotly as py\nfrom plotly.graph_objs import *\nimport plotly.tools as tls\nimport plotly.graph_objs as PyP\n\ndef explainedVarPlotter(meta):\n variances = meta.explained_variance_ratio_\n totalVarExpl = sum(variances)\n \n var_exp = [(i / totalVarExpl)*100 for i in sorted(variances, reverse=True)]\n cum_var_exp = np.cumsum(var_exp)\n\n trace1 = Bar(\n x=['PC %s' %i for i in range(1,10)],\n y=var_exp,\n showlegend=False)\n \n yaya=1\n if (yaya==1):\n trace2 = Scatter(\n x=['PC %s' %i for i in range(1,10)],\n y=cum_var_exp,\n name='cumulative explained variance')\n\n data = Data([trace1, trace2]) #\n\n layout=Layout(\n yaxis=YAxis(title='Explained variance in percent'),\n title='Explained variance by different principal components')\n\n fig = PyP.Figure(data=data, layout=layout)\n #%pylab inline\n py.iplot(fig)\n py.plot(fig)\n \n#explainVarPlotter(meta)\n\n\n# In[ ]:\n\n########88991122\n#########This is an angle plotter.\n\nangleLocal = np.zeros(np.shape(roiStats)[0])\nPC2PC1Magnitude = np.zeros(np.shape(roiStats)[0])\nfor roiId in range(np.shape(roiStats)[0]):\n angleLocal[roiId] = math.degrees(math.atan2(roiStats.ix[roiId]['PC2'],roiStats.ix[roiId]['PC1']))\n PC2PC1Magnitude[roiId] = math.hypot(roiStats.ix[roiId]['PC2'],roiStats.ix[roiId]['PC1'])\nroiStats['PC2PC1Angle'] = angleLocal\nroiStats['PC2PC1Magnitude'] = PC2PC1Magnitude\n\n\n# In[ ]:\n\n######718181\n##############Rotator:\nangleSpread = range(-180,181)\nangleSpread = np.roll(angleSpread,-135)#this centers it on our first block: -45->+45\nf, axarr = plt.subplots(2, 2)\nrow = 0\ncol = 0\nfor angleBatch in range(4):\n \n thisBlockAngles = angleSpread[0:90]\n\n relevantRois = roiStats[roiStats['PC2PC1Angle'].astype(int).isin(thisBlockAngles)]\n maxContributor = np.argmax(relevantRois['PC2PC1Magnitude'])\n axarr[row,col].plot(roiStats.ix[maxContributor]['meanTrace'])\n axarr[row, col].set_xlabel('Axis [1,0]')\n angleSpread = np.roll(angleSpread,-90)\n \n f.set_size_inches(15,10)\n \n if (col==0):\n col=col+1\n elif(col==1):\n row=row+1\n col=0\n print(maxContributor)\n \n\n\n\n# In[ ]:\n\n#777771\nplotRoiLocal=0\nif (plotRoiLocal==1):\n ################Plot an ROI in its entirety:\n for trialId in range(np.shape(roiStatsIT.ix[1817]['traceStore'])[1]):\n plot(roiStatsIT.ix[1817]['traceStore'][:,trialId])\n\n\n# In[ ]:\n\n##11331122\n####Roi contribution to componentsPlotter\nplt.scatter(roiStatsPTPlot[0,:],roiStatsPTPlot[1,:],facecolors='r', edgecolors='none', s=40)#,alpha=0.3) #color='red',alpha=0.1\nplt.scatter(roiStatsITPlot[0,:],roiStatsITPlot[1,:],facecolors='b', edgecolors='none',s=40)#,alpha=0.3) #color='blue',alpha=0.1)\nfig = plt.gcf()\nfig.set_size_inches(15,15)\nax = plt.gca()\nax.set_xlabel('1st component. Red= PT',size=20)\nax.set_ylabel('2nd component', size=20)\n\n\n\n# In[ ]:\n\n####33112211\nmatplotlib.pyplot.hist(roiStatsPTPlot[0,:],alpha=0.4) \nmatplotlib.pyplot.hist(roiStatsITPlot[0,:],alpha=0.4) \nmatplotlib.pyplot.hist(roiStatsPTPlot[1,:],alpha=0.4) \nmatplotlib.pyplot.hist(roiStatsITPlot[1,:],alpha=0.4) \n\n\n# In[ ]:\n\n#############################Significance plotting toolkit\n\n\n#991456\n\nimport pylab as P\nimport numpy as np\nplotDots=1\n# Define data\n# Define numBoxes\n\nP.figure()\nax = P.gca()\nax.set_xlabel('Neuron type')\nax.set_ylabel('Significance (p)')\n\n\n\nITMod = roiStats[roiStats['dataGroup']==1]['rankSumSig'].values\nPTMod = roiStats[roiStats['dataGroup']==0]['rankSumSig'].values\ndataSets={}\n\nITMod = ITMod.astype(np.float)\nPTMod = PTMod.astype(np.float)\ndataSets[0]= PTMod\ndataSets[1]= ITMod\nITMod = ITMod[:, np.newaxis]\nPTMod = PTMod[:,np.newaxis]\ndata = [PTMod, ITMod]\nfor i in range(2):\n \n \n bp = P.boxplot(data)\n y = dataSets[i]\n x = np.random.normal(1+i, 0.04, size=len(y))\n \n if (i==0):\n colorDot = 'r'\n elif(i==1):\n colorDot='b'\n if (plotDots ==1):\n P.plot(x, y, 'r.', alpha=0.2,color=colorDot)\n \n\nP.xticks([1, 2], ['PT', 'IT'])\n\n\nP.show()\n\nprint('The mean of PT is ' + str(np.mean(PTMod)))\nprint('The mean of IT is ' + str(np.mean(ITMod)))\n\nsigPT = np.shape(roiStats[(roiStats['dataGroup']==0)&(roiStats['rankSumSig']<0.05)])[0]\ntotalPT = np.shape(roiStats[(roiStats['dataGroup']==0)&(roiStats['rankSumSig']<5)])[0]\nsigIT = np.shape(roiStats[(roiStats['dataGroup']==1)&(roiStats['rankSumSig']<0.05)])[0]\ntotalIT = np.shape(roiStats[(roiStats['dataGroup']==1)&(roiStats['rankSumSig']<5)])[0]\n\nprint('Number of sigPT/TotalPT is ' + str(sigPT) + '/' + str(totalPT))\nprint('Number of sigIT/TotalIT is ' + str(sigIT) + '/' + str(totalIT))\n\nscipy.stats.ttest_ind(ITMod, PTMod, axis=0, equal_var=True)\n\ntTestCompSig = scipy.stats.ttest_ind(ITMod, PTMod, axis=0, equal_var=True)[1][0]\nprint('The significance of the difference is ' + str(tTestCompSig))\n\n\n\n# In[ ]:\n\n\n\n\n# In[ ]:\n\n#######77116611\n######################THIS CODE GROUPS AN INDIVIDUAL SESSIONS REACHES TOGETHER, FINDING THE RELEVANT ROIS FOR EACH REACH\n\nsessionProcess=14\ndgProcess=0\n\ntypesToUse = [0,1]\n\ntypes={}\nfor typeId in range(len(typesToUse)):\n reaches = dataGroups[dgProcess]['sessions'][sessionProcess]['reaches']\n roiData = dataGroups[dgProcess]['sessions'][sessionProcess]['data']\n spikesKeysData = roiStats[(roiStats['dataGroup']==dgProcess)&(roiStats['session']==sessionProcess)&(roiStats['rankSumSig']<0.05)]\n if (typeId ==0):\n \n spikesKeysData= spikesKeysData[spikesKeysData['PC1']>0.02]\n elif(typeId==1):\n spikesKeysData= spikesKeysData[spikesKeysData['PC2']>0.02]\n spikesKeys = spikesKeysData['localRoiKey'].values\n roiData = roiData[spikesKeys]\n\n reaches = reaches[reaches['reachRewarded']==1]\n reaches = reaches.reset_index(drop=True)\n\n\n reachResponse = np.zeros([len(reaches),len(spikesKeys),30])\n\n for reachId in range(len(reaches)):\n\n startTime = reaches.loc[reachId,'startTime']\n endTime = reaches.loc[reachId,'endTime']\n maxVel75Time = reaches.loc[reachId,'maxVel75Time']\n\n\n for roiId in range(len(spikesKeys)):\n\n reachResponse[reachId,roiId,:] = rebin(roiData[spikesKeys[roiId]][int(maxVel75Time-300):int(maxVel75Time+300)],30)\n \n types[typeId]=cp.deepcopy(reachResponse)\n \n \nmagnitudes = np.zeros([2,len(reaches)])\nfor reachNum in range(len(reaches)):\n \n firstMag = np.mean(np.mean(types[0][reachNum,:,:],axis=0))\n secondMag = np.mean(np.mean(types[1][reachNum,:,:],axis=0))\n \n magnitudes[0,reachNum]=firstMag\n magnitudes[1,reachNum]= secondMag\n \nplt.scatter(magnitudes[0,:],magnitudes[1,:])\nprint(scipy.stats.pearsonr(magnitudes[0,:], magnitudes[1,:]))\n\n\n# In[ ]:\n\n#######77116611_b\n\nmeanReachResponse = np.mean(types[0][:,:,:],axis=1)\nrowMaxValues = np.max(meanReachResponse,axis=1)\nrowMaxValues= rowMaxValues.T\nrowMaxValues = rowMaxValues[:,np.newaxis]\nmeanReachResponse = np.append(meanReachResponse,rowMaxValues,axis=1)\n#meanReachResponse = np.sort(meanReachResponse,axis=0,order=31)\n\nmeanReachResponse2 = np.mean(types[1][:,:,:],axis=1)\nrowMaxValues2 = np.max(meanReachResponse2,axis=1)\nrowMaxValues2= rowMaxValues2.T\nrowMaxValues2 = rowMaxValues2[:,np.newaxis]\nmeanReachResponse2 = np.append(meanReachResponse2,rowMaxValues2,axis=1)\n\n\nmeanReachResponse2 = np.flipud(meanReachResponse2[meanReachResponse[:,30].argsort(axis=-1)[:]])\nmeanReachResponse = np.flipud(meanReachResponse[meanReachResponse[:,30].argsort(axis=-1)[:]])\nf, axarr = plt.subplots(2,2)\n\n#11221\n\naxarr[0,0].imshow(meanReachResponse)\n#axarr[0].set_title('Sharing X axis')\naxarr[0,1].imshow(meanReachResponse2)\nf.set_figheight(25)\nf.set_figwidth(15)\n\n\n# In[ ]:\n\n\n\n\n# In[ ]:\n\n#44331122 --- Compares rewarded vs unrewarded\n\nmeanTrace = np.zeros([30])\nrelevantKeys = roiStats[(roiStats['PC2']>0.04)]['rewardedRoiTrace'].keys()\nprint('Running a total of ' + str(len(relevantKeys)) + ' rois')\nfor roiId in range(len(relevantKeys)):\n #plot(roiStats['rewardedRoiTrace'][relevantKeys[roiId]])\n meanTrace = meanTrace + roiStats['rewardedRoiTrace'][relevantKeys[roiId]]\n \n \nmeanTrace = meanTrace/len(relevantKeys)\nplot(meanTrace)\n\n\nmeanTrace2 = np.zeros([30])\nfor roiId in range(len(relevantKeys)):\n #plot(roiStats['unrewardedRoiTrace'][relevantKeys[roiId]])\n meanTrace2 = meanTrace2 + roiStats['unrewardedRoiTrace'][relevantKeys[roiId]]\n \nmeanTrace2 = meanTrace2/len(relevantKeys)\nplot(meanTrace2)\n\n\n# In[ ]:\n\n####FOV BY FOV ROI CONTRIBUTION PLOTTING\n###77668877\n#fovs = np.zeros([len(roiStats.groupby(['dataGroup', 'session']).count()),5])\nfovs={}\nfor dg in range(len(roiStats['dataGroup'].unique())):\n fovs[dg] = np.zeros([len(roiStats[roiStats['dataGroup']==dg]['session'].unique()),5])\n #print(roiStats[roiStats['dataGroup']==dg]['session'].unique())\n uniqueSessions = roiStats[roiStats['dataGroup']==dg]['session'].unique()\n for sId in range(len(roiStats[roiStats['dataGroup']==dg]['session'].unique())):\n localSeshNum = uniqueSessions[sId]\n fovs[dg][sId,0]=np.mean(roiStats[(roiStats['dataGroup']==dg)&(roiStats['session']==localSeshNum)]['PC1'])# roiStats[(roiStats['dataGroup']==dg)&(roiStats['session']==sId)]\n fovs[dg][sId,1]=np.mean(roiStats[(roiStats['dataGroup']==dg)&(roiStats['session']==localSeshNum)]['PC2'])# roiStats[(roiStats['dataGroup']==dg)&(roiStats['session']==sId)]\n fovs[dg][sId,2]=np.mean(roiStats[(roiStats['dataGroup']==dg)&(roiStats['session']==localSeshNum)]['PC3'])# roiStats[(roiStats['dataGroup']==dg)&(roiStats['session']==sId)]\n \n \n \n \n\n\npcPlot2=1\nplt.scatter(fovs[0][:,0],fovs[0][:,pcPlot2])\nplt.scatter(fovs[1][:,0],fovs[1][:,pcPlot2],color='r')\nplt.xlabel('PC1')\nplt.ylabel('PC2')\n\n\n\n\n\n# In[ ]:\n\n########################UNCATEGORISED CODE SNIPPETS\n\n\n# In[ ]:\n\nrelevantKeys = roiStats[roiStats['PC3']<-0.03].index\nvalues = np.zeros([2,len(relevantKeys)])\ntraces = np.zeros([2,len(relevantKeys),30])\nfor roiId in range(len(relevantKeys)):\n traces[0,roiId,:] = roiStats['rewardedRoiTrace'][relevantKeys[roiId]]\n traces[1,roiId,:] = roiStats['unrewardedRoiTrace'][relevantKeys[roiId]]\n \n localRewarded = np.sum(roiStats['rewardedRoiTrace'][relevantKeys[roiId]][20:26])\n localUnrewarded = np.sum(roiStats['unrewardedRoiTrace'][relevantKeys[roiId]][20:26])\n values[0,roiId] = localRewarded\n values[1,roiId] = localUnrewarded\n\nplot(np.mean(traces[0,:,:],axis=0))\nplot(np.mean(traces[1,:,:],axis=0))\n\nmeanRewarded = np.mean(values[0,:])\nmeanUnrewarded =np.mean(values[1,:])\nprint('The ratio of rewarded to unrewarded is ' + str(meanRewarded/meanUnrewarded))\n\nfig = plt.gcf()\nplt.ylim(0,np.max(np.mean(traces,axis=1)*1.1))\n\n","sub_path":"_DISTILL/analysis_codeSnippets.py","file_name":"analysis_codeSnippets.py","file_ext":"py","file_size_in_byte":12385,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"207189311","text":"from functions.base_functions_zh import *\nimport pytest\nimport allure\n\nfrom functions.ExcelFunctions import ReadWriteExcel\n\n# Reading data from excel\ndata_read = ReadWriteExcel(\n \"C://Users//Sumanth//PycharmProjects//PythonTesting//Resources//configurations//testdata//Test_data.xlsx\")\n\n# filename to be used in screen shot\ntest_file_name = os.path.basename(__file__)\n\n\ndef test_active_iq_config_advisor_shutdown_one():\n driver.get(properties_china('health_check_url'))\n driver.maximize_window()\n sleep(5)\n click('shutdown_power_off_button_xpath')\n sleep(2)\n actual_output = find_element(\"shutdown_confirm_product_title1_xpath\")\n print(\"Element Returned Test: \", actual_output.text)\n expected_output = properties_china('shutdown_confirm_test_cp_3_string1')\n highlight_element(actual_output)\n assert actual_output.text == expected_output\n\n\ndef test_active_iq_config_advisor_shutdown_two():\n actual_output = find_element(\"shutdown_note_product_title2_xpath\")\n print(\"Element Returned Test: \", actual_output.text)\n expected_output = properties_china('shutdown_note_test_cp_3_string2')\n highlight_element(actual_output)\n capture_screenshot(test_file_name)\n assert actual_output.text == expected_output\n\n\n\n\n\n\n\n\n\n\n# test_active_iq_config_advisor_shutdown_one()\n# test_active_iq_config_advisor_shutdown_two()\n","sub_path":"Testcases/NetApp_OEM_Chinese/test_cp_3_Ative_IQ_Config_Advisor/test_cp_3_shutdown_chinese.py","file_name":"test_cp_3_shutdown_chinese.py","file_ext":"py","file_size_in_byte":1353,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"35962133","text":"# -*- coding: utf-8 -*-\n#\n# Copyright (C) 2016-2018\n# Author: Marc van Dijk (marcvdijk@gmail.com)\n# file: io_pgf_format.py\n\n\"\"\"\nReading and writing graphs defined in Propitiatory Graph Format (.pgf) a\nformat specific to the graphit module.\n\nPGF stores graphit graph data as plain text python dictionaries or as\nserialized byte stream using the Python `pickle` module. Graphit graphs can\ncontain any hashable Python object as node (not just integers and strings).\nStoring a graph by \"Pickling\" it is probably the best way of representing\narbitrary hashable data types.\nBoth storage options are feature rich but not portable as they are (so far)\nonly supported by graphit.\n\"\"\"\n\nimport pprint\nimport logging\nimport ast\n\nfrom graphit import Graph, __module__\nfrom graphit.graph_exceptions import GraphitException\nfrom graphit.graph_io.io_helpers import open_anything\nfrom graphit.graph_py2to3 import StringIO\n\ntry:\n import cPickle as pickle\nexcept ImportError:\n import pickle\n\n__all__ = ['read_pgf', 'write_pgf']\nlogger = logging.getLogger(__module__)\n\n\ndef read_pgf(pgf_file, graph=None, pickle_graph=False):\n \"\"\"\n Import graph from Graph Python Format file\n\n PGF format is the modules own file format consisting of a serialized\n graph data, nodes and edges dictionaries. Import either as plain text\n serialized dictionary or pickled graph object.\n The format is feature rich with good performance but is not portable.\n\n :param pgf_file: PGF data to parse\n :type pgf_file: File, string, stream or URL\n :param graph: Graph object to import to or Graph by default\n :type graph: :graphit:Graph\n :param pickle_graph: PGF format is a pickled graph\n :type pickle_graph: :py:bool\n\n :return: Graph instance\n :rtype: :graphit:Graph\n \"\"\"\n\n # Unpickle pickled PGF format\n if pickle_graph:\n pgf_file = open_anything(pgf_file, mode='rb')\n pgraph = pickle.load(pgf_file)\n\n # Transfer data from unpickled graph to graph if defined\n if graph:\n graph.origin.nodes, graph.origin.edges, graph.origin.adjacency, graph.origin.data = graph.storagedriver(\n pgraph.nodes, pgraph.edges, pgraph.data)\n return graph\n return pgraph\n\n pgf_file = open_anything(pgf_file)\n\n # Import graph from serialized Graph Python Format\n if graph is None:\n graph = Graph()\n elif not isinstance(graph, Graph):\n raise GraphitException('Unsupported graph type {0}'.format(type(graph)))\n\n pgf_eval = ast.literal_eval(pgf_file.read())\n if not isinstance(pgf_eval, dict):\n raise GraphitException('Invalid PGF file format')\n\n missing_data = [d for d in pgf_file if d not in ('data', 'nodes', 'edges')]\n if missing_data:\n raise GraphitException('Invalid PGF file format, missing required attributes: {0}'.format(\n ','.join(missing_data)))\n\n graph.origin.nodes, graph.origin.edges, graph.origin.adjacency, graph.origin.data = graph.storagedriver(\n pgf_eval['nodes'], pgf_eval['edges'], pgf_eval['data'])\n\n return graph\n\n\ndef write_pgf(graph, pickle_graph=False):\n \"\"\"\n Export graph as Graph Python Format file\n\n PGF format is the modules own file format consisting of a serialized\n graph data, nodes and edges dictionaries. Exports either as plain text\n serialized dictionary or pickled graph object.\n The format is feature rich with good performance but is not portable.\n\n :param graph: Graph object to export\n :type graph: :graphit:Graph\n :param pickle_graph: serialize the Graph using Python pickle\n :type pickle_graph: :py:bool\n\n :return: Graph in GPF graph representation\n :rtype: :py:str\n \"\"\"\n\n # Pickle or not\n if pickle_graph:\n return pickle.dumps(graph)\n\n # Export graph as serialized Graph Python Format\n pp = pprint.PrettyPrinter(indent=2)\n string_buffer = StringIO()\n string_buffer.write('{')\n\n # Export graph data dictionary\n string_buffer.write('\"data\": {0},\\n'.format(pp.pformat(graph.data.to_dict())))\n\n # Export nodes as dictionary\n string_buffer.write('\"nodes\": {0},\\n'.format(pp.pformat(graph.nodes.to_dict())))\n\n # Export edges as dictionary\n string_buffer.write('\"edges\": {0},\\n'.format(pp.pformat(graph.edges.to_dict())))\n string_buffer.write('}')\n\n logger.info('Graph {0} exported in PGF format'.format(repr(graph)))\n\n # Reset buffer cursor\n string_buffer.seek(0)\n return string_buffer.read()\n","sub_path":"graphit/graph_io/io_pgf_format.py","file_name":"io_pgf_format.py","file_ext":"py","file_size_in_byte":4563,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"258017389","text":"import pymel.core as pm\r\n\r\n# CREATE THE OBJECTS\r\nobjectA = pm.PyNode(\"objectA\")\r\nobjectB = pm.PyNode(\"objectB\") \r\nobjectC = pm.PyNode(\"objectC\") \r\n\r\n# CHECK out the .translateX ATTR\r\nobjectA.translateX\r\n\r\n# CHECK OUT .tx ATTR same as the translateX\r\nobjectA.tx\r\n\r\n# COMPARE the long and short names\r\nobjectA.tx == objectA.translateX\r\n\r\n# SEE IT\r\nsee(objectA.tx)\r\n\r\n\r\n# GET THE VALUE OF AN ATTR\r\nrotX = objectA.rotateX.get()\r\nrot = objectA.rotate.get()\r\npos = objectA.translate.get()\r\n\r\n# TRANSFORMS HAVE .getMatrix() METHOD \r\n# !! more on using Matrices in the next module on aligning joints !! \r\nobjectA.getMatrix() # returns a normalized matrix\r\nobjectA.matrix.get()\r\nhelp(objectA.getMatrix)\r\n\r\n# THE SHORT NAME AND LONG NAME OF MOST ATTRS ARE THE SAME \r\n# BECAUSE THEY ARE LINKED ALL THE WAY TO THE API ATTR\r\nobjectA.tx.get == objectA.translateX.get\r\n\r\n\r\n# SETTING AN ATTR\r\nobjectA.tx.set(5)\r\nobjectA.rotateX.set(45)\r\nobjectA.template.set(True)\r\nobjectA.template.set(False)\r\n# COLORS\r\nobjectA.overrideEnabled.set(True)\r\nobjectA.overrideColor.set(13)\r\nobjectA.overrideColor.set(17)\r\nobjectA.overrideColor.set(6)\r\nobjectA.overrideEnabled.set(False)\r\n\r\n\r\n# ANY ATTR THAT IS A DOUBLE3 WILL ACCEPT ANY 3 ITERABLES\r\n# LIST\r\nobjectA.translate.set([1.0,2.0,3.0])\r\n\r\n# TUPLE\r\nobjectA.rotate.set((15,45,90))\r\n\r\n# VECTOR OR POINT\r\nobjectA.rotate.set(pm.dt.Vector(180,-90,10))\r\n\r\n# EVEN IF YOU FORGET TO CLASSIFY IT AND GIVE IT 3 ARGS\r\nobjectA.rotate.set(0,0,0)\r\n\r\n\r\n# SOME TIMES YOU NEED TO DYNAMICALLY MAKE THE ATTR NAME\r\n# YOU CAN USE THE .attr('string') to access an attr too\r\n\r\ntheAttr = 't' # make the string name of the attr\r\nobjectA.attr('%sx' % theAttr).get()\r\n\r\nfor vec in ['t','r']:\r\n for ch in ['x','y','z']:\r\n #objectA.attr(\"%s%s\"%(vec,ch)).set(20)\r\n objectA.attr(\"%s%s\"%(vec,ch)).unlock()\r\n\r\n \r\n \r\n#EVAL the last value has long name not short name!!\r\nobjectA.attr(\"%s%s\" %(vec,ch))\r\n \r\n# GET THE LONGNAME\r\nobjectA.translateX.longName()\r\n\r\n# GET THE SHORT NAME\r\nobjectA.translateX.shortName()\r\n\r\n# POTENTIAL GOTCHA. SET IS FLEXIBLE \r\n# BUT GET ALWAYS RETURNS THE PROPER TYPE\r\ntheTuple = (90,-90,180)\r\nobjectA.rotate.set(theTuple)\r\nobjARot = objectA.rotate.get()\r\n\r\n# NOT THE SAME\r\ntheTuple == objARot\r\n\r\n# THE SAME VALUES \r\nlist(theTuple) == list(objARot)\r\n\r\n# CHECKING FOR ATTRS===========================\r\n# APPROVED PYTHON WAY\r\nhasattr(node,attrname)\r\n\r\n# CHECKING FOR AN ATTR ON A PYNODE\r\nobjectA.hasAttr(\"matrix\")\r\nobjectA.hasAttr(\"bob\")\r\nobjectA.getShape().hasAttr(\"template\")\r\n\r\n\r\n# USEFUL ATTR METHODS ===========================\r\nobjectA.translateX.isKeyable()\r\nobjectA.rotateX.isLocked()\r\nobjectA.scale.lock()\r\nobjectA.scale.unlock()\r\n# MORE METHODS\r\nsee(objectA)\r\n\r\n\r\n\r\n\r\n# CONNECTING ====================================\r\n\r\n\r\n# CONNECT\r\nobjectA.translate.connect(objectB.translate)\r\n\r\n# WILL ERROR IF A CONNECTION IS ALREADY PRESENT\r\nobjectC.translate.connect(objectB.translate)\r\n\r\n# USE THE force FLAG\r\nobjectC.translate.connect(objectB.translate,f=True)\r\n\r\n# WHAT IF THE ATTRIBUTE HAS ANIMATION VALUES\r\n# !!!!! KEY THE ROTATE OF objectB\r\nobjectA.rotate.connect(objectB.rotate)\r\n\r\n\r\n# NO ERROR BUT NOT WORKING. WHY?\r\n# COMPOUND ATTRIBUTE\r\nobjectA.translate.isCompound()\r\nobjectA.translate.getChildren()\r\nobjectA.tx.parent()\r\nobjectA.tx.siblings()\r\n\r\n\"\"\" \r\nNotes on compound attributes\r\nthe members of the compound attribute collection are called\r\nchildren and they are part of the parent plug is called the compound\r\nscale, translate, rotate, colors, etc. work this way.\r\n\r\nit's the actual child that is attached to the API.\r\nthe parent container is just a convenient way to group attributes that\r\nare vectors or arrays\r\n\"\"\"\r\n\r\n\r\n\r\n\r\n\r\n# INPUTS AND OUTPUTS =========================================================\r\n# LISTING INPUTS\r\nobjectB.inputs()\r\nobjectB.inputs(type=\"animCurve\")\r\n\r\n# SAME AS but simpler\r\n# objectB.listConnections(s=True,d=False)\r\n\r\nobjectA.outputs()\r\n# SAME AS but simpler\r\n# objectA.listConnections(s=False,d=True)\r\n\r\n# USEFUL ARGS\r\n# plugs = True returns the name of the attribute that has a connection\r\nobjectB.inputs()\r\nobjectB.inputs(plugs=True)\r\n\r\n# SUPER USEFUL returns tuples of connections with main obj in the \r\n# first position of each tuple\r\nobjectB.inputs(connections=True)\r\n\r\n# DISCONNECTING ============================ \r\n# YOU CAN USE THE >> and // operators to connect too, but I don't know\r\n# HOW TO MAKE THE 'force' flag work with that\r\n# USE .connect and .disconnect so people who don't know pymel reading\r\n# your code later can understand what you're doing\r\nobjectB.translate.disconnect()\r\n\r\n# LOOP THROUGH AND DISCONNECT.\r\n[con.disconnect() for con in objectB.inputs(plugs=True)]\r\n\r\n# parent constraint B to A\r\n[con.disconnect() for con in objectB.inputs(plugs=True)]\r\n\r\n# BRIEFLY TALK ABOUT pairBlend nodes\r\nobjectB.inputs()\r\n\r\n# CREATING ATTRIBUTES ====================\r\nif not objectA.hasAttr(\"bob\"):\r\n objectA.addAttr(\"bob\",at=\"float\",k=True)\r\n \r\nif not objectA.hasAttr(\"sam\"):\r\n objectA.addAttr(\"sam\",at=\"float\", minValue=0.0, maxValue=1.0,hasMaxValue=True,hasMinValue=True)\r\n\r\n# MODIFY attribute behavior after it has been made\r\nobjectA.sam.setKeyable(True)\r\nobjectA.sam.setMin(-1.0)\r\n\r\n# DELETING AN ATTR\r\nobjectA.sam.delete()\r\n\r\n\r\n\r\n\r\n\r\n# OPEN FACE EXAMPLE FILE ==============================================================\r\n# GET THE GEOM\r\nhead = pm.PyNode(\"face_with_Blendshapes\")\r\n#GET THE SHAPE NODE\r\nheadShape = head.getShape()\r\n\r\n# GET THE BLENDSHAPE NODE INPUT\r\nblendShapeNode = headShape.inputs(type=\"blendShape\")[0].inputs(type=\"blendShape\")[0]\r\n\r\n# GET THE ATTR NAMES\r\nblendShapeNode.listAttr()\r\n# NOT shape names there????\r\n\r\n# eval the attribute\r\nblendShapeNode.L_brow_up\r\nblendShapeNode.L_cheek_up\r\n# Result: Attribute(u'faceShapes.weight[1]')\r\n# Result: Attribute(u'faceShapes.weight[8]') \r\n\r\n#What can we do with this?\r\nsee(blendShapeNode.weight[8])\r\n\r\n# TRY getAlias\r\nblendShapeNode.weight[8].getAlias()\r\n\r\n# find something to loop through and give an alias list \r\nsee(blendShapeNode)\r\n\r\n# .listAliases()\r\nblendShapeNode.listAliases()\r\n\r\n# SAME but a little different for weights on constraints\r\nparCon = pm.PyNode(\"face_with_Blendshapes_parentConstraint1\")\r\nsee (parCon)\r\nparCon.getWeightAliasList()","sub_path":"maya/CodeReference/www_cgcircuit_com/pymel/mod04_attributes/mod04_attributes.py","file_name":"mod04_attributes.py","file_ext":"py","file_size_in_byte":6235,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"423213968","text":"# -*- coding: utf-8 -*-\nfrom openerp import models, fields, api\nfrom pprint import pprint\nfrom datetime import datetime\nclass material_issue_wiz(models.TransientModel):\n _name = 'material.issue.wiz'\n\n\n def get_sale_ob(self):\n context = self._context\n active_id = context.get('active_id',False)\n sale = self.env['sale.order']\n return sale.browse(active_id)\n\n\n\n def default_vals(self):\n sale_ob = self.get_sale_ob()\n partner_id = sale_ob.partner_id and sale_ob.partner_id.id\n picking_type_id = sale_ob.warehouse_id and sale_ob.warehouse_id.out_type_id and \\\n sale_ob.warehouse_id.out_type_id.id\n company_id = sale_ob.company_id and sale_ob.company_id.id\n od_order_type_id = sale_ob.od_order_type_id and sale_ob.od_order_type_id.id\n od_analytic_id = sale_ob.project_id and sale_ob.project_id.id\n return {'partner_id':partner_id,'company_id':company_id,'od_analytic_id':od_analytic_id,\n 'od_order_type_id':od_order_type_id,'picking_type_id':picking_type_id,'origin':sale_ob.name,\n }\n def od_create_stock_moves(self,wiz_line,picking_id):\n stock_move = self.env['stock.move']\n todo_moves = []\n location_id = picking_id.picking_type_id and picking_id.picking_type_id.default_location_src_id and \\\n picking_id.picking_type_id.default_location_src_id.id\n location_dest_id = picking_id.picking_type_id and picking_id.picking_type_id.default_location_dest_id and \\\n picking_id.picking_type_id.default_location_dest_id.id\n invoice_state = self.get_invoice_control()\n partner_id = picking_id.partner_id and picking_id.partner_id.id\n for line in wiz_line:\n vals ={\n 'product_id':line.product_id and line.product_id.id,\n 'partner_id':partner_id,\n 'procure_method':'make_to_stock',\n 'product_uom':line.product_uom_id and line.product_uom_id.id,\n 'name':line.name,\n 'product_uom_qty':line.qty,\n 'date':datetime.now(),\n 'date_expected':datetime.now(),\n 'location_id':location_id,\n 'location_dest_id':location_dest_id,\n 'picking_id':picking_id.id,\n 'so_line_id':line.so_line_id and line.so_line_id.id,\n 'invoice_state':invoice_state,\n 'picking_type_id':picking_id.picking_type_id and picking_id.picking_type_id.id or False\n }\n if line.product_id.type in ('product', 'consu'):\n move = stock_move.create(vals)\n move.action_confirm()\n # todo_moves = stock_move.action_confirm(cr, uid, todo_moves)\n def get_invoice_control(self):\n sale_obj = self.get_sale_ob()\n order_policy = sale_obj.order_policy\n if order_policy == 'picking':\n return '2binvoiced'\n return 'none'\n @api.one\n def generate_delivery_order(self):\n order = self.get_sale_ob()\n wiz_line = self.wiz_line\n invoice_state = self.get_invoice_control()\n picking_vals = {\n 'date': order.date_order,\n 'origin': order.name,\n 'invoice_state':invoice_state,\n 'od_cost_sheet_id':order.od_cost_sheet_id and order.od_cost_sheet_id.id or False,\n 'od_cost_centre_id':order.od_cost_centre_id and order.od_cost_centre_id.id or False,\n 'od_branch_id':order.od_branch_id and order.od_branch_id.id or False,\n 'od_division_id':order.od_division_id and order.od_division_id.id or False\n }\n vals = self.default_vals()\n picking_vals.update(vals)\n picking_id = self.env['stock.picking'].create(picking_vals)\n self.od_create_stock_moves(wiz_line, picking_id)\n\n def get_default_line(self):\n res = []\n sale_ob = self.get_sale_ob()\n for line in sale_ob.order_line:\n od_issue_req_qty = line.od_issue_req_qty\n product_qty = line.product_uom_qty\n qty = product_qty - od_issue_req_qty\n ptype = line.product_id and line.product_id.type\n if qty > 0 and ptype != 'service' :\n res.append({'product_id':line.product_id and line.product_id.id or False,\n 'name':line.name,\n 'product_uom_id':line.product_uom and line.product_uom.id or False,\n 'qty':qty,\n 'so_line_id':line.id\n })\n return res\n def get_val(self,key):\n res =self.default_vals()\n return res.get(key,False)\n def get_partner_id(self):\n return self.get_val('partner_id')\n def get_company_id(self):\n return self.get_val('company_id')\n def get_picking_type_id(self):\n return self.get_val('picking_type_id')\n def get_order_type_id(self):\n return self.get_val('od_order_type_id')\n def get_analytic_id(self):\n return self.get_val('od_analytic_id')\n\n wiz_line = fields.One2many('material.issue.wiz.line','wiz_id',default=get_default_line)\n picking_type_id = fields.Many2one('stock.picking.type',string=\"Picking Type\",required=True,readonly=True,default=get_picking_type_id)\n company_id = fields.Many2one('res.company',string='Company',required=True,readonly=True,default=get_company_id)\n partner_id = fields.Many2one('res.partner',string=\"Partner\",default=get_partner_id,required=True)\n od_order_type_id = fields.Many2one('od.order.type',string=\"Transaction Type\",default=get_order_type_id)\n od_analytic_id = fields.Many2one('account.analytic.account',string=\"Analytic Account\",default=get_analytic_id)\n\n\n\nclass material_issue_wiz_line(models.TransientModel):\n _name = 'material.issue.wiz.line'\n wiz_id = fields.Many2one('material.issue.wiz',string=\"Wizard\")\n product_id = fields.Many2one('product.product',string=\"Product\")\n name = fields.Char(string='Name')\n product_uom_id =fields.Many2one('product.uom',string='Unit')\n qty = fields.Float(string='Product Qty')\n so_line_id = fields.Many2one('sale.order.line',string=\"Sale Order Line\")\n","sub_path":"orchid_cost_sheet/wizard/material_issue_wiz.py","file_name":"material_issue_wiz.py","file_ext":"py","file_size_in_byte":6191,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"428654072","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\" _ \n / | | __ _ __ _\n / | / |_||_|| ||\n / | / | |\\ | ||_\n /____ |__/\\ . | | \\|_|\\_|\n __________________________ .\n \nCreated on Wed Jun 19 09:36:27 2019\n\n@author: chrisunderwood\n \n Background Remover\n\"\"\"\nimport numpy as np\nimport matplotlib as mpl\nimport matplotlib.pyplot as plt\n\n# Load my module of functions\nimport CUnderwood_Functions3 as func\n\nimport unittest\nimport backgroundRemover\n\n\nclass test_backgroundRemover(unittest.TestCase):\n \n def test_RemovingBackgroundReducesAverage(self):\n LoadPath = \"/Volumes/GoogleDrive/My Drive/Experimental_Codes/Interferometry_Data_Extraction/verticalFrings.txt\"\n # Call the class\n bc = backgroundRemover.backgroundRemoverAndCrop()\n bc.LoadData(LoadPath)\n bc.blur(bc.im, 11)\n bot = 40\n top = 300\n left = 100\n right = 500\n out = bc.sub_blurredIm(bot, top, left, right) \n orig = bc.im[bot:top, left:right]\n \n self.assertTrue(abs(np.average(out)) < abs(np.average(orig)))\n\n def test_blur(self):\n # I can't think how to test this as it is just a scipy function....\n pass\n \n\n \n\nif __name__ == \"__main__\":\n\tunittest.main()\n","sub_path":"ta2_hrr_2019/Probe/test_backgroundRemover.py","file_name":"test_backgroundRemover.py","file_ext":"py","file_size_in_byte":1287,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"481846878","text":"import numpy as np\r\nimport matplotlib.pyplot as plt\r\nimport random\r\nfrom sklearn import datasets\r\nfrom sklearn.model_selection import train_test_split\r\nfrom sklearn.preprocessing import Normalizer\r\nfrom tensorflow.examples.tutorials.mnist import input_data\r\n#mnist = input_data.read_data_sets(\"MNIST_data\", one_hot=True)\r\n\r\n#X=mnist.train.images[8].reshape(-1,28)\r\n#imgplot = plt.imshow(X)\r\n#plt.show()\r\n\r\n#with open('结果存放.txt','a') as file_handle: \r\n# x=mnist.train.images[8].reshape(-1,28)\r\n# for i in x:\r\n# for j in i:\r\n# file_handle.write(str(j)+\" \") \r\n# file_handle.write(\"\\n\")\r\n\r\n\r\nif __name__ == '__main__':\r\n mnist = input_data.read_data_sets(\"MNIST_data\", one_hot=True)\r\n #MINBATCH\r\n Xc=mnist.train.images\r\n yc=np.zeros(len(mnist.train.labels),dtype='uint8')\r\n for i in range(len(mnist.train.labels)):\r\n for j in range(len(mnist.train.labels[i])):\r\n if mnist.train.labels[i][j]==1:\r\n yc[i]=j\r\n X=[Xc[i:i+5500] for i in range(0,len(Xc),5500)]\r\n y=[yc[i:i+5500] for i in range(0,len(yc),5500)]\r\n\r\n\r\n D = 784 # 样本维数(二维相当于横纵坐标)\r\n K = 10 # 样本种类数\r\n\r\n #两层神经网络尝试\r\n h1=100\r\n h2=100\r\n #初始化W和b\r\n W1=0.01*np.random.randn(D,h1)\r\n b1=np.zeros((1,h1))\r\n #print(b1)\r\n W2=0.01*np.random.randn(h1,h2)\r\n b2=np.zeros((1,h2))\r\n #print(b2)\r\n W3=0.01*np.random.randn(h2,K)\r\n b3=np.zeros((1,K))\r\n\r\n #设定步长(学习率)、和正则参数\r\n step=0.00001\r\n reg=1e-3\r\n\r\n \r\n #循环15000次\r\n for i in range(15001):\r\n j=i%10\r\n num_examples=X[j].shape[0]\r\n #每一千次步长缩小10%\r\n #if i%10000==0:\r\n # step=0.9*step\r\n #使用的ReLU激活函数\r\n hiddenout1=np.maximum(0,np.dot(X[j],W1)+b1)\r\n hiddenout2=np.maximum(0,np.dot(hiddenout1,W2)+b2)\r\n scores=np.dot(hiddenout2,W3)+b3\r\n #计算每一样本的分类概率(softmax)\r\n scores_exp=np.exp(scores)\r\n prob=scores_exp/np.sum(scores_exp,axis=1,keepdims=True)\r\n #计算损失(交叉熵损失,加正则)\r\n cross_loss_prob=-np.log(prob[range(num_examples),y[j]])\r\n cross_loss=np.sum(cross_loss_prob)/num_examples\r\n reg_loss = 0.5*reg*np.sum(W1*W1) + 0.5*reg*np.sum(W2*W2)+0.5*reg*np.sum(W3*W3)\r\n loss = cross_loss + reg_loss\r\n if i % 1000 == 0:\r\n print(\"循环次数: %d, 损失: %f\" % (i, loss))\r\n\r\n #计算梯度\r\n #输出的梯度\r\n dprob=prob\r\n dprob[range(num_examples),y[j]]-=1\r\n #dprob=dprob/num_examples\r\n #scores=np.dot(hiddenout2,W3)+b3梯度\r\n dW3=np.dot(hiddenout2.T,dprob)\r\n db3=np.sum(dprob,axis=0,keepdims=True)\r\n dhiddenout2=np.dot(dprob,W3.T)\r\n dhiddenout2[hiddenout2<=0]=0\r\n #hiddenout2=np.maximum(0,np.dot(hiddenout1,W2)+b2)梯度\r\n dW2=np.dot(hiddenout1.T,dhiddenout2)\r\n db2=np.sum(dhiddenout2,axis=0,keepdims=True)\r\n dhiddenout1=np.dot(dhiddenout2,W2.T)\r\n dhiddenout1[hiddenout1<=0]=0\r\n #hiddenout1=np.maximum(0,np.dot(X,W1)+b1)梯度\r\n dW1=np.dot(X[j].T,dhiddenout1)\r\n db1=np.sum(dhiddenout1,axis=0,keepdims=True)\r\n #梯度正则\r\n dW3+=reg*W3\r\n dW2+=reg*W2\r\n dW1+=reg*W1\r\n\r\n #参数更新\r\n W1+=-step*dW1\r\n b1+=-step*db1\r\n W2+=-step*dW2\r\n b2+=-step*db2\r\n W3+=-step*dW3\r\n b3+=-step*db3\r\n\r\n #测试\r\n Xc=mnist.train.images\r\n yc=np.zeros(len(mnist.train.labels),dtype='uint8')\r\n for i in range(len(mnist.train.labels)):\r\n for j in range(len(mnist.train.labels[i])):\r\n if mnist.train.labels[i][j]==1:\r\n yc[i]=j\r\n hiddenout1=np.maximum(0,np.dot(Xc,W1)+b1)\r\n hiddenout2=np.maximum(0,np.dot(hiddenout1,W2)+b2)\r\n scores=np.dot(hiddenout2,W3)+b3\r\n g1 = np.argmax(scores, axis=1)\r\n print('训练集准确度: %.2f' % (np.mean(g1 == yc)))\r\n # 测试1\r\n X2=mnist.validation.images\r\n y2=np.zeros(len(mnist.validation.labels),dtype='uint8')\r\n for i in range(len(mnist.validation.labels)):\r\n for j in range(len(mnist.validation.labels[i])):\r\n if mnist.validation.labels[i][j]==1:\r\n y2[i]=j\r\n hiddenout1=np.maximum(0,np.dot(X2,W1)+b1)\r\n hiddenout2=np.maximum(0,np.dot(hiddenout1,W2)+b2)\r\n scores=np.dot(hiddenout2,W3)+b3\r\n g2 = np.argmax(scores, axis=1)\r\n print('验证集准确度: %.2f' % (np.mean(g2 == y2)))\r\n #测试2\r\n X1=mnist.test.images\r\n y1=np.zeros(len(mnist.test.labels),dtype='uint8')\r\n for i in range(len(mnist.test.labels)):\r\n for j in range(len(mnist.test.labels[i])):\r\n if mnist.test.labels[i][j]==1:\r\n y1[i]=j\r\n hiddenout1=np.maximum(0,np.dot(X1,W1)+b1)\r\n hiddenout2=np.maximum(0,np.dot(hiddenout1,W2)+b2)\r\n scores=np.dot(hiddenout2,W3)+b3\r\n g3 = np.argmax(scores, axis=1)\r\n print('测试集准确度: %.2f' % (np.mean(g3 == y1)))\r\n","sub_path":"MNIST_BP3.py","file_name":"MNIST_BP3.py","file_ext":"py","file_size_in_byte":5048,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"276188653","text":"from __future__ import absolute_import\n\nimport collections\n\nfrom six.moves import range\n\nfrom ably import AblyRest, AblyException\nfrom ably import ChannelOptions\nfrom ably.rest.channel import Channel, Channels, Presence\nfrom ably.types.capability import Capability\nfrom ably.util.crypto import get_default_params\n\nfrom test.ably.restsetup import RestSetup\nfrom test.ably.utils import BaseTestCase\n\ntest_vars = RestSetup.get_test_vars()\n\n\n# makes no request, no need to use different protocols\nclass TestChannels(BaseTestCase):\n\n def setUp(self):\n self.ably = AblyRest(key=test_vars[\"keys\"][0][\"key_str\"],\n rest_host=test_vars[\"host\"],\n port=test_vars[\"port\"],\n tls_port=test_vars[\"tls_port\"],\n tls=test_vars[\"tls\"])\n\n def test_rest_channels_attr(self):\n self.assertTrue(hasattr(self.ably, 'channels'))\n self.assertIsInstance(self.ably.channels, Channels)\n\n def test_channels_get_returns_new_or_existing(self):\n channel = self.ably.channels.get('new_channel')\n self.assertIsInstance(channel, Channel)\n channel_same = self.ably.channels.get('new_channel')\n self.assertIs(channel, channel_same)\n\n def test_channels_get_returns_new_with_options(self):\n options = ChannelOptions(encrypted=False)\n channel = self.ably.channels.get('new_channel', options=options)\n self.assertIsInstance(channel, Channel)\n self.assertIs(channel.options, options)\n\n def test_channels_get_updates_existing_with_options(self):\n options = ChannelOptions(encrypted=True,\n cipher_params=get_default_params())\n options_new = ChannelOptions(encrypted=False)\n\n channel = self.ably.channels.get('new_channel', options=options)\n self.assertIs(channel.options, options)\n\n channel_same = self.ably.channels.get('new_channel', options=options_new)\n self.assertIs(channel, channel_same)\n self.assertIs(channel.options, options_new)\n\n def test_channels_get_doesnt_updates_existing_with_none_options(self):\n options = ChannelOptions(encrypted=True,\n cipher_params=get_default_params())\n\n channel = self.ably.channels.get('new_channel', options=options)\n self.assertIs(channel.options, options)\n\n channel_same = self.ably.channels.get('new_channel')\n self.assertIs(channel, channel_same)\n self.assertIsNot(channel.options, None)\n self.assertIs(channel.options, options)\n\n def test_channels_in(self):\n self.assertTrue('new_channel' not in self.ably.channels)\n self.ably.channels.get('new_channel')\n new_channel_2 = self.ably.channels.get('new_channel_2')\n self.assertTrue('new_channel' in self.ably.channels)\n self.assertTrue(new_channel_2 in self.ably.channels)\n\n def test_channels_iteration(self):\n channel_names = ['channel_{}'.format(i) for i in range(5)]\n [self.ably.channels.get(name) for name in channel_names]\n\n self.assertIsInstance(self.ably.channels, collections.Iterable)\n for name, channel in zip(channel_names, self.ably.channels):\n self.assertIsInstance(channel, Channel)\n self.assertEqual(name, channel.name)\n\n def test_channels_release(self):\n self.ably.channels.get('new_channel')\n self.ably.channels.release('new_channel')\n\n with self.assertRaises(KeyError):\n self.ably.channels.release('new_channel')\n\n def test_channels_del(self):\n self.ably.channels.get('new_channel')\n del self.ably.channels['new_channel']\n\n with self.assertRaises(KeyError):\n del self.ably.channels['new_channel']\n\n def test_channel_has_presence(self):\n channel = self.ably.channels.get('new_channnel')\n self.assertTrue(channel.presence)\n self.assertTrue(isinstance(channel.presence, Presence))\n\n def test_channel_options_encrypted_without_params(self):\n with self.assertRaises(ValueError):\n ChannelOptions(encrypted=True)\n\n def test_without_permissions(self):\n key = test_vars[\"keys\"][2]\n ably = AblyRest(key=key[\"key_str\"],\n rest_host=test_vars[\"host\"],\n port=test_vars[\"port\"],\n tls_port=test_vars[\"tls_port\"],\n tls=test_vars[\"tls\"])\n with self.assertRaises(AblyException) as cm:\n ably.channels['test_publish_without_permission'].publish('foo', 'woop')\n\n the_exception = cm.exception\n self.assertIn('not permitted', the_exception.message)\n","sub_path":"test/ably/restchannels_test.py","file_name":"restchannels_test.py","file_ext":"py","file_size_in_byte":4706,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"79508160","text":"import requests\nimport time\nimport json\n\ndef data_daemon():\n\n r = requests.get('http://ec2-54-183-187-18.us-west-1.compute.amazonaws.com:5000/response')\n \n with open('data.json', 'w') as f:\n f.write(json.dumps(r.json()))\n\nif __name__ == '__main__':\n while(1):\n data_daemon()\n time.sleep(10) \n","sub_path":"p5/data_daemon.py","file_name":"data_daemon.py","file_ext":"py","file_size_in_byte":325,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"37815910","text":"import pandas as pd\nimport datetime as dt\nimport methods as m\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport math\nfrom statsmodels.tsa.ar_model import AutoReg\nfrom sklearn.metrics import mean_squared_error\nfrom statsmodels.tsa.ar_model import ar_select_order\n\n# run a repeated experiment\ndef experiment_lags(series, n_lag, n_repeats, folds):\n\n data = np.array(np.array_split(series, folds))\n trends = ['c']\n lag_errors = []\n\n for i in np.arange(1,n_lag):\n errors = []\n for r in range(n_repeats):\n for t in trends:\n for k in np.arange(2,folds):\n for j in np.arange(0,1):\n\n test = data[k]\n train = np.concatenate(data[j:k]).ravel()\n if len(train)> i:\n #fit autoregressive model\n model = AutoReg(train, lags=i, trend=t)\n try:\n model_fit = model.fit()\n except:\n print(\"Couldnt fit model!\")\n\n predictions = pred(train, test, i, model_fit.params)\n rmse = math.sqrt(mean_squared_error(test, predictions))\n errors.append(rmse)\n else:\n print(\"Dataset too small for %f folds\" % folds)\n lag_errors.append(np.average(errors))\n\n return lag_errors\n\n\n# run a repeated experiment\ndef experiment_length(series,lag, n_repeats, folds):\n\n data = np.array(np.array_split(series, folds))\n trends = ['c']\n length_error = []\n for j in np.arange(1,folds):\n error = []\n for r in range(n_repeats):\n for t in trends:\n for k in np.arange(j,folds):\n\n test = data[k]\n if(j>1):\n train = np.concatenate(data[k-j:k]).ravel()\n else:\n train = data[k-j:k][0]\n\n #fit autoregressive model\n model = AutoReg(train, lags=lag, trend=t)\n try:\n model_fit = model.fit()\n except:\n print(\"Couldnt fit model!\")\n predictions = pred(train, test, lag, model_fit.params)\n print(len(train))\n rmse = math.sqrt(mean_squared_error(test, predictions))\n error.append(rmse)\n\n print(\"training length\",len(train))\n length_error.append(np.average(error))\n\n return length_error\n\n\n# run a repeated experiment\ndef experiment_type(series,lag, n_repeats, folds):\n data = np.array(np.array_split(series, folds))\n trends = ['c', 'ct', 't']\n type_error = []\n\n x = 0\n for t in trends:\n errors = []\n for r in range(n_repeats):\n for k in np.arange(2,folds):\n for j in np.arange(0,k):\n\n test = data[k]\n train = np.concatenate(data[j:k]).ravel()\n if len(train)> i:\n #fit autoregressive model\n model = AutoReg(train, lags=lag, trend=t)\n try:\n model_fit = model.fit()\n except:\n print(\"Couldnt fit model!\")\n\n predictions = pred(train, test, lag, model_fit.params)\n rmse = math.sqrt(mean_squared_error(test, predictions))\n errors.append(rmse)\n else:\n print(\"Dataset too small for %f folds\" % folds)\n type_error.append(np.average(errors))\n\n return type_error\n\n\ndef pred(train, test, n_lag,coeff):\n\n history = train[len(train) - n_lag:]\n history = [history[i] for i in range(len(history))]\n predictions = list()\n for t in range(len(test)):\n length = len(history)\n lag = [history[i] for i in range(length - n_lag, length)]\n #yhat = 0\n yhat = coeff[0]\n for d in range(n_lag):\n yhat += coeff[d + 1] * lag[n_lag - d - 1]\n #yhat += coeff[d] * lag[n_lag - d - 1]\n obs = test[t]\n predictions.append(yhat)\n history.append(obs)\n\n return predictions\n\nif __name__ == '__main__':\n\n ### SET PARAMETERS ###\n td = 0 # Time delay between twitter and polls\n rel_shift = 0.7\n tPolls = math.floor(td*rel_shift)\n tTwitter = math.ceil((1-rel_shift)*td)\n\n startTrain = 53\n m.setFonts('timeseries')\n ### Load in data and normalise\n twitterColumns = [0, 2]\n pollColumns = [1,3, 4, 5, 6, 7, 8,9] # avdate, Remain (norm), Leave (norm)\n lh, rh, p = m.getPanda(twitterColumns,pollColumns)\n h_agg, p_agg, p_var = m.aggregate(lh, rh, p, splitPolls=False,interpolate=True)\n _ , p_onl, p_tel = m.aggregate(lh,rh,p,splitPolls=True,interpolate=True)\n\n kalmanData = m.getKalmanData(p_agg, h_agg)\n\n all_data = kalmanData['remain_perc'].iloc[startTrain:]\n remain_data = all_data.values\n dates_train = all_data.index\n\n # run experiment for lags\n print(\"order to use\",ar_select_order(remain_data, maxlag=13)._aic)\n n_lag = 7\n runs = 100\n k = np.arange(4,5)\n res = np.zeros(shape=(len(k),n_lag-1))\n sorted = np.zeros(shape=(len(k),n_lag-1))\n\n for i,j in enumerate(k):\n res[i] = experiment_lags(remain_data, n_lag, runs, j)\n\n print(\"sum of results: \" + str(np.sum(res,axis=0)))\n optimal_lag = np.argmin(np.sum(res,axis=0))+1\n print(\"optimal lag = \" + str(optimal_lag))\n\n\n optimal_lag = 1\n runs = 3\n # Now train series for the optimal length (how long do i train to have optimal results?)\n optimal_length = experiment_length(remain_data,optimal_lag,runs,5)\n print(\"optimal length = \" + str(optimal_length))\n\n #print fit\n optimal_type = 'c'\n optimal_lag = 1\n\n startDate = kalmanData.index[startTrain]+dt.timedelta(days=optimal_lag)\n endDate = kalmanData.index[-1]\n pred_dates = pd.date_range(start=startDate, end=endDate)\n end_train = math.floor(len(remain_data)*0.2)\n\n test = remain_data[-end_train:]\n train = remain_data[:-end_train]\n model = AutoReg(train, lags=optimal_lag, trend=optimal_type)\n model_fit = model.fit()\n coeff = model_fit.params\n predictions = np.concatenate((np.array(model.predict(coeff,optimal_lag,len(train)-1)), np.array(pred(train,test,optimal_lag,coeff))))\n\n print(\"basic rmse\", math.sqrt(mean_squared_error(predictions,remain_data[optimal_lag:])))\n print(\"test set rmse\", math.sqrt(mean_squared_error(predictions[-23:],remain_data[-23:])))\n print(\"rmse with persistence model\", math.sqrt(mean_squared_error(predictions[1:],remain_data[optimal_lag:-1])))\n\n\n plt.plot(dates_train[optimal_lag:-1], predictions[1:])\n plt.plot(dates_train[optimal_lag:-1], remain_data[optimal_lag:-1])\n plt.show()\n\n fig, ax = plt.subplots()\n line1, = ax.plot(dates_train,remain_data, label=\"Truth\", marker='o',color='blue')\n line2, = ax.plot(pred_dates,predictions, label=\"Predictions\", marker='o',color='red')\n plt.axvline(x=dt.datetime(2016, 6, 23), label=\"Brexit vote\", color='slategray', linestyle='-.')\n ax.fill_between([dt.datetime(2016, 6, 23),endDate-dt.timedelta(days=end_train)], 0, 100,\n facecolor='gainsboro', interpolate=True)\n\n handles = [line1, line2]\n plt.xlabel(\"Date\")\n plt.ylabel(\"% support\")\n plt.ylim([0,100])\n plt.legend(handles=handles)\n plt.show()","sub_path":"trainingAR.py","file_name":"trainingAR.py","file_ext":"py","file_size_in_byte":7574,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"206673167","text":"from datetime import datetime\nfrom . import DatabaseContextManager\n\ndef create_table_bikesharing():\n query = \"\"\"CREATE TABLE `bikesharing` (\n `tstamp` timestamp,\n `cnt` integer,\n `temperature` decimal(5, 2),\n `temperature_feels` decimal(5, 2),\n `humidity` decimal(4, 1),\n `wind_speed` decimal(5,2),\n `weather_code` integer,\n `is_holiday` boolean,\n `is_weekend` boolean,\n `season` integer);\"\"\"\n\n with DatabaseContextManager() as db:\n db.execute(query)\n\n\ndef convert_line_to_values(line):\n values = line.split(\",\")\n # convert timestamp to datetime\n values[0] = datetime.st(values[0], \"%Y-%m-%d %H:%M:%S\")\n return values\n\n sql = \"\"\"\n INSERT INTO bikesharing\n (tstamp, cnt, temperature, temperature_feels, humidity, wind_speed,\n weather_code, is_holiday, is_weekend, season) VALUES\n (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s)\n \"\"\"\n\n with DatabaseContextManager() as cursor:\n with open(\"london-bikes.csv\") as f:\n for i, line in enumerate(f):\n if i == 0:\n continue\n values = convert_line_to_values(line)\n cursor.execute(sql, values)\n if i % 100 == 0:\n db.commit()\n db.commit()\n db.close()\n\ndatetime.hour\n\n","sub_path":"TasksInMysql/task1.py","file_name":"task1.py","file_ext":"py","file_size_in_byte":1315,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"579588170","text":"# This is the scraper with Part 2 and Part 3 Code: Will scrape data, add the Census data columns and then make a new csv\n# Part 1: Mahmudul Hasan. Script to scrape JSON Gas Leak Data points from ConEdison everyday and put them into a csv file for further use\n # In the ConEdison Gas Leak Report Map, each report in the map represents a gas leak report. Each report has these seven keys: TicketNumber, Latitude, Longitude, Zipcode, Classification Type, Date Reported, Last Inspected.\n # a) We need to constantly add new repots to out list so what tickets do we currently have? read the ticket col of the \"csvConEdFile\" and add the tickets to \"ticketSet\"\n # b) Scrape the JSON html response and using pandas to put the contents into a dataframe called \"jsonDF\"\n # c) See if there is a new report: Loop through each JSON obbject in \"jsonDF\" and compare it to the reports are already exists in \"ticketSet\"\n # d) If there is a new report, add append the keys of that report into \"csvConEdFile\", \"ticketListFile\" and push the latest changes to github\n# Part 2: Will edit the csv to have new columns for the Census Tract, Census Block, County Name and the hour only\n # Will use the census api to get census data from the lat and lon coords using this url request: https://geocoding.geo.census.gov/geocoder/geographies/coordinates?x=LONGITUDE&y=LATITUDE&benchmark=Public_AR_Current&vintage=Current_Current&format=json\n# Part 3: Will create a new csv that lists the reports per census tract per hour for that day. Headers: Date, Hour, Census Tract, Number of Reports\n\nimport json\nimport csv\nimport pandas as pd # to read csv file and store conent into a data frame. To turn json response string into a dataframe\nimport datetime,re # to turn Microsoft JSON date /Date()/ to normal date\nimport requests # Getting html data\nfrom bs4 import BeautifulSoup # Parse the HTML data\nfrom apscheduler.schedulers.blocking import BlockingScheduler # Sceduler. Will run a function every x seconds/minutes/hours\nfrom git import Repo # (GitPython) To push changes to gh\n\n\n# SETTING UP GLOBAL VARIABLES: need to change the first eight variables below\ncsvFile = \"test.csv\"#\"GasHistory_ConEdison.csv\" # add new tickets to the end of the csv file\nticketListFile = \"test.txt\"#\"conEd_TicketList.txt\" # add to end (just for me to see what i got)\njsonFile = \"SOME_JSON_FILE_WITH_SAME_KEYS.json\" # Normally the programm will be scrape JSOn data from a url but sometimes it might need to extract JSOn data from a file. See step 2)\nurl = 'https://apps.coned.com/gasleakmapweb/GasLeakMapWeb.aspx?ajax=true&' # Url to scrape JSOn data from\ndropCol = True # If you want to drop a column, specify which ones in step 2 in WebscraperJsonToCSV()\naddCols = [\"Date\", \"Time\", \"Hour\"] # Replacing column DateReported with these cols\n# csvHeader = [\"TicketNumber\",\"Longitude\",\"Latitude\",\"Zipcode\",\"Classification\",\"Date\", \"Time\", \"Hour\"]\n# keys= [ # The JSON report keys( better to use key iteration, instead i went through the columns of the dictionary with this)\n# \"TicketNumber\",\n# \"Latitude\",\n# \"Longitude\",\n# \"Zip\",\n# \"ClassificationType\",\n# \"DateReported\",\n# \"LastInspected\"\n# ]\n\nPATH_OF_GIT_REPO = r'/home/pi/repositories/gh/GasLeakProject' # the path to the .git file (.git location on my raspberry pi)\n#PATH_OF_GIT_REPO = r'/home/hasan/repositories/gh/GasLeakProject' # the path to the .git file (.git location on my Laptop)\nCOMMIT_MESSAGE = 'Automated Push - New Ticket Update' # the commmit message when it is pushed\nticketSet = set() # need to add what i got in the csv atm\nscrapingCount = 0 # Just counting how many times i have scraped the website while this was running\n\n# GIT PUSH FUNCTION: Setting up function to automatically push changes to github when there is a new ticket so that I can have access to the latest chnages\ndef git_push():\n repo = Repo(PATH_OF_GIT_REPO)\n try:\n repo.remotes.origin.pull() # try pulling new changes from the github repo (if there are any) so i can push changes\n except:\n print(\"Couldnt pull from repo\")\n repo.git.add(update=True)\n repo.index.commit(COMMIT_MESSAGE)\n origin = repo.remote(name='origin')\n try:\n origin.push() # try pushing the changes to github\n print(\"******** PUSHED TO GITHUB for Run \" + str(scrapingCount)+\"********\")\n except:\n print('Some error occured while pushing the code') \n \n\n# FUNCTION TO TURN MICROSOFT JSON DATE TO mm/dd/yyyy AND TIME: returns [\"mm/dd/yyyy\", \"hh:mm AM/PM\", \"hh AM/PM\"]\ndef turnToDateTimeHr(microsoftDate): \n TimestampUtc = str(microsoftDate)\n TimestampUtc = re.split('\\(|\\)', TimestampUtc)[1][:10]\n dateRaw = datetime.datetime.fromtimestamp(int(TimestampUtc))\n dateFormatted = str(dateRaw.strftime('%m/%d/20%y %I:%M %p')) # The datetime is of form: \"mm/dd/tt hh:mm AM/PM\"\n dateTimeSplit = dateFormatted.split(\" \") # [\"mm/dd/yyyy\", \"hh:mm\", \"AM/PM\"]\n date = dateTimeSplit[0] # Isolated the date string: \"mm/dd/yyyy\"\n time = dateTimeSplit[1] + \" \" + dateTimeSplit[2] # Isolated the time string: \"hh:mm AM/PM\"\n hour = time.split(\" \")[0].split(\":\")[0] + \" \" + dateTimeSplit[2] # Isolated the hour string: \"hh AM/PM\" (will need for part 2)\n dateTimeHr = [date, time, hour] # [\"mm/dd/yyyy\", \"hh:mm AM/PM\", \"hh AM/PM\"]\n return (dateTimeHr) \n\n# THE SCHEDULER WILL RUN THIS MAIN FUNCTION EVER X SECONDS/MINUTES/HOURS\ndef WebscraperJsonToCSV(): \n # Set up the web scraping iteration counter for debugging purposes\n global scrapingCount # Indicate that im using the global value\n scrapingCount = scrapingCount + 1 \n isNewTicket = False\n \n # 1) GET JSON DATA: Webscrape the html response which is usually just the JSON data from the url and add to the JSON Dataframe: \n # jsonDF = pd.read_json(jsonFile, orient='records') # If im getting data from json file, comment out the rest of this section. form: jsonDF[keys[i]/colStr(report keys)][j/rowsnumber(reports)]\n try:\n res = requests.get(url)\n html_data = res.content # Getting the HTML JSON data from the url \n soup = BeautifulSoup(html_data, 'html.parser') # parsing the html data with html parcer (can do stuuf like soup.title to get the title, soup.div, soup.li etc)\n text = soup.find_all(text=True) # Getting all the text thats in the soup\n \n jsonStr = '' # turning text to string from so i can use pandas to turn it to a dataframe\n for t in text:\n jsonStr += '{} '.format(t)\n jsonDF = pd.read_json(jsonStr, orient='records') # Turning the json string to a pandas dataframe\n except:\n print(\"Couldnt get the json data so will re-run function. This is Run \"+ str(scrapingCount))\n return WebscraperJsonToCSV()\n \n\n # 2) If the csv is empty, print the header. Im also droping columns from json DF and adding new col titles to csvHeader array\n if dropCol == True:\n jsonDF = jsonDF.drop(columns=[\"LastInspected\"]) # Dropping this col fom the jsonDF \n csvHeader = list(jsonDF.drop(columns=[\"DateReported\"]).columns.values) # \"DateReported\" Will be replaced by \"Date,Time,Hour\" So will now \n csvHeader.extend(addCols)\n\n with open(csvFile, 'r') as csvfile:\n csv_table = [row for row in csv.DictReader(csvfile)]\n if len(csv_table) == 0:\n with open(csvFile, 'w', newline='') as outf:\n writer = csv.writer(outf)\n writer.writerow(csvHeader)\n \n # 3) CHECK WHAT TICKETS WE ALREADY GOT FROM THE .CSV FILE AND ADD NEW TICKETS TO ticketSet and .txt file: Read the csv file and add \"TicketNumbers\" to the \"ticketSet\" and print ticketNumber to ticketList.txt\" for storage: \n csvDF = pd.read_csv(csvFile) # ***csvDF[colStr][rowNumber]\n outTXT = open(ticketListFile,\"w+\") # Settign up to write to txt file\n for row in range(0,len(csvDF)):\n ticketSet.add(str(csvDF[\"TicketNumber\"][row])) \n outTXT.write(str(csvDF[\"TicketNumber\"][row])+\"\\n\") # there is an error so cant continue so end this\n\n # 4) CHECK IF NEW TICKET: See if the tickets in \"jsonDF\" are in \"ticketDict\". If we have have it, add to \"ticketDic\", and .txt and .csv file for stoage. If we have it, skip this row since we have this info already. \n for row in range(0, len(jsonDF)):\n if jsonDF[\"TicketNumber\"][row] not in ticketSet: # If we DONT have this ticket add it\n isNewTicket = True # This is a new ticket so push the new files\n print(str(jsonDF[\"TicketNumber\"][row])+ \" not in set so adding it\")\n ticketSet.add(jsonDF[\"TicketNumber\"][row])\n outTXT.write(jsonDF[\"TicketNumber\"][row]+\"\\n\") # add new ticket to txt file \n with open(csvFile,'a') as outCSV: # Write the new Ticket object to csv file\n s=\"\"\n for col in jsonDF.columns: # go through each column property of the report. len(keys) -1 because im skipping the last key which is \"LastInspected\" (not needed)\n if col == \"DateReported\": # Need to change the Microsoft time to mm/dd/yyyy\n dateTimeHr = turnToDateTimeHr(str(jsonDF[col][row])) # Takes the microsoft date and returns: [\"mm/dd/yyyy\", \"hh:mm AM/PM\", \"hh AM/PM\"]\n s+=dateTimeHr[0]+\",\"+dateTimeHr[1]+\",\"+dateTimeHr[2]\n else: \n s+=str(jsonDF[col][row])\n s+=\",\"\n # for col in range(0, len(csvHeader)-1): # go through each column/report property. len(keys) -1 because im skipping the last key which is \"LastInspected\" (not needed)\n # if csvHeader[col] == \"DateReported\": # Need to change the Microsoft time to mm/dd/yyyy\n # dateTimeHr = turnToDateTimeHr(str(jsonDF[csvHeader[col]][row])) # Takes the microsoft date and returns: [\"mm/dd/yyyy\", \"hh:mm AM/PM\", \"hh AM/PM\"]\n # s+=dateTimeHr[0]+\",\"+dateTimeHr[1]+\",\"+dateTimeHr[2]\n # else: \n # s+=str(jsonDF[csvHeader[col]][row])\n # if col != len(csvHeader)-2:\n # s+=',' \n s = s[:-1] # Deleting the last comma for the row\n s += \"\\n\"\n outCSV.write(s) # add new ticket obj to csv file \n \n \n \n \n \n \n \n # # 5) PUSH TO GITHUB IF WE HAVE A NEW TICKET:\n # # if (isNewTicket == True):\n # # git_push()\n # # isNewTicket == False\n print(\"Run Done \" + str(scrapingCount) + \" Reports Scraped: \"+str(len(jsonDF)))\n\n\n\n\n\n\n\n# 6) RESCAN FOR TICKETS every x time using sceduler\nscheduler = BlockingScheduler()\nscheduler.add_job(WebscraperJsonToCSV, 'interval', seconds=1)\nscheduler.start()\n\n\n","sub_path":"DataFiles/Old Stuff/Old Files 2/scraper_ConEdison2_NotDone.py","file_name":"scraper_ConEdison2_NotDone.py","file_ext":"py","file_size_in_byte":13126,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"586892317","text":"#MCMC\n#Probability of the Weather\n\nimport random\n\n#function definitions\ndef genMarkovDays(n):\n climate = \"SR\"\n days = \"\"\n days += random.choice(climate)\n for i in range(1, n):\n if days[i-1] == 'S':\n weather = random.choices(climate, weights=(90,10), k=1)\n elif days[i-1] == 'R':\n weather = random.choices(climate, weights=(50,50), k=1)\n weatherToday = weather[0]\n days += weatherToday\n return days\n\ndef calcProbability(string):\n dct = {}\n for letter in string:\n if letter not in dct:\n dct.update({letter: 1})\n else:\n dct[letter] += 1\n for val in dct:\n dct[val] /= len(string)\n return dct\n\n#function calls\nchain = genMarkovDays(1000)\nprobability = calcProbability(chain)\n\nprint(probability)\n","sub_path":"MCMCWeather/mcmcWeather.py","file_name":"mcmcWeather.py","file_ext":"py","file_size_in_byte":810,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"569734805","text":"from __future__ import print_function\nimport httplib2\nimport os\nfrom random import randint\n\nfrom apiclient import discovery\nfrom oauth2client import client\nfrom oauth2client import tools\nfrom oauth2client.file import Storage\nimport datetime\n\ntry:\n import argparse\n flags = argparse.ArgumentParser(parents=[tools.argparser]).parse_args()\nexcept ImportError:\n flags = None\n\n# If modifying these scopes, delete your previously saved credentials\n# at ~/.credentials/sheets.googleapis.com-python-quickstart.json\nSCOPES = 'https://www.googleapis.com/auth/spreadsheets'\nCLIENT_SECRET_FILE = 'client_secret.json'\nAPPLICATION_NAME = 'Google Sheets API Python Quickstart'\nspreadsheetId = \"1EXPrM5N9viB-1ZMy7Vlc9FsLVfpq3PHyb7wQb_XjB08\"\nservice = 0;\nserviceInited = False\nconfigDict = {}\nUPDATE_ROW = 'F'\n\ndef get_credentials():\n \"\"\"Gets valid user credentials from storage.\n\n If nothing has been stored, or if the stored credentials are invalid,\n the OAuth2 flow is completed to obtain the new credentials.\n\n Returns:\n Credentials, the obtained credential.\n \"\"\"\n home_dir = os.path.expanduser('~')\n credential_dir = os.path.join(home_dir, '.credentials')\n if not os.path.exists(credential_dir):\n os.makedirs(credential_dir)\n credential_path = os.path.join(credential_dir,\n 'sheets.googleapis.com-python-quickstart.json')\n\n store = Storage(credential_path)\n credentials = store.get()\n if not credentials or credentials.invalid:\n flow = client.flow_from_clientsecrets(CLIENT_SECRET_FILE, SCOPES)\n flow.user_agent = APPLICATION_NAME\n if flags:\n credentials = tools.run_flow(flow, store, flags)\n else: # Needed only for compatibility with Python 2.6\n credentials = tools.run(flow, store)\n print('Storing credentials to ' + credential_path)\n return credentials\n\ndef Service():\n global service\n global serviceInited\n if serviceInited:\n return service\n credentials = get_credentials()\n http = credentials.authorize(httplib2.Http())\n discoveryUrl = ('https://sheets.googleapis.com/$discovery/rest?'\n 'version=v4')\n\n service = discovery.build('sheets', 'v4', http=http,\n discoveryServiceUrl=discoveryUrl)\n serviceInited = True;\n return service\n\ndef main():\n \"\"\"Shows basic usage of the Sheets API.\n\n Creates a Sheets API service object and prints the names and majors of\n students in a sample spreadsheet:\n https://docs.google.com/spreadsheets/d/1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgvE2upms/edit\n \"\"\"\n rangeName = 'testSheet!A3:B'\n result = Service().spreadsheets().values().get(\n spreadsheetId=spreadsheetId, range=rangeName).execute()\n values = result.get('values', [])\n valuesNew = len(values)*[None]\n print(len(values))\n if not values:\n print('No data found.')\n else:\n print('Item, Price:')\n x = 0\n for row in values:\n # Print columns A and E, which correspond to indices 0 and 4.\n if(len(row) >= 2):\n print('%s, %s' % (row[0], row[1] or \"-\"))\n #if(not row[1]):\n valuesNew[x] = [randint(0,20)]\n print(valuesNew[x])\n x = x + 1\n body = {\n 'values': valuesNew\n }\n range_name = 'testSheet!B3:B'\n result = Service().spreadsheets().values().update(\n spreadsheetId=spreadsheetId, range=range_name, valueInputOption='RAW',\n body=body).execute()\n print(\"updated google sheet\")\n\ndef getListOfItemsFromSheet(sheetName):\n rangeName = sheetName+\"!A3:A\"\n result = Service().spreadsheets().values().get(\n spreadsheetId=spreadsheetId, range=rangeName).execute()\n values = result.get('values', [])\n items = []\n for row in values: #make a 1D array, and remove white spaces\n try:\n if(row[0]):\n items.append(row[0])\n except IndexError:\n continue\n print(items)\n return items\n\ndef getConfigValues():\n global configDict\n if(configDict != {}): #if already initialized, just return it\n return configDict\n rangeName = 'ConfigValues!A1:B'\n result = Service().spreadsheets().values().get(\n spreadsheetId=spreadsheetId, range=rangeName).execute()\n values = result.get('values', [])\n for row in values:\n try:\n configDict[row[0]] = row[1]\n except IndexError:\n try:\n configDict[row[0]] = \"\"\n except IndexError:\n continue\n return configDict\n\ndef getSheets():\n sheets = getConfigValues()[\"sheetsToScan\"].split(',')\n print(sheets)\n return sheets\n\ndef saveListToSheet(listOfValues, sheetID=\"testSheet\"):\n valuess = len(listOfValues)*[None]\n x = 0\n for value in listOfValues:\n print (value)\n valuess[x] = [value]\n x += 1\n\n print(listOfValues)\n body = {\n 'values': valuess\n }\n range_name = sheetID+'!B3:B'\n result = Service().spreadsheets().values().update(\n spreadsheetId=spreadsheetId, range=range_name, valueInputOption='RAW',\n body=body).execute()\n updateLastUpdatedBlock(valuess, sheetID)\n print(\"updated\")\n\ndef updateLastUpdatedBlock(values, sheetID):\n range_name = sheetID+'!'+UPDATE_ROW+'3:'+UPDATE_ROW\n x = 0\n for value in values:\n if(value and value != 0):\n values[x] = [datetime.datetime.now().strftime(\"%m-%d %H:%M:%S\")]\n else:\n values[x] = [None]\n x = x+1\n body = {\n 'values': values\n }\n result = Service().spreadsheets().values().update(\n spreadsheetId=spreadsheetId, range=range_name, valueInputOption='RAW',\n body=body).execute()\n\nif __name__ == '__main__':\n main()","sub_path":"googleInteractions.py","file_name":"googleInteractions.py","file_ext":"py","file_size_in_byte":5841,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"119329738","text":"from util import *\n\ndef main():\n r = reader(\"input\")\n num = int(r.next())\n ans = []\n for i in range(num):\n X, R, C = map(int, r.next().split(\" \"))\n if checkVals(X, R, C):\n ans.append(\"GABRIEL\")\n else:\n ans.append(\"RICHARD\")\n\n write(\"output\", ans)\n\ndef checkVals(x, w, h):\n if x >= 7:\n return False\n if x > w and x > h:\n return False\n if (x + 1)/2 > w or (x + 1)/2 > h:\n return False\n if w * h % x != 0:\n return False\n if x == 1 or x == 2 or x == 3:\n return True\n if x == 4:\n if 3 > w or 3 > h:\n return False\n else:\n return True\n return True\n\nif __name__ == '__main__':\n main()\n","sub_path":"solutions_5658571765186560_0/Python/ReneZ/nominos.py","file_name":"nominos.py","file_ext":"py","file_size_in_byte":730,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"231850522","text":"import random\n\n\nclass Item(object):\n def __init__(self, name, description, location=None):\n self.name = name\n self.description = description\n self.location = location\n\n\nclass Equipment(Item):\n def __init__(self, name, description, location, weight, condition='NEW'):\n super(Equipment, self).__init__(name, description, location)\n self.weight = weight\n self.condition = condition\n\n\nclass Armour(Equipment):\n def __init__(self, name, description, location, weight, protection: int, material, blessing):\n super(Armour, self).__init__(name, description, location, weight)\n self.protection = protection # This attribute follows percentages\n self.material = material\n self.blessing = blessing # The enchantment or buff that the armour piece has.\n\n\nclass Headgear(Armour):\n def __init__(self, name, description, location, protection, material, blessing):\n super(Headgear, self).__init__(name, description, location, 'MODERATE', protection, material, blessing)\n self.is_a = 'HEADGEAR'\n\n\nclass Gelmet(Headgear): # INSTANTIABLE Generic Helmet\n def __init__(self, location, protection, material):\n super(Gelmet, self).__init__(\"Generic Helmet\", \"Just a regular helmet\", location, protection,\n material, None\n )\n\n\nclass Kinghelm(Headgear): # INSTANTIABLE King's Helmet\n def __init__(self, location, imprint):\n super(Kinghelm, self).__init__(\"A King's Helmet\", \"The helmet of which a king would wear.\", location, 50,\n 'MAGIC_GOLD', 'HONOR STATUS')\n self.imprint = imprint # Of whom's soul does this Helmet feel of?\n\n\nclass Torso(Armour):\n def __init__(self, name, description, location, protection, material, blessing):\n super(Torso, self).__init__(name, description, location, 'MODERATE', protection, material, blessing)\n self.is_a = 'TORSO'\n\n\nclass Gorso(Torso): # INSTANTIABLE Generic Torso\n def __init__(self, location, protection, material):\n super(Gorso, self).__init__(\"Generic Torso Armor\", \"Just your everyday armor\", location, protection, material,\n None)\n\n\nclass Footwear(Armour):\n def __init__(self, name, description, location, protection, material, blessing):\n super(Footwear, self).__init__(name, description, location, 'MODERATE', protection, material, blessing)\n self.is_a = 'FOOTWEAR'\n\n\nclass Gboots(Footwear): # INSTANTIABLE Generic Boots\n def __init__(self, location, protection, material):\n super(Gboots, self).__init__(\"Generic Boots\", \"Just a pair of boots\", location, protection, material, None)\n\n\nclass Pat(Equipment): # INSTANTIABLE Pat >>> Pan or Pot\n def __init__(self, name, description, location, kind, contents='EMPTY'):\n super(Pat, self).__init__(name, description, location, 'MODERATE')\n self.kind = kind\n self.contents = contents\n\n\nclass Carrier(Equipment):\n def __init__(self, name, description, location, weight, kind, tag_type, contents):\n super(Carrier, self).__init__(name, description, location, weight)\n self.kind = kind\n self.owned = False\n self.owner = \"\"\n self.tag_type = tag_type # If it's a drink, it's a drawn-on label. If it's a bag, it's a tag.\n self.contents = contents\n\n\nclass Generic(Carrier): # INSTANTIABLE Generic Carrier Bag\n def __init__(self, name, description, location, weight, contents=None):\n super(Generic, self).__init__(name, description, location, weight, 'THINGS', 'TAG', contents)\n self.contents = [contents]\n\n\nclass Thermos(Carrier): # INSTANTIABLE Thermos\n def __init__(self, location, contents, fill=0, color=\"purple\"):\n super(Thermos, self).__init__(\"Thermos\", \"A cup meant to hold liquids, hot or cold.\", location,\n 'LIGHT', 'LIQUIDS', 'LABEL', contents)\n self.fill = fill # %0 is Empty, %100 is Filled\n self.color = color\n\n\nclass Bottle(Carrier): # INSTANTIABLE Bottle (You can throw it)\n def __init__(self, location, material, contents='WATER'):\n super(Bottle, self).__init__(\"Thermos\", \"A bottle.\", location,\n 'LIGHT', 'LIQUIDS', 'LABEL', contents)\n self.material = material # PLASTIC OR GLASS\n\n\nclass Mallobarrel(Equipment): # INSTANTIABLE Mallobarrel\n def __init__(self, location=None, max_mallows=100, marshmallows=100):\n super(Mallobarrel, self).__init__(\"Marshooter Barrel\", \"The barrel of a Rapid-Fire Marshooter gun\", location,\n \"LIGHT\")\n self.marshmallows = marshmallows # Maximum mallows you can load\n self.max_mallows = max_mallows # Amount of marshmallows loaded\n\n def count_mallows(self):\n print(\"In this barrel is...\")\n print(\"%s marshmallows\" % self.marshmallows)\n print(\"This current barrel holds %s marshmallows\" % self.max_mallows)\n\n\nclass Tool(Equipment): # INSTANTIABLE Tool\n def __init__(self, name, description, location, material, head):\n super(Tool, self).__init__(name, description, location, 'MODERATE')\n self.material = material\n self.head = head # Axe, Knife, Shovel, Pick-axe, Hammer\n self.is_a = 'TOOL'\n\n\nclass Weapon(Equipment):\n def __init__(self, name, description, location, weight, attack_power: int, reach):\n super(Weapon, self).__init__(name, description, location, weight)\n self.attack_power = attack_power\n self.range_or_reach = reach\n self.is_a = 'WEAPON'\n\n\nregular_barrel = Mallobarrel()\n\n\nclass Marshooter(Weapon): # INSTANTIABLE Marshmallow Shooter\n def __init__(self, location, barrel=regular_barrel): # Trying to link mallobarrel to marshooter\n super(Marshooter, self).__init__(\"Rapid-Fire Marshmallow Shooter\", \"It's so fast, most enemies can't handle it!\"\n \"\", location, 'LIGHT', 20, 'FAR')\n self.barrel = barrel\n\n\nclass Standard(Weapon): # INSTANTIABLE Generic Weapon\n def __init__(self, name, description, location, kind):\n super(Standard, self).__init__(name, description, location, 'MODERATE', 70, 'DEFAULT')\n self.kind = kind # \"MELEE\" or \"RANGED\"\n\n\nclass Maxe(Weapon): # INSTANTIABLE Magical War axe (Maxe..M-axe >>> Magic-Axe)\n def __init__(self, location, imprint, curse):\n super(Maxe, self).__init__(\"Magical Marble War Axe\", \"A lovely polished war axe made of marble, purple designs \"\n \"painted on it like a vase...and enchanted like a curse.\",\n location, 'MODERATE', 200, 'EXTENDED')\n self.imprint = imprint # You can claim the weapon as your own and you shall be able to summon it at will\n self.curse = curse # You can set a curse you want to use on your enemies\n\n\nclass Ord(Weapon): # INSTANTIABLE Obsidian Sword (Ord >>> Obsidian-Sword)\n def __init__(self, location, mode):\n super(Ord, self).__init__(\"Obsidian Sword\", \"A shiny black sword made of obsidian...it can either be set aflame\"\n \" or emit a steam of which can hide you.\", location, 'MODERATE',\n 200, 'EXTENDED')\n self.mode = mode # Fire or Steam\n\n\nclass Oblet(Weapon): # INSTANTIABLE Obliteration Mallet (Oblet >>> Obliteration-mallet)\n def __init__(self, location, charge='TEDDY BEAR'):\n super(Oblet, self).__init__(\"Obliteration Mallet\", \"A mallet lined with gold. You must hit things to charge it.\"\n \"\", location, 'HEAVY', 200, 'EXTENDED')\n self.charge = charge # Level of Impact\n\n\nclass Sow(Weapon): # INSTANTIABLE Sky Bow (Sow >>> Sky-Bow)\n def __init__(self, location):\n super(Sow, self).__init__(\"Sky Bow\", \"A blue bow that feels like cloud to the touch. It's string is like that \"\n \"of a harp, except it can shoot arrows made of the mist in thin air\",\n location, 'FEATHER', 200, 'SKY')\n self.sting = True # No string, no service.\n\n\n# Instantiated items\nother_helm = Gelmet(None, 20, 'IRON')\n\ncool_torso = Gorso(None, 20, 'IRON')\n\nboots = Gboots(None, 5, 'LEATHER')\n\npan = Pat(\"A pan\", \"A regular frying pan.\", None, 'PAN')\n\nbag = Generic(\"Regular Bag\", \"A black bag...it is empty.\", None, 'LIGHT')\n\ncup = Thermos(None, None)\nprint(cup.description)\n\nwater_bottle = Bottle(None, \"PLASTIC\", \"WATER\")\nprint(water_bottle.description)\n\nanother_mallobarrel = Mallobarrel(None, 200, 100)\n\nsword = Standard(\"Some sword.\", \"Just a generic sword thing.\", \"INSERT ROOM HERE\", 'MELEE')\n\nmarsh = Marshooter(None, Mallobarrel(None, 100, 100))\n\ngood_sword = Ord(None, 'FIRE')\n\naxe = Tool(\"Regular axe\", \"Just some axe.\", None, 'STONE', 'AXE')\n\nclassic_sword = Standard(\"Classic Sword.\", \"Made of sword materials.\", None, 'MELEE')\n\nmagic_axe = Maxe(None, None, 'BAD_LUCK')\n\nobsidian_sword = Ord(None, 'FLAME')\n\nobliteration_mallet = Oblet(None)\n\nsky_bow = Sow(None)\n\nstartup_items = {\n 'WEAPONS': [sword, good_sword, classic_sword, magic_axe, obsidian_sword, obliteration_mallet, sky_bow],\n 'HELMETS': [other_helm],\n 'TORSO PIECES': [],\n 'SHOES': [boots, ]\n}\n\nplayer_name = \"Player\"\n\n\nclass Room(object):\n def __init__(self, name, description, north=None, east=None, south=None, west=None, up=None, down=None, away=None,\n left=None, right=None, back=None, forward=None):\n self.name = name\n self.description = description\n self.north = north\n self.east = east\n self.south = south\n self.west = west\n self.up = up\n self.down = down\n self.away = away\n self.left = left\n self.right = right\n self.back = back\n self.forward = forward\n self.characters = []\n self.stuff = []\n\n\nclass Entity(object):\n def __init__(self, name):\n self.name = name\n\n\nclass Interactive(Entity):\n def __init__(self, name, starting_location, health: int, money: int, weapon, helmet, torso, shoes):\n super(Interactive, self).__init__(name)\n self.current_location = starting_location\n self.health = health\n self.money = money\n self.weapon = weapon\n self.helmet = helmet\n self.torso = torso\n self.shoes = shoes\n self.armor = 0\n self.inventory = []\n\n def move(self, new_location):\n \"\"\"This moves the player to a new room\n\n :param new_location: The room object of which you are going to\n \"\"\"\n self.current_location = new_location\n\n def find_next_room(self, direction):\n \"\"\"This method searches the current room to see if a room exists in that direction\n\n :param direction: The direction that you want to move to\n :return: The Room object if it exists, or None if it does not\n \"\"\"\n name_of_room = getattr(self.current_location, direction) # Option 1 people get to say \"return\"\n return globals()[name_of_room] # Security risk\n\n def calculate_armor(self):\n try:\n self.armor += self.helmet.protection\n except AttributeError or TypeError:\n pass\n try:\n self.armor += self.torso.protection\n except AttributeError or TypeError:\n pass\n try:\n self.armor += self.shoes.protection\n except AttributeError or TypeError:\n pass\n\n def take_damage(self, damage: int, lost=0):\n self.calculate_armor()\n if self.armor > 100:\n print(\"%s's armor negated all the damage.\" % self.name)\n print(\"%s lost %s health\" % self.name, lost)\n else:\n self.health -= (damage*self.armor)/100\n lost = damage - (damage*self.armor)/100\n print(self.name, \" lost \", lost, \" health\")\n\n def attack(self, character_target):\n print(\"Attack! \", self.name, \"hit \", character_target.name, \" for \", self.weapon.attack_power, \" damage.\")\n character_target.take_damage(self.weapon.attack_power)\n\n\nclass Player(Interactive): # ENTITY, ATTACKABLE - PLAYER\n def __init__(self, name, starting_location, health=800, money=50):\n super(Player, self).__init__(name, starting_location, health, money, None, None, None, None)\n\n\nclass Character(Interactive): # ENTITY, ATTACKABLE - NPC\n def __init__(self, name, starting_location, health, money, weapon, helmet, torso, shoes, hostile):\n super(Character, self).__init__(name, starting_location, health, money, weapon, helmet, torso, shoes)\n self.hostile = hostile # True or False\n\n def instantialize_character(self, place):\n self.name = \"Jeff\"\n self.current_location = place\n self.health = random.randint(500, 1000)\n self.money = random.randint(10, 700)\n self.weapon = startup_items['WEAPONS'][random.randint(0, len(startup_items['WEAPONS'])-1)]\n self.helmet = startup_items['HELMETS'][random.randint(0, len(startup_items['HELMETS'])-1)]\n self.torso = startup_items['TORSO PIECES'][random.randint(0, len(startup_items['TORSO PIECES'])-1)]\n self.shoes = startup_items['SHOES'][random.randint(0, len(startup_items['SHOES']) - 1)]\n\n\nclass Guide(Entity): # ENTITY, NON-ATTACKABLE - NPC\n def __init__(self, name, alternative_species=None):\n super(Guide, self).__init__(name)\n self.anthropoid = True\n self.alternative_species = alternative_species\n self.dialogue_tree = {\n }\n\n\nguide = Guide(\"Gabe\")\n\nR19A = Room(\"Mr.Weibe's Room\", \"The classroom you learn in. There are two doors to the north.\", 'parking_lot')\nR19A.stuff = [axe]\nparking_lot = Room(\"The North Parking Lot\", \"There are a couple cars parked here\", 'sidewalk_A1', None, 'R19A', 'car')\ncar = Room(\"Your Cool Red Car\", \"This is the car you drove here in.\", None, 'parking_lot', None, None, None, None,\n 'freeway')\nfreeway = Room(\"On the Freeway\", \"You drove away\", None, None, None, None, None, None, None, 'friend_house', 'home',\n 'car')\nfriend_house = Room(\"Your Friend's House\", \"You have always been welcome here. You came just in time, too. Your friend\"\n \" and their mom are baking cookies.\")\nhome = Room(\"Your warm home\", \"You are back in the safety of your own home. You are sitting down now with a cup of\"\n \" hot chocolate reading your favorite books.\")\nsidewalk_A1 = Room(\"The Sidewalk\", \"...Right next to the Parking Lot.\", 'street_1', 'void_space_right', 'parking_lot',\n 'sidewalk_A2')\nsidewalk_A1.stuff = [obliteration_mallet]\nsidewalk_A2 = Room(\"The Sidewalk\", \"Still the sidewalk, but over here.\", 'street_2', 'sidewalk_A1', 'void_space_lower',\n 'sidewalk_A3')\nsidewalk_A3 = Room(\"The Sidewalk\", \"There's a trapdoor in the sidewalk...\", 'street_3', 'sidewalk_A2', 'trapdoor_drop',\n 'trapdoor_drop', None, 'trapdoor_drop', None, None, None, None, 'trapdoor_drop')\nstreet_1 = Room(\"Street\", \"This is the east-most side of the street. Cars should be driving here.\", 'sidewalk_B1',\n 'void_space_right', 'sidewalk_A1', 'street_2')\nstreet_1.stuff = [magic_axe, other_helm]\nstreet_2 = Room(\"Street\", \"This is the middle of the street.\", 'sidewalk_B2', 'street_1', 'sidewalk_A2', 'street_3')\nstreet_3 = Room(\"Street\", \"This is the west-most side of the street.\", 'sidewalk_B3', 'street_2', 'sidewalk_A3',\n 'street_3')\nsidewalk_B1 = Room(\"The other sidewalk\", \"To the north of the street, north of the parking lot.\", None,\n 'void_space_right', 'street_1', 'sidewalk_B2')\nsidewalk_B2 = Room(\"The other sidewalk\", \"To the north is a disembodied door.\", 'M_door', 'sidewalk_B1', 'street_2',\n 'sidewalk_B3')\nsidewalk_B3 = Room(\"The other sidewalk\", \"To the north is an elegant field, fenced in with stone walls. An elegant \"\n \"statue towers above in the field.\", 'field', 'sidewalk_B2', 'street_3')\nfield = Room(\"Inside the fenced area\", \"The grass beneath your feet is moist and sparkly. To the north is that statue\"\n \" of a pegasus.\", 'shrine_of_deanne', 'grass_patch', 'sidewalk_B3', 'nice_view')\nshrine_of_deanne = Room(\"Statue area\", \"The almighty pegasus stares to you...\", None, 'M_stone', 'field', 'pond')\n\npond = Room(\"Pond and stepping stones\", \"There are a bunch of assorted stones resting in a pond.\", None,\n 'shrine_of_deanne', 'nice_view')\nnice_view = Room(\"Nice view\", \"It's a nice view of the map, despite the fact that it is not up high. You gaze at the \"\n \"street and the room of which you began in this world.\", 'pond', 'field')\nM_stone = Room(\"Grassy field with a stone inscribed with a message\", \"There is a stone that has words engraved in it, \"\n \"saying:'Here stood a hero destined to find the \"\n \"wisdom of which would unlock our free will.\",\n None, None, 'grass_patch', 'shrine_of_deanne')\ngrass_patch = Room(\"Grassy field\", \"You gaze up at the house next to this field. This is the place where you would find\"\n \" something, but the world is not awake at the moment.\", 'M_stone', None, None,\n 'field')\nvoid_space_right = Room(\"VOID SPACE\", \"You stand on nothing, and yet nothing is the void to the right of the street.\",\n 'void_space_upper_corner', 'void_space_right', 'void_space_corner', 'street_1', None, None,\n 'void')\nvoid_space_corner = Room(\"VOID SPACE\", \"You stand on nothing, and yet nothing is the southeast of the world.\",\n 'void_space_right', 'void_space_corner', 'void_space_corner', 'void_space_lower', None, None,\n 'void')\nvoid_space_upper_corner = Room(\"VOID SPACE\", \"You stand on nothing, and yet nothing is the void to the northeast of the\"\n \" world.\", 'void_space_upper_corner', 'void_space_upper_corner',\n 'void_space_right', 'void_space_room_B', 'portal_hall', None, 'void')\nvoid_space_lower = Room(\"VOID SPACE\", \"You stand on nothing, and yet nothing is the void to the south of the south-most\"\n \" sidewalk.\", 'sidewalk_A2', 'void_space_corner', 'void_space_lower',\n 'void_space_room_A', None, None, 'void')\nvoid_space_room_A = Room(\"VOID SPACE ROOM\", \"A comfy little room of nothingness...\", 'void_space_room_B',\n 'void_space_lower', None, None, None, None, 'void')\nvoid_space_room_B = Room(\"VOID SPACE ROOM\", \"A comfy little room of nothingness....\", None, 'void_space_upper_corner',\n 'void_space_room_A', None, None, None, 'void')\nvoid = Room(\"VOID\", \"You wandered away into the deeper darkness and got lost\", None, None, None, None, None, None, None,\n None, None, 'shrine_of_deanne', 'finding_your_way')\nfinding_your_way = Room(\"VOID...\", \"You moved forward with conviction. You feel that you are getting somewhere.\", None,\n None, None, None, None, None, None, None, None, None, 'outside')\noutside = Room(\"Light Area\", \"You stepped out of the darkness into a vast landscape bathed in light. There are patches\"\n \" of darkness everywhere.\", None, None, None, None, None, None, None, None, None, 'R19A')\ntrapdoor_drop = Room(\"Trapdoor Drop Room\",\n \"This is where that trapdoor drops those who fall in. The room is very dark.\", 'M_kitchen')\nM_door = Room(\"Mysterious disembodied door\", \"It's just kind of...there. Nothing in front, nothing behind it.\",\n 'M_hallway', None, 'sidewalk_B2')\nM_hallway = Room(\"Mysterious Hallway\", \"This is strangely spacious for a door frame, isn't it?\", 'M_darkroom')\nM_darkroom = Room(\"A dark welcome room\", \"Who knew there was an actual place through the door?\", 'M_chest_room',\n 'M_bedroom', 'M_hallway', 'M_kitchen')\nM_chest_room = Room(\"Another dark room\", \"There's a locked chest here.\", None, None, 'M_darkroom', 'broken_staircase')\nM_kitchen = Room(\"Mysterious Kitchen\", \"Can you cook? All the pots, pans, and ingredients you'll need are here.\",\n 'broken_staircase', 'M_darkroom')\nbroken_staircase = Room(\"Staircase Up\", \"A long time ago, these stairs collapsed...\", None, 'M_chest_room', 'M_kitchen')\nM_bedroom = Room(\"Someone's bedroom\", \"IT looks as if no one has been here in centuries.\", 'bathroom', 'None',\n 'M_marble', 'M_darkroom')\nbathroom = Room(\"A bathroom.\", \"If you need, you can wash up and use a first-aid kit that was left over.\", None, None,\n 'M_bedroom')\nM_marble = Room(\"Marble Staircase\", \"This staircase, in contrast to the house, looks new and polished. How strange...\",\n 'M_bedroom', 'portal_connection', None, None, 'portal_connection', None, None, None, None, 'M_bedroom',\n 'portal_connection')\nportal_connection = Room(\"Room with a portal\", \"You are standing on a giant glass portal. If you choose to go through\"\n \" it, you will leave this zone...You can't come back after that.\", None, None, None,\n 'M_marble', None, 'portal_hall', 'void', None, None, 'M_marble', 'portal_hall')\nportal_hall = Room(\"Portal of Worlds Hall\", \"Portals, each with a different frame, are lined up on the walls. For now, \"\n \"this is the end of your tour. Quit to escape.\")\n\n\nplayer = Player(\"Player\", R19A) # Eligible for both option 1 and 2\n\n\n# Characters\nshrine_of_deanne.characters = [guide]\nvoid_space_right.characters = [Character(\"Void Wreath\", void_space_right, 1000, 0, None, None, None, None, False)]\n# Stuff\nshrine_of_deanne.stuff = [sky_bow, good_sword]\nM_marble.stuff = [Gorso(\"Chestplate of Honors\", 400, \"DIAMOND\"), Ord(\"Dark Sword of the Flames\", \"FLAME\")]\nstreet_2.stuff = [Marshooter(\"Marshmallow Shooter Edition1\"), Generic(\"Satchel\", \"A large black satchel\", None, \"LIGHT\",\n [])]\nportal_hall.stuff = [Kinghelm(\"King's helmet\", None)]\n\nequips = [player.weapon, player.helmet, player.torso, player.shoes]\ndirections = ['north', 'east', 'south', 'west', 'up', 'down', 'away', 'left', 'right', 'back', 'forward']\nshort_directions = ['n', 'e', 's', 'w', 'u', 'd', 'ay', 'l', 'r', 'b', 'f']\n\n\ndef set_item_target(string, vicinity):\n thing = None\n for b in range(len(vicinity)):\n if vicinity[b] is not None:\n if vicinity[b].name.lower() in string.lower():\n thing = vicinity[b]\n return thing\n\n\ndef set_character_target(string, vicinity):\n who = None\n for b in range(len(vicinity)):\n if vicinity[b] is not None:\n if vicinity[b].name.lower() in string.lower():\n who = vicinity[b]\n return who\n\n\ndef view_multiple_fields(string, fields: []):\n thing = None\n for c in range(len(fields)):\n thing = set_item_target(string, fields[c])\n return thing\n\n\ndef unequip(string):\n if player.weapon is not None:\n if player.weapon.name.lower() in string.lower():\n player.inventory.append(player.weapon)\n player.weapon = None\n print(\"You unequipped your weapon.\")\n elif player.helmet is not None:\n if player.helmet.name.lower() in string.lower():\n player.inventory.append(player.helmet)\n player.helmet = None\n print(\"You unequipped your headgear.\")\n elif player.torso is not None:\n if player.torso.name.lower() in string.lower():\n player.inventory.append(player.torso)\n player.torso = None\n print(\"You unequipped your armor.\")\n elif player.shoes is not None:\n if player.shoes.name.lower() in string.lower():\n player.inventory.append(player.shoes)\n player.shoes = None\n print(\"You unequipped your shoes.\")\n else:\n print(\"You do not seem to have this item equipped.\")\n\n\ndef equip(target):\n if type(target) is Weapon:\n if player.weapon is not None:\n unequip(player.weapon.name)\n player.weapon = target\n print(\"You now have\", target.name, \"equipped as your weapon.\")\n if target in player.current_location.stuff:\n player.current_location.stuff.remove(target)\n else:\n player.inventory.remove(target)\n elif type(target) is Tool:\n if player.weapon is not None:\n unequip(player.weapon.name)\n player.weapon = target\n print(\"You now have\", target.name, \"equipped as your weapon.\")\n if target in player.current_location.stuff:\n player.current_location.stuff.remove(target)\n else:\n player.inventory.remove(target)\n elif type(target) is Headgear:\n if player.helmet is not None:\n unequip(player.helmet.name)\n player.helmet = target\n print(\"You now have\", target.name, \"equipped as your helmet.\")\n if target in player.current_location.stuff:\n player.current_location.stuff.remove(target)\n else:\n player.inventory.remove(target)\n elif type(target) is Torso:\n if player.torso is not None:\n unequip(player.torso.name)\n player.torso = target\n print(\"You now have\", target.name, \"equipped as your armor.\")\n if target in player.current_location.stuff:\n player.current_location.stuff.remove(target)\n else:\n player.inventory.remove(target)\n elif type(target) is Footwear:\n if player.shoes is not None:\n unequip(player.shoes.name)\n player.shoes = target\n print(\"You now have \", target.name, \" equipped as your shoes.\")\n if target in player.current_location.stuff:\n player.current_location.stuff.remove(target)\n else:\n player.inventory.remove(target)\n else:\n print(target.name, \" isn't something you can equip.\")\n\n\nplaying = True\nwhile playing: # Controller\n print()\n print(player.current_location.name)\n print(player.current_location.description)\n if 2 > len(player.current_location.characters) > 0:\n print()\n print(\">>>%s is here.\" % player.current_location.characters[0].name)\n elif len(player.current_location.characters) >= 2:\n pass\n if len(player.current_location.stuff) == 1:\n print(\"In this area there is a/an\", player.current_location.stuff[0].name)\n elif len(player.current_location.stuff) > 1:\n things = []\n for i in range(len(player.current_location.stuff)):\n things.append(player.current_location.stuff[i].name)\n things = \", \".join(things)\n print(\"In this area there is %s\" % things)\n else:\n pass\n command = input(\">_\")\n if command.lower() in ['q', 'quit', 'exit', 'goodbye']: # QUIT GAME\n playing = False\n print(\"%s left the game\" % player_name)\n elif command.lower() in directions:\n try:\n next_room = player.find_next_room(command)\n player.move(next_room)\n except KeyError:\n print(\"You can't go that way\")\n elif command.lower() in short_directions:\n pos = short_directions.index(command.lower())\n command = directions [pos]\n elif \"inventory\" in command.lower():\n print(\"Your inventory...\")\n if len(player.inventory) > 1:\n inventory = []\n for i in range(len(player.inventory)):\n inventory.append(player.inventory[i].name)\n inventory = \", \".join(inventory)\n print(\"You have...\", inventory)\n elif len(player.inventory) > 0:\n print(\"You have a/an\", player.inventory[0].name)\n else:\n print(\"You have nothing.\")\n elif \"unequip\" in command.lower() or \"take off\" in command.lower():\n unequip(command.lower())\n elif \"pick up\" in command.lower() or \"take\" in command.lower() or \"get\" in command.lower():\n item_target = set_item_target(command.lower(), player.current_location.stuff)\n if item_target is not None:\n player.inventory.append(item_target)\n player.current_location.stuff.remove(item_target)\n print(\"You took a thing.\")\n else:\n print(\"There's nothing here of that name you can pick up.\")\n elif \"drop\" in command.lower() or \"leave\" in command.lower():\n item_target = set_item_target(command.lower(), player.inventory)\n if item_target is not None:\n player.current_location.stuff.append(item_target)\n player.inventory.remove(item_target)\n else:\n print(\"There's nothing in your inventory or that name.\")\n elif \"examine\" in command.lower() or \"look at\" in command.lower() or \"observe\" in command.lower(): # Examine\n item_target = view_multiple_fields(command.lower(), [player.inventory, player.current_location.stuff])\n if item_target is not None:\n print(item_target.name, \"...\")\n print(item_target.description)\n else:\n print(\"There doesn't seem to be anything in your inventory or this room by that name.\")\n elif \"equip\" in command.lower() or \"put on\" in command.lower() or \"wear\" in command.lower():\n item_target = set_item_target(command.lower(), player.inventory)\n if item_target is None:\n item_target = set_item_target(command.lower(), player.current_location.stuff)\n if item_target is not None:\n equip(item_target)\n else:\n print(\"There doesn't seem to be anything here by that name you can equip.\")\n elif \"attack\" in command.lower() or \"hit\" in command.lower():\n target = set_character_target(command.lower(), player.current_location.characters)\n player.attack(target)\n\n else:\n print(\"Command Not Found...\")\n print()\n print(\"---\" * 9)\n","sub_path":"GABRIELLA - ADVENTURE GAME/Gabriella - Game_Draft_Demo.py","file_name":"Gabriella - Game_Draft_Demo.py","file_ext":"py","file_size_in_byte":30386,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"217084849","text":"# getting false positives in vscode\nfrom pyspark.sql import SparkSession # pylint: disable=no-name-in-module,import-error\nfrom pyspark.rdd import RDD # pylint: disable=no-name-in-module,import-error\n\nfrom dagster import (\n Bool,\n Dict,\n Field,\n Selector,\n Path,\n String,\n as_dagster_type,\n check,\n input_selector_schema,\n output_selector_schema,\n resource,\n)\nfrom dagster.core.types.runtime import define_any_type\n\nfrom dagster_spark.configs_spark import spark_config\n\nfrom dagster_spark.utils import flatten_dict\n\n\n@input_selector_schema(\n Selector(\n {\n 'csv': Field(\n Dict(\n {\n 'path': Field(Path),\n 'sep': Field(String, is_optional=True),\n 'header': Field(Bool, is_optional=True),\n }\n )\n )\n }\n )\n)\ndef load_rdd(context, file_type, file_options):\n if file_type == 'csv':\n return context.resources.spark.read.csv(\n file_options['path'], sep=file_options.get('sep')\n ).rdd\n else:\n check.failed('Unsupported file type: {}'.format(file_type))\n\n\n@output_selector_schema(\n Selector(\n {\n 'csv': Field(\n Dict(\n {\n 'path': Field(Path),\n 'sep': Field(String, is_optional=True),\n 'header': Field(Bool, is_optional=True),\n }\n )\n )\n }\n )\n)\ndef write_rdd(context, file_type, file_options, spark_rdd):\n if file_type == 'csv':\n df = context.resources.spark.createDataFrame(spark_rdd)\n context.log.info('DF: {}'.format(df))\n df.write.csv(\n file_options['path'], header=file_options.get('header'), sep=file_options.get('sep')\n )\n else:\n check.failed('Unsupported file type: {}'.format(file_type))\n\n\nSparkRDD = as_dagster_type(RDD, 'SparkRDD', input_schema=load_rdd, output_schema=write_rdd)\n\n\n@resource(config_field=Field(Dict({'spark_conf': spark_config()})))\ndef spark_session_resource(init_context):\n builder = SparkSession.builder\n flat = flatten_dict(init_context.resource_config['spark_conf'])\n for key, value in flat:\n builder = builder.config(key, value)\n\n spark = builder.getOrCreate()\n try:\n yield spark\n finally:\n spark.stop()\n","sub_path":"python_modules/libraries/dagster-pyspark/dagster_pyspark/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":2444,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"506299426","text":"import pickle\nimport datetime\n\nimport baekjoon\n\n\nclass Database:\n def __init__(self):\n self.db = dict()\n try:\n with open('./data.dat', 'rb') as file:\n self.db = pickle.load(file)\n except IOError or FileNotFoundError as e:\n print(\"Error: db:\", e)\n self.problem_db = dict()\n try:\n with open('./problem_db.dat', 'rb') as file:\n self.problem_db = pickle.load(file)\n except IOError or FileNotFoundError as e:\n print(\"Error: problem_db:\", e)\n\n def close(self):\n with open('./data.dat', 'wb') as file:\n pickle.dump(self.db, file)\n with open('./problem_db.dat', 'wb') as file:\n pickle.dump(self.problem_db, file)\n\n def get_problem_name(self, problem_num):\n if problem_num in self.problem_db:\n return self.problem_db[problem_num]\n else:\n return 'N/A'\n\n def is_already_solved(self, user_id: str, problem_num: list):\n if user_id in self.db:\n return all(i in self.db[user_id]['solved_problem'] for i in problem_num)\n raise KeyError(\"{} is not found\".format(user_id))\n\n # 가장 최신 기록의 벌금 정보\n def get_fine_status(self):\n ret = {}\n for user_id, user_info in self.db.items():\n if user_id == 'last_update':\n continue\n ret[user_id] = {'name': user_info['name'], 'fine': user_info['total_fine'] - user_info['total_paid']}\n return ret\n\n def add_user(self, user_id: str, user_name: str, solved_problem=None, prepaid=0):\n if solved_problem is None:\n solved_problem = []\n if user_id in self.db.keys():\n raise KeyError('{} is already registered'.format(user_id))\n date = datetime.datetime.now().date()\n self.db[user_id] = {'name': user_name, 'solved_problem': {}, 'fine': {}, 'total_fine': 0,\n 'paid': {date: prepaid} if prepaid != 0 else {}, 'total_paid': prepaid, 'unsolved_day': []}\n if isinstance(solved_problem, list):\n self.db[user_id]['solved_problem'] = {problem_num: date for problem_num in solved_problem}\n else:\n raise ValueError('solved_problem must be list or dict, but your type is {}'.format(type(solved_problem)))\n\n def delete_user(self, user_id: str):\n if user_id in self.db:\n del self.db[user_id]\n else:\n raise KeyError(\"{} is not found\".format(user_id))\n\n def update_solved(self, user_id: str, solved: list):\n if user_id not in self.db:\n raise KeyError('{} is not registered'.format(user_id))\n # date = datetime.datetime.now().date()\n # unique_solved = {i: date for i in solved.keys() if i not in self.db[user_id]['solved_problem']}\n # self.db[user_id]['solved_problem'].update(unique_solved)\n unique_solved = dict()\n for row in solved:\n problem_num = row['problem_id']\n problem_name = row['problem_title']\n self.update_problem_name(problem_num, problem_name)\n date = row['submit_date'].date()\n if problem_num in self.db[user_id]['solved_problem']:\n continue\n unique_solved[problem_num] = date\n self.db[user_id]['solved_problem'].update(unique_solved)\n return len(unique_solved)\n # self.update_problem_name(solved)\n\n def update_problem_name(self, problem_num: int, problem_name: str):\n self.problem_db[problem_num] = problem_name\n\n def get_last_update_date(self):\n if 'last_update' in self.db:\n return self.db['last_update']\n raise KeyError('\"last_update\" was not found.')\n\n def calculate_fine(self):\n date = datetime.datetime.now().date()\n prev_day = date - datetime.timedelta(days=1)\n if 'last_update' not in self.db:\n print(\"last_update was not found.\")\n elif self.db['last_update'] == date:\n raise ValueError('already updated fine information.')\n for user_id in self.db:\n if user_id == 'last_update':\n continue\n if date in self.db[user_id]['solved_problem'].values():\n fine = 0\n else:\n if prev_day not in self.db[user_id]['fine']:\n fine = 1000\n else:\n fine = self.db[user_id]['fine'][prev_day] * 2 if self.db[user_id]['fine'][prev_day] != 0 else 1000\n self.db[user_id]['fine'][date] = fine\n self.db[user_id]['total_fine'] += fine\n self.db['last_update'] = date\n\n def get_fine_by_date(self, user_id, start_date, end_date):\n ret = dict()\n fine = self.db[user_id]['fine']\n for k, v in fine.items():\n if start_date <= k <= end_date:\n ret[k] = v\n return ret\n\n def get_solved_problem_by_date(self, user_id, start_date, end_date):\n ret = dict()\n problem = self.db[user_id]['solved_problem']\n for k, v in problem.items():\n if start_date <= v <= end_date:\n ret[k] = {'date': v, 'problem_name': self.get_problem_name(k)}\n return ret\n\n def get_accumulated_fine(self, fine):\n ret = dict()\n fine = sorted(list(fine.items()), key=lambda x: x[0])\n for i in range(len(fine)):\n if i == 0:\n ret[fine[i][0]] = {'fine': fine[i][1], 'acc_fine': fine[i][1]}\n else:\n ret[fine[i][0]] = {'fine': fine[i][1], 'acc_fine': fine[i - 1][1] + fine[i][1]}\n return ret\n\n def get_detail(self, start_date, end_date):\n ret = {'pass': {}, 'non_pass': {}}\n for user_id in self.db:\n if user_id == 'last_update':\n continue\n fine = self.get_fine_by_date(user_id, start_date, end_date)\n problem = self.get_solved_problem_by_date(user_id, start_date, end_date)\n ret['pass'][user_id] = {'name': self.db[user_id]['name'], 'record': problem}\n if [x for x in fine.values() if x != 0]: # 벌금 0\n ret['non_pass'][user_id] = {'name': self.db[user_id]['name'], 'record': self.get_accumulated_fine(fine)}\n return ret\n\n def update_fined(self, user_id, amount):\n if user_id not in self.db:\n raise KeyError(\"{} was not registered.\".format(user_id))\n date = datetime.datetime.now().date()\n if date in self.db[user_id]['paid']:\n self.db[user_id]['paid'][date] += amount\n else:\n self.db[user_id]['paid'][date] = amount\n self.db[user_id]['total_paid'] += amount\n\n\nif __name__ == '__main__':\n db = Database()\n # db.add_user('whdgmawkd', 'test')\n print(db.update_solved('whdgmawkd',\n baekjoon.get_submit_detail('whdgmawkd', datetime.datetime(2018, 11, 20), datetime.datetime(2018, 11, 22))))\n print(db.is_already_solved('whdgmawkd', [1000,1001,1002,1003]))\n db.calculate_fine()\n print(db.get_fine_status())\n print(db.get_detail(datetime.date(2018, 1, 1), datetime.date(2018, 12, 31)))\n print(db.db)\n db.close()\n","sub_path":"database.py","file_name":"database.py","file_ext":"py","file_size_in_byte":7155,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"634266569","text":"#!/usr/bin/env python3\nimport os\nimport sys\nimport requests\nimport base64\nimport json\nimport argparse\nfrom pathlib import Path\nfrom time import sleep\nfrom typing import Any, Dict\n\n\nclass ImgurAPIError(Exception):\n def __init__(self, response):\n self.error = response['data']['error']\n self.status = response['status']\n\nclass ImgurClient:\n MASHAPE_API_ROOT = 'https://imgur-apiv3.p.mashape.com/3/'\n IMGUR_API_ROOT = 'https://api.imgur.com/3/'\n\n def __init__(self, client_id: str, access_token: str = None,\n mashape_key: str = None) -> None:\n s = requests.Session()\n s.headers.update({\n 'Authorization': f'Client-ID {client_id}',\n 'User-agent': f'Album uploader 0.1',\n })\n\n if access_token:\n s.headers.update({ 'Authorization': f'Bearer {access_token}' })\n\n if mashape_key:\n s.headers.update({ 'X-Mashape-Key': mashape_key })\n self.api_root = self.MASHAPE_API_ROOT\n else:\n self.api_root = self.IMGUR_API_ROOT\n\n self.session = s\n\n def upload_album(self, directory, album_id=None):\n if not album_id:\n try:\n album = self._post('album')\n except ImgurAPIError as e:\n print('Unexpected error while creating album:')\n print(e.error)\n sys.exit(1)\n album_id = album['id']\n\n dir_path = Path(directory)\n files = os.listdir(dir_path)\n files.sort()\n n = len(files)\n\n for i, name in enumerate(files, 1):\n path = dir_path.joinpath(name)\n print('\\033[K', end='') # clear line\n print(f'Uploading {path} ({i}/{n})', end='\\r')\n try:\n self.upload_image(path, album=album_id)\n except ImgurAPIError as e:\n print(f\"Unexpected error encountered while uploading '{path}':\")\n print(e.error)\n sys.exit(1)\n print()\n print(f\"Uploading '{dir_path}' complete\")\n print(f'See it at https://imgur.com/a/{album_id}')\n\n def upload_image(self, path, **kwargs):\n data = kwargs\n data['type'] = 'binary'\n\n with path.open('rb') as image:\n files = { 'image': image }\n return self._post('image', data=data, files=files)\n\n def _get(self, endpoint, **kwargs):\n return self._request('get', endpoint, **kwargs)\n\n def _post(self, endpoint, **kwargs):\n return self._request('post', endpoint, **kwargs)\n\n def _request(self, method: str, endpoint: str, **kwargs) -> Dict[str, Any]:\n response = self.session.request(\n method.upper(), self.api_root + endpoint, **kwargs\n )\n\n body = json.loads(response.text)\n if not body['success']:\n raise ImgurAPIError(body)\n\n return body['data']\n\ndef load_env(keys):\n env = {}\n\n secrets_path = Path('secrets.env')\n if secrets_path.is_file():\n with secrets_path.open('r') as secrets:\n for line in secrets:\n key, value = line.strip().split('=')\n env[key] = value\n\n for key in keys:\n value = os.getenv(key)\n if value or not key in env:\n env[key] = value\n\n return env\n\ndef main():\n parser = argparse.ArgumentParser(\n description='Upload collections of images to imgur'\n )\n\n parser.add_argument('directory', help='a directory of images to upload')\n parser.add_argument('-a', '--album',\n help='an album to upload to')\n\n args = parser.parse_args()\n env = load_env(['CLIENT_ID', 'ACCESS_TOKEN', 'MASHAPE_KEY'])\n\n client = ImgurClient(env['CLIENT_ID'], env['ACCESS_TOKEN'],\n env['MASHAPE_KEY'])\n\n album_id = args.album.lstrip('https://imgur.com/a/')\n client.upload_album(args.directory, album_id)\n\nif __name__ == '__main__':\n main()\n","sub_path":"albumupload.py","file_name":"albumupload.py","file_ext":"py","file_size_in_byte":3935,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"353176806","text":"import numpy as np\nimport pandas as pd\n\nimport matplotlib\nimport matplotlib.pyplot as pp\n\nplanets = pd.read_csv(\"./chapter2/02_03/Planets.csv\")\nplanets.head()\nplanets.describe()\nplanets[\"Mass\"]\n\n# Look at first\nplanets.loc[0]\n\n# Set the index\nplanets.set_index(\"Planet\", inplace=True)\n\n# Presents information about the dataframe\nplanets.info()\n\nplanets.loc[\"MERCURY\"]\n\n# .loc accepts ranges (and are inclusive)\nplanets.loc[\"MERCURY\": \"EARTH\"]\n\nplanets.FirstVisited[\"MERCURY\"]\n\nplanets.loc[\"MERCURY\"].FirstVisited\n\nplanets.loc[\"MERCURY\", \"FirstVisited\"]\n\ntype(planets.loc[\"MERCURY\", \"FirstVisited\"])\n\n# Assign the FirstVisited series to now be the datetime version of the string data\nplanets.FirstVisited = pd.to_datetime(planets.FirstVisited)\n\n# the .dt property exists on all datetimes\nplanets.FirstVisited.dt.year\nplanets.FirstVisited.dt.month\n\n# How long has it been since 2019 that each planet was visited?\n2019 - planets.FirstVisited.dt.year\n\n# planets.loc[\"MARS\"].FirstVisited.month - planets.loc[\"MOON\"].FirstVisited.month\ndelta = planets.FirstVisited[\"MARS\"] - planets.FirstVisited[\"MOON\"]\nyears_between_mars_and_moon_landing = delta / np.timedelta64(1, 'Y')\nmonths_between_mars_and_moon_landing = delta / np.timedelta64(1, 'M')\n","sub_path":"pandas_start.py","file_name":"pandas_start.py","file_ext":"py","file_size_in_byte":1237,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"85231398","text":"# 根据和风天气网的api来查询天气信息,只需要输入地点就行。\n# 认证key:6288e7d92be4440c98a4e721b5c5b68e\nimport requests\nimport json\nfrom pprint import pprint\nkey='6288e7d92be4440c98a4e721b5c5b68e'\nurl='https://free-api.heweather.com/s6/weather/now'#实况天气,每小时更新两次\n# url='https://free-api.heweather.com/s6/weather/forecast'#近三天的天气,每天更新三次\n# location=input('please input the location:\\n')\nlocation='洪山,武汉'#要用英文的逗号\nparas=dict(key=key,location=location)\nresponse=requests.get(url,params=paras)\ndata=json.loads(response.text)\npprint(data)\n# pprint(data['HeWeather6'][0]['daily_forecast'],indent=4)\n# for k,v in data.items():\n# print(k,v)\n\n","sub_path":"python/2018f_exe/heweather.py","file_name":"heweather.py","file_ext":"py","file_size_in_byte":734,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"297006117","text":"''' \n@file: run_retrieval.py\n@author: John3Kim\n@desc: Run a retrieval script for Reddit data\n'''\n\nfrom CollectDataFactory import CollectDataFactory\nimport datetime\nimport time\nfrom typing import List\nfrom export_to_json import build_json_file\nimport json\nimport logging\n\n\nlogging.basicConfig(level=logging.DEBUG,\n format=' %(asctime)s - %(levelname)s - %(message)s')\n\ndef make_date_range(start_date:datetime.time, end_date:datetime.time) -> List[str]: \n '''\n Creates a list of date ranges\n\n Arguments:\n start_date: datetime.time -> The start date of the output list\n end_date: datetime.time -> The end date of the output list\n \n Returns: \n List[str] -> A list of strings containing UNIX datetimes from the start_date to the end_date\n '''\n\n time_delta = end_date - start_date \n time_stamps = []\n\n for num_days in range(time_delta.days + 1):\n day = start_date + datetime.timedelta(days=num_days)\n unix_timestamp = str(int(time.mktime(day.timetuple())))\n time_stamps.append(unix_timestamp)\n\n return time_stamps\n\ndef run_reddit_psio_query(query:str, subreddit:str, start_date:datetime.date, end_date:datetime.date) -> None: \n ''' \n Runs a single query for Reddit using pushshift.io as a data source instead of the official \n Reddit API.\n\n Arguments:\n query: str -> The search query that you want to run. You can write a single term \n or combine with the following boolean commands: \n AND, OR, (), NOT\n \n Search terms may be stemmed. e.g. dogs resolves as dog for search.\n\n subreddit:str -> The subreddit, or categories devoted to one topic, that you want to search into.\n start_date: datetime.time -> The start date of the query\n end_date: datetime.time -> The end date of the query\n \n Returns: \n None -> No object returned but we export queries into three separate files\n '''\n \n reddit_historical = CollectDataFactory()\n reddit_historical = reddit_historical.get_data_source('reddit-historical')\n curr_datetime = datetime.datetime.now().strftime(\"%Y-%m-%d\")\n\n date_range = make_date_range(start_date, end_date) \n size_date_range = len(date_range)\n\n for idx in range(size_date_range-1): \n start_date = date_range[idx]\n end_date = date_range[idx+1] \n\n submissions = reddit_historical.get_submissions(query,subreddit,start_date,end_date)\n\n # Export or transfer to DB\n build_json_file(submissions[\"data\"],f\"submissions_{curr_datetime}\")\n\n # Turn subs into list of strings\n subs_id = [submission_id[\"id\"] for submission_id in submissions[\"data\"]]\n\n # Get the comments id from the submissions ids\n for sub_id in subs_id:\n subs_id_to_comm_id = reddit_historical.get_comments_id_from_submissions_id(sub_id)\n # Export or transfer to DB\n build_json_file(subs_id_to_comm_id,f\"submission_id_to_comment_id_{curr_datetime}\")\n\n list_comments_ids = [comment[\"comment_id\"] for comment in subs_id_to_comm_id]\n \n # If we have a single element with N/A, we have no comments and move on to the next id\n if list_comments_ids[0] != \"N/A\":\n comments = reddit_historical.get_comments(list_comments_ids)\n build_json_file(comments[\"data\"], f\"comments_{curr_datetime}\")\n \n\nif __name__ == \"__main__\": \n queries=['covid', 'coronavirus','sars-cov-2']\n subreddits=['Canada', 'CanadaPolitics', 'CanadaCoronavirus', \n 'Vancouver', 'Edmonton', 'Winnipeg', \n 'Montreal', 'Ottawa', 'Saskatoon', \n 'Calgary', 'Toronto', 'Ontario', \"onguardforthee\"]\n\n start_date = datetime.date(2020,1,1)\n end_date = datetime.date(2020,3,30)\n \n for query in queries: \n\n logging.info(f\"Running query: {query}\")\n\n for subreddit in subreddits:\n\n logging.info(f\"Running in subreddit: {subreddit}\")\n\n run_reddit_psio_query(query, subreddit, start_date, end_date)","sub_path":"run_retrieval.py","file_name":"run_retrieval.py","file_ext":"py","file_size_in_byte":4128,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"339208616","text":"import requests\n\n# import json\n\n# Global Variables\nToken = 'Your token'\nallurls = {} # To write urls into a file\nget_server_link = 'https://api.gofile.io/getServer'\nupload_sever_link = 'https://{0}.gofile.io/uploadFile'\n\n\n# gets Account details and prints it:\ndef check_token(token):\n response = requests.get('https://api.gofile.io/getAccountDetails', {'token': token})\n try:\n if response.json()['status'] == 'ok':\n return True\n else:\n return False\n except KeyError:\n return False\n\n\n# Checks for in script token, asks to use it, or ask for a new token:\ndef get_token():\n global Token\n while True:\n answer = input(\"Enter Y to continue with Custom TOKEN or Enter N to continue with GLOBAL token\")\n if answer == \"N\":\n token = Token\n if check_token(token):\n break\n else:\n print(f\"Given token : {token} could be invalid\")\n continue\n if answer == 'Y':\n token = input(\"Enter new token here >>> : \")\n if check_token(token):\n break\n else:\n print(f\"Given token : {token} could be invalid\")\n continue\n return token\n\n\ndef get_server():\n print('Fetching Server...')\n global upload_sever_link\n a = requests.get('https://api.gofile.io/getServer')\n status = a.json()['status']\n if status == 'ok':\n print('Successfully Fetched Server using get_server()')\n server = a.json()['data']['server']\n upload_sever_link = upload_sever_link.format(server)\n return True\n else:\n print('Error in retrieving server try Again')\n return False\n\n\n'''def openfiles():\n filename=''\n filedict={}\n while True:\n filename=input('Enter Name of file to be uploaded : ')\n if filename == '':\n break\n file=open(filename,\"rb\")\n filedict[filename] = file\n file.close()\n return filedict'''\n\n\ndef upload():\n global upload_sever_link\n global allurls\n global Token\n urls = []\n filenamelist = []\n\n while True: # for avaling all files to be uploaded\n filename = input('Enter Name of file to be uploaded : ')\n if filename == '':\n break\n filenamelist.append(filename)\n\n for filename in filenamelist:\n\n try:\n file = open(filename, \"rb\")\n except FileNotFoundError:\n print(filename, 'is not found in current directory')\n continue\n\n filedict = {filename:file}\n print(f'Started uploading {filename}')\n response = requests.post(upload_sever_link, files=filedict, data={'token':Token,'folderId':'c3ee9b9f-df5b-41f0-92e0-419db094c12f','private':True})\n status = response.json()['status']\n print(response.json().items())\n if status == 'ok':\n print(f'succesfully uploaded {filename}')\n else:\n print(f'something went wrong...\\nCouldn\\'t upload {filename}')\n\n urls.append(response.json()['data']['downloadPage'])\n allurls[filename] = response.json()['data']['downloadPage']\n file.close()\n\n return urls\n\n\ndef writeurl():\n try:\n log = open('allurls.txt', 'a')\n except FileNotFoundError:\n print('allurls.txt not found creating new file')\n log = open('allurls.txt', 'w')\n log.close()\n log = open('allurls.txt', 'a')\n for filename, link in allurls.items():\n log.write(filename + ' : ' + link + '\\n')\n log.close()\n return True\n\n\nget_server()\nprint(upload_sever_link)\nprint(upload())\nwriteurl()\n","sub_path":"gofileapi.py","file_name":"gofileapi.py","file_ext":"py","file_size_in_byte":3624,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"151937008","text":"\"\"\"\nСокращатель ссылок\n\"\"\"\nfrom concurrent.futures import ThreadPoolExecutor\nimport os\nimport random\nimport shelve\nimport string\n\nfrom sanic import Sanic\nfrom sanic.exceptions import abort\nfrom sanic.response import redirect, text\n\n\nSITENAME = os.getenv('SITENAME', 'http://127.0.0.1:8080')\nMAX_LENGTH = 5\nBASE_DIR = os.path.abspath('.')\nDB_PATH = os.path.join(BASE_DIR, 'data', 'db')\n\napp = Sanic()\n\n\ndef generate_slug():\n return ''.join(random.choices(string.ascii_letters, k=MAX_LENGTH))\n\n\ndef add_url(url, *, db):\n slug = generate_slug()\n while slug in db:\n slug = generate_slug()\n\n db[slug] = url\n return slug\n\n\n@app.route('/')\nasync def add(request):\n if not request.args.get('url'):\n abort(400, \"Missing 'url' parameter\")\n\n fut = request.app.executor.submit(add_url, request.args['url'][0], db=request.app.db)\n slug = fut.result()\n return text(f'{SITENAME}/{slug}')\n\n\n@app.route('/')\nasync def get(request, slug):\n url = request.app.db.get(slug)\n if not url:\n abort(404, 'Url not found')\n\n return redirect(url, status=301)\n\n\n@app.listener('before_server_start')\nasync def setup_db(app, loop):\n app.db = shelve.open(DB_PATH)\n\n # Многопоточный executor для неблокирующей записи в shelve\n app.executor = ThreadPoolExecutor()\n\n\nif __name__ == '__main__':\n app.run(host='0.0.0.0', port=8080)\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1422,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"106774993","text":"from flask import (\n Blueprint, flash, g, redirect, render_template, request, url_for\n)\nfrom werkzeug.exceptions import abort\nfrom sqlalchemy import text\nfrom booksite.auth import login_required\nfrom booksite.db import get_db\n\nbp = Blueprint('book', __name__)\n\n@bp.route('/book/', methods=['GET', 'POST'])\n@login_required\ndef book(book_id):\n db = get_db()\n\n if request.method == 'POST':\n rating = request.form.get('reviewrating')\n comment = request.form.get('reviewcomment')\n try:\n db.engine.execute(text(\n f\"\"\"INSERT INTO review (rating, comment, book_id, user_id) \n VALUES ({rating}, '{comment}', {book_id}, {g.user['id']})\"\"\"))\n except:\n flash('You have already submitted a review for this book.')\n\n book = db.engine.execute(text('SELECT * FROM book WHERE id = :id'), id=book_id).fetchone()\n if book is None:\n render_template('error.html', message='No such book.')\n reviews = db.engine.execute(text('SELECT * FROM review WHERE book_id = :id'), id=book_id).fetchall()\n average_review = db.engine.execute(text(\n 'SELECT AVG(rating) average_review FROM review WHERE book_id = :id GROUP BY book_id'), id=book_id).fetchone()\n return render_template('books/book.html', book=book, reviews=reviews, average_review=average_review)","sub_path":"Project1/booksite/book.py","file_name":"book.py","file_ext":"py","file_size_in_byte":1359,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"322054515","text":"import pandas as pd\nimport matplotlib.pyplot as plt\n\nplt.rcParams['font.family'] = 'AppleGothic'\n\nwhile True:\n excel_file = 'elec.xlsx'\n df = pd.read_excel(excel_file)\n\n names = df['이름']\n rate = df['득표율']\n colors = ['yellowgreen', 'lightskyblue', 'lightcoral', 'grey']\n explodes = (0.03, 0.03, 0.03, 0.03)\n\n plt.pie(rate,\n labels=names,\n colors=colors,\n autopct='%1.2f%%',\n explode=explodes\n )\n plt.title('20대 선거 득표율', fontsize=20)\n plt.draw()\n plt.pause(10)\n plt.clf()\n","sub_path":"2019-2_visualprogramming/assignment5_1.py","file_name":"assignment5_1.py","file_ext":"py","file_size_in_byte":580,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"20064867","text":"from django.http import HttpResponse\n\nfrom ..models import MyUser as User\n\ndef AddFriendController(request, username):\n try:\n id = request.session['_auth_user_id']\n current_user = User.objects.get(pk=id)\n friend = User.objects.get(username=username)\n current_user.friends.add(friend)\n current_user.save()\n return HttpResponse(status=200)\n except:\n return HttpResponse(status=300)","sub_path":"app/controllers/add_friend.py","file_name":"add_friend.py","file_ext":"py","file_size_in_byte":402,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"56049980","text":"import random as r\r\n\r\nclass Deck:\r\n def __init__(self):\r\n self.new_deck = [1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 6, 6, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 10, 10, 10, 10, 11, 11, 11, 11, 12, 12, 12, 12, 13, 13, 13, 13]\r\n self.deck1 = []\r\n self.deck2 = []\r\n self.p1_card = None\r\n self.p2_card = None\r\n\r\n def deal(self):\r\n r.shuffle(self.new_deck)\r\n self.deck1 = self.new_deck[0:25]\r\n self.deck2 = self.new_deck[26:51]\r\n return self.deck1, self.deck2\r\n\r\n def draw(self):\r\n self.p1_card = self.deck1.pop(1)\r\n self.p2_card = self.deck2.pop(1)\r\n return self.p1_card, self.p2_card\r\n\r\n def war(self):\r\n self.p1_card_facedown = self.deck1.pop(1)\r\n self.p1_card_faceup = self.deck1.pop(1)\r\n self.p2_card_facedown = self.deck2.pop(1)\r\n self.p2_card_faceup = self.deck2.pop(1)\r\n\r\n if self.p1_card_faceup > self.p2_card_faceup:\r\n self.deck1.append(self.p1_card)\r\n self.deck1.append(self.p1_card_facedown)\r\n self.deck1.append(self.p1_card_faceup)\r\n self.deck1.append(self.p2_card)\r\n self.deck1.append(self.p2_card_facedown)\r\n self.deck1.append(self.p2_card_faceup)\r\n elif self.p1_card_faceup < self.p2_card_faceup:\r\n self.deck2.append(self.p1_card)\r\n self.deck2.append(self.p1_card_facedown)\r\n self.deck2.append(self.p1_card_faceup)\r\n self.deck2.append(self.p2_card)\r\n self.deck2.append(self.p2_card_facedown)\r\n self.deck2.append(self.p2_card_faceup)\r\n return self.deck1, self.deck2\r\n\r\n def reveal(self):\r\n if self.p1_card > self.p2_card:\r\n self.deck1.append(self.p1_card)\r\n self.deck1.append(self.p2_card)\r\n elif self.p2_card > self.p1_card:\r\n self.deck2.append(self.p1_card)\r\n self.deck2.append(self.p2_card)\r\n else:\r\n self.war()\r\n return self.deck1, self.deck2\r\n \r\n\r\n","sub_path":"war/war_test.py","file_name":"war_test.py","file_ext":"py","file_size_in_byte":2055,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"231796101","text":"import unittest\nfrom google.appengine.ext import db\n\nimport main\nimport models\nfrom webtest import TestApp\n\nclass AppTest(unittest.TestCase):\n def setUp(self):\n self.app = TestApp(main.application)\n\n def test_index(self):\n response = self.app.get('/')\n self.assertEqual(200, response.status_int)\n\n def tearDown(self):\n del self.app\n\nclass ModelTest(unittest.TestCase):\n def test_entity_creation(self):\n # list of properties to test\n properties = ['title','uri','content','tags']\n\n # some known test value\n val = 'test'\n\n blog_post = models.BlogPost(title=val,\n uri=val,\n content=val,\n tags=list(val), \n )\n \n # need to add capability to test more property types \n for property in properties:\n if isinstance(getattr(blog_post, property), list):\n self.assertEqual(list(val), getattr(blog_post, property))\n else:\n self.assertEqual(val, getattr(blog_post, property))\n\n #blog_comment = models.BlogComment(author='test author')\n #self.assertEqual('test author', blog_comment.author)\n\n def test_entity_save(self):\n blog_post = models.BlogPost(title='test post')\n key = blog_post.put()\n self.assertEqual('test post', db.get(key).title)\n\n blog_comment = models.BlogComment(author='test author')\n key = blog_comment.put()\n self.assertEqual('test author', db.get(key).author)\n","sub_path":"test/test_entities.py","file_name":"test_entities.py","file_ext":"py","file_size_in_byte":1611,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"262849014","text":"from typing import Optional\n\nimport tensorflow as tf\n\nfrom lab import experiment\nfrom lab.logger import tensorboard_writer\n\n\nclass Experiment(experiment.Experiment):\n \"\"\"\n ## Experiment\n\n Each experiment has different configurations or algorithms.\n An experiment can have multiple trials.\n \"\"\"\n\n def __init__(self, *,\n name: str,\n python_file: str,\n comment: str,\n check_repo_dirty: Optional[bool] = None,\n is_log_python_file: Optional[bool] = None):\n \"\"\"\n ### Create the experiment\n\n :param name: name of the experiment\n :param python_file: `__file__` that invokes this. This is stored in\n the experiments list.\n :param comment: a short description of the experiment\n :param check_repo_dirty: whether not to start the experiment if\n there are uncommitted changes.\n\n The experiments log keeps track of `python_file`, `name`, `comment` as\n well as the git commit.\n\n Experiment maintains the locations of checkpoints, logs, etc.\n \"\"\"\n\n super().__init__(name=name,\n python_file=python_file,\n comment=comment,\n check_repo_dirty=check_repo_dirty,\n is_log_python_file=is_log_python_file)\n\n def load_checkpoint(self):\n raise NotImplementedError()\n\n def save_checkpoint(self):\n raise NotImplementedError()\n\n def create_writer(self):\n \"\"\"\n ## Create TensorFlow summary writer\n \"\"\"\n self.logger.add_writer(tensorboard_writer.Writer(\n tf.summary.FileWriter(str(self.info.summary_path))))\n\n def start_train(self, global_step: int):\n \"\"\"\n ## Start experiment\n\n Load a checkpoint or reset based on `global_step`.\n \"\"\"\n\n self.trial.start_step = global_step\n self._start()\n\n if global_step > 0:\n # load checkpoint if we are starting from middle\n with self.logger.section(\"Loading checkpoint\") as m:\n m.is_successful = self.load_checkpoint()\n else:\n # initialize variables and clear summaries if we are starting from scratch\n with self.logger.section(\"Clearing summaries\"):\n self.clear_summaries()\n with self.logger.section(\"Clearing checkpoints\"):\n self.clear_checkpoints()\n\n self.create_writer()\n\n def start_replay(self):\n \"\"\"\n ## Start replaying experiment\n\n Load a checkpoint or reset based on `global_step`.\n \"\"\"\n\n with self.logger.section(\"Loading checkpoint\") as m:\n m.is_successful = self.load_checkpoint()\n","sub_path":"lab/experiment/pytorch.py","file_name":"pytorch.py","file_ext":"py","file_size_in_byte":2763,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"236391698","text":"# -*- coding: utf-8 -*-\n\"\"\"\nAbstract :class:`~sidpy.io.dataset.Dataset` base-class\n\nCreated on Tue Nov 3 15:07:16 2015\n\n@author: Gerd Duscher\n\nModified by Mani Valleti.\n\nLook up dask source code to understand how numerical functions are implemented\n\nstarting code from:\nhttps://scikit-allel.readthedocs.io/en/v0.21.1/_modules/allel/model/dask.html\n\"\"\"\n\nfrom __future__ import division, print_function, absolute_import, unicode_literals\nfrom hashlib import new\nfrom functools import wraps\nfrom re import A\nimport sys\nfrom collections.abc import Iterable, Iterator, Mapping\nimport warnings\n\nimport dask.array.core\nimport numpy as np\nimport matplotlib.pylab as plt\nimport string\nimport dask.array as da\nimport h5py\nfrom enum import Enum\n\nfrom .dimension import Dimension, DimensionType\nfrom ..base.num_utils import get_slope\nfrom ..base.dict_utils import print_nested_dict\nfrom ..viz.dataset_viz import CurveVisualizer, ImageVisualizer, ImageStackVisualizer\nfrom ..viz.dataset_viz import SpectralImageVisualizer, FourDimImageVisualizer\n# from ..hdf.hdf_utils import is_editable_h5\n\n\nclass DataType(Enum):\n UNKNOWN = -1\n SPECTRUM = 1\n LINE_PLOT = 2\n LINE_PLOT_FAMILY = 3\n IMAGE = 4\n IMAGE_MAP = 5\n IMAGE_STACK = 6\n SPECTRAL_IMAGE = 7\n IMAGE_4D = 8\n\n\ndef view_subclass(dask_array, cls):\n \"\"\"\n View a dask Array as an instance of a dask Array sub-class.\n\n Parameters\n ----------\n dask_array\n cls\n\n Returns\n -------\n\n \"\"\"\n \n return cls(dask_array.dask, name=dask_array.name, chunks=dask_array.chunks,\n dtype=dask_array.dtype, shape=dask_array.shape)\n\nclass Dataset(da.Array):\n \"\"\"\n ..autoclass::Dataset\n\n To instantiate from an existing array-like object,\n use :func:`Dataset.from_array` - requires numpy array, list or tuple\n\n This dask array is extended to have the following attributes:\n -data_type: DataTypes ('image', 'image_stack', spectral_image', ...\n -units: str\n -quantity: str what kind of data ('intensity', 'height', ..)\n -title: title of the data set\n -modality: character of data such as 'STM, 'AFM', 'TEM', 'SEM', 'DFT', 'simulation', ..)\n -source: origin of data such as acquisition instrument ('Nion US100', 'VASP', ..)\n -_axes: dictionary of Dimensions one for each data dimension\n (the axes are dimension datasets with name, label, units,\n and 'dimension_type' attributes).\n\n -metadata: dictionary of additional metadata\n -original_metadata: dictionary of original metadata of file,\n\n -labels: returns labels of all dimensions.\n -data_descriptor: returns a label for the colorbar in matplotlib and such\n\n functions:\n -from_array(data, title): constructs the dataset form a array like object (numpy array, dask array, ...)\n -like_data(data,title): constructs the dataset form a array like object and copies attributes and\n metadata from parent dataset\n -copy()\n -plot(): plots dataset dependent on data_type and dimension_types.\n -get_extent(): extent to be used with imshow function of matplotlib\n -set_dimension(axis, dimensions): set a Dimension to a specific axis\n -rename_dimension(dimension, name): renames attribute of dimension\n -view_metadata: pretty plot of metadata dictionary\n -view_original_metadata: pretty plot of original_metadata dictionary\n \"\"\"\n\n def __init__(self, *args, **kwargs):\n \"\"\"\n Initializes Dataset object which is essentially a Dask array\n underneath\n\n Attributes\n ----------\n self.quantity : str\n Physical quantity. E.g. - current\n self.units : str\n Physical units. E.g. - amperes\n self.data_type : enum\n Type of data such as Image, Spectrum, Spectral Image etc.\n self.title : str\n Title for Dataset\n self.view : Visualizer\n Instance of class appropriate for visualizing this object\n self.data_descriptor : str\n Description of this dataset\n self.modality : str\n character of data such as 'STM', 'TEM', 'DFT'\n self.source : str\n Source of this dataset. Such as instrument, analysis, etc.?\n self.h5_dataset : h5py.Dataset\n Reference to HDF5 Dataset object from which this Dataset was\n created\n self._axes : dict\n Dictionary of Dimension objects per dimension of the Dataset\n self.meta_data : dict\n Metadata to store relevant additional information for the dataset.\n self.original_metadata : dict\n Metadata from the original source of the dataset. This dictionary\n often contains the vendor-specific metadata or internal attributes\n of the analysis algorithm\n \"\"\"\n # TODO: Consider using python package - pint for quantities\n super(Dataset, self).__init__()\n\n self._units = ''\n self._quantity = ''\n self._title = ''\n self._data_type = DataType.UNKNOWN\n self._modality = ''\n self._source = ''\n\n self._h5_dataset = None\n self._metadata = {}\n self._original_metadata = {}\n self._axes = {}\n\n self.view = None # this will hold the figure and axis reference for a plot\n\n def __repr__(self):\n rep = 'sidpy.Dataset of type {} with:\\n '.format(self.data_type.name)\n rep = rep + super(Dataset, self).__repr__()\n rep = rep + '\\n data contains: {} ({})'.format(self.quantity, self.units)\n rep = rep + '\\n and Dimensions: '\n\n for key in self._axes:\n rep = rep + '\\n'+self._axes[key].__repr__()\n\n if hasattr(self, 'metadata'):\n if len(self.metadata) > 0:\n rep = rep + '\\n with metadata: {}'.format(list(self.metadata.keys()))\n return rep\n\n def hdf_close(self):\n if self.h5_dataset is not None:\n self.h5_dataset.file.close()\n print(self.h5_dataset)\n\n @classmethod\n def from_array(cls, x, title='generic', chunks='auto', lock=False, \n datatype = 'UNKNOWN', units = 'generic', quantity = 'generic', \n modality = 'generic', source = 'source', **kwargs):\n \"\"\"\n Initializes a sidpy dataset from an array-like object (i.e. numpy array)\n All meta-data will be set to be generically.\n\n Parameters\n ----------\n x: array-like object\n the values which will populate this dataset\n chunks: optional integer or list of integers\n the shape of the chunks to be loaded\n title: optional string\n the title of this dataset\n lock: boolean\n\n Returns\n -------\n sidpy dataset\n\n \"\"\"\n\n # create vanilla dask array\n if isinstance(x, da.Array):\n dask_array = x\n else:\n dask_array = da.from_array(np.array(x), chunks=chunks, lock=lock)\n\n # view as sub-class\n sid_dataset = view_subclass(dask_array, cls)\n sid_dataset.data_type = datatype\n sid_dataset.units = units\n sid_dataset.title = title\n sid_dataset.quantity = quantity\n\n sid_dataset.modality = modality\n sid_dataset.source = source\n\n sid_dataset._axes = {}\n for dim in range(sid_dataset.ndim):\n # TODO: add parent to dimension to set attribute if name changes\n sid_dataset.set_dimension(dim,\n Dimension(np.arange(sid_dataset.shape[dim]), string.ascii_lowercase[dim]))\n sid_dataset.metadata = {}\n sid_dataset.original_metadata = {}\n return sid_dataset\n\n def like_data(self, data, title=None, chunks='auto', lock=False, **kwargs):\n \"\"\"\n Returns sidpy.Dataset of new values but with metadata of this dataset\n - if dimension of new dataset is different from this dataset and the scale is linear,\n then this scale will be applied to the new dataset (naming and units will stay the same),\n otherwise the dimension will be generic.\n -Additional functionality to override numeric functions\n Parameters\n ----------\n data: array like\n values of new sidpy dataset\n title: optional string\n title of new sidpy dataset\n chunks: optional list of integers\n size of chunks for dask array\n lock: optional boolean\n for dask array\n\n\n Returns\n -------\n sidpy dataset\n \"\"\"\n title_suffix = kwargs.get('title_suffix', '')\n title_prefix = kwargs.get('title_prefix', '')\n reset_quantity = kwargs.get('reset_quantity', False)\n reset_units = kwargs.get('reset_units', False)\n checkdims = kwargs.get('checkdims', True)\n \n\n new_data = self.from_array(data, chunks=chunks, lock=lock)\n \n new_data.data_type = self.data_type\n \n #units\n if reset_units:\n new_data.units = 'generic'\n else:\n new_data.units = self.units\n \n \n if title is not None:\n new_data.title = title\n else:\n if not(title_prefix and title_suffix):\n new_data.title = self.title\n else:\n new_data.title = self.title + '_new'\n \n new_data.title = title_prefix+new_data.title+title_suffix\n \n #quantity\n if reset_quantity:\n new_data.quantity = 'generic'\n else:\n new_data.quantity = self.quantity\n\n new_data.modality = self.modality\n new_data.source = self.source\n\n if checkdims:\n for dim in range(new_data.ndim):\n # TODO: add parent to dimension to set attribute if name changes\n if len(self._axes[dim].values) == new_data.shape[dim]:\n new_data.set_dimension(dim, self._axes[dim])\n else:\n # assuming the axis scale is equidistant\n try:\n scale = get_slope(self._axes[dim])\n # axis = self._axes[dim].copy()\n axis = Dimension(np.arange(new_data.shape[dim])*scale, self._axes[dim].name)\n axis.quantity = self._axes[dim].quantity\n axis.units = self._axes[dim].units\n axis.dimension_type = self._axes[dim].dimension_type\n\n new_data.set_dimension(dim, axis)\n\n except ValueError:\n print('using generic parameters for dimension ', dim)\n\n new_data.metadata = dict(self.metadata).copy()\n new_data.original_metadata = {}\n return new_data\n\n \n def __reduce_dimensions(self, new_dataset, axes, keepdims = False):\n new_dataset._axes = {}\n if not keepdims:\n i = 0\n for key, dim in self._axes.items():\n new_dim = dim.copy()\n if key not in axes:\n new_dataset.set_dimension(i, new_dim)\n i+=1\n \n if keepdims:\n for key, dim in self._axes.items():\n new_dim = dim.copy()\n if key in axes:\n new_dim = Dimension(np.arange(1), name = new_dim.name,\n quantity = new_dim.quantity, units = new_dim.units,\n dimension_type=new_dim.dimension_type)\n new_dataset.set_dimension(key, new_dim)\n \n return new_dataset\n\n def __rearrange_axes(self, new_dataset, new_order = None):\n \"\"\"Rearranges the dimension order of the current instance\n Parameters:\n new_order: list or tuple of integers\n\n All the dimensions that are not in the new_order are deleted\n \"\"\"\n new_dataset._axes = {}\n\n\n for i,dim in enumerate(new_order):\n new_dataset.set_dimension(i, self._axes[dim])\n \n return new_dataset \n\n def copy(self):\n \"\"\"\n Returns a deep copy of this dataset.\n\n Returns\n -------\n sidpy dataset\n\n \"\"\"\n dataset_copy = Dataset.from_array(self, self.title, self.chunks)\n\n dataset_copy.title = self.title\n dataset_copy.units = self.units\n dataset_copy.quantity = self.quantity\n dataset_copy.data_type = self.data_type\n dataset_copy.modality = self.modality\n dataset_copy.source = self.source\n\n dataset_copy._axes = {}\n for dim in self._axes:\n dataset_copy.set_dimension(dim, self._axes[dim])\n dataset_copy.metadata = dict(self.metadata).copy()\n\n return dataset_copy\n\n def __validate_dim(self, ind, name):\n \"\"\"\n Validates the provided index for a Dimension object\n\n Parameters\n ----------\n ind : int\n Index of the dimension\n\n Raises\n -------\n TypeError : if ind is not an integer\n IndexError : if ind is less than 0 or greater than maximum allowed\n index for Dimension\n \"\"\"\n if not isinstance(ind, int):\n raise TypeError('Dimension must be an integer')\n if (0 > ind) or (ind >= self.ndim):\n raise IndexError('Dimension must be an integer between 0 and {}'\n ''.format(self.ndim-1))\n for key, dim in self._axes.items():\n if key != ind:\n if name == dim.name:\n raise ValueError('name: {} already used, but must be unique'.format(name))\n\n def rename_dimension(self, ind, name):\n \"\"\"\n Renames Dimension at the specified index\n\n Parameters\n ----------\n ind : int\n Index of the dimension\n name : str\n New name for Dimension\n \"\"\"\n self.__validate_dim(ind, name)\n if not isinstance(name, str):\n raise TypeError('New Dimension name must be a string')\n delattr(self, self._axes[ind].name)\n self._axes[ind].name = name\n setattr(self, name, self._axes[ind])\n\n def set_dimension(self, ind, dimension):\n \"\"\"\n sets the dimension for the dataset including new name and updating the axes dictionary\n\n Parameters\n ----------\n ind: int\n Index of dimension\n dimension: sidpy.Dimension\n Dimension object describing this dimension of the Dataset\n\n Returns\n -------\n\n \"\"\"\n if not isinstance(dimension, Dimension):\n raise TypeError('dimension needs to be a sidpy.Dimension object')\n self.__validate_dim(ind, dimension.name)\n # delattr(self, self._axes[ind].name)\n setattr(self, dimension.name, dimension)\n setattr(self, 'dim_{}'.format(ind), dimension)\n self._axes[ind] = dimension\n\n def view_metadata(self):\n \"\"\"\n Prints the metadata to stdout\n\n Returns\n -------\n None\n \"\"\"\n if isinstance(self.metadata, dict):\n print_nested_dict(self.metadata)\n \n def view_original_metadata(self):\n \"\"\"\n Prints the original_metadata dictionary to stdout\n\n Returns\n -------\n None\n \"\"\"\n if isinstance(self.original_metadata, dict):\n print_nested_dict(self.original_metadata)\n\n def plot(self, verbose=False, **kwargs):\n \"\"\"\n Plots the dataset according to the\n - shape of the sidpy Dataset,\n - data_type of the sidpy Dataset and\n - dimension_type of dimensions of sidpy Dataset\n the dimension_type 'spatial' or 'spectral' determines how a dataset is plotted.\n\n Recognized data_types are:\n 1D: any keyword, but 'spectrum' or 'line_plot' are encouraged\n 2D: 'image' or one of ['spectrum_family', 'line_family', 'line_plot_family', 'spectra']\n 3D: 'image', 'image_map', 'image_stack', 'spectrum_image'\n 4D: not implemented yet, but will be similar to spectrum_image.\n\n Parameters\n ----------\n verbose: boolean\n kwargs: dictionary for additional plotting parameters\n additional keywords (besides the matplotlib ones) for plotting are:\n - scale_bar: for images to replace axis with a scale bar inside the image\n\n Returns\n -------\n does not return anything but the view parameter is set with access to figure and axis.\n\n \"\"\"\n\n if verbose:\n print('Shape of dataset is: ', self.shape)\n\n if self.data_type.value < 0:\n raise NameError('Datasets with UNKNOWN data_types cannot be plotted')\n\n if len(self.shape) == 1:\n if verbose:\n print('1D dataset')\n self.view = CurveVisualizer(self)\n plt.show()\n elif len(self.shape) == 2:\n # this can be an image or a set of line_plots\n if verbose:\n print('2D dataset')\n if self.data_type == DataType.IMAGE:\n self.view = ImageVisualizer(self, **kwargs)\n plt.show()\n elif self.data_type.value <= DataType['LINE_PLOT'].value:\n # self.data_type in ['spectrum_family', 'line_family', 'line_plot_family', 'spectra']:\n self.view = CurveVisualizer(self, **kwargs)\n plt.show()\n else:\n raise NotImplementedError('Datasets with data_type {} cannot be plotted, yet.'.format(self.data_type))\n elif len(self.shape) == 3:\n if verbose:\n print('3D dataset')\n if self.data_type == DataType.IMAGE:\n self.view = ImageVisualizer(self, **kwargs)\n plt.show()\n elif self.data_type == DataType.IMAGE_MAP:\n pass\n elif self.data_type == DataType.IMAGE_STACK:\n self.view = ImageStackVisualizer(self, **kwargs)\n plt.show()\n elif self.data_type == DataType.SPECTRAL_IMAGE:\n self.view = SpectralImageVisualizer(self, **kwargs)\n plt.show()\n else:\n raise NotImplementedError('Datasets with data_type {} cannot be plotted, yet.'.format(self.data_type))\n elif len(self.shape) == 4:\n if verbose:\n print('4D dataset')\n if self.data_type == DataType.IMAGE:\n self.view = ImageVisualizer(self, **kwargs)\n plt.show()\n elif self.data_type == DataType.IMAGE_MAP:\n pass\n elif self.data_type == DataType.IMAGE_STACK:\n self.view = ImageStackVisualizer(self, **kwargs)\n plt.show()\n elif self.data_type == DataType.SPECTRAL_IMAGE:\n self.view = SpectralImageVisualizer(self, **kwargs)\n plt.show()\n elif self.data_type == DataType.IMAGE_4D:\n self.view = FourDimImageVisualizer(self, **kwargs)\n plt.show()\n if verbose:\n print('4D dataset')\n else:\n raise NotImplementedError('Datasets with data_type {} cannot be plotted, yet.'.format(self.data_type))\n else:\n raise NotImplementedError('Datasets with data_type {} cannot be plotted, yet.'.format(self.data_type))\n\n def get_extent(self, dimensions):\n \"\"\"\n get image extents as needed i.e. in matplotlib's imshow function.\n This function works for equi- or non-equi spaced axes and is suitable\n for subpixel accuracy of positions\n\n Parameters\n ----------\n dimensions: list of dimensions\n\n Returns\n -------\n list of floats\n \"\"\"\n extent = []\n for ind, dim in enumerate(dimensions):\n temp = self._axes[dim].values\n start = temp[0] - (temp[1] - temp[0])/2\n end = temp[-1] + (temp[-1] - temp[-2])/2\n if ind == 1:\n extent.append(end) # y axis starts on top\n extent.append(start)\n else:\n extent.append(start)\n extent.append(end)\n return extent\n\n def get_dimensions_by_type(self, dims_in):\n \"\"\" get dimension by dimension_type name\n\n Parameters\n ----------\n dims_in: dimension_type/str or list of dimension_types/string\n\n\n Returns\n -------\n dims_out: list of [index, dimension]\n the kind of dimensions specified in input in numerical order of the dataset, not the input!\n \"\"\"\n\n if isinstance(dims_in, (str, DimensionType)):\n dims_in = [dims_in]\n for i in range(len(dims_in)):\n if isinstance(dims_in[i], str):\n dims_in[i] = DimensionType[dims_in[i].upper()]\n dims_out = []\n for dim, axis in self._axes.items():\n if axis.dimension_type in dims_in:\n dims_out.append(dim) # , self._axes[dim]])\n return dims_out\n\n def get_image_dims(self):\n \"\"\"Get all spatial dimensions\"\"\"\n\n image_dims = []\n for dim, axis in self._axes.items():\n if axis.dimension_type == DimensionType.SPATIAL:\n image_dims.append(dim)\n return image_dims\n\n def get_spectrum_dims(self):\n \"\"\"Get all spectral dimensions\"\"\"\n\n image_dims = []\n for dim, axis in self._axes.items():\n if axis.dimension_type == DimensionType.SPECTRAL:\n image_dims.append(dim)\n return image_dims\n\n @property\n def labels(self):\n labels = []\n for key, dim in self._axes.items():\n labels.append('{} ({})'.format(dim.quantity, dim.units))\n return labels\n\n @property\n def title(self):\n return self._title\n\n @title.setter\n def title(self, value):\n if isinstance(value, str):\n self._title = value\n else:\n raise ValueError('title needs to be a string')\n\n @property\n def units(self):\n return self._units\n\n @units.setter\n def units(self, value):\n if isinstance(value, str):\n self._units = value\n else:\n raise ValueError('units needs to be a string')\n\n @property\n def quantity(self):\n return self._quantity\n\n @quantity.setter\n def quantity(self, value):\n if isinstance(value, str):\n self._quantity = value\n else:\n raise ValueError('quantity needs to be a string')\n\n @property\n def data_type(self):\n return self._data_type\n\n @data_type.setter\n def data_type(self, value):\n if isinstance(value, str):\n if value.upper() in DataType._member_names_:\n self._data_type = DataType[value.upper()]\n else:\n self._data_type = DataType.UNKNOWN\n raise Warning('Supported data_types for plotting are only: ', DataType._member_names_)\n\n elif isinstance(value, DataType):\n self._data_type = value\n else:\n raise ValueError('data_type needs to be a string')\n\n @property\n def modality(self):\n return self._modality\n\n @modality.setter\n def modality(self, value):\n if isinstance(value, str):\n self._modality = value\n else:\n raise ValueError('modality needs to be a string')\n\n @property\n def source(self):\n return self._source\n\n @source.setter\n def source(self, value):\n if isinstance(value, str):\n self._source = value\n else:\n raise ValueError('source needs to be a string')\n\n @property\n def h5_dataset(self):\n return self._h5_dataset\n\n @h5_dataset.setter\n def h5_dataset(self, value):\n if isinstance(value, h5py.Dataset):\n self._h5_dataset = value\n elif value is None:\n self.hdf_close()\n else:\n raise ValueError('h5_dataset needs to be a hdf5 Dataset')\n\n @property\n def metadata(self):\n return self._metadata\n\n @metadata.setter\n def metadata(self, value):\n if isinstance(value, dict):\n if sys.getsizeof(value) < 64000:\n self._metadata = value\n else:\n raise ValueError('metadata dictionary too large, please use attributes for '\n 'large additional data sets')\n else:\n raise ValueError('metadata needs to be a python dictionary')\n\n @property\n def original_metadata(self):\n return self._original_metadata\n\n @original_metadata.setter\n def original_metadata(self, value):\n if isinstance(value, dict):\n if sys.getsizeof(value) < 64000:\n self._original_metadata = value\n else:\n raise ValueError('original_metadata dictionary too large, please use attributes for '\n 'large additional data sets')\n else:\n raise ValueError('original_metadata needs to be a python dictionary')\n\n @property\n def data_descriptor(self):\n return '{} ({})'.format(self.quantity, self.units)\n\n def fft(self, dimension_type=None):\n \"\"\" Gets the FFT of a sidpy.Dataset of any size\n\n The data_type of the sidpy.Dataset determines the dimension_type over which the\n fourier transform is performed over, if the dimension_type is not set explicitly.\n\n The fourier transformed dataset is automatically shifted to center of dataset.\n\n Parameters\n ----------\n dimension_type: None, str, or sidpy.DimensionType - optional\n dimension_type over which fourier transform is performed, if None an educated guess will determine\n that from dimensions of sidpy.Dataset\n\n Returns\n -------\n fft_dset: 2D or 3D complex sidpy.Dataset (not tested for higher dimensions)\n 2 or 3 dimensional matrix arranged in the same way as input\n\n Example\n -------\n >> fft_dataset = sidpy_dataset.fft()\n >> fft_dataset.plot()\n \"\"\"\n\n if dimension_type is None:\n # test for data_type of sidpy.Dataset\n if self.data_type.name in ['IMAGE_MAP', 'IMAGE_STACK', 'SPECTRAL_IMAGE', 'IMAGE_4D']:\n dimension_type = self.dim_2.dimension_type\n else:\n dimension_type = self.dim_0.dimension_type\n\n if isinstance(dimension_type, str):\n dimension_type = DimensionType[dimension_type.upper()]\n\n if not isinstance(dimension_type, DimensionType):\n raise TypeError('Could not identify a dimension_type to perform Fourier transform on')\n\n axes = self.get_dimensions_by_type(dimension_type)\n if dimension_type.name in ['SPATIAL', 'RECIPROCAL']:\n if len(axes) != 2:\n raise TypeError('sidpy dataset of type', self.data_type,\n ' has no obvious dimension over which to perform fourier transform, please specify')\n if dimension_type.name == 'SPATIAL':\n new_dimension_type = DimensionType.RECIPROCAL\n else:\n new_dimension_type = DimensionType.SPATIAL\n\n elif dimension_type.name == 'SPECTRAL':\n if len(axes) != 1:\n raise TypeError('sidpy dataset of type', self.data_type,\n ' has no obvious dimension over which to perform fourier transform, please specify')\n new_dimension_type = DimensionType.SPECTRAL\n else:\n raise NotImplementedError('fourier transform not implemented for dimension_type ', dimension_type.name)\n\n fft_transform = np.fft.fftshift(da.fft.fftn(self, axes=axes))\n fft_dset = self.like_data(fft_transform)\n fft_dset.units = 'a.u.'\n fft_dset.modality = 'fft'\n\n units_x = '1/' + self._axes[axes[0]].units\n fft_dset.set_dimension(axes[0],\n Dimension(np.fft.fftshift(np.fft.fftfreq(self.shape[axes[0]],\n d=get_slope(self._axes[axes[0]].values))),\n name='u', units=units_x, dimension_type=new_dimension_type,\n quantity='reciprocal'))\n if len(axes) > 1:\n units_y = '1/' + self._axes[axes[1]].units\n fft_dset.set_dimension(axes[1],\n Dimension(np.fft.fftshift(np.fft.fftfreq(self.shape[axes[1]],\n d=get_slope(self._axes[axes[1]].values))),\n name='v', units=units_y, dimension_type=new_dimension_type,\n quantity='reciprocal_length'))\n return fft_dset\n\n # #####################################################\n # Original dask.array functions replaced\n # ##################################################\n\n def __eq__(self, other): # TODO: Test __eq__\n if not isinstance(other, Dataset):\n return False\n # if (self.__array__() == other.__array__()).all():\n if (self.__array__().__eq__(other.__array__())).all():\n if self._units != other._units:\n return False\n if self._quantity != other._quantity:\n return False\n if self._source != other._source:\n return False\n if self._data_type != other._data_type:\n return False\n if self._modality != other._modality:\n return False\n if self._axes != other._axes:\n return False\n return True\n return False\n\n @property\n def T(self):\n return self.transpose()\n\n def abs(self):\n return self.like_data(super().__abs__(), title_suffix = '_absolute_value')\n\n ######################################################\n # Original dask.array functions handed through\n ##################################################\n @property\n def real(self):\n return self.like_data(super().real)\n\n @property\n def imag(self):\n return self.like_data(super().imag)\n\n def reduce_dims(original_method):\n @wraps(original_method)\n def wrapper_method(self, *args, **kwargs):\n result, arguments = original_method(self, *args, **kwargs)\n axis, keepdims = arguments.get('axis'), arguments.get('keepdims', False)\n if axis is None and not(keepdims):\n return result\n if axis is None:\n axes = list(np.arange(self.ndim))\n elif isinstance(axis, int):\n axes = [axis]\n else:\n axes = list(axis)\n \n return self.__reduce_dimensions(result, axes, keepdims)\n \n return wrapper_method\n \n\n @reduce_dims\n def all(self, axis=None, keepdims=False, split_every=None, out=None):\n if axis is None and not(keepdims):\n result = bool(super().all())\n \n else:\n result = self.like_data(super().all(axis = axis, keepdims = keepdims,\n split_every = split_every, out = out), checkdims = False)\n return result, locals().copy()\n\n @reduce_dims\n def any(self, axis=None, keepdims=False, split_every=None, out=None):\n if axis is None and not(keepdims):\n result = bool(super().any())\n \n else:\n result = self.like_data(super().any(axis = axis, keepdims = keepdims,\n split_every = split_every, out = out), checkdims = False)\n return result, locals().copy()\n\n @reduce_dims\n def min(self, axis=None, keepdims=False, split_every=None, out=None):\n if axis is None and not(keepdims):\n result = float(super().min())\n \n else:\n result = self.like_data(super().min(axis = axis, keepdims = keepdims,\n split_every = split_every, out = out), checkdims = False)\n return result, locals().copy()\n \n \n @reduce_dims\n def max(self, axis=None, keepdims=False, split_every=None, out=None):\n if axis is None and not(keepdims):\n result = float(super().max())\n \n else:\n result = self.like_data(super().max(axis = axis, keepdims = keepdims,\n split_every = split_every, out = out), checkdims = False)\n return result, locals().copy()\n\n @reduce_dims\n def sum(self, axis=None, dtype=None, keepdims=False, split_every=None, out=None):\n if axis is None and not(keepdims):\n result = float(super().sum())\n \n else:\n result = self.like_data(super().sum(axis = axis, dtype = dtype, keepdims = keepdims,\n split_every = split_every, out = out), checkdims = False)\n return result, locals().copy()\n \n @reduce_dims\n def mean(self, axis=None, dtype=None, keepdims=False, split_every=None, out=None):\n if axis is None and not(keepdims):\n result = float(super().mean())\n \n else:\n result = self.like_data(super().mean(axis = axis, dtype = dtype, keepdims = keepdims,\n split_every = split_every, out = out), checkdims = False)\n return result, locals().copy()\n \n @reduce_dims\n def std(self, axis=None, dtype=None, keepdims=False, ddof = 0, split_every=None, out=None):\n if axis is None and not(keepdims):\n result = float(super().std())\n \n else:\n result = self.like_data(super().std(axis = axis, dtype = dtype, keepdims = keepdims,\n ddof = 0, split_every = split_every, out = out), checkdims = False)\n return result, locals().copy()\n\n @reduce_dims\n def var(self, axis=None, dtype=None, keepdims=False, ddof = 0, split_every=None, out=None):\n if axis is None and not(keepdims):\n result = float(super().var())\n \n else:\n result = self.like_data(super().var(axis = axis, dtype = dtype, keepdims = keepdims,\n ddof = 0, split_every = split_every, out = out), checkdims = False)\n return result, locals().copy()\n \n @reduce_dims\n def argmin(self, axis=None, split_every=None, out=None):\n if axis is None:\n result = int(super().argmin(axis=axis, split_every=split_every, out=out))\n else:\n result = self.like_data(super().argmin(axis=axis, split_every=split_every, out=out),\n title_suffix = '_argmin_indices', reset_units = True, reset_quantity = True, check_dims = False)\n\n return result, locals().copy()\n \n @reduce_dims\n def argmax(self, axis=None, split_every=None, out=None):\n if axis is None:\n result = int(super().argmax(axis=axis, split_every=split_every, out=out))\n else:\n result = self.like_data(super().argmax(axis=axis, split_every=split_every, out=out),\n title_suffix = '_argmin_indices', reset_units = True, reset_quantity = True, check_dims = False)\n\n return result, locals().copy()\n \n def angle(self, deg = False):\n result = self.like_data(da.angle(self, deg = deg), reset_units = True, \n reset_quantity = True, title_suffix = '_angle', checkdims = True)\n if deg:\n result.units = 'degrees'\n else:\n result.units = 'radians'\n return result\n \n def conj(self):\n return self.like_data(super().conj(), reset_units = True,\n reset_quantity = True, title_suffix = '_conj', checkdims = True)\n\n def astype(self, dtype, **kwargs):\n return self.like_data(super().astype(dtype = dtype, **kwargs))\n\n def flatten(self):\n return self.like_data(super().flatten(), title_suffix = '_raveled',\n check_dims = False)\n \n def ravel(self):\n return self.flatten()\n\n def clip(self, min=None, max=None):\n return self.like_data(super().clip(min = min, max = max),\n reset_quantity = True, title_suffix = '_clipped')\n \n def compute_chunk_sizes(self):\n return self.like_data(super().compute_chunk_sizes())\n \n def cumprod(self, axis, dtype = None, out = None, method = 'sequential'):\n if axis is None:\n self = self.flatten()\n axis = 0\n \n return self.like_data(super().cumprod(axis = axis, dtype=dtype, out=out, \n method=method), title_suffix = '_cumprod', reset_quantity = True)\n \n def cumsum(self, axis, dtype = None, out = None, method = 'sequential'):\n if axis is None:\n self = self.flatten()\n axis = 0\n \n return self.like_data(super().cumsum(axis = axis, dtype=dtype, out=out, \n method=method), title_suffix = '_cumprod', reset_quantity = True)\n \n #What happens to the dimensions??\n def dot(self, other):\n return self.from_array(super().dot(other))\n\n def squeeze(self, axis = None):\n result = self.like_data(super().squeeze(axis = axis), title_prefix = 'Squeezed_',\n checkdims = False)\n if axis is None:\n shape_list = list(self.shape)\n axes = [i for i in range(self.ndim) if shape_list[i]==1]\n elif isinstance(axis, int):\n axes = [axis]\n else:\n axes = list(axis)\n\n return self.__reduce_dimensions(result, axes, keepdims = False)\n \n def swapaxes(self, axis1, axis2):\n result = self.like_data(super().swapaxes(axis1, axis2), \n title_prefix = 'Swapped_axes_', checkdims = False)\n new_order = np.arange(self.ndim)\n new_order[axis1] = axis2\n new_order[axis2] = axis1\n print(new_order)\n return self.__rearrange_axes(result, new_order)\n\n def transpose(self, *axes):\n result = self.like_data(super().transpose(*axes), \n title_prefix = 'Transposed_', checkdims = False)\n if not axes:\n new_axes_order = range(self.ndim)[::-1]\n elif len(axes) == 1 and isinstance(axes[0], Iterable):\n new_axes_order = axes[0]\n else:\n new_axes_order = axes\n return self.__rearrange_axes(result, new_axes_order)\n \n def round(self, decimals = 0):\n return self.like_data(super().round(decimals = decimals),\n title_prefix = 'Rounded_')\n\n def reshape(self, *shape, merge_chunks = True):\n #This somehow adds an extra dimension at the end\n # Will come back to this\n warnings.warn('Dimensional information will be lost.\\\n Please use fold unfold to combine dimensions')\n if len(shape) == 1 and isinstance(shape[0], Iterable):\n new_shape = shape[0]\n else: \n new_shape = shape\n print(new_shape)\n return super().reshape(*new_shape, merge_chunks)\n \n @reduce_dims\n def prod(self, axis=None, dtype=None, keepdims=False, \n split_every=None, out=None):\n if axis is None and not(keepdims):\n result = float(super().prod())\n \n else:\n result = self.like_data(super().prod(axis = axis, dtype = dtype, keepdims = keepdims,\n split_every = split_every, out = out), checkdims = False)\n return result, locals().copy()\n \n @reduce_dims\n def trace(self, offset=0, axis1 = 0, axis2 = 1, dtype=None):\n \n if self.ndim == 2:\n axes = None\n result = float(super().trace(offset = offset))\n \n else:\n axes = [axis1, axis2]\n result = self.like_data(super().trace(offset = offset, axis1 = axis1,\n axis2 = axis2, dtype = None), title_prefix = 'Trace_', checkdims = False)\n local_args = locals().copy()\n local_args['axis'] = axes\n return result, local_args\n\n def repeat(self, repeats, axis = None):\n result = self.like_data(super().repeat(repeats = repeats, axis = axis), \n title_prefix = 'Repeated_', checkdims = False)\n \n result._axes = {}\n for i, dim in self._axes.items():\n if axis != i:\n new_dim = dim.copy()\n else:\n new_dim = Dimension(np.repeat(dim.values, repeats = repeats),\n name=dim.name, quantity=dim.quantity, \n units=dim.units, dimension_type=dim.dimension_type) \n result.set_dimension(i, new_dim)\n \n return result\n \n @reduce_dims\n def moment(self, order, axis=None, dtype=None,\n keepdims=False, ddof=0, split_every=None,\n out=None):\n\n if axis is None and not(keepdims):\n result = float(super().moment(order = order))\n \n else:\n result = self.like_data(super().moment(order = order, \n axis = axis, \n dtype = dtype, keepdims = keepdims,\n ddof = 0, split_every = split_every,\n out = out), checkdims = False)\n return result, locals().copy()\n\n def persist(self, **kwargs):\n return self.like_data(super().persist(**kwargs), \n title_prefix = 'persisted_')\n \n def rechunk(self, chunks, threshold, block_size_limit, balance):\n return self.like_data(super().rechunk(chunks=chunks, \n threshold=threshold, \n block_size_limit=block_size_limit, \n balance=balance), title_prefix = 'Rechunked_')\n\n \n \n \n \n\n\n \n \n\n #Following methods are to be edited\n\n def adjust_axis(self, result, axis, title='', keepdims=False):\n if not keepdims:\n dim = 0\n dataset = self.from_array(result)\n if isinstance(axis, int):\n axis = [axis]\n\n # for ax, dimension in self._axes.items():\n # if int(ax) not in axis:\n # delattr(self, dimension.name)\n # delattr(self, f'dim_{ax}')\n # del self._axes[ax]\n\n for ax, dimension in self._axes.items():\n if int(ax) not in axis:\n dataset.set_dimension(dim, dimension)\n dim += 1\n else:\n dataset = self.like_data(result)\n dataset.title = title + self.title\n dataset.modality = f'sum axis {axis}'\n dataset.quantity = self.quantity\n dataset.source = self.source\n dataset.units = self.units\n\n return dataset\n\n\n\n def choose(self, choices):\n return self.like_data(super().choose(choices))\n \n\n def __abs__(self):\n print(super().__abs__.__name__)\n return self.like_data(super().__abs__(), title_suffix = '_absolute_value')\n\n def __add__(self, other):\n return self.like_data(super().__add__(other))\n\n def __radd__(self, other):\n return self.like_data(super().__radd__(other))\n\n def __and__(self, other):\n return self.like_data(super().__and__(other))\n\n def __rand__(self, other):\n return self.like_data(super().__rand__(other))\n\n def __div__(self, other):\n return self.like_data(super().__div__(other))\n\n def __rdiv__(self, other):\n return self.like_data(super().__rdiv__(other))\n\n def __gt__(self, other):\n return self.like_data(super().__gt__(other))\n\n def __ge__(self, other):\n return self.like_data(super().__ge__(other))\n\n def __invert__(self):\n return self.like_data(super().__invert__())\n\n def __lshift__(self, other):\n return self.like_data(super().__lshift__(other))\n\n def __rlshift__(self, other):\n return self.like_data(super().__rlshift__(other))\n\n def __lt__(self, other):\n return self.like_data(super().__lt__(other))\n\n def __le__(self, other):\n return self.like_data(super().__lt__(other))\n\n def __mod__(self, other):\n return self.like_data(super().__lshift__(other))\n\n def __rmod__(self, other):\n return self.like_data(super().__rmod__(other))\n\n def __mul__(self, other):\n return self.like_data(super().__mul__(other))\n\n def __rmul__(self, other):\n return self.like_data(super().__rmul__(other))\n\n def __ne__(self, other):\n return self.like_data(super().__ne__(other))\n\n def __neg__(self):\n return self.like_data(super().__neg__())\n\n def __or__(self, other):\n return self.like_data(super().__or__(other))\n\n def __ror__(self, other):\n return self.like_data(super().__ror__(other))\n\n def __pos__(self):\n return self.like_data(super().__pos__())\n\n def __pow__(self, other):\n return self.like_data(super().__pow__(other))\n\n def __rpow__(self, other):\n return self.like_data(super().__rpow__(other))\n\n def __rshift__(self, other):\n return self.like_data(super().__rshift__(other))\n\n def __rrshift__(self, other):\n return self.like_data(super().__rrshift__(other))\n\n def __sub__(self, other):\n return self.like_data(super().__sub__(other))\n\n def __rsub__(self, other):\n return self.like_data(super().__rsub__(other))\n\n def __truediv__(self, other):\n return self.like_data(super().__truediv__(other))\n\n def __rtruediv__(self, other):\n return self.like_data(super().__rtruediv__(other))\n\n def __floordiv__(self, other):\n return self.like_data(super().__floordiv__(other))\n\n def __rfloordiv__(self, other):\n return self.like_data(super().__rfloordiv__(other))\n\n def __xor__(self, other):\n return self.like_data(super().__xor__(other))\n\n def __rxor__(self, other):\n return self.like_data(super().__rxor__(other))\n\n def __matmul__(self, other):\n return self.like_data(super().__matmul__(other))\n\n def __rmatmul__(self, other):\n return self.like_data(super().__rmatmul__(other))\n\n\n def __array_ufunc__(self, numpy_ufunc, method, *inputs, **kwargs):\n out = kwargs.get(\"out\", ())\n\n if method == \"__call__\":\n if numpy_ufunc is np.matmul:\n from dask.array.routines import matmul\n\n # special case until apply_gufunc handles optional dimensions\n return self.like_data(matmul(*inputs, **kwargs))\n if numpy_ufunc.signature is not None:\n from dask.array.gufunc import apply_gufunc\n\n return self.like_data(apply_gufunc(\n numpy_ufunc, numpy_ufunc.signature, *inputs, **kwargs))\n if numpy_ufunc.nout > 1:\n from dask.array import ufunc\n\n try:\n da_ufunc = getattr(ufunc, numpy_ufunc.__name__)\n except AttributeError:\n return NotImplemented\n return self.like_data(da_ufunc(*inputs, **kwargs))\n else:\n return self.like_data(dask.array.core.elemwise(numpy_ufunc, *inputs, **kwargs))\n elif method == \"outer\":\n from dask.array import ufunc\n\n try:\n da_ufunc = getattr(ufunc, numpy_ufunc.__name__)\n except AttributeError:\n return NotImplemented\n return self.like_data(da_ufunc.outer(*inputs, **kwargs))\n else:\n return NotImplemented\n\n\n\ndef convert_hyperspy(s):\n \"\"\"\n imports a hyperspy signal object into sidpy.Dataset\n\n Parameters\n ----------\n s: hyperspy dataset\n\n Return\n ------\n dataset: sidpy.Dataset\n \"\"\"\n try:\n import hyperspy.api as hs\n except ModuleNotFoundError:\n raise ModuleNotFoundError(\"Hyperspy is not installed\")\n\n if not isinstance(s, (hs.signals.Signal1D, hs.signals.Signal2D)):\n raise TypeError('This is not a hyperspy signal object')\n dataset = Dataset.from_array(s, name=s.metadata.General.title)\n # Add dimension info\n axes = s.axes_manager.as_dictionary()\n\n if isinstance(s, hs.signals.Signal1D):\n if s.data.ndim < 2:\n dataset.data_type = 'spectrum'\n elif s.data.ndim > 1:\n if s.data.ndim == 2:\n dataset = Dataset.from_array(np.expand_dims(s, 2), title=s.metadata.General.title)\n dataset.set_dimension(2, Dimension([0], name='y', units='pixel',\n quantity='distance', dimension_type='spatial'))\n dataset.data_type = DataType.SPECTRAL_IMAGE\n for key, axis in axes.items():\n if axis['navigate']:\n dimension_type = 'spatial'\n else:\n dimension_type = 'spectral'\n dim_array = np.arange(axis['size']) * axis['scale'] + axis['offset']\n if axis['units'] == '':\n axis['units'] = 'frame'\n dataset.set_dimension(int(key[-1]), Dimension(dim_array, name=axis['name'], units=axis['units'],\n quantity=axis['name'], dimension_type=dimension_type))\n\n elif isinstance(s, hs.signals.Signal2D):\n if s.data.ndim < 4:\n if s.data.ndim == 2:\n dataset.data_type = 'image'\n elif s.data.ndim == 3:\n dataset.data_type = 'image_stack'\n for key, axis in axes.items():\n if axis['navigate']:\n dimension_type = 'temporal'\n else:\n dimension_type = 'spatial'\n dim_array = np.arange(axis['size']) * axis['scale'] + axis['offset']\n if axis['units'] == '':\n axis['units'] = 'pixel'\n dataset.set_dimension(int(key[-1]), Dimension(dim_array, name=axis['name'], units=axis['units'],\n quantity=axis['name'],\n dimension_type=dimension_type))\n elif s.data.ndim == 4:\n dataset.data_type = 'IMAGE_4D'\n for key, axis in axes.items():\n if axis['navigate']:\n dimension_type = 'spatial'\n else:\n dimension_type = 'reciprocal'\n dim_array = np.arange(axis['size']) * axis['scale'] + axis['offset']\n dataset.set_dimension(int(key[-1]), Dimension(dim_array, name=axis['name'], units=axis['units'],\n quantity=axis['name'],\n dimension_type=dimension_type))\n dataset.metadata = dict(s.metadata)\n dataset.original_metadata = dict(s.original_metadata)\n dataset.title = dataset.metadata['General']['title']\n dataset.units = dataset.metadata['Signal']['quantity '].split('(')[-1][:-1]\n dataset.quantity = dataset.metadata['Signal']['quantity '].split('(')[0]\n dataset.source = 'hyperspy'\n return dataset\n","sub_path":"sidpy/sid/dataset.py","file_name":"dataset.py","file_ext":"py","file_size_in_byte":51114,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"177905639","text":"\n# Classes and Objects\n\n# Accessing Object Variables\n\n# You can create multiple different objects that are of the same class(have the same variables and functions defined).\n# However, each object contains independent copies of the variables defined in the class.\n# For instance, if we were to define another object with the \"MyClass\" class and then change the string in the variable above:\n\nclass MyClass:\n variable = \"blah\"\n\n def function(self):\n print(\"This is a message inside the class.\")\n\nmyobjectx = MyClass()\nmyobjecty = MyClass()\n\nmyobjecty.variable = \"yackity\"\n\n# Then print out both values\nprint(myobjectx.variable)\nprint(myobjecty.variable)\n\n# Accessing Object Functions\n\n# To access a function inside of an object you use notation similar to accessing a variable:\n\nclass MyClass:\n variable = \"blah\"\n\n def function(self):\n print(\"This is a message inside the class.\")\n\nmyobjectx = MyClass()\n\nmyobjectx.function()\n\n\n# Exercise\n# We have a class defined for vehicles.\n# Create two new vehicles called car1 and car2.\n# Set car1 to be a red convertible worth $60,000.00 with a name of Fer, and car2 to be a blue van named Jump worth $10,000.00.\n#\n# У нас є клас, визначений для транспортних засобів.\n# Створіть два нових автомобілі під назвою car1 і car2.\n# Встановити car1 бути червоним конвертованим вартістю $ 60,000.00 з ім'ям Fer, а car2 - блакитною ванною на ім'я Jump, вартістю $ 10,000.00.\n\n# define the Vehicle class\nclass Vehicle:\n name = \"\"\n kind = \"car\"\n color = \"\"\n value = 100.00\n def description(self):\n desc_str = \"%s is a %s %s worth $%.2f.\" % (self.name, self.color, self.kind, self.value)\n return desc_str\n# your code goes here\n# car1\ncar1 = Vehicle()\ncar1.name = \"Fer\"\ncar1.kind = \"convertible\"\ncar1.color = \"red\"\ncar1.value = 60000.00\n# car2\ncar2 = Vehicle()\ncar2.name = \"Jump\"\ncar2.kind = \"van\"\ncar2.color = \"blue\"\ncar2.value = 10000.00\n# test code\nprint(car1.description())\nprint(car2.description())","sub_path":"Classes and Objects.py","file_name":"Classes and Objects.py","file_ext":"py","file_size_in_byte":2138,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"454077133","text":"import multiprocessing\nimport argparse\nfrom libnmap.parser import NmapParserException, NmapParser\nfrom IPy import IP\nfrom subprocess import call\nimport time\nimport os\nimport json\nimport fcntl\nimport logging\n\n\nlogging.basicConfig(level=logging.DEBUG,\n format=\"[%(asctime)s %(filename)s(line:%(lineno)d)] %(levelname)s %(message)s\",\n datefmt=\"%Y-%m-%d %H:%M:%S\",\n filename=\"summary.log\",\n filemode='a')\n\nstart_time = time.time()\n\n\ndef handler_result(task_item):\n with open(\"{}.json\".format(time.strftime(\"%Y%m%d%H%M\", time.localtime(int(start_time)))), 'a') as f:\n fcntl.flock(f, fcntl.LOCK_EX)\n f.write(json.dumps(task_item))\n f.write('\\n')\n fcntl.flock(f, fcntl.LOCK_UN)\n\n\ndef work(ips, options):\n temp_file = \"{}.log\".format(' '.join(ips))\n scan_cmd = \"nmap {} -oX {} {}\".format(options, temp_file, ' '.join(ips))\n call(scan_cmd, shell=True)\n\n try:\n result = NmapParser.parse_fromfile(temp_file)\n task_item = {\n \"start_time\": result.started,\n \"end_time\": result.endtime,\n \"elasped\": result.elapsed,\n \"commandline\": result.commandline,\n \"hosts\": [],\n }\n\n for host in result.hosts:\n host_item = {\n \"address\": host.address,\n \"vendor\": host.vendor,\n \"services\": [],\n }\n for service in host.services:\n service_item = {\n \"port\": service.port,\n \"tunnel\": service.tunnel,\n \"protocol\": service.protocol,\n \"state\": service.state,\n \"service\": service.service,\n \"banner\": service.banner,\n }\n host_item[\"services\"].append(service_item)\n task_item[\"hosts\"].append(host_item)\n logging.info(json.dumps(task_item))\n handler_result(task_item)\n if os.path.exists(temp_file):\n os.remove(temp_file)\n except NmapParserException as e:\n # 出错重新扫描\n work(ips, options)\n logging.error(\"Parser error: {}\".format(e.msg))\n\n\ndef do_scan(ip_group, options, thread_number):\n pool = multiprocessing.Pool(processes=thread_number)\n for ips in ip_group:\n pool.apply_async(work, (ips, options))\n pool.close()\n pool.join()\n\n\ndef command_parse():\n parser = argparse.ArgumentParser(description=\"A probe for finding ports and applications\")\n\n parser.add_argument(\"-f\", \"--file\", dest=\"target_file\", nargs='?', required=False,\n help=\"Specify targets from file\")\n parser.add_argument(\"-o\", \"--options\", dest=\"options\", nargs='?', required=False,\n default=\"-n -Pn -sS -sV --host-timeout 600s\",\n help=\"Specify nmap options\")\n parser.add_argument(\"-t\", \"--thread-number\", dest=\"thread_number\", nargs='?', type=int, required=False, default=1,\n help=\"Specify thread number\")\n parser.add_argument(\"-g\", \"--group-count\", dest=\"group_count\", nargs='?', type=int, required=False, default=1)\n return parser.parse_args()\n\n\ndef main():\n\n args = command_parse()\n\n target_file = args.target_file\n group_count = args.group_count\n thread_number = args.thread_number\n options = args.options\n\n # get ip list\n ip_list = []\n with open(target_file, \"r\") as f:\n for line in f.readlines():\n temp_data = line.strip()\n ip_list.extend([ip.strNormal() for ip in IP(temp_data)])\n\n ip_group = [ip_list[i:i+group_count] for i in range(0, len(ip_list), group_count)]\n do_scan(ip_group, options, thread_number)\n\n # count time\n time_cost = time.time() - start_time\n logging.info(\"Time cost: {}.\".format(time_cost))\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"probe.py","file_name":"probe.py","file_ext":"py","file_size_in_byte":3893,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"214475021","text":"# -*- coding: utf-8 -*-\nimport scrapy\nfrom time import sleep\nimport pandas as pd\n\nclass Alibaba_S5(scrapy.Spider):\n name = 'spider5D'\n allowed_domains = ['alibaba.com']\n \n def start_requests(self):\n df = pd.read_csv('/home/swang/scrapy_read/supplier_names_https.csv')\n url_list = df.contacts_url.tolist()\n for url in url_list[150000:200000]: \n yield scrapy.Request(url, callback=self.parse)\n\n def parse(self, response):\n sleep(1)\n contact_url = response.request.url\n contact_name = response.xpath('//div[@class=\"contact-name\"]/text()').extract()\n contact_dept = response.xpath('//div[@class=\"contact-department\"]/text()').extract()\n \n table_rows = response.xpath('//*[contains(@class, \"info-table\")]//tr')\n data = {}\n data['contact_url'] = contact_url\n data['contact_name'] = contact_name\n data['contact_dept'] = contact_dept\n data['Telephone:'] = None\n data['Mobile Phone:'] = None\n data['Fax:'] = None\n \n for table_row in table_rows:\n category = table_row.xpath('th/text()').extract_first()\n if table_row.xpath('td/text()').extract_first() is not None:\n value = table_row.xpath('td/text()').extract_first()\n else:\n value = 0\n data[category] = value\n \n yield data","sub_path":"scrapy_alibaba/spiders/.ipynb_checkpoints/s5-DictStyle-150-200-checkpoint.py","file_name":"s5-DictStyle-150-200-checkpoint.py","file_ext":"py","file_size_in_byte":1419,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"410976833","text":"#-*- coding: UTF-8 -*-\n\nimport pandas as pd\nimport numpy as np\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn import linear_model\nfrom sklearn.metrics import accuracy_score, classification_report\n\niris_path = 'D://ML//LogisticRegression//iris.csv'\ndata = pd.read_csv(iris_path)\nx=data.iloc[:,[1,2,3,4]].values\ny=data.iloc[:,[5]].values\ny=np.where(y=='setosa',1,0)\nx_train,x_test,y_train,y_test=train_test_split(x,y,test_size=0.3,random_state=0)\n\n#数据标准化\nsc = StandardScaler()\nsc.fit(x_train)\nx_train_std = sc.transform(x_train)\nx_test_std = sc.transform(x_test)\n\n\nlogreg = linear_model.LogisticRegression(C=1000.0, random_state=0,solver='lbfgs',multi_class='multinomial')\nlogreg.fit(x_train_std, y_train)\n\nprepro = logreg.predict(x_test_std) #返回属于某一类别\n#prepro=logreg.predict(x_test_std) #返回属于某一类别的概率\n\nprint(classification_report(y_test, prepro)) #类别的区分评估\nprint(prepro)\nprint(logreg.score(x_test_std,y_test))\n","sub_path":"LogisticRegression/LogisticRegression.py","file_name":"LogisticRegression.py","file_ext":"py","file_size_in_byte":1042,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"538363018","text":"import numpy as np\nimport torch\nfrom torch.utils.data import Dataset\nfrom torchvision import transforms\n\nclass Seq_Dataset(Dataset):\n\n def __init__(self,datasets,channel=None,out_frame=1):\n self.datasets = datasets\n self.channel = channel\n self.out_frame = out_frame\n self.total_dataset = []\n \n for dataset in datasets:\n arange = np.arange(len(dataset))\n dset = []\n for i in (arange):\n dset.append(dataset[i])\n self.total_dataset.append(dset)\n\n def __getitem__(self, idx):\n da = self.total_dataset[idx]\n datas = [np.load(d)[:,:,self.channel] for d in da[:-self.out_frame]]\n images = [np.array(data) for data in datas]\n images = np.stack([[image] for image in images])\n images = np.squeeze(images)\n mean = [image.mean() for image in images]\n std = [image.std() for image in images]\n images = images.transpose(1,2,0)\n transform = transforms.Compose([transforms.ToTensor(),transforms.Normalize(mean,std)])\n input_image = transform(images)\n datas = [np.load(d)[:,:,self.channel] for d in da[len(da) - self.out_frame:]]\n images = [np.array(data) for data in datas]\n images = np.stack([[image] for image in images])\n images = np.squeeze(images)\n images = images.transpose(1,2,0)\n transform = transforms.Compose([transforms.ToTensor()])\n output_image = transform(images)\n\n return input_image, output_image\n\n def __len__(self):\n return len(self.total_dataset)\n","sub_path":"Seq_Dataset.py","file_name":"Seq_Dataset.py","file_ext":"py","file_size_in_byte":1457,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"458188499","text":"#!/usr/bin/env python\n\nimport rospy, tf, rospkg\nfrom gazebo_msgs.srv import SpawnModel\nimport time\nfrom geometry_msgs.msg import *\nfrom gazebo_msgs.msg import ModelState, ModelStates\nimport os\nfrom os.path import expanduser\n\nrospack = rospkg.RosPack()\nHome = rospack.get_path('multi_ur5')\npath = Home + '/models/object/model.sdf'\n\nclass Spawn():\n\tdef __init__(self, model_name, Spawning, x_pose, y_pose):\n\t\tself.pub_model = rospy.Publisher('gazebo/set_model_state', ModelState, queue_size=1)\n\t\tself.model_name = model_name\n\t\tself.rate = rospy.Rate(10)\n\t\tself.x_model_pose = x_pose\n\t\tself.y_model_pose = y_pose\n\t\tself.Spawning = Spawning \n\t\tself.flag = 0\n\t\tself.flag1 = 0\n\n\n\tdef spawning(self,):\n\t\twith open(path) as f:\n\t\t\tproduct_xml = f.read()\n\t\titem_name = \"product_{0}_0\".format(0)\n\t\tprint(\"Spawning model:%s\", self.model_name)\n\t\titem_pose = Pose(Point(x=self.x_model_pose, y=self.y_model_pose, z=1.0), Quaternion(0.,0.,0.,0.))\n\t\t# item_pose = Pose(Point(x=self.x_model_pose, y=self.y_model_pose, z=2))\n\t\tself.Spawning(self.model_name, product_xml, \"\", item_pose, \"world\")\n\ndef main():\n\trospy.init_node('moving_obstacle')\n\tSpawning = rospy.ServiceProxy(\"gazebo/spawn_sdf_model\", SpawnModel)\n\trospy.wait_for_service(\"gazebo/spawn_sdf_model\")\n\tobject1 = Spawn(\"object\", Spawning, 0.65, -0.25)\n\tobject1.spawning()\n\nif __name__ == '__main__':\n\tmain()\n # 0.6 1 2 0 0.785 -1.57 -->\n","sub_path":"version3/Multi_robot/multi_ur5/scripts/spawn_object.py","file_name":"spawn_object.py","file_ext":"py","file_size_in_byte":1427,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"87882432","text":"from mpxapi.api_base import ApiBase\n\n\nclass Program(ApiBase):\n def __init__(self, api):\n ApiBase.__init__(self, api)\n\n self.schema = \"2.15.0\"\n self.searchSchema = \"1.3.0\"\n self.service = \"Entertainment Data Service\"\n self.path = \"/data/Program\"\n","sub_path":"mpxapi/entertainment/program.py","file_name":"program.py","file_ext":"py","file_size_in_byte":283,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"615351148","text":"\"\"\"\nアプリの足跡自動化ツール\n元ネタ\nhttps://rikediary.com/matching-app/automation/python-pairs/\n\"\"\"\nfrom os import environ\nfrom os.path import basename\nimport time\nimport random\nimport re\n\nfrom selenium import webdriver\n\nfrom commonlib.log import get_logger, stop_watch\nfrom commonlib.db import default_engine, DB\nfrom db.kotapypj_models import AccessLog\n\n_PAIRS_LOGIN_URL = 'https://pairs.lv/#/login'\n_SEARCH_RESULT_COUNT_SELECTOR = '#pairs_search_page > div > div.box_search_menu > p:nth-child(5)'\n_FACE_BOOK_LOGIN_BUTTON = '#registerBtn1'\n_FIRST_ACCESS_NUM = 1\n_MAX_ACCESS_NUM_BASE = int(environ['PAIRS_MAX_ACCESS_NUM'])\n_ADD_ACCESS_NUM = int(environ['PAIRS_ADD_ACCESS_NUM'])\n_PROFILE_PATH = r'/Users/kota-ishizuka/Library/Application Support/Google/Chrome'\nfail_count = 0\n\n# logger\nlogger = get_logger(__name__)\n\n\n@stop_watch(basename(__file__), logger)\ndef main():\n init_db()\n current_access_count = 0\n\n max_access_num = random.randint(_MAX_ACCESS_NUM_BASE, _MAX_ACCESS_NUM_BASE + _ADD_ACCESS_NUM)\n options = webdriver.ChromeOptions()\n # options.add_argument('--headless')\n # options.add_argument(\"user-data-dir=\" + _PROFILE_PATH) # これでsession保てるはずだができない。\n\n # このprofileを読み込ませることで「facebook.comが許可を求めています。」のアラートがなくなる。\n prefs = {\"profile.default_content_setting_values.notifications\": 2}\n options.add_experimental_option(\"prefs\", prefs)\n driver = webdriver.Chrome(chrome_options=options)\n driver.get(_PAIRS_LOGIN_URL)\n time.sleep(5)\n authenticate_facebook(driver)\n\n src = \"https://pairs.lv/#/search/one/%s\" % str(_FIRST_ACCESS_NUM)\n driver.get(src)\n num_list = get_random_list(driver)\n time.sleep(5)\n\n logger.info(f'max_access_num:{max_access_num}')\n for i, num in enumerate(num_list, start=1):\n if current_access_count >= max_access_num:\n break\n current_access_count = current_access_count + 1\n src = \"https://pairs.lv/#/search/one/%s\" % str(num)\n try:\n driver.get(src)\n except Exception as e:\n continue\n logger.info(f'{i}人目:{num}')\n time.sleep(random.randint(7, 9))\n\n logger.info(f\"{current_access_count}人に足跡を付けました\")\n insert_access_count(current_access_count)\n driver.close()\n driver.quit()\n\n\ndef authenticate_facebook(driver):\n \"\"\"\n Facebookアカウントからログイン認証を行う。\n :param driver: chrome driver\n \"\"\"\n driver.find_element_by_css_selector(_FACE_BOOK_LOGIN_BUTTON).click()\n\n time.sleep(5)\n handle_array = driver.window_handles\n driver.switch_to.window(handle_array[1])\n driver.find_element_by_css_selector('#email').send_keys(environ['FACEBOOK_EMAIL'])\n driver.find_element_by_css_selector('#pass').send_keys(environ['FACEBOOK_PASS'])\n try:\n driver.find_element_by_css_selector('#u_0_0').click()\n time.sleep(5)\n driver.switch_to.window(handle_array[0])\n except:\n # \"We could not log you in\"が出た時の逃げ対応\n time.sleep(3)\n driver.find_element_by_css_selector('#u_0_2').click()\n time.sleep(5)\n driver.close()\n time.sleep(3)\n driver.switch_to.window(handle_array[0])\n time.sleep(5)\n driver.find_element_by_css_selector(_FACE_BOOK_LOGIN_BUTTON).click()\n time.sleep(5)\n\n\ndef get_random_list(driver):\n \"\"\"\n 検索結果の件数を取得し、件数分のリストを作成する。\n そのリストをシャッフルして返却する。(ランダムに足跡をつけるため。)\n\n たまにCSSセレクタを取得できない場合があるので、10回まで再帰処理で繰り返す。\n 10回処理をしても取得できない場合は、処理を強制終了する。\n :param driver: chrome driver\n :return: 検索結果の件数分のシャッフルした数値リスト\n \"\"\"\n try:\n global fail_count\n time.sleep(1)\n result_count_info = driver.find_element_by_css_selector(_SEARCH_RESULT_COUNT_SELECTOR).text\n result_count = int(re.search(r'^\\d+', re.sub(',', '', result_count_info)).group(0))\n logger.info(f'result_count: {result_count}')\n if result_count == 0:\n exit(1)\n num_list = list(range(1, result_count))\n random.shuffle(num_list)\n return num_list\n except Exception as e:\n if fail_count >= 10:\n logger.error('css NG')\n return exit(1)\n fail_count += 1\n time.sleep(3)\n return get_random_list(driver)\n\n\ndef init_db():\n global dbsvr\n dbsvr = default_engine()\n\n\ndef insert_access_count(access_count):\n access_log = AccessLog(access_count=access_count)\n DB(dbsvr).insert(access_log)\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"src/kozuke/pairs/automate-pairs.py","file_name":"automate-pairs.py","file_ext":"py","file_size_in_byte":4866,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"424449506","text":"# coding=utf-8\n# --------------------------------------------------------------------------\n# Copyright (c) Microsoft Corporation. All rights reserved.\n# Licensed under the MIT License. See License.txt in the project root for\n# license information.\n#\n# Code generated by Microsoft (R) AutoRest Code Generator.\n# Changes may cause incorrect behavior and will be lost if the code is\n# regenerated.\n# --------------------------------------------------------------------------\n\nfrom msrest.serialization import Model\n\n\nclass DocumentStatistics(Model):\n \"\"\"DocumentStatistics.\n\n :param characters_count: Number of text elements recognized in the\n document.\n :type characters_count: int\n :param transactions_count: Number of transactions for the document.\n :type transactions_count: int\n \"\"\"\n\n _attribute_map = {\n 'characters_count': {'key': 'charactersCount', 'type': 'int'},\n 'transactions_count': {'key': 'transactionsCount', 'type': 'int'},\n }\n\n def __init__(self, **kwargs):\n super(DocumentStatistics, self).__init__(**kwargs)\n self.characters_count = kwargs.get('characters_count', None)\n self.transactions_count = kwargs.get('transactions_count', None)\n","sub_path":"sdk/cognitiveservices/azure-cognitiveservices-language-textanalytics/azure/cognitiveservices/language/textanalytics/models/document_statistics.py","file_name":"document_statistics.py","file_ext":"py","file_size_in_byte":1220,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"107172360","text":"import re\n\nfrom boac import db\nimport boac.api.util as api_util\nfrom boac.externals import calnet, canvas, sis_enrollments_api, sis_student_api\nfrom boac.models.team_member import TeamMember\n\n\ndef merge_sis_enrollments(canvas_course_sites, cs_id, term_id):\n # TODO For the moment, we're returning Canvas courses only for the current term as defined in\n # app config. Once we start grabbing multiple terms, we'll need additional sorting logic.\n enrollments = sis_enrollments_api.get_enrollments(cs_id, term_id)\n if enrollments:\n enrollments = enrollments.get('studentEnrollments', [])\n else:\n return\n\n for site in canvas_course_sites:\n site['sisEnrollments'] = []\n sections = canvas.get_course_sections(site['canvasCourseId'])\n if not sections:\n continue\n for section in sections:\n # Manually created site sections will have no integration ID.\n canvas_sis_section_id = section.get('sis_section_id') or ''\n ccn_match = re.match(r'\\ASEC:20\\d{2}-[BCD]-(\\d{5})', canvas_sis_section_id)\n if not ccn_match:\n continue\n canvas_ccn = ccn_match.group(1)\n if not canvas_ccn:\n continue\n for enrollment in enrollments:\n sis_ccn = str(enrollment.get('classSection', {}).get('id'))\n if canvas_ccn == sis_ccn:\n site['sisEnrollments'].append(api_util.sis_enrollment_api_feed(enrollment))\n break\n\n\ndef merge_sis_profile(csid):\n sis_response = sis_student_api.get_student(csid)\n if not sis_response:\n return False\n\n sis_profile = {}\n merge_sis_profile_academic_status(sis_response, sis_profile)\n merge_sis_profile_degree_progress(sis_response, sis_profile)\n merge_sis_profile_emails(sis_response, sis_profile)\n merge_sis_profile_names(sis_response, sis_profile)\n merge_sis_profile_phones(sis_response, sis_profile)\n return sis_profile\n\n\ndef merge_sis_profile_academic_status(sis_response, sis_profile):\n academic_statuses = sis_response.get('academicStatuses', [])\n if len(academic_statuses):\n academic_status = academic_statuses[0]\n else:\n return\n\n sis_profile['cumulativeGPA'] = academic_status.get('cumulativeGPA', {}).get('average')\n sis_profile['level'] = academic_status.get('currentRegistration', {}).get('academicLevel', {}).get('level')\n\n for units in academic_status.get('cumulativeUnits', []):\n if units.get('type', {}).get('code') == 'Total':\n sis_profile['cumulativeUnits'] = units.get('unitsCumulative')\n break\n\n try:\n student_plan = next(plan for plan in academic_status.get('studentPlans', []) if plan.get('primary'))\n plan = student_plan.get('academicPlan', {}).get('plan', {})\n sis_profile['plan'] = {\n 'description': plan.get('description'),\n }\n # Add program and date unless plan code indicates undeclared.\n if plan.get('code') != '25000U':\n sis_profile['plan']['fromDate'] = plan.get('fromDate')\n program = student_plan.get('academicPlan', {}).get('academicProgram', {}).get('program', {})\n sis_profile['plan']['program'] = program.get('description')\n except StopIteration:\n pass\n\n\ndef merge_sis_profile_degree_progress(sis_response, sis_profile):\n sis_profile['degreeProgress'] = {\n 'americanCultures': False,\n 'americanInstitutions': False,\n 'americanHistory': False,\n 'entryLevelWriting': False,\n 'foreignLanguage': False,\n }\n\n # TODO These code translations take provided descriptions at face value. Analysis and confirmation is needed.\n for attribute in sis_response.get('studentAttributes', []):\n code = attribute.get('type', {}).get('code')\n # American History completed at UCB\n if code == 'AHC':\n sis_profile['degreeProgress']['americanHistory'] = True\n # American History & Institutions high school or pre-matriculation\n elif code == 'AHI1' or code == 'AHIP':\n sis_profile['degreeProgress']['americanHistory'] = True\n sis_profile['degreeProgress']['americanInstitutions'] = True\n # American Institutions completed at UCB\n elif code == 'AIC':\n sis_profile['degreeProgress']['americanInstitutions'] = True\n # Entry-Level Writing satisfied pre-matriculation or completed at UCB\n elif code == 'ELW' or code == 'VELW':\n sis_profile['degreeProgress']['entryLevelWriting'] = True\n # American Cultures completed at UCB\n elif code == 'VAC':\n sis_profile['degreeProgress']['americanCultures'] = True\n # Foreign Language completed high school or at UCB\n elif code == 'VFLH' or code == 'VLFL':\n sis_profile['degreeProgress']['foreignLanguage'] = True\n\n\ndef merge_sis_profile_emails(sis_response, sis_profile):\n primary_email = None\n campus_email = None\n for email in sis_response.get('emails', []):\n if email.get('primary'):\n primary_email = email.get('emailAddress')\n break\n elif email.get('type', {}).get('code') == 'CAMP':\n campus_email = email.get('emailAddress')\n sis_profile['emailAddress'] = primary_email or campus_email\n\n\ndef merge_sis_profile_names(sis_response, sis_profile):\n for name in sis_response.get('names', []):\n code = name.get('type', {}).get('code')\n if code == 'PRF':\n sis_profile['preferredName'] = name.get('formattedName')\n elif code == 'PRI':\n sis_profile['primaryName'] = name.get('formattedName')\n if 'primaryName' in sis_profile and 'preferredName' in sis_profile:\n break\n\n\ndef merge_sis_profile_phones(sis_response, sis_profile):\n phones_by_code = {\n phone.get('type', {}).get('code'): phone.get('number')\n for phone in sis_response.get('phones', [])\n }\n sis_profile['phoneNumber'] = phones_by_code.get('CELL') or phones_by_code.get('LOCL') or phones_by_code.get('HOME')\n\n\ndef refresh_cohort_attributes_from_calnet(app, cohorts=None):\n members = cohorts or TeamMember.query.all()\n # Students who play more than one sport will have multiple records.\n member_map = {}\n for m in members:\n member_map.setdefault(m.member_csid, []).append(m)\n csids = list(member_map.keys())\n\n # Search LDAP.\n all_attrs = calnet.client(app).search_csids(csids)\n if len(csids) != len(all_attrs):\n app.logger.warning('Looked for {} CSIDS but only found {}'.format(\n len(csids),\n len(all_attrs),\n ))\n\n # Update the DB.\n for attrs in all_attrs:\n # Since we searched LDAP by CSID, we can be fairly sure that the results have CSIDs.\n csid = attrs['csid']\n for m in member_map[csid]:\n m.member_uid = attrs['uid']\n # A manually-entered ASC name may be more nicely formatted than a student's CalNet default.\n # For now, don't overwrite it.\n m.member_name = m.member_name or attrs['sortable_name']\n return members\n\n\ndef fill_cohort_uids_from_calnet(app):\n to_update = TeamMember.query.filter(TeamMember.member_uid.is_(None)).all()\n refresh_cohort_attributes_from_calnet(app, to_update)\n db.session.commit()\n return to_update\n","sub_path":"boac/lib/merged.py","file_name":"merged.py","file_ext":"py","file_size_in_byte":7376,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"149240674","text":"\"\"\"\nhttps://pythonprogramming.net/loading-video-python-opencv-tutorial/?completed=/loading-images-python-opencv-tutorial/\n\"\"\"\nimport cv2\nfrom matplotlib import pyplot as plt\n\n\ndef demo1():\n \"\"\" demo1\n \"\"\"\n cap = cv2.VideoCapture(0)\n\n # plt.axis([0, 10, 0, 1])\n plt.ion()\n\n while True:\n ret, frame = cap.read()\n if not ret:\n break\n\n # gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)\n frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)\n print(frame.shape)\n # plt.scatter(i, y)\n plt.imshow(frame)\n plt.show()\n plt.pause(0.05)\n\n cap.release()\n\n\ndef demo2():\n \"\"\" demo 2\n \"\"\"\n cap = cv2.VideoCapture(0)\n fourcc = cv2.VideoWriter_fourcc(*'XVID')\n out = cv2.VideoWriter('output.avi', fourcc, 20.0, (640, 480))\n\n while True:\n ret, frame = cap.read()\n gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)\n out.write(frame)\n cv2.imshow('frame', gray)\n if not ret or cv2.waitKey(1) & 0xFF == ord('q'):\n break\n\n cap.release()\n out.release()\n cv2.destroyAllWindows()\n\n\ndemo1()\n","sub_path":"tutorial/opencv-tutorial/loading-video.py","file_name":"loading-video.py","file_ext":"py","file_size_in_byte":1121,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"266911761","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Sep 7 18:51:51 2020\n\n@author: 91852\n\"\"\"\n\n\n\n\n\n\n\n\n\na=10\nb=20\nprint(a+b)\nprint(a-b)\nprint(a*b)\nprint(a/b)\nprint(a**b)\n\na=20\nb=30\nprint(a+b)\nprint(a-b)\nprint(a*b)\nprint(a/b)\nprint(a**b)\n\na=50\nb=60\nprint(a+b)\nprint(a-b)\nprint(a*b)\nprint(a/b)\nprint(a**b)\n\na=70\nb=40\nprint(a+b)\nprint(a-b)\nprint(a*b)\nprint(a/b)\nprint(a**b)\n\n\n#user defined functions\ndef oper(a,b):\n print(\"Sum\",a+b)\n print(\"Sub\",a-b)\n print(\"Mul\",a*b)\n print(\"Div\",a/b)\n print(\"Pow\",a**b)\n \noper(10,20)\noper(20,30)\noper(50,60)\noper(40,70)\n\ni = 0\nj = 10\nwhile(i<10):\n oper(i,j)\n i = i+1\n j = j+1\n \ni = 0\nj = 10\nwhile(i<10):\n print(\"Oper Call\")\n oper(i,j)\n i = i+1\n j = j+1\n \ndef oper(a,b):\n Sum= a+b\n Sub= a-b\n return(Sum, Sub)\n\n\n#individual elements are integers \noper(10,20)\n \n \n#when fetching it is tuple\nc= oper(10,20)\nc\ntype(c)\n\ndef printhello(fname):\n print(\"Hello\", fname,\" welcome\")\n\nprinthello(\"Aman\")\nprinthello(\"Sushant\")\n\n#inputs are needed because no default input has been provided\ndef totalsale(x, y):\n return(x+y)\n\ntotalsale()\n\n#no inputs put so default inputs used\ndef totalsale(x=0, y=0):\n return(x+y)\n\ntotalsale()\ntotalsale(10,20)\n\n\ndef totalsale(x=0, y=0):\n c=x+y\n return(c)\n\n\n#random numbers\nimport random\n\n#random integers every single time you run it till the time you store that\nrandom.randint(1,10)\n\nx = random.randint(100, 1000)\nx\n\n#choose an element from the list on random basis \nlist = [11,12,13,14,15,16]\nrandom.choice (list)\n\n#4 groups of 5 random numbers \n\nlist1 = []\nlist2 = []\nlist3 = []\nlist4 = []\n\ni=0\nwhile(i<4):\n list1.append(random.randint(100,1000))\n list2.append(random.randint(100,1000))\n list3.append(random.randint(100,1000))\n list4.append(random.randint(100,1000))\n i = i+1\nlist1\nlist2\nlist3\nlist4\n\n#Use of choice command with string\nimport random\nst = \"abcdef\"\nst\nrandom.choice(st)\n\nnames=[\"vikas\", \"Aman\", \"Simar\", \"Sirat\"]\nrandom.choice(names)\n\n#random.choices returns you \"n\" no of random items\nrandom.choices (names, k=3)\nrandom.choices(list1, k=3)\n\n#creating a random sample \nimport random\nsample = random.choices (names, k=2)\n\nsample\n\n#working these random codes on dictionary\n\nd1 = {\"Name\": \"vikas\", \"RollNo\": 111, \"Class\" : \"ML\"}\ntype(d1)\nrandom.choices(d1)\n\n#it does not work on dict or set and has to converted to list or tuple\nc = random.choices(list(d1), k=3)\nc\n\nd1 = {\"Name\": \"vikas\", \"RollNo\": 111, \"Class\" : \"ML\"}\ntype(d1)\ns1 ={20,30,40,50}\nc= random.choices(list(d1), k=3)\nc\nc= random.choices(tuple(s1), k=3)\nc\n\n#this word random can be replaced with other name\nimport random as rd\nrd.choices(list(s1), k=3)\n\n\n#randrange usuage\nmovie_list = [\"The Godfather\", \"The Wizard of Oz\", \"Citizen Kane\", \"The shawkerliners\", \" Fast and Furious\"]\n\nrandom_ndex = rd.randrange(9)\nrandom_ndex\n\nRandom_index = rd.randrange(len(movie_list))\nRandom_index \n\nitem = movie_list[Random_index]\nprint(\"Randomly selected item and its index is - \", item, \"Index - \", Random_index)\n\nimport random as rd\ns1={1,2,3,4}\nl1=list(s1)\nl1[2]\n\nt=(1,2,3,4)\nt=[1]\n\n#seed function- used to state of the random number, the same data can be called randomly again and again \n#don't want to change samples frequently\n\nimport random\nfor i in range(5):\n #any number can be used in the place of \"0\"\n random.seed(0)\n #generated random number will be between 1 to 1000\n print(random.randint(1, 1000))\n\nrandom.seed(100)\nrandom.randint(1, 1000)\n\n\n#highly required and important library in Python, it can hold any array related object\nimport numpy\n","sub_path":"Session3 Part1.py","file_name":"Session3 Part1.py","file_ext":"py","file_size_in_byte":3572,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"470070703","text":"# -*- mode: python -*-\n# Copyright (C) 2016 Niklas Rosenstein\n#\n# Permission is hereby granted, free of charge, to any person obtaining a copy\n# of this software and associated documentation files (the \"Software\"), to deal\n# in the Software without restriction, including without limitation the rights\n# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n# copies of the Software, and to permit persons to whom the Software is\n# furnished to do so, subject to the following conditions:\n#\n# The above copyright notice and this permission notice shall be included in\n# all copies or substantial portions of the Software.\n#\n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n# THE SOFTWARE.\n\n__all__ = ['CSCompiler']\n\nfrom craftr import Target\n\n\nclass CSCompiler(object):\n ''' Class for compiling C-Sharp programs using Microsoft CSC. '''\n\n def __init__(self, program='csc'):\n super().__init__()\n self.program = program\n\n def compile(self, filename, sources, target='exe', defines=(),\n optimize=True, warn=None, warnaserror=False, appconfig=None, baseaddress=None,\n checked=False, debug=False, main=None, platform=None, unsafe=False,\n win32icon=None, win32manifest=None, win32res=None, additional_flags=()):\n\n filename = path.normpath(filename, module.project_name)\n if target in ('appcontainerexe', 'exe', 'winexe'):\n filename = path.addsuffix(filename, '.exe')\n elif target == 'library':\n filename = path.addsuffix(filename, '.dll')\n elif target == 'winmdobj':\n filename = path.addsuffix(filename, '.winmdobj')\n elif target == 'module':\n filename = path.addsuffix(filename, '.netmodule')\n else:\n raise ValueError('invalid target: {0!r}'.format(target))\n if warn not in (None, 0, 1, 2, 3, 4):\n raise ValueError('invalid warn: {0!r}'.format(warn))\n if platform not in (None, 'anycpu', 'anycpu32bitpreferred', 'ARM', 'x64', 'x86', 'Itanium'):\n raise ValueError('invalid platform: {0!r}'.format(platform))\n\n command = [self.program, '/nologo', '/out:$out']\n command += ['/warn:{0}'.format(warn)] if warn is not None else []\n command += ['/warnaserror'] if warnaserror else []\n command += ['/target:{0}'.format(target)]\n command += ['/define:{0}'.format(x) for x in defines]\n command += ['/appconfig:{0}'.format(appconfig)] if appconfig else []\n command += ['/baseaddress:{0}'.format(baseaddress)] if baseaddress else []\n command += ['/checked'] if checked else []\n command += ['/main:{0}'.format(main)] if main else []\n command += ['/platform:{0}'.format(platform)] if platform else []\n command += ['/unsafe'] if unsafe else []\n if debug:\n command += ['/debug']\n elif optimize:\n command += ['/optimize']\n command += ['/win32icon:{0}'.format(win32icon)] if win32icon else []\n command += ['/win32manifest:{0}'.format(win32manifest)] if win32manifest else []\n command += ['/win32res:{0}'.format(win32res)] if win32res else []\n command += ['$in']\n\n return Target(command, sources, [filename])\n","sub_path":"craftr/lib/craftr.ext.compiler.csc.py","file_name":"craftr.ext.compiler.csc.py","file_ext":"py","file_size_in_byte":3463,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"53864488","text":"import copy\nimport random\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport json\nimport os.path\nimport sys\nsys.path.append('../')\nfrom types import SimpleNamespace as Namespace\nfrom feature.FeatureTransformation import FeatureTransformation\nfrom feature.SimpleFeatureExtractor import SimpleFeatureExtractor\nfrom feature.TimeSeriesFeatureExtractor import TimeSeriesFeatureExtractor\nfrom util.Util import Util\nimport pandas as pd\n\n# Test how our algorithm performs in others' data.\nrootDir = '../../data/AReM/'\nfileName1 = '/dataset'\nfileName2 = '.csv'\nfolders = ['bending1','bending2','cycling','lying','sitting','standing','walking']\nis_heldout = False\nmin_samples_leaf = 1\n# print(df)\ndfAll = None\nfor index,folder in enumerate(folders):\n for i in range(1,14):\n filePath = rootDir + folder + fileName1 + str(i) + fileName2\n import os.path\n if not os.path.isfile(filePath):\n continue\n df = pd.read_csv(filePath, comment='#'\n ,names = ['time','avg_rss12','var_rss12','avg_rss13','var_rss13','avg_rss23','var_rss23'])\n df['label'] = folder\n print(filePath, folder, len(df))\n if dfAll is None:\n dfAll = df\n continue\n else:\n dfAll = dfAll.append(df)\n\n\n\"\"\"Test data\"\"\"\ntest_dfAll = None\nfor index,folder in enumerate(folders):\n for i in range(14,16):\n filePath = rootDir + folder + fileName1 + str(i) + fileName2\n import os.path\n if not os.path.isfile(filePath):\n continue\n df = pd.read_csv(filePath, comment='#'\n ,names = ['time','avg_rss12','var_rss12','avg_rss13','var_rss13','avg_rss23','var_rss23'])\n df['label'] = folder\n print(filePath, folder, len(df))\n if test_dfAll is None:\n test_dfAll = df\n continue\n else:\n test_dfAll = test_dfAll.append(df)\n\nprint(len(test_dfAll))\n\n\ndfAll = dfAll.dropna(subset=['avg_rss12','var_rss12','avg_rss13','var_rss13','avg_rss23','var_rss23','label'])\ndfAll = dfAll[['avg_rss12','var_rss12','avg_rss13','var_rss13','avg_rss23','var_rss23','label']]\ndata = dfAll.as_matrix()\n\ntest_dfAll = test_dfAll.dropna(subset=['avg_rss12','var_rss12','avg_rss13','var_rss13','avg_rss23','var_rss23','label'])\ntest_dfAll = test_dfAll[['avg_rss12','var_rss12','avg_rss13','var_rss13','avg_rss23','var_rss23','label']]\ntest_data = test_dfAll.as_matrix()\nprint('****************Start to run classifications***************')\nrand_data = np.array(copy.deepcopy(data))\nrandom.shuffle(rand_data)\nprint(rand_data[0])\nX_rand = rand_data[:,:len(data[0])-1]\ny_rand = rand_data[:,len(data[0])-1]\n# print('888888888888', X_rand, '---------', y_rand)\n\nheldout_len = int(len(X_rand)*0.8)\nx_train = X_rand[:heldout_len]\ny_train = y_rand[:heldout_len]\nx_test = []\ny_test = []\nif is_heldout:\n x_test = X_rand[heldout_len:]\n y_test = y_rand[heldout_len:]\nelse:\n x_test = test_data[:,:len(test_data[0])-1]\n y_test = test_data[:,len(test_data[0])-1]\n\n# X = data[:,:3]\n# y = data[:,4]\n\nfor numTree in range(9,11):\n if(numTree%2 == 0):\n continue\n \"\"\"Random Forest\"\"\"\n from sklearn.ensemble import RandomForestClassifier\n rf_model = RandomForestClassifier(n_estimators=numTree, min_samples_leaf = min_samples_leaf, n_jobs =8)\n model = rf_model\n print('Random Forest(',numTree,'):')\n\n # \"\"\"Artificial Neural Network\"\"\"\n # from sklearn.neural_network import MLPClassifier\n # ann_model = MLPClassifier()\n # model = ann_model\n # print('ANN:')\n #\n # \"\"\"SVM\"\"\"\n # from sklearn.svm import SVC\n # svm_model = SVC()\n # model = svm_model\n # print('SVM:')\n\n # \"\"\"knn\"\"\"\n # from sklearn.neighbors import KNeighborsClassifier\n # model = KNeighborsClassifier(n_neighbors=numTree)\n #\n # \"\"\"SGD\"\"\"\n # from sklearn import linear_model\n # model = linear_model.SGDClassifier(max_iter=1000,tol = 1000)\n\n # \"\"\"adaboost\"\"\"\n # from sklearn.model_selection import cross_val_score\n # from sklearn.datasets import load_iris\n # from sklearn.ensemble import AdaBoostClassifier\n\n model.fit(x_train,y_train)\n\n # from sklearn.tree import export_graphviz\n # export_graphviz(model.estimators_[0],\n # feature_names=x_columns,\n # filled=True,\n # rounded=True)\n\n # os.system('dot -Tpng tree.dot -o tree.png')\n\n\n print('Training score: ',model.score(x_train,y_train))\n print('Testing score: ', model.score(x_test,y_test))\n\n from sklearn.metrics import classification_report\n y_true = y_test\n y_pred = model.predict(x_test)\n target_names = folders\n print(classification_report(y_true, y_pred, target_names=target_names))\n\n from sklearn.model_selection import cross_val_predict\n from sklearn.metrics import confusion_matrix\n conf_mat = confusion_matrix(y_true,y_pred, labels = folders)\n print(conf_mat)\n\n if is_heldout:\n\n y_pred = cross_val_predict(model,x_train,y_train,cv=10)\n conf_mat = confusion_matrix(y_train,y_pred)\n print(conf_mat)\n","sub_path":"script/process/testOthersData.py","file_name":"testOthersData.py","file_ext":"py","file_size_in_byte":5056,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"244812323","text":"#\r\n#\r\n#\r\n\r\nimport sys\r\nimport pygame\r\nimport time\r\n\r\npygame.init()\r\n\r\nWHITE = (255, 255, 255)\r\nGREEN = (27, 127, 66)\r\nBLACK = (0, 0, 0)\r\nBLUE = (0, 0, 255)\r\n\r\n\r\n\r\nWINDOWWIDTH = 1920\r\nWINDOWHEIGHT = 1080\r\n\r\nWINDOW_SURFACE = pygame.display.set_mode((WINDOWWIDTH, WINDOWHEIGHT))\r\n\r\n#screen = pygame.display.set_mode((1920, 1080), pygame.FULLSCREEN)\r\n\r\nbasicFont = pygame.font.SysFont(None,48)\r\ntext=basicFont.render(\"Hello World!\", True, WHITE)\r\n\r\n\r\n\r\n## GAME LOOP\r\nwhile True:\r\n \r\n for x in range(0,255):\r\n COLOR = (x,0,0)\r\n print (COLOR)\r\n WINDOW_SURFACE.fill(COLOR)\r\n \r\n textRect = text.get_rect()\r\n textRect.centerx = WINDOW_SURFACE.get_rect().centerx\r\n textRect.centery = WINDOW_SURFACE.get_rect().centery\r\n WINDOW_SURFACE.blit(text, textRect)\r\n \r\n pygame.display.update()\r\n for event in pygame.event.get():\r\n if event.type == pygame.QUIT:\r\n pygame.quit()\r\n sys.exit(0)\r\n \r\n","sub_path":"g2.py","file_name":"g2.py","file_ext":"py","file_size_in_byte":1147,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"34479390","text":"# -*- coding: utf-8 -*-\nfrom south.utils import datetime_utils as datetime\nfrom south.db import db\nfrom south.v2 import SchemaMigration\nfrom django.db import models\n\n\nclass Migration(SchemaMigration):\n\n def forwards(self, orm):\n # Deleting model 'User'\n db.delete_table(u'unicoresso_user')\n\n # Deleting model 'Repo'\n db.delete_table(u'unicoresso_repo')\n\n # Removing M2M table for field users on 'Repo'\n db.delete_table(db.shorten_name(u'unicoresso_repo_users'))\n\n # Adding model 'AuthorizedSite'\n db.create_table(u'unicoresso_authorizedsite', (\n (u'id', self.gf('django.db.models.fields.AutoField')(primary_key=True)),\n ('site', self.gf('django.db.models.fields.CharField')(max_length=200)),\n ))\n db.send_create_signal(u'unicoresso', ['AuthorizedSite'])\n\n # Adding M2M table for field group on 'AuthorizedSite'\n m2m_table_name = db.shorten_name(u'unicoresso_authorizedsite_group')\n db.create_table(m2m_table_name, (\n ('id', models.AutoField(verbose_name='ID', primary_key=True, auto_created=True)),\n ('authorizedsite', models.ForeignKey(orm[u'unicoresso.authorizedsite'], null=False)),\n ('group', models.ForeignKey(orm[u'auth.group'], null=False))\n ))\n db.create_unique(m2m_table_name, ['authorizedsite_id', 'group_id'])\n\n\n def backwards(self, orm):\n # Adding model 'User'\n db.create_table(u'unicoresso_user', (\n ('username', self.gf('django.db.models.fields.CharField')(max_length=30)),\n ('password', self.gf('django.db.models.fields.CharField')(max_length=30)),\n (u'id', self.gf('django.db.models.fields.AutoField')(primary_key=True)),\n ))\n db.send_create_signal(u'unicoresso', ['User'])\n\n # Adding model 'Repo'\n db.create_table(u'unicoresso_repo', (\n ('url', self.gf('django.db.models.fields.CharField')(max_length=30)),\n (u'id', self.gf('django.db.models.fields.AutoField')(primary_key=True)),\n ))\n db.send_create_signal(u'unicoresso', ['Repo'])\n\n # Adding M2M table for field users on 'Repo'\n m2m_table_name = db.shorten_name(u'unicoresso_repo_users')\n db.create_table(m2m_table_name, (\n ('id', models.AutoField(verbose_name='ID', primary_key=True, auto_created=True)),\n ('repo', models.ForeignKey(orm[u'unicoresso.repo'], null=False)),\n ('user', models.ForeignKey(orm[u'unicoresso.user'], null=False))\n ))\n db.create_unique(m2m_table_name, ['repo_id', 'user_id'])\n\n # Deleting model 'AuthorizedSite'\n db.delete_table(u'unicoresso_authorizedsite')\n\n # Removing M2M table for field group on 'AuthorizedSite'\n db.delete_table(db.shorten_name(u'unicoresso_authorizedsite_group'))\n\n\n models = {\n u'auth.group': {\n 'Meta': {'object_name': 'Group'},\n u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),\n 'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '80'}),\n 'permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': u\"orm['auth.Permission']\", 'symmetrical': 'False', 'blank': 'True'})\n },\n u'auth.permission': {\n 'Meta': {'ordering': \"(u'content_type__app_label', u'content_type__model', u'codename')\", 'unique_together': \"((u'content_type', u'codename'),)\", 'object_name': 'Permission'},\n 'codename': ('django.db.models.fields.CharField', [], {'max_length': '100'}),\n 'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': u\"orm['contenttypes.ContentType']\"}),\n u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),\n 'name': ('django.db.models.fields.CharField', [], {'max_length': '50'})\n },\n u'contenttypes.contenttype': {\n 'Meta': {'ordering': \"('name',)\", 'unique_together': \"(('app_label', 'model'),)\", 'object_name': 'ContentType', 'db_table': \"'django_content_type'\"},\n 'app_label': ('django.db.models.fields.CharField', [], {'max_length': '100'}),\n u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),\n 'model': ('django.db.models.fields.CharField', [], {'max_length': '100'}),\n 'name': ('django.db.models.fields.CharField', [], {'max_length': '100'})\n },\n u'unicoresso.authorizedsite': {\n 'Meta': {'object_name': 'AuthorizedSite'},\n 'group': ('django.db.models.fields.related.ManyToManyField', [], {'to': u\"orm['auth.Group']\", 'symmetrical': 'False'}),\n u'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),\n 'site': ('django.db.models.fields.CharField', [], {'max_length': '200'})\n }\n }\n\n complete_apps = ['unicoresso']","sub_path":"unicoresso/migrations/0002_auto__del_user__del_repo__add_authorizedsite.py","file_name":"0002_auto__del_user__del_repo__add_authorizedsite.py","file_ext":"py","file_size_in_byte":4929,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"135155703","text":"import pickle\nimport os\n\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom tqdm import tqdm\n\nwith open('data/sentences.txt', 'r') as inp:\n texts = inp.read()\nsentences = texts.split('\\nEOS\\n') # 按EOS按句分开成list\nsentences.remove('')# 去除list的最后一个空白要素d()\n\ntokenized = list()\ntag_list = list()\nfor sent in tqdm(sentences):\n lines = sent.split('\\n')\n ma_info = [line.split(' ') for line in lines]\n tokens = [info[0] for info in ma_info]\n tokenized.append(tokens)\n tags = list()\n for info in ma_info:\n if info[4] == '人名': # PER\n tags.append(1)\n elif info[4] == '地名': # LOC\n tags.append(2)\n elif info[4] == '組織名': # GRP\n tags.append(3)\n else: # OTHER\n tags.append(4)\n tag_list.append(tags)\n\nsentence_len = pd.Series([len(sent) for sent in tokenized])\nsentence_len.hist(bins=100)\nplt.xlim(0, 240)\nplt.xlabel('sentence_length')\nplt.ylabel('sentence_num')\nplt.title('Distribution of the Length of Sentence')\nplt.xticks(np.arange(0, 240, 40))\nplt.show()\n\nvocab = list(set([token for tokens in tokenized for token in tokens]))\nids = range(1, len(vocab)+1)\n\nword2id = pd.Series(ids, index=vocab)\nid2word = pd.Series(vocab, index=ids)\n\nmax_len = 40\n\n\ndef X_padding(words):\n \"\"\"把 words 转为 id 形式,并自动补全位 max_len 长度。\"\"\"\n ids = list(word2id[words])\n if len(ids) >= max_len: # 长则弃掉\n return ids[:max_len]\n ids.extend([0]*(max_len-len(ids))) # 短则补全\n return ids\n\n\ndef y_padding(tags):\n \"\"\"把 tags 转为 id 形式, 并自动补全位 max_len 长度。\"\"\"\n ids = tags\n if len(ids) >= max_len: # 长则弃掉\n return ids[:max_len]\n ids.extend([0]*(max_len-len(ids))) # 短则补全\n return ids\n\n\nx = pd.Series(tokenized).apply(X_padding)\ny = pd.Series(tag_list).apply(y_padding)\nx = np.asarray(list(x.values))\ny = np.asarray(list(y.values))\n\n\ndef convert_y(y):\n new_y = list()\n for sent in y:\n a = list()\n for tag in sent:\n if tag == 0:\n a.append(np.array([1, 0, 0, 0, 0]))\n elif tag == 1:\n a.append(np.array([0, 1, 0, 0, 0]))\n elif tag == 2:\n a.append(np.array([0, 0, 1, 0, 0]))\n elif tag == 3:\n a.append(np.array([0, 0, 0, 1, 0]))\n elif tag == 4:\n a.append(np.array([0, 0, 0, 0, 1]))\n new_y.append(a)\n return np.array(new_y)\n\n\ny = convert_y(y)\n\nwith open('data/ner_data.pkl', 'wb') as output:\n pickle.dump(x, output)\n pickle.dump(y, output)\n pickle.dump(word2id, output)\n pickle.dump(id2word, output)\n","sub_path":"jner/preprocessing.py","file_name":"preprocessing.py","file_ext":"py","file_size_in_byte":2717,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"626848279","text":"# 直方体のマージ\n\ndef get_intersection(cuboid1, cuboid2):\n\t# each line is represented as (origin, len)\n\tdef get_line_intersection(x, y):\n\t\tstart = max(x[0], y[0])\n\t\tend = min(x[0] + x[1], y[0] + y[1])\n\t\tif (end - start > 0):\n\t\t\treturn (start, end - start)\n\t\telse:\n\t\t\treturn False\n\tx_intersection = get_line_intersection((cuboid1[0], cuboid1[3]), (cuboid2[0], cuboid2[3]))\n\ty_intersection = get_line_intersection((cuboid1[1], cuboid1[4]), (cuboid2[1], cuboid2[4]))\n\tz_intersection = get_line_intersection((cuboid1[2], cuboid1[5]), (cuboid2[2], cuboid2[5]))\n\tif (x_intersection and y_intersection and z_intersection):\n\t\treturn (x_intersection[0], y_intersection[0], z_intersection[0], \\\n\t\t\tx_intersection[1], y_intersection[1], z_intersection[1])\n\telse:\n\t\treturn False\n\ndef get_volumn(cuboids):\n\tdef volumn_of(cuboid):\n\t\treturn cuboid[3] * cuboid[4] * cuboid[5]\n\tsum = 0\n\tfor cuboid, sign in cuboids.items():\n\t\tthis_volumn = volumn_of(cuboid)\n\t\tif sign == 1:\n\t\t\tsum += this_volumn\n\t\telse:\n\t\t\tsum -= this_volumn\n\treturn sum\n\n# -1 means that cuboid must be subtracted\ndef get_union(cuboids):\n\tif (len(cuboids) == 1):\n\t\treturn {cuboids[0]: 1}\n\tlast = cuboids.pop(len(cuboids) - 1)\n\tsubset = get_union(cuboids)\n\tresult = dict(subset)\n\tresult[last] = 1\n\tfor key, value in subset.items():\n\t\tintersection = get_intersection(key, last)\n\t\tif (intersection != False):\n\t\t\tif (intersection in result):\n\t\t\t\tresult[intersection] = result[intersection] + value * -1\n\t\t\telse:\n\t\t\t\tresult[intersection] = value * -1\n\t\t\tif (result[intersection] == 0):\n\t\t\t\tresult.pop(intersection, 2)\n\treturn result\n\ndef main(input):\n\tlines = input.split(\"\\n\")\n\n\tdef read_line():\n\t\treturn lines.pop(0)\n\n\tdata = []\n\tnum_cuboid = int(read_line())\n\tfor _ in range(num_cuboid):\n\t\tdata.append(tuple(int(x) for x in read_line().split()))\n\n\treturn str(get_volumn(get_union(data)))\n\nimport sys\n#print(main(sys.stdin.read()))\n\n","sub_path":"python/coding_problems/paiza/s_014.py","file_name":"s_014.py","file_ext":"py","file_size_in_byte":1887,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"429165859","text":"import random as rn\nlst = []\nfor i in range (1,101):\n lst.append(rn.randint(1,1000))\nprint(lst) \nnew_lst = []\nfor i in lst:\n if i % 3 == 0 and i % 6 ==0 and \\\n not i % 9 == 0:\n new_lst.append(i)\nprint(new_lst)","sub_path":"n2.py","file_name":"n2.py","file_ext":"py","file_size_in_byte":228,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"236501307","text":"# 37. 解数独\n# https://leetcode-cn.com/problems/sudoku-solver/\nclass Solution:\n def solveSudoku(self, board: List[List[str]]) -> None:\n \"\"\"\n Do not return anything, modify board in-place instead.\n \"\"\"\n n = len(board)\n if n == 0 or len(board[0]) == 0:\n return\n self.solve(board)\n \n def solve(self, board):\n n = len(board)\n for i in range(n):\n for j in range(n):\n if board[i][j] == '.': \n for c in range(1,10):\n if self.is_valid(board, i, j, str(c)):\n board[i][j] = str(c)\n if self.solve(board):\n return True\n board[i][j] = '.'\n return False\n return True\n \n def is_valid(self, board, row, col, num):\n for k in range(0,9):\n if board[row][k]!='.' and board[row][k]== num : return False\n if board[k][col]!='.' and board[k][col]== num : return False\n if board[(row//3)*3+k//3][(col//3)*3+k%3] == num: return False\n return True \n\n\n ","sub_path":"Week_07/solve_sudoku.py","file_name":"solve_sudoku.py","file_ext":"py","file_size_in_byte":1186,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"124187836","text":"\"\"\"\n 三维线框图\n\"\"\"\nimport numpy as np\nimport matplotlib.pyplot as mp\nfrom mpl_toolkits.mplot3d import axes3d\nn = 500\nx,y = np.meshgrid(np.linspace(-3,3,n),np.linspace(-3,3,n))\n#通过每个xy的值算出z的值\nz = (1 - x / 2 + x ** 5 + y ** 3) * np.exp(-x ** 2 - y ** 2)\n\nmp.figure('3D WireFrame',facecolor='lightgrey')\nmp.title('3D WireFrame',fontsize=16)\nax3d = mp.gca(projection='3d')#三维坐标系\nax3d.set_xlabel('X')\nax3d.set_ylabel('Y')\nax3d.set_zlabel('Z')\nax3d.plot_wireframe(x,y,z,linewidth=1,color='dodgerblue',rstride=20,cstride=20)\nmp.tight_layout()\nmp.show()","sub_path":"DataAnalysis/day03/demo08_wireframe.py","file_name":"demo08_wireframe.py","file_ext":"py","file_size_in_byte":582,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"206396343","text":"import json\nfrom colorama import Fore\n\n\nclass ParamsManager(object):\n def __init__(self, params_file):\n self.params = json.load(open(params_file, 'r'))\n\n def get_params(self):\n return self.params\n\n def get_agent_params(self):\n return self.params['agente']\n\n def get_environment_params(self):\n return self.params['environment']\n\n def update_agent_params(self, **kwargs):\n for key, value in kwargs.items():\n if key in self.get_agent_params().keys():\n self.params['agente'][key] = value\n\n def export_agent_params(self, file_name):\n with open(file_name, 'w') as f:\n json.dump(self.params['agente'], f, indent=4, separators=(',', ':'), sort_keys=True)\n f.write('\\n')\n\n def export_env_params(self, file_name):\n with open(file_name, 'w') as f:\n json.dump(self.params['environment'], f, indent=4, separators=(',', ':'), sort_keys=True)\n f.write('\\n')\n\n\nif __name__ == \"__main__\":\n print(\"Prueba\")\n params = \"../parameters.json\"\n manager = ParamsManager(params_file=params)\n agents_params = manager.get_agent_params()\n print(Fore.GREEN + \"los parametros del agente son\")\n for key, value in agents_params.items():\n print(Fore.RESET, key, ':', value)\n env_params = manager.get_environment_params()\n print(Fore.GREEN + \"los parametros del entorno son\")\n for key, value in env_params.items():\n print(Fore.RESET, key, ':', value)\n manager.update_agent_params(learning_rate=0.01, gamma=0.92)\n agents_params = manager.get_agent_params()\n print(Fore.GREEN + \"los parametros actualizados del agente son\")\n for key, value in agents_params.items():\n print(Fore.RESET, key, ':', value)\n","sub_path":"DeepQLearner/utils/params_manager.py","file_name":"params_manager.py","file_ext":"py","file_size_in_byte":1765,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"410593551","text":"import requests\nimport xml.etree.ElementTree as ET\nimport os\n\n\nclass TranslateClient():\n\n def __init__(self, api_key=None):\n self.key = api_key\n self.token = None\n\n def get_token(self):\n token = requests.post(\n 'https://api.cognitive.microsoft.com/sts/v1.0/issueToken',\n params={\n 'Subscription-Key': self.key\n }\n ).text\n # print('token=', token)\n return token\n\n def translate(self, word):\n if not self.token:\n self.token = self.get_token()\n\n response = requests.get(\n 'https://api.microsofttranslator.com/v2/http.svc/Translate',\n params={\n 'appid': 'Bearer ' + self.token,\n 'to': 'ja',\n 'text': word,\n 'category': 'generalnn'\n }\n ).text\n\n translated_word = ET.fromstring(response).text\n return translated_word\n\n\nif __name__ == \"__main__\":\n word = \"a group of giraffe standing on top of a dirt field\"\n key = os.environ['MS_COGNITIVE_TRANSLATE_API_KEY']\n client = TranslateClient(api_key=key)\n result = client.translate(word)\n print(word)\n print('->')\n print(result)\n","sub_path":"py3_api_clients/translate_client.py","file_name":"translate_client.py","file_ext":"py","file_size_in_byte":1225,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"125012153","text":"import os\nimport shutil\n\ndef image_select(rootpath, io_dic):\n print('筛选上行车辆,请选择1,筛选下行车辆,请选择0,全部保留请输入-1')\n flag = eval(input())\n filename = os.listdir(rootpath)\n\n if flag == -1:\n number_select(rootpath)\n return\n elif flag == 0:\n for i in filename:\n if i not in io_dic['0']:\n\n print('{}{}'.format(rootpath, i))\n try:\n shutil.rmtree('{}{}'.format(rootpath, i))\n print('successfully delete {}{}'.format(rootpath, i))\n except:\n print('sth error')\n elif flag == 1:\n for i in filename:\n if i not in io_dic['1']:\n\n print('{}{}'.format(rootpath, i))\n try:\n shutil.rmtree('{}{}'.format(rootpath, i))\n print('successfully delete {}{}'.format(rootpath, i))\n except:\n print('sth error')\n number_select(rootpath)\n\n#若含有图像超过10个,则选取其中最大(默认最大的代表清晰度最高,特征最多)的十个图像,舍弃其他图像\ndef number_select(rootpath):\n single_car_list = os.listdir(rootpath)\n for single_car in single_car_list:\n single_folder_path = '{}{}'.format(rootpath, single_car)\n files_path = os.listdir(single_folder_path)\n size_dic = {}\n for file in files_path:\n size_dic[file] = os.path.getsize('{}//{}'.format(single_folder_path, file))\n #对字典进行排序\n sorted(size_dic.items(),key=lambda item:item[1],reverse=True)\n count = 0\n for k,v in size_dic.items():\n if count > 9:\n os.remove('{}//{}'.format(single_folder_path, k))\n count += 1\n #print(count)\n\n\n\n#从网上寻找的,一种删除文件夹及内部文件的方法,但是已经被弃用\ndef del_file(filepath):\n del_list = os.listdir(filepath)\n for file in del_list:\n file_path = os.path.join(filepath, file)\n if os.path.isfile(file_path):\n os.remove(file_path)\n elif os.path.isdir(file_path):\n shutil.rmtree(file_path)\n os.rmdir(filepath)","sub_path":"Car_Re_ID_yolov5/image_select.py","file_name":"image_select.py","file_ext":"py","file_size_in_byte":2248,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"499041110","text":"import feedparser\nfrom feed import Feed\nfrom feeditem import FeedItem\n\nfrom utils import upload_to_storage\nfrom utils import get_file_from_storage\n\n\nclass Podcast(object):\n \"\"\"utilities for working with an individual feed item\"\"\"\n\n def __init__(self, user_id, storage_endpoint, service_key):\n super(Podcast, self).__init__()\n self.user_id = user_id\n self.storage_endpoint = storage_endpoint\n self.service_key = service_key\n self.file_name = f'/tmp/{user_id}.xml'\n status, body = get_file_from_storage(storage_endpoint=storage_endpoint,\n bucket_name='podcast-xml', file_name=f'{user_id}.xml')\n if status == 200:\n self.feed = self.parse_feed(body)\n else:\n self.feed = self.initialise_podcast_feed()\n self.update()\n\n def initialise_podcast_feed(self):\n newFeed = Feed(title=\"Inian's podcast\", link=\"https://example.com\",\n description=\"Podcast description\")\n return newFeed\n\n def update(self):\n upload_to_storage(file_contents=self.feed.return_feed(), storage_endpoint=self.storage_endpoint,\n bucket_name='podcast-xml', service_key=self.service_key, content_type='application/rss+xml', file_path=self.file_name)\n\n def add_podcast_item(self, feeditem):\n self.feed.add_entry(feeditem)\n return self.update()\n\n def parse_feed(self, feed_content):\n d = feedparser.parse(feed_content)\n feed = Feed(title=d.feed.title, link=d.feed.link,\n description=d.feed.subtitle)\n for entry in d.entries:\n fi = FeedItem(id=entry['id'], title=entry['title'], link=entry['links'][-1]['href'], mimeType=entry[\n 'links'][-1]['type'], length=entry['links'][-1]['length'], description=entry['summary'], published=entry['published'])\n feed.add_entry(fi)\n return feed\n","sub_path":"backend/podcast.py","file_name":"podcast.py","file_ext":"py","file_size_in_byte":1953,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"601500777","text":"# Uses python3\nimport sys\n\ndef calc_sum_of_last_digit_fib(n, m):\n if n <= 1:\n return n\n fib_mod=[0, 1]\n privious = 0\n current = 1\n for i in range(2, n+1):\n privious, current = current, privious + current\n fib_mod.append(current % m)\n if ((fib_mod[i-1] == 0) and (fib_mod[i] == 1)):\n return (fib_mod[n % (len(fib_mod)-2)]-1)%m\n return ((current-1)%m)%m\n\n\ninput = sys.stdin.read()\ntokens = input.split()\nm = int(tokens[0])\nn = int(tokens[1])\n\nprint(((calc_sum_of_last_digit_fib(n+2, 10) % 10)- (calc_sum_of_last_digit_fib(m-1+2, 10) % 10)) % 10)\n","sub_path":"week2_partial_sum_last_digit_fibonacci.py","file_name":"week2_partial_sum_last_digit_fibonacci.py","file_ext":"py","file_size_in_byte":601,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"189148998","text":"import os\n# path = input('请输入文件路径(结尾加上/):')\n\n# 获取该目录下所有文件,存入列表中\ndef getFile(dir_name):\n if not os.path.exists(str(dir_name)): # os模块判断并创建\n os.mkdir(dir_name)\n return dir_name\n\n\n\npath = './list/'\nnewPath = './newList/'\n\ngetFile(newPath)\n\n\nfileList = os.listdir(path)\nprint('fileList', fileList)\nn = 0\nfor i in fileList:\n\n # 设置旧文件名(就是路径+文件名)\n oldname = path + os.sep + fileList[n] # os.sep添加系统分隔符\n\n # 设置新文件名\n # newname = path + os.sep + 'a'+str(n+1)+'.JPG'\n newname = newPath + str(n+1)+str('.') + fileList[n]\n\n os.rename(oldname, newname) # 用os模块中的rename方法对文件改名\n print(oldname, '======>', newname)\n\n n += 1\n\n\n\n\n","sub_path":"测试玩耍/python玩耍/文件重命名/文件重命名排序.py","file_name":"文件重命名排序.py","file_ext":"py","file_size_in_byte":801,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"157682137","text":"import json\nimport pickle\nimport pymongo\nfrom bson.objectid import ObjectId\nimport os\nfrom abc import ABC, abstractmethod\n\n\nclass Storage(ABC):\n \"\"\" Defines essential interface for all kind of storages. \"\"\"\n @abstractmethod\n def save(self, file: str, protocol: str, filename: str):\n pass\n\n @abstractmethod\n def read(self, file: [str, None], protocol: str, arg: str):\n pass\n\n\nclass FileStorage:\n \"\"\" Provides save and read methods with using serialization. \"\"\"\n @staticmethod\n def save(data, protocol: str, filename: str) -> None:\n \"\"\" Saves an object to a library using the given serialization protocol.\n\n Args:\n data: A Python object, which will be saved.\n protocol (str): Pickle or json.\n filename (str): Output filename for saved object.\n \"\"\"\n filename = filename + '.' + protocol\n if protocol.lower() == 'json':\n flag, protocol = 'w', json\n elif protocol.lower() == 'pickle':\n flag, protocol = 'wb', pickle\n else:\n raise ValueError(\"Unknown protocol\")\n\n with open(filename, flag) as f:\n protocol.dump(data, f)\n\n path_to_file = os.getcwd() + '/' + filename\n if os.path.exists(path_to_file):\n print('\\nФайл успешно создан: ', path_to_file)\n else:\n print('\\nЧто-то пошло не так. Файл не создан.')\n\n @staticmethod\n def read(file: str, protocol: str):\n \"\"\" Returns a file from file storage available to read.\n\n Args:\n file (str): A name of the file, which will be read.\n protocol (str): Pickle or json.\n \"\"\"\n if protocol.lower() == 'json':\n flag, protocol = 'r', json\n elif protocol.lower() == 'pickle':\n flag, protocol = 'rb', pickle\n else:\n raise ValueError(\"Unknown protocol\")\n\n with open(file, flag) as rf:\n data = protocol.load(rf)\n return data\n\n\nclass MongoDB(Storage):\n \"\"\" An interface for saving, reading and deletion documents from Mongo .\"\"\"\n def __init__(self, client=None):\n if not client:\n client = input(\"\\nВведите адрес для соединения с БД Mongo.\"\n \"\\nЕсли адрес не введен, будет предпринята попытка \"\n \"подключения к БД mongodb.net:27017,library. \\n\"\n \"Чтобы пропустить, нажмите Enter. \\n\")\n if client:\n self.client = pymongo.MongoClient(client)\n db_name = input(\"Введите имя базы данных: \\n\")\n self.db = self.client[db_name]\n else:\n self.client = pymongo.MongoClient(\n 'mongodb://kristy:rfvtym3gg@library-shard-00-00-ags0v.mongodb.'\n 'net:27017,library-shard-00-01-ags0v.mongodb.net:27017,library'\n '-shard-00-02-ags0v.mongodb.net:27017/test?ssl=true&replicaSet'\n '=library-shard-0&authSource=admin&retryWrites=true&w=majority')\n self.db = self.client.library\n\n def save(self, data, protocol, descriprion: str):\n \"\"\" Saves an object to a Mongo db with the given serialization protocol.\n\n A protocol name is used as a collection name. Documents within collection\n is stored as dictionaries {\"_id\": ID, description: serialized data}\n\n Args:\n data: A Python object, which will be saved.\n protocol (str): Pickle or json.\n descriprion (str): It is recommended to use a short title that\n reflects the content of your document.\n Will be used for searching if ID will not be given.\n\n Returns:\n docum_id: inserted_id number of saved document.\n \"\"\"\n if protocol.lower() == 'json':\n protocol, collection_name = json, 'json_serial'\n elif protocol.lower() == 'pickle':\n protocol, collection_name = pickle, 'pickle_serial'\n else:\n raise ValueError(\"Unknown protocol\")\n\n collection = self.db[collection_name]\n docum_id = collection.insert_one({descriprion: protocol.dumps(data)})\n print(f\"Данные успешно сохранены в БД Mongo. \\n\"\n f\"Коллекция: '{collection_name}' \\n\"\n f\"ID документа: {docum_id.inserted_id}\\n\")\n return docum_id.inserted_id\n\n def read(self, title: [str, None], protocol: str, doc_id: str = None):\n \"\"\" Returns a readable document from Mongo db.\n\n Documents might be found from database depending on the given args.\n If ID is given method returns exactly this document.\n If descriprion given without ID - method returns all documents with the\n given descriprion.\n\n Args:\n title (str, None): A short document title given when saving.\n protocol (str): Pickle or json.\n doc_id (str): Optional, if known.\n Returns:\n unserial: a list of unserialized documents.\n \"\"\"\n if protocol.lower() == 'json':\n protocol, collection_name = json, 'json_serial'\n elif protocol.lower() == 'pickle':\n protocol, collection_name = pickle, 'pickle_serial'\n else:\n raise ValueError(\"Unknown protocol\")\n\n collection = self.db[collection_name]\n if not doc_id:\n unserial = list(collection.find({}, {'_id': 0, title: 1}))\n list_docs = [protocol.loads(i[title]) for i in unserial if i]\n return list_docs\n else:\n data = collection.find({'_id': ObjectId(doc_id)})\n try:\n key = list(data[0].keys())[1]\n return protocol.loads(data[0][key])\n except IndexError:\n print(f\"Документов с ID {doc_id} не найдено в базе.\")\n\n def delete_collection(self, collection_name: [list, str]):\n \"\"\" Clear database from the given collections. \"\"\"\n if isinstance(collection_name, list):\n for i in collection_name:\n collection = self.db[i]\n collection.drop()\n else:\n collection = self.db[collection_name]\n collection.drop()\n\n print(f\"Коллекции {','.join(collection_name)} успешно удалены.\")\n\n\nif __name__ == \"__main__\":\n\n # Examples of usage:\n class Foo:\n attr = 'A class attribute'\n\n my_data = {'key': 'This is an object for JSON and Mongo'}\n mylist = [\n {\"name\": \"Amy\", \"address\": \"Apple st 652\"},\n {\"name\": \"Hannah\", \"address\": \"Mountain 21\"},\n {\"name\": \"Michael\", \"address\": \"Valley 345\"},\n {\"name\": \"Sandy\", \"address\": \"Ocean blvd 2\"},\n {\"name\": \"Betty\", \"address\": \"Green Grass 1\"},\n {\"name\": \"Richard\", \"address\": \"Sky st 331\"},\n {\"name\": \"Susan\", \"address\": \"One way 98\"},\n {\"name\": \"Vicky\", \"address\": \"Yellow Garden 2\"},\n {\"name\": \"Ben\", \"address\": \"Park Lane 38\"},\n {\"name\": \"William\", \"address\": \"Central st 954\"},\n {\"name\": \"Chuck\", \"address\": \"Main Road 989\"},\n {\"name\": \"Viola\", \"address\": \"Sideway 1633\"}\n ]\n\n FileStorage.save(Foo, \"pickle\", \"new_file\")\n file_pickle_from_storage = FileStorage.read(\"new_file.pickle\", \"pickle\")\n print(file_pickle_from_storage)\n print(file_pickle_from_storage.attr)\n\n FileStorage.save(my_data, \"json\", \"new_file\")\n file_json_from_storage = FileStorage.read(\"new_file.json\", \"json\")\n print(file_json_from_storage)\n\n\n library = MongoDB()\n library.save(my_data, 'pickle', 'first_data')\n library.save(mylist, 'pickle', 'first_data')\n library.save(mylist, 'pickle', 'second_data')\n\n library.save(my_data, 'json', 'ins_manyyyy')\n library.save(mylist, 'json', 'ins_many')\n\n obj1 = library.read('ins_manyyyy', 'json') # ID is not given\n obj2 = library.read(None, 'json', '5e173e1721ffc75aba5faa0c')\n print(obj1, obj2)\n\n library.delete_collection(['pickle', 'json'])\n","sub_path":"14-data-persistence/library.py","file_name":"library.py","file_ext":"py","file_size_in_byte":8199,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"220490617","text":"import curses\nimport io\nimport sys\nimport time\nfrom abc import ABCMeta, abstractmethod\n\nimport atexit\nimport numpy as np\n\nU_BLACK_SQUARE = '\\u25A0' # ■ BLACK SQUARE\nU_FULL_BLOCK = '\\u2588' # █ FULL BLOCK\nU_LOWER_HALF_BLOCK = '\\u2584' # ▄ LOWER HALF BLOCK\nBRIGHTNESS_UNICODE_BLOCK = [\n ' ', # 0\n '▁',\n '▂',\n '▃',\n '▄', # 4\n '▅',\n '▆',\n '▉',\n '█',\n '▇', # 9\n]\nBRIGHTNESS_8BIT = np.linspace(0, 255, num=10, dtype=int)\nBRIGHTNESS = BRIGHTNESS_UNICODE_BLOCK\n\n\ndef ansi_brightness(value):\n return '\\x1b[38;2;{red};0;0m'.format(red=BRIGHTNESS_8BIT[value])\n\n\ndef format_brightness(value, char=U_LOWER_HALF_BLOCK):\n return '{}{char}\\x1b[0m'.format(\n ansi_brightness(value),\n char=char)\n\n\nBRIGHTNESS_8BIT_ANSI = [format_brightness(value) for value in range(0, 10)]\n\n\nclass AbstractRenderer(metaclass=ABCMeta):\n @abstractmethod\n def render(self, buffer: np.ndarray) -> None:\n pass\n\n\nclass ANSIRenderer(AbstractRenderer):\n \"\"\"\n Renders the microbit display using raw ANSI escape codes.\n\n See https://en.wikipedia.org/wiki/ANSI_escape_code#CSI_codes\n \"\"\"\n SPACE = ' ' # For clarity\n TOP_LEFT = '\\u256d'\n TOP_RIGHT = '\\u256e'\n BOTTOM_RIGHT = '\\u256f'\n BOTTOM_LEFT = '\\u2570'\n LEFT = RIGHT = '\\u2502'\n BOTTOM = TOP = '\\u2500'\n LED_CHAR = '\\u25A0' # ■ BLACK SQUARE\n\n MAX_FPS = 60\n\n MARGIN_X = 7\n MARGIN_Y = 1\n LED_X = 9\n LED_Y = 5\n BORDER_WIDTH = 1\n\n def __init__(self):\n self.term_buf = sys.stderr\n self._last_render = time.time()\n\n self.hide_cursor()\n self.write_decoration()\n\n atexit.register(self.show_cursor)\n\n def hide_cursor(self):\n self.term_buf.write('\\x1b[?25l')\n\n def show_cursor(self):\n self.term_buf.write('\\x1b[?12;25h')\n\n def center(self, text, length=None):\n if length is None:\n return text\n\n x_pad, remainder = divmod(length - len(text), 2)\n return (self.SPACE * (x_pad + remainder) +\n text +\n self.SPACE * x_pad)\n\n def pad_x(self, text, corr_l=0, corr_r=0):\n pad_l = self.SPACE * (self.MARGIN_X + corr_l)\n pad_r = self.SPACE * (self.MARGIN_X + corr_r)\n\n return '{left}{pad_l}{text}{pad_r}{right}\\n'.format(\n pad_l=pad_l,\n text=text,\n pad_r=pad_r,\n left=self.LEFT,\n right=self.RIGHT\n )\n\n def write_decoration(self):\n buf = io.StringIO()\n\n # Write top border\n buf.write(self.TOP_LEFT + self.TOP * (self.MARGIN_X * 2 + self.LED_X) +\n self.TOP_RIGHT + '\\n')\n\n # Empty lines for Y margins\n y_pad = [self.pad_x(self.SPACE * self.LED_X)\n for _ in range(0, self.MARGIN_Y)]\n\n # Header and\n buf.write(self.pad_x(self.center('microbit', self.LED_X)))\n buf.write(''.join(y_pad[:-1]))\n\n # Empty area for LED indicators\n for i in range(0, self.LED_Y):\n buf.write(self.pad_x(self.SPACE * self.LED_X))\n\n buf.write(''.join(y_pad))\n\n buf.write(self.BOTTOM_LEFT +\n self.BOTTOM * (self.MARGIN_X * 2 + self.LED_X) +\n self.BOTTOM_RIGHT + '\\n')\n buf.flush()\n\n self.term_buf.write('\\x1b[2J'\n '\\x1b[1;1H')\n self.term_buf.write(buf.getvalue())\n self.term_buf.flush()\n\n def render(self, buffer):\n # Rate limiting\n t_now = time.time()\n delta_t = t_now - self._last_render\n\n if delta_t < 1 / 60:\n return\n\n self._last_render = t_now\n\n buf = io.StringIO()\n\n for y, line in enumerate(buffer):\n for x, value in enumerate(line):\n ansi_x = self.MARGIN_X + x * 2 + self.BORDER_WIDTH + 1\n ansi_y = self.MARGIN_Y + y + self.BORDER_WIDTH + 1\n buf.write('\\x1b[{y};{x}H'.format(x=ansi_x, y=ansi_y))\n buf.write(format_brightness(value))\n # buf.write(\n # self.pad_x(\n # ''.join(' {}'.format(\n # format_brightness(value, self.LED_CHAR)) for\n # value in line),\n # corr_l=-1))\n\n buf.flush()\n self.term_buf.write(buf.getvalue())\n self.term_buf.flush()\n\n\nclass CursesRenderer(AbstractRenderer):\n def __init__(self):\n self._screen = curses.initscr()\n\n curses.start_color()\n curses.use_default_colors()\n\n def render(self, buffer):\n try:\n self._screen.clear()\n for (x, y), value in np.ndenumerate(buffer):\n self._screen.addch(y, x, BRIGHTNESS[value])\n\n self._screen.refresh()\n except Exception:\n self._deinit()\n raise\n\n def _deinit(self):\n curses.endwin()\n","sub_path":"microbit/_renderer.py","file_name":"_renderer.py","file_ext":"py","file_size_in_byte":4885,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"605989191","text":"import random,sys\n\ndef screw(s,n):\n\tf=open('a.html','w')\n\tf.write('

    ')\n\tfor c in s:\n\t\tf.write(c)\n\t\tfor x in range(random.randint(1,n)):\n\t\t\tchar=format(random.randint(768,879), '04x')\n\t\t\tf.write('&#x'+char+';')\n\tf.write('

    ')\n\nscrew(sys.argv[1],int(sys.argv[2]))","sub_path":"crazytext/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":265,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"314475296","text":"import json\nfrom pathlib import Path\n\n\ndef to_path(maybe_str):\n if isinstance(maybe_str, str):\n return Path(maybe_str)\n return maybe_str\n\n\ndef json_load(json_file):\n \"\"\"Load object from json file.\"\"\"\n with to_path(json_file).open(encoding=\"utf8\") as f:\n return json.load(f)\n\n\ndef json_dump(obj, json_file):\n \"\"\"Dump obj to json file.\"\"\"\n with to_path(json_file).open(\"w\", encoding=\"utf8\") as out:\n json.dump(obj, out)\n\n\ndef jsonlines_load(jsonlines_file, max=None, skip=None):\n \"\"\"Load objects from json lines file, i.e. a file with one\n serialized object per line.\"\"\"\n yield from map(json.loads, lines(jsonlines_file, max=max, skip=skip))\n\n\ndef lines(file, max=None, skip=0, apply_func=str.strip):\n \"\"\"Iterate over stripped lines in (text) file.\"\"\"\n from itertools import islice\n if apply_func:\n with open(str(file), encoding=\"utf8\") as f:\n for line in islice(f, skip, max):\n yield apply_func(line)\n else:\n with open(str(file), encoding=\"utf8\") as f:\n for line in islice(f, skip, max):\n yield line\n\n\ndef dict_load(\n file,\n max=None, skip=0, splitter=None, key_apply=None, value_apply=None):\n \"\"\"Load a dictionary from a text file containing one key-value\n pair per line.\"\"\"\n if splitter is not None:\n if isinstance(splitter, (str, bytes)):\n def split(s):\n return s.split(splitter)\n else:\n split = splitter\n else:\n split = str.split\n if key_apply is not None and value_apply is not None:\n def kv(line):\n parts = split(line)\n return key_apply(parts[0]), value_apply(parts[1])\n elif key_apply is not None:\n def kv(line):\n parts = split(line)\n return key_apply(parts[0]), parts[1]\n elif value_apply is not None:\n def kv(line):\n parts = split(line)\n return parts[0], value_apply(parts[1])\n else:\n kv = split\n return dict(map(kv, lines(file, max=max, skip=skip)))\n\n\ndef write_str(string, file, encoding=\"utf8\"):\n \"\"\"Write string to file.\"\"\"\n with open(str(file), \"w\", encoding=encoding) as out:\n out.write(string)\n\n\ndef deserialize_protobuf_instances(cls, protobuf_file, max_bytes=None):\n \"\"\"Deserialze a protobuf file into instances of cls\"\"\"\n from google.protobuf.internal.decoder import _DecodeVarint32\n with open(protobuf_file, \"rb\") as f:\n buf = f.read(max_bytes)\n n = 0\n while n < len(buf):\n msg_len, new_pos = _DecodeVarint32(buf, n)\n n = new_pos\n msg_buf = buf[n:n+msg_len]\n n += msg_len\n c = cls()\n c.ParseFromString(msg_buf)\n yield c\n\n\ndef dump_args(args, file):\n \"\"\"Write argparse args to file.\"\"\"\n with to_path(file).open(\"w\", encoding=\"utf8\") as out:\n json.dump({k: str(v) for k, v in args.__dict__.items()}, out, indent=4)\n\n\ndef mkdir(dir, parents=True, exist_ok=True):\n \"\"\"Convenience function for Path.mkdir\"\"\"\n dir = to_path(dir)\n dir.mkdir(parents=parents, exist_ok=exist_ok)\n return dir\n\n\ndef sentencepiece_load(file):\n \"\"\"Load a SentencePiece model\"\"\"\n from sentencepiece import SentencePieceProcessor\n spm = SentencePieceProcessor()\n spm.Load(str(file))\n return spm\n\n\n# https://stackoverflow.com/a/27077437\ndef cat(infiles, outfile, buffer_size=1024 * 1024 * 100):\n \"\"\"Concatenate infiles and write result to outfile, like Linux cat.\"\"\"\n import shutil\n\n with outfile.open(\"wb\") as out:\n for infile in infiles:\n with infile.open(\"rb\") as f:\n shutil.copyfileobj(f, out, buffer_size)\n","sub_path":"dougu/io.py","file_name":"io.py","file_ext":"py","file_size_in_byte":3682,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"216467521","text":"li1 = set(map(int,input(\"Enter values of list with space between: \").split()))\nli2 = set(map(int,input(\"Enter values of list with space between: \").split()))\nprint(li1,li2)\ncount = 0\nfor i in li1:\n if i in li2:\n count += 1\nif count > 0:\n # print(count)\n print(\"Not Disjoint set\")\nelse:\n print(\"Disjoint set-as intersection is null\")","sub_path":"submissions/sm_103_apoorva/week_13/day_4/check_disjoint.py","file_name":"check_disjoint.py","file_ext":"py","file_size_in_byte":351,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"509283630","text":"import re\nimport sys\n\n#d:a,c,l\ndef pdates(path, output=\"./output/pdate.txt\"):\n with open(output, 'w') as d:\n with open(path, 'r') as r:\n for l in r:\n if re.search(\"(.*)\", l) is not None:\n date = re.search(\"(.*)\", l).group(1)\n aid = re.search(\"(.*)\", l).group(1)\n cat = re.search(\"(.*)\", l).group(1).lower()\n loc = re.search(\"(.*)\", l).group(1).lower()\n d.write(\"%s:%s,%s,%s\\n\" % (date, aid, cat, loc))\n\n\n# p:a,c,l\ndef prices(path, output=\"./output/prices.txt\"):\n with open(output, 'w') as d:\n with open(path, 'r') as r:\n for l in r:\n if re.search(\"(.*)\", l) is not None:\n price = re.search(\"(.*)\", l).group(1).rjust(12)\n aid = re.search(\"(.*)\", l).group(1)\n cat = re.search(\"(.*)\", l).group(1).lower()\n loc = re.search(\"(.*)\", l).group(1).lower()\n d.write(\"%s:%s,%s,%s\\n\" % (price, aid, cat, loc))\n\n# a:ad\ndef ads(path, output=\"./output/ads.txt\"):\n with open(output, 'w') as d:\n with open(path, 'r') as r:\n for l in r:\n if re.search(\"(.*)\", l) is not None:\n a = re.search(\"(.*)\", l).group(1)\n d.write(\"%s:%s\" % (a, l))\n\n\ndef terms(path, output=\"./output/terms.txt\"):\n with open(path, 'r') as f:\n with open(output, 'w') as o:\n for line in f:\n if re.search(\"(.*)\", line) is not None:\n aid = re.search(\"(.*)\", line).group(1)\n term1 = re.sub(\"[^0-9a-zA-Z-_]\", \" \", re.sub(\"&.*?;\", \"\", re.sub(\"&\", \" \", re.search(\"(.*)\", line).group(1).lower()))).split()\n term2 = re.sub(\"[^0-9a-zA-Z-_]\", \" \", re.sub(\"&.*?;\", \"\", re.sub(\"&\", \" \", re.search(\"(.*)\", line).group(1).lower()))).split()\n for term in term1:\n term = re.search(\"([0-9a-zA-Z-_]+)\", term)\n if term is not None:\n if len(term.group(1)) > 2:\n o.write(term.group(1) + \":\" + aid + '\\n')\n for term in term2:\n term = re.search(\"([0-9a-zA-Z-_]+)\", term)\n if term is not None:\n if len(term.group(1)) > 2:\n o.write(term.group(1) + \":\" + aid + '\\n')\n\n\n# Now we can simply do: {from phase1 import init} then call to create all files based on the path to whatever records we're using\ndef init(path):\n terms(path)\n pdates(path)\n prices(path)\n ads(path)\n\n# def tests():\n# inputs = [\"./10records.txt\", \"./1000records.txt\"]\n# mods = [\"10\", \"1000\"]\n# for i in range(len(inputs)):\n# pdates(inputs[i], \"./output/pdate\" + mods[i] + \".txt\")\n# prices(inputs[i], \"./output/prices\" + mods[i] + \".txt\")\n# ads(inputs[i], \"./output/ads\" + mods[i] + \".txt\")\n# terms(inputs[i], \"./output/terms\" + mods[i] + \".txt\")\n\ninit(sys.argv[1])\n\n# def main(argv):\n# records = sys.argv[1]\n","sub_path":"phase1.py","file_name":"phase1.py","file_ext":"py","file_size_in_byte":3327,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"473624687","text":"\"\"\"Unit tests for the Jenkins CI integration.\"\"\"\n\nimport json\nfrom urllib.error import HTTPError\nfrom urllib.parse import urlencode\n\nimport kgb\nimport reviewboard\nfrom django.utils.encoding import force_bytes\nfrom djblets.conditions import ConditionSet, Condition\nfrom reviewboard.reviews.conditions import ReviewRequestRepositoriesChoice\nfrom reviewboard.reviews.signals import status_update_request_run\n\nfrom rbintegrations.jenkinsci.api import JenkinsAPI\nfrom rbintegrations.jenkinsci.integration import JenkinsCIIntegration\nfrom rbintegrations.testing.testcases import IntegrationTestCase\n\n\nclass JenkinsCIIntegrationTests(IntegrationTestCase):\n \"\"\"Tests for Jenkins CI.\"\"\"\n\n integration_cls = JenkinsCIIntegration\n fixtures = ['test_scmtools', 'test_site', 'test_users']\n\n def test_build_new_review_request(self):\n \"\"\"Testing JenkinsCIIntegration builds a new review request\"\"\"\n review_request = self._setup_build_requests()\n review_request.publish(review_request.submitter)\n\n self._check_build_requests(payload={\n 'parameter': [\n {\n 'name': 'REVIEWBOARD_SERVER',\n 'value': 'http://example.com/'\n },\n {\n 'name': 'REVIEWBOARD_REVIEW_ID',\n 'value': review_request.display_id\n },\n {\n 'name': 'REVIEWBOARD_REVIEW_BRANCH',\n 'value': review_request.branch\n },\n {\n 'name': 'REVIEWBOARD_DIFF_REVISION',\n 'value': 1\n },\n {\n 'name': 'REVIEWBOARD_STATUS_UPDATE_ID',\n 'value': 1\n }\n ]\n })\n\n def test_build_new_review_request_with_local_site(self):\n \"\"\"Testing JenkinsCIIntegration builds a new review request with a\n local site\n \"\"\"\n review_request = self._setup_build_requests(with_local_site=True)\n review_request.publish(review_request.submitter)\n\n self._check_build_requests(payload={\n 'parameter': [\n {\n 'name': 'REVIEWBOARD_SERVER',\n 'value': ('http://example.com/s/%s/' %\n self.local_site_name)\n },\n {\n 'name': 'REVIEWBOARD_REVIEW_ID',\n 'value': review_request.display_id\n },\n {\n 'name': 'REVIEWBOARD_REVIEW_BRANCH',\n 'value': review_request.branch\n },\n {\n 'name': 'REVIEWBOARD_DIFF_REVISION',\n 'value': 1\n },\n {\n 'name': 'REVIEWBOARD_STATUS_UPDATE_ID',\n 'value': 1\n }\n ]\n })\n\n def test_manual_run_no_build_on_publish(self):\n \"\"\"Testing lack of JenkinsCIIntegration build when a new review\n request is made with the run manually configuration\n \"\"\"\n review_request = self._setup_build_requests(run_manually=True)\n review_request.publish(review_request.submitter)\n\n self._check_build_requests(expect_fetch_csrf_token=False,\n expect_open_request=False)\n\n def test_build_manual_run(self):\n \"\"\"Testing JenkinsCIIntegration build via a manual trigger\"\"\"\n review_request = self._setup_build_requests(run_manually=True)\n\n status_update = \\\n self.create_status_update(service_id='jenkins-ci',\n review_request=review_request)\n\n status_update_request_run.send(sender=self.__class__,\n status_update=status_update)\n\n self._check_build_requests(payload={\n 'parameter': [\n {\n 'name': 'REVIEWBOARD_SERVER',\n 'value': 'http://example.com/',\n },\n {\n 'name': 'REVIEWBOARD_REVIEW_ID',\n 'value': review_request.display_id,\n },\n {\n 'name': 'REVIEWBOARD_REVIEW_BRANCH',\n 'value': review_request.branch\n },\n {\n 'name': 'REVIEWBOARD_DIFF_REVISION',\n 'value': 1,\n },\n {\n 'name': 'REVIEWBOARD_STATUS_UPDATE_ID',\n 'value': 1,\n }\n ]\n })\n\n def test_build_new_review_request_no_csrf_protection(self):\n \"\"\"Testing that JenkinsCIIntegration builds a new review request\n without csrf protection\n \"\"\"\n review_request = self._setup_build_requests(\n csrf_error=HTTPError('', 404, 'Not found', None, None))\n review_request.publish(review_request.submitter)\n\n self._check_build_requests(\n payload={\n 'parameter': [\n {\n 'name': 'REVIEWBOARD_SERVER',\n 'value': 'http://example.com/',\n },\n {\n 'name': 'REVIEWBOARD_REVIEW_ID',\n 'value': review_request.display_id,\n },\n {\n 'name': 'REVIEWBOARD_REVIEW_BRANCH',\n 'value': review_request.branch\n },\n {\n 'name': 'REVIEWBOARD_DIFF_REVISION',\n 'value': 1,\n },\n {\n 'name': 'REVIEWBOARD_STATUS_UPDATE_ID',\n 'value': 1,\n }\n ],\n },\n expect_csrf_protection=False)\n\n def test_build_new_review_request_crumb_fetch_error(self):\n \"\"\"Testing that JenkinsCIIntegration does not build when fetching the\n csrf token (or crumb) results in a non-404 error code\n \"\"\"\n review_request = self._setup_build_requests(\n csrf_error=HTTPError('', 400, 'Bad request', None, None))\n review_request.publish(review_request.submitter)\n\n self._check_build_requests(expect_open_request=False)\n\n def test_job_name_variables_replaced(self):\n \"\"\"Testing that JenkinsCIIntegration correctly replaces variables in a\n job name\n \"\"\"\n review_request = self._setup_build_requests(\n job_name='{repository}_{branch}_1')\n review_request.publish(review_request.submitter)\n\n self._check_build_requests(\n url='http://localhost:8000/job/Test%20Repo_my-branch_1/build',\n payload={\n 'parameter': [\n {\n 'name': 'REVIEWBOARD_SERVER',\n 'value': 'http://example.com/'\n },\n {\n 'name': 'REVIEWBOARD_REVIEW_ID',\n 'value': review_request.display_id\n },\n {\n 'name': 'REVIEWBOARD_REVIEW_BRANCH',\n 'value': review_request.branch\n },\n {\n 'name': 'REVIEWBOARD_DIFF_REVISION',\n 'value': 1\n },\n {\n 'name': 'REVIEWBOARD_STATUS_UPDATE_ID',\n 'value': 1\n }\n ]\n })\n\n def _create_config(self, job_name=None, with_local_site=False,\n run_manually=False):\n \"\"\"Create an integration config.\n\n Args:\n job_name (string, optional):\n The Jenkins job name, which is used in constructing the\n URL to start a build on Jenkins.\n\n with_local_site (bool, optional):\n Whether to create the configuration for a Local Site.\n\n run_manually (bool, optional):\n Whether to run JenkinsCIIntegration manually.\n\n Returns:\n reviewboard.integrations.models.IntegrationConfig:\n The resulting integration configuration.\n \"\"\"\n choice = ReviewRequestRepositoriesChoice()\n\n condition_set = ConditionSet(conditions=[\n Condition(choice=choice,\n operator=choice.get_operator('any'))\n ])\n\n if with_local_site:\n local_site = self.get_local_site(name=self.local_site_name)\n else:\n local_site = None\n\n config = self.integration.create_config(name='Config 1',\n enabled=True,\n local_site=local_site)\n config.set('conditions', condition_set.serialize())\n config.set('jenkins_job_name', job_name or 'job_1')\n config.set('jenkins_endpoint', 'http://localhost:8000')\n config.set('jenkins_username', 'admin')\n config.set('jenkins_password', 'admin')\n config.set('run_manually', run_manually)\n config.save()\n\n return config\n\n def _setup_build_requests(self, with_local_site=False, run_manually=False,\n job_name=None, csrf_error=None):\n \"\"\"Set up state for build-related tests.\n\n This will set up a repository, review request, integration\n configuration, and spies for a build-related unit test.\n\n Args:\n with_local_site (bool, optional):\n Whether the tests should be performed against a Local Site.\n\n run_manually (bool, optional):\n Whether to create the integration configuration with\n ``run_manually`` set.\n\n job_name (unicode, optional):\n An explicit name or pattern to give the job.\n\n csrf_error (Exception, optional):\n An optional exception to raise for the CSRF request.\n\n If not provided, a successful payload will be returned\n instead.\n\n Returns:\n reviewboard.reviews.models.ReviewRequest:\n The created review request.\n \"\"\"\n repository = self.create_repository(with_local_site=with_local_site)\n review_request = self.create_review_request(\n repository=repository,\n with_local_site=with_local_site)\n\n diffset = self.create_diffset(review_request=review_request)\n diffset.base_commit_id = '8fd69d70f07b57c21ad8733c1c04ae604d21493f'\n diffset.save(update_fields=('base_commit_id',))\n\n self._create_config(with_local_site=with_local_site,\n run_manually=run_manually,\n job_name=job_name)\n self.integration.enable_integration()\n\n # We'll always perform a CSRF check before any build request. This\n # code works under that assumption. Assertions later will confirm\n # them.\n def _handle_csrf(*args, **kwarga):\n if csrf_error:\n raise csrf_error\n\n return json.dumps({\n 'crumb': 'crumb123',\n 'crumbRequestField': 'crumbField',\n }).encode('utf-8')\n\n self.spy_on(\n JenkinsAPI._open_request,\n owner=JenkinsAPI,\n op=kgb.SpyOpMatchInOrder([\n {\n 'call_fake': _handle_csrf,\n },\n {\n 'call_fake': lambda *args, **kwargs: b'',\n },\n ]))\n\n return review_request\n\n def _check_build_requests(self,\n url='http://localhost:8000/job/job_1/build',\n payload=None,\n expect_fetch_csrf_token=True,\n expect_open_request=True,\n expect_csrf_protection=True):\n \"\"\"Check the requests made via the API.\n\n Args:\n url (unicode, optional):\n The expected URL.\n\n This will be ignored if ``expect_open_request`` is ``False``.\n\n payload (dict):\n The expected JSON payload.\n\n This will be ignored if ``expect_open_request`` is ``False``.\n\n expect_fetch_csrf_token (bool, optional):\n Whether to expect :py:meth:`rbintegrations.jenkinsci.api.\n JenkinsAPI._fetch_csrf_token` to be called.\n\n expect_open_request (bool, optional):\n Whether to expect :py:meth:`rbintegrations.jenkinsci.api.\n JenkinsAPI._open_request` to be called.\n\n expect_csrf_protection (bool, optional):\n Whether to expect that CSRF protection was enabled for\n build requests.\n\n Raises:\n AssertionError:\n One of the checks failed.\n \"\"\"\n if expect_fetch_csrf_token and expect_open_request:\n self.assertSpyCallCount(JenkinsAPI._open_request, 2)\n elif expect_fetch_csrf_token or expect_open_request:\n self.assertSpyCallCount(JenkinsAPI._open_request, 1)\n else:\n self.assertSpyNotCalled(JenkinsAPI._open_request)\n\n call_index = 0\n\n # Check the CSRF call.\n if expect_fetch_csrf_token:\n self._check_http_request(\n call_index=call_index,\n url='http://localhost:8000/crumbIssuer/api/json')\n call_index += 1\n\n # Check the build request.\n if expect_open_request:\n if expect_csrf_protection:\n crumb = 'crumb123'\n else:\n crumb = None\n\n self._check_http_request(\n call_index=call_index,\n url=url,\n content_type='application/x-www-form-urlencoded',\n crumb=crumb,\n data=force_bytes(urlencode({\n 'json': json.dumps(payload, sort_keys=True),\n })))\n\n def _check_http_request(self, call_index, url, data=None,\n content_type=None, crumb=None):\n \"\"\"Check the contents of an HTTP request.\n\n This will ensure the request has the expected URL, payload, and\n headers.\n\n Args:\n call_index (int):\n The index of this particular HTTP call.\n\n url (unicode):\n The expected URL.\n\n data (bytes, optional):\n The expected request payload contents.\n\n content_type (unicode, optional):\n The expected value of the :mimeheader:`Content-type` header.\n\n crumb (unicode, optional):\n The expected value of the crumb header from a CSRF\n request.\n\n Raises:\n AssertionError:\n One of the checks failed.\n \"\"\"\n request = JenkinsAPI._open_request.calls[call_index].args[0]\n\n if reviewboard.VERSION[0] >= 4:\n request_url = request.url\n else:\n request_url = request.get_full_url()\n\n self.assertEqual(request_url, url)\n self.assertEqual(request.data, data)\n self.assertEqual(request.headers.get('Content-type'), content_type)\n self.assertEqual(request.headers.get('Crumbfield'), crumb)\n","sub_path":"rbintegrations/jenkinsci/tests.py","file_name":"tests.py","file_ext":"py","file_size_in_byte":15481,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"270820868","text":"from rest_framework import serializers\nfrom .models import Transacoes\n\n#Serializer utilizado para o GET\nclass TransacoesSerializer(serializers.ModelSerializer):\n\tsaldo = serializers.IntegerField()\n\tclass Meta:\n\t\tmodel = Transacoes\n\t\tfields = ('credito', 'descricao_credito', 'debito', 'descricao_debito', 'saldo')\n\n#Serializer utilizado para o POST\nclass DebCredSerializer(serializers.ModelSerializer):\n\tclass Meta:\n\t\tmodel = Transacoes\n\t\tfields = ('credito', 'descricao_credito', 'debito', 'descricao_debito')\t\t","sub_path":"myapi/myapp/serializers.py","file_name":"serializers.py","file_ext":"py","file_size_in_byte":512,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"370258183","text":"\"\"\"\nThis is meant to test resilience and stability of state watchers.\n\nIts hard to test automatically, so we must inspect it ourselves.\n\"\"\"\nimport random\nimport time\n\nimport zproc\n\nTIMEOUT = 10\nSLOW = True\n\nctx = zproc.Context()\nctx.state[\"foobar\"] = 0\n\n\ndef wait_and_stop():\n try:\n test_process.wait(TIMEOUT)\n except TimeoutError:\n test_process.stop()\n print(\"\\n\" * 5, \"-\" * 10, \"\\n\" * 5)\n time.sleep(1)\n\n\n@zproc.atomic\ndef inc(state):\n state[\"foobar\"] += 1\n\n\n@ctx.process\ndef generator(state):\n while True:\n inc(state)\n if SLOW:\n time.sleep(random.random())\n\n\nprint(\"LIVE:\")\n\n\n@ctx.process\ndef test_process(state):\n while True:\n print(state.get_when_change(\"foobar\", live=True), end=\",\", flush=True)\n if SLOW:\n time.sleep(random.random())\n\n\nwait_and_stop()\nprint(\"BUFFERED:\")\n\n\n@ctx.process\ndef test_process(state):\n while True:\n print(state.get_when_change(\"foobar\", live=False), end=\",\", flush=True)\n if SLOW:\n time.sleep(random.random())\n\n\nwait_and_stop()\nprint(\"LIVE:\")\n\n\n@ctx.call_when_change(\"foobar\", stateful=False, live=True)\ndef test_process(foobar):\n print(foobar, end=\",\", flush=True)\n if SLOW:\n time.sleep(random.random())\n\n\nwait_and_stop()\nprint(\"BUFFERED:\")\n\n\n@ctx.call_when_change(\"foobar\", live=False, stateful=False)\ndef test_process(foobar):\n print(foobar, end=\",\", flush=True)\n if SLOW:\n time.sleep(random.random())\n\n\nwait_and_stop()\n","sub_path":"tests/resillience.py","file_name":"resillience.py","file_ext":"py","file_size_in_byte":1495,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"497085134","text":"from flask import Flask,render_template,request,session,redirect,url_for\nfrom flask_mysqldb import MySQL \nfrom datetime import date\nimport string\nimport random\nimport pymsgbox\n\napp = Flask(__name__,template_folder= \"template\")\n\napp.secret_key=\"aniket123\"\napp.config['MYSQL_HOST']='localhost'\napp.config['MYSQL_USER']='root'\napp.config['MYSQL_PASSWORD']='aniket@123'\napp.config['MYSQL_DB']='project'\n\nmysql=MySQL(app)\n\n@app.route('/')\ndef homepage():\n return render_template('homepage.html')\n\n@app.route('/admin')\ndef admin():\n\treturn render_template('admin.html')\n\n@app.route('/addpsychologist',methods=['GET','POST'])\ndef addpsychologist():\n\tif request.method=='POST':\n\t\tfname=request.form['fname']\n\t\tlname=request.form['lname']\n\t\temail=request.form['email']\n\t\tphoneno=request.form['phoneno']\n\t\tpswd=request.form['pswd']\n\t\tgender=request.form['gender']\n\t\tqualification=request.form['qualification']\n\t\texperience=request.form['experience']\n\t\tuid=id_generator()\t\t\n\t\tcur= mysql.connection.cursor()\n\t\tcur.execute(\"insert into user values(%s,%s,%s)\",[uid,email,pswd])\n\t\tcur.connection.commit()\n\t\tcur.execute(\"insert into therapist values(%s,%s,%s,%s,%s,%s,%s)\",[fname,lname,gender,qualification,experience,phoneno,uid])\n\t\tcur.connection.commit()\t\n\t\tcur.close()\n\t\tpymsgbox.alert('Psychologist Added Successfully','Title')\n\t\treturn redirect(url_for(\"admin\"))\t\t\n\treturn render_template('psychologist.html')\n\n@app.route('/psychologicaltest',methods=['GET','POST'])\ndef test1():\n\tcur= mysql.connection.cursor()\n\tcur.execute(\"select question_description from psychotest;\")\n\tres=cur.fetchall()\n\tif \"pscore\" in session:\n\t\tsession.pop(\"pscore\",None)\n\n\tif request.method=='POST':\t\t\n\t\tQ=[\"Q1\",\"Q2\",\"Q3\",\"Q4\",\"Q5\",\"Q6\",\"Q7\",\"Q8\",\"Q9\",\"Q10\",\"Q11\",\"Q12\",\"Q13\",\"Q14\",\"Q15\",\"Q16\",\"Q17\",\"Q18\"]\n\t\tpscore=0\n\t\tfor i in Q:\n\t\t\ta=int(request.form[i])\n\t\t\tpscore=pscore+a\t\t\t\n\t\tuid=session['uid']\n\t\tcur.execute(\"insert into client_test values(%s,%s,%s)\",[uid,1,pscore])\n\t\tcur.connection.commit()\t\n\t\tcur.close()\n\t\tsession['pscore']=pscore\n\t\treturn redirect(url_for(\"test2\"))\n\treturn render_template('test1.html',rs=res,content_type='application/json')\n\n@app.route('/IQtest',methods=['GET','POST'])\ndef test2():\n\tcur= mysql.connection.cursor()\n\tcur.execute(\"select question_description,option1,option2,option3,option4 from iqtest;\")\n\tres=cur.fetchall()\n\tcur.execute(\"select correct_answer from iqtest;\")\n\tres1=cur.fetchall()\n\tif \"iqscore\" in session:\n\t\tsession.pop(\"iqscore\",None)\n\n\tif request.method=='POST':\n\t\tiqscore=0\n\t\tans=[]\n\t\tQ=[\"Q1\",\"Q2\",\"Q3\",\"Q4\",\"Q5\",\"Q6\",\"Q7\",\"Q8\",\"Q9\",\"Q10\",\"Q11\",\"Q12\",\"Q13\",\"Q14\",\"Q15\"]\n\t\tfor i in Q:\n\t\t\tif request.form.get(str(i)) is None:\n\t\t\t\tans.append(0)\n\t\t\telse:\n\t\t\t\tQ1=request.form[str(i)]\n\t\t\t\tans.append(Q1) \n\t\tfor j in range(0,15):\n\t\t\tif ans[j]==res1[j][0] and ans[j]!=0:\n\t\t\t\tiqscore=iqscore+1\n\t\t\telse:\n\t\t\t\tiqscore=iqscore+0\n\t\tuid=session['uid']\n\t\tcur.execute(\"insert into client_test values(%s,%s,%s)\",[uid,2,iqscore])\n\t\tcur.connection.commit()\t\n\t\tcur.close()\n\t\tsession['iqscore']=iqscore\n\t\treturn redirect(url_for(\"result\"))\n\treturn render_template('test2.html',rs=res,content_type='application/json')\n\ndef id_generator(size=6,chars=string.digits):\n\treturn ''.join(random.choice(chars) for x in range(size))\n\n@app.route('/signup',methods=['GET','POST'])\ndef signup():\n\tif request.method=='POST':\n\t\tfname=request.form['fname']\n\t\tmname=request.form['mname']\n\t\tlname=request.form['lname']\n\t\temail=request.form['email']\n\t\tphoneno=request.form['phoneno']\n\t\tpswd=request.form['pswd']\n\t\tDOB=request.form['DOB']\n\t\tgender=request.form['gender']\n\t\tquestion=request.form['question']\n\t\tanswer=request.form['answer']\n\t\tuid=id_generator()\t\t\n\t\tcur= mysql.connection.cursor()\n\t\tcur.execute(\"select EXISTS(select email from user where email=%s)\",[email])\n\t\tres=cur.fetchone()\n\t\tif res[0]==0:\n\t\t\tcur.execute(\"insert into user values(%s,%s,%s)\",[uid,email,pswd])\n\t\t\tcur.connection.commit()\n\t\t\tcur.execute(\"insert into client values(%s,%s,%s,%s,%s,%s,%s,%s,%s)\",[fname,lname,mname,gender,question,answer,phoneno,DOB,uid])\n\t\t\tcur.connection.commit()\t\n\t\t\tcur.close()\n\t\t\treturn redirect(url_for(\"login\"))\n\t\telse:\n\t\t\tpymsgbox.alert('Email id already Registered')\n\t\t\treturn redirect(url_for(\"login\"))\t\t\n\treturn render_template('signup.html')\n\n@app.route('/login',methods=['GET','POST'])\ndef login():\n\tif request.method=='POST':\n\t\temail=request.form['email']\n\t\tpswd=request.form['pswd']\n\t\tif email==\"aniketkudale2805@gmail.com\" and pswd==\"aniket2805\":\n\t\t\tsession['email']=email\t\t\t\n\t\t\treturn redirect(url_for(\"admin\"))\n\t\telse:\n\t\t\tcur= mysql.connection.cursor()\n\t\t\tcur.execute(\"select uid from user where email=%s and pswd=%s\",[email,pswd])\t\n\t\t\tuid=cur.fetchone()\n\t\t\tif uid==None:\n\t\t\t\tpymsgbox.alert('User not Found','Title')\n\t\t\t\treturn redirect(url_for(\"login\"))\n\t\t\telse:\t\n\t\t\t\tcur.execute(\"select EXISTS(select uid from client where uid=%s)\",[uid])\n\t\t\t\tres=cur.fetchone()\n\t\t\t\tcur.execute(\"select EXISTS(select uid from therapist where uid=%s)\",[uid])\n\t\t\t\tres1=cur.fetchone()\n\t\t\t\tif res[0]==1 and res1[0]==0:\n\t\t\t\t\tcur.execute(\"select fname from client where uid=%s\",[uid])\n\t\t\t\t\tf=cur.fetchone()\n\t\t\t\t\tfname=f[0]\n\t\t\t\t\tsession['fname']=fname\n\t\t\t\t\tsession['uid']=uid\n\t\t\t\t\tsession['client']=True\n\t\t\t\t\tcur.close()\n\t\t\t\t\treturn redirect(url_for(\"homepage\"))\n\t\t\t\telif res[0]==0 and res1[0]==1:\n\t\t\t\t\tcur.execute(\"select fname from therapist where uid=%s\",[uid])\n\t\t\t\t\tf=cur.fetchone()\n\t\t\t\t\tfname=f[0]\n\t\t\t\t\tsession['fname']=fname\n\t\t\t\t\tsession['uid']=uid\n\t\t\t\t\tsession['therapist']=True\n\t\t\t\t\tcur.close()\n\t\t\t\t\treturn redirect(url_for(\"homepage\"))\n\treturn render_template(\"login.html\")\n\t\t\n@app.route('/forgetpswd',methods=['GET','POST'])\ndef forgetpswd():\n\tif request.method=='POST':\n\t\temail=request.form['email']\n\t\tquestion=request.form['question']\n\t\tanswer=request.form['answer']\n\t\tnewpswd=request.form['newpswd']\n\t\tcur= mysql.connection.cursor()\n\t\tcur.execute(\"select uid from user natural join client where email=%s and security_question=%s and answer=%s\",[email,question,answer])\t\n\t\tuid=cur.fetchone()\n\t\tcur.execute(\"update user set pswd=%s where uid=%s\",[newpswd,uid])\n\t\tcur.connection.commit()\n\t\tcur.close()\n\t\treturn redirect(url_for(\"login\"))\n\treturn render_template('forgetpswd.html')\n \n@app.route('/changepswd',methods=['GET','POST'])\ndef changepswd():\n\tif request.method=='POST':\n\t\temail=request.form['email']\n\t\toldpswd=request.form['oldpswd']\n\t\tnewpswd=request.form['newpswd']\n\t\tcur= mysql.connection.cursor()\n\t\tcur.execute(\"select uid from user where email=%s and pswd=%s\",[email,oldpswd])\t\n\t\tuid=cur.fetchone()\n\t\tif uid==None:\n\t\t\tpymsgbox.alert('User Not Found','Title')\n\t\t\tcur.close()\n\t\t\treturn redirect(url_for(\"changepswd\"))\n\t\telse:\n\t\t\tcur.execute(\"update user set pswd=%s where uid=%s\",[newpswd,uid])\n\t\t\tcur.connection.commit()\n\t\t\tpymsgbox.alert('Password Changed Successfully','Title')\n\t\t\tcur.close()\n\t\t\treturn redirect(url_for(\"homepage\"))\n\treturn render_template('changepswd.html')\n\n@app.route('/blogs')\ndef blogs():\n return render_template('blogs.html')\n\n@app.route('/help')\ndef help():\n\tcur= mysql.connection.cursor()\n\tcur.execute(\"select uid,fname,lname from therapist;\")\n\tres=cur.fetchall()\n\tl=len(res)\n\tcur.close()\t\t\n\treturn render_template('help.html',rs=res,length=l,content_type='application/json')\n\n@app.route('/messages')\ndef messages():\n\tnames=[]\n\tuid=session['uid']\n\tcur= mysql.connection.cursor()\n\tcur.execute(\"select uid,msg_desc,date(datetime),Time(datetime) from message where reciever=%s;\",[uid])\n\tres=cur.fetchall()\n\tlength=len(res)\n\tfor i in range(length):\n\t\tcur.execute(\"select fname from client where uid=%s UNION select fname from therapist where uid=%s;\",[res[i][0],res[i][0]])\n\t\tnames.append(cur.fetchone())\t\n\tcur.close()\t\t\n\treturn render_template('message.html',rs=res,fname=names,j=length,content_type='application/json')\n\n@app.route('/chat/',methods=['GET','POST'])\ndef chat(to):\n\tif request.method=='POST':\n\t\tTo=to\n\t\tmessage=request.form['message']\n\t\tcur= mysql.connection.cursor()\n\t\tcur.execute(\"select uid from therapist where fname=%s UNION select uid from client where fname=%s;\",[To,To])\n\t\tres=cur.fetchone()\n\t\treciever=res[0]\n\t\tuid=session['uid']\n\t\tmsgid=id_generator()\t\t\n\t\tcur.execute(\"insert into message values(%s,%s,%s,%s,now())\",[msgid,uid,message,reciever])\n\t\tcur.connection.commit()\n\t\tcur.close()\t\t\n\t\tpymsgbox.alert('Message Sent','Title')\n\t\treturn redirect(url_for(\"messages\"))\n\treturn render_template('chat.html',To=to)\n\n@app.route('/result',methods=['GET','POST'])\ndef result():\n\tcur= mysql.connection.cursor()\n\tcur.execute(\"select uid,fname,lname from therapist;\")\n\tres=cur.fetchall()\n\tl=len(res)\n\tcur.close()\t\t\n\treturn render_template('result.html',rs=res,length=l,content_type='application/json')\n\n@app.route('/editprofile',methods=['GET','POST'])\ndef editprofile():\n\tif request.method=='POST':\n\t\tfname=request.form['fname']\n\t\tmname=request.form['mname']\n\t\tlname=request.form['lname']\n\t\temail=request.form['email']\n\t\tphoneno=request.form['phoneno']\n\t\tpswd=request.form['pswd']\n\t\tDOB=request.form['DOB']\n\t\tgender=request.form['gender']\n\t\tquestion=request.form['question']\n\t\tanswer=request.form['answer']\t\t\n\t\tcur= mysql.connection.cursor()\n\t\tuid=session['uid']\n\t\tcur.execute(\"update user set email=%s,pswd=%s where uid=%s\",[email,pswd,uid])\n\t\tcur.connection.commit()\n\t\tcur.execute(\"update client set fname=%s,lname=%s,mname=%s,gender=%s,security_question=%s,answer=%s,phone_number=%s,dob=%s where uid=%s\",[fname,lname,mname,gender,question,answer,phoneno,DOB,uid])\n\t\tcur.connection.commit()\n\t\tcur.close()\n\t\tpymsgbox.alert('Profile Updated Successfully','Title')\n\t\treturn redirect(url_for(\"homepage\"))\t\t \n\treturn render_template('editprofile.html')\n\n@app.route('/logout')\ndef logout():\n\tif \"email\" in session:\n\t\tsession.pop(\"email\",None)\n\tif \"uid\" in session:\n\t\tsession.pop(\"uid\",None)\n\treturn render_template('homepage.html')\n\nif __name__ == \"__main__\":\n\tapp.run(debug=True)\n","sub_path":"homepage.py","file_name":"homepage.py","file_ext":"py","file_size_in_byte":9821,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"414442567","text":"def pancake_flipper(S, K):\n \"\"\"\n Returns the minimum number of K sign flips that are needed to have only \n positive signs in the String. When one flip is performed, exactly K signs \n must be flipped. Returns -1 if not possible.\n \"\"\"\n if K > len(S):\n return 0\n counter = 0\n for i in range(len(S)-K+1):\n if S[i] == '-':\n temp = S[i:i+K].replace('-', '#')\n temp = temp.replace('+', '-')\n temp = temp.replace('#', '+')\n S = S[:i] + temp + S[i+K:]\n counter +=1\n print(\"S after is {}\".format(S))\n if '-' in S:\n return -1\n else:\n return counter\n\ndef main():\n s = \"-+-+-\"\n t = \"---+-++-\"\n u = \"+++++\"\n print(pancake_flipper(s,4))\n print(pancake_flipper(t,3))\n print(pancake_flipper(u,4))\n\nif __name__ == \"__main__\":\n main()","sub_path":"code_jam.py","file_name":"code_jam.py","file_ext":"py","file_size_in_byte":852,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"647546350","text":"##############################################################################\n# File: coding.py #\n# Description: functions to be called by coding.vim #\n# #\n# Usage: #\n# #\n# Author: OU Yuyuan #\n# Created: Fri May 25 08:38:46 UTC+8 2012 #\n# Last Change: 2012-09-30 23:29:45 CST \n##############################################################################\n\n\ndef updateTime(strings,file_info):\n authorpattern = re.compile(r'.*[\\W_]*\\s*author[\\W_]?\\s*(%s)?'\\\n %self.codeSignature,re.I|re.DOTALL)\n if not authorpatthern.match(''.join(strings)): # not the author's code\n return ''\n\n changepattern = re.compile(r'.*[\\W_]*\\s*last\\s*change[\\W_]?\\s*',\\\n re.I|re.DOTALL)\n filepattern =\\\n re.compile(r'.*(?P[\\W_]*\\s*file\\:\\s*)(?P\\w+)',\\\n re.IGNORECASE|re.DOTALL)\n\n filematch = filepattern.match(cb[line]).group('filetag')\n mainname = filepattern.match(cb[line]).group('mainname')\n\n time = os.popen('env LANG=en_US.UTF-8 date').read().rstrip().replace('CST','UTC+8')\n if changeflag:\n textwidth = len(cb[changeline])\n newchange = changematch.rstrip()\n newchange += ' ' + time\n spaces = (textwidth - len(newchange) - len(self.comment[self.filetype()]))*' '\n newchange += spaces + self.comment[self.filetype()] + '\\n'\n cb[changeline] = newchange\n if fileflag and mainname != self.mainname():\n textwidth = len(cb[fileline])\n newfile = filematch.rstrip() + ' '\n newfile += self.filename()\n spaces = (textwidth - len(newfile) - len(self.comment[self.filetype()]))*' '\n newfile += spaces + self.comment[self.filetype()] + '\\n'\n cb[fileline] = newfile\n\n\ndef creatTitle(commentchar,textwidth):\n commentchar = self.comment[self.filetype()]\n commentline = (self.textwidth/len(commentchar))*commentchar\n delimitline = commentchar + (self.textwidth-2*len(commentchar))*' ' + \\\n commentchar\n textwidth = self.textwidth\n sourcefile = commentchar + ' File: ' + self.filename()\n sourcefile += (textwidth - len(sourcefile) - len(commentchar))*' ' + commentchar\n description = commentchar + ' Description: '\n description+= (textwidth - len(description) - len(commentchar))*' ' + commentchar\n usage = ''\n usage = commentchar + ' Usage: '\n usage += (textwidth - len(usage) - 1)*' ' + commentchar\n author = commentchar + ' Author: '\n author += self.codeSignature\n author += (textwidth - len(author) - len(commentchar))*' ' + commentchar\n created = commentchar + ' Created: '\n created+= os.popen('env LANG=en_US.UTF-8 date').read().rstrip().replace('CST','UTC+8')\n created+= (textwidth - len(created) - len(commentchar))*' ' + commentchar\n change = commentchar + ' Last Change: '\n change += os.popen('env LANG=en_US.UTF-8 date').read().rstrip().replace('CST','UTC+8')\n change += (textwidth - len(change) - len(commentchar))*' ' + commentchar\n\n title = [ ]\n title.append(commentline)\n if self.filetype() == 'txt':\n title.append(delimitline)\n title.append(sourcefile)\n title.append(description) \n title.append(delimitline)\n if usage:\n title.append(usage)\n title.append(delimitline)\n title.append(author)\n title.append(created)\n title.append(change)\n title.append(commentline)\n appendline = 0\n while re.match(r'^[\\W_]\\!',self.curbuff()[appendline]):\n appendline +=1\n if self.filetype() == 'cls' and re.match(r'^\\s*\\%+',self.curbuff()[appendline]):\n appendline +=1\n elif self.filetype() == 'ntx' and re.match(r'^\\*\\w+\\*',self.curbuff()[appendline]):\n appendline +=1\n else: pass\n self.curbuff().append(title,appendline)\n #entlen = max(list(map(len,maps.values())))\n\ndef insertMapping(commentchar,textwidth):\n try: \n if self.filetype() not in self.comment.keys():\n return None\n except:\n return None\n commentchar = self.comment[self.filetype()]\n commentline = (self.textwidth/len(commentchar))*commentchar\n delimitline = commentchar + (self.textwidth-2*len(commentchar))*' ' + commentchar\n enter = ''\n if self.filetype() == 'vim':\n # in case that the new line will contain the comment character in the head\n enter += 'S' \n elif self.filetype() == 'tex':\n asymptote =r'\\begin{center}\\begin{asy}\\end{asy}\\end{center}'\n asymptote += r'\\begin{Verbatim}[frame=single,framerule=0.5mm,rulecolor=\\color{cyan}]'\n asymptote += r'\\end{Verbatim}'\n else:\n pass\n section = 3*(commentline + enter) + 1*(commentchar+enter)\n subsec = 2*(commentline + enter) + 1*(commentchar+enter)\n subsub = (commentline + enter) + 1*(commentchar+enter)\n\n\n insertmaps = {}\n insertmaps[';se'] = section\n insertmaps[';su'] = subsec\n insertmaps[';ss'] = subsub\n if self.filetype() == 'tex':\n insertmaps[';asy'] = asymptote\n else:\n pass\n","sub_path":"python/old/coding.py","file_name":"coding.py","file_ext":"py","file_size_in_byte":5468,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"535245964","text":"import numpy as np\nimport math\nimport scipy\nimport scipy.signal as signal\nimport scipy.ndimage\nimport arrus.metadata\nimport arrus.devices.cpu\nimport arrus.devices.gpu\nimport arrus.kernels.imaging\n\n\nclass Pipeline:\n \"\"\"\n Imaging pipeline.\n\n Processes given data,metadata using a given sequence of steps.\n The processing will be performed on a given device ('placement').\n \"\"\"\n def __init__(self, steps, placement=None):\n self.steps = steps\n if placement is not None:\n self.set_placement(placement)\n\n def __call__(self, data):\n for step in self.steps:\n data = step(data)\n return data\n\n def initialize(self, const_metadata):\n input_shape = const_metadata.input_shape\n input_dtype = const_metadata.dtype\n for step in self.steps:\n const_metadata = step._prepare(const_metadata)\n # Force cupy to recompile kernels before running the pipeline.\n init_array = self.num_pkg.zeros(input_shape, dtype=input_dtype)+1000\n self.__call__(init_array)\n return const_metadata\n\n def set_placement(self, device):\n \"\"\"\n Sets the pipeline to be executed on a particular device.\n\n :param device: device on which the pipeline should be executed\n \"\"\"\n self.placement = device\n # Initialize steps with a proper library.\n if isinstance(self.placement, arrus.devices.gpu.GPU):\n import cupy as cp\n import cupyx.scipy.ndimage as cupy_scipy_ndimage\n pkgs = dict(num_pkg=cp, filter_pkg=cupy_scipy_ndimage)\n elif isinstance(self.placement, arrus.devices.cpu.CPU):\n import scipy.ndimage\n pkgs = dict(num_pkg=np, filter_pkg=scipy.ndimage)\n else:\n raise ValueError(f\"Unsupported device: {device}\")\n for step in self.steps:\n step.set_pkgs(**pkgs)\n self.num_pkg = pkgs['num_pkg']\n self.filter_pkg = pkgs['filter_pkg']\n\n\nclass BandpassFilter:\n \"\"\"\n Bandpass filtering to apply to signal data.\n\n A bandwidth [0.5, 1.5]*center_frequency is currently used.\n\n The filtering is performed along the last axis.\n\n Currently only FIR filter is available.\n \"\"\"\n def __init__(self, numtaps=7, bounds=(0.5, 1.5), filter_type=\"butter\",\n num_pkg=None, filter_pkg=None):\n \"\"\"\n Bandpass filter constructor.\n\n :param bounds: determines filter's frequency boundaries,\n e.g. setting 0.5 will give a bandpass filter\n [0.5*center_frequency, 1.5*center_frequency].\n \"\"\"\n self.taps = None\n self.numtaps = numtaps\n self.bound_l, self.bound_r = bounds\n self.filter_type = filter_type\n self.xp = num_pkg\n self.filter_pkg = filter_pkg\n\n def set_pkgs(self, num_pkg, filter_pkg, **kwargs):\n self.xp = num_pkg\n self.filter_pkg = filter_pkg\n\n def _prepare(self, const_metadata: arrus.metadata.ConstMetadata):\n l, r = self.bound_l, self.bound_r\n center_frequency = const_metadata.context.sequence.pulse.center_frequency\n sampling_frequency = const_metadata.data_description.sampling_frequency\n # FIXME(pjarosik) implement iir filter\n taps, _ = scipy.signal.butter(\n 2,\n [l * center_frequency, r * center_frequency],\n btype='bandpass', fs=sampling_frequency)\n self.taps = self.xp.asarray(taps).astype(self.xp.float32)\n return const_metadata\n\n def __call__(self, data):\n return self.filter_pkg.convolve1d(data.astype(self.xp.float32),\n self.taps, axis=-1,\n mode='constant')\n\n\nclass FirFilter:\n\n def __init__(self, taps, num_pkg=None, filter_pkg=None):\n \"\"\"\n Bandpass filter constructor.\n\n :param bounds: determines filter's frequency boundaries,\n e.g. setting 0.5 will give a bandpass filter\n [0.5*center_frequency, 1.5*center_frequency].\n \"\"\"\n self.taps = taps\n self.xp = num_pkg\n self.filter_pkg = filter_pkg\n self.convolve1d_func = None\n self.dumped = 0\n\n def set_pkgs(self, num_pkg, filter_pkg, **kwargs):\n self.xp = num_pkg\n self.filter_pkg = filter_pkg\n\n def _prepare(self, const_metadata: arrus.metadata.ConstMetadata):\n if self.xp == np:\n raise ValueError(\"This operation is NYI for CPU\")\n import cupy as cp\n self.taps = cp.asarray(self.taps).astype(cp.float32)\n n_taps = len(self.taps)\n\n n_frames, n_channels, n_samples = const_metadata.input_shape\n total_n_samples = n_frames*n_channels*n_samples\n\n fir_output_buffer = cp.zeros(const_metadata.input_shape, dtype=cp.float32)\n from arrus.utils.fir import (\n run_fir_int16,\n get_default_grid_block_size_fir_int16,\n get_default_shared_mem_size_fir_int16\n )\n grid_size, block_size = get_default_grid_block_size_fir_int16(\n n_samples,\n total_n_samples)\n shared_memory_size = get_default_shared_mem_size_fir_int16(\n n_samples, n_taps)\n\n def gpu_convolve1d(data):\n data = cp.ascontiguousarray(data)\n run_fir_int16(\n grid_size, block_size,\n (fir_output_buffer, data, n_samples,\n total_n_samples, self.taps, n_taps),\n shared_memory_size)\n return fir_output_buffer\n self.convolve1d_func = gpu_convolve1d\n return const_metadata\n\n def __call__(self, data):\n return self.convolve1d_func(data)\n\n\nclass QuadratureDemodulation:\n \"\"\"\n Quadrature demodulation (I/Q decomposition).\n \"\"\"\n def __init__(self, num_pkg=None):\n self.mod_factor = None\n self.xp = num_pkg\n\n def set_pkgs(self, num_pkg, **kwargs):\n self.xp = num_pkg\n\n def _is_prepared(self):\n return self.mod_factor is not None\n\n def _prepare(self, const_metadata):\n xp = self.xp\n fs = const_metadata.data_description.sampling_frequency\n fc = const_metadata.context.sequence.pulse.center_frequency\n _, _, n_samples = const_metadata.input_shape\n t = (xp.arange(0, n_samples) / fs).reshape(1, 1, -1)\n self.mod_factor = (2 * xp.cos(-2 * xp.pi * fc * t)\n + 2 * xp.sin(-2 * xp.pi * fc * t) * 1j)\n self.mod_factor = self.mod_factor.astype(xp.complex64)\n return const_metadata.copy(is_iq_data=True, dtype=\"complex64\")\n\n def __call__(self, data):\n return self.mod_factor * data\n\n\nclass Decimation:\n \"\"\"\n Decimation + CIC (Cascade Integrator-Comb) filter.\n\n See: https://en.wikipedia.org/wiki/Cascaded_integrator%E2%80%93comb_filter\n \"\"\"\n\n def __init__(self, decimation_factor, cic_order, num_pkg=None, impl=\"legacy\"):\n \"\"\"\n Decimation op constructor.\n\n :param decimation_factor: decimation factor to apply\n :param cic_order: CIC filter order\n \"\"\"\n self.decimation_factor = decimation_factor\n self.cic_order = cic_order\n self.xp = num_pkg\n self.impl = impl\n if self.impl == \"legacy\":\n self._decimate = self._legacy_decimate\n elif self.impl == \"fir\":\n self._decimate = self._fir_decimate\n\n def set_pkgs(self, num_pkg, filter_pkg, **kwargs):\n self.xp = num_pkg\n self.filter_pkg = filter_pkg # not used by the GPU implementation (custom kernel for complex input data)\n\n def _prepare(self, const_metadata):\n new_fs = (const_metadata.data_description.sampling_frequency\n / self.decimation_factor)\n new_signal_description = arrus.metadata.EchoDataDescription(\n sampling_frequency=new_fs, custom=\n const_metadata.data_description.custom)\n\n n_frames, n_channels, n_samples = const_metadata.input_shape\n total_n_samples = n_frames*n_channels*n_samples\n\n output_shape = n_frames, n_channels, math.ceil(n_samples/self.decimation_factor)\n\n # CIC FIR coefficients\n if self.impl == \"fir\":\n cicFir = self.xp.array([1], dtype=self.xp.float32)\n cicFir1 = self.xp.ones(self.decimation_factor, dtype=self.xp.float32)\n for i in range(self.cic_order):\n cicFir = self.xp.convolve(cicFir, cicFir1, 'full')\n fir_taps = cicFir\n n_fir_taps = len(fir_taps)\n if self.xp == np:\n def _cpu_fir_filter(data):\n return self.filter_pkg.convolve1d(\n np.real(data), fir_taps,\n axis=-1, mode='constant',\n cval=0, origin=-1) \\\n + self.filter_pkg.convolve1d(np.imag(data),\n fir_taps, axis=-1,\n mode='constant', cval=0,\n origin=-1)*1j\n # CPU\n self._fir_filter = _cpu_fir_filter\n else:\n # GPU\n import cupy as cp\n _fir_output_buffer = cp.zeros(const_metadata.input_shape,\n dtype=cp.complex64)\n # Kernel settings\n from arrus.utils.fir import (\n get_default_grid_block_size,\n get_default_shared_mem_size,\n run_fir)\n grid_size, block_size = get_default_grid_block_size(n_samples, total_n_samples)\n shared_memory_size = get_default_shared_mem_size(n_samples, n_fir_taps)\n\n def _gpu_fir_filter(data):\n run_fir(grid_size, block_size,\n (_fir_output_buffer, data, n_samples,\n total_n_samples, fir_taps, n_fir_taps),\n shared_memory_size)\n return _fir_output_buffer\n\n self._fir_filter = _gpu_fir_filter\n return const_metadata.copy(data_desc=new_signal_description,\n input_shape=output_shape)\n\n def __call__(self, data):\n return self._decimate(data)\n\n def _fir_decimate(self, data):\n fir_output = self._fir_filter(data)\n data_out = fir_output[:, :, 0::self.decimation_factor]\n return data_out\n\n def _legacy_decimate(self, data):\n data_out = data\n for i in range(self.cic_order):\n data_out = self.xp.cumsum(data_out, axis=-1)\n data_out = data_out[:, :, 0::self.decimation_factor]\n for i in range(self.cic_order):\n data_out[:, :, 1:] = self.xp.diff(data_out, axis=-1)\n return data_out\n\n\nclass RxBeamforming:\n \"\"\"\n Rx beamforming.\n\n Expected input data shape: n_emissions, n_rx, n_samples\n\n Currently the beamforming op works only for LIN sequence output data.\n \"\"\"\n\n def __init__(self, num_pkg=None):\n self.delays = None\n self.buffer = None\n self.rx_apodization = None\n self.xp = num_pkg\n self.interp1d_func = None\n\n def set_pkgs(self, num_pkg, **kwargs):\n self.xp = num_pkg\n if self.xp is np:\n import scipy.interpolate\n\n def numpy_interp1d(input, samples, output):\n n_samples = input.shape[-1]\n x = np.arange(0, n_samples)\n interpolator = scipy.interpolate.interp1d(\n x, input, kind=\"linear\", bounds_error=False,\n fill_value=0.0)\n interp_values = interpolator(samples)\n n_scanlines, _, n_samples = interp_values.shape\n interp_values = np.reshape(interp_values, (n_scanlines, n_samples))\n output[:] = interp_values\n\n self.interp1d_func = numpy_interp1d\n else:\n import cupy as cp\n if self.xp != cp:\n raise ValueError(f\"Unhandled numerical package: {self.xp}\")\n import arrus.utils.interpolate\n self.interp1d_func = arrus.utils.interpolate.interp1d\n\n def _prepare(self, const_metadata: arrus.metadata.ConstMetadata):\n # TODO verify that all angles, focal points are the same\n # TODO make sure start_sample is computed appropriately\n context = const_metadata.context\n probe_model = const_metadata.context.device.probe.model\n seq = const_metadata.context.sequence\n raw_seq = const_metadata.context.raw_sequence\n medium = const_metadata.context.medium\n rx_aperture_center_element = np.array(seq.rx_aperture_center_element)\n\n self.n_tx, self.n_rx, self.n_samples = const_metadata.input_shape\n self.is_iq = const_metadata.is_iq_data\n if self.is_iq:\n buffer_dtype = self.xp.complex64\n else:\n buffer_dtype = self.xp.float32\n\n # -- Output buffer\n self.buffer = self.xp.zeros((self.n_tx, self.n_rx * self.n_samples),\n dtype=buffer_dtype)\n\n # -- Delays\n acq_fs = (const_metadata.context.device.sampling_frequency\n / seq.downsampling_factor)\n fs = const_metadata.data_description.sampling_frequency\n fc = seq.pulse.center_frequency\n n_periods = seq.pulse.n_periods\n if seq.speed_of_sound is not None:\n c = seq.speed_of_sound\n else:\n c = medium.speed_of_sound\n tx_angle = 0\n start_sample = seq.rx_sample_range[0]\n rx_aperture_origin = _get_rx_aperture_origin(seq)\n\n _, _, tx_delay_center = arrus.kernels.imaging.compute_tx_parameters(\n seq, probe_model, c)\n\n burst_factor = n_periods / (2 * fc)\n # -start_sample compensates the fact, that the data indices always start from 0\n initial_delay = - start_sample / acq_fs\n if seq.init_delay == \"tx_start\":\n burst_factor = n_periods / (2 * fc)\n _, _, tx_delay_center = arrus.kernels.imaging.compute_tx_parameters(\n seq, probe_model, c)\n initial_delay += tx_delay_center + burst_factor\n elif not seq.init_delay == \"tx_center\":\n raise ValueError(f\"Unrecognized init_delay value: {initial_delay}\")\n\n radial_distance = (\n (start_sample / acq_fs + np.arange(0, self.n_samples) / fs)\n * c / 2\n )\n x_distance = (radial_distance * np.sin(tx_angle)).reshape(1, -1)\n z_distance = radial_distance * np.cos(tx_angle).reshape(1, -1)\n\n origin_offset = (rx_aperture_origin[0]\n - (seq.rx_aperture_center_element[0]))\n # New coordinate system: origin: rx aperture center\n element_position = ((np.arange(0, self.n_rx) + origin_offset)\n * probe_model.pitch)\n element_position = element_position.reshape((self.n_rx, 1))\n if not probe_model.is_convex_array():\n element_angle = np.zeros((self.n_rx, 1))\n element_x = element_position\n element_z = np.zeros((self.n_rx, 1))\n else:\n element_angle = element_position / probe_model.curvature_radius\n element_x = probe_model.curvature_radius * np.sin(element_angle)\n element_z = probe_model.curvature_radius * (\n np.cos(element_angle) - 1)\n\n tx_distance = radial_distance\n rx_distance = np.sqrt(\n (x_distance - element_x) ** 2 + (z_distance - element_z) ** 2)\n\n self.t = (tx_distance + rx_distance) / c + initial_delay\n self.delays = self.t * fs # in number of samples\n total_n_samples = self.n_rx * self.n_samples\n # Move samples outside the available area\n self.delays[np.isclose(self.delays, self.n_samples-1)] = self.n_samples-1\n self.delays[self.delays > self.n_samples-1] = total_n_samples + 1\n # (RF data will also be unrolled to a vect. n_rx*n_samples elements,\n # row-wise major order).\n self.delays = self.xp.asarray(self.delays)\n self.delays += self.xp.arange(0, self.n_rx).reshape(self.n_rx, 1) \\\n * self.n_samples\n self.delays = self.delays.reshape(-1, self.n_samples * self.n_rx) \\\n .astype(self.xp.float32)\n # Apodization\n lambd = c / fc\n max_tang = math.tan(\n math.asin(min(1, 2 / 3 * lambd / probe_model.pitch)))\n rx_tang = np.abs(np.tan(np.arctan2(x_distance - element_x,\n z_distance - element_z) - element_angle))\n rx_apodization = (rx_tang < max_tang).astype(np.float32)\n rx_apod_sum = np.sum(rx_apodization, axis=0)\n rx_apod_sum[rx_apod_sum == 0] = 1\n rx_apodization = rx_apodization/(rx_apod_sum.reshape(1, self.n_samples))\n self.rx_apodization = self.xp.asarray(rx_apodization)\n # IQ correction\n self.t = self.xp.asarray(self.t)\n self.iq_correction = self.xp.exp(1j * 2 * np.pi * fc * self.t) \\\n .astype(self.xp.complex64)\n # Create new output shape\n return const_metadata.copy(input_shape=(self.n_tx, self.n_samples))\n\n def __call__(self, data):\n data = data.copy().reshape(self.n_tx, self.n_rx * self.n_samples)\n\n self.interp1d_func(data, self.delays, self.buffer)\n out = self.buffer.reshape((self.n_tx, self.n_rx, self.n_samples))\n if self.is_iq:\n out = out * self.iq_correction\n out = out * self.rx_apodization\n out = self.xp.sum(out, axis=1)\n return out.reshape((self.n_tx, self.n_samples))\n\n\nclass EnvelopeDetection:\n \"\"\"\n Envelope detection (Hilbert transform).\n\n Currently this op works only for I/Q data (complex64).\n \"\"\"\n\n def __init__(self, num_pkg=None):\n self.xp = num_pkg\n\n def set_pkgs(self, num_pkg, **kwargs):\n self.xp = num_pkg\n\n def _prepare(self, const_metadata: arrus.metadata.ConstMetadata):\n return const_metadata.copy(is_iq_data=False)\n\n def __call__(self, data):\n if data.dtype != self.xp.complex64:\n raise ValueError(\n f\"Data type {data.dtype} is currently not supported.\")\n return self.xp.abs(data)\n\n\nclass Transpose:\n \"\"\"\n Data transposition.\n \"\"\"\n\n def __init__(self, axes=None):\n self.axes = axes\n self.xp = None\n\n def set_pkgs(self, num_pkg, **kwargs):\n self.xp = num_pkg\n\n def _prepare(self, const_metadata):\n input_shape = const_metadata.input_shape\n axes = list(range(len(input_shape)))[::-1] if self.axes is None else self.axes\n output_shape = tuple(input_shape[ax] for ax in axes)\n return const_metadata.copy(input_shape=output_shape)\n\n def __call__(self, data):\n return self.xp.transpose(data, self.axes)\n\n\nclass ScanConversion:\n \"\"\"\n Scan conversion (interpolation to target mesh).\n\n Currently linear interpolation is used by default, values outside\n the input mesh will be set to 0.0.\n\n Currently the op is implement for CPU only.\n :param x_grid: a vector of grid points along OX axis [m]\n :param z_grid: a vector of grid points along OZ axis [m]\n \"\"\"\n\n def __init__(self, x_grid, z_grid):\n self.dst_points = None\n self.dst_shape = None\n self.x_grid = x_grid.reshape(1, -1)\n self.z_grid = z_grid.reshape(1, -1)\n self.is_gpu = False\n\n def set_pkgs(self, num_pkg, **kwargs):\n if num_pkg != np:\n self.is_gpu = True\n # Ignoring provided num. package - currently CPU implementation is\n # available only.\n\n def _prepare(self, const_metadata: arrus.metadata.ConstMetadata):\n probe = const_metadata.context.device.probe.model\n medium = const_metadata.context.medium\n data_desc = const_metadata.data_description\n\n if not probe.is_convex_array():\n raise ValueError(\n \"Scan conversion currently works for convex probes data only.\")\n\n n_samples, _ = const_metadata.input_shape\n seq = const_metadata.context.sequence\n custom_data = const_metadata.context.custom_data\n\n acq_fs = (const_metadata.context.device.sampling_frequency\n / seq.downsampling_factor)\n fs = data_desc.sampling_frequency\n\n start_sample = seq.rx_sample_range[0]\n\n if seq.speed_of_sound is not None:\n c = seq.speed_of_sound\n else:\n c = medium.speed_of_sound\n\n tx_ap_cent_ang, _, _ = arrus.kernels.imaging.get_tx_aperture_center_coords(seq, probe)\n\n z_grid_moved = self.z_grid.T + probe.curvature_radius - np.max(\n probe.element_pos_z)\n\n self.radGridIn = (\n (start_sample / acq_fs + np.arange(0, n_samples) / fs)\n * c / 2)\n\n self.azimuthGridIn = tx_ap_cent_ang\n azimuthGridOut = np.arctan2(self.x_grid, z_grid_moved)\n radGridOut = (np.sqrt(self.x_grid ** 2 + z_grid_moved ** 2)\n - probe.curvature_radius)\n\n dst_points = np.dstack((radGridOut, azimuthGridOut))\n w, h, d = dst_points.shape\n self.dst_points = dst_points.reshape((w * h, d))\n self.dst_shape = len(self.z_grid.squeeze()), len(self.x_grid.squeeze())\n return const_metadata.copy(input_shape=self.dst_shape)\n\n def __call__(self, data):\n if self.is_gpu:\n data = data.get()\n data[np.isnan(data)] = 0.0\n self.interpolator = scipy.interpolate.RegularGridInterpolator(\n (self.radGridIn, self.azimuthGridIn), data, method=\"linear\",\n bounds_error=False, fill_value=0)\n return self.interpolator(self.dst_points).reshape(self.dst_shape)\n\n\nclass LogCompression:\n \"\"\"\n Converts to decibel scale.\n \"\"\"\n def __init__(self):\n pass\n\n def set_pkgs(self, **kwargs):\n # Intentionally ignoring num. package -\n # currently numpy is available only.\n pass\n\n def _prepare(self, const_metadata: arrus.metadata.ConstMetadata):\n return const_metadata\n\n def __call__(self, data):\n if not isinstance(data, np.ndarray):\n data = data.get()\n data[data == 0] = 1e-9\n return 20 * np.log10(data)\n\n\nclass DynamicRangeAdjustment:\n\n def __init__(self, min=20, max=80):\n self.min = min\n self.max = max\n self.xp = None\n\n def set_pkgs(self, num_pkg, **kwargs):\n self.xp = num_pkg\n\n def _prepare(self, const_metadata: arrus.metadata.ConstMetadata):\n return const_metadata\n\n def __call__(self, data):\n return self.xp.clip(data, a_min=self.min, a_max=self.max)\n\n\nclass ToGrayscaleImg:\n\n def __init__(self):\n self.xp = None\n\n def set_pkgs(self, num_pkg, **kwargs):\n self.xp = num_pkg\n\n def _prepare(self, const_metadata: arrus.metadata.ConstMetadata):\n return const_metadata\n\n def __call__(self, data):\n data = data - self.xp.min(data)\n data = data/self.xp.max(data)*255\n return data.astype(self.xp.uint8)\n\n\ndef _get_rx_aperture_origin(sequence):\n rx_aperture_size = sequence.rx_aperture_size\n rx_aperture_center_element = np.array(sequence.rx_aperture_center_element)\n rx_aperture_origin = np.round(rx_aperture_center_element -\n (rx_aperture_size - 1) / 2 + 1e-9)\n if rx_aperture_size % 2 == 0:\n rx_aperture_origin = rx_aperture_origin-0.5\n return rx_aperture_origin\n\n\n","sub_path":"api/python/arrus/utils/imaging.py","file_name":"imaging.py","file_ext":"py","file_size_in_byte":23489,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"334823136","text":"\nimport copy\nimport importlib\nimport tensorflow as tf\nimport kaleido as kld\nimport numpy as np\n\n##### TESTER\nclass Tester( kld.Algorithm ):\n\n ### __INIT__\n def __init__( self , args ):\n self.preInit()\n\n self.args = args\n self.sess = tf.Session()\n self.load_network()\n\n args.image_test = kld.prepare_image_dict( args.image_test )\n\n self.build( args )\n self.test( args )\n\n ### BUILD\n def build( self , args ):\n self.preBuild()\n\n self.x = kld.plchf( [ None , None , 3 ] , 'input' )\n self.xi = tf.expand_dims( self.x , 0 )\n\n with tf.variable_scope( '' , reuse = tf.AUTO_REUSE ):\n\n args.net.type = 'calc'\n args.net.build( self.xi )\n\n args.net.type = 'eval'\n self.yh = args.net.build( self.xi )\n self.yh = tf.squeeze( self.yh )\n self.yh = tf.clip_by_value( self.yh , 0.0 , 255.0 )\n\n ### TEST\n def test( self , args ):\n self.preTest()\n\n model_name = kld.basename( args.model_dir )\n suffix = '%s_%d.jpg' % ( model_name , args.image_test['size'] )\n\n self.load_model()\n\n files = kld.get_dir_files( args.input_dir )\n for file in files:\n\n print( '%d - %s' % ( args.image_test['size'] , file ) )\n\n file_name = kld.basename( file )[:-4]\n file_dir = '%s/%s' % ( args.input_dir , file_name )\n kld.make_dir( file_dir )\n\n input = self.load_image( file , args.image_test )\n size , pad = 256 , 32\n h , w , c = input.shape\n n = int( np.ceil( max( h , w ) / size ) )\n hs , ws = int( h / n ) , int( w / n )\n\n print( 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA' )\n\n# print( input.shape )\n\n# arr = []\n# i = 0\n# while i < input.shape[0]:\n# arr.append( i )\n# if ( i + 1 ) % 4 == 0 : i += 13\n# else: i += 1\n# arr = np.asarray( arr )\n# small = input[ arr , : , : ]\n\n# print( small.shape )\n\n# arr = []\n# i = 0\n# while i < input.shape[1]:\n# arr.append( i )\n# if ( i + 1 ) % 4 == 0 : i += 13\n# else: i += 1\n# arr = np.asarray( arr )\n# small = small[ : , arr , : ]\n\n# print( small.shape )\n\n# pars = self.sess.run( args.net.pars , feed_dict = { self.x : small } )\n\n import scipy\n small = scipy.misc.imresize( input , 1.0 / n , interp = 'nearest' )\n\n# arr = np.arange( 2 , input.shape[0] , 4 )\n# small = input[ arr , : , : ]\n# arr = np.arange( 2 , input.shape[1] , 4 )\n# small = small[ : , arr , : ]\n\n pars = self.sess.run( args.net.pars_calc , feed_dict = { self.x : small } )\n\n# for i in range( len( pars ) ):\n# if i % 2 == 1: pars[i] = np.sqrt( pars[i] * n * n )\n\n# h2 , w2 = int( h / 2 ) , int( w / 2 )\n# hs2 , ws2 = int( hs / 2 ) , int( ws / 2 )\n# pars = self.sess.run( args.net.pars , feed_dict = { self.x : input[ h2 - hs2 : h2 + hs2 ,\n# w2 - ws2 : w2 + ws2 , : ] } )\n\n# small = input[ hs:2*hs , ws:2*ws , : ]\n# pars = self.sess.run( args.net.pars , feed_dict = { self.x : small } )\n\n print( 'BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB' )\n\n# pars2 = self.sess.run( args.net.pars , feed_dict = { self.x : input } )\n\n print( 'CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC' )\n\n# pars3 = []\n# for i in range( n ):\n# for j in range( n ):\n# input_ij = input[ i * hs : ( i + 1 ) * hs ,\n# j * ws : ( j + 1 ) * ws , : ]\n# tmp = self.sess.run( args.net.pars , feed_dict = { self.x : input_ij } )\n# if len( pars3 ) == 0:\n# pars3 = tmp\n## for k in range( len( pars3 ) ):\n## if k % 2 == 1: pars3[k] = np.sqrt( pars3[k] )\n# else:\n# for k in range( len( pars3 ) ):\n# if k % 2 == 0: pars3[k] += tmp[k]\n# if k % 2 == 1: pars3[k] += tmp[k]\n# for k in range( len( pars3 ) ):\n# if k % 2 == 0: pars3[k] /= n ** 2\n# if k % 2 == 1: pars3[k] /= n ** 2\n\n print( 'DDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDD' )\n\n# pars = pars2\n# for i in range( len( pars ) ):\n# if i % 2 == 0: pars[i] = pars3[i]\n# if i % 2 == 1: pars[i] = pars3[i]\n\n# [ print( p.shape ) for p in pars ]\n\n print( len(pars) )\n print( len(args.net.pars_eval) )\n\n pars_dict = {}\n for i in range( len( pars ) ):\n pars_dict[args.net.pars_eval[i]] = pars[i]\n\n# for i in range( 1 , len(pars) , 2 ):\n# print( '###############################################' , i )\n# print( pars[i] / pars2[i] )\n\n print( 'EEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEE' )\n\n canvasfull = np.zeros( input.shape )\n\n hst , hfn , wst , wfn = 0 , 0 , 0 , 0\n\n# for i in range( n ):\n\n# for j in range( n ):\n\n# hst , hfn = i * hs , ( i + 1 ) * hs\n# wst , wfn = j * ws , ( j + 1 ) * ws\n\n# hstp = 0 if i == 0 else - pad\n# wstp = 0 if j == 0 else - pad\n# hfnp = 0 if i == n - 1 else pad\n# wfnp = 0 if j == n - 1 else pad\n\n# input_ij = input[ hst + hstp : hfn + hfnp , wst + wstp : wfn + wfnp , : ]\n# output_ij = self.sess.run( self.yh , feed_dict = { **{ self.x : input_ij } , **pars_dict } )\n\n# canvasfull[ hst : hfn , wst : wfn , : ] = output_ij[ - hstp : hs - hstp , - wstp : ws - wstp , : ]\n\n# canvas = np.zeros( input.shape )\n# canvas[ hst + hstp : hfn + hfnp , wst + wstp : wfn + wfnp , : ] = output_ij\n\n# path = '%s/split_%2d-%2d_%s_%s' % ( file_dir , i , j , file_name , suffix )\n# kld.save_image( canvas , path )\n\n# path = '%s/fullsplit_%s_%s' % ( file_dir , file_name , suffix )\n# kld.save_image( canvasfull , path )\n\n output = self.sess.run( self.yh , feed_dict = { **{ self.x : input } , **pars_dict } )\n\n path = '%s/full_%s_%s' % ( file_dir , file_name , suffix )\n kld.save_image( output , path )\n\n# self.store_model( 'fast_style_transfer' )\n\n\n","sub_path":"style/ZZZ/fst/code/testers/testerAsplit_backup.py","file_name":"testerAsplit_backup.py","file_ext":"py","file_size_in_byte":6829,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"137133980","text":"import pytest\n\nimport numpy as np\nfrom scipy.sparse import coo_matrix\n\nfrom ophys_etl.transforms import trace_transforms\n\n\n@pytest.mark.parametrize(\"frames, rois, normalize_by_roi_size, expected\", [\n # movie frames\n (np.array([np.array(range(0, 6)).reshape((2, 3)),\n np.array(range(7, 13)).reshape((2, 3)),\n np.array(range(13, 19)).reshape((2, 3))]),\n # rois\n [np.array([[0, 1, 0],\n [1, 0, 1]]),\n np.array([[1, 1, 0],\n [0, 0, 0]]),\n np.array([[0, 0, 1],\n [0, 0, 1]])],\n # normalize_by_roi_size\n False,\n # expected\n np.array([[9, 30, 48],\n [1, 15, 27],\n [7, 21, 33]])),\n\n (np.array([np.array(range(0, 6)).reshape((2, 3)),\n np.array(range(7, 13)).reshape((2, 3)),\n np.array(range(13, 19)).reshape((2, 3))]),\n [np.array([[0, 1, 0],\n [1, 0, 1]]),\n np.array([[1, 1, 0],\n [0, 0, 0]]),\n np.array([[0, 0, 1],\n [0, 0, 1]])],\n True,\n np.array([[3, 10, 16],\n [0.5, 7.5, 13.5],\n [3.5, 10.5, 16.5]])),\n\n (np.array([np.array(range(0, 6)).reshape((2, 3)),\n np.array(range(7, 13)).reshape((2, 3)),\n np.array(range(13, 19)).reshape((2, 3))]),\n [np.array([[0.0, 0.0, 0.0],\n [1.0, 2.0, 1.0]]),\n np.array([[0.0, 0.0, 0.0],\n [1.0, 3.0, 0.0]]),\n np.array([[0.0, 0.0, 0.5],\n [0.0, 0.5, 1.0]])],\n False,\n np.array([[16, 44, 68],\n [15, 43, 67],\n [8, 22.0, 34.0]])),\n])\ndef test_extract_traces(frames, rois, normalize_by_roi_size, expected):\n rois = [coo_matrix(roi) for roi in rois]\n\n obtained = trace_transforms.extract_traces(frames, rois,\n normalize_by_roi_size)\n\n assert np.allclose(obtained, expected)\n","sub_path":"tests/transforms/test_trace_transforms.py","file_name":"test_trace_transforms.py","file_ext":"py","file_size_in_byte":1930,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"229592737","text":"\"\"\"Views of the application GrandPy\"\"\"\n\nfrom flask import Flask, render_template, jsonify, request\nfrom .parseur import parse\nfrom .wiki_info import get_wiki_extract, get_wiki_url\nfrom .location import get_address, get_latitude, get_longitude\n\napp = Flask(__name__)\n\n\n@app.route('/')\ndef main():\n \"\"\"Method which renders an html page\"\"\"\n return render_template(\"main.html\")\n\n\n@app.route('/process/', methods=['POST'])\ndef process():\n \"\"\"Method which renders the data for the processing with ajax\"\"\"\n question = request.form['question']\n parsed_question = parse(question)\n wiki_extract = get_wiki_extract(parsed_question)\n wiki_url = get_wiki_url(parsed_question)\n address = get_address(parsed_question)\n lat = get_latitude(parsed_question)\n lng = get_longitude(parsed_question)\n return jsonify({'data': [question, address, wiki_extract,\n wiki_url, lat, lng, parsed_question]})\n","sub_path":"GrandPy/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":938,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"15564643","text":"# ==============================================================================\n# Copyright (C) 2018-2020 Intel Corporation\n#\n# SPDX-License-Identifier: MIT\n# ==============================================================================\n\n## @file video_region_of_interest_meta.py\n# @brief This file contains VideoRegionOfInterestMeta class which mimics GstVideoRegionOfInterestMeta standard C structure and provides read access \n# to bounding box coordinates (in pixels), roi type, and more.\n\nimport ctypes\n\nimport gi\ngi.require_version('GstVideo', '1.0')\ngi.require_version('GLib', '2.0')\ngi.require_version('Gst', '1.0')\n\nfrom gi.repository import GstVideo, GLib, GObject, Gst\nfrom .util import libgst, libgobject, libgstvideo, GLIST_POINTER\n\n## @brief This class mimics GstVideoRegionOfInterestMeta standard C structure and provides read access to bounding box coordinates (in pixels), roi \n# type, and more. To see full fields list, turn to GstVideoRegionOfInterestMeta official documentation, and use this VideoRegionOfInterestMeta object\n# as simple structure with fields accessible for reading.\n# It's not expected that you will write data into or modify VideoRegionOfInterestMeta. Instead, you should create region_of_interest.RegionOfInterest \n# object with video_frame.VideoFrame.add_region() call\nclass VideoRegionOfInterestMeta(ctypes.Structure):\n _fields_ = [\n ('_meta_flags', ctypes.c_int),\n ('_info', ctypes.c_void_p),\n ('roi_type', ctypes.c_int),\n ('id', ctypes.c_int),\n ('parent_id', ctypes.c_int),\n ('x', ctypes.c_int),\n ('y', ctypes.c_int),\n ('w', ctypes.c_int),\n ('h', ctypes.c_int),\n ('_params', GLIST_POINTER)\n ]\n\n ## @brief Get VideoRegionOfInterestMeta.roi_type as a string (type/class of detected objects, such as \"vehicle\", \"person\", etc)\n # @return VideoRegionOfInterestMeta.roi_type as a string\n def get_roi_type(self) -> str:\n return GLib.quark_to_string(self.roi_type)\n\n ## @brief Set VideoRegionOfInterestMeta.roi_type from string (type/class of detected objects, such as \"vehicle\", \"person\", etc)\n # @param new_type string value to set to VideoRegionOfInterestMeta.roi_type\n def set_roi_type(self, new_type: str) -> None:\n self.roi_type = GLib.quark_from_string(new_type)\n\n ## @brief Iterate by VideoRegionOfInterestMeta instances attached to buffer\n # @param buffer buffer with GstVideoRegionOfInterestMeta instances attached\n # @return generator for VideoRegionOfInterestMeta instances attached to buffer\n @classmethod\n def iterate(cls, buffer: Gst.Buffer):\n try:\n meta_api = hash(GObject.GType.from_name(\n \"GstVideoRegionOfInterestMetaAPI\"))\n except:\n return\n gpointer = ctypes.c_void_p()\n while True:\n try:\n value = libgst.gst_buffer_iterate_meta_filtered(hash(buffer),\n ctypes.byref(\n gpointer),\n meta_api)\n except:\n value = None\n\n if not value:\n return\n\n yield ctypes.cast(value, ctypes.POINTER(VideoRegionOfInterestMeta)).contents\n\n\nVIDEO_REGION_OF_INTEREST_POINTER = ctypes.POINTER(VideoRegionOfInterestMeta)\nlibgstvideo.gst_video_region_of_interest_meta_get_param.argtypes = [VIDEO_REGION_OF_INTEREST_POINTER,\n ctypes.c_char_p]\nlibgstvideo.gst_video_region_of_interest_meta_get_param.restype = ctypes.c_void_p\n\nlibgstvideo.gst_video_region_of_interest_meta_add_param.argtypes = [VIDEO_REGION_OF_INTEREST_POINTER,\n ctypes.c_void_p]\nlibgstvideo.gst_video_region_of_interest_meta_add_param.restype = None\n","sub_path":"python/gstgva/video_region_of_interest_meta.py","file_name":"video_region_of_interest_meta.py","file_ext":"py","file_size_in_byte":3950,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"649008033","text":"import requests\n\nfrom checker.models import NonPaasSites\n\n\ndef check_routes():\n # breakpoint()\n print('Checking non paas routes')\n sites_to_check = NonPaasSites.objects.filter(reporting_enabled=True)\n\n for site in sites_to_check:\n response = requests.get(site.site_url)\n print(site.site_url)\n\n if response.status_code == 401:\n print('Site ' + site.site_url + ' is protected')\n NonPaasSites.objects.update_or_create(\n site_url=site.site_url,\n defaults={'is_protected': True})\n else:\n print('Site ' + site.site_url + ' is not protected')\n","sub_path":"core/check_non_paas_sites.py","file_name":"check_non_paas_sites.py","file_ext":"py","file_size_in_byte":639,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"153013616","text":"# encoding:utf-8\r\n'''\r\n爬虫调度器(入口)\r\n'''\r\nfrom URLManager import UrlManager\r\nfrom HTMLDownloader import HtmlDownloader\r\nfrom HTMLParser import HtmlParser\r\nfrom DataOutput import DataOutput\r\nimport pyprind\r\n\r\n\r\nclass SpiderMan(object):\r\n def __init__(self):\r\n self.manager = UrlManager()\r\n self.downloader = HtmlDownloader()\r\n self.parser = HtmlParser()\r\n self.output = DataOutput() # 实例化时连接到数据库\r\n\r\n def crawl(self):\r\n self.output.create_table() # 创建表\r\n self.manager.add_new_urls() # 创建url\r\n total = self.manager.new_urls_size()\r\n bar = pyprind.ProgBar(30, title=\"Crawling......\") # 进度条\r\n while (self.manager.new_urls_size()):\r\n url = self.manager.get_new_url()\r\n html = self.downloader.download(url)\r\n data = self.parser.parse(html)\r\n errors, errors_messages = self.output.insert_into_db(\r\n data) # 插入数据库\r\n bar.update()\r\n '''\r\n sys.stdout.write(\r\n str(self.manager.old_urls_size() / total * 100) + \"%\")\r\n sys.stdout.flush()\r\n # print('爬取', self.manager.old_urls_size(), '条。')\r\n '''\r\n self.output.close_cursor() # 关闭数据库连接\r\n print(\"本次共爬取\", total, \"条\")\r\n if errors:\r\n print(\"其中\", errors, \"条数据出错\")\r\n print(\"错误:\" + str(errors_messages))\r\n\r\n\r\nif __name__ == '__main__':\r\n spider_man = SpiderMan()\r\n spider_man.crawl()\r\n","sub_path":"SpiderMan.py","file_name":"SpiderMan.py","file_ext":"py","file_size_in_byte":1606,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"271004280","text":"import numpy as np\nfrom scipy.io import wavfile\nimport matplotlib.pyplot as plt\nimport math\nfrom scipy.linalg import svd\n\n\nSTD_SR_HZ = 44100\n\n# DSP FUNCTIONS:\ndef plot_matrix(matrix, name, ylabel, ratio=0.08):\n matrix = matrix.T # For this model\n num_wdws = matrix.shape[1]\n num_comp = matrix.shape[0]\n\n fig, ax = plt.subplots()\n ax.title.set_text(name)\n ax.set_ylabel(ylabel)\n if ylabel == 'Frequency (Hz)':\n # Map the axis to a new correct frequency scale, something in imshow() 0 to 44100 / 2, step by window size\n _ = ax.imshow(np.log(matrix), extent=[0, num_wdws, STD_SR_HZ // 2, 0]) \n fig.tight_layout()\n # bottom, top = plt.ylim()\n # print('Bottom:', bottom, 'Top:', top)\n plt.ylim(8000.0, 0.0) # Crop an axis (to ~double the piano frequency max)\n else:\n _ = ax.imshow(matrix, extent=[0, num_wdws, num_comp, 0])\n fig.tight_layout()\n # bottom, top = plt.ylim()\n # print('Bottom:', bottom, 'Top:', top)\n plt.ylim(num_comp, 0.0) # Crop an axis (to ~double the piano frequency max)\n ax.set_aspect(ratio) # Set a visually nice ratio\n # plt.show()\n plt.savefig('../kl_euc_div_comp/' + name + '.png')\n\n# SIGNAL -> SPECTROGRAM\ndef signal_to_pos_fft(sgmt, wdw_size, ova=False, debug_flag=False):\n if len(sgmt) != wdw_size:\n deficit = wdw_size - len(sgmt)\n sgmt = np.pad(sgmt, (0,deficit)) # pads on right side (good b/c end of signal), (deficit, 0) pads on left side # , mode='constant')\n\n if debug_flag:\n print('Original segment (len =', len(sgmt), '):\\n', sgmt[:5])\n\n if ova: # Perform lobing on ends of segment\n sgmt *= np.hanning(wdw_size)\n # pos_phases_fft = np.abs(np.fft.fft(sgmt))[: (wdw_size // 2) + 1].copy()\n # pos_mag_fft = np.angle(np.fft.fft(sgmt))[: (wdw_size // 2) + 1].copy()\n \n fft = np.fft.fft(sgmt)\n phases_fft = np.angle(fft)\n mag_fft = np.abs(fft)\n pos_phases_fft = phases_fft[: (wdw_size // 2) + 1].copy()\n pos_mag_fft = mag_fft[: (wdw_size // 2) + 1].copy()\n\n if debug_flag:\n if ova:\n print('hanning mult segment:\\n', sgmt[:5])\n print('FFT of wdw (len =', len(fft), '):\\n', fft[:5])\n print('phases of FFT of wdw:\\n', phases_fft[:5])\n print('mag FFT of wdw:\\n', mag_fft[:5])\n print('pos FFT of wdw:\\n', fft[: (wdw_size // 2) + 1])\n print('\\nType of elem in spectrogram:', type(pos_mag_fft[0]), pos_mag_fft[0].dtype, '\\n')\n print('positive mag FFT and phase lengths:', len(pos_mag_fft), len(pos_phases_fft))\n print('positive mag FFT:\\n', pos_mag_fft[:5])\n print('positive phases:\\n', pos_phases_fft[:5])\n print('\\nEnd of Segment -> FT\\n')\n \n return pos_mag_fft, pos_phases_fft\n\ndef make_spectrogram(signal, wdw_size, epsilon, ova=False, debug=False):\n # Pre-processing steps specific for Brahms (not training data)\n # If 8-bit PCM, convert to 16-bit PCM (signed to unsigned)\n if signal.dtype == 'uint8':\n signal = convert_sig_8bit_to_16bit(signal).astype('float64')\n if isinstance(signal[0], np.ndarray): # Stereo signal = 2 channels\n # sig = np.array([((x[0] + x[1]) / 2) for x in signal.astype('float32')]) # float64\n signal = np.average(signal, axis=-1)\n # else: # Mono signal = 1 channel \n # sig = np.array(signal).astype('float32') # float64 - too big, lower performance\n\n # Data Granularity Check\n if signal.dtype != 'float64':\n signal = signal.astype('float64')\n num_spls = len(signal)\n # print('Len in makespgm:', num_spls)\n if debug:\n pass\n # print('ORIGINAL SIG (FLOAT64) BEFORE SPGM:\\n', signal[(wdw_size // 2): (wdw_size // 2) + 20]) if num_spls > 20 else print('ORIGINAL SIG (FLOAT64) BEFORE SPGM:\\n', signal)\n\n # Hop size is half-length of window if OVA, else it's just window length (if length sufficient)\n hop_size = (wdw_size // 2) if (ova and num_spls >= (wdw_size + (wdw_size // 2))) else wdw_size\n # Number of segments depends on if OVA implemented\n num_sgmts = (math.ceil(num_spls / (wdw_size // 2)) - 1) if ova else math.ceil(num_spls / wdw_size)\n sgmt_len = (wdw_size // 2) + 1\n\n if debug:\n print('Num of Samples:', num_spls)\n print('Hop size:', hop_size)\n print('Num segments:', num_sgmts)\n \n # spectrogram, pos_phases = [], []\n spectrogram, pos_phases = np.empty((num_sgmts, sgmt_len)), np.empty((num_sgmts, sgmt_len))\n for i in range(num_sgmts):\n # Slicing a numpy array makes a view, so explicit copy\n sgmt = signal[i * hop_size: (i * hop_size) + wdw_size].copy()\n \n debug_flag = ((i == 0) or (i == 1)) if debug else False\n pos_mag_fft, pos_phases_fft = signal_to_pos_fft(sgmt, wdw_size, ova=ova, debug_flag=debug_flag)\n\n spectrogram[i] = pos_mag_fft\n pos_phases[i] = pos_phases_fft\n # spectrogram.append(pos_mag_fft)\n # pos_phases.append(pos_phases_fft)\n \n # Replace NaNs and 0s w/ epsilon\n spectrogram, pos_phases = np.nan_to_num(spectrogram), np.nan_to_num(pos_phases)\n spectrogram[spectrogram == 0], pos_phases[pos_phases == 0] = epsilon, epsilon\n\n # Safety measure to avoid overflow\n spectrogram = np.clip(spectrogram, np.finfo('float32').min, np.finfo('float32').max)\n # Spectrogram matrix w/ correct orientation (orig orient.)\n spectrogram = spectrogram.astype('float32') # T Needed? (don't think so, only for plotting)\n #if debug:\n #plot_matrix(spectrogram, name='Built Spectrogram', ylabel='Frequency (Hz)', ratio=SPGM_BRAHMS_RATIO)\n\n return spectrogram, pos_phases\n\n\ndef nmf(input_matrix, k, learn_iter=100):\n W = np.random.rand(input_matrix.shape[0], k)\n H = np.random.rand(k, input_matrix.shape[1])\n ones = np.ones(input_matrix.shape) # so dimensions match W transpose dot w/ V\n\n for learn_i in range(learn_iter):\n \n H *= ((W.T @ (input_matrix / (W @ H))) / (W.T @ ones))\n \n W *= (((input_matrix / (W @ H)) @ H.T) / (ones @ H.T))\n\n return W, H\n\n\ndef make_basis_vector(waveform, wdw_size, epsilon, ova=False):\n spectrogram, _ = make_spectrogram(waveform, wdw_size, epsilon, ova=ova)\n # Spectrogram in features = time orientation\n spectrogram = spectrogram.T\n\n W, H = nmf(spectrogram, 1)\n print('W shape:', W.shape, 'H shape:', H.shape)\n\n basis_vector = W[:, 0]\n print('--- Basis vector shape (NMF):', basis_vector.shape)\n\n return basis_vector\n\n\n# Idea - rank-1 approx = take avg of the pos. mag. spectrogram NOT the signal\ndef make_rank_1_approx(waveform, wdw_size, epsilon, ova=False, debug=False):\n\n spectrogram, _ = make_spectrogram(waveform, wdw_size, epsilon, ova=ova)\n # Spectrogram in features = time orientation\n spectrogram = spectrogram.T\n\n # Equivalent to W of rank-1 NMF\n basis_vector = np.mean(spectrogram, axis=1)\n print('--- Rank-1 approx. shape (Avged Freq Spectrum):', basis_vector.shape)\n\n return basis_vector\n\n\ndef make_left_singular_vector(waveform, wdw_size, epsilon, ova=False):\n\n spectrogram, _ = make_spectrogram(waveform, wdw_size, epsilon, ova=ova)\n # Spectrogram in features = time orientation\n spectrogram = spectrogram.T\n\n # Perform rank-1 SVD (LSA = SVD for dimensionality reduction)\n U, s, VT = svd(spectrogram)\n # Make sigma into diag matrix\n S = np.zeros((spectrogram.shape[0], spectrogram.shape[1]))\n diagonals = np.diag(s)\n S[:spectrogram.shape[1], :spectrogram.shape[1]] = np.diag(s)\n\n print('U shape:', U.shape, 'S shape:', S.shape, 'V^T.shape:', VT.shape)\n\n left_singular_vector = U[:,0] # First column of U is the most important eigen-frequency-spectrum\n print('--- Left singular vector shape (SVD):', left_singular_vector.shape)\n\n return left_singular_vector\n\n\ndef main():\n\n wdw_size, ova, avg = 4096, True, True\n epsilon = 10 ** (-10)\n \n audio_file = '../all_notes_ff_wav/Piano.ff.C4.wav'\n note_sr, stereo_sig = wavfile.read(audio_file)\n orig_note_sig_type = stereo_sig.dtype\n # Convert to mono signal (avg left & right channels) \n sig = np.average(stereo_sig.astype('float64'), axis=-1)\n\n # Trim out the silence on both ends of sig\n amp_thresh = max(sig) * 0.01\n while sig[0] < amp_thresh:\n sig = sig[1:]\n while sig[-1] < amp_thresh:\n sig = sig[:-1]\n\n rank_1_approx = make_rank_1_approx(sig, wdw_size, epsilon, ova=ova)\n plot_matrix(np.expand_dims(rank_1_approx, axis=0), 'rank_1_approx', 'frequency (Hz)', ratio=0.001)\n\n left_singular_vector = make_left_singular_vector(sig, wdw_size, epsilon, ova=ova)\n plot_matrix(np.expand_dims(left_singular_vector, axis=0), 'left_singular_vector', 'frequency (Hz)', ratio=0.001)\n\n basis_vector = make_basis_vector(sig, wdw_size, epsilon, ova=ova)\n plot_matrix(np.expand_dims(basis_vector, axis=0), 'basis_vector', 'frequency (Hz)', ratio=0.001)\n \n bv_to_r1_diff = basis_vector - rank_1_approx\n bv_to_r1_mse = np.mean(np.square(basis_vector - rank_1_approx))\n bv_to_r1_mae = np.mean(np.abs(basis_vector - rank_1_approx))\n print('\\nBasis Vector to Rank-1 Approx. Diff:\\n', bv_to_r1_diff, '\\nMSE:', bv_to_r1_mse, '\\nMAE:', bv_to_r1_mae)\n\n lsv_to_r1_diff = left_singular_vector - rank_1_approx\n lsv_to_r1_mse = np.mean(np.square(left_singular_vector - rank_1_approx))\n lsv_to_r1_mae = np.mean(np.abs(left_singular_vector - rank_1_approx))\n print('\\nLeft Singular Vector to Rank-1 Approx. Diff:\\n', lsv_to_r1_diff, '\\nMSE:', lsv_to_r1_mse, '\\nMAE:', lsv_to_r1_mae)\n\n # B/c we can\n bv_to_lsv_diff = basis_vector - left_singular_vector\n bv_to_lsv_mse = np.mean(np.square(basis_vector - left_singular_vector))\n bv_to_lsv_mae = np.mean(np.abs(basis_vector - left_singular_vector))\n print('\\nBasis Vector to Left Singular Vector Diff:\\n', bv_to_lsv_diff, '\\nMSE:', bv_to_lsv_mse, '\\nMAE:', bv_to_lsv_mae)\n\n\nif __name__ == '__main__':\n main()","sub_path":"brahms_restore_ml/nmf/old/restore_audio_oldfolder/compare_kl_euc_div.py","file_name":"compare_kl_euc_div.py","file_ext":"py","file_size_in_byte":9989,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"73330457","text":"import multiprocessing\nimport qt\nimport threading\nimport sys\nimport time\n\n\nclass WorkThread(threading.Thread):\n def __init__(self, process_name, input_queue, output_queue):\n super().__init__()\n self.process_name = process_name\n self.input_queue: multiprocessing.Queue = input_queue\n self.output_queue: multiprocessing.Queue = output_queue\n\n def run(self):\n while True:\n number, item = self.input_queue.get(block=True)\n\n print('item', number, 'received.')\n print('Sleeping', item, 'seconds.')\n time.sleep(item)\n\n print('item', number, 'complete.')\n # self.input_queue.task_done()\n self.output_queue.put((self.process_name, f'Completed {number}'))\n\n\nclass WorkerProcess(multiprocessing.Process):\n def __init__(self, process_count, input_queue, output_queue):\n super().__init__()\n self.process_count = process_count\n self.output_queue: multiprocessing.Queue = output_queue\n self.input_queue: multiprocessing.Queue = input_queue\n\n def run(self) -> None:\n app = qt.QApplication([])\n\n class TestWindow(qt.QWidget):\n def __init__(self):\n super().__init__()\n\n self.hboxlayout = qt.QHBoxLayout(self)\n self.output = qt.QPlainTextEdit()\n # self.output.setCenterOnScroll(True)\n self.hboxlayout.addWidget(self.output)\n\n def write(self, data):\n scroll = False\n if self.output.verticalScrollBar().value() == self.output.verticalScrollBar().maximum():\n scroll = True\n\n self.output.insertPlainText(data)\n\n if scroll:\n self.output.verticalScrollBar().setValue(self.output.verticalScrollBar().maximum())\n\n test_window = TestWindow()\n test_window.setWindowTitle(self.name)\n\n class StdOut(qt.QObject):\n write_signal = qt.pyqtSignal(str)\n\n def write(self, data):\n self.write_signal.emit(data)\n\n def flush(self):\n pass\n\n def close(self):\n pass\n\n stdout = StdOut()\n stdout.write_signal.connect(test_window.write)\n sys.stdout = stdout\n\n test_window.show()\n test_window_width = test_window.frameGeometry().width()\n test_window_height = test_window.frameGeometry().height()\n\n screen_rect: qt.QRect = test_window.windowHandle().screen().availableGeometry()\n columns = screen_rect.width() // test_window_width\n # rows = screen_rect.height() // test_window_height\n\n row, column = divmod(self.process_count, columns)\n\n test_window.move(column*test_window_width, row*test_window_height)\n\n print('Hi!')\n print('This is process', self.name)\n self.output_queue.put((self.name, 'Lol!'), block=False)\n\n work_thread = WorkThread(self.name, self.input_queue, self.output_queue)\n work_thread.start()\n\n app.exec()\n\n\nif __name__ == '__main__':\n def main():\n # app = qt.QApplication([])\n\n input_queue = multiprocessing.Queue()\n output_queue = multiprocessing.Queue()\n\n class OutputThread(threading.Thread):\n def __init__(self):\n super().__init__()\n self.setDaemon(True)\n\n def run(self) -> None:\n while True:\n item = output_queue.get(block=True)\n print(item)\n\n class InputThread(threading.Thread):\n def __init__(self):\n super().__init__()\n self.setDaemon(True)\n\n def run(self):\n import random\n for j in range(1_000_000):\n input_queue.put((j, random.random()))\n\n InputThread().start()\n OutputThread().start()\n\n processes = []\n for i in range(10):\n worker_process = WorkerProcess(i, input_queue, output_queue)\n worker_process.start()\n processes.append(worker_process)\n\n for process in processes:\n process.join()\n\n # app.exec()\n\n main()\n","sub_path":".old/work.py","file_name":"work.py","file_ext":"py","file_size_in_byte":4213,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"438407480","text":"valor_casa = float(input('Qual o valor da casa? '))\nsalario = float(input('Qual o salário? '))\nanos = int(input('Em quantos anos vai pagar? '))\n\nprestação = (valor_casa)/ (anos * 12)\n\nif prestação > salario:\n print('Empréstimo não aprovado')\nelse:\n print('Empréstimo aprovado')","sub_path":"backup/user_014/ch26_2020_04_11_14_42_18_713875.py","file_name":"ch26_2020_04_11_14_42_18_713875.py","file_ext":"py","file_size_in_byte":291,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"479163834","text":"from flask import Flask, jsonify, abort, request, Response\nfrom random import choice\nfrom tools_db import create_connection, execute_query, execute_read_query, BASE_DIR\n\n\napp = Flask(__name__)\nquotes = [\n {\n \"id\": 1,\n \"author\": \"Rick Cook\",\n \"text\": \"Программирование сегодня — это гонка разработчиков программ, стремящихся писать программы с большей и лучшей идиотоустойчивостью, и вселенной, которая пытается создать больше отборных идиотов. Пока вселенная побеждает.\",\n },\n {\n \"id\": 2,\n \"author\": \"Waldi Ravens\",\n \"text\": \"Программирование на С похоже на быстрые танцы на только что отполированном полу людей с острыми бритвами в руках.\"\n },\n {\n \"id\": 3,\n \"author\": \"Mosher’s Law of Software Engineering\",\n \"text\": \"Не волнуйтесь, если что-то не работает. Если бы всё работало, вас бы уволили.\"\n },\n {\n \"id\": 4,\n \"author\": \"Yoggi Berra\",\n \"text\": \"В теории, теория и практика неразделимы. На практике это не так.\"\n },\n\n]\n\nabout_me = {\n \"name\": \"Alexandr\",\n \"surname\": \"Igorevich\",\n \"fastname\": \"Goncharenko\",\n \"age\": 31\n}\n\n\n@app.route(\"/count_quotes\")\ndef count_quotes():\n return {\n \"count\": len(quotes)\n }\n\n\n@app.route(\"/quotes\")\ndef quotes_list():\n query = \"SELECT * FROM quotes;\"\n connection = create_connection(BASE_DIR / 'db.sqlite')\n results = execute_read_query(connection, query)\n keys = (\"id\", \"author\", \"text\")\n quotes = []\n for data in results:\n quote = dict(zip(keys, data))\n quotes.append(quote)\n return jsonify(quotes) # Сериализация dict --> json\n\n\n@app.route(\"/random_qoutes\")\ndef random_quotes():\n return jsonify(choice(quotes))\n\n\n@app.route(\"/quotes/\")\ndef get_quote(id):\n query = f\"SELECT * FROM quotes WHERE id={id};\"\n connection = create_connection(BASE_DIR / 'db.sqlite')\n data = execute_read_query(connection, query, only_one=True)\n if data is None:\n abort(404, description=f\"Quote with id={id} not found\")\n # print(f\"{data=}\")\n keys = (\"id\", \"author\", \"text\")\n quote = dict(zip(keys, data))\n return jsonify(quote)\n\n\n@app.route(\"/quotes\", methods=[\"POST\"])\ndef create_quote():\n new_quote = request.json\n try:\n query = f\"INSERT INTO quotes (author, text) VALUES ('{new_quote['author']}', '{new_quote['text']}');\"\n except KeyError:\n abort(400, \"field author and text required\")\n connection = create_connection(BASE_DIR / 'db.sqlite')\n execute_query(connection, query)\n return {}, 201\n\n\n@app.route(\"/quotes/\", methods=[\"PUT\"])\ndef edit_quote(id):\n new_data = request.json\n for quote in quotes:\n if quote[\"id\"] == id:\n if new_data.get(\"author\"):\n quote[\"author\"] = new_data[\"author\"]\n if new_data.get(\"text\"):\n quote[\"text\"] = new_data[\"text\"]\n return quote, 200\n new_data['id'] = quotes[-1][\"id\"] + 1\n quotes.append(new_data)\n return new_data, 201\n\n\n@app.route(\"/quotes/\", methods=['DELETE'])\ndef delete(id: int):\n # delete quote with id\n for quote in quotes:\n if quote[\"id\"] == id:\n quotes.remove(quote)\n return f\"Quote with id {id} was deleted.\", 200\n abort(404, description=f\"Quote with id={id} not found\")\n\n\nif __name__ == \"__main__\":\n app.run(debug=True)\n","sub_path":"app_2.py","file_name":"app_2.py","file_ext":"py","file_size_in_byte":3790,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"219434780","text":"from sklearn.feature_extraction.text import TfidfVectorizer\nimport os\nabsPath = os.path.dirname(os.path.abspath(__file__))\n\ndef processFile(f):\n pass\n\ndef tfidf_similarity(files, basedir):\n print(absPath)\n if len(files) < 3 or not files:\n errorMessage = \"Select at least 3 files to compare\"\n print(errorMessage)\n return errorMessage\n else:\n corpus = [open(basedir + \"/upload/\"+ f).read() for f in files]\n print(corpus)\n TfidfVectorizer()\n return corpus \n #TfidfVectorizer()\n \ndef similarityMethodLookup(method, files, basedir):\n METHODS = {\n 'similarity' : tfidf_similarity\n }\n\n return METHODS[method](files, basedir)","sub_path":"models/workers/similarity.py","file_name":"similarity.py","file_ext":"py","file_size_in_byte":706,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"276544751","text":"from django.shortcuts import render, redirect\nfrom genie.models import VehiclePhoto, Cleanliness, PhotoId\nfrom vehicle.models import Book\nfrom django.contrib.auth.models import User\nfrom vehicle.models import Definition\nfrom django.contrib import messages\nfrom datetime import date\nimport datetime\nfrom django.contrib.auth.decorators import login_required\n\n# Create your views here.\n\n\n@login_required\ndef index(request):\n now = date.today()\n book = Book.objects.filter(check_in_date__gte=now)\n return render(request, \"genie/index.html\", {\"book\": book})\n\n\n@login_required\ndef create(request, pk):\n book = Book.objects.get(pk=pk)\n vehicle = VehiclePhoto.objects.filter(book=book)\n if vehicle.count() >= 1:\n messages.warning(request, \"Already uploaded updation will come soon\")\n return redirect(\"genie:index\")\n\n if request.method == 'POST':\n # Car images\n\n front = request.FILES['front']\n back = request.FILES['back']\n side1 = request.FILES['side1']\n side2 = request.FILES['side2']\n\n # Cleanliness\n inside_tent = request.FILES['inside_tent']\n inside_car = request.FILES['inside_car']\n outside_car = request.FILES['outside_car']\n\n # id\n id1 = request.FILES['id1']\n id2 = request.FILES['id2']\n id3 = request.FILES['id3']\n id4 = request.FILES['id4']\n id5 = request.FILES['id5']\n\n VehiclePhoto(book=book, front=front, back=back, side1=side1, side2=side2).save()\n Cleanliness(book=book, inside_tent=inside_tent, inside_car=inside_car, outside_car=outside_car).save()\n PhotoId(book=book, id1=id1, id2=id2, id3=id3, id4=id4, id5=id5).save()\n messages.success(request, \"Saved image success\")\n return redirect(\"genie:index\")\n\n return render(request, \"genie/create.html\")\n\n\n@login_required\ndef show(request, pk):\n book = Book.objects.get(pk=pk)\n try:\n vehicle = VehiclePhoto.objects.get(book=book)\n clean = Cleanliness.objects.get(book=book)\n ids = PhotoId.objects.get(book=book)\n except:\n messages.warning(request, \"there is no image\")\n return redirect(\"genie:index\")\n return render(request, \"genie/show.html\", {\"vehicle\": vehicle,\n \"book\": book, \"clean\": clean,\n \"ids\": ids})\n\n\n@login_required\ndef offline(request):\n if request.method == \"POST\":\n check_in = datetime.datetime.strptime(request.POST.get(\"check_in\"), \"%Y-%m-%d\").date()\n check_out = datetime.datetime.strptime(request.POST.get(\"check_out\"), \"%Y-%m-%d\").date()\n duration = int(request.POST.get(\"duration\"))\n txnid = request.POST.get(\"txnid\")\n username = request.POST.get(\"username\")\n defi = request.POST.get(\"definition\")\n definition = Definition.objects.get(car_name=defi)\n user = User.objects.get(username=username)\n Book(user=user, definition=definition, car_name=definition.car_name,\n check_in_date=check_in, check_out_date=check_out, duration=duration, txnid=txnid).save()\n messages.success(request, \"Book saved success\")\n return redirect(\"genie:index\")\n return render(request, \"genie/offline.html\")\n","sub_path":"genie/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3269,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"476808420","text":"#Pixel puzzle game v 1.1\r\n#28.03.2020 bug fixed\r\nfrom m5stack import *\r\nfrom m5ui import *\r\nfrom uiflow import *\r\nimport unit\r\nimport imu\r\nimport math\r\nimport gc\r\nimport esp32\r\nimport machine\r\nimport random\r\n\r\n\r\nwin_cnt =0\r\n\r\nupside_down = False\r\nPixel_pos_pre = 28\r\nPixel_pos_init = 28\r\nPixel_pos =0\r\nPixel_target_index = 32\r\nPixel_row_num= 4\r\nPixel_col_num= 4\r\nPixel_brightness =30\r\nPixel_brightness_m = 15\r\nPixel_brightness_dk = 5\r\n\r\nColor_Blue = 0x0000FF\r\nColor_Red = 0xFF0000\r\nColor_Green = 0x00FF00\r\nColor_Orange = 0xFFA500\r\nColor_Yellow = 0xFFFF00\r\nColor_White = 0xFFFFE0\r\nColor_BK = 0x000000\r\nColor_RedPink = 0xFF1644\r\nColor_DeepPink = 0xFF198C\r\nColor_Random = 0x000000\r\n\r\n\r\n\r\n# offset calibration\r\ndef buttonB_wasPressed():\r\n # global params\r\n global ACC_X_offset,ACC_Y_offset,ACC_Z_offset\r\n ACC_X_offset = imu0.acceleration[0]\r\n ACC_Y_offset = imu0.acceleration[1]\r\n ACC_Z_offset = imu0.acceleration[2]\r\n pass\r\n\r\n\r\ndef get_bmm150_status():\r\n import bmm150\r\n state = 0\r\n bmm = bmm150.Bmm150()\r\n if bmm.available():\r\n if bmm.readID() == 0x32:\r\n state = 1\r\n bmm.set_normal_mode()\r\n if bmm.readData()[1] == 0:\r\n time.sleep_ms(200)\r\n if bmm.readData()[1] == 0:\r\n state = 0\r\n return state\r\n \r\ndef tilt_calc(x,y,z):\r\n unit_g = x**2 + y**2 + z**2\r\n unit_g = math.sqrt(unit_g)\r\n if z<0:\r\n z= -z\r\n if (unit_g < 1.25):\r\n tilt_angle = math.acos(z / unit_g)\r\n else:\r\n tilt_angle = math.acos(z / unit_g) #need improve\r\n tilt_angle = tilt_angle * 57.296 #RAD_TO_DEG\r\n return tilt_angle\r\n \r\n \r\ndef init_puzzle(Pixel_pos,Pixel_target_index):\r\n #page 1\r\n #global Pixel_target_index\r\n neopixel0.setColorFrom(1, 64, 0x000000)\r\n neopixel0.setColor(Pixel_pos, Color_Yellow)\r\n neopixel0.setColor(Pixel_target_index, Color_Green)\r\n \r\n pass\r\n\r\n\r\ndef win_flag():\r\n #clear\r\n neopixel0.setColorFrom(1, 64, 0x000000)\r\n wait(0.05)\r\n #frame\r\n neopixel0.setColorFrom(2, 7, Color_Yellow)\r\n neopixel0.setColor(9, Color_Yellow)\r\n neopixel0.setColor(16, Color_Yellow)\r\n neopixel0.setColor(17, Color_Yellow)\r\n neopixel0.setColor(24, Color_Yellow)\r\n neopixel0.setColor(25, Color_Yellow)\r\n neopixel0.setColor(32, Color_Yellow)\r\n neopixel0.setColor(34, Color_Yellow)\r\n neopixel0.setColor(39, Color_Yellow)\r\n neopixel0.setColor(42, Color_Yellow)\r\n neopixel0.setColor(47, Color_Yellow)\r\n neopixel0.setColor(51, Color_Yellow)\r\n neopixel0.setColor(54, Color_Yellow)\r\n neopixel0.setColorFrom(60, 61, Color_Yellow)\r\n #!\r\n neopixel0.setColorFrom(12, 13, Color_Red)\r\n neopixel0.setColorFrom(20, 21, Color_Red)\r\n neopixel0.setColorFrom(28, 29, Color_Red)\r\n neopixel0.setColorFrom(36, 37, Color_Red)\r\n neopixel0.setColorFrom(52, 53, Color_RedPink)\r\n wait(0.5)\r\n neopixel0.setColorFrom(12, 13, 0x000000)\r\n neopixel0.setColorFrom(20, 21, 0x000000)\r\n neopixel0.setColorFrom(28, 29, 0x000000)\r\n neopixel0.setColorFrom(36, 37, 0x000000)\r\n neopixel0.setColorFrom(52, 53, 0x000000)\r\n wait(0.5)\r\n neopixel0.setColorFrom(12, 13, Color_Red)\r\n neopixel0.setColorFrom(20, 21, Color_Red)\r\n neopixel0.setColorFrom(28, 29, Color_Red)\r\n neopixel0.setColorFrom(36, 37, Color_Red)\r\n neopixel0.setColorFrom(52, 53, Color_RedPink)\r\n wait(0.25)\r\n neopixel0.setColorFrom(1, 64, 0x000000)\r\n pass\r\n \r\ndef win_5():\r\n global Pixel_brightness_dk,Pixel_brightness\r\n #clear\r\n neopixel0.setColorFrom(1, 64, 0x000000)\r\n wait(0.05)\r\n neopixel0.setBrightness(Pixel_brightness_dk)\r\n neopixel0.setColorFrom(1, 64, Color_Green)\r\n Pixel_brightness = Pixel_brightness_dk\r\n while(Pixel_brightness<100):\r\n neopixel0.setBrightness(Pixel_brightness)\r\n Pixel_brightness = Pixel_brightness+2\r\n wait(0.05)\r\n \r\n Pixel_brightness =30\r\n wait(0.25)\r\n neopixel0.setBrightness(Pixel_brightness)\r\n pass\r\n \r\ndef pixel_row_col_update(Pixel_pos):\r\n global Pixel_row_num, Pixel_col_num\r\n Pixel_row_num =int(math.floor((Pixel_pos-1)/8)+1 )\r\n if Pixel_pos>8:\r\n Pixel_col_num = int(math.fmod(Pixel_pos, 8) )\r\n if Pixel_col_num ==0:\r\n Pixel_col_num =8\r\n else:\r\n Pixel_col_num = int(Pixel_pos)\r\n \r\n pass \r\n\r\ndef pixel_up():\r\n global Pixel_pos, Pixel_pos_pre\r\n Pixel_pos = Pixel_pos_pre -8\r\n \r\n\r\n pass \r\n \r\ndef pixel_down():\r\n global Pixel_pos, Pixel_pos_pre\r\n Pixel_pos = Pixel_pos_pre +8\r\n \r\n\r\n pass \r\ndef pixel_update(pos, pos_pre):\r\n #page 1\r\n #neopixel0.setColorFrom(1, 64, 0x000000)\r\n neopixel0.setBrightness(Pixel_brightness_m)\r\n wait(0.15)\r\n neopixel0.setBrightness(Pixel_brightness_dk)\r\n neopixel0.setColor(pos_pre, int(Color_Yellow/3))\r\n neopixel0.setColor(pos, int(Color_Yellow/2))\r\n wait(0.05)\r\n neopixel0.setBrightness(Pixel_brightness_m)\r\n neopixel0.setColor(pos_pre, int(Color_Yellow/2))\r\n neopixel0.setColor(pos, int(Color_Yellow/3))\r\n wait(0.05)\r\n neopixel0.setBrightness(Pixel_brightness)\r\n neopixel0.setColor(pos_pre, Color_BK)\r\n neopixel0.setColor(pos, Color_Yellow)\r\n wait(0.1)\r\n pass\r\n \r\ndef pixel_draw(pos, color):\r\n #page 1\r\n #neopixel0.setColorFrom(1, 64, 0x000000)\r\n neopixel0.setColor(pos, color)\r\n wait(0.05)\r\n pass\r\nACC_X_offset =0\r\nACC_Y_offset =0\r\nACC_Z_offset =0\r\nrun_cnt = 0\r\nsetScreenColor(0x111111)\r\nneopixel0 = unit.get(unit.NEOPIXEL, unit.PORTB, 64)\r\nneopixel0.setBrightness(Pixel_brightness)\r\nlabel0 = M5TextBox(6, 10, \"Pixel puzzle demo v1.01\", lcd.FONT_DejaVu24,0xFFFFFF, rotate=0)\r\n #lcd.set_fg(lcd.WHITE)\r\nlabel1 = M5TextBox(20, 40, \"IMU status:\", lcd.FONT_Default,0xAFCFFF, rotate=0)\r\n#labelT = M5TextBox(20, 140, \"Tilt:\", lcd.FONT_Default,0xAFCFFF, rotate=0)\r\nlabel_data_T_CPU = M5TextBox(125, 225, \"T_CPU:\", lcd.FONT_Default,0xAFCFFF, rotate=0)\r\nlabel_pixel = M5TextBox(20, 180, \"Pixel:\", lcd.FONT_Default,0xAFCF3F, rotate=0)\r\nlabel_cnt = M5TextBox(220, 225, \"CNT: \", lcd.FONT_Default,0xFFEEBB, rotate=0)\r\n#Vb values\r\nlabel_akku = M5TextBox(20, 225, \"Akku\", lcd.FONT_Default,0xFFFFAA, rotate=0)\r\nlabel_sys = M5TextBox(20, 205, \"sys: \", lcd.FONT_Default,0xF0CEAA, rotate=0)\r\nlabelT = M5TextBox(20, 140, \"Tilt:\", lcd.FONT_DejaVu24,0xAFCFFF, rotate=0)\r\n#label_ACC = M5TextBox(20, 60, \"Acc_X: \", lcd.FONT_Default,0xCFCFCF, rotate=0)\r\nPixel_target_index = random.randint(1, 60)\r\ninit_puzzle(Pixel_pos_init,Pixel_target_index)\r\nPixel_pos_pre = Pixel_pos_init\r\nPixel_pos = Pixel_pos_pre\r\nimu0 = imu.IMU()\r\n\r\nif get_bmm150_status(): \r\n label1.setText(\"IMU status: OK\")\r\n wait(0.2)\r\n ACC_X_offset = imu0.acceleration[0]\r\n ACC_Y_offset = imu0.acceleration[1]\r\n ACC_Z_offset = imu0.acceleration[2]\r\n Tilt_angel=tilt_calc(ACC_X_offset,ACC_Y_offset,ACC_Z_offset)\r\n if ACC_Z_offset<-0.5:\r\n upside_down = True\r\n if (Tilt_angel>5):\r\n label1.setText(\"Offset compensation failed\")\r\n else:\r\n label1.setText(\"Offset compensation OK\")\r\n wait(0.05)\r\n \r\nspeaker.setVolume(1)\r\n#speaker.sing(220, 1)\r\n\r\nwhile True:\r\n run_cnt = run_cnt+1\r\n #try:\r\n #roll = imu0.ypr[2]\r\n ACC_X = imu0.acceleration[0]-ACC_X_offset\r\n ACC_Y = imu0.acceleration[1]-ACC_Y_offset\r\n ACC_Z = imu0.acceleration[2]\r\n if ACC_Z<-0.5:\r\n upside_down = True\r\n else:\r\n upside_down = False\r\n Tilt_angel=tilt_calc(ACC_X,ACC_Y,ACC_Z)\r\n #ACC_total = (ACC_X**2+ACC_Y**2+ACC_Z**2)**0.5\r\n lcd.print(\"Acc_X: \"+\"%.3f\" % (ACC_X)+\" \", 20, 60, 0xFFAAAA)\r\n lcd.print(\"Acc_Y: \"+\"%.3f\" % (ACC_Y)+\" \", 20, 80, 0xFFAAAA)\r\n lcd.print(\"Acc_Z: \"+\"%.3f\" % (ACC_Z)+\" \", 20, 100, 0xFFAAAA)\r\n labelT.setText(\"Tilt: \"+str(Tilt_angel))\r\n \r\n pixel_row_col_update(Pixel_pos)\r\n \r\n if Tilt_angel>12:\r\n #speaker.sing(220, 1)\r\n if ACC_X> 0.3 :\r\n \r\n if upside_down:\r\n if Pixel_col_num<8 :\r\n Pixel_pos= Pixel_pos_pre +1\r\n else:\r\n speaker.sing(180, 1)\r\n else:\r\n if Pixel_col_num>1 :\r\n Pixel_pos= Pixel_pos_pre -1\r\n else:\r\n speaker.sing(220, 1)\r\n \r\n \r\n elif ACC_X <-0.3:\r\n \r\n if upside_down:\r\n if Pixel_col_num>1 :\r\n Pixel_pos= Pixel_pos_pre -1\r\n else:\r\n speaker.sing(180, 1)\r\n else:\r\n if Pixel_col_num<8 :\r\n Pixel_pos= Pixel_pos_pre +1\r\n else:\r\n speaker.sing(220, 1)\r\n\r\n \r\n if ACC_Y> 0.3 :\r\n if Pixel_row_num<8 :\r\n pixel_down()\r\n else:\r\n speaker.sing(180, 1)\r\n elif ACC_Y< -0.3 :\r\n if Pixel_row_num>1 :\r\n pixel_up()\r\n else:\r\n speaker.sing(180, 1)\r\n \r\n #speaker.sing(220, 1)\r\n if Pixel_pos>64:\r\n Pixel_pos = 64\r\n speaker.sing(220, 1)\r\n if Pixel_pos<1:\r\n Pixel_pos = 1\r\n speaker.sing(220, 1)\r\n \r\n pixel_update(Pixel_pos, Pixel_pos_pre) \r\n #pixel_draw(Pixel_pos, Pixel_pos_pre) \r\n Pixel_pos_pre = Pixel_pos \r\n \r\n \r\n if Pixel_pos == Pixel_target_index:\r\n win_cnt = win_cnt +1\r\n if (win_cnt > 5):\r\n win_5()\r\n label_pixel.setText(\"Pixel: \"+str(Pixel_pos)+\" Col:\"+str(Pixel_col_num)+ \"Target:\"+str(Pixel_target_index))\r\n speaker.sing(660, 1)\r\n wait(0.15)\r\n win_flag()\r\n wait(0.15)\r\n #try:\r\n #contain bugs!!!\r\n Pixel_target_index = int (math.fmod(run_cnt,64)+1)\r\n Pixel_pos = int(random.randint(1, 63)+1)\r\n label_pixel.setText(\"Pixel: \" + str(Pixel_pos)+ \" Col:\" + str(Pixel_col_num) +\" Row:\" + str(Pixel_row_num) + \"Target:\"+str(Pixel_target_index))\r\n #except:\r\n # label_data_T_CPU.setText(\"win funct error\")\r\n #label1.setText(\"random.randint error\")\r\n #pass\r\n label1.setText(\"Reset puzzle now!\")\r\n init_puzzle(Pixel_pos,Pixel_target_index)\r\n Color_Random = int(random.randint(0x1F, 0xffffff))\r\n pixel_draw(Pixel_target_index, Color_Random)\r\n wait(0.25)\r\n #Btn B: reset acc value\r\n if btnB.isPressed():\r\n buttonB_wasPressed() \r\n gc.collect()\r\n label_pixel.setText(\"Pixel: \" + str(Pixel_pos)+ \" Col:\" + str(Pixel_col_num) +\" Row:\" + str(Pixel_row_num) + \"Target:\"+str(Pixel_target_index))\r\n label_sys.setText(\"Free HEAP: \"+str(gc.mem_free())+\" Bytes\" )\r\n label_data_T_CPU.setText(\"\")\r\n label_cnt.setText(\"Run: \"+str(run_cnt) )\r\n #except:\r\n #label_data_T_CPU.setText(\"Unknown error occurred\")\r\n #time.sleep(0.1) \r\n #pass\r\n\r\n ","sub_path":"UiFLOW APP/Pixel_puzzle v2.py","file_name":"Pixel_puzzle v2.py","file_ext":"py","file_size_in_byte":11101,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"85611589","text":"import json\n\nfrom django.http import JsonResponse\nfrom django.utils import timezone\nfrom django.views.decorators.csrf import csrf_exempt\nfrom chat_bot.models import Scenario, Step\n\n\n@csrf_exempt\ndef scenarios(request):\n if request.method == \"GET\":\n _scenarios = Scenario.objects.all()\n\n # handle bot_id\n bot_id = request.GET.get('bot_id', None)\n if bot_id != None:\n _scenarios = _scenarios.filter(bot_id__exact=bot_id)\n\n\n # handle return\n data = []\n for scenario in _scenarios:\n steps = list(Step.objects.filter(scenario_id=scenario.id).values())\n data.append({\n 'id': scenario.id,\n 'bot_id': scenario.bot_id,\n 'name': scenario.name,\n 'position': scenario.position,\n 'steps': steps,\n 'created_time': scenario.created_time,\n 'updated_time': scenario.updated_time\n })\n\n return JsonResponse(data, safe=False)\n elif request.method == \"POST\":\n params = json.loads(request.body)\n Scenario.objects.create(\n bot_id=3,\n name=params[\"name\"],\n position=params[\"position\"],\n created_time=timezone.now\n )\n return JsonResponse({\"status\": 200}, safe=False)\n\n@csrf_exempt\ndef scenario_detail(request, id):\n if request.method == \"GET\":\n _scenarios = list(Scenario.objects.filter(id=id).values())\n\n if not _scenarios:\n return JsonResponse(None, safe=False)\n\n return JsonResponse(_scenarios[0], safe=False)\n elif request.method == \"PUT\":\n params = json.loads(request.body)\n\n scenario = Scenario.objects.get(id=id)\n scenario.bot_id = 3\n scenario.name = params.get('name')\n scenario.position = params.get('position')\n scenario.updated_time = timezone.now\n scenario.save()\n\n return JsonResponse({\"status\": 200}, safe=False)\n elif request.method == 'DELETE':\n scenario = Scenario.objects.get(id=id)\n scenario.delete()\n return JsonResponse({\"status\": 200}, safe=False)\n\n","sub_path":"tdai/api/views/view_scenario.py","file_name":"view_scenario.py","file_ext":"py","file_size_in_byte":2147,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"608997546","text":"# atom class\n\nfrom scipy.interpolate import interp1d\nimport numpy as np\nimport pandas as pd\nimport sys, os\nhere = os.path.dirname(os.path.abspath(__file__))\n\nclass atom:\n '''\n The atom class contains relevent parameters for determining the ionization\n rate in a strong field. Parameters come from 'Fundamentals of Attosecond Optics' and \n use the ADK formalism. It also contains information for calculation XUV dispersion and XUV \n photoabsorption. It contains the index of refraction for the driving laser wavelenth.\n\n Some parameters are stored in other classes but passed in during init. See comments of __init__.\n '''\n\n def __init__(self, Atom , Lam , Pressure , Temperature ):\n self.Atom = Atom\n\n #get from laser class, defaults given. \n self.Lam = Lam\n \n #get from gas class, defaults given.\n self.Pressure = Pressure\n self.Temperature = Temperature\n\n # intensity dependent phase\n self.alpha1 = 2\n self.alpha2 = 22\n\n # loaded using numpy \n nrg, f1, f2 = np.genfromtxt(here + '/sf/' + self.Atom + '.txt', dtype = float, skip_header = 1, \n usecols = (0,1,2), delimiter = '\\t', unpack = True)\n\n # load using pandas\n # d = pd.read_csv('sf/' + self.Atom + '.txt', skiprows = 1, delimiter = '\\t')\n # nrg = d.values[:,0]\n # f1 = d.values[:,1]\n # f2 = d.values[:,2]\n\n self.nrg = nrg\n self.f1 = f1\n self.f2 = f2\n\n def adk_params(self):\n '''\n ADK parameters. See 'Fundamentals of Attosecond Optics'\n\n return [F0, n_star, l_star, ang_l, ang_m, abs_Cnl_sq, G_lm, Ip]\n '''\n F0 = {'Xe': 0.84187, 'Kr': 1.04375, 'Ar': 1.24665, 'Ne': 1.99547, 'He': 2.42946}\n n_star = {'Xe': 1.05906, 'Kr': 0.98583, 'Ar': 0.92915, 'Ne': 0.7943, 'He': 0.74387}\n l_star = {'Xe': 0.05906, 'Kr': 0.98583, 'Ar': 0.92915, 'Ne': 0.7943, 'He': 0.74387}\n ang_l = {'Xe': 1, 'Kr': 1, 'Ar': 1, 'Ne': 1, 'He': 0}\n ang_m = {'Xe': 0, 'Kr': 0, 'Ar': 0, 'Ne': 0, 'He': 0}\n abs_Cnl_sq = {'Xe': 3.88241, 'Kr': 4.02548,'Ar': 4.11564, 'Ne': 4.24355, 'He': 4.25575}\n G_lm = {'Xe': 3, 'Kr': 3,'Ar': 3, 'Ne': 3, 'He': 3}\n Ip = {'Xe': 12.129, 'Kr': 13.99,'Ar': 15.759, 'Ne': 21.564, 'He': 24.587}\n alpha = {'Xe': 9, 'Kr': 9,'Ar': 9, 'Ne': 9, 'He': 7}\n\n return {'F0':F0[self.Atom], 'n_star': n_star[self.Atom], 'l_star': l_star[self.Atom],\n 'ang_l': ang_l[self.Atom], 'ang_m': ang_m[self.Atom], 'abs_Cnl_sq':abs_Cnl_sq[self.Atom],\n 'G_lm': G_lm[self.Atom], 'Ip':Ip[self.Atom], 'alpha': alpha[self.Atom]}\n\n def xuv_index(self, eV):\n '''\n Based on atomic scattering factors from LBNL.\n\n returns a function for the index of refraction for a given photon energy.\n\n '''\n re = 2.8179 * 10 ** -15 #classical electron radius\n kb = 1.3806488 * 10 ** -23 #Boltzmann constant\n f1_interp = interp1d(self.nrg, self.f1)\n f2_interp = interp1d(self.nrg, self.f2)\n wl = 1240 / eV * 10 ** -9\n dens = self.Pressure/kb/self.Temperature #density\n return 1 - re * wl ** 2 / 2 / np.pi * dens * (f1_interp(eV) + 1j * f2_interp(eV))\n\n def xuv_absorption(self, eV):\n '''\n Based on atomic scattering factors from LBNL\n\n returns the absorption crossection for a given photon energy.\n '''\n re = 2.8179 * 10 ** -15\n f2_interp = interp1d(self.nrg, self.f2)\n wl = 1240 / eV * 10 **-9\n return 2 * wl * re * f2_interp(eV)\n\n\n\n def drive_index(self):\n '''\n Based on Börzsönyi APPLIED OPTICS / Vol. 47, No. 27 / 20 September 2008\n\n returns the index of refraction of the driving laser for a given wavelength,\n pressure and temperature.\n '''\n B1 = {'Xe': 103701.61 * 10 ** -8, 'Kr': 26102.88 * 10 ** -8, 'Ar': 20332.29 * 10 ** -8, 'Ne': 9154.48 * 10 ** -8, 'He': 4977.77 * 10 ** -8}\n C1 = {'Xe': 12.75 * 10 ** -6, 'Kr': 2.01 * 10 ** -6, 'Ar': 206.12 * 10 ** -6, 'Ne': 656.97 * 10 ** -6, 'He': 28.54 * 10 ** -6}\n B2 = {'Xe': 31228.61 * 10 ** -8, 'Kr': 56946.82 * 10 ** -8, 'Ar': 8.066 * 10 ** -8, 'Ne': 4018.63 * 10 ** -8, 'He': 1856.94 * 10 ** -8}\n C2 = {'Xe': 0.561 * 10 ** -3, 'Kr': 10.043 * 10 ** -3, 'Ar': 1.24665 * 10 ** -3, 'Ne': 5.728 * 10 ** -3, 'He': 7.760 * 10 ** -3}\n wl = self.Lam * 10 ** 6\n return np.sqrt( 1 + ( self.Pressure * 273 / self.Temperature ) * (\n B1[self.Atom] * wl ** 2 / (wl ** 2 - C1[self.Atom] ) +\n B2[self.Atom] * wl ** 2 / (wl ** 2 - C2[self.Atom] ) ) ) \n\n def drive_index2(self):\n '''\n base on The Refractive Indices and Verdet Constants of the Inert Gases, \n Proc. R. Soc. Lond. A 1960 259, doi: 10.1098/rspa.1960.0237\n\n '''\n A = {'Xe': 1.366e-3, 'Kr': 8.377e-4 , 'Ar': 5.547e-4 , 'Ne': 1.335e-4 , 'He': 6.927e-5 }\n B1 = {'Xe': 9.02e5, 'Kr': 6.7e5, 'Ar': 5.15e5, 'Ne': 2.24e5, 'He': 2.24e5}\n B2 = {'Xe': 1.81e12, 'Kr': 8.84e11, 'Ar': 4.19e11, 'Ne': 8.09e10, 'He': 5.94e10}\n B3 = {'Xe': 4.89e18, 'Kr': 1.49e18, 'Ar': 4.09e17, 'Ne': 3.56e16, 'He': 1.72e16}\n B4 = {'Xe': 1.45e25, 'Kr': 2.74e24, 'Ar': 4.32e23, 'Ne': 0, 'He': 0}\n B5 = {'Xe': 4.34e31, 'Kr': 5.10e30, 'Ar': 0, 'Ne': 0, 'He': 0}\n wl = self.Lam * 10 ** 10\n return np.sqrt( 1 + A[self.Atom] * (1 + B1[self.Atom] / wl ** 2 + B2[self.Atom] / wl ** 4 + B3[self.Atom] / wl ** 6 + B4[self.Atom] / wl ** 8 + B5[self.Atom] / wl ** 10))\n\n def eta_crit(self, eV):\n '''\n Critical ionization fraction.\n '''\n re = 2.8179 * 10 ** -15 #classical electron radius\n kb = 1.3806488 * 10 ** -23 #Boltzmann constant\n Natm = 1.013 * 10 ** 5 / kb / self.Temperature\n\n dn = np.real(self.drive_index() - self.xuv_index(eV) )\n eta_crit = 1 / (1 + Natm * re * self.Lam ** 2 / 2 / np.pi / dn)\n return dn, eta_crit\n\n def kp(self):\n '''\n Decay rate, see Allison et al. PRL (2011)\n '''\n kp = {'Xe': .08, 'Kr': .2 , 'Ar': .3 , 'Ne': .4 , 'He': .5 }\n kp = {'Xe': .1, 'Kr': .2 , 'Ar': .3 , 'Ne': .4 , 'He': .5 }\n return kp[self.Atom]\n\n\n\n\n\n","sub_path":"src/atom.py","file_name":"atom.py","file_ext":"py","file_size_in_byte":6311,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"152644042","text":"# -*- coding: utf-8 -*-\nimport os \nimport sys\nmyFolder = os.path.split(os.path.dirname(__file__))[0]\nsys.path = [os.path.join(myFolder, 'widgets'),\nos.path.join(myFolder, 'features'),os.path.join(myFolder,'lenet5')\n] + sys.path\nfrom base import (itv2time ,QObject,QInputDialog, QTimer,QThread)\nfrom leNet5TrainThread import LeNet5TrainThread\n\ntimeCount=1000\nreSetCount=100000.0\n#LeNet5网络训练界面与功能的整合\nclass ConfigLeNet5Train(QObject):\n\n def __init__(self,leNet5TrainContent,parent=None,):\n super(ConfigLeNet5Train,self).__init__()\n self.trainContent=leNet5TrainContent\n self.numSteps=50\n self.bindConnet()\n self.parent=None\n self.runNum=0.0\n self.trainTimer=None\n self.trainThread=LeNet5TrainThread()\n self.runThread=None\n \n def bindConnet(self):\n self.trainContent.paraWidget.changeButton.clicked.connect(self.changeTrainStatus)\n self.trainContent.paraWidget.numStepButton.clicked.connect(self.showDialog)\n \n def changeTrainStatus(self):\n #训练时单击则停止\n if self.trainContent.paraWidget.isRunningThread:\n self.trainThread.setTrainStop()\n self.trainContent.paraWidget.changeButton.setText(\"开始训练\")\n self.trainContent.paraWidget.numStepButton.setEnabled(True)\n self.trainThread.quit()\n self.trainThread.wait()\n self.runThread.exit()\n self.runThread.wait()\n\n #不在训练时单击则开始训练\n elif not self.trainContent.paraWidget.isRunningThread:\n self.runNum=0.0\n self.trainContent.paraWidget.runTimeLabel.setText(itv2time(self.runNum))\n\n self.trainTimer=QTimer()\n self.trainTimer.start(timeCount)\n #重新连接\n self.trainTimer.timeout.connect(self.showTrainRun)\n self.trainContent.matplotWidget.baseMpl.re_figure()\n self.trainContent.paraWidget.changeButton.setText(\"停止训练\")\n self.trainContent.paraWidget.numStepButton.setEnabled(False)\n self.trainContent.disDetailsText.setText(\"\")\n self.trainThread=LeNet5TrainThread()\n\n self.trainThread.someStepsOverSin.connect(self.trainContent.matplotWidget.baseMpl.update_figure)\n self.trainThread.someStepsOverSin.connect(self.disDetailsShow)\n self.trainThread.finishedTrainSin.connect(self.reSetTrainStatus)\n self.trainThread.setNumSteps(self.numSteps)\n self.runThread=QThread()\n self.trainThread.moveToThread(self.runThread)\n self.runThread.started.connect(self.trainThread.run)\n self.runThread.start()\n \n #最后更正状态\n self.trainContent.paraWidget.isRunningThread=not self.trainContent.paraWidget.isRunningThread\n\n def showDialog(self):\n text, ok = QInputDialog.getInt(self.trainContent.paraWidget, '修改参数', '输入:',min=1)\n if ok:\n self.strNumSteps=str(text)\n self.trainContent.paraWidget.numStepLabel.setText(self.strNumSteps)\n self.numSteps=text\n def reSetTrainStatus(self):\n try:\n self.trainThread.quit()\n self.trainThread.wait()\n self.runThread.exit()\n self.runThread.wait()\n self.trainContent.paraWidget.changeButton.setText(\"开始训练\")\n except exception as e:\n print(e)\n\n self.trainContent.paraWidget.numStepButton.setEnabled(True)\n #最后更正状态\n self.trainContent.paraWidget.isRunningThread=not self.trainContent.paraWidget.isRunningThread\n self.runThread.exit()\n self.runThread.wait()\n def disDetailsShow(self,dict):\n if self.runNum>=reSetCount:\n self.trainContent.disDetailsText.setText(\"\")\n self.trainContent.matplotWidget.baseMpl.re_figure()\n self.trainContent.disDetailsText.append(dict['message'])\n\n def showTrainRun(self):\n if self.runThread.isRunning():\n self.runNum=self.runNum+1.0\n self.trainContent.paraWidget.runTimeLabel.setText(itv2time(self.runNum))\n else:\n self.trainTimer=None\n","sub_path":"features/configLeNet5TrainFeatures.py","file_name":"configLeNet5TrainFeatures.py","file_ext":"py","file_size_in_byte":4232,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"372761046","text":"# @cronline 1 */1 * * * python3\n# $ODF_HOME/flows/OpenExchangeRates/openexchangerates.py\nimport urllib.request\nimport ssl\nimport json\nfrom cassandra.cluster import Cluster\n\ngcontext = ssl.SSLContext(ssl.PROTOCOL_TLSv1) \n\nusdRates = urllib.request.urlopen(\"https://openexchangerates.org/api/latest.json?app_id=\").read()\n\nusdRatesDecoded = json.loads(usdRates.decode('utf-8'))['rates']\n\nts = json.loads(usdRates.decode('utf-8'))['timestamp']\n\ncluster = Cluster(['127.0.0.1'])\nsession = cluster.connect()\nsession = cluster.connect('dwh')\n\nfor rate in usdRatesDecoded:\n session.execute(\n \"\"\"\n INSERT INTO rates (id,quote,ts,rate)\n VALUES (%s,%s,%s,%s);\n \"\"\",\n (\"usd\"+rate.lower()+\"::\"+str(ts),\"usd\"+rate.lower(),ts,usdRatesDecoded[rate])\n)\n\n","sub_path":"flows/OpenExchangeRates/openexchangerates.py","file_name":"openexchangerates.py","file_ext":"py","file_size_in_byte":756,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"421976127","text":"# Jérôme Pacquet, paqj2905\n# Malcolm St. John, stjm2505\nimport matplotlib.pyplot as plt\nimport numpy as np\n\n\n# Load the image into python from npy file\ndef load_img():\n img_load = plt.imread('../images/goldhill_rotate.png')\n plt.figure()\n plt.imshow(img_load, cmap='gray')\n plt.title('Image sans modifs')\n plt.show()\n return img_load\n\n\n# Effectue la rotation\ndef rotation(img):\n mat_to_fill = np.zeros(img.shape)\n mat_rotation = np.array([[0, -1], [1, 0]])\n for y in range(0, len(img)):\n for x in range(0, len(img[y])):\n new_coords = np.dot(mat_rotation, [x, y])\n new_x = new_coords[0]\n new_y = new_coords[1]\n mat_to_fill[new_y][new_x] = img[y][x]\n plt.figure()\n plt.imshow(mat_to_fill, cmap='gray')\n plt.title('Image tournee')\n plt.show()\n return mat_to_fill\n\n\nif __name__ == \"__main__\":\n print('Executing main')\n rotation(load_img())\n","sub_path":"S5/app5/lib/rotation.py","file_name":"rotation.py","file_ext":"py","file_size_in_byte":937,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"433349762","text":"from marvinbot.plugins import load_plugins\nfrom marvinbot.signals import bot_shutdown, bot_started\nfrom marvinbot.polling import TelegramPollingThread\nfrom marvinbot.scheduler import configure_scheduler\nimport logging\n\nlog = logging.getLogger(__name__)\n\n\ndef shutdown_bot(adapter):\n log.info('Shutting down...')\n if adapter.scheduler_available:\n adapter.scheduler.shutdown()\n adapter.updater.stop()\n bot_shutdown.send(adapter)\n\n\ndef run_bot(adapter):\n # The program will exit as soon as all non-daemon threads stop\n log.info(\"Starting bot in standalone mode\")\n adapter.updater.daemon = False\n adapter.updater.start()\n configure_scheduler(adapter.config, adapter)\n load_plugins(adapter.config, adapter)\n if adapter.scheduler_available:\n adapter.scheduler.start()\n bot_started.send(adapter)\n","sub_path":"marvinbot/runner.py","file_name":"runner.py","file_ext":"py","file_size_in_byte":839,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"176447515","text":"import numpy as np\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.decomposition import PCA\nfrom sklearn.linear_model import LogisticRegression\n\ndata = np.genfromtxt(\"spambase/spambase.data\", delimiter=',')\nX = data[:,:57]\nY = data[:,-1]\nscaler = StandardScaler()\nX = scaler.fit_transform(X)\n\nXtr, Xte, Ytr, Yte = train_test_split(X, Y, test_size=0.05, shuffle=True)\n\nprint(\"Number of features:\\t\", X.shape[1])\nprint(\"Number of training data points:\\t\", Xtr.shape[0])\nprint(\"Number of test data points:\\t\", Xte.shape[0])\n\nlogreg = LogisticRegression(tol=1e-8, C=10.0, random_state=0, solver='lbfgs', multi_class='multinomial')\nclf = logreg.fit(Xtr,Ytr)\n#clf = LogisticRegression(tol=1e-8, C=10.0).fit(Xtr, Ytr)\n\nprint(\"training score:\\t\", clf.score(Xtr,Ytr))\nprint(\"test score:\\t\", clf.score(Xte,Yte))\n\nYhat = clf.predict(Xte)\n\nerr = 0\nfor i in range(len(Xte)):\n if Yhat[i] != Yte[i]:\n err += 1\nprint(\"Error rate: \", err/len(Xte))","sub_path":"SpamLearn-master-2/src/LogisticRegression.py","file_name":"LogisticRegression.py","file_ext":"py","file_size_in_byte":1008,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"361199932","text":"\n\n#calss header\nclass _SHODDY():\n\tdef __init__(self,): \n\t\tself.name = \"SHODDY\"\n\t\tself.definitions = [u'badly and carelessly made, using low quality materials: ', u'showing little respect, thought, or care: ']\n\n\t\tself.parents = []\n\t\tself.childen = []\n\t\tself.properties = []\n\t\tself.jsondata = {}\n\n\n\t\tself.specie = 'adjectives'\n\n\n\tdef run(self, obj1, obj2):\n\t\tself.jsondata[obj2] = {}\n\t\tself.jsondata[obj2]['properties'] = self.name.lower()\n\t\treturn self.jsondata\n","sub_path":"xai/brain/wordbase/adjectives/_shoddy.py","file_name":"_shoddy.py","file_ext":"py","file_size_in_byte":461,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"134667306","text":"def tvarsumma(n):\r\n if n > 0:\r\n return n % 10 + tvarsumma((n - n % 10) / 10)\r\n if n == 0:\r\n return 0\r\n\r\n\r\ndef tvarsumma2(n):\r\n result = 0\r\n while n > 0:\r\n result = result + n % 10\r\n n = (n - n % 10) / 10\r\n return result\r\n\r\n\r\nprint(tvarsumma(513574))\r\nprint(tvarsumma2(513574))\r\n","sub_path":"Lab2/Tvarsumma.py","file_name":"Tvarsumma.py","file_ext":"py","file_size_in_byte":321,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"152232080","text":"import os\nimport sys\nif not os.path.dirname(__file__) in sys.path:\n sys.path.append(os.path.dirname(__file__))\nfrom test_utils import Base as unittest\nimport job_system\nimport logging\n\n\nclass JobSystemTest(unittest.TestCase):\n\n def test_spawn_job(self):\n import job_system\n parameter = 999\n job_id = job_system.spawn(\n self.service, 'job_system_test.TestJob', parameter)\n result = self.wait_for_job(job_id)\n self.assertEqual(parameter, result)\n results = self.search_job_results(job_id, \"parameter=%s\" % parameter)\n self.assertEqual(len(results), 1)\n\n def test_child_job(self):\n import job_system\n parent_job_id = job_system.spawn(\n self.service, 'job_system_test.ParentJob')\n child_job_id = self.wait_for_job(parent_job_id)\n self.wait_for_job(child_job_id)\n\n parent_job = self.get(\"msaas/jobs/%s\" % (parent_job_id))\n child_job = self.get(\"msaas/jobs/%s\" % (child_job_id))\n\n self.assertEqual(child_job[\"parent_id\"], parent_job_id)\n\n\nclass TestJob(job_system.Job):\n\n def run(self, parameter):\n logging.info('parameter=%s', parameter)\n return parameter\n\n\nclass ParentJob(job_system.Job):\n\n def run(self, _):\n import job_system\n job_id = job_system.spawn(\n self.service, 'job_system_test.ChildJob')\n return job_id\n\n\nclass ChildJob(job_system.Job):\n\n def run(self, _):\n pass\n","sub_path":"apps/msaas/bin/job_system_test.py","file_name":"job_system_test.py","file_ext":"py","file_size_in_byte":1462,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"158990965","text":"from mors_module import application, socketio\nfrom mors_module.currently_playing import *\nfrom mors_module.methods import *\nfrom flask import render_template\nfrom flask_socketio import emit\nfrom datetime import datetime\n\n\n@application.route('/')\n@application.route('/index')\ndef index():\n cp_obj = CurrentlyPlaying()\n current_program = cp_obj.now_playing()\n broadcasts = Broadcast.query.all()\n b_cast_date = get_next_or_last_broadcast(datetime.today())\n schedule = get_schedule_by_date(b_cast_date)\n chat_messages = ChatMessages.query.order_by(ChatMessages.id.desc()).limit(20)\n\n print('broadcasts', broadcasts)\n print('schedule', schedule)\n\n return render_template('main_page.html',\n schedule=schedule,\n broadcasts=broadcasts,\n version='20.31 (alpha)',\n chat_messages=chat_messages,\n current_program=current_program)\n\n\n@socketio.on('sent_message')\ndef get_messages(message):\n msg = ChatMessages(**message, timestamp=datetime.today())\n db.session.add(msg)\n db.session.commit()\n emit('new_message', {\n 'author': message['author'],\n 'text': message['text'],\n 'timestamp': msg.timestamp.strftime('%d.%m.%Y, %H:%M:%S')\n }, broadcast=True)\n\n\n@socketio.on('cp_request')\ndef currently_playing():\n cp_obj = CurrentlyPlaying()\n emit('cp_response', cp_obj.now_playing())\n\n\n@socketio.on('refresh_schedule')\ndef refresh_schedule(date):\n date_dt = datetime.strptime(date, '%d.%m.%Y')\n schedule = get_schedule_by_date(date_dt)\n emit('new_schedule', schedule)\n","sub_path":"mors_module/routes.py","file_name":"routes.py","file_ext":"py","file_size_in_byte":1653,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"538273881","text":"import pandas as pd \n\ngamesdata = pd.read_csv(\"data/games.csv\")\n\n# Adds the total points scored in a game to the end of the dataframe\npoint_total= gamesdata.PTS_home + gamesdata.PTS_away\ngamesdata[\"point_total\"] = point_total[0:23194]\n\n# Removing entries before 2018 season \ngamesdata = gamesdata.loc[gamesdata.SEASON >= 2018]\ngamesdata.sort_values(by=[\"GAME_DATE_EST\"])\ngamesdata = gamesdata.reset_index(drop = True)\n\n# Checked missing values, there are none\n#print (gamesdata.isnull().sum()) \n\n\n\n\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":499,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"45755711","text":"from sklearn.metrics import *\nimport numpy as np\nfrom sklearn.metrics import make_scorer\nfrom sklearn.model_selection import cross_validate\n\n\nclass Metrics:\n\n @classmethod\n def smape(cls, A, F):\n \"\"\"\n Calculates the smape value between the real and the predicted\n\n Parameters\n ----------\n A : array\n Target values\n F : array\n Predicted values\n\n Returns\n -------\n float: smape value\n \"\"\"\n return 100/len(A) * np.sum(np.abs(F - A) / (np.abs(A) + np.abs(F)))\n\n @classmethod\n def __custom_score(cls, y_true, y_pred):\n \"\"\"\n Creates a custom metric\n\n Parameters\n ----------\n y_true : array\n Target values\n y_pred : array\n Predicted values\n\n Returns\n -------\n sklearn.metrics\n \"\"\"\n #return sklearn.metrics.fbeta_score(y_true, y_pred, 2)\n pass\n\n @classmethod\n def customized(cls, y_true, y_pred):\n \"\"\"\n Creates a custom metric\n\n Parameters\n ----------\n y_true : array\n Target values\n y_pred : array\n Predicted values\n\n Returns\n -------\n float\n \"\"\"\n custom_metric = make_scorer(cls.__custom_score, greater_is_better=True)\n return custom_metric\n\n @classmethod\n def mape(cls, y_true, y_pred):\n \"\"\"\n Calculates the map value between the real and the predicted\n\n Parameters\n ----------\n y_true : array\n Target values\n y_pred : array\n Predicted values\n\n Returns\n -------\n float : value of mape\n \"\"\"\n y_true, y_pred = np.array(y_true), np.array(y_pred)\n return np.mean(np.abs(((y_true+1) - (y_pred+1)) / (y_true+1))) * 100\n\n @classmethod\n def regression(cls, y_true, y_pred):\n \"\"\"\n Calculates some metrics for regression problems\n\n Parameters\n ----------\n y_true : array\n Target values\n y_pred : array\n Predicted values\n\n Returns\n -------\n dict : metrics results\n \"\"\"\n results = {'mean_absolute_error': round(mean_absolute_error(\n y_true, y_pred), 7),\n 'root_mean_squared_error': round(np.sqrt(\n mean_squared_error(y_true, y_pred)), 7),\n 'r2': round(r2_score(y_true, y_pred), 7),\n 'smape': round(cls.smape(y_true, y_pred), 7),\n 'mape': round(cls.mape(y_true, y_pred), 7)\n }\n return results\n\n @classmethod\n def crossvalidation(cls, model, X, y, classification: bool,\n cv=5, agg=np.mean):\n if classification:\n if len(set(y)) > 2:\n metrics = ['accuracy', 'f1_weighted',\n 'recall_weighted', 'precision_weighted']\n else:\n metrics = ['accuracy', 'f1', 'recall', 'precision', 'roc_auc']\n else:\n metrics = ['mean_absolute_error', 'r2', 'root_mean_squared_error',\n 'smape', 'mape']\n res_metrics = cross_validate(model, X, y, cv=cv,\n return_train_score=False,\n scoring=metrics)\n results = {metric.replace(\"test_\", \"\"): round(agg(\n res_metrics[metric]), 7)\n for metric in res_metrics}\n return results\n\n @classmethod\n def __multiclass_classification(cls, y_true, y_pred):\n \"\"\"\n Calculates some metrics for multiclass classification problems\n\n Parameters\n ----------\n y_true : array\n Target values\n y_pred : array\n Predicted values\n\n Returns\n -------\n dict : metrics results\n \"\"\"\n results = {'accuracy': accuracy_score(y_true, y_pred),\n 'f1': f1_score(y_true, y_pred, average='weighted'),\n 'precision': precision_score(y_true, y_pred,\n average='weighted'),\n 'recall': recall_score(y_true, y_pred,\n average='weighted')}\n return results\n\n @classmethod\n def __binary_classification(cls, y_true, y_pred, y_probs):\n \"\"\"\n Calculates some metrics for binary classification problems\n\n Parameters\n ----------\n y_true : array\n Target values\n y_pred : array\n Predicted values\n\n Returns\n -------\n dict : metrics results\n \"\"\"\n results = {'accuracy': accuracy_score(y_true, y_pred),\n 'f1': f1_score(y_true, y_pred),\n 'precision': precision_score(y_true, y_pred),\n 'recall': recall_score(y_true, y_pred),\n 'roc_auc': roc_auc_score(y_true, y_probs)}\n return results\n\n @classmethod\n def classification(cls, y_true, y_pred, y_probs):\n \"\"\"\n Checks which classification method will be applied:\n binary or multiclass\n\n Parameters\n ----------\n y_true : array\n Target values\n y_pred : array\n Predicted values\n y_probs : array\n Probabilities values\n\n Returns\n -------\n dict: metrics results\n \"\"\"\n if len(set(y_true)) > 2:\n results = cls.__multiclass_classification(y_true, y_pred)\n else:\n results = cls.__binary_classification(y_true, y_pred, y_probs)\n return results\n\n @classmethod\n def clusterization(cls, X, labels):\n \"\"\"\n Calculates some metrics on clustering quality\n\n Parameters\n ----------\n X : array[array], shape (n_linha, n_colunas)\n Matrix with the values that were used in the cluster\n labels : array, shape (n_linha, 1)\n Vector with labels selected by the clustering method\n (eg KMeans)\n\n Returns\n -------\n dict : metrics results\n \"\"\"\n results = {'silhouette': silhouette_score(X, labels,\n metric='euclidean'),\n 'calinski_harabaz': calinski_harabaz_score(X, labels)}\n return results\n","sub_path":"hermione/module_templates/__IMPLEMENTED_SAGEMAKER__/src/ml/model/metrics.py","file_name":"metrics.py","file_ext":"py","file_size_in_byte":6535,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"9252111","text":"#! /usr/bin/env python3\nimport sys, re, math\nfrom functools import partial\n\nfrom random import seed, random, randint\n\nverbose = len(sys.argv) > 1 and sys.argv[1] == '--verbose'\nlog = partial(print, flush = True, file = sys.stderr) if verbose\\\n else (lambda *a, **k: None)\n\n#Seed = None\nSeed = 12345\nIterations = 10000\n\nX, Y, Z, R = range(4)\n\nclass State:\n def __init__(self, nanobots, x = 0, y = 0, z = 0):\n self.x = x\n self.y = y\n self.z = z\n self.nanobots = nanobots\n self.error = self.__error()\n\n def distance_to_origin(self):\n return self.x + self.y + self.z\n\n def sample_neighbor(self, rangex, rangey, rangez):\n while True:\n axis = randint(0, 2)\n\n d = (1 << randint(0, 25)) * (-1) ** randint(0, 1)\n\n x, y, z = self.x, self.y, self.z\n\n if axis == X: x += d\n elif axis == Y: y += d\n else: z += d\n\n if x < rangex[0] or x > rangex[1]\\\n or y < rangey[0] or y > rangey[1]\\\n or z < rangez[0] or z > rangez[1]:\n continue\n\n if x != self.x or y != self.y or z != self.z:\n return State(self.nanobots, x, y, z)\n\n @staticmethod\n def sample(nanobots, rangex, rangey, rangez):\n x = randint(rangex[0], rangex[1])\n y = randint(rangey[0], rangey[1])\n z = randint(rangez[0], rangez[1])\n\n return State(nanobots, x, y, z)\n\n def __error(self):\n x, y, z = self.x, self.y, self.z\n return len(self.nanobots) - sum(in_range(b, (x, y, z, 0)) for b in self.nanobots)\n\n def __str__(self):\n return '({}, {}, {}) -> {}'.format(self.x, self.y, self.z, len(self.nanobots) - self.error)\n\ndef find_position(nanobots):\n minx = min(x - r for x, y, z, r in nanobots)\n miny = min(y - r for x, y, z, r in nanobots)\n minz = min(z - r for x, y, z, r in nanobots)\n maxx = max(x + r for x, y, z, r in nanobots)\n maxy = max(y + r for x, y, z, r in nanobots)\n maxz = max(z + r for x, y, z, r in nanobots)\n\n rangex = minx, maxx\n rangey = miny, maxy\n rangez = minz, maxz\n\n ranges = rangex, rangey, rangez\n\n seed(Seed)\n\n old = State.sample(nanobots, *ranges)\n best = old\n\n t0 = 1\n for k in range(Iterations):\n t = T(k, t0)\n\n new = old.sample_neighbor(*ranges)\n\n d = new.error - old.error\n\n log(\n 'T: {:10.3f}; Delta: {:12.3f}; Best: {}; New: {};'.format(t, d, best, new),\n ' ' * 10,\n end = '\\r'\n )\n\n if new.error <= old.error or P(d, t) >= random():\n old = new\n\n if new.error < best.error\\\n or (new.error == best.error and\n new.distance_to_origin() <\n best.distance_to_origin()):\n best = new\n\n log()\n\n min_dist = best.x + best.y + best.z\n max_bots = sum(in_range(b, (best.x, best.y, best.z, 0)) for b in nanobots)\n\n return min_dist, max_bots\n\ndef T(k, t0, tn = .0001, n = Iterations):\n return tn + .5 * (t0 - tn) * (1. + math.cos(k * math.pi / n))\n\ndef P(delta, t):\n return math.exp(-delta / t)\n\ndef in_range(reference, bot):\n return sum(abs(bot[i] - reference[i]) for i in (X, Y, Z)) <= reference[R]\n\ndef read():\n bots = []\n for record in map(partial(re.match, r'pos=<(-?\\d+),(-?\\d+),(-?\\d+)>, *r=(\\d+)'), sys.stdin.readlines()):\n x, y, z, r = map(int, record.groups())\n\n bots.append((x, y, z, r))\n\n return sorted(bots, reverse = True, key = lambda b: (b[R], b[X], b[Y], b[Z]))\n\n# Part 1\nnanobots = read()\n\nbot_with_largest_radius = nanobots[0]\n\nprint(sum(in_range(bot_with_largest_radius, b) for b in nanobots))\n\n# Part 2: Stochastic search with simulated annealing.\n# It only finds approximate solutions at a minimum,\n# but I was very pleased/surprised with the accuracy I got!\nmin_dist, max_bots = find_position(nanobots)\n\n#print(min_dist, '({} nanobots)'.format(max_bots))\nprint(min_dist)\n","sub_path":"day23_stochastic_search.py","file_name":"day23_stochastic_search.py","file_ext":"py","file_size_in_byte":4011,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"293881323","text":"#!/usr/bin/python3\nimport json\n\nwith open('incidents.json') as file: # Opening the json file\n content = json.load(file)\n\n\nlist = content[\"tickets\"] # Catching the dictionaries from the list\n\ndef makeScheme(): # This function just show the json in a different form\n cont = 0\n\n for dic in list:\n for key, value in dic.items():\n if key == 'ticket_id':\n print('\\n')\n print('{} - {} -> {}'.format(cont, key, value))\n cont += 1\n\n\n# This function bellow catch the maximum value of src_ip\ndef maxCommonSrcIp():\n commonDict = dict()\n\n for ticket in list:\n commonDict[ticket[\"src_ip\"]] = commonDict.get(ticket[\"src_ip\"], 0) + 1\n\n max_commonDict = max(commonDict, key = lambda k:commonDict[k])\n\n return max_commonDict\n\n\n# This function bellow get the quantity of destination ip given a src_ip\ndef qtdDstIp(ip):\n dst = dict()\n\n for ticket in list:\n if ip == ticket['src_ip']:\n dst[ticket[\"dst_ip\"]] = dst.get(ticket[\"dst_ip\"], 0) + 1\n\n lengthDst = len(dst.keys())\n return lengthDst\n\n\n# This function bellow get the average of all file_hash from json\ndef average():\n dictHash = dict()\n\n for ticket in list:\n dictHash[ticket[\"file_hash\"]] = dictHash.get(ticket[\"file_hash\"], 0) + 1\n\n allSum = float(sum(dictHash.values()))\n average = allSum / len(dictHash)\n\n return average\n\n# Bellow we have a example how to call the functions\n\n'''\nmakeScheme()\n\nmaxCommonSrcIp()\n\nqtdDstIp('186.120.220.162')\n\naverage = average()\nprint('{:.2f}'.format(average))\n'''\n","sub_path":"Desrouleaux/desrouleaux.py","file_name":"desrouleaux.py","file_ext":"py","file_size_in_byte":1574,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"570161002","text":"from django.contrib import admin\nfrom django.contrib.admin.filterspecs import FilterSpec\n\nfrom .models import License, Version\n\n\nclass LicenseAdmin(admin.ModelAdmin):\n list_display = ('id', 'name', 'builtin', 'url')\n list_filter = ('builtin',)\n ordering = ('builtin',)\n\n\nclass BuiltinFilterSpec(FilterSpec):\n \"\"\"Let us filter licenses by builtin/non-builtin.\"\"\"\n\n def __init__(self, field, request, params, model, model_admin):\n super(BuiltinFilterSpec, self).__init__(field, request, params,\n model, model_admin)\n self.lookup_kwarg = '%s__gt' % field.name\n self.lookup_val = request.GET.get(self.lookup_kwarg, False)\n\n def choices(self, cl):\n yield {'selected': not self.lookup_val,\n 'query_string': cl.get_query_string({}, [self.lookup_kwarg]),\n 'display': 'All licenses'}\n yield {'selected': self.lookup_val,\n 'query_string': cl.get_query_string({self.lookup_kwarg: 0}),\n 'display': 'Built-in licenses'}\n\n\nFilterSpec.filter_specs.insert(0,\n (lambda f: f.model is License, BuiltinFilterSpec))\n\nadmin.site.register(License, LicenseAdmin)\nadmin.site.register(Version)\n","sub_path":"apps/versions/admin.py","file_name":"admin.py","file_ext":"py","file_size_in_byte":1227,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"307972430","text":"#! python 3\n\n# from model import expected_cms_given_m\n# from model import expected_idp\n# import csv\nfrom model_evaluations import c_vs_id_evaluation\n\nL = [1000]\nmu = [1/1000]\ngenerations = [300]\n# GC = [1.0]\nkappa = [0.50,1.0, 2.0, 3.0, 4.0, 5.0, 6.0]\nphi = [0.25, 0.50, 0.75, 1.00]\n# iterations = 1000\n\nc_vs_id_evaluation(L, mu, generations, kappa, phi)\n\n# for l in L:\n# \tfor g in generations:\n# \t\t# for gc in GC:\n# \t\tfor k in kappa:\n# \t\t\tidps = g*[None]\n# \t\t\tcms = g*[None] # index = g - 1\n# \t\t\tfor i in range(g):\n# \t\t\t\tprint(1/l)\n# \t\t\t\tprint(k)\n# \t\t\t\tprint(phi)\n# \t\t\t\tprint(i+1)\n# \t\t\t\tidp = expected_idp(1/l, k, phi, i+1)\n# \t\t\t\texpected_cms = expected_cms_given_m(l,i+1,k,phi)\n# \t\t\t\tidps[i] = idp\n# \t\t\t\tcms[i] = expected_cms\n# \t\t\t\tprint(i)\n# \t\t\twith open(('model_id_vs_cm_data_' + str(l) + '_' + str(k) + '.csv'), 'w', newline = '') as f:\n# \t\t\t\twriter = csv.writer(f)\n# \t\t\t\twriter.writerow(['Number of Mutations per Strand', 'Expected ID%', 'Expected CMs']) # column headers\n# \t\t\t\tdata = [list(range(1,g+1)), idps, cms]\n# \t\t\t\tdata = zip(*data) # formats the data so it can be written row by row and produce two long columns\n# \t\t\t\twriter.writerows(data)","sub_path":"Model_and_Simulations/NEW/Old Direction/model_c_vs_id.py","file_name":"model_c_vs_id.py","file_ext":"py","file_size_in_byte":1155,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"644828154","text":"#!/usr/bin/env python3\n# -*- coding:utf-8 -*-\nu\"\"\"\nCreated at 2020.10.10 by Zhang Yiming\n\"\"\"\nimport os\nfrom glob import glob\nfrom multiprocessing import cpu_count, Pool\nfrom shutil import rmtree\n\nimport click\nimport pybedtools as pb\n\nfrom src import diff_cluster, diff_segmentReadCounts, diff_ru, diff_test\nfrom src.functions import sort_bedfile\n\n\ndef multiprocessing_diff_ru(data):\n\n for i in data[\"files\"]:\n sort_bedfile(i, i, sort_by_bedtools=True, add_header = False)\n\n diff_ru.diff_ru(\n data[\"files\"],\n segments=data[\"segments\"], \n condition=data[\"condition\"], \n input_cp=data[\"input_cp\"], \n output=data[\"output\"], \n min_segments=data[\"min_segments\"], \n verbose=data[\"verbose\"]\n )\n pb.helpers.cleanup()\n\n\n@click.command()\n@click.option(\n \"-i\", \"--input_dir\", type=click.Path(exists=True),\n help=\"Path to climb output directory\", required = True\n)\n@click.option(\"-o\", \"--output\", type=click.Path(),help=\"Prefix of output file\", required=True)\n@click.option(\"--min-conditions\", type=float, default=1, help=\"Minimum number of conditions for a gene to be clustered across conditions.\", show_default=True)\n@click.option(\n \"--minpts\", type=int, default=0, show_default=True, \n help=\"List of space-delimited DBSCAN minPts values. These indicate the minimum # points for DBSCAN to consider a core point. The minimum of this list will be used to cluster across conditions.\"\n)\n@click.option(\"--min-fc\", type=float, default=-1,help=\"Minimum fold change for change points.\", show_default=True)\n@click.option(\"--min-expn\", type=float, default=0, help=\"Minimum expression in exons for a gene to be clustered.\", show_default=True)\n@click.option(\"--lm-flag\", type=click.BOOL, default=False, show_default=True, help=\"Input are results from diff_cluster.\")\n@click.option(\"--ss-flag\", type=click.BOOL, default=False, show_default=True, help=\"Flag: RNA-Seq is strand-specific.\")\n@click.option(\n \"--eps\", type=float, default=-1, show_default=True,\n help=\"Maximum distance between 2 points in a neighborhood. -1.0 indicates using the minimum optimal window size from mountain climber.\"\n)\n@click.option(\"--bgminus\", type=click.Path(exists=True),help=\"List of space-delimited bedgraphs: minus strand. One file per line\", show_default=True)\n@click.option(\"--min-segments\", type=int, default=3, help=\"Minimum number of segments required in the TU to calculate relative end usage\", show_default=True)\n@click.option(\"-p\", \"--processes\", type=click.IntRange(1, cpu_count(), clamp=True), default=1, help=\"How many processes to use\", show_default=True)\n@click.option(\"--min-dstl-cov\", type=float, default=5, help=\"Minimum average reads per bp in distal segment across samples in at least 1 condition.\", show_default=True)\n@click.option(\"--min-prxl-cov\", type=float, default=0, help=\"Minimum average reads per bp in proximal segment across samples in all conditions.\", show_default=True)\n@click.option(\"--pmax\", type=float, default=0.05, help=\"Maximum p-value.\", show_default=True)\n@click.option(\"--dtop-abs-dif-min\", type=float, default=0.05, help=\"Minimum relative usage (RU) difference.\", show_default=True)\n@click.option(\"--root\", type=str, help=\"The root to compare to.\")\n@click.option('--verbose', type=click.BOOL, default=False, show_default=True, help='Print progress.')\n@click.option('--keep', type=click.BOOL, default=False, show_default=True, help='Keep temp file of diff_test.')\ndef diff(\n input_dir: str, output: str, min_conditions: int,\n minpts: int, min_fc: float, min_expn: float, \n lm_flag: bool, eps: float, ss_flag: bool,\n bgminus: str, min_segments: int, processes: int,\n min_dstl_cov:float, min_prxl_cov:float, pmax: float, dtop_abs_dif_min: float,\n verbose: bool, keep: bool, root: str\n):\n u\"\"\"\n differential analysis after climb pipline\n \n \\f\n Output files include _cluster_totals.txt, _segments.bed, _cp.bed, and one _cp.bed file for each condition. _cp.bed name field = label_prioritized;condition_labels:gene:TUstart:TUend:chrom:strand:dbscan_epsilon:min_clustered_change_point:max_clustered_change_point:cluster_standard_deviation:total_clusters. _segments.bed name field = label_prioritized_cp1;condition_labels_cp1|label_prioritized_cp2;condition_labels_cp2:gene:TUstart:TUend:chrom:strand:dbscan_epsilon.\n \"\"\"\n output = os.path.abspath(output)\n temp_dir = output + \"_tmp\"\n os.makedirs(temp_dir, exist_ok=True)\n pb.helpers.set_tempdir(temp_dir)\n \n # diff cluster\n cp_files = {}\n for x in glob(os.path.join(input_dir, \"*_CP.bed\")):\n c = os.path.basename(x).replace(\"_CP.bed\", \"\").split(\"_\")[1:]\n c = \"_\".join(c).strip(\"_\")\n\n temp = cp_files.get(c, [])\n temp.append(x)\n cp_files[c] = temp\n\n # construct the pairs\n comparisions = []\n if root:\n for c in cp_files.keys():\n if c != root:\n comparisions.append([root, c])\n else:\n cs = sorted(cp_files.keys())\n for i in range(len(cs)):\n for j in range(i+1, len(cs)):\n comparisions.append([cs[i], cs[j]])\n\n for i in comparisions:\n\n temp_diff_cluster_output = os.path.join(output, \"_vs_\".join(i), \"diff_cluster\")\n temp_diff_segments_output = os.path.join(output, \"_vs_\".join(i), \"segments_read_counts\")\n temp_diff_ru_output = os.path.join(output, \"_vs_\".join(i), \"diff_ru\")\n temp_diff_test_output = os.path.join(output, \"_vs_\".join(i), \"diff_test\")\n \n os.makedirs(temp_diff_cluster_output, exist_ok=True)\n temp_files, conditions = [], []\n for c in i:\n temp_files += cp_files[c]\n conditions += [c for _ in range(len(cp_files[c]))]\n\n diff_cluster.cluster(\n temp_files, os.path.join(temp_diff_cluster_output, \"diff\"), \n conditions, min_conditions, [minpts for _ in range(len(temp_files))], \n min_fc, min_expn, lm_flag, eps, ss_flag, \n verbose=verbose\n )\n pb.helpers.cleanup()\n\n # diff segment read count\n input_file, conditions = [], []\n for c in i:\n for x in glob(os.path.join(input_dir, f\"*_{c}.bedgraph\")):\n rc = os.path.basename(x).replace(\".bedgraph\", \"\").split(\"_\")\n rc = \"_\".join(rc[1:])\n\n if rc == c:\n input_file.append(x)\n # conditions.append(os.path.basename(x).replace(\".bedgraph\", \"\"))\n conditions.append(\"\")\n\n bgminus_list = None\n if bgminus:\n with open(bgminus) as r:\n bgminus_list = [x.strip() for x in r if x and os.path.exists(x.strip())]\n\n seg = os.path.join(temp_diff_cluster_output, \"diff_segments.bed\")\n sort_bedfile(seg, seg, add_header = False, sort_by_bedtools = True)\n os.makedirs(temp_diff_segments_output, exist_ok=True)\n diff_segmentReadCounts.read_count(\n segments=seg, \n conditions=conditions,\n bgplus=input_file, \n bgminus=bgminus_list, \n output=os.path.join(temp_diff_segments_output, \"diff\"),\n n_jobs=processes,\n )\n pb.helpers.cleanup()\n\n # diff_ru\n input_file = {}\n for x in glob(os.path.join(temp_diff_segments_output, \"*_readCounts.bed\")):\n c = os.path.basename(x).replace(\"_readCounts.bed\", \"\").replace(\"diff_\", \"\").split(\"_\")\n c = \"_\".join(c[1:]).strip(\"_\")\n temp = input_file.get(c, [])\n temp.append(x)\n input_file[c] = temp\n\n cmds = []\n \n for c, files in input_file.items():\n cmds.append({\n \"files\": files, \"condition\": c,\n \"segments\": os.path.join(temp_diff_cluster_output, \"diff_segments.bed\"), \n \"input_cp\": os.path.join(temp_diff_cluster_output, f\"diff_cp_{c}.bed\"),\n \"output\": os.path.join(temp_diff_ru_output, \"diff\"), \"min_segments\": min_segments,\n \"verbose\": verbose\n })\n\n os.makedirs(temp_diff_ru_output, exist_ok=True)\n with Pool(min(processes, len(cmds))) as p:\n p.map(multiprocessing_diff_ru, cmds)\n\n cmds = {\n \"input_file\": [], \"conditions_input\": [],\n \"ru_segments\": set(), \"conditions_ru_segments\": set()\n }\n\n for c in i:\n files = input_file[c]\n for f in files:\n cmds[\"input_file\"].append(f)\n cmds[\"conditions_input\"].append(c)\n \n cmds[\"ru_segments\"].add(os.path.join(temp_diff_ru_output, f\"diff_ru_segments_{c}.bed\"))\n cmds[\"conditions_ru_segments\"].add(c)\n \n os.makedirs(temp_diff_test_output, exist_ok=True)\n diff_test.test(\n input_file=cmds[\"input_file\"], ru_segments=list(cmds[\"ru_segments\"]), \n output=os.path.join(temp_diff_test_output, f\"diff_{'_'.join(i)}\"), \n conditions_input=cmds[\"conditions_input\"], conditions_ru_segments=list(cmds[\"conditions_ru_segments\"]), \n dtop_abs_dif_min=dtop_abs_dif_min, min_dstlCov=min_dstl_cov, \n min_prxlCov=min_prxl_cov, pmax=pmax, \n verbose=verbose, keep=keep\n )\n\n if os.path.exists(temp_dir):\n rmtree(temp_dir)\n # python src/diff_cluster.py -i tests/science/C000R7B4_neutrophil_CP.bed tests/science/S001QBB1_HSC_CP.bed -c nerutrophil HSC -o tests/diff_test1\n # python src/diff_segmentReadCounts.py -i tests/diff_test_segments.bed -p tests/science/C000R7B4_neutrophil.bedgraph tests/science/S001QBB1_HSC.bedgraph -c nerutrophil HSC -o tests/diff\n # python src/diff_ru.py -i tests/diff_C000R7B4_neutrophil_nerutrophil_readCounts.bed -s tests/diff_test_segments.bed -c neutrophil -o tests/diff_neutrophil -l tests/diff_test_cp_nerutrophil.bed","sub_path":"cli/diff.py","file_name":"diff.py","file_ext":"py","file_size_in_byte":9828,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"205209414","text":"import asyncio\nimport aiomysql as aiomysql\n\n\nfrom multicp import multicp_logger_nr, multicp_logger\nfrom multicp.connection.ConnectionInterface import ConnectionAsyncInterface\nfrom multicp.connection.DBConnection import DBConnection\nfrom multicp.connection.TransactionConnection import TransactionConnection\n\nfrom multicp.connection.sql.Parser import Parser\nfrom multicp.util.Basic import gen_id\nfrom multicp.util.DateUtil import make_timestamp\n\n\nclass Connection(ConnectionAsyncInterface, DBConnection, TransactionConnection):\n\n def __init__(self, host=\"127.0.0.1\", port=\"3306\",\n db=\"db\", user=\"root\", password=\"\",\n charset = \"utf8\",loop=None,\n connection_timeout=60\n ):\n self.host = host\n self.port = port\n self.db = db\n self.user = user\n self.password = password\n self.charset = charset\n\n self.connector = None\n\n self.auto_commit = True\n\n self.id = id(self)\n self.loop = loop\n if self.loop is None:\n self.loop = asyncio.get_event_loop()\n\n\n self._last_check_health_time=None\n self._timeout = connection_timeout\n async def connect(self):\n config = {\n 'host': self.host, # 默认127.0.0.1\n 'user': self.user,\n 'password': self.password,\n 'port': int(self.port), # 默认即为3306\n 'db': self.db,\n 'charset': self.charset, # 默认即为utf8\n \"loop\":self.loop\n }\n\n connection = await aiomysql.connect(**config)\n self.connector = connection\n self._last_check_health_time = make_timestamp()\n\n async def disconnect(self):\n self.connector.close()\n\n async def check(self):\n if make_timestamp() - self._last_check_health_time > self._timeout:\n cursor = None\n try:\n cursor = await self.connector.cursor()\n await cursor.execute(\"SHOW DATABASES\")\n await cursor.fetchall()\n multicp_logger_nr.info(\"AioMysql connection check success\")\n self._last_check_health_time = make_timestamp()\n return True\n except Exception as e:\n return False\n finally:\n if cursor:\n cursor.close()\n else:\n self._last_check_health_time = make_timestamp()\n return True\n\n\n\n async def exec(self, sql, field_list = None, outer_cursor = None):\n if not field_list:\n field_list = []\n if not outer_cursor:\n cursor = await self.connector.cursor(aiomysql.DictCursor)\n else:\n cursor = outer_cursor\n\n multicp_logger.debug(\"{} | {}\".format(sql, field_list))\n await cursor.execute(sql, tuple(field_list))\n result = await cursor.fetchall()\n # data = [dict_data for dict_data in result]\n # logging.debug(\"返回数据 %s\"%data)\n\n if self.auto_commit:\n await self.connector.commit()\n\n if not outer_cursor:\n await cursor.close()\n\n return result\n\n async def begin_transaction(self):\n self.auto_commit = False\n await self.connector.begin()\n\n async def commit(self):\n await self.connector.commit()\n self.auto_commit = True\n\n async def rollback(self):\n await self.connector.rollback()\n self.auto_commit = True\n\n\n async def add(self, data, obj, return_id=False, pid_use_int=False):\n \"\"\"\n\n :param data:\n :param obj:\n :param return_id: 将来废弃:如果为False不会返回ID,如果是一个id域,给这个ID加1返回ID\n :param pid_use_int: 将来废弃:如果为真,则用int型自增id来确保一致性,注意这样性能很差,不建议在大量插入的时候使用\n :return:\n\n 注意,自增ID实现方式为锁表,效率较差,如果postoragesql可以优化一下\n \"\"\"\n\n if return_id:\n if pid_use_int:\n p = Parser(obj)\n sql, fill_data = p.add(data)\n data = await self.exec(sql, fill_data)\n\n max_id = await self.exec(\"select LAST_INSERT_ID() as max\")\n return max_id[0][\"max\"]\n else:\n pid = gen_id()\n data[return_id] = str(pid)\n p = Parser(obj)\n sql, fill_data = p.add(data)\n await self.exec(sql, fill_data)\n return data[return_id]\n else:\n p = Parser(obj)\n sql, fill_data = p.add(data)\n\n data = await self.exec(sql, fill_data)\n\n return data\n\n async def add_by_id(self, data, obj):\n \"\"\"\n 添加并返回id的实现\n :param data:\n :param obj:\n :return:\n \"\"\"\n p = Parser(obj)\n sql, fill_data = p.add(data)\n data = await self.exec(sql, fill_data)\n max_id = await self.exec(\"select LAST_INSERT_ID() as max\")\n return max_id[0][\"max\"]\n\n async def update(self, limit, data, obj):\n p = Parser.build_query(obj, limit)\n sql, fill_data = p.update(data)\n multicp_logger_nr.debug(\"{}-{}\".format(sql,fill_data))\n data = await self.exec(sql, fill_data)\n\n return data\n\n async def delete(self, limit, obj):\n p = Parser.build_query(obj,limit)\n sql, fill_data = p.delete()\n\n data = await self.exec(sql, fill_data)\n\n return data\n\n async def get(self, limit, obj, count=None):\n if count:\n data = await self.count(limit,obj,count)\n else:\n p = Parser.build_query(obj, limit)\n sql, fill_data = p.get()\n\n data = await self.exec(sql, fill_data)\n\n return data\n async def count(self, limit, obj, count):\n if \"$start\" in limit:\n del limit[\"$start\"]\n if \"$limit\" in limit:\n del limit[\"$limit\"]\n if \"$link\" in limit:\n del limit[\"$link\"]\n limit.update({\n \"$field\": [\"count(%s) as count\" % count]\n })\n count_data = await self.get(limit, obj)\n if not count_data:\n return 0\n count = count_data[0][\"count\"]\n return count\n\n @staticmethod\n def get_type():\n from multicp.Constant import TYPE_ASYNCIO\n return TYPE_ASYNCIO\n","sub_path":"multicp/connection/sql/async_mysql/Connection.py","file_name":"Connection.py","file_ext":"py","file_size_in_byte":6398,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"474304700","text":"# !/usr/bin/env python3\n# _*_coding:utf-8_*_\n# __author__:FLS\n\nimport argparse\n\nparser=argparse.ArgumentParser(description='功能:输入数字计算数字的和',\n\t\t\t\t\t\t\t usage='python3 %(prog)s [option]',\n\t\t\t\t\t\t\t epilog='祝你用的愉快',\n\t\t\t\t\t\t\t )\n\n# 位置参数是必须要填的\n# parser.add_argument('sum1',type=int,nargs='+',default=0,help='传入的数字')\n# args=parser.parse_args() # 执行这条命令后才能真正添加进参数\n# print(args)\n# print(args.sum1)\n# print(sum(args.sum1))\n\n# 位置参数有多个的情况:\n# parser.add_argument('sum2',type=int,nargs='+',default=0,help='传入的数字')\n# args=parser.parse_args()\n# print(args.sum1,args.sum2) # [1, 2] [3],就是最后一个变量只有一个参数,多的参数都给前面。\n\n\n'''\n设置参数的类型,并且要接受多个数值:\nadd_argument中有type参数可以设置传入参数的数据类型。我们看到代码中有type这个关键词,该关键词可以传入list, str, tuple, set, dict等。例如我们把上面的type=str,改成type=int,这时候我们就可以进行四则运算。\n'''\n# parser.add_argument('sum',type=int,nargs='+',help='输入的数字')\n# 参数nargs:\n# nargs='*'  表示参数可设置零个或多个\n# nargs='+' 表示参数可设置一个或多个\n# nargs='?' 表示参数可设置零个或一个\n# args=parser.parse_args()\n# print(args.sum)\n# print(sum(args.sum))\n\n\n\n'''\n位置参数改成关键字参数(其实是可选参数--) --是长参数格式,也是默认显示的格式,-是短参数格式\n在命令行中传入参数时候,传入的参数的先后顺序不同,运行结果往往会不同,这是因为采用了位置参数,改写成关键字参数\n'''\nparser.add_argument('-f','--first',dest='fr',type=str,help='姓')\nparser.add_argument('-s','--second',dest='se',type=str,help='名')\n# args=parser.parse_args()\n# print(args.fr+args.se)\n'''\n参数默认值\nadd_argument中有一个default参数。有的时候需要对某个参数设置默认值,即如果命令行中没有传入该参数的值,程序使用默认值。如果命令行传入该参数,则程序使用传入的值\n'''\n# parser.add_argument('--first',type=str,default='张',help='姓')\n# parser.add_argument('--second',type=str,default='三',help='名')\n# args=parser.parse_args()\n# print(args.first+args.second)\n\n\n'''\n必需参数 这个只是在可选参数的必须参数,\nadd_argument有一个required参数可以设置该参数是否必需。\n'''\n# parser.add_argument('--first',type=str,default='张',help='姓')\n# parser.add_argument('--second',type=str,required=True,help='名')\n# args=parser.parse_args()\n# print(args.first+args.second)\n\n\n'''\n# ArgumentParser类的理解:\n\nclass ArgumentParser(_AttributeHolder, _ActionsContainer):\n \"\"\"Object for parsing command line strings into Python objects.\n\n Keyword Arguments:\n - prog -- The name of the program (default: sys.argv[0])\n - usage -- A usage message (default: auto-generated from arguments)\n - description -- A description of what the program does\n - epilog -- Text following the argument descriptions\n - parents -- Parsers whose arguments should be copied into this one\n - formatter_class -- HelpFormatter class for printing help messages\n - prefix_chars -- Characters that prefix optional arguments\n - fromfile_prefix_chars -- Characters that prefix files containing\n additional arguments\n - argument_default -- The default value for all arguments\n - conflict_handler -- String indicating how to handle conflicts\n - add_help -- Add a -h/-help option\n \"\"\"\n\n def __init__(self,\n prog=None,\n usage=None,\n description=None,\n epilog=None,\n version=None,\n parents=[],\n formatter_class=HelpFormatter,\n prefix_chars='-',\n fromfile_prefix_chars=None,\n argument_default=None,\n conflict_handler='error',\n add_help=True):\nprog - 程序的名字(默认:sys.argv[0])\nusage - 描述程序用法的字符串(默认:从解析器的参数生成)\ndescription - 参数帮助信息之前的文本(默认:空)\nepilog - 参数帮助信息之后的文本(默认:空)\nparents - ArgumentParser 对象的一个列表,这些对象的参数应该包括进去\nformatter_class - 定制化帮助信息的类\nprefix_chars - 可选参数的前缀字符集(默认:‘-‘)\nfromfile_prefix_chars - 额外的参数应该读取的文件的前缀字符集(默认:None)\nargument_default - 参数的全局默认值(默认:None)\nconflict_handler - 解决冲突的可选参数的策略(通常没有必要)\nadd_help - 给解析器添加-h/–help 选项(默认:True)\n\n\n\n\nArgumentParser.add_argument方法:\n\nArgumentParser.add_argument(name or flags...[, action][, nargs][, const][, default][, type][, choices][, required][, help][, metavar][, dest])\n定义应该如何解析一个命令行参数。下面每个参数有它们自己详细的描述,简单地讲它们是:\n\nname or flags - 选项字符串的名字或者列表,例如foo 或者-f, --foo。\naction - 在命令行遇到该参数时采取的基本动作类型。\nnargs - 应该读取的命令行参数数目。\nconst - 某些action和nargs选项要求的常数值。\ndefault - 如果命令行中没有出现该参数时的默认值。\ntype - 命令行参数应该被转换成的类型。\nchoices - 参数可允许的值的一个容器。\nrequired - 该命令行选��是否可以省略(只针对可选参数)。\nhelp - 参数的简短描述。\nmetavar - 参数在帮助信息中的名字。\ndest - 给parse_args()返回的对象要添加的属性名称,如果没有这个,默认就是长格式的值。\n\n\n\n\n重点介绍:\naction: 这个参数算是一个重头戏而且可以继承 argparse.Action 定制自己的 action 。先介绍几个这个参数常用的变量\n\n复制代码\n'store' - 只是保存参数的值。这是默认的动作。例如:\n\n>>>\n>>> parser = argparse.ArgumentParser()\n>>> parser.add_argument('--foo')\n>>> parser.parse_args('--foo 1'.split())\nNamespace(foo='1')\n'store_const' - 保存由const关键字参数指出的值。(注意const关键字参数默认是几乎没有帮助的None。)'store_const'动作最常用于指定某种标记的可选参数。例如:\n\n>>>\n>>> parser = argparse.ArgumentParser()\n>>> parser.add_argument('--foo', action='store_const', const=42)\n>>> parser.parse_args('--foo'.split())\nNamespace(foo=42)\n'store_true'和'store_false' - 它们是'store_const' 的特殊情形,分别用于保存值True和False。另外,它们分别会创建默认值False 和True。例如:\n\n>>>\n>>> parser = argparse.ArgumentParser()\n>>> parser.add_argument('--foo', action='store_true')\n>>> parser.add_argument('--bar', action='store_false')\n>>> parser.add_argument('--baz', action='store_false')\n>>> parser.parse_args('--foo --bar'.split())\nNamespace(bar=False, baz=True, foo=True)\n'append' - 保存一个列表,并将每个参数值附加在列表的后面。这对于允许指定多次的选项很有帮助。示例用法:\n\n>>>\n>>> parser = argparse.ArgumentParser()\n>>> parser.add_argument('--foo', action='append')\n>>> parser.parse_args('--foo 1 --foo 2'.split())\nNamespace(foo=['1', '2'])\n'append_const' - 保存一个列表,并将const关键字参数指出的值附加在列表的后面。(注意const关键字参数默认是None。)'append_const' 动作在多个参数需要保存常量到相同的列表时特别有用。例如:\n\n>>>\n>>> parser = argparse.ArgumentParser()\n>>> parser.add_argument('--str', dest='types', action='append_const', const=str)\n>>> parser.add_argument('--int', dest='types', action='append_const', const=int)\n>>> parser.parse_args('--str --int'.split())\nNamespace(types=[, ])\n\n\n'count' - 计算关键字参数出现的次数。例如,这可用于增加详细的级别:\n>>> parser = argparse.ArgumentParser()\n>>> parser.add_argument('--verbose', '-v', action='count')\n>>> parser.parse_args('-vvv'.split())\nNamespace(verbose=3)\n'help' - 打印当前解析器中所有选项的完整的帮助信息然后退出。默认情况下,help动作会自动添加到解析器中。参见ArgumentParser以得到如何生成输出信息。\n\n'version' - 它期待version=参数出现在add_argument()调用中,在调用时打印出版本信息并退出:\n>>>\n>>> import argparse\n>>> parser = argparse.ArgumentParser(prog='PROG')\n>>> parser.add_argument('--version', action='version', version='%(prog)s 2.0')\n>>> parser.parse_args(['--version'])\nPROG 2.0\n\n\n\n\n添加互斥选项:\nexptypegroup=parser.add_mutually_exclusive_group() #添加一组互斥的选项,如上例中的-l和-r只能用一个\nexptypegroup.add_argument(\"-r\",\"--read\",help=\"Read Action\",action=\"store_true\")\nexptypegroup.add_argument(\"-w\",\"--write\",help=\"Write Action\",action=\"store_true\")\nARGS=parser.parse_args()\n\n'''\n\n\n\n\n\n\n\n\n\n\n\n# 这个和 sys 模块的联系:\n# import sys\n#\n# print(sys.argv)\n# print(sys.exit(1))\n# print(sys.version)\n# print(sys.path)\n# print(sys.stdin)\n# print(sys.stdout)\n# print(sys.stderror)\n\n\n\n\n\n","sub_path":"基本模块库/运维脚本/argparse模块.py","file_name":"argparse模块.py","file_ext":"py","file_size_in_byte":9309,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"120289471","text":"# coding=utf-8\n#\n# Created by junn, on 2018/6/25\n#\n\n# \n\nimport logging\n\nfrom nmis.projects.models import ProjectMilestoneState\nfrom runtests import BaseTestCase\nfrom runtests.common.mixins import ProjectPlanMixin\nfrom utils import times\n\nlogger = logging.getLogger(__name__)\n\n\nclass ProjectTestCase(BaseTestCase, ProjectPlanMixin):\n\n def setUp(self):\n super(ProjectTestCase, self).setUp()\n self.create_default_flow(self.organ)\n self.project = self.create_project(self.admin_staff, self.dept)\n self.performer = self.create_completed_staff(self.organ, self.dept, name=\"项目负责人x\")\n # self.flow = self.create_flow(self.organ)\n\n def test_project_dispatch(self):\n \"\"\"\n 测试: 项目分配(分配项目负责人,分配默认流程,项目直接进入需求论证里程碑)\n \"\"\"\n self.assertTrue(self.project.is_unstarted())\n\n success, result = self.project.dispatch(self.performer)\n self.assertTrue(success)\n self.assertFalse(self.project.is_unstarted()) # 分配后项目后状态发生改变(变成已启动状态)\n self.assertIsNotNone(self.project.performer)\n\n def test_project_redispatch(self):\n \"\"\"\n 测试: 项目重新分配(不改变项目的里程碑状态,只改变项目负责人信息)\n \"\"\"\n self.assertTrue(self.project.is_unstarted())\n # 先分配项目负责人\n dispatch_success, result = self.project.dispatch(self.performer)\n self.assertTrue(dispatch_success)\n self.assertFalse(self.project.is_unstarted())\n self.assertIsNotNone(self.project.performer)\n\n # 重新分配项目负责人\n redispatch_success = self.project.redispatch(self.admin_staff)\n self.assertTrue(redispatch_success)\n self.assertFalse(self.project.is_unstarted())\n self.assertEqual(self.admin_staff, self.project.performer)\n\n def test_change_milestone(self):\n \"\"\"\n 测试: 变更项目里程碑项\n \"\"\"\n\n # 分配负责人\n self.assertTrue(self.project.status == 'PE')\n\n default_flow = self.get_default_flow()\n if not default_flow:\n self.create_flow(self.organ)\n\n self.assertTrue(\n self.project.dispatch(self.performer)\n )\n self.assertTrue(self.project.status == 'SD')\n\n first_main_milestone = self.project.attached_flow.get_first_main_milestone()\n first_main_milestone_state = ProjectMilestoneState.objects.get_pro_milestone_state_by_project_milestone(\n project=self.project, milestone=first_main_milestone)\n\n self.assertEqual(first_main_milestone_state.status, \"DOING\", \"里程碑状态异常\")\n\n success, msg = self.project.change_project_milestone_state(first_main_milestone_state)\n self.assertTrue(success)\n\n success, msg = self.project.change_project_milestone_state(first_main_milestone_state)\n self.assertFalse(success)\n\n # self.assertEqual(self.project.current_stone, self.flow.get_first_main_milestone())\n #\n # # new_milestone = self.project.current_stone\n # # success, msg = self.project.change_milestone(new_milestone)\n # # self.assertFalse(success)\n #\n # new_milestone = self.project.current_stone.next()\n # success, msg = self.project.change_milestone(new_milestone, done_sign='UN')\n # self.assertTrue(success)\n # self.assertEqual(self.project.current_stone, new_milestone)\n # self.assertTrue(self.project.contains_project_milestone_state(new_milestone))\n\n\nclass MilestoneTestCase(BaseTestCase, ProjectPlanMixin):\n def setUp(self):\n super(MilestoneTestCase, self).setUp()\n\n def test_next(self):\n\n default_flow = self.get_default_flow()\n if not default_flow:\n default_flow = self.create_default_flow(self.organ)\n default_flow.get_milestones()\n main_milestone1 = default_flow.get_first_main_milestone()\n self.assertEqual(main_milestone1.title, \"需求论证\")\n\n main_milestone2 = main_milestone1.next()\n self.assertEqual(main_milestone2.title, '圈定方案')\n main_milestone2_child1 = main_milestone2.next()\n self.assertEqual(main_milestone2_child1.title, '调研')\n main_milestone2_child2 = main_milestone2_child1.next()\n self.assertEqual(main_milestone2_child2.title, '方案收集')\n main_milestone2_child3 = main_milestone2_child2.next()\n self.assertEqual(main_milestone2_child3.title, '方案论证')\n\n main_milestone3 = main_milestone2_child3.next()\n self.assertEqual(main_milestone3.title, '采购管理')\n main_milestone3_child1 = main_milestone3.next()\n self.assertEqual(main_milestone3_child1.title, '确定采购方式')\n main_milestone3_child2 = main_milestone3_child1.next()\n self.assertEqual(main_milestone3_child2.title, '启动采购')\n main_milestone3_child3 = main_milestone3_child2.next()\n self.assertEqual(main_milestone3_child3.title, '合同管理')\n\n main_milestone4 = main_milestone3_child3.next()\n self.assertEqual(main_milestone4.title, '实施验收')\n main_milestone4_child1 = main_milestone4.next()\n self.assertEqual(main_milestone4_child1.title, '到货')\n main_milestone4_child2 = main_milestone4_child1.next()\n self.assertEqual(main_milestone4_child2.title, '实施调试')\n main_milestone4_child3 = main_milestone4_child2.next()\n self.assertEqual(main_milestone4_child3.title, '项目验收')\n self.assertEqual(main_milestone4_child3.next(), None)\n","sub_path":"apps/runtests/units/test_milestones.py","file_name":"test_milestones.py","file_ext":"py","file_size_in_byte":5654,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"485249414","text":"# coding: utf-8\n# Copyright 2013 The Font Bakery 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# See AUTHORS.txt for the list of Authors and LICENSE.txt for the License.\nimport os.path as op\n\nfrom checker.base import BakeryTestCase as TestCase\nfrom checker.metadata import Metadata\nfrom checker.ttfont import Font\n\n\nclass CheckCanonicalWeights(TestCase):\n\n path = '.'\n targets = 'metadata'\n name = __name__\n tool = 'lint'\n\n def read_metadata_contents(self):\n return open(self.path).read()\n\n def test_check_canonical_weights(self):\n contents = self.read_metadata_contents()\n fm = Metadata.get_family_metadata(contents)\n for font_metadata in fm.fonts:\n weight = font_metadata.weight\n first_digit = weight / 100\n is_invalid = (weight % 100) != 0 or (first_digit < 1\n or first_digit > 9)\n _ = (\"%s: The weight is %d which is not a \"\n \"multiple of 100 between 1 and 9\")\n\n self.assertFalse(is_invalid, _ % (op.basename(self.path),\n font_metadata.weight))\n\n tf = Font.get_ttfont_from_metadata(self.path, font_metadata)\n _ = (\"%s: METADATA.json overwrites the weight. \"\n \" The METADATA.json weight is %d and the font\"\n \" file %s weight is %d\")\n _ = _ % (font_metadata.filename, font_metadata.weight,\n font_metadata.filename, tf.OS2_usWeightClass)\n\n self.assertEqual(tf.OS2_usWeightClass, font_metadata.weight)\n","sub_path":"checker/tests/test_check_canonical_weights.py","file_name":"test_check_canonical_weights.py","file_ext":"py","file_size_in_byte":2140,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"16939007","text":"from selenium import webdriver\nfrom selenium.webdriver.common.keys import Keys\nfrom selenium.webdriver.common.by import By\nimport time\n\n\nclass GoogleMapsScraper:\n\n def urlGen(addr1,addr2):\n url = \"http://google.com/maps/dir/\"+addr1.replace(\" \",\"+\")+\"/\"+addr2.replace(\" \",\"+\")\n return url\n\n def setupBrowser():\n options = webdriver.ChromeOptions()\n options.add_argument('--headless')\n #options.add_experimental_option(\"detach\", True)\n driver = webdriver.Chrome(chrome_options=options)\n print(\"opening chrome\")\n return driver\n\n def goToPage(url,driver):\n driver.get(url)\n\n def goToWalkingTab(driver):\n time.sleep(1)\n driver.find_element_by_css_selector('.travel-mode:nth-child(4) button').click()\n time.sleep(1.5)\n\n def collectWalkingTime(driver):\n test = driver.find_element_by_css_selector(\"[jstcache='447']\")\n return (test.text)\n\n def returnWalkingTime(loc1,loc2):\n driver = setupBrowser()\n url = urlGen(loc1,loc2)\n goToPage(url,driver)\n goToWalkingTab(driver)\n time = collectWalkingTime(driver)\n #time = 0\n return time\n\n def test():\n addr1 = \"409 may ave south plainfield nj\"\n addr2 = \"200 lake street south plainfield nj\"\n addr3 = \"empire state building\"\n addr4 = \"flatiron building\"\n addr5 = \"hershey park\"\n addr6 = \"giant center\"\n print(\"starting\")\n url = urlGen(addr1,addr6)\n print(\"url generated is\",url)\n driver = setupBrowser()\n goToPage(url,driver)\n goToWalkingTab(driver)\n print(collectWalkingTime(driver))\n","sub_path":"google_maps_scraper.py","file_name":"google_maps_scraper.py","file_ext":"py","file_size_in_byte":1677,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"560162734","text":"\"\"\"\nDiffraction functions\n\"\"\"\nfrom __future__ import absolute_import, print_function, division\n\nfrom dtmm.conf import cached_function, BETAMAX, FDTYPE, CDTYPE\nfrom dtmm.wave import betaphi\nfrom dtmm.window import tukey\nfrom dtmm.data import refind2eps\nfrom dtmm.tmm import phase_mat, polarizer4x4, alphaffi, alphaf, transmission_mat, alphaEEi, tr_mat, t_mat\nfrom dtmm.linalg import dotmdm, dotmf\nfrom dtmm.fft import fft2, ifft2\nfrom dtmm.jones import jonesvec\nimport numpy as np\n\n\nDIFRACTION_PARAMETERS = (\"distance\", \"mode\")#, \"refind\")\n\n@cached_function\ndef diffraction_alphaf(shape, ks, epsv = (1.,1.,1.), \n epsa = (0.,0.,0.), betamax = BETAMAX, out = None):\n\n ks = np.asarray(ks)\n ks = abs(ks)\n beta, phi = betaphi(shape,ks)\n epsv = np.asarray(epsv, CDTYPE)\n epsa = np.asarray(epsa, FDTYPE)\n\n alpha, f= alphaf(beta,phi,epsv,epsa,out = out) \n\n out = (alpha,f)\n\n mask0 = (beta >= betamax)\n \n f[mask0] = 0.\n alpha[mask0] = 0.\n\n return out\n\n\n\n@cached_function\ndef diffraction_alphaffi(shape, ks, epsv = (1.,1.,1.), \n epsa = (0.,0.,0.), betamax = BETAMAX, out = None):\n\n\n ks = np.asarray(ks)\n ks = abs(ks)\n beta, phi = betaphi(shape,ks)\n\n alpha, f, fi = alphaffi(beta,phi,epsv,epsa,out = out) \n\n out = (alpha,f,fi)\n \n# try:\n# b1,betamax = betamax\n# a = (betamax-b1)/(betamax)\n# m = tukey(beta,a,betamax)\n# np.multiply(f,m[...,None,None],f)\n# except:\n# pass\n mask0 = (beta >= betamax)#betamax)\n fi[mask0] = 0.\n f[mask0] = 0.\n alpha[mask0] = 0.\n #return mask, alpha,f,fi\n \n return out\n\n\n@cached_function\ndef E_diffraction_alphaEEi(shape, ks, epsv = (1,1,1), \n epsa = (0.,0.,0.), mode = +1, betamax = BETAMAX, out = None):\n\n ks = np.asarray(ks)\n ks = abs(ks)\n beta, phi = betaphi(shape,ks)\n\n mask0 = (beta >= betamax)#betamax)\n \n alpha, j, ji = alphaEEi(beta,phi,epsv,epsa, mode = mode, out = out) \n ji[mask0] = 0.\n j[mask0] = 0.\n alpha[mask0] = 0.\n out = (alpha,j,ji)\n return out\n\n \ndef phase_matrix(alpha, kd, mode = None, mask = None, out = None):\n kd = np.asarray(kd, dtype = FDTYPE)\n out = phase_mat(alpha,kd[...,None,None], out = out) \n if mode == \"t\" or mode == +1:\n out[...,1::2] = 0.\n elif mode == \"r\" or mode == -1:\n out[...,::2] = 0.\n if mask is not None:\n out[mask] = 0.\n return out \n\n@cached_function\ndef field_diffraction_matrix(shape, ks, d = 1., epsv = (1,1,1), epsa = (0,0,0.), mode = \"b\", betamax = BETAMAX, out = None):\n ks = np.asarray(ks, dtype = FDTYPE)\n epsv = np.asarray(epsv, dtype = CDTYPE)\n epsa = np.asarray(epsa, dtype = FDTYPE)\n alpha, f, fi = diffraction_alphaffi(shape, ks, epsv = epsv, epsa = epsa, betamax = betamax)\n kd =ks * d\n pmat = phase_matrix(alpha, kd , mode = mode)\n return dotmdm(f,pmat,fi,out = out) \n\n@cached_function\ndef E_diffraction_matrix(shape, ks, d = 1., epsv = (1,1,1), epsa = (0,0,0.), mode = +1, betamax = BETAMAX, out = None):\n ks = np.asarray(ks, dtype = FDTYPE)\n epsv = np.asarray(epsv, dtype = CDTYPE)\n epsa = np.asarray(epsa, dtype = FDTYPE)\n alpha, j, ji = E_diffraction_alphaEEi(shape, ks, epsv = epsv, epsa = epsa, mode = mode, betamax = betamax)\n kd =ks * d\n pmat = phase_matrix(alpha, kd)\n return dotmdm(j,pmat,ji,out = out) \n\n\n#@cached_function\n#def jones_transmission_matrix(shape, ks, epsv_in = (1.,1.,1.), epsa_in = (0.,0.,0.),\n# epsv_out = (1.,1.,1.), epsa_out = (0.,0.,0.), mode = +1, betamax = BETAMAX, out = None):\n# \n# \n# alpha, fin,fini = diffraction_alphaffi(shape, ks, epsv = epsv_in, \n# epsa = epsa_in, betamax = betamax)\n# \n# alpha, fout,fouti = diffraction_alphaffi(shape, ks, epsv = epsv_out, \n# epsa = epsa_out, betamax = betamax)\n# \n# return transmission_mat(fin, fout, fini = fini, mode = mode, out = out)\n#\n@cached_function\ndef E_tr_matrix(shape, ks, epsv_in = (1.,1.,1.), epsa_in = (0.,0.,0.),\n epsv_out = (1.,1.,1.), epsa_out = (0.,0.,0.), mode = +1, betamax = BETAMAX, out = None):\n \n \n alpha, fin,fini = diffraction_alphaffi(shape, ks, epsv = epsv_in, \n epsa = epsa_in, betamax = betamax)\n \n alpha, fout,fouti = diffraction_alphaffi(shape, ks, epsv = epsv_out, \n epsa = epsa_out, betamax = betamax)\n \n return tr_mat(fin, fout, fini = fini, mode = mode, out = out)\n#\n#@cached_function\n#def jones_t_matrix(shape, ks, epsv_in = (1.,1.,1.), epsa_in = (0.,0.,0.),\n# epsv_out = (1.,1.,1.), epsa_out = (0.,0.,0.), mode = +1, betamax = BETAMAX, out = None):\n# \n# \n# alpha, fin,fini = diffraction_alphaffi(shape, ks, epsv = epsv_in, \n# epsa = epsa_in, betamax = betamax)\n# \n# alpha, fout,fouti = diffraction_alphaffi(shape, ks, epsv = epsv_out, \n# epsa = epsa_out, betamax = betamax)\n# \n# return t_mat(fin, fout, fini = fini, mode = mode, out = out)\n \n\n@cached_function\ndef projection_matrix(shape, ks, epsv = (1,1,1),epsa = (0,0,0.), mode = +1, betamax = BETAMAX, out = None):\n \"\"\"Computes a reciprocial field projection matrix.\n \"\"\"\n ks = np.asarray(ks, dtype = FDTYPE)\n epsv = np.asarray(epsv, dtype = CDTYPE)\n epsa = np.asarray(epsa, dtype = FDTYPE) \n alpha, f, fi = diffraction_alphaffi(shape, ks, epsv = epsv, epsa = epsa, betamax = betamax)\n kd = np.zeros_like(ks)\n pmat = phase_matrix(alpha, kd , mode = mode)\n return dotmdm(f,pmat,fi,out = out) \n \n \ndef diffract(fieldv, dmat, window = None, out = None): \n f = fft2(fieldv, out = out)\n f2 = dotmf(dmat, f ,out = f)\n out = ifft2(f2, out = out)\n if window is not None:\n out = np.multiply(out,window,out = out)\n return out\n\ndef diffracted_field(field, wavenumbers, d = 0.,n = 1, mode = \"t\", betamax = BETAMAX, out = None):\n eps = refind2eps([n]*3)\n pmat = field_diffraction_matrix(field.shape[-2:], wavenumbers, d = d, epsv = eps, epsa = (0.,0.,0.), mode = mode, betamax = betamax)\n return diffract(field, pmat, out = out) \n#\n#def transmitted_field(field, wavenumbers, n = 1, betamax = BETAMAX, out = None):\n# eps = refind2eps([n]*3)\n# pmat = projection_matrix(field.shape[-2:], wavenumbers, epsv = eps, epsa = (0.,0.,0.), mode = \"t\", betamax = betamax)\n# return diffract(field, pmat, out = out) \n#\n#def reflected_field(field, wavenumbers, n = 1, betamax = BETAMAX, out = None):\n# eps = refind2eps([n]*3)\n# pmat = projection_matrix(field.shape[-2:], wavenumbers, epsv = eps, epsa = (0.,0.,0.), mode = \"r\", betamax = betamax)\n# return diffract(field, pmat, out = out) \n\n__all__ = []\n","sub_path":"dtmm/diffract.py","file_name":"diffract.py","file_ext":"py","file_size_in_byte":6836,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"181722632","text":"#!/usr/bin/env python\n\nfrom bs4 import BeautifulSoup\nimport img2pdf\nfrom md2pdf.core import md2pdf\nimport os\nimport requests\nimport shutil\nimport sys\nimport json\nimport argparse\n\n\ndef get_arguments():\n parser = argparse.ArgumentParser(\n description='Download documents/text from scribd.com')\n\n parser.add_argument(\n 'content',\n metavar='CONTENT',\n type=str,\n help='scribd url to download')\n parser.add_argument(\n '-i',\n '--images',\n help=\"download url made up of images\",\n action='store_true',\n default=False)\n parser.add_argument(\n '-p',\n '--pdf',\n help='convert images to pdf (*Nix: imagemagick)',\n action='store_true',\n default=False)\n\n return parser.parse_args()\n\n\ndef is_book(url):\n return '/book/' in url or '/read/' in url\n\n\n# fix encoding issues in python2\ndef fix_encoding(query):\n if sys.version_info > (3, 0):\n return query\n else:\n return query.encode('utf-8')\n\n\ndef sanitize_title(title):\n '''\n Remove forbidden characters from title that will prevent OS from creating directory. (For Windows at least.)\n Also change ' ' to '_' to preserve previous behavior.\n '''\n forbidden_chars = \" *\\\"/\\<>:|(),\"\n replace_char = \"_\"\n\n for ch in forbidden_chars:\n title = title.replace(ch, replace_char)\n\n return title\n\n\nclass ScribdDocument:\n def __init__(self, url, images, pdf):\n self.url = url\n self.images = images\n self.images_list = []\n self.pdf = pdf\n\n def get_document(self):\n response = requests.get(self.url).text\n soup = BeautifulSoup(response, 'html.parser')\n\n title = soup.find('title').get_text()\n title = sanitize_title(title)\n train = 1\n print(title + '\\n')\n\n if self.images:\n # sometimes images embedded directly in html as well\n absimg = soup.find_all('img', {'class':'absimg'}, src=True)\n for img in absimg:\n train = self._save_content(img['src'], True, train, title)\n else:\n print('Extracting text to ' + title + '.txt\\n')\n\n found = train > 1\n js_text = soup.find_all('script', type='text/javascript')\n\n for opening in js_text:\n\n for inner_opening in opening:\n portion1 = inner_opening.find('https://')\n\n if not portion1 == -1:\n portion2 = inner_opening.find('.jsonp')\n jsonp = inner_opening[portion1:portion2+6]\n\n train = self._save_content(jsonp, train, title, found)\n\n if self.pdf:\n self._convert_to_pdf(title)\n\n def _save_image(self, content, imagename, found=False):\n already_present = os.listdir('.')\n if imagename in already_present:\n return\n\n if content.endswith('.jsonp'):\n replacement = content.replace('/pages/', '/images/')\n if found:\n replacement = replacement.replace('.jsonp', '/000.jpg')\n else:\n replacement = replacement.replace('.jsonp', '.jpg')\n else:\n replacement = content\n\n response = requests.get(replacement, stream=True)\n with open(imagename, 'wb') as out_file:\n shutil.copyfileobj(response.raw, out_file)\n self.images_list.append(imagename)\n\n def _save_text(self, jsonp, filename):\n response = requests.get(jsonp).text\n page_no = response[11:12]\n\n response_head = (\n response).replace('window.page' + page_no + '_callback([\"',\n '').replace('\\\\n', '').replace('\\\\', '').replace(\n '\"]);', '')\n soup_content = BeautifulSoup(response_head, 'html.parser')\n\n for x in soup_content.find_all('span', {'class': 'a'}):\n xtext = fix_encoding(x.get_text())\n print(xtext)\n\n extraction = xtext + '\\n'\n with open(filename, 'a') as feed:\n feed.write(extraction)\n\n # detect image and text\n def _save_content(self, content, train, title, found=False):\n if not content == '':\n if self.images:\n imagename = title + '_' + str(train) + '.jpg'\n print('Downloading image to ' + imagename)\n self._save_image(content, imagename, found)\n else:\n self._save_text(content, (title + '.txt'))\n train += 1\n\n return train\n\n def _convert_to_pdf(self, title):\n if self.images_list:\n try:\n with open(title.strip('_') + '.pdf', 'wb') as f:\n f.write(img2pdf.convert([open(img, 'rb') for img in self.images_list]))\n print('PDF file generated.')\n except Exception as e:\n print('PDF conversion failed: ' + str(e))\n\n\nclass ScribdBook:\n def __init__(self, url):\n self.url = url\n\n def _extract_text(self, content):\n words = []\n for word in content['words']:\n if word.get('break_map', None):\n words.append(word['break_map']['text'])\n elif word.get('text', None):\n words.append(word['text'])\n else:\n words += self._extract_text(word)\n return words\n\n def get_book(self):\n book_id = self._get_book_id()\n token = self._get_token(book_id)\n\n chapter = 1\n string_text = ''\n\n while True:\n url = self._format_content_url(book_id, chapter, token)\n response = requests.get(url)\n\n try:\n json_response = json.loads(response.text)\n for block in json_response['blocks']:\n if block['type'] == 'text':\n string_text += ' '.join(self._extract_text(block)) + '\\n\\n'\n print(string_text)\n elif block['type'] == 'image':\n image_url = self._format_image_url(book_id, chapter, block['src'], token)\n imagename = block['src'].replace('images/', '')\n string_text += '![{}]({})\\n\\n'.format(imagename, image_url)\n\n chapter += 1\n\n except ValueError:\n print('No more content being exposed by Scribd!')\n pdf_out = '{}.pdf'.format(book_id)\n print('Generating PDF file: {}'.format(pdf_out))\n md2pdf(pdf_out, md_content=string_text)\n break\n\n def _format_content_url(self, book_id, chapter, token):\n unformatted_url = ('https://www.scribd.com/scepub/{}/chapters/{}/'\n 'contents.json?token={}')\n return unformatted_url.format(book_id, chapter, token)\n\n def _format_image_url(self, book_id, chapter, image, token):\n unformatted_url = ('https://www.scribd.com/scepub/{}/chapters/{}/'\n '{}?token={}')\n return unformatted_url.format(book_id, chapter, image, token)\n\n def _get_book_id(self):\n splits = self.url.split('/')\n for split in splits:\n try:\n book_id = int(split)\n except ValueError:\n continue\n return book_id\n\n def _get_token(self, book_id):\n token_url = 'https://www.scribd.com/read2/{}/access_token'.format(book_id)\n token = requests.post(token_url)\n return json.loads(token.text)['response']\n\n\ndef command_line():\n args = get_arguments()\n url = args.content\n if is_book(url):\n book = ScribdBook(url)\n book.get_book()\n else:\n images = args.images\n pdf = args.pdf\n document = ScribdDocument(url, images, pdf)\n document.get_document()\n\n\nif __name__ == '__main__':\n\n command_line()\n","sub_path":"scribdl/scribdl.py","file_name":"scribdl.py","file_ext":"py","file_size_in_byte":7844,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"443623800","text":"import random\r\nimport sys, os\r\nfrom scipy.stats import pearsonr\r\nfrom scipy.stats import spearmanr\r\nfrom scipy.stats import scoreatpercentile\r\nfrom itertools import combinations\r\n\r\n#python calculate_EC1.py /mnt/home/john3784/1-herb_CRE_project/clustering/clusters_all/ /mnt/home/john3784/1-herb_CRE_project/herbivory-wounding_data/logFC_matrices/logFC_gene_matrix_herb-wound-hormone-Appel-abiotic-biotic.txt exprs_coeff\r\naracyc = sys.argv[1] #pathway_genelist_exp\r\ndict = {}\r\nfor file in os.listdir(aracyc):\r\n #if file.endswith(\"man\"):\r\n filename = file.split(\".\")\r\n p = filename[1]\r\n file1 = aracyc+file\r\n a = open(file1, \"r\")\r\n line = a.readline()\r\n while line:\r\n inf = line.strip().split('\\t')\r\n print (inf)\r\n if inf == '':\r\n pass\r\n elif inf == ' ':\r\n pass\r\n else:\r\n gene = inf[0]\r\n #print (gene)\r\n if p in dict:\r\n dict[p].append(gene)\r\n else:\r\n dict[p] = [gene]\r\n line = a.readline()\r\n a.close()\r\n\r\nexpression = sys.argv[2]\r\ntype = sys.argv[3]\r\nexpression_open = open(expression, 'r')\r\nline1 = expression_open.readline()\r\nline1 = expression_open.readline()\r\ndict_e = {}\r\ngen_list = []\r\nwhile line1:\r\n info = line1.strip().split()\r\n gen_list.append(info[0])\r\n dict_e[info[0]] = [float(i) for i in info[1:]]\r\n line1 = expression_open.readline()\r\npcc_list =[]\r\nsp_list = []\r\nfor i in range(1, 500000):\r\n a = random.choice(gen_list)\r\n b = random.choice(gen_list)\r\n x = dict_e[a]\r\n y = dict_e[b]\r\n #sp= spearmanr(x, y)[0]\r\n pcc= pearsonr(x, y)[0]\r\n #sp_list.append(sp)\r\n pcc_list.append(pcc)\r\n \r\nthreshold2 = scoreatpercentile(pcc_list, 95)\r\n#threshold2 = 0.404774\r\n\r\noutput = open('EC_%s' % type, 'w')\r\n\r\noutput.write(\"Pathway\\tEC95pcc_%f\\t#ofgenes\\t#ofgenesinexpress\\n\" %(threshold2))\r\n\r\ndict_ec = {}\r\ndict_ec2 ={}\r\n\r\nfor bio in dict:\r\n ec =0\r\n pcc_path_list = []\r\n new_list =[]\r\n genez = dict[bio]\r\n count2_random=0\r\n pcc_random =[]\r\n #for file in os.listdir(expression):\r\n # name = file.split(\"_\")\r\n # name = name[0]\r\n for el in genez:\r\n if el in dict_e:\r\n new_list.append(el)\r\n leng_genez = float(len(new_list))\r\n for combo in combinations(new_list, 2):\r\n gen1=list(combo)[0]\r\n gen2=list(combo)[1]\r\n gen1exp = dict_e[gen1]\r\n gen2exp = dict_e[gen2]\r\n pcc_path = pearsonr(gen1exp, gen2exp)[0]\r\n pcc_path_list.append(pcc_path)\r\n count2 = 0\r\n for p in pcc_path_list:\r\n if p > threshold2:\r\n count2 = count2 + 1\r\n if leng_genez > 2:\r\n ec2 = float(count2)/float((leng_genez*(leng_genez-1)/2))\r\n else: \r\n ec2 = \"NA\"\r\n output.write(\"%s\\t%s\\t%i\\t%i\\n\" % (bio, str(ec2), len(genez), len(new_list)))\r\n \r\nexpression_open.close()\r\noutput.close()\r\n\r\n\r\n\r\n\r\n","sub_path":"parse_scripts/calculate_EC1.py","file_name":"calculate_EC1.py","file_ext":"py","file_size_in_byte":2984,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"653861368","text":"'''\nThis problem was asked by LinkedIn.\n\nGiven a list of points, a central point, and an integer k, find the nearest k points from the central point.\n\nFor example, given the list of points [(0, 0), (5, 4), (3, 1)], the central point (1, 2), and k = 2, return [(0, 0), (3, 1)]\n'''\nfrom heapq import *\nimport math\n\ndef solve(points,central,k):\n\tif len(points)<=k:\n\t\treturn points\n\tpq = []\n\tfor point in points:\n\t\tneg_distance = neg_dist(point,central)\n\t\tif len(pq)Name:%{customdata[0]}
    Load:%{customdata[1]}
    Acc/Dec:%{customdata[2]}
    Turns:%{customdata[3]}\",\n )\n )\n\n\n\n bubble_fig.update_layout(\n template=\"plotly_white\",\n transition={\n 'duration': 500,\n 'easing': 'cubic-in-out'\n },\n xaxis={\"autorange\": False, \"title\": \"Average Acc and Dec\"},\n yaxis={\"autorange\": False, \"title\": \"Average Turns\"},\n margin=dict(\n t=0,\n pad=1\n ),\n hoverlabel=dict(\n bgcolor=\"white\",\n font_size=16,\n font_family=\"Rockwell\"\n )\n )\n\n bubble_fig.update_xaxes(range=[acc_min*0.9, acc_max*1.1])\n bubble_fig.update_yaxes(range=[turns_min*0.9, turns_max*1.1])\n\n # load fig\n load_fig = go.Figure(data=[\n go.Bar(\n name=\"Players\",\n x=data_df['name'],\n y=data_df['exerciseLoad'],\n marker_color=\"#F18412\",\n ),\n go.Scatter(\n name=\"Team Average\",\n mode=\"lines\",\n x=data_df['name'],\n y=[round(player_df['exerciseLoad'].mean(),2)]*len(data_df),\n marker_color=\"black\",\n )\n ]\n )\n\n load_fig.update_layout(\n template=\"plotly_white\",\n transition={\n 'duration': 500,\n 'easing': 'cubic-in-out'\n },\n margin=dict(\n t=0,\n pad=1\n ),\n yaxis_title=\"Exercise Load (AU)\",\n hoverlabel=dict(\n bgcolor=\"white\",\n font_size=16,\n font_family=\"Rockwell\"\n ),\n hovermode=\"x unified\"\n )\n\n # acc/dec fig\n acc_dec_fig = go.Figure(data=[\n go.Bar(\n name=\"Acc Mid\",\n x=data_df['name'],\n y=data_df['accMidCount'],\n offsetgroup=0,\n marker_color=\"#42C939\",\n ),\n\n go.Bar(\n name=\"Acc High\",\n x=data_df['name'],\n y=data_df['accHighCount'],\n base=data_df['accMidCount'],\n offsetgroup=0,\n marker_color=\"#70DE68\",\n ),\n\n go.Bar(\n name=\"Dec Mid\",\n x=data_df['name'],\n y=data_df['decMidCount'],\n offsetgroup=1,\n marker_color=\"#E0C835\"\n ),\n\n go.Bar(\n name=\"Dec High\",\n x=data_df['name'],\n y=data_df['decHighCount'],\n base=data_df['decMidCount'],\n offsetgroup=1,\n marker_color=\"#F0F02D\",\n ),\n ])\n\n acc_dec_fig.update_layout(\n template=\"plotly_white\",\n transition={\n 'duration': 500,\n 'easing': 'cubic-in-out'\n },\n margin=dict(\n t=0,\n pad=1\n ),\n yaxis_title=\"Acc / Dec\",\n hoverlabel=dict(\n bgcolor=\"white\",\n font_size=16,\n font_family=\"Rockwell\"\n ),\n hovermode=\"x unified\"\n )\n\n # left/right turn fig\n left_right_turns_fig = go.Figure(data=[\n \n ])\n\n left_right_turns_fig.update_layout(\n template=\"plotly_white\",\n transition={\n 'duration': 500,\n 'easing': 'cubic-in-out'\n },\n margin=dict(\n t=0,\n pad=1\n ),\n yaxis_title=\"Left Right\",\n hoverlabel=dict(\n bgcolor=\"white\",\n font_size=16,\n font_family=\"Rockwell\"\n ),\n hovermode=\"x unified\"\n )\n\n # turn plots into children\n bubble_children = [\n html.H5(\"Bubble Chart\", style={\"textAlign\": \"center\"}),\n dcc.Graph(\n id=\"select-bubble-fig\",\n figure=bubble_fig\n )\n ]\n\n load_children = [\n html.H5(\"Load\", style={\"textAlign\": \"center\"}),\n dcc.Graph(\n id=\"select-load-fig\",\n figure=load_fig\n )\n ]\n\n acc_dec_children = [\n html.H5(\"Accelerations | Decelerations\",\n style={\"textAlign\": \"center\"}),\n dcc.Graph(\n id=\"select-acc-dec-fig\",\n figure=acc_dec_fig\n )\n ]\n\n left_right_turns_children = [\n html.H5(\"Left Turns | Right Turns\", style={\"textAlign\": \"center\"}),\n dcc.Graph(\n id=\"select-left-right-fig\",\n figure=left_right_turns_fig\n )\n ]\n\n return bubble_children, load_children, acc_dec_children, left_right_turns_children\n else:\n return [], [], [], []\n","sub_path":"keycloak/BigDataProject-master/forward-sports-basketball-dashboard/app/basketballApp/basketballDashboard/basketballApps/select.py","file_name":"select.py","file_ext":"py","file_size_in_byte":15094,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"508144934","text":"\"\"\" 581. Shortest Unsorted Continuous Subarray\nhttps://leetcode.com/problems/shortest-unsorted-continuous-subarray/\n\nGiven an integer array nums, you need to find one continuous subarray that\nif you only sort this subarray in ascending order,\nthen the whole array will be sorted in ascending order.\n\nReturn the shortest such subarray and output its length.\n\nExample 1:\nInput: nums = [2,6,4,8,10,9,15]\nOutput: 5\nExplanation: You need to sort [6, 4, 8, 10, 9] in ascending order\nto make the whole array sorted in ascending order.\n\nExample 2:\nInput: nums = [1,2,3,4]\nOutput: 0\n\nExample 3:\nInput: nums = [1]\nOutput: 0\n\nConstraints:\n1 <= nums.length <= 10^4\n-10^5 <= nums[i] <= 10^5\n\"\"\"\n\n\nclass Solution:\n def find_unsorted_subarray(self, nums: list[int]) -> int:\n # good (easy to understand) solution - found\n end_subarray = 0\n max_seen = -1000000\n for i in range(0, len(nums)):\n max_seen = max(max_seen, nums[i])\n if nums[i] < max_seen:\n end_subarray = i\n\n if end_subarray == 0:\n return 0\n\n start_subarray = 0\n min_seen = 1000000\n for i in range(len(nums) - 1, -1, -1):\n min_seen = min(min_seen, nums[i])\n if nums[i] > min_seen:\n start_subarray = i\n\n return end_subarray - start_subarray + 1\n\n# Runtime: 228 ms, faster than 29.03% of Python3 online submissions for Shortest Unsorted Continuous Subarray.\n# Memory Usage: 15.3 MB, less than 65.09% of Python3 online submissions for Shortest Unsorted Continuous Subarray.\n\n\n # my_solution (with help)\n left_idx = len(nums) - 1\n left_stack = [nums[0]]\n for i in range(1, len(nums)):\n if left_stack[-1] > nums[i]:\n while left_stack:\n if left_stack[-1] <= nums[i]:\n break\n left_stack.pop()\n left_idx = min(left_idx, len(left_stack))\n left_stack.append(nums[i])\n\n if left_idx == len(nums) - 1:\n return 0\n\n right_idx = 0\n right_stack = [nums[-1]]\n for i in range(len(nums) - 2, -1, -1):\n if right_stack[-1] < nums[i]:\n while right_stack:\n if right_stack[-1] >= nums[i]:\n break\n right_stack.pop()\n right_idx = max(len(nums) - len(right_stack), right_idx)\n right_stack.append(nums[i])\n\n return right_idx - left_idx\n\n# Runtime: 304 ms, faster than 5.02% of Python3 online submissions for Shortest Unsorted Continuous Subarray.\n# Memory Usage: 15.5 MB, less than 28.41% of Python3 online submissions for Shortest Unsorted Continuous Subarray.\n\n\nif __name__ == '__main__':\n\n my_solution = Solution()\n in_lst = [2,6,4,8,10,9,15]\n in_lst = [0, 1, 2, 3, 4]\n in_lst = [-1, 0, -2, 2, 4, 3]\n\n\n #\n print(\"input: {}\".format(in_lst))\n print(\"result: {}\".format(my_solution.find_unsorted_subarray(in_lst)))\n\n","sub_path":"05/80-89/0581-shortest-unsorted-continuous-subarray/solution.py","file_name":"solution.py","file_ext":"py","file_size_in_byte":3004,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"460289100","text":"from django.shortcuts import render_to_response\nfrom nice_data_app.models import Team, Employee, Coaching_overview, Coaching_topics_discussed, Daily_average\nfrom django.core import serializers\nimport json\n\n# Create your views here.\n\nteams = Team.objects.all()\nemployees = Employee.objects.all()\ndaily_averages = Daily_average.objects.all();\n\nteamFields = Team.objects.model._meta.get_fields()\nemployeeFields = Employee.objects.model._meta.get_fields()\ncoaching_topics_discussed_fields = Coaching_topics_discussed._meta.get_fields()\ndaily_average_fields = Daily_average._meta.get_fields()\n\nteams_json = serializers.serialize(\"json\", teams)\nemployees_json = serializers.serialize(\"json\", employees)\ncoaching_overviews_json = serializers.serialize(\"json\", Coaching_overview.objects.all())\ncoaching_topics_discussed_json = serializers.serialize(\"json\", Coaching_topics_discussed.objects.all())\ndaily_average_json = serializers.serialize(\"json\", daily_averages)\n\ndef base(request):\n return render_to_response('base.html')\n\n\ndef home(request):\n return render_to_response('index.html', {\"teams\": teams, \"teams_json\": teams_json, \"employees\": employees,\n \"employees_json\": employees_json, \"employeeFields\": employeeFields,\n \"coaching_overviews_json\": coaching_overviews_json,\n \"coaching_topics_discussed_json\": coaching_topics_discussed_json,\n \"coaching_topics_discussed_fields\": coaching_topics_discussed_fields,\n \"daily_average\": daily_average_json,\n \"daily_average_fields\": daily_average_fields})\n\ndef team_details(request):\n return render_to_response('team_details.html')\n\ndata = json.dumps({\"employees\": employees_json, \"teams\":teams_json,\n \"coaching_topics_discussed\": coaching_topics_discussed_json,\n \"coaching_overviews\":coaching_overviews_json})\n\nhandle1 = open('file.txt', 'w+')\nhandle1.write(data)\nhandle1.close()","sub_path":"nice_data_app/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2125,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"80719461","text":"# 298. Binary Tree Longest Consecutive Sequence\n# https://leetcode.com/problems/binary-tree-longest-consecutive-sequence/#/description\n\n# Solution:\n# DFS: calculate \n# 1) longest consecutive path starting from current node\n# 2) longest consecutive path starting from any node in the current subtree\n\n# Notes:\n# *) Always check input : None, len == 0, val == 0\n\n\n# Definition for a binary tree node.\n# class TreeNode(object):\n# def __init__(self, x):\n# self.val = x\n# self.left = None\n# self.right = None\n\nclass Solution(object):\n def DFS(self, root):\n root_len = 1\n root_max_len = 1\n\n for child in (root.left, root.right):\n if child != None:\n child_len, child_max_len = self.DFS(child)\n if root.val + 1 == child.val:\n root_len = max(root_len, 1 + child_len)\n root_max_len = max(root_max_len, child_max_len)\n \n root_max_len = max(root_max_len, root_len)\n\n return root_len, root_max_len \n\n def longestConsecutive(self, root):\n \"\"\"\n :type root: TreeNode\n :rtype: int\n \"\"\"\n if root == None:\n return 0\n else:\n _, max_len = self.DFS(root)\n return max_len\n\n","sub_path":"298.py","file_name":"298.py","file_ext":"py","file_size_in_byte":1171,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"617701718","text":"# Эта программа применяет метод writelines для сохранения\n# списка строковых значений в файл.\n\ndef main():\n # Создать список строковых значений.\n cities = ['Нью-Йорк', 'Бостон', 'Атланта', 'Даллас']\n\n # Открыть файл для записи.\n with open('cities.txt', 'w') as outfile:\n # Записать список в файл.\n outfile.writelines(cities)\n\n # Закрыть файл.\n outfile.close()\n\n# Вызвать главную функцию.\nmain()","sub_path":"7/writelines.py","file_name":"writelines.py","file_ext":"py","file_size_in_byte":620,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"296073250","text":"#!/usr/bin/python\n#\n# Copyright 2018-2022 Polyaxon, Inc.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\ndef get_resource_path(run_path: str, kind: str = None, name: str = None) -> str:\n _path = \"{}/resources\".format(run_path)\n if kind:\n _path = \"{}/{}\".format(_path, kind)\n if name:\n _path = \"{}/{}.plx\".format(_path, name)\n\n return _path\n\n\ndef get_event_path(run_path: str, kind: str = None, name: str = None) -> str:\n _path = \"{}/events\".format(run_path)\n if kind:\n _path = \"{}/{}\".format(_path, kind)\n if name:\n _path = \"{}/{}.plx\".format(_path, name)\n\n return _path\n\n\ndef get_event_assets_path(run_path: str, kind: str = None) -> str:\n _path = \"{}/assets\".format(run_path)\n if kind:\n _path = \"{}/{}\".format(_path, kind)\n return _path\n\n\ndef get_asset_path(\n run_path: str, kind: str = None, name: str = None, step: int = None, ext=None\n) -> str:\n _path = get_event_assets_path(run_path, kind)\n if name:\n _path = \"{}/{}\".format(_path, name)\n if step is not None:\n _path = \"{}_{}\".format(_path, step)\n if ext:\n _path = \"{}.{}\".format(_path, ext)\n\n return _path\n","sub_path":"traceml/traceml/events/paths.py","file_name":"paths.py","file_ext":"py","file_size_in_byte":1671,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"460517803","text":"import os\nimport sys\nimport json\nfrom os.path import isfile\n\nimport requests\n\ntry:\n import config\nexcept ImportError:\n sys.exit(\"Unable to load configuration file. See README for more information\")\n\n# Create module-wide authenticated session\nauth_session = requests.Session()\nauth_session.headers = {\n 'Authorization': 'Bearer {0}'.format(\n config.auth_token)}\n\n\ndef get_course():\n try:\n response = auth_session.get(\n ''.join([config.domain, '/api/v1/courses']))\n finally:\n auth_session.close()\n \n latestTerm = 0\n for i in range(len(response.json())):\n if 'enrollment_term_id' in response.json()[i] and response.json()[i]['enrollment_term_id'] > latestTerm:\n latestTerm = response.json()[i]['enrollment_term_id']\n\n courses = list(\n filter(\n lambda a: 'enrollment_term_id' in a and a['enrollment_term_id'] >= latestTerm and 'name' in a,\n response.json()))\n\n for i in range(len(courses)):\n print(\"[{0}] {1}\".format(i + 1, courses[i]['name']))\n\n selection = int(input(\"Select Course: \")) - 1\n\n return courses[selection]['id']\n\n\ndef get_assignment(class_id):\n url = ''.join(\n [config.domain, '/api/v1/courses/{0}/assignments'.format(class_id)])\n params = {'include': ['submission']}\n try:\n response = auth_session.get(url, params=params)\n finally:\n auth_session.close()\n assignments = list(\n filter(\n lambda a: 'online_upload' in a['submission_types'] and a['locked_for_user'] != True,\n response.json()))\n\n print()\n if not assignments:\n print(\"This class has no assignments available for you.\")\n return None\n for i in range(len(assignments)):\n print(\"[{0}] {1}\".format(i + 1, assignments[i]['name']))\n\n selection = int(input(\"Select assignment: \")) - 1\n \n if 'submission' in assignments[selection] and assignments[selection]['submission']['submitted_at'] != None:\n choice = \"\"\n while choice != \"n\" and choice != \"y\":\n choice = input(\"This assignment already has a submisson. Continue? [y/n]: \")\n if choice.lower() == \"n\":\n return None\n\n return assignments[selection]['id']\n\n\ndef get_file():\n cwd = os.getcwd()\n files = list(filter(isfile, os.listdir(cwd)))\n\n if not files:\n print(\"No files to upload in current directory.\")\n return None;\n print()\n for i in range(len(files)):\n print(\"[{0}] {1}\".format(i + 1, files[i]))\n\n selection = int(input(\"Select file: \")) - 1\n\n return files[selection]\n","sub_path":"UserInterface.py","file_name":"UserInterface.py","file_ext":"py","file_size_in_byte":2601,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"652403185","text":"import cv2\n# Load an color image in grayscale\nimg1 = cv2.imread('C:/Users/Dinesh/Pictures/face_eye.jpg',1)\nimg = cv2.imread('C:/Users/Dinesh/Pictures/face_eye.jpg',0)\ntmpl = cv2.imread('C:/Users/Dinesh/Pictures/eye.png',0)\nw, h = tmpl.shape[::-1]\nres = cv2.matchTemplate(img,tmpl,cv2.TM_CCORR_NORMED)\nmin_val, max_val, min_loc, max_loc = cv2.minMaxLoc(res)\ncv2.imshow('image',img)\ntop_left = max_loc\nbottom_right = (top_left[0] + w, top_left[1] + h)\ncv2.rectangle(img1,top_left, bottom_right, (0,0,255), 4)\ncv2.imshow('result',img1)\ncv2.imshow('template',tmpl)\ncv2.waitKey(0)\ncv2.destroyAllWindows()","sub_path":"templatematching.py","file_name":"templatematching.py","file_ext":"py","file_size_in_byte":599,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"562686680","text":"#! /usr/bin/env python\n\"\"\"Preparation of curations\"\"\"\nfrom __future__ import annotations\n\nfrom dataclasses import dataclass\n\nimport timeout_decorator\nimport zope.interface\nfrom dataclasses_jsonschema import JsonSchemaMixin\n\nimport colrev.env.package_manager\nimport colrev.ops.search_sources\nimport colrev.record\n\nif False: # pylint: disable=using-constant-test\n from typing import TYPE_CHECKING\n\n if TYPE_CHECKING:\n import colrev.ops.prep\n\n# pylint: disable=too-few-public-methods\n# pylint: disable=duplicate-code\n\n\n@zope.interface.implementer(colrev.env.package_manager.PrepPackageEndpointInterface)\n@dataclass\nclass CurationPrep(JsonSchemaMixin):\n \"\"\"Preparation of curations\"\"\"\n\n settings_class = colrev.env.package_manager.DefaultSettings\n ci_supported: bool = True\n\n source_correction_hint = \"check with the developer\"\n always_apply_changes = True\n\n def __init__(\n self,\n *,\n prep_operation: colrev.ops.prep.Prep, # pylint: disable=unused-argument\n settings: dict,\n ) -> None:\n self.settings = self.settings_class.load_settings(data=settings)\n\n self.prep_operation = prep_operation\n\n @timeout_decorator.timeout(20, use_signals=False)\n def prepare(\n self,\n prep_operation: colrev.ops.prep.Prep, # pylint: disable=unused-argument\n record: colrev.record.PrepRecord,\n ) -> colrev.record.Record:\n \"\"\"Prepare records in a CoLRev curation\"\"\"\n\n # pylint: disable=too-many-branches\n\n if (\n record.data[\"colrev_status\"]\n == colrev.record.RecordState.rev_prescreen_excluded\n ):\n return record\n\n if record.data.get(\"year\", \"UNKNOWN\") == \"UNKNOWN\":\n record.data[\n \"colrev_status\"\n ] = colrev.record.RecordState.md_needs_manual_preparation\n colrev.record.Record(data=record.data).add_masterdata_provenance(\n key=\"year\",\n source=\"colrev_curation.masterdata_restrictions\",\n note=\"missing\",\n )\n return record\n\n applicable_restrictions = (\n prep_operation.review_manager.dataset.get_applicable_restrictions(\n record_dict=record.data,\n )\n )\n\n colrev.record.Record(data=record.data).apply_restrictions(\n restrictions=applicable_restrictions\n )\n if any(\n \"missing\" in note\n for note in [\n x[\"note\"]\n for x in record.data.get(\"colrev_masterdata_provenance\", {}).values()\n ]\n ):\n colrev.record.Record(data=record.data).set_status(\n target_state=colrev.record.RecordState.md_needs_manual_preparation\n )\n return record\n\n\nif __name__ == \"__main__\":\n pass\n","sub_path":"colrev/ops/built_in/prep/curation_prep.py","file_name":"curation_prep.py","file_ext":"py","file_size_in_byte":2826,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"607108157","text":"\n'''Communicator which handles UDP/TCP communication\n\n'''\nimport inspect\nimport json\nimport logging\nimport math\nimport socket\nimport struct\nimport threading\nimport collections\nimport time\n\n\nTAG_SIZE = 4\nSEQ_SIZE = 2\nUDP = 10\nTCP = 20\n\nsocket.setdefaulttimeout(1.5)\nlogger = logging.getLogger(__name__)\n\n\ndef get_mtu():\n '''Attempts to return the MTU for the network by finding the min of the\n first hop MTU and 576 bytes. i.e min(MTU_fh, 576)\n\n Note that the 576 byte sized MTU does not account for the checksum/ip headers so\n when sending data we need to take the IP/protocol headers into account.\n\n The current implementation just assumes the default minimum of 576.\n We should try to implement something to actually calculate min(MTU_fh, 576)\n\n Returns:\n int: 576\n '''\n return 576\n\ndef default_log_callback(sender, tag, data):\n logger.error('MESSAGE from {}; TAG {}; DATA {}'.format(sender, tag, data))\n\n\ndef check_port(port):\n '''Checks if a port is valid.\n\n A port is restricted to be a 16 bit integer which is in the range 0 < port < 65535.\n Typically most applications will use ports > ~5000\n\n Args:\n port (int): The port number. ValueError raised if it is not an int.\n\n Returns:\n int: returns the port number if valid, otherwise an error is raised\n\n '''\n if isinstance(port, int) is not True: # Ensure we're dealing with real ports\n raise TypeError(\"port must be an integer\")\n elif port < 0 or port > 65535:\n raise ValueError(\"port must be between 0 and 65535\")\n else:\n return port\n\n\ndef check_tag(input_tag):\n '''Checks if a tag is valid. Automatically tries to convert tag from string\n\n Converts the argument to a bytes object and returns the first 4 bytes of the object.\n\n Args:\n input_tag (int/bytes/str): The input tag to check/convert\n Returns:\n bytes: A 4 byte identifier.\n\n '''\n if isinstance(input_tag, str):\n input_tag = input_tag.encode('utf-8')\n elif isinstance(input_tag, int):\n input_tag = bytes(input_tag)\n\n if len(input_tag) < 4:\n raise ValueError(\"Tag must be at least 4 bytes long\")\n \n return input_tag[0:4]\n\n\ndef get_payload(payload):\n '''Take data payload and return a byte array of the object. Should be\n structured as a dict/list object. Note this method is slightly expensive\n because it encodes a dictionary as a JSON string in order to get the bytes\n\n We also set the separators to exclude spaces in the interest of saving\n data due to spaces being unnecessary. This is a primitive way to convert\n data into bytes and you can load it.\n\n Args:\n payload(obj): A JSON serializable object representing the payload data\n\n Returns:\n bytes: The object as a utf-8 encoded string\n '''\n data = json.dumps(payload, separators=[':', ',']).encode('utf-8')\n return data\n\n\ndef decode_payload(payload):\n '''Takes a byte array and converts it into an object using ``json.loads``\n\n Args:\n payload (bytearray): An array of bytes to decode and convert into an object.\n\n Returns:\n dict/list: A dictionary or list object depending on the JSON that was encoded\n '''\n\n data = json.loads(payload.decode('utf-8'), separator=([':', ',']))\n return data\n\n\ndef build_meta_packet(seq_num, seq_total, tag):\n '''Create a bytearray which returns a sequence of bytes based on the metadata\n\n Args:\n seq_num(int): The packet's sequence number\n seq_total(int): The total number of sequence packets to be sent\n tag (bytes): A string or bytes object to encode as the data tag\n\n Returns:\n bytearray: A bytearray with the metadata\n '''\n if isinstance(seq_total, int) is False or isinstance(seq_num, int) is False:\n raise TypeError(\"Sequence number and total must be integer\")\n packet = bytearray()\n packet += struct.pack('H', seq_total)\n packet += struct.pack('H', seq_num)\n packet += check_tag(tag)\n return packet\n\ndef recv_n_bytes(conn, num):\n '''Get a set number of bytes from a TCP connection\n\n Args:\n conn (socket): A connected TCP socket\n num (int): Number of bytes to read\n\n Returns:\n bytes: a bytes object containing the data read. None if num < 0\n '''\n if num < 0:\n raise ValueError(\"conn {} request {} bytes. Bytes must be > 0\".format(conn, num))\n bytes_left = num\n msg_b = b''\n while len(msg_b) < num:\n try:\n bts = conn.recv(bytes_left)\n if len(bts) <= 0: # error/socket close\n return None\n # break # Empty str means closed socket\n msg_b += bts\n bytes_left -= len(bts)\n except socket.timeout as err:\n # Socket timed out waiting for bytes\n pass\n except OSError as err:\n # Socket timed out - log an error eventually\n logger.info('recv_n_bytes: %s', str(err))\n return None\n return msg_b\n\nclass BaseCommunicator(object):\n '''Communicators send and receive data with a specific \"tag\" and store it until a user\n retrieves it.\n\n Lifetime: listen -> send -> get -> close\n\n Possible to simply just send -> get, however you won't be able to receive connection\n attempts from other hosts\n\n '''\n\n def __init__(self, port):\n self.connections = {}\n self.data_store = {}\n self.listen_thread = None\n self.listen_sock = None\n self.port = check_port(port)\n\n self.is_listening = False\n self.recv_callback = None\n\n self.conn_lock = threading.Lock()\n self.data_lock = threading.Lock()\n\n def send(self, addr, data, tag):\n '''Sends a message of bytes to addr with a tag identifier'''\n raise NotImplementedError(\"Can't use base communicator object. Use UDP or TCP\")\n\n def listen(self):\n '''Listen for incoming messages or connection requests'''\n raise NotImplementedError(\"Can't use BaseCommunicator. Use UDP or TCP.\")\n\n def receive(self):\n '''Take a piece of data which was received and process it into a message'''\n raise NotImplementedError()\n\n def close(self):\n '''Close all the communicator sockets'''\n raise NotImplementedError(\"Can't use BaseCommunicator. Use UDP or TCP.\")\n\n def get(self, ip_addr, tag):\n '''Get a key/tag value from the data store.\n\n The data is only going to be located in the data store if every single packet for the given\n tag was received and able to be reassembled. Otherwise the incomplete data will reside\n in ``self.tmp_data``.\n\n The ``self.data_store`` object has the following structure:\n\n .. code-block:: javascript\n\n {\n ip_address: {\n tag_1: data,\n tag_2: data2\n }\n }\n\n\n Args:\n ip (str): The ip address of the host we wish get data from\n tag (bytes/bytearray): The data tag for the message which is being received\n\n Returns:\n bytes: ``None`` if complete data is not found, Otherwise if found will return the data\n\n '''\n data = None\n tg_int = int.from_bytes(check_tag(tag), byteorder='little')\n if ip_addr not in self.data_store:\n data = None\n elif tg_int not in self.data_store[ip_addr]:\n data = None\n else:\n self.data_lock.acquire()\n data = self.data_store[ip_addr][tg_int]\n self.data_store[ip_addr][tg_int] = None\n self.data_lock.release()\n return data\n\n def register_recv_callback(self, callback):\n '''Allows one to register a callback function which is executed whenever a\n full message is received and decoded.\n\n The callback must have the signature of ``(str, bytes, bytes)`` where ``str`` is the sender\n address. The first ``bytes`` is the tag. The second ``bytes`` is the data.\n\n Args:\n callback (func): A function with arguments of (sender, tag, data)\n\n Returns:\n N/A\n '''\n if isinstance(callback, collections.Callable) is not True:\n raise TypeError(\"Callback must be a function\")\n fullspec = inspect.getfullargspec(callback)\n n_args = len(fullspec[0])\n if n_args != 3:\n raise ValueError(\"Callback function did not have 3 arguments.\")\n self.recv_callback = callback\n\n\nclass TCPCommunicator(BaseCommunicator):\n '''Communicators send and receive data with a specific \"tag\" and store it until a user\n retrieves it.\n\n Lifetime: listen -> send -> get -> close\n\n Possible to simply just send -> get, however you won't be able to receive connection\n attempts from other hosts\n\n '''\n\n def __init__(self, port):\n super().__init__(port)\n\n def connect(self, ip_addr, timeout=None):\n '''Connect to a TCP socket at ``ip_addr:self.port``.\n\n The connection of addr will be put into the internal connections dictionary. When the next\n send call is initiated a new thread will start reading messages from the connection\n\n The call will block until timeout seconds have passed. A socket.TimeoutError will be\n raised if the connection is not successful. Otherwise if timeout is None the call\n will block indefinitely until a connection has been made.\n\n Args:\n ip_addr (str): The IP to connect to on self.port\n timeout (float): Number of seconds to wait before timing out the connection. None indicates no timeout\n\n Returns: N/A\n '''\n conn = None\n # Work until we hit the timeout\n self.conn_lock.acquire()\n if ip_addr in self.connections:\n self.conn_lock.release()\n logger.warning('Attempting to make a connection to %s which already exists.', ip_addr)\n return\n self.conn_lock.release()\n\n msg = None\n if timeout is None:\n while conn is None:\n try:\n conn = socket.create_connection((ip_addr, self.port))\n except socket.timeout as err:\n pass\n except OSError as err:\n msg = \"Got {} while trying to connect() to {}\".format(err, ip_addr)\n else:\n time_start = time.time()\n while time.time() - time_start < timeout and conn is None:\n try:\n conn = socket.create_connection((ip_addr, self.port), timeout=timeout)\n except BaseException as err:\n msg = str(err)\n\n if msg is not None:\n logger.info(\"Exception trying to connect to %s with err %s\", ip_addr, msg)\n\n self.conn_lock.acquire()\n if conn is not None and ip_addr not in self.connections: # Brand new\n self.connections[ip_addr] = conn\n conn_thread = threading.Thread(target=self._run_connect, args=(conn, ip_addr))\n conn_thread.start()\n elif conn is not None and ip_addr in self.connections: # Already existing\n logger.warning(\"Connect to ip %s requested but connection already existed\", ip_addr)\n conn.close()\n else:\n self.conn_lock.release() # Release here because we raise an exception\n raise ConnectionError('Unable to connect to {}'.format(ip_addr))\n self.conn_lock.release()\n\n def send(self, addr, data, tag):\n '''Sends data to specified hosts\n\n Args:\n addrs (str): IPv4 Address to send to\n data (bytes): Data to send\n tag (bytes): Message identifier. Will take up to first 4 bytes\n\n '''\n tag = check_tag(tag)\n if not isinstance(data, bytes):\n raise TypeError(\"data must be bytes\")\n # Create the packet with tag at the top\n msg = bytearray()\n msg += tag\n msg += data\n mlen = len(msg) # msg length\n msg = struct.pack('!I', mlen) + msg # prepend message length to data\n self._attempt_send_data(addr, msg, timeout=15)\n\n def listen(self):\n '''Start listening on port ``self.port``. Creates a new thread where the socket will\n listen for incoming data\n '''\n if self.is_listening is True:\n raise RuntimeError('Cannot listen. Socket already listening.')\n\n if self.listen_thread is None: # Create thread if not already created\n self.listen_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n self.listen_thread = threading.Thread(target=self._run_tcp,\n args=(self.listen_sock, '0.0.0.0',\n self.port))\n\n self.is_listening = True\n self.listen_thread.start()\n\n def close(self):\n logger.debug('Close requested on communicator %s', self)\n if self.listen_thread != None:\n self.is_listening = False\n self.listen_thread.join()\n self.listen_thread = None\n try:\n self.listen_sock.close()\n except BaseException as err:\n logger.debug('exception closing listening socket: %s', err)\n\n with self.conn_lock:\n for addr in self.connections:\n try:\n self.connections[addr].close()\n except BaseException as err:\n logger.debug('Closing %s, Error: %s', addr, err)\n self.connections = {}\n\n def _run_tcp(self, _sock, host, port, unacc_conn=10):\n '''Method which accepts TCP connections and passes them off to run_connect\n\n Args:\n _sock (sockets.socket): A socket object to bind to\n host (str): The hostname/IP that we should bind the socket to. Use empty string '' for\n senders who wish to contact you outside the network.\n port (int): The port as an integer\n '''\n _sock.settimeout(1.5)\n _sock.bind((host, port))\n # Accept maximum of three un-accepted conns before refusing\n _sock.listen(unacc_conn)\n while self.is_listening:\n try:\n conn, addr = _sock.accept()\n #logger.info('Accepted new socket connection to %s', str(addr[0]))\n self.conn_lock.acquire()\n if addr[0] not in self.connections:\n self.connections[addr[0]] = conn\n thd = threading.Thread(target=self._run_connect,\n args=(conn, addr[0]))\n thd.start()\n else:\n logger.debug('Got new connection which was already present from %s', addr)\n conn.close()\n self.conn_lock.release()\n except socket.timeout:\n pass\n # logger.debug('__run_tcp__, connection accept timeout: %s', err)\n logger.debug('Listening thread exiting')\n\n def _run_connect(self, connection, addr):\n '''Worker methods which receives data from TCP connections.\n\n Must be able to convert TCP byte streams into individual messages. In order to accomplish\n this we used a message-length prefixing strategy. Every message sent from the other end of\n the wire is required to prefix a 4-byte message length to the very front of every message.\n This allows us to 'chunk' the messages and read only the necessary bytes. If an invalid\n message length arrives then we close the socket connection and log an error.\n\n Args:\n connection (connection): A TCP connection from socket.accept()\n addr (str): The Inet(6) address representing the address of the client\n '''\n\n while self.is_listening: # A break from this loop indicated the connection closed\n try:\n # Get message length\n len_b = recv_n_bytes(connection, 4)\n if len_b is None:\n break\n m_len = struct.unpack('!I', len_b)[0] # Get the next message length\n if m_len < 0:\n # Log an error, close connection\n logger.warning(\"msg len < 0\")\n break\n msg_data = recv_n_bytes(connection, m_len)\n if msg_data is not None:\n self.receive_tcp(msg_data, addr)\n else:\n logger.warning(\"msgdata is None\")\n break # Close connection if returned None\n\n except socket.timeout as err:\n pass\n except OSError as err:\n logger.warning('OSError on _run_tcp: %s', err)\n break\n\n self.conn_lock.acquire()\n del self.connections[addr] # Remove the connection\n logger.debug(\"Popped connection with addr %s\", addr)\n self.conn_lock.release()\n try:\n connection.close()\n except OSError as err:\n logger.debug('_run_connect, error closing TCP socket: %s', err)\n return\n\n def receive_tcp(self, data, addr):\n '''Stores the TCP data reveived into the data store\n\n Args:\n data (bytes) : The data to store.\n addr (str): The ip address of the node.\n\n '''\n if len(data) < 4:\n # Log error on data\n return\n data_tag = int.from_bytes(data[:4], byteorder='little')\n dat = data[4:]\n\n with self.data_lock:\n if addr not in self.data_store:\n self.data_store[addr] = {}\n self.data_store[addr][data_tag] = dat\n logger.debug('Stored data at [%s][%s]', addr, data_tag)\n if self.recv_callback != None:\n # run a callback on the newly collected data.\n self.recv_callback(addr, data_tag, dat)\n return\n\n def _attempt_send_data(self, addr, msg, timeout=None):\n '''Perform an attempt at sending data to the specified address\n\n First we check if we can access the connection in our current connections list.\n Then if it exists, we send it or find a new\n\n Args:\n addr (str): The IP address to send to\n msg (bytes): The message in bytes to send\n '''\n with self.conn_lock:\n if addr in self.connections:\n self.connections[addr].sendall(msg)\n return\n\n try:\n self.connect(addr, timeout=timeout)\n # addr should now be in connections if connect() was successful\n with self.conn_lock:\n conn_sock = self.connections[addr]\n conn_sock.sendall(msg)\n logger.debug('Successfully transmitted data to %s', addr)\n except OSError as err:\n # Log message about how unable to send\n exception = 'Unable to send data to {}. Error: {}'.format(addr, err)\n logger.error(exception)\n raise RuntimeError(exception)\n\n\nclass UDPCommunicator(BaseCommunicator):\n '''This is a threaded class interface designed to send and receive messages\n 'asynchronously' via python's threading interface. It was designed mainly\n designed for use in communication for the algorithm termed 'Cloud K-SVD'.\n\n This class provides the following methods for users\n\n - listen: Starts the threaded listener\n - send: sends data via the open socket\n - get: retrieve data from the data-store\n - stop: stop listening on the thread\n\n The typical sequence will be something like the following:\n\n 1. Take the object you wish to send. Encode it to bytes.\n i.e. ``my_bytes = str([1, 2, 3, 4, 5]).encode('utf-8')``\n 2. After encoding to bytes and creating a communicator,\n use ``send()`` in order to send it to the listening host.\n The methods here will take care of packet fragmenting and\n makes sure messages are reassembled correctly. You\n must also add a 'tag' to the data. It should be a 4-byte\n long identifier. For strings this is limited to 4 characters.\n Anything longer than 4 is truncated\n\n - ``comm.send('IP_ADDRESS', my_bytes, 'tag1')``\n\n\n 3. After sending, there's nothing else for the client to do'\n 4. When the packet reaches the other end, each packet is received and\n catalogged. Once all of the pieces of a message are received,\n the message is transferred as a whole to the data store where it can\n be retrieved\n 5. Use ``get()`` to retrieve the message from the sender and by tag. ``comm.get('ip', 'tag1')``\n\n As simple as that!\n\n Notes:\n\n - A limitation (dependent upon python implementation) is that there may only be a single python\n thread running at one time due to GIL (Global Interpreter Lock)\n\n - There is an intermediate step between receiving data and making it\n available to the user. The object must receive all packets in order to\n reconstruct the data into its original form in bytes. This is performed\n by the ``receive`` method.\n\n - Data segments which have not been reconstructed lie within\n ``self.tmp_data``. Reconstructed data is within ``self.data_store``\n\n Constructor Docs\n\n Args:\n protocol (str): A string. One of 'UDP' or 'TCP' (case insensistive)\n listen_port(int): A port between 0 and 65535\n send_port(int): (Optional) Defaults to value set for listen_port, otherwise\n must be set to a valid port number.\n\n '''\n\n def __init__(self, port):\n '''Constructor calls BaseCommunicator constructor and sets up tmp data store'''\n self.tmp_data = {}\n self.send_sock = None\n super().__init__(port)\n\n def close(self):\n '''Closes both listening sockets and the sending sockets\n\n The sockets may only be closed once. After closing a new object must be created.\n\n Args:\n N/A\n\n Returns:\n N/A\n\n '''\n logger.debug('Close requested on communicator %s', self)\n if self.is_listening is True:\n if self.listen_thread != None:\n self.is_listening = False\n self.listen_thread.join()\n self.listen_thread = None\n # On a close, we can still send afterwards, but we never receive anything\n try:\n self.listen_sock.close()\n except BaseException as err:\n logger.debug('exception closing listening socket: %s', err)\n\n try:\n self.send_sock.close()\n except BaseException as err:\n logger.debug('exception closing sending socket: %s', err)\n\n self.send_sock = None\n self.listen_sock = None\n\n def listen(self):\n '''Start listening on port ``self.port``. Creates a new thread where the socket will\n listen for incoming data\n\n Args:\n N/A\n\n Returns:\n N/A\n\n '''\n if self.listen_thread is None: # Create thread if not already created\n self.listen_sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\n # Set to nonblocking in order to get our threaded server to work :) (We\n # should investigate the performance impact of this)\n self.listen_sock.setblocking(False)\n self.listen_thread = threading.Thread(target=self._run_listen,\n args=(self.listen_sock, '0.0.0.0',\n self.port))\n\n self.is_listening = True\n self.listen_thread.start()\n\n def _run_listen(self, _sock, host, port):\n '''Worker method for the threaded listener in order to retrieve incoming messages\n\n Args:\n _sock (sockets.socket): A socket object to bind to\n host (str): The hostname/IP that we should bind the socket to. Use empty string '' for\n senders who wish to contact you outside the network.\n port (int): The port as an integer\n\n Returns:\n N/A\n\n '''\n try:\n _sock.bind((host, port))\n except BaseException as err:\n logger.warning(\"Could not bind to %s:%s, Got %s\", host, port, err)\n _sock.close()\n self.close()\n return\n\n while self.is_listening:\n try:\n data, addr = _sock.recvfrom(1024) # Receive at max 1024 bytes\n # logger.debug('Received data from address {}'.format(addr))\n self.receive(data, addr[0])\n except BlockingIOError:\n pass\n\n _sock.close()\n\n def create_packets(self, data, tag):\n '''Segments a chunk of data (payload) into separate packets in order to send in sequence to\n the desired address.\n\n The messages sent using this class are simple byte arrays, which include metadata, so in\n order to segment into the correct number of packets we also need to calculate the size of\n the packet overhead (metadata) as well as subtract the IP headers in order to find the\n maximal amount of payload data we can send in a single packet.\n\n We need to use the MTU in this case which we'll take as typically a minimum of 576 bytes.\n According to RFC 791 the maximum IP header size is 60 bytes (typically 20), and according\n to RFC 768, the UDP header size is 8 bytes. This leaves the bare minimum payload size to be\n 508 bytes. (576 - 60 - 8).\n\n We will structure packets as such (not including IP/UDP headers)\n\n +---------------------+--------------------+---------------+\n | Seq.Total (2 bytes) | Seq. Num (2 bytes) | Tag (4 bytes) |\n +---------------------+--------------------+---------------+\n | Data (500 Bytes) |\n +----------------------------------------------------------+\n\n A limitation is that we can only sequence a total of 2^16 packets which, given a max data\n size of 500 bytes gives us a maximum data transmission of (2^16)*500 ~= 33MB for a single\n request.\n\n Also note that the Seq Num. is zero-indexed so that the maximum sequence number (and the\n sequence total) will go up to ``len(packets) - 1``. Or in other words, 1 less than the\n number of packets.\n\n Args:\n data (bytes): The data as a string which is meant to be sent to its destination\n tag (bytes): A tag. Only the first 4 bytes are added as the tag.\n\n Returns\n list: A list containing the payload for the packets which should be sent to the\n destination.\n '''\n packets = []\n max_payload = get_mtu() - 68 # conservative estimate to prevent IP fragmenting on UDP\n metadata_size = 8 # 8 bytes constant\n data_size = len(data)\n max_data = max_payload - metadata_size\n\n # TWO CASES\n # - We can send everything in 1 packet\n # - We must break into multiple packets which will require sequencing\n if data_size <= max_data:\n # Assemble the packet, no sequencing\n payload = build_meta_packet(0, 0, tag)\n payload += data\n packets.append(payload)\n else:\n total_packets = math.floor(data_size / max_payload)\n for i in range(total_packets): # [0, total_packets-1]\n pkt1 = build_meta_packet(i, total_packets, tag)\n\n # Slice data into ~500 byte packs\n dat1 = data[i * max_data:(i + 1) * max_data]\n pkt1 += dat1\n packets.append(pkt1)\n # Build the final packet\n pkt1 = build_meta_packet(total_packets, total_packets, tag)\n min_bound = (total_packets) * max_data\n dat1 = data[min_bound:]\n pkt1 += dat1\n packets.append(pkt1)\n\n return packets\n\n def send(self, ip_addr, data, tag):\n '''Send a chunk of data with a specific tag to an ip address. The packet will be\n automatically chunked into N packets where N = ceil(bytes/(MTU-68))\n\n Args:\n ip (str): The hostname/ip to send to\n data (bytes): The bytes of data which will be sent to the other host.\n tag (bytes): An identifier for the message\n\n Returns:\n bool: True if all packets were created and sent successfully.\n '''\n tag = check_tag(tag)\n if not isinstance(data, bytes):\n raise TypeError(\"data must be bytes\")\n\n if self.send_sock is None:\n self.send_sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\n # As simple as just creating the packets and sending each one\n # individually\n ret = True\n packets = self.create_packets(data, tag)\n # logger.debug(\"Sending {} packet(s) to {}\".format(len(packets), ip))\n for packet in packets:\n # logger.debug('Sending packet to IP: {} on port {}'.format(ip, self.send_port))\n try:\n if self.send_sock.sendto(packet, (ip_addr, self.port)) < 0:\n logger.debug(\"Some packets were not sent successfully\")\n ret = False\n\n except OSError as err:\n ret = False\n logger.warning(str(err))\n break\n return ret\n\n def receive(self, data, addr):\n '''Take a piece of data received over the socket and processes the data and attempt to\n combine packet sequences together, passing them to the data store when ready.\n\n ``self.tmp_data`` is an object with the structure\n\n .. code-block:: javascript\n\n {\n ip_address: {\n tag_1: {\n 'seq_total': Max_num_packets,\n 'packets' = {\n 1: packet_data_1,\n 2: packet_data_2,\n ...\n ...\n }\n },\n tag_2: {\n ...\n }\n },\n ip_address_2 : {\n ...\n }\n }\n\n Args:\n data (bytes): a packet of data received over the socket to process\n addr (str): The ip address or hostname of the sending host\n\n Returns:\n N/A\n '''\n\n if addr not in self.tmp_data:\n self.tmp_data[addr] = {}\n\n # disassemble the packet\n seq_total = struct.unpack('H', data[0:2])[0]\n seq_num = struct.unpack('H', data[2:4])[0]\n data_tag = int.from_bytes(data[4:8], byteorder='little')\n dat = data[8:]\n\n # Create an entry for data_tag\n if data_tag not in self.tmp_data[addr]:\n self.tmp_data[addr][data_tag] = {}\n self.tmp_data[addr][data_tag]['packets'] = {}\n self.tmp_data[addr][data_tag]['seq_total'] = seq_total\n\n if (seq_total != self.tmp_data[addr][data_tag]['seq_total']\n or self.tmp_data[addr][data_tag]['seq_total'] is None):\n # If the tag existed, make sure the sequence total is equal to the\n # current, otherwise throw away any packets we've already collected\n self.tmp_data[addr][data_tag]['seq_total'] = seq_total\n self.tmp_data[addr][data_tag]['packets'] = {}\n\n self.tmp_data[addr][data_tag]['packets'][seq_num] = dat\n\n num_packets = len(self.tmp_data[addr][data_tag]['packets'])\n # seq_total is max index of 0-index based list.\n if num_packets == seq_total + 1:\n # Reassmble the packets in order\n reassembled = bytes()\n for i in range(num_packets):\n reassembled += self.tmp_data[addr][data_tag]['packets'][i]\n if addr not in self.data_store:\n self.data_store[addr] = {}\n logger.debug(\"Adding reassmbled packet to data store with IP %s and tag %s\",\n addr, data_tag)\n self.data_lock.acquire()\n self.data_store[addr][data_tag] = reassembled\n self.data_lock.release()\n if self.recv_callback != None:\n # run a callback on the newly collected packets.\n self.recv_callback(addr, data_tag, reassembled)\n self.tmp_data[addr][data_tag]['packets'] = {}\n self.tmp_data[addr][data_tag]['seq_total'] = {}\n","sub_path":"adac/communicator.py","file_name":"communicator.py","file_ext":"py","file_size_in_byte":32522,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"482395198","text":"import json\nimport os\nimport random\n\nimport black\nimport isort\nimport redis\nimport requests\nimport telebot\nfrom isort import SortImports\nfrom telebot import types\n\nSortImports(\"bot0.py\")\n\ntoken = os.environ['TELEGRAM_TOKEN']\n\nbot = telebot.TeleBot(token)\n\nkoeficienti = {} # будем в основном использовать на этапе с конвертацией, для коэффициентов\n\nurl = 'https://www.cbr-xml-daily.ru/daily_json.js' # записываем в переменную url API центрабанка\n\nresponse = requests.get(url).json() # преобразуем полученные из ссылки данные в словарь\n\nUSD = response['Valute']['USD']['Value'] # Из api центрабанка достали стоимость доллара в рублях\nkoeficienti[11] = USD\n\nEUR = response['Valute']['EUR']['Value'] # Из api центрабанка достали стоимость евро в рублях\nkoeficienti[0] = EUR\n\nCNY = response['Valute']['CNY']['Value'] # Из api центрабанка достали стоимость юаней в рублях\nkoeficienti[1] = CNY\n\n# Задаём коэффициенты перевода из одной валюты в другую\nizEURvUSD = int(EUR) / int(USD)\nkoeficienti[2] = izEURvUSD\nizUSDvEUR = int(USD) / int(EUR)\nkoeficienti[3] = izUSDvEUR\nizRUBvUSD = 1 / int(USD)\nkoeficienti[4] = izRUBvUSD\nizRUBvEUR = 1 / int(EUR)\nkoeficienti[5] = izRUBvEUR\nizRUBvCNY = 1 / int(CNY)\nkoeficienti[6] = izRUBvCNY\nizUSDvCNY = int(USD) / int(CNY)\nkoeficienti[7] = izUSDvCNY\nizEURvCNY = int(EUR) / int(CNY)\nkoeficienti[8] = izEURvCNY\nizCNYvUSD = int(CNY) / int(USD)\nkoeficienti[9] = izCNYvUSD\nizCNYvEUR = int(CNY) / int(EUR)\nkoeficienti[10] = izCNYvEUR\n\n# Вводим все состояния\nMAIN_STATE = 'main'\nVvedini = 'vvedeni dannie'\nSymiruem = 'idet rasschet'\nSYM1 = 'vtoroe rasschitat'\nkonvertiruem = 'idet konvertaciya'\nADMIN = 'idet administrirovanie'\nredis_url = os.environ.get('REDIS_URL')\ndict_db = {}\n\n# Создаём базу данных либо загружаем готовую\nif redis_url is None:\n try:\n data = json.load(open('db/data.json', 'r', encoding='utf-8')) # выводим нашу базу данных\n except FileNotFoundError:\n data = {\n \"states\": {},\n \"main\": {},\n \"vvedeni dannie\": {},\n \"idet rasschet\": {},\n \"vtoroe rasschitat\": {},\n \"idet konvertaciya\": {},\n \"idet administrirovanie\": {},\n \"sym\": {},\n \"konvertaciya\": {},\n \"Admins\": {\n \"mainadmins\": \"810391410\"\n }\n }\n\n\nelse:\n redis_db = redis.from_url(redis_url)\n raw_data = redis_db.get('data')\n print('Viveodim')\n\n if raw_data is None:\n data = {\n \"states\": {},\n \"main\": {},\n \"vvedeni dannie\": {},\n \"idet rasschet\": {},\n \"vtoroe rasschitat\": {},\n \"idet konvertaciya\": {},\n \"idet administrirovanie\": {},\n \"sym\": {},\n \"konvertaciya\": {},\n \"Admins\": {\n \"mainadmins\": \"810391410\"\n }\n }\n\n else:\n data = json.loads(raw_data) # выводим нашу базу данных\n print('Viveli')\n\nkonvertaciya = data['konvertaciya'] # будем использовать на этапе с конвертацией и выводом \"квт\", для других переменных\nsym = data['sym'] # объявляем словарь с суммой\n\n\n# функция изменения базы данных\ndef change_data(key, user_id, value):\n data[key][user_id] = value\n # проверяем наличие базы данных на редис\n if redis_url is None: # Обработка базы данных, если нет подключения к редис\n json.dump(data,\n open('db/data.json', 'w', encoding='utf-8'),\n indent=2,\n ensure_ascii=False,\n )\n # Загружаем базу данных из редис\n else:\n redis_db = redis.from_url(redis_url)\n redis_db.set('data', json.dumps(data))\n\n\n# диспетчер состояний\n@bot.message_handler(content_types=['text'])\n# Обработчик всех состояний\ndef dispatcher(message):\n user_id = str(message.from_user.id)\n # Если словарь с состояниями пустой, то добавляем туда пользователя и присваиваем ему состояние MAIN_STATE\n if str(data['states']) == '{}':\n change_data('states', user_id, MAIN_STATE)\n\n try:\n print(data['states'][user_id]) # Проверяем наличие пользователя в БД, если его нет в БД, то добавляем его в БД\n except KeyError:\n change_data('states', user_id, MAIN_STATE)\n\n state = data['states'][user_id] # Достаём состояния\n print('current state', user_id, state) # Печатаем текущее состояние в логи\n\n # Обрабатываем состояния\n if state == MAIN_STATE:\n main_handler(message)\n\n elif state == Vvedini:\n Trati(message)\n\n elif state == Symiruem:\n Sym(message)\n\n elif state == SYM1:\n Sym1(message)\n\n elif state == konvertiruem:\n Trati2(message)\n\n elif state == ADMIN:\n adminpanel(message)\n\n\n# основной обработчик\ndef main_handler(message):\n user_id = str(message.from_user.id) # Объявляем переменную user id\n # Обрабатываем команды\n if message.text == '/start':\n markup = types.ReplyKeyboardMarkup(row_width=2, one_time_keyboard=True, resize_keyboard=True)\n btn1 = types.KeyboardButton('/test')\n btn2 = types.KeyboardButton('/help')\n btn3 = types.KeyboardButton('Рассчитать')\n markup.row(btn1, btn2, btn3)\n bot.send_message(message.from_user.id, 'Привет, я могу помочь тебе рассчитать дневные затраты, по команде '\n '/help '\n 'вы узнаете возможности бота. '\n 'Напишите комманду /test для более понятного объяснения работы бота. '\n 'Напишите \"Рассчитать\" чтобы добавить трату', reply_markup=markup)\n\n elif message.text == '/test':\n test(message)\n\n elif message.text == '/help':\n markup = types.ReplyKeyboardMarkup(row_width=2, one_time_keyboard=True, resize_keyboard=True)\n btn2 = types.KeyboardButton('/test')\n btn3 = types.KeyboardButton('Рассчитать')\n markup.row(btn2, btn3)\n tekct = 'По команде \"рассчитать\" вы вводите трату, по комманде /test вам будет представлен пример работы бота'\n bot.send_message(message.from_user.id, tekct, reply_markup=markup)\n # Обрабатываем кнопки\n elif message.text.lower() == 'рассчитать':\n bot.send_message(message.from_user.id, 'напиши сколько ты потратил(только цифрами)')\n change_data('states', user_id, Symiruem)\n print(str(data['states'][user_id]))\n\n elif message.text.lower() == 'траты' or message.text.lower() == 'квт' or message.text.lower() == 'конвертировать':\n bot.send_message(message.from_user.id, 'Вы ещё не ввели трату. Напишите \"рассчитать\" чтобы ввести трату')\n\n elif message.text.lower() == 'админ панель':\n adminpanel(message)\n doadmenki = data['states'][user_id]\n koeficienti[12] = doadmenki\n change_data('states', user_id, ADMIN)\n # Обрабатывем всё остальное\n else:\n bot.send_message(message.from_user.id, 'Я вас не понял')\n\n\n# Панель администратора\ndef adminpanel(message):\n user_id = str(message.from_user.id)\n admins = data[\"Admins\"][\"mainadmins\"]\n\n if user_id in admins:\n if message.text.lower() == 'очистить бд':\n bot.send_message(message.from_user.id, 'Идёт очистка базы данных')\n ochistka(message)\n\n elif message.text.lower() == 'вывод бд':\n tekct0 = 'STATES: ' + str(data['states']) + 'SYMMI: ' + str(data['sym']) + 'Informaciya pro konvertaciyu'\n tekct1 = str(data['konvertaciya'])\n tekct = tekct0 + ' ' + tekct1\n bot.send_message(user_id, tekct)\n\n elif message.text.lower() == 'выход':\n doadmenki = koeficienti[12]\n change_data('states', user_id, doadmenki)\n bot.send_message(user_id, 'Выход выполнен')\n\n elif message.text.lower() == 'админ панель':\n bot.send_message(user_id, 'Режим администрирования')\n\n else:\n bot.send_message(user_id, 'Команда не верна')\n\n\n# Функция очистки базы данных\ndef ochistka(message):\n user_id = str(message.from_user.id)\n data['states'] = {}\n data['sym'] = {}\n data['konvertaciya'] = {}\n print(data)\n change_data('states', user_id, ADMIN)\n print(data['states'])\n\n\n# Пример работы бота\ndef test(message):\n markup = types.ReplyKeyboardMarkup(row_width=2, one_time_keyboard=True, resize_keyboard=True)\n btn2 = types.KeyboardButton('/help')\n btn3 = types.KeyboardButton('Рассчитать')\n markup.row(btn2, btn3)\n\n tekct = ' Вы: Пишите комманду \"рассчитать\",\\nЗатем пишите цифрами сколько вы потратили,\\nПосле выбираете валюту,\\n'\n tekct1 = 'Потом вы можете Получить ваши траты написав комманду \"Траты\"\\nвам выведится значение в виде:'\n bot.send_message(message.from_user.id, tekct + tekct1)\n\n primersymmi = random.randrange(1000, 30000)\n primervaluti = random.choice(['Долларов', 'Рублей', 'Евро', 'Юаней'])\n soobchenie = 'Ваши траты составили: ' + str(primersymmi) + ' ' + str(primervaluti)\n bot.send_message(message.from_user.id, soobchenie, reply_markup=markup)\n\n\n# записывальщик трат\ndef Sym(message):\n user_id = str(message.from_user.id)\n state = data['states'][user_id]\n aftercikl = Vvedini # Переменная, которая позволяет в случае ошибки перезапустить цикл, стандарт: она равна Vvedini\n\n if state == Symiruem: # Проверка, что мы правельно попали в функцию\n symma = 0\n cifra = message.text\n\n try: # Если всё введено правельно, то прибавляем введёное число к сумме\n symma += int(str(cifra))\n except: # Если введено что-то помимо числа, то отправляем сообщение о неправельных данных\n bot.send_message(user_id, 'Введите только цифры')\n aftercikl = Symiruem\n\n if aftercikl == Vvedini: # Проверка, что не допущены ошибки\n sym[user_id] = symma\n sym[\"1\"] = cifra\n keyboard2 = types.InlineKeyboardMarkup()\n key_eur = types.InlineKeyboardButton(text='в евро', callback_data='eunow')\n keyboard2.add(key_eur) # добавляем кнопку в клавиатуру\n key_usd = types.InlineKeyboardButton(text='В долларах', callback_data='usnow')\n keyboard2.add(key_usd)\n key_rub = types.InlineKeyboardButton(text='В рублях', callback_data='rubnow')\n keyboard2.add(key_rub)\n key_cny = types.InlineKeyboardButton(text='В юанях', callback_data='cnynow')\n keyboard2.add(key_cny)\n question2 = 'В какой валюте вы тратили деньги?'\n bot.send_message(message.from_user.id, text=question2, reply_markup=keyboard2)\n\n else: # Если ошибки допущены, перезапускаем цикл\n change_data('states', user_id, aftercikl)\n\n\n# записывальщик трат, когда уже была введена трата\ndef Sym1(message):\n user_id = str(message.from_user.id)\n state = data['states'][user_id]\n\n try: # Проверяем, что у нас имеется состояние, которое было до начала выполнения функции\n dosymmi = data['dosymmi']\n except:\n # Если состояние исчезло(к примеру ошибка сервера или утрата БД), то считаем состояние за Vvedini\n dosymmi = Vvedini\n aftercikl = Vvedini\n\n if state == SYM1:\n symma = int(sym[user_id])\n cifra = message.text\n\n try:\n symma += int(str(cifra)) # Если всё верно, то сумируем\n except:\n bot.send_message(user_id, 'Введите только цифры') # Если допущена какая-либо ошибка, то перезапускаем\n aftercikl = SYM1\n\n if aftercikl == Vvedini: # Если всё введено нормально, то продолжаем\n\n sym[user_id] = symma\n sym[\"1\"] = cifra\n\n markup1 = types.ReplyKeyboardMarkup(row_width=2, one_time_keyboard=True, resize_keyboard=True)\n btn1 = types.KeyboardButton('Траты')\n btn2 = types.KeyboardButton('конвертировать')\n btn3 = types.KeyboardButton('Рассчитать')\n markup1.row(btn1, btn2, btn3)\n\n bot.send_message(message.from_user.id, 'Хорошо, я записал вашу трату, узнать её вы можете написав команду '\n '\"траты\"', reply_markup=markup1)\n\n if dosymmi == konvertiruem and aftercikl == Vvedini:\n change_data('states', user_id, dosymmi)\n\n else: # Если допущена ошибка при вводе суммы, то перезапускаем цикл\n change_data('states', user_id, aftercikl)\n\n\n# функция присваивания валюты\ndef oprvaliuti(call, valuta):\n user_id = str(call.from_user.id)\n konvertaciya[user_id + 'valiutatrat'] = valuta\n\n\n# обработчик клавиатуры\n@bot.callback_query_handler(func=lambda call: True)\ndef valuta(call):\n\n user_id = str(call.from_user.id) # Задаём user_id и state\n state = data['states'][user_id]\n\n if state == Symiruem: # Проверка, верно ли состояние\n\n # объявляем валюту\n if call.data == 'eunow':\n valiuta = 'Евро'\n oprvaliuti(call, valiuta)\n\n if call.data == 'usnow':\n valiuta = 'Долларах'\n oprvaliuti(call, valiuta)\n\n if call.data == 'rubnow':\n valiuta = 'Рублях'\n oprvaliuti(call, valiuta)\n\n if call.data == 'cnynow':\n valiuta = 'Юанях'\n oprvaliuti(call, valiuta)\n\n # Настраиваем клавиатуру\n markup1 = types.ReplyKeyboardMarkup(row_width=2, one_time_keyboard=True, resize_keyboard=True)\n btn1 = types.KeyboardButton('Траты')\n btn2 = types.KeyboardButton('конвертировать')\n btn3 = types.KeyboardButton('Рассчитать')\n markup1.row(btn1, btn2, btn3)\n\n bot.send_message(call.message.chat.id, 'Я записал вашу валюту, узнать ваши траты и '\n 'валюту трат вы можете по комманде \"траты\" '\n 'Также вы можете конвертировать ваши траты в другую валюту написав '\n 'комманду '\n '\"конвертировать\"', reply_markup=markup1)\n\n change_data('states', user_id, Vvedini)\n\n valiutahandler(call) # вызываем функцию обработки переменной now\n\n else:\n valiutahandler(call) # вызываем функцию обработки переменной now\n\n perevod(call) # вызываем другой скрипт обработчика\n\n\ndef valiutahandler(call):\n\n user_id = str(call.from_user.id) # Объявляем переменные user_id и valiuta\n valiuta = konvertaciya[user_id + 'valiutatrat']\n\n # Объявляем переменную now\n if 'Руб' in valiuta:\n now = 'rub'\n konvertaciya[1] = now\n\n if 'Дол' in valiuta:\n now = 'us'\n konvertaciya[1] = now\n\n if 'Евр' in valiuta:\n now = 'eu'\n konvertaciya[1] = now\n\n if 'Юан' in valiuta:\n now = 'cny'\n konvertaciya[1] = now\n\n\n# обработчик при введённых тратах\ndef Trati(message):\n\n user_id = str(message.from_user.id) # Объявляем переменные user_id и valiuta\n valiuta = konvertaciya[user_id + 'valiutatrat']\n\n if message.text.lower() == 'траты':\n # Вводим стандартные кнопки и стандартную клавиатуру\n markup = types.ReplyKeyboardMarkup(row_width=2, one_time_keyboard=True, resize_keyboard=True)\n btn1 = types.KeyboardButton('Рассчитать')\n btn2 = types.KeyboardButton('конвертировать')\n\n # Если состояние 'konvertiruem', то добавляем дополнительную кнопку с текстом 'квт'\n if str(data['states'][user_id]) == konvertiruem:\n btn3 = types.KeyboardButton('квт')\n markup.row(btn1, btn2, btn3)\n # Если другое состояние, то добавляем кнопки к клавиатуре\n else:\n markup.row(btn1, btn2)\n\n # Объявляем переменную symma и объявляем переменную vivod\n symma = data['sym'][user_id]\n vivod = 'Ваши траты составили: ' + str(symma) + ' ' + 'Вы тратили деньги в ' + valiuta\n bot.send_message(message.from_user.id, vivod, reply_markup=markup)\n\n elif message.text.lower() == 'рассчитать':\n\n # Делаем все манипуляции, для возврата к тому же состоянию\n dosymmi = data['states'][user_id]\n data['dosymmi'] = dosymmi\n json.dump(data,\n open('db/data.json', 'w', encoding='utf-8'),\n indent=2,\n ensure_ascii=False,\n )\n\n bot.send_message(message.from_user.id, 'напиши сколько ты потратил(только цифрами)')\n change_data('states', user_id, SYM1)\n\n elif message.text.lower() == 'конвертировать':\n konvert(message)\n\n elif message.text.lower() == 'квт':\n bot.send_message(message.from_user.id, 'Вы ещё не сконвертировали траты')\n\n else:\n main_handler(message)\n\n\n# обработчик при введённых данных и проделанной конвертации\ndef Trati2(message):\n user_id = str(message.from_user.id)\n\n if message.text.lower() == 'квт':\n konvertirovano = konvertaciya[user_id + 'symma']\n vochtoperevesti = konvertaciya[user_id]\n\n markup = types.ReplyKeyboardMarkup(row_width=2, one_time_keyboard=True, resize_keyboard=True)\n btn1 = types.KeyboardButton('Рассчитать')\n btn2 = types.KeyboardButton('конвертировать')\n btn3 = types.KeyboardButton('Траты')\n markup.row(btn1, btn2, btn3)\n\n tekct = 'Ваши траты: ' + str(konvertirovano) + ' ' + str(vochtoperevesti)\n bot.send_message(message.from_user.id, tekct, reply_markup=markup)\n\n else:\n Trati(message)\n\n\n# Клавиатура выбора валюты в которую конвертировать\ndef konvert(message):\n\n # создаём клавиатуру, для определения, в какую валюту переводить\n keyboard = types.InlineKeyboardMarkup()\n key_euro = types.InlineKeyboardButton(text=' перевести в Евро', callback_data='eu')\n keyboard.add(key_euro) # добавляем кнопку в клавиатуру\n key_usd = types.InlineKeyboardButton(text='перевести в Доллары', callback_data='us')\n keyboard.add(key_usd)\n key_rub = types.InlineKeyboardButton(text='перевести в Рубли', callback_data='rub')\n keyboard.add(key_rub)\n key_cny = types.InlineKeyboardButton(text='Перевести в Юани', callback_data='cny')\n keyboard.add(key_cny)\n\n question = 'В какую валюту вы хотите конвертировать?'\n bot.send_message(message.from_user.id, text=question, reply_markup=keyboard)\n\n\n# Конвертатор валют\n@bot.callback_query_handler(func=lambda call: True)\ndef perevod(call):\n user_id = str(call.from_user.id)\n change_data('states', user_id, konvertiruem)\n now = konvertaciya[1]\n\n # об��аботчик клавиатуры в которой задаётся, переменная в которую мы переводим\n symma = sym[user_id]\n CNY = koeficienti[1]\n USD = koeficienti[11]\n EUR = koeficienti[0]\n izEURvUSD = koeficienti[2]\n izUSDvEUR = koeficienti[3]\n izRUBvUSD = koeficienti[4]\n izRUBvEUR = koeficienti[5]\n izRUBvCNY = koeficienti[6]\n izUSDvCNY = koeficienti[7]\n izEURvCNY = koeficienti[8]\n izCNYvUSD = koeficienti[9]\n izCNYvEUR = koeficienti[10]\n vochtoperevesti = call.data\n\n # всё ниже это конвертаторы из одной валюты в другую. Всё точно работает:)\n if vochtoperevesti == \"eu\" and now == 'eu':\n bot.send_message(call.message.chat.id, 'Ваша валюта уже евро')\n\n if vochtoperevesti == \"rub\" and now == 'rub':\n bot.send_message(call.message.chat.id, 'Ваша валюта уже рубли')\n\n if vochtoperevesti == \"us\" and now == 'us':\n bot.send_message(call.message.chat.id, 'Ваша валюта уже доллары')\n\n if vochtoperevesti == 'cny' and now == 'cny':\n bot.send_message(call.message.chat.id, 'Ваша валюта уже юани')\n\n if vochtoperevesti == 'rub' and now == 'cny':\n konvertirovano = int(symma) * CNY\n konvertaciya[user_id + 'symma'] = konvertirovano\n okryglenie(call)\n KonvertV_RUB(call)\n messkonvert(call)\n\n if vochtoperevesti == 'cny' and now == 'rub':\n konvertirovano = int(symma) * izRUBvCNY\n konvertaciya[user_id + 'symma'] = konvertirovano\n okryglenie(call)\n KonvertV_CNY(call)\n messkonvert(call)\n\n if vochtoperevesti == 'us' and now == 'cny':\n konvertirovano = int(symma) * izCNYvUSD\n konvertaciya[user_id + 'symma'] = konvertirovano\n okryglenie(call)\n KonvertV_USD(call)\n messkonvert(call)\n\n if vochtoperevesti == 'cny' and now == 'eu':\n konvertirovano = int(symma) * izEURvCNY\n konvertaciya[user_id + 'symma'] = konvertirovano\n okryglenie(call)\n KonvertV_CNY(call)\n messkonvert(call)\n\n if vochtoperevesti == 'cny' and now == 'us':\n konvertirovano = int(symma) * izUSDvCNY\n konvertaciya[user_id + 'symma'] = konvertirovano\n okryglenie(call)\n KonvertV_CNY(call)\n messkonvert(call)\n\n if vochtoperevesti == 'eu' and now == 'cny':\n konvertirovano = int(symma) * izCNYvEUR\n konvertaciya[user_id + 'symma'] = konvertirovano\n okryglenie(call)\n KonvertV_EUR(call)\n messkonvert(call)\n\n if vochtoperevesti == 'us' and now == 'rub':\n konvertirovano = int(symma) * izRUBvUSD\n konvertaciya[user_id + 'symma'] = konvertirovano\n okryglenie(call)\n KonvertV_USD(call)\n messkonvert(call)\n\n if vochtoperevesti == 'rub' and now == 'us':\n konvertirovano = int(symma) * USD\n konvertaciya[user_id + 'symma'] = konvertirovano\n okryglenie(call)\n KonvertV_RUB(call)\n messkonvert(call)\n\n if vochtoperevesti == 'eu' and now == 'rub':\n konvertirovano = int(symma) * izRUBvEUR\n konvertaciya[user_id + 'symma'] = konvertirovano\n okryglenie(call)\n KonvertV_EUR(call)\n messkonvert(call)\n\n if vochtoperevesti == 'rub' and now == 'eu':\n konvertirovano = int(symma) * EUR\n konvertaciya[user_id + 'symma'] = konvertirovano\n okryglenie(call)\n KonvertV_RUB(call)\n messkonvert(call)\n\n if vochtoperevesti == 'eu' and now == 'us':\n konvertirovano = int(symma) * izUSDvEUR\n konvertaciya[user_id + 'symma'] = konvertirovano\n okryglenie(call)\n KonvertV_EUR(call)\n messkonvert(call)\n\n if vochtoperevesti == 'us' and now == 'eu':\n konvertirovano = int(symma) * izEURvUSD\n konvertaciya[user_id + 'symma'] = konvertirovano\n okryglenie(call)\n KonvertV_USD(call)\n messkonvert(call)\n\n json.dump(data,\n open('db/data.json', 'w', encoding='utf-8'),\n indent=2,\n ensure_ascii=False,\n )\n\n\ndef KonvertV_USD(call): # функция отправки сообщения при переводе в доллары\n user_id = str(call.message.chat.id)\n bot.send_message(call.message.chat.id, 'Ваши траты в долларах = ' + str(konvertaciya[user_id + 'symma']))\n vochtoperevesti = 'В долларах'\n konvertaciya[user_id] = vochtoperevesti\n\n\ndef KonvertV_CNY(call): # функция отправки сообщения при переводе в юани\n user_id = str(call.message.chat.id)\n bot.send_message(call.message.chat.id, 'Ваши траты в юанях = ' + str(konvertaciya[user_id + 'symma']))\n vochtoperevesti = 'В юанях'\n konvertaciya[user_id] = vochtoperevesti\n\n\ndef KonvertV_RUB(call): # функция отправки с��общения при переводе в рубли\n user_id = str(call.message.chat.id)\n bot.send_message(call.message.chat.id, 'Ваши траты в рублях = ' + str(konvertaciya[user_id + 'symma']))\n vochtoperevesti = 'В рублях'\n konvertaciya[user_id] = vochtoperevesti\n\n\ndef KonvertV_EUR(call): # функция отправки сообщения при переводе в евро\n user_id = str(call.message.chat.id)\n bot.send_message(call.message.chat.id, 'Ваши траты в евро = ' + str(konvertaciya[user_id + 'symma']))\n vochtoperevesti = 'В евро'\n konvertaciya[user_id] = vochtoperevesti\n\n\ndef okryglenie(call): # Функция округления\n user_id = str(call.from_user.id)\n konvertirovano = konvertaciya[user_id + 'symma']\n konvertirovano = round(konvertirovano, 2)\n konvertaciya[user_id + 'symma'] = konvertirovano\n\n\ndef messkonvert(call): # функция отправки сообщения, о возможности узнать конвертированную трату :)\n user_id = call.message.chat.id\n\n markup1 = types.ReplyKeyboardMarkup(row_width=2, resize_keyboard=True)\n btn1 = types.KeyboardButton('Траты')\n btn2 = types.KeyboardButton('квт')\n btn3 = types.KeyboardButton('Рассчитать')\n btn4 = types.KeyboardButton('конвертировать')\n markup1.row(btn1, btn2, btn3, btn4)\n\n bot.send_message(user_id, 'В любой момент вы можете узнать конвертированную трату написав комманду'\n '\"квт\"', reply_markup=markup1)\n\n\nif __name__ == '__main__':\n bot.polling()\n","sub_path":"bot0.py","file_name":"bot0.py","file_ext":"py","file_size_in_byte":28936,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"457032934","text":"# -*- coding: utf-8 -*-\nimport pygmsh\n\nfrom helpers import compute_volume\n\n\ndef test():\n geom = pygmsh.built_in.Geometry()\n\n lcar = 0.1\n p1 = geom.add_point([0.0, 0.0, 0.0], lcar)\n p2 = geom.add_point([1.0, 0.0, 0.0], lcar)\n p3 = geom.add_point([1.0, 0.5, 0.0], lcar)\n p4 = geom.add_point([1.0, 1.0, 0.0], lcar)\n s1 = geom.add_spline([p1, p2, p3, p4])\n\n p2 = geom.add_point([0.0, 1.0, 0.0], lcar)\n p3 = geom.add_point([0.5, 1.0, 0.0], lcar)\n s2 = geom.add_spline([p4, p3, p2, p1])\n\n ll = geom.add_line_loop([s1, s2])\n geom.add_plane_surface(ll)\n\n ref = 1.0809439490373247\n points, cells, _, _, _ = pygmsh.generate_mesh(geom)\n assert abs(compute_volume(points, cells) - ref) < 1.0e-2 * ref\n return points, cells\n\n\nif __name__ == \"__main__\":\n import meshio\n\n out = test()\n meshio.write_points_cells(\"splines.vtu\", *out)\n","sub_path":"test/test_splines.py","file_name":"test_splines.py","file_ext":"py","file_size_in_byte":875,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"459212432","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n'''\n你的比萨和我的比萨:在你为完成练习 4-1 而编写的程序中,创建比萨列表的副本,并将其存储到变量 friend_pizzas 中,再完成如下任务。\n- 在原来的比萨列表中添加一种比萨。\n- 在列表 friend_pizzas 中添加另一种比萨。核实你有两个不同的列表。为此,打印消息“My favorite pizzas are:”,\n 再使用一个 for 循环来打印第一个列表;打印消息“My friend’s favorite pizzas are:”,\n 再使用一个 for 循环来打印第二个列表。核实新增的比萨被添加到了正确的列表中。\n'''\n\npizzas = ['Romana', 'Napoletana', 'Siciliana']\n\nfriend_pizzas = pizzas[:]\n\npizzas.append('Turkey')\nfriend_pizzas.append('potato')\n\nfor pizza in pizzas:\n print('My friend’s favorite pizzas are:'+pizza)\n\nfor pizza in friend_pizzas:\n print(pizza)","sub_path":"Chapter 4/4-11.py","file_name":"4-11.py","file_ext":"py","file_size_in_byte":905,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"226021895","text":"import numpy as np\nimport gym\nimport tensorflow as tf\nimport datetime\nfrom ant_maze_env import *\nimport pickle\nimport autograd.numpy as anp\nfrom pymoo.model.problem import Problem\nfrom pymoo.algorithms.nsga2 import NSGA2\nfrom pymoo.factory import get_sampling, get_crossover, get_mutation, get_termination\nfrom pymoo.optimize import minimize\n\n# multi-objective evolution algorithm\n\nTASK_NAME = 'Maze'\nVERSION = '1'\nPOPULATION = 50\nEPISODE_NUMBER = 1000\n\nif TASK_NAME is 'Maze':\n TARGET_GOAL = np.array([0, 16])\nelif TASK_NAME is 'Push':\n TARGET_GOAL = np.array([0, 19])\nelif TASK_NAME is 'Fall':\n TARGET_GOAL = np.array([0, 27])\n\n\n# run the GA with novelty search\n# 2020-2-8\nclass HP:\n def __init__(self, env, seed=1, input_dim=None, output_dim=None, hidden_size=64):\n self.env = env\n self.input_dim = self.env.observation_space.shape[0] if input_dim is None else input_dim\n self.output_dim = self.env.action_space.shape[0] if output_dim is None else output_dim\n self.seed = seed\n self.hidden_size = hidden_size\n np.random.seed(seed)\n tf.set_random_seed(seed)\n self.env.seed(seed)\n self.archive = [] # store the final position of the states\n self.count = 0 # calculate the number of episodes\n self.current_bc_list = []\n self.bc_list = []\n\n def cal_novelty(self, position):\n #\n all_data = np.reshape(self.archive, [-1, 2])\n p = np.reshape(position, [-1, 2])\n dist = np.sqrt(np.sum(np.square(p - all_data), axis=1))\n return np.mean(np.sort(dist)[:15])\n\n def get_update_signal(self):\n if self.count % 50 is 0:\n return True\n else:\n return False\n\n\nclass Policy:\n def __init__(self, hp, params=None):\n # 根据parameter初始化\n self.hp = hp\n self.input_dim, self.output_dim, self.hidden_size = hp.input_dim, hp.output_dim, hp.hidden_size\n self.param_count = hp.input_dim * hp.hidden_size + self.hidden_size + self.hidden_size * self.hidden_size + \\\n self.hidden_size + self.hidden_size * self.output_dim + self.output_dim\n if params is not None:\n print(self.param_count)\n assert len(params) == self.param_count\n self.params = params\n\n def set_params(self, params):\n self.params = params\n\n def get_params_count(self):\n return self.param_count\n\n def evaluate_tf(self, state):\n # 得出action值,三层神经网络?用parameter来说\n sess = tf.Session()\n input_state = np.reshape(state, [1, self.input_dim])\n feed_state = tf.placeholder(dtype=tf.float64, shape=[1, self.input_dim])\n param_list = self.get_detail_params()\n l1 = tf.nn.relu(tf.matmul(feed_state, param_list[0]) + param_list[1])\n l2 = tf.nn.relu(tf.matmul(l1, param_list[2])) + param_list[3]\n output_action = tf.nn.tanh(tf.matmul(l2, param_list[4]) + param_list[5]) * 30\n return sess.run(output_action, feed_dict={feed_state: input_state})\n\n def evaluate(self, state):\n input_state = np.reshape(state, [1, self.input_dim])\n param_list = self.get_detail_params()\n l1 = np.maximum(0, input_state.dot(param_list[0]) + param_list[1])\n l2 = np.maximum(0, l1.dot(param_list[2]) + param_list[3])\n return 30 * np.tanh(l2.dot(param_list[4]) + param_list[5])\n\n def get_detail_params(self):\n # 得到w1,b1,w2,b2,w3,b3\n w1 = self.params[:self.input_dim * self.hidden_size]\n b1 = self.params[len(w1):len(w1) + self.hidden_size]\n w2 = self.params[len(w1) + len(b1):len(w1) + len(b1) + self.hidden_size * self.hidden_size]\n b2 = self.params[len(w1) + len(b1) + len(w2):len(w1) + len(b1) + len(w2) + self.hidden_size]\n w3 = self.params[len(w1) + len(w2) + len(b1) + len(b2):len(w1) + len(w2) + len(b1) + len(\n b2) + self.hidden_size * self.output_dim]\n b3 = self.params[-self.output_dim:]\n return [np.reshape(w1, [self.input_dim, self.hidden_size]),\n np.reshape(b1, [self.hidden_size, ]),\n np.reshape(w2, [self.hidden_size, self.hidden_size]),\n np.reshape(b2, [self.hidden_size, ]),\n np.reshape(w3, [self.hidden_size, self.output_dim]),\n np.reshape(b3, [self.output_dim, ])]\n\n def get_fitness(self):\n total_reward = 0\n env = self.hp.env\n obs = env.reset()\n for step in range(500):\n # env.render()\n action = self.evaluate(obs)\n next_obs, reward, done, _ = env.step(action)\n if np.sqrt(np.sum(np.square(next_obs[:2] - TARGET_GOAL))) < 0.1:\n reward = 1\n else:\n reward = 0\n obs = next_obs\n total_reward += reward\n if done:\n break\n if len(self.hp.archive) > 0:\n novelty = self.hp.cal_novelty(obs[:2])\n else:\n novelty = 0\n self.hp.count += 1\n return -novelty, -total_reward,obs[:2]\n\n\nclass MyProblem(Problem):\n def __init__(self, n_var, hp):\n super().__init__(n_var=n_var, n_obj=2, n_constr=0,\n xl=anp.array(-10000 * np.ones([n_var, ])),\n xu=anp.array(10000 * np.ones([n_var, ])))\n self.hp = hp\n\n def _evaluate(self, x, out, *args, **kwargs):\n novelty = []\n fitness = []\n for x1 in x:\n policy = Policy(hp=self.hp, params=x1)\n n, f, b = policy.get_fitness()\n novelty.append(n)\n fitness.append(f)\n self.hp.current_bc_list.append(b)\n out[\"F\"] = anp.column_stack([fitness, novelty])\n # out[\"G\"] = anp.column_stack(np.zeros([50,2]))\n if self.hp.get_update_signal():\n # 存储每一个当前bc list中的bc进novelty\n best_idx = np.argmin(novelty)\n print('########')\n print('Generation:',int(self.hp.count/50))\n print('Max novelty is:', np.min(novelty))\n print('Position:', self.hp.current_bc_list[best_idx])\n print('Archive length:', len(self.hp.archive))\n for bc in self.hp.current_bc_list:\n self.hp.archive.append(bc)\n self.hp.current_bc_list = []\n\n\nenv = AntMazeEnv(maze_id=TASK_NAME)\nhp = HP(env=env, input_dim=30, output_dim=8)\npolicy = Policy(hp)\nalgorithm = NSGA2(pop_size=50, n_offsprings=50, sampling=get_sampling(\"real_random\"),\n crossover=get_crossover(\"real_sbx\", prob=0.9, eta=15),\n mutation=get_mutation(\"real_pm\", eta=20),\n eliminate_duplicates=True)\ntermination = get_termination(\"n_gen\", 1000)\nproblem = MyProblem(n_var=policy.get_params_count(), hp=hp)\nres = minimize(problem, algorithm, termination, seed=1)\npickle.dump(problem.hp.archive,open(TASK_NAME+'_moea_'+str(VERSION),mode='wb'))\n","sub_path":"moea.py","file_name":"moea.py","file_ext":"py","file_size_in_byte":6922,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"50541929","text":"import random\n\nfrom helpers.rest_helper import RestHelper\nfrom model.company import Company\nfrom helpers.config import appUrl\nfrom model.division import Division\nfrom model.position import Position\nfrom helpers.config import parentCompanyOid\nfrom random import choice\n\nclass OrgHelper:\n\n def __init__(self):\n self.rest = RestHelper()\n self.appUrl = appUrl\n\n def create_company_type(self, initial_company, parent_company_oid=parentCompanyOid):\n url = f\"{appUrl}/idm/api/companies/card/new\"\n headers = {\"Accept-Encoding\": \"gzip, deflate\", \"Accept-Language\": \"ru\"}\n params = {\"sort\": \"\"}\n\n json = initial_company.return_company_data_as_json()\n # parent_company_value = self._generate_company_parent_value(parent_company_oid=parentCompanyOid)\n json.update({'parentCompanyRef': parent_company_oid})\n\n response = self.rest.call_request(request_type=\"POST\", url=url, json=json, headers=headers, params=params)\n json_response = response.json()\n #\n self.fill_company_data_from_response(initial_company, json_response)\n #\n setattr(initial_company, 'oid', initial_company.oid)\n print(initial_company)\n #\n return initial_company\n\n def get_company_by_oid(self, company_oid):\n url=f'{appUrl}/idm/api/companies/card/{company_oid}'\n headers = {\"Accept-Encoding\": \"gzip, deflate\", \"Accept-Language\": \"ru\"}\n params = {\"sort\": \"\"}\n json=None\n company_got_by_oid = Company()\n\n response = self.rest.call_request(request_type=\"GET\", url=url, json=json, headers=headers, params=params)\n json_response = response.json()\n\n self.fill_company_data_from_response(company_object=company_got_by_oid, json_response=json_response)\n # print(company_got_by_oid)\n return company_got_by_oid\n\n def fill_company_data_from_response(self, company_object, json_response):\n items = json_response['attributes']\n param_list = company_object.__dict__.keys()\n\n for param in list(param_list):\n for item in items:\n if item['name'] == param:\n setattr(company_object, param, item['value'])\n\n company_oid = json_response['oid']\n setattr(company_object, 'oid', company_oid)\n return company_object\n\n def _generate_company_parent_value(self, parent_company_oid):\n parent_company = self.get_company_by_oid(company_oid=parent_company_oid)\n parent_company_value = {}\n parent_company_value.update({'id': parent_company.oid, 'name': parent_company.shortName, 'userId': None})\n print(parent_company_value)\n\n def compare_company_data(self, created_company, company_get_by_oid):\n if created_company.__eq__(company_get_by_oid) == True:\n assert True\n print(f'[INFO] Created company with oid: {created_company.oid} and fullname: {created_company.fullName}')\n else:\n print(f'[ERROR] EXPECTED: {created_company}, BUT GOT: {company_get_by_oid}')\n assert False\n\n def create_division(self, initial_division, parent_id):\n url = f'{appUrl}/idm/api/division/card/new'\n headers = {\"Accept-Encoding\": \"gzip, deflate\", \"Accept-Language\": \"ru\"}\n params = {\"sort\": \"\"}\n json = None\n\n initial_division_object = initial_division.return_division_data_as_json()\n # division_json = initial_division_object.return_division_data_as_json()\n parent_orgs_object = self.generate_parent_org_object(parentId=parent_id)\n initial_division_object.update({'parentOrgs': parent_orgs_object})\n # print(division_json)\n json = initial_division_object\n\n response = self.rest.call_request(request_type=\"POST\", url=url, json=json, headers=headers, params=params)\n json_response = response.json()\n # initial_division_object = self.fill_division_data_from_response(division_object=initial_division_object, json_response=json_response)\n created_division = Division()\n self.fill_division_data_from_response(created_division, json_response)\n setattr(initial_division, 'oid', created_division.oid)\n assert initial_division.__eq__(created_division)\n\n #print(initial_division)\n print(created_division)\n\n return created_division\n\n\n def fill_division_data_from_response(self, division_object, json_response):\n items = json_response['attributes']\n param_list = division_object.__dict__.keys()\n\n for param in list(param_list):\n for item in items:\n if item['name'] == param:\n setattr(division_object, param, item['value'])\n\n division_oid = json_response['oid']\n setattr(division_object, 'oid', division_oid)\n return division_object\n\n def get_division_by_oid(self, division_oid):\n url = f'{appUrl}/idm/api/division/card/{division_oid}'\n headers = {\"Accept-Encoding\": \"gzip, deflate\", \"Accept-Language\": \"ru\"}\n params = {\"sort\": \"\"}\n json = None\n division_got_by_oid = Division()\n\n response = self.rest.call_request(request_type=\"GET\", url=url, json=json, headers=headers, params=params)\n json_response = response.json()\n\n self.fill_division_data_from_response(division_object=division_got_by_oid, json_response=json_response)\n # print(division_got_by_oid)\n return division_got_by_oid\n\n def compare_division_data(self, created_division, division_get_by_oid):\n if created_division.__eq__(division_get_by_oid) == True:\n assert True\n print(f'[INFO] Created division with oid: {created_division.oid} and fullname: {created_division.fullName}')\n else:\n print(f'[ERROR] EXPECTED: {created_division}, BUT GOT: {division_get_by_oid}')\n assert False\n\n\n def generate_parent_org_object(self, parentId):\n parent_orgs_object = {}\n url = f'{appUrl}/idm/api/division/card/{parentId}'\n headers = {\"Accept-Encoding\": \"gzip, deflate\", \"Accept-Language\": \"ru\"}\n params = {\"sort\": \"\"}\n json = None\n\n response = self.rest.call_request(request_type=\"GET\", url=url, json=json, headers=headers, params=params)\n json_reponse = response.json()\n if response.status_code == 200:\n division_object = Division()\n parent_division_object_filled = self.fill_division_data_from_response(division_object=division_object,\n json_response=json_reponse)\n parent_orgs = parent_division_object_filled.parentOrgs\n parent_orgs_object.update({'id': parentId, 'ids': parent_orgs['ids'] + [parent_division_object_filled.oid],\n 'name': parent_orgs['name'] + [parent_division_object_filled.shortName],\n 'paths': parent_orgs['name'] + [parent_division_object_filled.shortName],\n 'type': 'org'})\n # print(parent_orgs_object)\n return parent_orgs_object\n\n elif response.status_code == 500:\n parent_company_filled = self.get_company_by_oid(company_oid=parentId)\n # print(parent_company_filled)\n parent_orgs = parent_company_filled.parentCompanyRef\n parent_orgs_object.update({'id': parentId, 'ids': [parent_orgs['id']] + [parent_company_filled.oid],\n 'name': [parent_orgs['name']] + [parent_company_filled.shortName],\n 'paths': [parent_orgs['name']] + [parent_company_filled.shortName] ,'type': 'org'})\n # print(parent_orgs_object)\n return parent_orgs_object\n else:\n print(f'Что то пошло не так, код ответа: {response.status_code}')\n\n def make_position_path(self, parentId):\n clientId = 'root/'\n parent_division = self.get_division_by_oid(division_oid=parentId)\n parent_orgs_division = parent_division.parentOrgs\n parent_ids = parent_orgs_division['ids']\n\n for id in parent_ids:\n clientId += f'{id}/'\n\n clientId += f'{parentId}/'\n\n return clientId\n\n def create_position(self, parent_division_oid):\n url = f'{appUrl}/idm/api/catalog/entry/'\n headers = {\"Accept-Encoding\": \"gzip, deflate\", \"Accept-Language\": \"ru\"}\n params = {'search':'', 'countType': 'all', \"sort\": \"\"}\n\n initial_position_object = Position()\n position_json = initial_position_object.return_position_data_as_json()\n clientId = self.make_position_path(parentId=parent_division_oid)\n position_json.update({'clientId': clientId, 'parentId': parent_division_oid})\n print(position_json)\n\n response = self.rest.call_request(request_type=\"POST\", url=url, json=position_json, headers=headers, params=params)\n json_response = response.json()\n print(json_response)\n created_position = Position()\n self.fill_position_data_from_response(created_position, json_response)\n setattr(initial_position_object, 'id', created_position.id)\n assert initial_position_object.__eq__(created_position)\n\n return created_position\n\n def delete_position(self, position_id):\n url = f'{appUrl}/idm/api/catalog/entry/{position_id}'\n headers = {'WWW-Operation-Context': 'orgStruct', 'Accept-Encoding': 'gzip, deflate', 'Accept-Language': 'ru'}\n params = {}\n json = {'id': position_id, 'parentId': None, 'type': 'position'}\n\n response = self.rest.call_request(request_type=\"DELETE\", url=url, json=json, headers=headers, params=params)\n\n if response.status_code == 500:\n json_response = response.json()\n print(json_response)\n assert False\n else:\n print(response.status_code)\n assert True\n\n def get_children_by_parent_node_oid(self, parent_oid=None, child_oid=None):\n url = f'{appUrl}/idm/api/catalog/entry/{parent_oid}'\n headers = {'WWW-Operation-Context': 'orgStruct', 'Accept-Encoding': 'gzip, deflate', 'Accept-Language': 'ru'}\n params = {'search': None, 'countType': 'all', 'sort': None, 'node': f'root/{parent_oid}'}\n json = None\n\n response = self.rest.call_request(request_type=\"GET\", url=url, json=json, headers=headers, params=params)\n json_response = response.json()\n print(json_response)\n\n children_object = None\n for children in json_response['children']:\n if children['id'] == child_oid:\n children_object = children\n\n break\n if children_object == None:\n print(f'[ERROR] Cant get children with oid {child_oid} in node with oid {parent_oid}')\n\n children_got_by_oid = Position()\n self.fill_position_data_from_response(position_object=children_got_by_oid, json_response=children_object)\n print(children_got_by_oid)\n return children_got_by_oid\n\n def fill_position_data_from_response(self, position_object, json_response):\n\n param_list = position_object.__dict__.keys()\n for param in list(param_list):\n for json_key in json_response.keys():\n\n if json_key == param:\n setattr(position_object, param, json_response[json_key])\n\n position_oid = json_response['id']\n setattr(position_object, 'oid', position_oid)\n return position_object\n\n def compare_position_data(self, created_position=None, position_get_by_oid=None):\n if created_position.__eq__(position_get_by_oid) == True:\n assert True\n print(f'[INFO] Created position with oid: {created_position.id} and fullname: {created_position.name}')\n else:\n print(f'[ERROR] Expected: {created_position}, but got: {position_get_by_oid}')\n assert False\n\n def _get_all_children_for_node(self, node_oid=parentCompanyOid):\n url = f'{appUrl}/idm/api/catalog/entry/{node_oid}'\n headers = {'WWW-Operation-Context': 'orgStruct', 'Accept-Encoding': 'gzip, deflate', 'Accept-Language': 'ru'}\n params = {'search': None, 'countType': 'all', 'sort': None, 'node': f'root/{node_oid}'}\n json = None\n\n response = self.rest.call_request(request_type=\"GET\", url=url, json=json, headers=headers, params=params)\n children_list = response.json()\n #print(children_list['children'])\n return children_list['children']\n\n def _find_positions_in_org_node(self, node_oid, position_list=[]):\n\n node_objects = self._get_all_children_for_node(node_oid=node_oid)\n\n for node_object in node_objects:\n if node_object['type'] == 'position':\n position_list.append(node_object['id'])\n # print(position_list)\n else:\n self._find_positions_in_org_node(node_oid=node_object['id'])\n\n return position_list\n\n def _find_random_position_in_org_structure(self):\n # Проблема: если в орге нет ни одной должности random падает в ошибку\n # Решено обработкой исключения, если должностей нет возвращает False\n position_list = []\n node_objects = self._get_all_children_for_node(node_oid=parentCompanyOid)\n\n for node_object in node_objects:\n if node_object['type'] == 'position':\n position_list.append(node_object['id'])\n else:\n self._find_position_in_org_node(node_oid=node_object['id'], position_list=position_list)\n try:\n return random.choice(position_list)\n except IndexError:\n return False\n\n def _create_position_object_for_user(self, parent_division_oid, position_oid):\n position = {}\n path = 'root/'\n paths = []\n name = []\n ids = []\n parent_division = self.get_division_by_oid(division_oid=parent_division_oid)\n parent_orgs_division = parent_division.parentOrgs\n parent_ids = parent_orgs_division[0]['ids']\n parent_names = parent_orgs_division[0]['name']\n\n for id in parent_ids:\n path += f'{id}/'\n ids.append(id)\n\n path += f'{parent_division_oid}/{position_oid}'\n ids.append(parent_division_oid)\n ids.append(position_oid)\n\n for item in parent_names:\n name.append(item)\n paths.append(item)\n\n name.append(parent_division.shortName)\n paths.append(parent_division.shortName)\n\n parent_divison_children = self._get_all_children_for_node(node_oid=parent_division_oid)\n\n for child in parent_divison_children:\n if child['id'] == position_oid:\n name.append(child['name'])\n paths.append(child['name'])\n\n position.update({'id': position_oid, 'ids': ids , 'name': name, 'path': path, 'paths': paths, 'type': 'position'})\n\n # print(position)\n return position\n\n def _find_parent_for_position(self, position_oid, parent_oid = parentCompanyOid):\n # Проблема: отрабатывает 3 минуты на 186 стенде\n\n node_objects = self._get_all_children_for_node(node_oid=parent_oid)\n\n for node_object in node_objects:\n parent_oid = None\n parent_oid = node_object['id']\n #print(parent_oid)\n children_list = self._get_all_children_for_node(node_oid=parent_oid)\n for child in children_list:\n # print(child)\n if child['id'] == position_oid:\n print(parent_oid)\n return parent_oid\n break\n else:\n self._find_parent_for_position(position_oid=position_oid, parent_oid=parent_oid)\n\n\n\n\n\n\n\n\n\n\n\n\n\n\na = OrgHelper()\n# # # a.get_company_by_oid(company_oid='876412c3-4fab-4c12-b42f-7a40a1b38267')\ndivision = Division()\n# company = Company()\n# position = Position()\n# new_pos = Position()\n# # a.generate_parent_org_object(parentId='efb6f40a-c391-44e2-aeb0-6675cb321151')\n# #a.generate_parent_org_object(parentId='58fe98de-27cd-4205-8df8-d1071c4eb2bf')\n#a.create_division(division, parent_id='3252e137-98db-47a5-bae7-6cf947ddfdaf')\n# # a.make_position_path(parentId='b5a1f64f-d75c-4230-bd51-672bfc01c489')\n# # a.create_position(parentId='b5a1f64f-d75c-4230-bd51-672bfc01c489')\n# a.delete_position(positionId='f1b823ec-4442-4d56-baa9-c39152e5c404')\n#a.create_company_type(initial_company=company, parent_company_oid='876412c3-4fab-4c12-b42f-7a40a1b38267')\n#a._generate_company_parent_value(parent_company_oid='876412c3-4fab-4c12-b42f-7a40a1b38267')\n# json_response = a.get_children_by_parent_node_oid(parent_oid='3252e137-98db-47a5-bae7-6cf947ddfdaf', child_oid='585060c4-267f-40cd-99bc-f0b7f8668c0b')\n# position_object = a.fill_position_data_from_response(position_object=position, json_response=json_response)\n# print(position_object)\n# a.compare_position_data(created_position=position_object, position_get_by_oid=position_object)\n# print(a._get_all_children_for_node(node_oid='876412c3-4fab-4c12-b42f-7a40a1b38267'))\n# b = a._find_positions_in_org_node(node_oid='876412c3-4fab-4c12-b42f-7a40a1b38267')\n# print(b)\n#print(a._find_random_position_in_org_structure())\n# position = a._create_position_object_for_user(parent_division_oid='61c5664b-b27a-4ed1-958f-3db08c1e62e2', position_oid='9afd1807-d2c0-4ae9-a3cb-eb333a25f404')\n# print(position)\n# a._find_random_position_and_parent_in_org_structure()\n#a._find_parent_for_position(position_oid='568649f6-f4ab-4e9f-be7f-a502693f1dd7')\n\n\n","sub_path":"helpers/org_helper.py","file_name":"org_helper.py","file_ext":"py","file_size_in_byte":17753,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"474730634","text":"\"\"\"\nGathers functions required to perform operations on data : load, clean, create batches ...\n\"\"\"\n\nimport numpy as np\nimport pandas as pd\nimport re\nimport itertools\nimport sys\nfrom collections import Counter\nimport pickle\nimport os.path\nimport spacy\nfrom tqdm import tqdm\n\n\ndef clean_str(string):\n \"\"\"\n Tokenization/string cleaning\n Inspired from https://github.com/yoonkim/CNN_sentence/blob/master/process_data.py\n \"\"\"\n string = re.sub(r\"[^A-Za-z0-9(),!?\\'\\`]\", \" \", string)\n string = re.sub(r\"\\'s\", \" \\'s\", string)\n string = re.sub(r\"\\'ve\", \" \\'ve\", string)\n string = re.sub(r\"n\\'t\", \" n\\'t\", string)\n string = re.sub(r\"\\'re\", \" \\'re\", string)\n string = re.sub(r\"\\'d\", \" \\'d\", string)\n string = re.sub(r\"\\'ll\", \" \\'ll\", string)\n string = re.sub(r\",\", \" , \", string)\n string = re.sub(r\"!\", \" ! \", string)\n string = re.sub(r\"\\(\", \" \\( \", string)\n string = re.sub(r\"\\)\", \" \\) \", string)\n string = re.sub(r\"\\?\", \" \\? \", string)\n string = re.sub(r\"\\s{2,}\", \" \", string)\n return string.strip().lower()\n\n\ndef cut(s):\n \"\"\"\n Cuts questions at max question length\n \"\"\"\n temp = s.split(\" \")\n temp_max_question_length = s[:FLAGS.max_question_length]\n return \" \".join(temp_max_question_length)\n\n\ndef load_data_and_labels(FLAGS): #labels, query_CBOW, paragraph_CBOW, embedding_method\n \"\"\"\n Loads data from file and generates labels.\n \"\"\"\n\n if FLAGS.dataset_size == 'short_balanced':\n q_path = FLAGS.short_balanced_query_text\n p_path = FLAGS.short_balanced_paragraph_text\n y_path = FLAGS.short_balanced_labels\n elif FLAGS.dataset_size == 'full_balanced':\n q_path = FLAGS.full_balanced_query_text\n p_path = FLAGS.full_balanced_paragraph_text\n y_path = FLAGS.full_balanced_labels\n elif FLAGS.dataset_size == 'medium_balanced':\n q_path = FLAGS.medium_balanced_query_text\n p_path = FLAGS.medium_balanced_paragraph_text\n y_path = FLAGS.medium_balanced_labels\n else:\n print(\"Please define size of dataset to use\")\n sys.exit()\n\n if os.path.isfile(q_path):\n print(\"Loading and cleaning queries...\")\n q = np.load(q_path)\n\n if FLAGS.data_cleaning_flag is True:\n q = [clean_str(x) for x in q]\n print(\"Queries cleaned !\")\n else:\n print(\"text file not present. Exiting ...\")\n sys.exit()\n\n if os.path.isfile(p_path):\n print(\"Loading and cleaning paragraphs...\")\n p = np.load(p_path)\n if FLAGS.data_cleaning_flag is True:\n p = [clean_str(x) for x in p]\n print(\"Paragraph cleaned !\")\n else:\n print(\"text file not present. Exiting ...\")\n sys.exit()\n\n if not os.path.isfile(y_path):\n print(\"File containing labels not present. Please check the directory.\")\n sys.exit()\n else:\n y = np.load(y_path)\n\n print(\"Finished loading data successfully.\")\n return q, p, y\n\n\ndef batch_iter(data, batch_size, num_epochs, shuffle=True):\n \"\"\"\n Generates a batch iterator for a dataset.\n \"\"\"\n data = np.array(data)\n data_size = len(data)\n num_batches_per_epoch = int((len(data)-1)/batch_size) + 1\n for epoch in range(num_epochs):\n # Shuffle the data at each epoch\n if shuffle:\n shuffle_indices = np.random.permutation(np.arange(data_size))\n shuffled_data = data[shuffle_indices]\n else:\n shuffled_data = data\n for batch_num in range(num_batches_per_epoch):\n start_index = batch_num * batch_size\n end_index = min((batch_num + 1) * batch_size, data_size)\n yield shuffled_data[start_index:end_index]\n\n\ndef load_embeddings(path,vocab):\n \"\"\"\n Loads Glove emeddings and returns an embedding matrix corresponding to the vocabulary.\n Embedding matrix is of size vocab_size * embedding_size\n \"\"\"\n print(\"Loading embeddings...\")\n embs = ([x.split(\" \") for x in open(path).read().strip().split(\"\\n\")])\n print(\"Creating embedding mapping matrix...\")\n words = np.array([x[0] for x in embs])\n words_list = words.tolist()\n state_index = words_list.index('state')\n print(\"index of state : \",state_index)\n print(\"glove words[:10] : \", words[:10])\n mat = np.array([x[1:] for x in embs]).astype(float)\n print(\"glove vector 'word : state' : \", mat[state_index])\n mapped_words = [x[0] for x in vocab.transform(words)]\n print(\"glove mapped_words\",mapped_words[:100]) #lots of 0 for special symbols\n vocab_size = len(vocab.vocabulary_)\n emb_matrix = np.zeros((vocab_size,mat.shape[1]))\n set_words = set(mapped_words)\n print(\"mapped_words.index[0] :\",mapped_words.index(0))\n print(\"mat[0] :\",mat[mapped_words.index(0)])\n print(\"words[0] :\",words[mapped_words.index(0)])\n for i in range(vocab_size):\n if i in set_words:\n emb_matrix[i]=mat[mapped_words.index(i)]\n return emb_matrix\n","sub_path":"clean_code/data_helpers_embed.py","file_name":"data_helpers_embed.py","file_ext":"py","file_size_in_byte":4946,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"494231183","text":"import smax.io\nimport smax.process\nimport smax.display\nimport smax.check\n\n\ndef run(img_path, diameter=1.21, verbose=True, display=False, debug=False, write_results=False,\n iterations=10, scales_range=0.5, channel=0, pixel_size=False, save_raster=False, save_interpolated=False,\n check_time=False):\n # create dict from given variables\n v = locals()\n\n import smax\n import sys\n import time\n\n if check_time:\n time_total_start = time.time()\n\n # Print header and adjust variables\n v = smax.run_header(v)\n\n detections_df, v = smax.run_detection(v)\n\n if check_time:\n time_total_end = time.time()\n time_total = time_total_end - time_total_start\n print ('\\nTotal elapsed time:\\t' + str(time_total))\n print (' * load file:\\t\\t' + str(v['time_load_file']))\n print (' * interpolation:\\t' + str(v['time_interpolation']))\n print (' * first gauss filter:\\t' + str(v['time_first_gaussian']))\n print (' * local max:\\t\\t' + str(v['time_local_max']))\n print (' - scale gauss\\t' + str(v['time_scale_gauss']))\n print (' * get intensity:\\t' + str(v['time_get_intensity']))\n print (' * calculate GMM:\\t' + str(v['time_GMM']))\n\n return detections_df\n\n\ndef run_header(v):\n import time\n import smax\n import os\n import sys\n\n v['FWHMxy'] = v['diameter']\n\n if v['verbose']:\n smax.version()\n print(time.ctime())\n print ('')\n\n if v['debug']:\n print ('*** Attention, debug mode enabled ! ***')\n print ('')\n sys.stdout.flush()\n\n # Split path\n v['base_path'], v['full_file_name'] = os.path.split(v['img_path'])\n v['base_path'] += os.path.sep # Putting a slash on the end to create a full path\n v['file_name'] = v['full_file_name'][0:-4] # Getting only the name of the file, without extension\n\n if v['verbose']:\n print ('Path:\\t' + str(v['img_path']))\n print ('FWHM:\\t' + str(v['FWHMxy']))\n print ('Scales:\\t' + str(v['iterations']))\n # print ('Path:\\t\\t\\t' + str(v['base_path']))\n # print ('Name:\\t\\t\\t' + str(v['file_name']))\n sys.stdout.flush()\n\n # --- Reading metadata --- #\n if v['verbose']:\n print ('\\nReading file metadata:')\n v['meta'] = smax.io.meta(v['img_path'], verbose=v['verbose'])\n\n # Setting variables for img size\n if v['meta']['SizeT']:\n v['SizeT'] = v['meta']['SizeT']\n else:\n v['SizeT'] = 1\n v['meta']['SizeT'] = 1\n\n if v['debug']:\n v['SizeT'] = int(v['debug'])\n print ('\\n*** Debug mode, using only ' + str(v['debug']) + ' frames ! ***')\n sys.stdout.flush()\n v['SizeZ'] = v['meta']['SizeZ']\n v['SizeY'] = v['meta']['SizeY']\n v['SizeX'] = v['meta']['SizeX']\n v['pixel_size'] = float(v['meta']['PhysicalSizeX'])\n if v['SizeT']:\n v['ref_frame'] = int(float(v['SizeT']) / 2)\n else:\n v['ref_frame'] = 1\n\n if v['verbose']:\n print ('')\n\n return v\n\n\ndef run_detection(v):\n import numpy as np\n import scipy.ndimage\n import pandas as pd\n import sys\n import tifffile as tiff\n import scipy.spatial.distance\n import scipy.spatial\n import math\n import time\n\n # Start dataframe\n detections_df = pd.DataFrame([], columns=['t', 'z', 'y', 'x'])\n\n # Setting variables for img size\n SizeT = v['meta']['SizeT']\n SizeZ = v['meta']['SizeZ']\n PhysicalSizeX = float(v['meta']['PhysicalSizeX'])\n PhysicalSizeY = float(v['meta']['PhysicalSizeY'])\n PhysicalSizeZ = float(v['meta']['PhysicalSizeZ'])\n if v['check_time']:\n time_load_file = 0\n time_interpolation = 0\n time_first_gaussian = 0\n time_local_max = 0\n time_get_intensity = 0\n time_GMM = 0\n time_scale_gauss = 0\n\n if PhysicalSizeX != PhysicalSizeY:\n print ('WARNING: Pixel dimensions are different on X and Y. Maybe something is wrong with the metadata ?')\n sys.stdout.flush()\n\n # Case pixel size is not supplied, use from metadata\n if v['pixel_size']:\n pixel_size = v['pixel_size']\n else:\n pixel_size = PhysicalSizeX\n\n # Generate list of sigma values\n target_size = (float(v['FWHMxy']) / pixel_size) / 2 # diameter in microns -> radius in pixels\n target_sigma = target_size / (math.sqrt(2 * math.log(2))) # square root of 2ln2 for the equivalence with sigma\n\n scale_range = float(v['scales_range'])\n min_value = target_sigma - (target_sigma * scale_range) # Minimum object size\n max_value = target_sigma + (target_sigma * scale_range) # Maximum object size\n sigma_step = (max_value - min_value) / v['iterations'] # Sigma step for the desired number of iterations\n\n if v['verbose']:\n print ('Target radius:\\t' + str(target_size) + ' pixels')\n print ('Target sigma:\\t' + str(target_sigma))\n print ('Min sigma:\\t' + str(min_value))\n print ('Max sigma:\\t' + str(max_value))\n print ('Sigma step:\\t' + str(sigma_step))\n\n full_img = smax.io.load_full_img(v['img_path'], verbose=True)\n\n # Process every frame of the image\n for ref_frame in range(SizeT):\n if v['check_time']:\n time_load_file_start = time.time()\n\n # Reading file. Default channel is zero\n # img = smax.io.read(v['img_path'], v['meta'], frame=ref_frame, channel=v['channel'], verbose=v['verbose'])\n\n # Mode for already loaded image (TZCYX)\n if len(np.shape(full_img)) == 3:\n img = full_img\n else:\n img = full_img[ref_frame, :, 0, :, :] # nuclei channel is zero\n\n\n\n if v['check_time']:\n time_load_file_end = time.time()\n time_load_file = time_load_file_end - time_load_file_start\n v['time_load_file'] = time_load_file\n\n # Convert to float\n img = img.astype(float) # Converting to float, to be sure of precision level in next steps\n if v['debug']:\n print ('Working on ' + str(img.dtype))\n sys.stdout.flush()\n if v['check_time']:\n time_interpolation_start = time.time()\n # Interpolation. This step assures the isometric voxel\n if PhysicalSizeX != PhysicalSizeZ: # Only do it if it's needed\n nslices = int((SizeZ * PhysicalSizeZ) / PhysicalSizeX) # Number of slices we need for an isometric image\n if v['verbose']:\n print ('Interpolating ' + str(nslices) + ' slices from ' + str(SizeZ) + ' of the original image.'),\n sys.stdout.flush()\n zoom_ratio = float(nslices) / float(SizeZ)\n img = scipy.ndimage.interpolation.zoom(img, [zoom_ratio, 1, 1], order=3, mode='nearest')\n # Interpolation with order higher than 2 may cause negative values, fixing this here\n img[img < 0] = 0\n if v['verbose']:\n print ('[Done]')\n sys.stdout.flush()\n\n if v['save_interpolated']:\n save_path_interpolated = v['img_path'][:-4] + '_interpolated.tif'\n if v['debug']:\n print ('Saving detections as raster to disk:')\n print (str(save_path_interpolated)),\n sys.stdout.flush()\n sys.stdout.flush()\n img_to_save = img.astype('uint16', copy=True)\n tiff.imsave(save_path_interpolated, img_to_save)\n if v['debug']:\n print ('[Done]')\n sys.stdout.flush()\n\n # Add interpolated size to metadata\n v['meta']['SizeZinterpolated'] = np.shape(img)[0]\n\n if v['check_time']:\n time_interpolation_end = time.time()\n time_interpolation += time_interpolation_end - time_interpolation_start\n v['time_interpolation'] = time_interpolation\n # Counters and variables for this iteration\n total_iter = 0 # iteration counter\n accum_array = np.zeros(np.shape(img), dtype='float') # initializing accumulator array\n max_intensity = np.max(img)\n min_intensity = np.min(img)\n avg_intensity = np.mean(img)\n med_intensity = np.median(img)\n if v['debug']:\n print ('max intensity: ' + str(max_intensity))\n print ('avg intensity: ' + str(avg_intensity))\n print ('med intensity: ' + str(med_intensity))\n print ('min intensity: ' + str(min_intensity))\n sys.stdout.flush()\n\n if v['debug']:\n print ('\\nStarting filtered img for intensities...'),\n sys.stdout.flush()\n\n if v['check_time']:\n time_gaussian_start = time.time()\n\n # Filtered image to fetch the intensities\n img_intensity_filter = scipy.ndimage.filters.gaussian_filter(img, sigma=target_sigma, mode='constant', cval=0)\n\n if v['check_time']:\n time_first_gaussian_end = time.time()\n time_first_gaussian += time_first_gaussian_end - time_gaussian_start\n v['time_first_gaussian'] = time_first_gaussian\n\n if v['debug']:\n print ('[Done]')\n sys.stdout.flush()\n\n # Iterate through all the scales (sigma values)\n for sigma in np.arange(min_value, max_value, sigma_step):\n total_iter += 1\n\n if v['verbose']:\n print ('\\nScale #' + str(total_iter))\n print ('sigma ' + str(sigma))\n sys.stdout.flush()\n\n if v['check_time']:\n time_local_max_start = time.time()\n # Detection\n outputs = smax.process.local_max(img, v['FWHMxy'], pixel_size=pixel_size, gauss_sigma=sigma,\n verbose=v['verbose'], debug=v['debug'], v=v)\n if v['check_time']:\n time_local_max_end = time.time()\n time_local_max += time_local_max_end - time_local_max_start\n v['time_local_max'] = time_local_max\n # unpack outputs\n temp_df, num_detections, detections_array, img_filtered, v = outputs\n\n if v['check_time']:\n time_scale_gauss += float(v['time_scale_gauss_temp'])\n v['time_scale_gauss'] = time_scale_gauss\n\n # Using only indices doesn't improve speed for large arrays, need new ideas !\n # temp_accum_array = np.zeros(np.shape(detections_array))\n # temp_accum_array[detections_array] = img_intensity_filter[detections_array]\n\n if v['check_time']:\n time_get_intensity_start = time.time()\n temp_accum_array = detections_array * img_intensity_filter # reliable but slow\n if v['check_time']:\n time_get_intensity_end = time.time()\n time_get_intensity += time_get_intensity_end - time_get_intensity_start\n v['time_get_intensity'] = time_get_intensity\n\n if v['debug']:\n print ('[Done]')\n sys.stdout.flush()\n\n # Filter temporary array\n # Here we use a GMM to separate values that should be only background noise\n if v['debug']:\n print ('Initializing GMM...'),\n sys.stdout.flush()\n\n if v['check_time']:\n time_GMM_start = time.time()\n temp_thresh = smax.process.GMM_thresh(temp_accum_array, debug=v['debug'], verbose=v['debug'])\n\n if v['check_time']:\n time_GMM_end = time.time()\n time_GMM += time_GMM_end - time_GMM_start\n v['time_GMM'] = time_GMM\n\n if v['debug']:\n print ('[Done]')\n sys.stdout.flush()\n if v['display'] and v['debug']:\n # This histogram show the distribution of weights for this scale\n # Dark bars show values above the threshold\n smax.display.histogram(temp_accum_array[temp_accum_array > 0].flatten(), nbins=25, ylog=True,\n accent_after=temp_thresh[0], rotate_labels=True,\n title='Sigma: ' + str(sigma) + ' Thresh: ' + str(temp_thresh))\n\n # Values lower than the GMM threshold are removed\n if v['debug']:\n print ('Applying threshold...')\n sys.stdout.flush()\n\n if v['debug']:\n print ('min intensity before thresh: ' + str(np.min(temp_accum_array[np.nonzero(temp_accum_array)])))\n\n temp_accum_array[temp_accum_array < temp_thresh] = 0\n\n if v['debug']:\n print ('min value after thresh: ' + str(np.min(temp_accum_array[np.nonzero(temp_accum_array)])))\n\n if v['debug']:\n print ('[Done]')\n sys.stdout.flush()\n\n # Get number of detections after threshold\n foreground_ndetections = len(np.nonzero(np.ravel(temp_accum_array))[0])\n\n if v['verbose']:\n print (str(foreground_ndetections) + ' on foreground')\n sys.stdout.flush()\n\n # This scale is added to the global accumulator array\n accum_array += temp_accum_array\n\n # Save accumulator array to disk as raster image\n # This step is not needed for the rest of the process, It's only for later check\n if v['save_raster']:\n save_accum_path = v['base_path'] + 'accumulator.tif'\n print ('\\nSaving accumulator array:')\n\n print (str(save_accum_path)),\n sys.stdout.flush()\n accum_img = accum_array.astype('float', copy=True)\n tiff.imsave(save_accum_path, accum_img)\n print ('[Done]' + str(np.shape(accum_img)))\n\n # Create df from the iterations, for summary\n\n # Filtering the accumulator array, so that the final local maxima can be detected\n if v['debug']:\n print ('Filtering accumulator array...')\n sys.stdout.flush()\n\n array_blur = scipy.ndimage.filters.gaussian_filter(accum_array, sigma=target_sigma, mode='constant',\n cval=0)\n if v['debug']:\n print ('[Done]')\n sys.stdout.flush()\n\n # Save filtered array\n # This step is not needed for the rest of the process, It's only for debug purposes\n if v['save_raster']:\n save_accum_path = v['base_path'] + 'filtered.tif'\n print ('\\nSaving filtered array:')\n sys.stdout.flush()\n print (str(save_accum_path)),\n sys.stdout.flush()\n tiff.imsave(save_accum_path, array_blur)\n print ('[Done]' + str(np.shape(array_blur)))\n sys.stdout.flush()\n\n # Detect position on accumulator array\n if v['verbose']:\n print ('\\nStarting detection on accumulator array')\n sys.stdout.flush()\n if v['save_raster']:\n save_final_path = v['base_path'] + 'detections_final.tif'\n else:\n save_final_path = False\n outputs = smax.process.local_max(array_blur, v['FWHMxy'], pixel_size=pixel_size,\n gauss_sigma=target_sigma, verbose=False, debug=v['debug'],\n save_raster=save_final_path, gauss_filter=False, v=v)\n\n # unpack outputs\n temp_df, num_detections, detections_array, img_filtered, v = outputs\n\n # Insert time\n temp_df['t'] = ref_frame\n\n # Concatenate temporary frame to the final\n detections_df = pd.concat([detections_df, temp_df])\n\n if v['verbose']:\n print ('Process finished with '),\n print (str(len(temp_df)) + ' detections')\n\n # Writing to disk the results from the detection\n if v['write_results']:\n if v['verbose']:\n print ('\\nWriting dataframe to disk...'),\n sys.stdout.flush()\n detections_dataframe_path = v['base_path'] + v['file_name'] + '_detections.csv'\n detections_df.to_csv(detections_dataframe_path, index_label=False)\n if v['verbose']:\n print ('[Done]')\n print (detections_dataframe_path)\n sys.stdout.flush()\n\n if v['display']:\n # Generate 3D scatter plot with detections\n smax.display.plot_from_df(detections_df)\n\n return detections_df, v\n\n\ndef version(verbose=True):\n smax_version = '0.1'\n if verbose:\n print('smax v' + smax_version)\n return smax_version\n","sub_path":"smax/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":16539,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"598953131","text":"class Solution(object):\r\n def strStr(self, haystack, needle):\r\n \"\"\"\r\n :type haystack: str\r\n :type needle: str\r\n :rtype: int\r\n \"\"\"\r\n # print(len(needle),len(haystack))\r\n \r\n if needle ==\"\" and haystack == \"\":\r\n return 0\r\n if needle ==\"\" and haystack != \"\":\r\n return 0\r\n if needle != \"\" and haystack == \"\":\r\n return -1\r\n if len(needle)> len(haystack):\r\n return -1\r\n \r\n for i in range(len(haystack)):\r\n \r\n if needle[0] == haystack[i]:\r\n #print(\"hey\")\r\n #print(haystack[i:i+len(needle)])\r\n \r\n if needle == haystack[i:i+len(needle)]:\r\n \r\n return i\r\n \r\n return -1\r\n\r\nif __name__ == '__main__':\r\n\r\n test = Solution()\r\n print(test.strStr(\"PowerPoint\",\"Point\"))\r\n","sub_path":"strStr.py","file_name":"strStr.py","file_ext":"py","file_size_in_byte":935,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"126278126","text":"#! /usr/bin/env python\n# -*- coding:utf8 -*-\n#\n# test.py\n#\n# Copyright © 2013 Mathieu Gaborit (matael) \n#\n#\n# Distributed under WTFPL terms\n#\n# DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE\n# Version 2, December 2004\n#\n# Copyright (C) 2004 Sam Hocevar \n#\n# Everyone is permitted to copy and distribute verbatim or modified\n# copies of this license document, and changing it is allowed as long\n# as the name is changed.\n#\n# DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE\n# TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION\n#\n# 0. You just DO WHAT THE FUCK YOU WANT TO.\n#\n\nfrom ambilightsender1 import Sender\nfrom Queue import Queue\nimport sys\n\nHOST = '192.168.0.249'\n\nq = Queue()\n\ns = Sender(q, address=HOST)\n\nq.put((255,0,0))\nq.put((0,255,0))\nq.put((0,0,255))\n\ns.start()\n\nq.join()\n\nsys.exit()\n\n\n\n","sub_path":"matael_test/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":887,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"110645679","text":"\n# coding: utf-8\n\n# In[4]:\n\n\nimport copy\nimport numpy as np\nfrom random import *\nfrom IPython.display import clear_output\nimport sys\n\nwidth = 0\nheight = 0\ngrid = []\nup = np.array([0, -1])\ndown = np.array([0, 1])\nleft = np.array([-1, 0])\nright = np.array([1, 0])\nstay = np.array([0, 0])\n\ndef clear():\n for f in range(10):\n clear_output(wait=True)\n print(f)\n\ndef createmap():\n width = int(input(\"How wide?\"))\n height = int(input(\"How high?\"))\n row = []\n bak = '.'\n\n \n grid = [['.'] * (width) for height in range(height)]\n\n #for i in range(width):\n # row.append(bak)\n \n #for i in range(height):\n # row2 = copy.deepcopy(row)\n # grid.append(row2)\n \n return width, height, grid\n\ndef playerstart(width, height):\n x = randint(0, width-1)\n y = randint(0, height-1)\n \n playerposition = np.array([x, y])\n \n grid[y][x] = \"P\"\n\n print (\"You start at ({0},{1})\".format((x),(y)))\n \n return playerposition\n\ndef printmap():\n while True:\n for i in range(len(grid)):\n print(*grid[i:i+1])\n else: \n break\n return\n\ndef initialize():\n width, height, grid = createmap()\n playerposition = playerstart(width, height)\n printmap() \n\ndef move(playerposition):\n\n \n return playerposition\n\ndef playloop(): \n if data.lower()==\"move\":\n while True:\n createmap()\n printmap()\n data = input(\"Where do you want to go UP, DOWN, LEFT, RIGHT, STAY:\")\n if data.lower() not in ('up', 'down', 'left', 'right', 'stay'):\n print(\"Not an appropriate choice.\")\n continue\n else:\n break\n if data.lower()==\"up\":\n newposition = playerposition+up\n if newposition[1] < 0:\n newposition[1] = newposition[1]+len(grid)\n elif data.lower()==\"down\":\n newposition = playerposition+down\n if newposition[1] > len(grid)-1:\n newposition[1] = newposition[1]-len(grid)\n elif data.lower()==\"right\":\n newposition = playerposition+right\n if newposition[0] > width-1:\n newposition[0] = newposition[0]-width\n elif data.lower()==\"left\":\n newposition = playerposition+left \n if newposition[0] < 0:\n newposition[0] = newposition[0]+width\n\n elif data.lower()==\"stay\":\n newposition = playerposition+stay\n\n if (np.array_equal(playerposition, newposition)):\n print (\"You didnt move\") \n\n else:\n grid[playerposition[1]][playerposition[0]] = \" \"\n playerposition = newposition\n grid[playerposition[1]][playerposition[0]] = \"P\"\n print (\"You moved to ({0},{1})\".format((playerposition[0]),(playerposition[1])))\n\n printmap()\n \nplayloop()\n\n\n\n# In[ ]:\n\n\n#for i in range(height):\n# x = randint(0, width-1)\n# y = randint(0, height-1)\n#\n# grid[x][y] = \"A\"\"\"\"\n\n\n# In[ ]:\n\n\nprintmap(createmap())\n\n","sub_path":"old game.py","file_name":"old game.py","file_ext":"py","file_size_in_byte":3471,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"250087002","text":"import os\nimport csv\nimport datetime\nimport cv2\nimport numpy as np\nimport sklearn\nfrom keras.models import Sequential, Model\nfrom keras.layers import Lambda, Input, Flatten, Dense, Cropping2D, Convolution2D, Dropout\nfrom keras.callbacks import ModelCheckpoint\nimport matplotlib.pyplot as plt\nimport tensorflow as tf\nfrom sklearn.model_selection import train_test_split\n\ndef color2gray(xin):\n \"\"\"\n convert color image to gray\n \"\"\"\n return (0.21 * xin[:,:,:,:1]) + (0.72 * xin[:,:,:,1:2]) + (0.07 * xin[:,:,:,-1:])\n\ndef genModel():\n \"\"\"\n generate CNN model (based on NVIDIA self driving car)\n \"\"\"\n inp = (160, 320, 3) # initial image size\n oup1 = (160, 320, 1) # gray image size\n oup2 = (80, 320, 1) # cropped image size\n\n model = Sequential()\n model.add(Lambda(color2gray, input_shape = inp, output_shape= oup1))\n # crop top 50 pixels, bottom 30 pixels, left/right 0 pixels\n model.add(Cropping2D(cropping=((50,30), (0,0))))\n # Preprocess incoming data, centered around zero with small standard deviation \n model.add(Lambda(lambda x: x/127.5 - 1., output_shape= oup2))\n model.add(Convolution2D(24,5,5,subsample=(1,2), activation=\"relu\"))\n model.add(Convolution2D(36,5,5,subsample=(2,2), activation=\"relu\"))\n model.add(Convolution2D(48,5,5,subsample=(2,2), activation=\"relu\"))\n model.add(Convolution2D(64,3,3, activation=\"relu\"))\n model.add(Convolution2D(64,3,3, activation=\"relu\"))\n model.add(Flatten())\n model.add(Dropout(0.3))\n model.add(Dense(180, activation=\"relu\"))\n model.add(Dense(60))\n model.add(Dense(10, activation=\"relu\"))\n model.add(Dense(1))\n # print layer size for each model layers\n for layer in model.layers:\n print(layer.get_output_at(0).get_shape().as_list())\n return model\n\ndef Plot_loss(history_object):\n \"\"\"\n print history data and plot losses\n \"\"\" \n ### print the keys contained in the history object\n print(history_object.history.keys())\n print(history_object.history['loss'])\n print(history_object.history['val_loss'])\n\n ### plot the training and validation loss for each epoch\n plt.plot(history_object.history['loss'])\n plt.plot(history_object.history['val_loss'])\n plt.title('model mean squared error loss')\n plt.ylabel('mean squared error loss')\n plt.xlabel('epoch')\n plt.legend(['training set', 'validation set'], loc='upper right')\n plt.show()\n\n\n\ndef generator(samples, batch_size=32):\n \"\"\"\n use generator to avoid large memory consumption\n \"\"\"\n num_samples = len(samples)\n while 1: # Loop forever so the generator never terminates\n sklearn.utils.shuffle(samples)\n for offset in range(0, num_samples, batch_size):\n batch_samples = samples[offset:offset+batch_size]\n images = []\n angles = []\n for batch_sample in batch_samples:\n # append center image\n name = 'Sample_data/IMG/'+batch_sample[0].split('/')[-1]\n center_image = cv2.imread(name)\n center_angle = float(batch_sample[3])\n images.append(center_image)\n angles.append(center_angle)\n correction = 0.30 # shift angle commands\n # append left camera image\n left_angle = center_angle + correction\n lname = 'Sample_data/IMG/'+batch_sample[1].split('/')[-1]\n left_image = cv2.imread(lname)\n images.append(left_image)\n angles.append(left_angle)\n \n # append right camera image\n right_angle = center_angle + correction\n rname = 'Sample_data/IMG/'+batch_sample[1].split('/')[-1]\n right_image = cv2.imread(rname)\n images.append(right_image)\n angles.append(right_angle)\n\n # flip image to augment data\n Nsample = len(angles)\n for i in range(len(angles)):\n images.append(np.fliplr(images[i]))\n angles.append(-angles[i])\n\n # trim image to only see section with road\n X_train = np.array(images)\n y_train = np.array(angles)\n yield sklearn.utils.shuffle(X_train, y_train)\n\ndef loadRawData():\n \"\"\"\n load Raw data for steering angle\n \"\"\"\n samples = []\n with open('Sample_data/driving_log.csv') as csvfile:\n reader = csv.reader(csvfile)\n for line in reader:\n # skip the first line, which is the title line\n if line[0] != 'center':\n samples.append(line)\n # for testing implementation only, commented for GPU training\n #if len(samples)>100:\n # break\n train_samples, validation_samples = train_test_split(samples, test_size=0.2)\n return train_samples, validation_samples\n\ndef trainModel(model, train_raw, validation_raw):\n \"\"\"\n training data and save model checkpoints\n \"\"\"\n # compile and train the model using the generator function\n train_generator = generator(train_raw, batch_size=32)\n validation_generator = generator(validation_raw, batch_size=32)\n\n # model checkpoint\n now = datetime.datetime.now()\n datenow = now.strftime(\"%Y-%m-%d-\")\n #file_path_model = \"Model_checkpoints/\" + datenow + \"model-weights-{epoch:02d}-{val_loss:0.2f}.hdf5\"\n file_path_model = \"Model_checkpoints/\" + datenow + \"model-weights.hdf5\"\n checkpoint = ModelCheckpoint(file_path_model, monitor='val_loss', verbose=1, save_best_only=True, mode='auto')\n callbacks_list = [checkpoint]\n model.compile(loss='mse', optimizer='adam')\n # left/center/right images, and all flipped\n ntrain = len(train_raw)*3*2\n nvalid = len(validation_raw)*3*2\n history_object = model.fit_generator(train_generator, samples_per_epoch= \\\n ntrain, validation_data=validation_generator, \\\n nb_val_samples=nvalid, nb_epoch=10, \\\n callbacks = callbacks_list, verbose=1)\n #history_object = model.fit_generator(train_generator, steps_per_epoch= ntrain, \\\n # validation_data=validation_generator, validation_steps=nvalid, \\\n # callbacks = callbacks_list, epochs=5, verbose = 1) \n return history_object\n\n\nif __name__ == \"__main__\":\n # load raw training data\n train_raw, validation_raw = loadRawData()\n\n # generate CNN model\n model = genModel()\n\n # train CNN model\n history_object = trainModel(model, train_raw, validation_raw)\n\n # plot training data\n Plot_loss(history_object)\n","sub_path":"model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":6582,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"451221694","text":"from selenium.webdriver.common.by import By\nfrom selenium.webdriver.support.ui import Select\nfrom CommonLibs.webdriver.Wait import Wait\nfrom .FileUploader import FileUploader\n\n\nclass FormFiller(FileUploader):\n\t\"\"\"\n\tЗаполнение формы данными. \n\t\"\"\"\n\tdef __init__(self, driver):\n\t\tsuper().__init__(driver)\t\t\t\t\n\n\tdef __SetCheckbox(self, locator, state):\n\t\t\"\"\"\n\t\tПоставить чекбокс в положение state. \n\t\t\"\"\"\n\t\tcheckbox = self.__SearchFunction(locator)\t\t\n\t\tif state ^ checkbox.is_selected():\n\t\t\tcheckbox.click()\n\n\tdef __SetSelect(self, locator, TextOption):\n\t\t\"\"\"\n\t\tВыбрать из списка пункт с текстом TextOption. \n\t\t\"\"\"\n\t\tselect = Select(self.__SearchFunction(locator))\n\t\tselect.select_by_visible_text(TextOption)\n\n\tdef __SetCustomSelect(self, locators, TextOption):\n\t\t\"\"\"\n\t\tВыбрать из кастомного списка пункт с текстом TextOption. \n\t\t\"\"\"\n\t\tself.__waiter.waitVisible(self.driver.find_element_by_xpath(locators[0])).click()\n\t\tOptionLocator = locators[1].format(TEXT = TextOption)\t\t\n\t\tself.__waiter.waitVisible(self.driver.find_element_by_xpath(OptionLocator)).click()\n\n\tdef __SetWysiwyg(self, locator, data):\n\t\t\"\"\"\n\t\tЗаполнить визивиг. \n\n\t\tArguments:\n\t\t- locator: Ид скрытой textarea, расположенной рядом с визивигом. \n\t\t- data: Данные для ввода. \n\t\t\"\"\"\n\t\tIframeLocator = \"//iframe[contains(@title, '{0:s}')]\".format(locator)\n\t\tframe = self.__waiter.waitVisible(self.driver.find_element_by_xpath(IframeLocator))\n\t\tself.driver.switch_to.frame(frame)\t\t\t\t\n\t\tself.driver.find_element_by_tag_name('body').send_keys(data)\n\t\tself.driver.switch_to.default_content()\n\n\tdef __SetInput(self, locator, data):\n\t\t\"\"\"\n\t\tЗаполнить текстовое поле input. \n\t\t\"\"\"\n\t\telement = self.__waiter.waitVisible(self.__SearchFunction(locator))\n\t\telement.clear()\n\t\telement.send_keys(data)\n\n\tdef FillForm(self, FormLocators, FormData, strategy = 'id'):\n\t\t\"\"\"\n\t\tЗаполнить форму. \n\n\t\tArguments:\n\t\t- FormLocators: Локаторы полей формы. \n\t\t- FormData: Данные. \n\t\t- strategy: Стратегия поиска полей. По умолчанию поля ищутся по ид. \n\t\t\tВозможные значения: id, name, xpath\n\t\t\"\"\"\n\t\tif strategy == 'id':\n\t\t\tself.__SearchFunction = self.driver.find_element_by_id\n\t\telif strategy == 'name':\n\t\t\tself.__SearchFunction = self.driver.find_element_by_name\n\t\telif strategy == 'xpath':\n\t\t\tself.__SearchFunction = self.driver.find_element_by_xpath\n\n\t\tself.__waiter = Wait(self.driver,60)\n\n\t\tfor i in range(0,len(FormData)):\t\t\t\t\t\t\t\t\t\n\t\t\tif FormLocators[i][0] == 'checkbox':\n\t\t\t\tself.__SetCheckbox(FormLocators[i][1], FormData[i])\n\t\t\telif FormLocators[i][0] == 'input':\t\t\t\t\t\t\t\t\n\t\t\t\tself.__SetInput(FormLocators[i][1], FormData[i])\n\t\t\telif FormLocators[i][0] == 'select':\n\t\t\t\tself.__SetSelect(FormLocators[i][1], FormData[i])\n\t\t\telif FormLocators[i][0] == 'custom select':\n\t\t\t\tself.__SetCustomSelect(FormLocators[i][1], FormData[i])\t\n\t\t\telif FormLocators[i][0] == 'wysiwyg':\t\t\t\t\n\t\t\t\tself.__SetWysiwyg(FormLocators[i][1], FormData[i])\n\t\t\telif FormLocators[i][0] == 'image':\n\t\t\t\tself.UploadImageFromGallery(FormLocators[i][1], FormData[i])\n\t\t\t\t#'form-field-image_id'\n\t\t\telif FormLocators[i][0] == 'upload':\n\t\t\t\tself.UploadFile(FormLocators[i][1], FormData[i])\n\n\tdef Submit(self, FormLocator):\n\t\t\"\"\"\n\t\tОтправить форму. \n\n\t\tArguments:\n\t\t- FormLocator: Локатор любого поля формы. \n\t\t\"\"\"\t\n\t\tself.__SearchFunction(FormLocator).submit()","sub_path":"FormFiller/FormFiller.py","file_name":"FormFiller.py","file_ext":"py","file_size_in_byte":3605,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"500948691","text":"#Barnaby Skinner\n#2016-05-30\n#Homework 3\n\n#LISTS\n\n#1) Make a list called \"countries\" - it should contain seven different\n#countries and NOT be in alphabetical order\ncountries = [\"Switzerland\", \"Germany\", \"United Kingdom\", \"France\", \"Italy\",\n\"Liechstenstein\"]\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#print(countries)\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 using a line of code that\n#will work no matter what the size of the list is (hint: len will be helpful)\ncountries_count = int(len(countries))\ncountries_count_minus_1 = countries_count - 2\nprint(countries[countries_count_minus_1])\n\n#6) Delete one of the countries from the list using its name (we didn't\n#learn this in class).\ncountries.remove(\"Germany\")\n\n#7) Using a for loop, print each element of the list again, which should now\n#be one element shorter.\nfor country in countries:\n print(country)\n\n#DICTIONARIES\n\n#1) Make a dictionary called 'tree' that responds to 'name', 'species', 'age',\n#'location_name', 'latitude' and 'longitude'. Pick a tree from\n#here:https://en.wikipedia.org/wiki/List_of_trees\ntree = {\"name\": \"Granit Oak\", \"species\": \"Oak\", \"age\": 1650, \"location_name\":\n \"Granit village, Bulgaria\", \"Latitude\": 42.252403, \"Longitude\": 25.136684}\n\n#2) Print the sentence \"{name} is a {years old} tree that is in {location_name}\"\nprint((tree[\"name\"]), \"is a\", (tree[\"age\"]), \"years old tree that is in\",\n (tree[\"location_name\"]), \".\")\n\n#3) The coordinates of New York City are 40.7128° N, 74.0059° W. Check to see\n#if the tree is south of NYC, and print \"The tree {name} in {location} is south\n#of NYC\" if it is. If it isn't, print \"The tree {name} in {location} is north\n#of NYC\"\nNew_York = {\"Latitude\": 40.7128, \"Longitude\": -74.0059}\nif New_York[\"Latitude\"] < tree[\"Latitude\"]:\n print(\"The tree\", (tree[\"name\"]), \"in\", (tree[\"location_name\"]),\n \"is north of NYC.\")\nelse:\n print(\"The tree\", (tree[\"name\"]), \"in\", (tree[\"location_name\"]),\n \"is south of NYC.\")\n\n#4) 4) Ask the user how old they are. If they are older than the tree, display\n#\"you are {XXX} years older than {name}.\" If they are younger than the tree,\n#display \"{name} was {XXX} years old when you were born.\"\nuser_age= input(\"How old are you, if I may ask? \")\n\nif int(user_age) > tree[\"age\"]:\n age_difference = int(user_age) - tree[\"age\"]\n print(\"You are\", age_difference, \"years older than\", tree[\"name\"])\nelse:\n age_difference2 = tree[\"age\"] - int(user_age)\n print(tree[\"name\"], \"was\", age_difference2, \"years old, when you were born\",)\n\n#LISTS OF DICTIONARIES\n\n#1) Make a list of dictionaries of five places across the world - (1) Moscow,\n#(2) Tehran, (3) Falkland Islands, (4) Seoul, and (5) Santiago. Each dictionary\n#should include each city's name and latitude/longitude (see note above).\nFive_places = [\n {\"name\": \"Moscow\", \"Latitude\": 55.755826, \"Longitude\": 37.617300},\n {\"name\": \"Tehran\", \"Latitude\": 35.689197, \"Longitude\": 51.388974},\n {\"name\": \"Falkland Islands\", \"Latitude\": -51.796253, \"Longitude\": -59.523613},\n {\"name\": \"Seoul\", \"Latitude\": 37.566535, \"Longitude\": 126.977969},\n {\"name\": \"Santiago\", \"Latitude\": -33.4489, \"Longitude\": -70.6693}\n ]\n#2) Loop through the list, printing each city's name and whether it is above or\n#below the equator (How do you know? Think hard about the latitude.). When you\n#get to the Falkland Islands, also display the message \"The Falkland Islands are\n#a biogeographical part of the mild Antarctic zone,\" which is a sentence I stole\n#from Wikipedia.\nfor city in Five_places:\n if city[\"Latitude\"] == -51.796253:\n print(\"The Falkland Islands are a biogeographical part of the mild Antarctic zone, and below the equator.\")\n elif city[\"Latitude\"] > 0 and city[\"Latitude\"] != -51.796253:\n print(city[\"name\"], \"is above the equator.\")\n else:\n print(city[\"name\"], \"is below the equator.\")\n\n#3) Loop through the list, printing whether each city is north of south of your\n#tree from the previous section.\n\nfor city in Five_places:\n if city[\"Latitude\"] > tree[\"Latitude\"]:\n print((city[\"name\"]), \"is north of the\", (tree[\"name\"]))\n elif city[\"Latitude\"] == tree[\"Latitude\"]:\n print((city[\"name\"]), \"and\", (tree[\"name\"]), \"are at exactly the same latitude.\")\n else:\n print((city[\"name\"]), \"is south of the\", (tree[\"name\"]))\n","sub_path":"03/homework-3-skinner.py","file_name":"homework-3-skinner.py","file_ext":"py","file_size_in_byte":4520,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"424690678","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Thu Feb 4 11:19:52 2021\r\n\r\n@author: suraj\r\n\"\"\"\r\n\r\n\r\nimport numpy as np\r\nimport cv2\r\nfrom matplotlib import pyplot as plt\r\n\r\ndef readfile(image):\r\n img1=open(image,\"r\")\r\n p1=img1.readline()\r\n p2=img1.readline()\r\n t1=img1.readline()\r\n p3=img1.readline()\r\n width,height=[int(i) for i in t1.split()]\r\n imag=np.zeros((height,width), dtype=np.uint8)\r\n for i in range(height):\r\n for j in range(width):\r\n imag[i,j]=img1.readline()\r\n \r\n return(imag,p1,p2,t1,p3)\r\n \r\n\r\ndef writefile(img,t1,t2,t3,t4):\r\n im=open(\"images\\camera5.pgm\",\"w\")\r\n im.write(\"%s\"%t1)\r\n im.write(\"%s\"%t2)\r\n im.write(\"%s\"%t3)\r\n im.write(\"%s\"%t4)\r\n h=img.shape[0]\r\n w=img.shape[1]\r\n \r\n for i in range(h):\r\n for j in range(w):\r\n im.write(\"%d\\n\"%img[i,j])\r\n\r\n im.close()\r\n\r\n\r\nimg,p1,p2,t1,p3=readfile(\"images\\camera2.pgm\")\r\ndimension=img.shape\r\nprint(dimension)\r\nheight=img.shape[0]\r\nwidth=img.shape[1]\r\n\r\nimag=np.zeros((height,width), dtype=np.uint8)\r\n\r\nfor i in range(0,height-1,1):\r\n for j in range(0,width-1,1):\r\n pixel=[img[i-1, j-1],img[i-1, j],img[i-1, j + 1],img[i, j-1],img[i, j],img[i, j + 1],img[i + 1, j-1],img[i + 1, j],img[i + 1, j + 1]]\r\n pixel.sort()\r\n imag[i,j]=pixel[4]\r\n\r\n\r\nwritefile(imag,p1,p2,t1,p3)\r\nprint(imag)\r\nimg3 = cv2.hconcat([img,imag])\r\ncv2.imshow('image',img3)","sub_path":"medianfilter.py","file_name":"medianfilter.py","file_ext":"py","file_size_in_byte":1422,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"368277026","text":"from node import Node\nfrom particle import Particle\nfrom vector2d import Vector2d\nfrom bh_tree import BHtree\nfrom profiler import Profiler\nimport random\nimport io_xyz\nimport math\nimport forces\nimport constants\nimport plotting\nimport copy\nimport os\n\n# import networkx as nx\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport matplotlib\n\n\ndef make_rotation_matrix(angle):\n return np.array([[np.cos(angle), -np.sin(angle)], [np.sin(angle), np.cos(angle)]])\n\n\ndef getMinVolEllipse(P=None, tolerance=0.01):\n \"\"\" Find the minimum volume ellipsoid which holds all the points\n\n Based on work by Nima Moshtagh\n http://www.mathworks.com/matlabcentral/fileexchange/9542\n and also by looking at:\n http://cctbx.sourceforge.net/current/python/scitbx.math.minimum_covering_ellipsoid.html\n Which is based on the first reference anyway!\n\n Here, P is a numpy array of N dimensional points like this:\n P = [[x,y,z,...], <-- one point per line\n [x,y,z,...],\n [x,y,z,...]]\n\n Returns:\n (center, radii, rotation)\n\n \"\"\"\n (N, d) = np.shape(P)\n d = float(d)\n\n # Q will be our working array\n Q = np.vstack([np.copy(P.T), np.ones(N)])\n QT = Q.T\n\n # initializations\n err = 1.0 + tolerance\n u = (1.0 / N) * np.ones(N)\n\n # Khachiyan Algorithm\n while err > tolerance:\n V = np.dot(Q, np.dot(np.diag(u), QT))\n M = np.diag(np.dot(QT, np.dot(np.linalg.inv(V), Q))) # M the diagonal vector of an NxN matrix\n j = np.argmax(M)\n maximum = M[j]\n step_size = (maximum - d - 1.0) / ((d + 1.0) * (maximum - 1.0))\n new_u = (1.0 - step_size) * u\n new_u[j] += step_size\n err = np.linalg.norm(new_u - u)\n u = new_u\n\n # center of the ellipse\n center = np.dot(P.T, u)\n\n # the A matrix for the ellipse\n A = np.linalg.inv(\n np.dot(P.T, np.dot(np.diag(u), P)) -\n np.array([[a * b for b in center] for a in center])\n ) / d\n\n # Get the values we'd like to return\n U, s, rotation = np.linalg.svd(A)\n radii = 1.0 / np.sqrt(s)\n\n return (center, radii, rotation)\n\n\ndef create_sphere(radii, num_sumples=2000):\n cur_num_particles = 0\n attempts = 100\n particles = []\n while True:\n u = np.random.uniform(0, 2*np.pi)\n # v = np.random.uniform(0, np.pi)\n\n # cosu = np.random.uniform(-1, 1)\n cosv = np.random.uniform(-1, 1)\n tmp_z = np.random.uniform(0, 1)\n\n v = np.arccos(cosv)\n\n mul = tmp_z**(1/3)\n r1 = radii[0]*mul\n r2 = radii[1]*mul\n r3 = radii[2]*mul\n\n # mul = tmp_z**(1/2)\n # r1 = radii[0]*mul\n # r2 = radii[1]*mul\n # r3 = radii[2]*mul\n\n\n # lam = 0.1\n # k = 0.00001\n # r1 = radii[0]*(1-np.exp(tmp_z/lam)**k)\n # r2 = radii[1]*(1-np.exp(tmp_z/lam)**k)\n # r3 = radii[2]*(1-np.exp(tmp_z/lam)**k)\n\n # k = 1\n # mul = -1/np.log(k - k*0.99999) * np.log(k - k*tmp_z)\n # r1 = radii[0]*mul\n # r2 = radii[1]*mul\n # r3 = radii[2]*mul\n\n # k = 1\n # mul = (-1/(1+np.exp(-10*(tmp_z-0.5)))+1)**(1/3)\n # r1 = radii[0]*mul\n # r2 = radii[1]*mul\n # r3 = radii[2]*mul\n\n tmp = [r1 * np.cos(u) * np.sin(v), r2 * np.sin(u) * np.sin(v), r3 * np.cos(v)]\n if criterion(tmp, particles):\n # [x, y, z] = np.dot([tmp[0][0][0], tmp[1][0][0], tmp[2][0][0]], rotation) + center\n [x, y, z] = [tmp[0], tmp[1], tmp[2]]\n particles.append(Particle(r=Vector3d(x, y, z), color=(0, 0, 0), name=len(particles)))\n\n cur_num_particles += 1\n if cur_num_particles % 1 == 0:\n print(cur_num_particles)\n if cur_num_particles == num_sumples:\n break\n return particles\n\n\ndef get_and_plot_density(particles, radii, rotation, center, num=100):\n cm = Vector2d()\n particles_ = copy.deepcopy(particles)\n\n derotation = np.linalg.inv(rotation)\n\n for particle in particles_:\n particle.r.x -= center[0]\n particle.r.y -= center[1]\n\n tmp = np.dot(np.array([particle.r.x, particle.r.y]), derotation)\n particle.r = Vector2d(tmp[0], tmp[1])\n\n cm += particle.r\n cm = cm * (1/len(particles_))\n\n for i in range(len(particles)):\n particles_[i].r.x *= 1/radii[0]\n particles_[i].r.y *= 1/radii[1]\n\n lengths = sorted([abs(particle.r) for particle in particles_])\n density = []\n l = []\n # particles = sorted(particles, key=lambda particle: abs(particle.r - cm))\n\n for i in range(len(lengths)//num):\n density.append(num*particles_[0].mass/(np.pi*(lengths[i*num + num-1]**2 - lengths[i*num]**2)))\n # l.append(lengths[i*num] + 0.5*(lengths[i*num + num-1] - lengths[i*num]))\n l.append(lengths[i*num])\n\n ig, ax1 = plt.subplots(figsize=(4, 4))\n\n ax1.scatter(x=l, y=density, marker='o', c='r', edgecolor='b')\n ax1.set_title('Scatter: $x$ versus $y$')\n ax1.set_xlabel('$x$')\n ax1.set_ylabel('$y$')\n plt.show()\n\n return density, lengths\n\n\ndef criterion(tmp, particles):\n tmp_particle = Particle(r=Vector2d(*tmp))\n for particle in particles:\n # print((tmp_particle.r - particle.r).dot(forces.base_force(tmp_particle, particle)))\n # if (tmp_particle.r - particle.r).dot(forces.base_force(tmp_particle, particle)) > -0.3:\n if abs(tmp_particle.r - particle.r) < 1*constants.a:\n return False\n return True\n\n\ndef create_sphere2(radii, lengths, num_sumples=2000, mass=1):\n attempts = 100\n # particles = [Particle(r=Vector3d(), mass=10)]\n particles = []\n num = 100\n for i in range(0, len(lengths) // num):\n cur_num_particles = 0\n while True:\n u = np.random.uniform(0, 2*np.pi)\n tmp_z = np.random.uniform(0, 1)\n\n mul = tmp_z**(1/3)\n # mul = (mul * lengths[i*num + num-1]) + (lengths[i*num + num-1] - lengths[i*num])\n mul = lengths[i*num] + mul*(lengths[i*num + num-1] - lengths[i*num])\n r1 = radii[0]*mul\n r2 = radii[1]*mul\n\n tmp = [r1 * np.cos(u), r2 * np.sin(u)]\n if criterion(tmp, particles):\n [x, y] = [tmp[0], tmp[1]]\n particles.append(Particle(r=Vector2d(x, y), mass=mass))\n\n cur_num_particles += 1\n # if cur_num_particles % 1 == 0:\n # print(cur_num_particles)\n if cur_num_particles == num//10:\n break\n return particles\n\n\n# particles = io_xyz.read('../Space/test/results_22350.xyz')\n# particles = io_xyz.read('../Space/test/results_1.xyz')\nparticles = io_xyz.read('../Space/test3/results_150.xyz')\nprint(len(particles))\n\n(center, radii, rotation) = getMinVolEllipse(\n np.array([[particle.r.x, particle.r.y] for particle in particles], dtype='float32'))\n\ndens, lengths = get_and_plot_density(particles, radii, rotation, center)\n\nparticles = create_sphere2(radii, lengths, mass=1)\nprint(len(particles))\n\nrot = make_rotation_matrix(np.pi/2)\n\ncm = Vector2d()\nfor particle in particles:\n cm += particle.r\ncm = cm * (1/len(particles))\n\n# delta = 100\n# for particle in particles:\n# # particle.v = Vector2d(10 * np.random.sample(), 10 * np.random.sample())\n# r = particle.r - cm\n# r = np.dot(rot, [r.x, r.y])\n# x = np.random.sample() * 2 * delta + (r[0] - delta)\n# y = np.random.sample() * 2 * delta + (r[1] - delta)\n# particle.v = Vector2d(x, y) * 1\n#####\n# for i, particle in enumerate(particles):\n# brute_force = Vector2d(0, 0)\n# for particle2 in particles:\n# if particle != particle2:\n# brute_force += forces.base_force(particle, particle2)\n#\n# r = particle.r - cm\n# r = np.dot(rot, [r.x, r.y])\n# r = Vector2d(r[0], r[1])\n# tmp_v = r * (1/abs(r)) * abs((r.dot(brute_force)/abs(r)))\n# particle.v = tmp_v * 0.1\n########\n# Nice!\nfor i, particle in enumerate(particles):\n print(i)\n brute_force = Vector2d(0, 0)\n for particle2 in particles:\n if particle != particle2:\n brute_force += forces.base_force(particle, particle2)\n\n r = particle.r - cm\n r = np.dot(rot, [r.x, r.y])\n r = Vector2d(r[0], r[1])\n # tmp_v = r * (1/abs(r)) * np.sqrt(abs((r.dot(brute_force)))/particle.mass)\n tmp_v = r * (1/abs(r)) * np.sqrt(abs(brute_force) * abs(r)/particle.mass)\n angle_a = np.pi/24\n angle_b = np.pi/12\n # particle.v = tmp_v.rotate(np.random.sample() * 2 * angle - angle)\n particle.v = tmp_v.rotate(np.random.sample() * angle_b + (angle_b - angle_a))\n########\n# for i, particle in enumerate(particles):\n# brute_force = Vector2d(0, 0)\n# for particle2 in particles:\n# if particle != particle2:\n# brute_force += forces.base_force(particle, particle2)\n#\n# r = particle.r - cm\n# tmp_v = r * (1/abs(r)) * abs((r.dot(brute_force)/abs(r)))\n# particle.v = tmp_v * 0.1\n######\n\n\ntmp_v = Vector2d()\nfor particle in particles:\n tmp_v += particle.v\ntmp_v = tmp_v * (1/len(particles))\n\nfor particle in particles:\n particle.v -= tmp_v\n\nsave_path = os.path.dirname(os.path.realpath(__file__)) + '/test_velocity'\nif not os.path.exists(save_path):\n os.makedirs(save_path)\n\nfor step in range(constants.steps_number):\n print(step)\n\n with open(save_path + '/results_' + str(step) + '.xyz', 'w') as outfile:\n outfile.write(str(len(particles)) + '\\n\\n')\n for i, particle in enumerate(particles):\n outfile.write(str(particle.r) + ' ' +\n str(particle.v) + '\\n')\n\n for i, particle in enumerate(particles):\n brute_force = Vector2d(0, 0)\n for particle2 in particles:\n if particle != particle2:\n brute_force += forces.base_force(particle, particle2)\n\n particle.force = brute_force\n\n for particle in particles:\n particle.v += particle.force * constants.dt\n particle.r += particle.v * constants.dt\n\n\n","sub_path":"diplom2.py","file_name":"diplom2.py","file_ext":"py","file_size_in_byte":9900,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"618150146","text":"\"\"\"Jump to github repos at light speed!\"\"\"\nimport time\n\nimport json\nimport os\nfrom albertv0 import *\nfrom difflib import SequenceMatcher as SM\nfrom github import Github\nfrom os import path\nfrom pathlib import Path\n\n__iid__ = \"PythonInterface/v0.1\"\n__prettyname__ = \"Github Jump\"\n__version__ = \"0.1\"\n__trigger__ = \"gj\"\n__author__ = \"Bharat kalluri\"\n__dependencies__ = [\"pygithub\", \"boltons\"]\n\nicon_path = \"{}/icons/{}.png\".format(path.dirname(__file__), \"repo\")\nCONFIG_PATH = os.path.join(configLocation(), 'gh_token')\nCACHE_PATH = os.path.join(dataLocation(), 'gh_cache')\n\n\ndef get_token():\n gh_token_file = Path(CONFIG_PATH)\n if gh_token_file.is_file():\n return gh_token_file.read_text().strip()\n else:\n raise FileNotFoundError\n\n\ndef save_token(github_token: str):\n with open(CONFIG_PATH, 'w') as f:\n f.write(github_token)\n\n\ndef get_repos(github_token, cache_override: bool = False):\n gh_cache_file = Path(CACHE_PATH)\n if cache_override is False and gh_cache_file.is_file():\n print(\"Getting from cache\")\n repo_list = json.loads(gh_cache_file.read_text())\n else:\n print(\"Cache empty, getting repos\")\n repo_list = []\n g = Github(github_token)\n user_data = g.get_user()\n starred = user_data.get_starred()\n personal_repos = user_data.get_repos()\n for repo in personal_repos:\n repo_list.append(repo)\n for repo in starred:\n repo_list.append(repo)\n repo_list = [{\n 'name': repo.name,\n 'description': repo.description,\n 'html_url': repo.html_url\n } for repo in repo_list]\n gh_cache_file.write_text(json.dumps(repo_list))\n return repo_list\n\n\ndef list_safe_get(arr: list, position: int):\n try:\n return arr[position]\n except IndexError:\n return None\n\n\ndef handleQuery(query):\n results = []\n\n if query.isTriggered and query.string.strip():\n\n # avoid rate limiting\n time.sleep(0.3)\n if not query.isValid:\n return\n\n input_query = query.string.strip()\n input_query_arr = input_query.split(\" \")\n\n item = Item(\n id=__prettyname__,\n icon=icon_path,\n completion=query.rawString,\n text=__prettyname__,\n actions=[]\n )\n\n if list_safe_get(input_query_arr, 0) == \"token\":\n gh_token = list_safe_get(input_query_arr, 1)\n return Item(\n id=__prettyname__,\n icon=icon_path,\n text=\"Save token?\",\n subtext=f\"Github token: {gh_token} will be saved on enter\",\n actions=[FuncAction(text=\"Save token\",\n callable=lambda: save_token(gh_token))]\n )\n\n # Require a token to start\n try:\n github_token = get_token()\n except FileNotFoundError:\n return Item(\n id=__prettyname__,\n icon=icon_path,\n text=\"Token needed\",\n subtext=\"Please give a token by giving gj token [your token]\")\n\n if list_safe_get(input_query_arr, 0) == 'cache' and list_safe_get(input_query_arr, 1) == 'refresh':\n print(\"Force refresh cache\")\n return Item(\n id=__prettyname__,\n icon=icon_path,\n text=\"Refresh cache?\",\n subtext=\"Cache will be refreshed on enter\",\n actions=[FuncAction(text=\"Refresh cache\",\n callable=lambda: get_repos(github_token, cache_override=True))]\n )\n\n if len(query.string) >= 1:\n repo_list = get_repos(github_token)\n match_list = []\n cleaned_query = str(input_query).replace('#', '').replace('!', '')\n for repo in repo_list:\n match_list.append([repo, SM(\n lambda x: x in [\" \", \"-\"],\n cleaned_query, repo['name'].lower()).ratio()\n ])\n match_list.sort(key=lambda x: x[1], reverse=True)\n for repo, ratio in match_list:\n repo_url = repo['html_url']\n if \"!\" in str(input_query):\n repo_url = repo_url + \"/issues\"\n elif \"#\" in str(input_query):\n repo_url = repo_url + \"/pulls\"\n results.append(Item(\n id=__prettyname__,\n icon=icon_path,\n text=repo['name'],\n subtext=repo['description'] if repo['description'] else \"\",\n actions=[UrlAction(\"Open in Github\", repo_url)])\n )\n else:\n item.subtext = \"Jump to repo in Github! Enter more than 2 Characters to begin search.\"\n return item\n return results\n","sub_path":"__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":4874,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"518621223","text":"# Definition for a binary tree node.\n# class TreeNode(object):\n# def __init__(self, x):\n# self.val = x\n# self.left = None\n# self.right = None\n\nclass Solution(object):\n def delNodes(self, root, to_delete):\n \"\"\"\n :type root: TreeNode\n :type to_delete: List[int]\n :rtype: List[TreeNode]\n \"\"\"\n\n to_delete_set = set(to_delete)\n res = []\n def dfs(root, is_root):\n if not root: return None\n deleted = root.val in to_delete_set\n if is_root and not deleted:\n res.append(root)\n root.left = dfs(root.left, deleted)\n root.right = dfs(root.right, deleted)\n return None if deleted else root\n dfs(root, True)\n return res\n","sub_path":"Leetcode/tree/1110_DeleteNodesAndReturnForest/Solution.py","file_name":"Solution.py","file_ext":"py","file_size_in_byte":788,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"42304472","text":"from sklearn import metrics\nimport torch\nimport numpy as np\nimport torch.nn.functional as F\n\ndef accuracy(logits, target):\n '''\n logits: N,C\n target: N,C\n '''\n thresholds = [0.05, 0.1, 0.15, 0.2, 0.3, 0.4, 0.5, 0.6]\n results = []\n target = target.byte()\n #pred = pred.topk(3, )\n for t in thresholds:\n pred = (torch.sigmoid(logits) > t).byte()\n corrects = (pred.eq(target) * target).sum().item()\n incorrects = (pred.ne(target) * (target.eq(0))).sum().item()\n results.append((corrects, incorrects, round(corrects/(incorrects+1),3), t, target.sum().item()))\n return results\n\ndef accuracy_th(logits, target, thresholds):\n '''\n logits: N,C\n target: N,C\n '''\n #thresholds = [0.05, 0.1, 0.15, 0.2, 0.3, 0.4, 0.5, 0.6]\n results = []\n target = target.byte()\n #pred = pred.topk(3, )\n #for t in thresholds:\n pred = (torch.sigmoid(logits) > thresholds).byte()\n corrects = (pred.eq(target) * target).sum().item()\n incorrects = (pred.ne(target) * (target.eq(0))).sum().item()\n results.append((corrects, incorrects, round(corrects/(incorrects+1),3), 'optimized'))\n \n return results\n\ndef find_fix_threshold(preds, targets):\n #print('>>>', logits.size(), targets.size())\n assert preds.size() == targets.size()\n\n best_t = 0.01\n best_score = 0.\n for t in range(1, 100):\n cur_th = t/100.\n preds_t = (preds > cur_th).float()\n score = f2_score(targets, preds_t)\n if score > best_score:\n best_score = score\n best_t = cur_th\n #print(thresholds)\n return best_t\n\n\ndef find_threshold(logits, targets):\n #print('>>>', logits.size(), targets.size())\n N_CLASSESS = logits.size(1)\n assert logits.size() == targets.size()\n\n thresholds = [0.15]*N_CLASSESS\n outputs = torch.sigmoid(logits)\n for i in range(N_CLASSESS):\n best_t = 0.15\n best_score = f2_score(targets, outputs, threshold=torch.Tensor(thresholds).cuda())\n for t in range(99):\n cur_th = t/100.+0.001\n thresholds[i] = cur_th\n score = f2_score(targets, outputs, threshold=torch.Tensor(thresholds).cuda())\n if score > best_score:\n best_score = score\n best_t = cur_th\n thresholds[i] = best_t\n #print(thresholds)\n return thresholds\n\ndef topk_accuracy(output, label, topk=(1,100)):\n maxk = max(topk)\n\n _, pred = output.topk(maxk, 1, True, True)\n pred = pred.t()\n correct = pred.eq(label.view(1, -1).expand_as(pred))\n\n res = []\n for k in topk:\n correct_k = correct[:k].view(-1).sum().item()\n res.append(correct_k)\n return res\n\ndef f2_scores(logits, target):\n thresholds = [0.05, 0.1, 0.15, 0.2, 0.3, 0.4, 0.5, 0.6]\n preds = torch.sigmoid(logits)\n results = []\n for t in thresholds:\n preds_t = (preds > t).float()\n score = round(f2_score(target, preds_t).item(), 4)\n results.append((t, score))\n return results\n\ndef f2_score(y_true, y_pred):\n return fbeta_score(y_true, y_pred, 2)\n\n\ndef fbeta_score(y_true, y_pred, beta, eps=1e-9):\n beta2 = beta**2\n\n #y_pred = torch.ge(y_pred.float(), threshold).float()\n y_pred = y_pred.float()\n y_true = y_true.float()\n\n true_positive = (y_pred * y_true).sum(dim=1)\n precision = true_positive.div(y_pred.sum(dim=1).add(eps))\n recall = true_positive.div(y_true.sum(dim=1).add(eps))\n\n return torch.mean(\n (precision*recall).\n div(precision.mul(beta2) + recall + eps).\n mul(1 + beta2))\n\ndef test_f2():\n y_pred = np.array([[0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 1, 0, 1, 0, 0, 1, 0],\n [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0],\n [1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1],\n [0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0],\n [0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0]])\n\n y_true = np.array([[0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 1, 0, 1, 0, 0, 1, 0],\n [1, 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0],\n [1, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1],\n [0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0],\n [0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0]])\n\n py_pred = torch.from_numpy(y_pred)\n py_true = torch.from_numpy(y_true)\n\n fbeta_pytorch = f2_score(py_true, py_pred)\n #fbeta_sklearn = metrics.fbeta_score(y_true, y_pred, 2, average='samples')\n #print('Scores are {:.3f} (sklearn) and {:.3f} (pytorch)'.format(fbeta_sklearn, fbeta_pytorch))\n print(fbeta_pytorch.cuda().item())\n print('Scores are {:.3f}'.format(fbeta_pytorch))\n\ndef test_f2_2():\n y_pred = np.array([[1, 1, 1, 1, 1, 0, 0, 0, 1, 1, 1, 1, 0, 0, 1, 1, 0]])\n\n y_true = np.array([[0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 1, 0, 1, 0, 0, 1, 0]])\n\n py_pred = torch.from_numpy(y_pred)\n py_true = torch.from_numpy(y_true)\n\n fbeta_pytorch = f2_score(py_true, py_pred)\n #fbeta_sklearn = metrics.fbeta_score(y_true, y_pred, 2, average='samples')\n #print('Scores are {:.3f} (sklearn) and {:.3f} (pytorch)'.format(fbeta_sklearn, fbeta_pytorch))\n print(fbeta_pytorch.cuda().item())\n print('Scores are {:.3f}'.format(fbeta_pytorch))\n\nif __name__ == '__main__':\n test_f2_2()\n","sub_path":"metrics.py","file_name":"metrics.py","file_ext":"py","file_size_in_byte":5325,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"508990651","text":"import random\nimport re\nfrom analyzer import * \nfrom markov import *\nfrom itertools import chain # itertoolsモジュールからchainをインポート\n\nclass Responder:\n \"\"\" 応答クラスのスーパークラス\n \"\"\"\n def __init__(self, name, dictionary):\n \"\"\" Responderオブジェクトの名前をnameに格納\n\n @param name Responderオブジェクトの名前\n @param dictionary Dictionaryオブジェクト\n \"\"\"\n self.name = name\n self.dictionary = dictionary\n\n def response(self, input, mood, parts):\n \"\"\" オーバーライドを前提としたresponse()メソッド\n\n @param input 入力された文字列\n @param mood 機嫌値\n 戻り値 空の文字列\n \"\"\"\n return ''\n\n def get_name(self):\n \"\"\" 応答オブジェクトの名前を返す\n \"\"\"\n return self.name\n\nclass RepeatResponder(Responder):\n \"\"\" オウム返しのための行うサブクラス\n \"\"\"\n def response(self, input, mood, parts):\n \"\"\" 応答文字列を作って返す\n\n @param input 入力された文字列\n @param mood 機嫌値\n \"\"\"\n return '{}ってなに?'.format(input)\n\nclass RandomResponder(Responder):\n \"\"\" ランダムな応答のための行うサブクラス\n \"\"\"\n def response(self, input, mood, parts):\n \"\"\" 応答文字列を作って返す\n\n @param input 入力された文字列\n 戻り値 リストからランダムに抽出した文字列\n \"\"\"\n return random.choice(self.dictionary.random)\n\nclass PatternResponder(Responder):\n \"\"\" パターンに反応するためのサブクラス\n \"\"\"\n def response(self, input, mood, parts):\n \"\"\" パターンにマッチした場合に応答文字列を作って返す\n\n @param input 入力された文字列\n \"\"\"\n self.resp = None\n for ptn_item in self.dictionary.pattern:\n # match()でインプット文字列にパターンマッチを行う\n m = ptn_item.match(input)\n # マッチした場合は機嫌値moodを引数にしてchoice()を実行、\n # 戻り値の応答文字列、またはNoneを取得\n if (m):\n self.resp = ptn_item.choice(mood)\n # choice()の戻り値がNoneでない場合は\n # 応答例の中の%match%をインプットされた文字列内の\n # マッチした文字列に置き換える\n if self.resp != None:\n return re.sub('%match%', m.group(), self.resp)\n # パターンマッチしない場合はランダム辞書から返す\n return random.choice(self.dictionary.random)\n\nclass TemplateResponder(Responder):\n \"\"\" テンプレートを利用して応答を生成するためのサブクラス\n \"\"\"\n def response(self, input, mood, parts):\n \"\"\" パターンに反応するためのサブクラス\n @param input インプット文字列\n @param parts インプット文字列の形態素解析結果\n @param mood アップデート後の機嫌値\n \"\"\"\n # インプット文字列の名詞の部分のみを格納するリスト\n keywords = []\n template = ''\n # 解析結果partsの「文字列」→word、「品詞情報」→partに順次格納\n for word, part in parts:\n # 名詞であるかをチェックしてkeywordsリストに格納\n if (keyword_check(part)):\n keywords.append(word)\n # keywordsリストに格納された名詞の数を取得\n count = len(keywords)\n # keywordsリストに1つ以上の名詞が存在し、\n # 名詞の数に対応するテンプレートが存在するかをチェック\n if (count > 0) and (str(count) in self.dictionary.template):\n # テンプレートリストから名詞の数に対応するテンプレートを\n # ランダムに抽出\n template = random.choice(self.dictionary.template[str(count)])\n \n for word in keywords:\n template = template.replace('%noun%', word, 1)\n\n return template\n return random.choice(self.dictionary.random)\n \nclass MarcovResponder(Responder):\n \"\"\" マルコフ連鎖を利用して応答を生成するためのサブクラス\n \n \"\"\"\n def response(self, input, mood, parts):\n m = [] #\n # 解析結果の形態素と品詞に対して反復処理\n for word, part in parts:\n #print('word===',word)\n #print('part===',part)\n \n # インプット文字列に名詞があればそれを含むマルコフ連鎖文を検索\n if keyword_check(part):\n # マルコフ連鎖で生成した文章を1つずつ処理\n for sentence in self.dictionary.sentences:\n # 形態素の文字列がマルコフ連鎖の文章に含まれているか検索する\n # 最後を'.*?'にすると検索文字列だけにもマッチするので\n # + '.*'として検索文字列だけにマッチしないようにする\n find = '.*?' + word + '.*'\n # マルコフ連鎖文にマッチさせる\n tmp = re.findall(find, sentence)\n if tmp:\n # マッチする文章があればリストmに追加\n m.append(tmp)\n # findall()はリストを返してくるので多重リストをフラットにする\n m = list(chain.from_iterable(m))\n # 集合に変換して重複した文章を取り除く\n check = set(m)\n # 再度、リストに戻す\n m = list(check)\n \n if m:\n # インプット文字列の名詞にマッチしたマルコフ連鎖文からランダムに選択\n return(random.choice(m))\n\n # マッチするマルコフ連鎖文がない場合\n return random.choice(self.dictionary.random)\n\n \n\n\n \n\n","sub_path":"normal/PythonAI/chap08/sec03/Ptna/responder.py","file_name":"responder.py","file_ext":"py","file_size_in_byte":6250,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"209879612","text":"# Estimating DSGE by Maximum Likelihood in Python by PyTorch\n# Author: Michal Miktus\n# Date: 20.03.2019\n\n# Useful to debug: with torch.autograd.set_detect_anomaly(True):\n\n# Import libraries\n\nimport matplotlib.pyplot as plt\nimport seaborn as sn\n\nimport numpy as np\nimport pandas as pd\nimport torch\nfrom pandas_datareader.data import DataReader\nfrom torch import tensor, zeros, mm, randn, normal, cat, squeeze, unsqueeze\nfrom Solution_function_PyTorch import Solution\n\n\n# %matplotlib inline\n\n# Set printing options\n\nnp.set_printoptions(precision=3, suppress=True, linewidth=120)\ntorch.set_printoptions(precision=3, linewidth=120)\npd.set_option('float_format', lambda x: '%.3g' % x, )\n\n# --------------------------------------------------------------------------\n# -- Define the model\n# --------------------------------------------------------------------------\n\n# VARIABLES [M,3] cell array: Variable name (case sensitive) ~ Variable type ~ Description\n# Variable type: 'X' ... Endogenous state variable\n# 'Y' ... Endogenous other (jump) variable\n# 'Z' ... Exogenous state variable\n# 'U' ... Innovation to exogenous state variable\n# '' ... Skip variable\n\nvariable_symbols = [r'$e_a$', r'$e_I$', r'$e_b$', r'$e_L$',\n r'$e_G$', r'$e_pi$', r'$pi$', r'$w$', r'$K$',\n r'$Q$', r'$I$', r'$C$', r'$R$', r'$r$', r'$L$',\n r'$Y$', r'$pi_f$', r'$w_f$', r'$K_f$', r'$Q_f$',\n r'$I_f$', r'$C_f$', r'$R_f$', r'$r_f$', r'$L_f$',\n r'$Y_f$', r'$ee_a$', r'$ee_I$', r'$ee_b$', r'$ee_L$', r'$ee_G$', r'$ee_pi$', r'$n_p$', r'$n_Q$', r'$n_R$', r'$n_w$', r'$one$']\n\nvariable_types = ['Z', 'Z', 'Z', 'Z', 'Z', 'Z',\n 'X', 'X', 'X', 'X', 'X', 'X',\n 'X', 'Y', 'Y', 'X', 'X', 'X',\n 'X', 'X', 'X', 'X', 'X', 'Y',\n 'Y', 'X', 'U', 'U', 'U', 'U',\n 'U', 'U', 'Z', 'Z', 'Z', 'Z',\n 'X', ]\n\nvariable_names = ['Aggregate productivity shock', 'Adjustment cost shock',\n 'Preference shock', 'Labor supply shock',\n 'Public spending shock', 'Inflation target', 'Inflation rate', 'Real wages', 'Capital', 'Q-Tobin ratio', 'Investment',\n 'Consumption', 'Monetary policy interest rate', 'Capital rental rate', 'Labor', 'Output',\n 'Flexible inflation rate', 'Flexible wages', 'Flexible capital', 'Flexible Q-Tobin ratio',\n 'Flexible investment', 'Flexible consumption', 'Flexible monetary policy interest rate',\n 'Flexible capital rental rate', 'Flexible labor', 'Flexible output', 'Aggregate productivity shock error',\n 'Adjustment cost shock error', 'Preference shock error', 'Labor supply shock error', 'Public spending shock error',\n 'Inflation target error', 'Prices error', 'Tobin Q-ratio error', 'Monetary policy interest rate error', 'Wages error',\n 'Temporary variable']\n\n\nvariables = pd.DataFrame({\n 'names': variable_names,\n 'types': variable_types,\n 'symbols': variable_symbols\n })\n\nvar_endo_states = variables.loc[variables['types'] == 'X']\nvar_endo_controls = variables.loc[variables['types'] == 'Y']\nvar_exo = variables.loc[variables['types'] == 'Z']\n\n# EQUATIONS [N,3] cell array: Equation type ~ Equation name ~ equation\n# Equation type: 'D' ... Deterministic equation\n# 'E' ... Expectational equation\n# 'S' ... Shock equation\n# '' ... Skip equation\n\nequation_formulas = [\n '0 = - C(t) + (h/(1 + h))*C(t-1) + (1/(1 + h))*C(t+1) - ((1 - h)/((1 + h)*sigma_c))*(R(t) - pi(t+1)) + ((1 - h)/((1 + h)*sigma_c))*(e_b(t)-e_b(t+1))',\n '0 = - I(t) + (1/(1 + betta))*I(t-1) + (betta/(1 + betta))*I(t+1) + (adj/(1 + betta))*Q(t) + (betta*e_I(t+1) - e_I(t))/(1 + betta)',\n '0 = - Q(t) -R(t) + pi(t+1) + ((1 - tau)/(1 - tau + r_k))*Q(t+1) + (r_k/(1 - tau + r_k))*r(t+1) + n_Q(t)',\n '0 = - K(t) + (1 - tau)*K(t-1) + tau*I(t-1)', '0 = - pi(t) + (betta/(1 + betta*gamma_p))*pi(t+1) + (gamma_p/(1 + betta*gamma_p))*pi(t-1) + (((1 - betta*xi_p)*(1 - xi_p))/((1 + betta*gamma_p)*xi_p))*(alphaa*r(t) + (1 - alphaa)*w(t) - e_a(t) + n_p(t))',\n '0 = (-1 - ((1/(1 + betta))*((1 - betta*xi_w)*(1 - xi_w))/((1 + (1/lambda_w)*((1 + lambda_w)*sigma_L))*xi_w)))*w(t) + (betta/(1 + betta))*w(t+1) + (1/(1 + betta))*w(t-1)+ (betta/(1 + betta))*pi(t+1) - ((1 + betta*gamma_w)/(1 + betta))*pi(t) + (gamma_w/( 1 + betta))*pi(t-1) - ((1/(1 + betta))*((1 - betta*xi_w)*(1 - xi_w))/((1 + (1/lambda_w)*((1 + lambda_w)*sigma_L))*xi_w))*(- sigma_L*L(t) - (sigma_c/(1 - h))*(C(t) - h*C(t-1)) - e_L(t) - n_w(t))', '0 = - L(t) + -w(t) + (1 + psi)*r(t) + K(t-1)',\n '0 = - Y(t) + phi*e_a(t) + phi*alphaa*K(t-1) + phi*alphaa*psi*r(t) + phi*(1 - alphaa)*L(t)',\n '0 = - Y(t) + (1 - tau*k - g)*C(t) + tau*k*I(t) + e_G(t)',\n '0 = - R(t) + rho*R(t-1) + ((1 - rho)*r_pi - r_dpi)*pi(t-1) + (1 - rho)*(1 - r_pi)*e_pi(t) + Y(t)*((1-rho)*r_Y+r_dY) - Y_f(t)*((1-rho)*r_Y+r_dY) + r_dpi*pi(t) - r_dY*Y(t-1) - r_dY*Y_f(t-1) + n_R(t)',\n '0 = - C_f(t) + (h/(1 + h))*C_f(t-1) + (1/(1 + h))*C_f(t+1) - ((1 - h)/((1 + h)*sigma_c))*(R_f(t) - pi_f(t+1)) + ((1 - h)/((1 + h)*sigma_c))*(e_b(t)-e_b(t+1))',\n '0 = - I_f(t) + (1/(1 + betta))*I_f(t-1) + (betta/(1 + betta))*I_f(t+1) + (adj/(1 + betta))*Q_f(t) + (betta*e_I(t+1) - e_I(t))/(1 + betta)',\n '0 = - Q_f(t) - R_f(t) + pi_f(t+1) + ((1 - tau)/(1 - tau + r_k))*Q_f(t+1) + (r_k/(1 - tau + r_k))*r_f(t+1)',\n '0 = - K_f(t) + (1 - tau)*K_f(t-1) + tau*I_f(t-1)',\n '0 = alphaa*r_f(t)+(1-alphaa)*w_f(t) - e_a(t)',\n '0 = - w_f(t) + sigma_L*L_f(t) + (sigma_c/(1 - h))*(C_f(t) - h*C_f(t-1)) - e_L(t)',\n '0 = - L_f(t) + -w_f(t) + (1 + psi)*r_f(t) + K_f(t-1)',\n '0 = - Y_f(t) + phi*e_a(t) + phi*alphaa*K_f(t-1) + phi*alphaa*psi*r_f(t) + phi*(1 - alphaa)*L_f(t)',\n '0 = - Y_f(t) + (1 - tau*k - g)*C_f(t) + tau*k*I_f(t) + e_G(t)',\n 'e_I(t+1) = rho_I*e_I(t) + ee_I(t+1)',\n 'e_b(t+1) = rho_b*e_b(t) + ee_b(t+1)',\n 'e_L(t+1) = rho_L*e_L(t) + ee_L(t+1)',\n 'e_G(t+1) = rho_G*e_G(t) + ee_G(t+1)',\n 'e_a(t+1) = rho_a*e_a(t) + ee_a(t+1)',\n 'e_pi(t+1) = rho_pi*e_pi(t)+ ee_pi(t+1)',\n 'pi_f(t) = 0*one(t)',\n 'one(t) = 0*one(t-1)',\n 'n_p(t) = 0',\n 'n_Q(t) = 0',\n 'n_R(t) = 0',\n 'n_w(t) = 0'\n ]\n\nequation_type = ['E', 'E', 'E', 'E', 'E', 'E',\n 'D', 'D', 'E', 'E', 'E', 'E',\n 'E', 'E', 'E', 'E', 'D', 'D',\n 'E', 'S', 'S', 'S', 'S', 'S',\n 'S', 'E', 'E', 'S', 'S', 'S',\n 'S']\n\nequation_names = ['Consumption', 'Investment', 'Q-equation', 'Capital', 'Prices', 'Wages', 'Labor demand', 'Production',\n 'Goods market', 'Monetary policy', 'Flexible Consumption', 'Flexible Investment', 'Flexible Q-equation',\n 'Flexible Capital', 'Flexible Prices', 'Flexible Wages', 'Flexible Labor demand', 'Flexible Production',\n 'Flexible Goods market', 'Aggregate productivity shock', 'Adjustment cost shock',\n 'Preference shock', 'Labor supply shock', 'Public spending shock', 'Inflation target', 'Temporary first equation', 'Temporary second equation', 'Prices error expectation', 'Tobin Q-ratio error expectation',\n 'Monetary policy interest rate error expectation', 'Wages error expectation']\n\nequations = pd.DataFrame({\n 'names': equation_names,\n 'types': equation_type,\n 'formulas': equation_formulas\n })\n\n# --------------------------------------------------------------------------\n# --- Setting parameters\n# --------------------------------------------------------------------------\n\nbetta = tensor(0.99, requires_grad = True)\ntau = tensor(0.025, requires_grad = True)\nalphaa = tensor(0.3, requires_grad = True)\npsi = tensor(1/0.169, requires_grad = True)\ngamma_p = tensor(0.469, requires_grad = True)\ngamma_w = tensor(0.763, requires_grad = True)\nlambda_w = tensor(0.5, requires_grad = True)\nxi_p = tensor(0.908, requires_grad = True)\nxi_w = tensor(0.737, requires_grad = True)\nsigma_L = tensor(2.4, requires_grad = True)\nsigma_c = tensor(1.353, requires_grad = True)\nh = tensor(0.573, requires_grad = True)\nphi = tensor(1.408, requires_grad = True)\nadj = tensor(1/6.771, requires_grad = True)\nr_k = (1/betta)-1+tau\nk = tensor(8.8, requires_grad = True)\ng = tensor(0.18, requires_grad = True)\nr_dpi = tensor(0.14, requires_grad = True)\nr_Y = tensor(0.099, requires_grad = True)\nr_dY = tensor(0.159, requires_grad = True)\nrho = tensor(0.961, requires_grad = True)\nr_pi = tensor(1.684, requires_grad = True)\n\nrho_L = tensor(0.889, requires_grad = True)\nrho_a = tensor(0.823, requires_grad = True)\nrho_b = tensor(0.855, requires_grad = True)\nrho_G = tensor(0.949, requires_grad = True)\nrho_pi = tensor(0.924, requires_grad = True)\nrho_I = tensor(0.927, requires_grad = True)\n\nsd_R = tensor(0.081, requires_grad = True)\nsd_p = tensor(0.16, requires_grad = True)\nsd_w = tensor(0.289, requires_grad = True)\nsd_Q = tensor(0.604, requires_grad = True)\n\n# --------------------------------------------------------------------------\n# --- Solution\n# --------------------------------------------------------------------------\n\nF, Q, nx, ny, nz = Solution(betta = betta, tau = tau, alphaa = alphaa, psi = psi, gamma_p = gamma_p,\n gamma_w = gamma_w, lambda_w = lambda_w, xi_p = xi_p, xi_w = xi_w, sigma_L = sigma_L,\n sigma_c = sigma_c, h = h, phi = phi, adj = adj, k = k, g = g, r_dpi = r_dpi, r_Y = r_Y,\n r_dY = r_dY, rho = rho, r_pi = r_pi, rho_L = rho_L, rho_a = rho_a, rho_b = rho_b, rho_G = rho_G,\n rho_pi = rho_pi, rho_I = rho_I, sd_R = sd_R, sd_p = sd_p, sd_w = sd_w, sd_Q = sd_Q)\n\n# --------------------------------------------------------------------------\n# --- Simulation\n# --------------------------------------------------------------------------\n\nT = 1000 # Number of periods to simulate\n\nepsilon = tensor([normal(mean = 0, std = sd_Q), normal(mean = 0, std = sd_p), normal(mean = 0, std = sd_w),\n normal(mean = 0, std = sd_R)])\nepsilon = cat((randn(6), epsilon))\nepsilon = cat((zeros((nx+ny)), epsilon))\n\nX_sim = zeros((nx+ny+nz, T))\nX_sim[:, 0] = squeeze(mm(Q, torch.t(unsqueeze(epsilon, 0))))\n\nfor t in range(1, T):\n epsilon = tensor([normal(mean=0, std=sd_Q),\n normal(mean=0, std=sd_p), normal(mean=0, std=sd_w),\n normal(mean=0, std=sd_R)])\n epsilon = cat((randn(6), epsilon))\n epsilon = cat((zeros((nx + ny)), epsilon))\n X_sim[:, t] = squeeze(mm(F, torch.t(unsqueeze(X_sim[:, t-1].clone(), 0))) + mm(Q, torch.t(unsqueeze(epsilon, 0))))\n\n# Plot for consumption\n\n# plt.plot(X_sim[11,:].detach().numpy())\n# plt.show()\n\n\n# --------------------------------------------------------------------------\n# --- Estimation on real data (TO BE DONE)\n# --------------------------------------------------------------------------\n# Get some data\n# start='1984-01'\n# end = '2015-01'\n# labor = DataReader('HOANBS', 'fred', start=start, end=end) # hours\n# consumption = DataReader('PCECC96', 'fred', start=start, end=end) # billions of dollars\n# investment = DataReader('GPDI', 'fred', start=start, end=end) # billions of dollars\n# population = DataReader('CNP16OV', 'fred', start=start, end=end) # thousands of persons\n# recessions = DataReader('USRECQ', 'fred', start=start, end=end)\n#\n# # Collect the raw values\n# raw = pd.concat((labor, consumption, investment, population.resample('QS').mean()), axis=1)\n# raw.columns = ['labor', 'consumption', 'investment', 'population']\n# raw['output'] = raw['consumption'] + raw['investment']\n#\n# # Make the data consistent with the model\n# y = np.log(raw.output * 10**(9-3) / raw.population)\n# n = np.log(raw.labor * (1e3 * 40) / raw.population)\n# c = np.log(raw.consumption * 10**(9-3) / raw.population)\n#\n# # Make the data stationary\n# y = y.diff()[1:]\n# n = n.diff()[1:]\n# c = c.diff()[1:]\n#\n# # Construct the final dataset\n# econ_observed = pd.concat((y, n, c), axis=1)\n# econ_observed.columns = ['output','labor','consumption']\n#\n# fig, ax = plt.subplots(figsize=(13,4))\n#\n# dates = econ_observed.index._mpl_repr()\n#\n# ax.plot(dates, econ_observed.output, label='Output')\n# ax.plot(dates, econ_observed.labor, label='Labor')\n# ax.plot(dates, econ_observed.consumption, label='Consumption')\n#\n# rec = recessions.resample('QS').last().loc[econ_observed.index[0]:].iloc[:, 0].values\n# ylim = ax.get_ylim()\n# ax.fill_between(dates, ylim[0]+1e-5, ylim[1]-1e-5, rec, facecolor='k', alpha=0.1)\n#\n# ax.xaxis.grid()\n# ax.legend(loc='lower left')\n# plt.show()\n\n# --------------------------------------------------------------------------\n# --- Estimation\n# --------------------------------------------------------------------------\n\n# Observables: labor, consumption, investment\n# Indexes: 14, 11, 10\n\nno = 3 # Number of observables\n\nobservation_matrix = tensor([\n [0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 1., 0., 0., 0., 0., 0.,\n 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.],\n [0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 1., 0., 0., 0., 0.,\n 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.],\n [0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 1., 0.,\n 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.]], requires_grad = True)\n\n# observation_matrix = zeros((no, nx+ny+nz), requires_grad=True)\n# observation_matrix[0,10] = observation_matrix[1,11] = observation_matrix[2,14] = 1\n\nobservables = X_sim[(10,11,14), :]\n\n# Optimization\n\nfrom Loss_function_PyTorch import loss_function\n\npar = torch.rand(1, requires_grad=True)\nlearning_rate = 1e-5\nn_iter = 50\n\noptimizer = torch.optim.SGD(params=[par], lr=learning_rate)\n\n# optimizer.zero_grad()\n# loss = loss_function(par, observation_matrix, observables, X_sim[:, 0])\n# print(loss)\n# loss.backward()\n# optimizer.step()\n\ndef closure():\n # Before the backward pass, use the optimizer object to zero all of the\n # gradients for the Tensors it will update (which are the learnable weights\n # of the model)\n optimizer.zero_grad()\n\n # Without a constant term in the likelihood function:\n\n loss_value = loss_function(par, observation_matrix, observables, X_sim[:, 0])\n\n # Backward pass: compute gradient of the loss with respect to model parameters\n\n loss_value.backward(retain_graph=True)\n\n return loss_value, par\n\n# Calling the step function on an Optimizer makes an update to its parameters\n\nloss_vector = torch.empty(n_iter)\npar_vector = torch.empty(n_iter)\n\nfor i in range(n_iter):\n print(i)\n optimizer.step(closure)\n loss_vector[i], par_vector[i] = closure()\n\nprint(par_vector)\n","sub_path":"DSGE_estimation/DSGE_solution_PyTorch.py","file_name":"DSGE_solution_PyTorch.py","file_ext":"py","file_size_in_byte":15069,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"617837952","text":"\"\"\"\n Supports parsing of Textual Model Output Statistics files\n\"\"\"\nimport re\nimport datetime\n\nimport pytz\nfrom pyiem.nws.product import TextProduct\n\nLATLON = re.compile(r\"LAT\\.\\.\\.LON\\s+((?:[0-9]{8}\\s+)+)\")\nDISCUSSIONNUM = re.compile(\n r\"MESOSCALE (?:PRECIPITATION )?DISCUSSION\\s+([0-9]+)\", re.IGNORECASE)\nATTN_WFO = re.compile(\n r\"ATTN\\.\\.\\.WFO\\.\\.\\.([\\.A-Z]*?)(?:LAT\\.\\.\\.LON|ATTN\\.\\.\\.RFC)\")\nATTN_RFC = re.compile(r\"ATTN\\.\\.\\.RFC\\.\\.\\.([\\.A-Z]*)\")\nWATCH_PROB = re.compile(\n r\"PROBABILITY OF WATCH ISSUANCE\\s?\\.\\.\\.\\s?([0-9]+) PERCENT\",\n re.IGNORECASE)\n\n\ndef section_parser(sect):\n \"\"\"Parse this section of text\"\"\"\n metadata = re.findall((r\"([A-Z0-9]{4})\\s+(...) (...) GUIDANCE\\s+\"\n r\"([01]?[0-9])/([0-3][0-9])/([0-9]{4})\\s+\"\n r\"([0-2][0-9]00) UTC\"), sect)\n (station, model, mos, month, day, year, hhmm) = metadata[0]\n if model == 'NBM':\n model = mos\n initts = datetime.datetime(int(year), int(month), int(day), int(hhmm[:2]))\n initts = initts.replace(tzinfo=pytz.utc)\n\n times = [initts, ]\n data = {}\n lines = sect.split(\"___\")\n hrs = lines[2].split()\n for hr in hrs[1:]:\n if hr == \"00\":\n ts = times[-1] + datetime.timedelta(days=1)\n ts = ts.replace(hour=0)\n else:\n ts = times[-1].replace(hour=int(hr))\n times.append(ts)\n data[ts] = {}\n\n for line in lines[3:]:\n if len(line) < 10:\n continue\n vname = line[:3].replace(\"/\", \"_\")\n if vname == \"X_N\":\n vname = \"N_X\"\n vals = re.findall(\"(...)\", line[4:])\n for i, val in enumerate(vals):\n if vname == \"T06\" and times[i+1].hour in [0, 6, 12, 18]:\n data[times[i+1]][\"T06_1\"] = vals[i-1].replace(\"/\", \"\").strip()\n data[times[i+1]][\"T06_2\"] = val.replace(\"/\", \"\").strip()\n elif vname == \"T06\":\n pass\n elif vname == \"T12\" and times[i+1].hour in [0, 12]:\n data[times[i+1]][\"T12_1\"] = vals[i-1].replace(\"/\", \"\").strip()\n data[times[i+1]][\"T12_2\"] = val.replace(\"/\", \"\").strip()\n elif vname == \"T12\":\n pass\n elif vname == \"WDR\":\n data[times[i+1]][vname] = int(vals[i].strip()) * 10\n else:\n data[times[i+1]][vname] = val.strip()\n return dict(station=station, model=model, data=data, initts=initts)\n\n\ndef make_null(val):\n \"\"\"Hmmm\"\"\"\n if val == \"\" or val is None:\n return None\n return val\n\n\nclass MOSProduct(TextProduct):\n \"\"\"\n Represents a Model Output Statistics file\n \"\"\"\n\n def __init__(self, text, utcnow=None, ugc_provider=None,\n nwsli_provider=None):\n \"\"\"constructor\"\"\"\n TextProduct.__init__(self, text, utcnow, ugc_provider,\n nwsli_provider)\n self.data = []\n self.parse_data()\n\n def sql(self, txn):\n \"\"\"Persist our data to the database\n\n Args:\n txn: Database cursor\n\n Returns:\n int number of inserts made to the database\n \"\"\"\n inserts = 0\n for sect in self.data:\n for ts in sect['data']:\n if ts == sect['initts']:\n continue\n # Account for 'empty' MOS products\n if not sect['data'][ts]:\n continue\n fst = \"\"\"\n INSERT into t%s (station, model, runtime, ftime,\n \"\"\" % (sect['initts'].year, )\n sst = \"VALUES(%s,%s,%s,%s,\"\n args = [sect['station'], sect['model'], sect['initts'], ts]\n for vname in sect['data'][ts].keys():\n # variables we don't wish to database\n if vname in ['FHR', ]:\n continue\n fst += \" %s,\" % (vname, )\n sst += \"%s,\"\n args.append(make_null(sect['data'][ts][vname]))\n if len(args) == 4:\n # No data was found\n continue\n sql = fst[:-1] + \") \" + sst[:-1] + \")\"\n txn.execute(sql, args)\n inserts += 1\n return inserts\n\n def parse_data(self):\n \"\"\"Parse out our data!\"\"\"\n raw = self.unixtext + \"\\n\"\n raw = raw.replace(\"\\n\", \"___\").replace(\"\\x1e\", \"\")\n sections = re.findall(r\"([A-Z0-9]{4}\\s+... ... GUIDANCE .*?)______\",\n raw)\n self.data = list(map(section_parser, sections))\n if not sections:\n raise Exception(\"Failed to split MOS Product\")\n\n\ndef parser(text, utcnow=None, ugc_provider=None, nwsli_provider=None):\n ''' Helper function '''\n return MOSProduct(text, utcnow, ugc_provider, nwsli_provider)\n","sub_path":"pyiem/nws/products/mos.py","file_name":"mos.py","file_ext":"py","file_size_in_byte":4825,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"487671717","text":"__author__ = 'sibirrer'\n\nimport numpy as np\nimport copy\n\nfrom lenstronomy.Sampling.sampler import Sampler\nfrom lenstronomy.Sampling.reinitialize import ReusePositionGenerator\nfrom lenstronomy.Sampling.parameters import Param\nimport lenstronomy.Util.class_creator as class_creator\nfrom lenstronomy.Sampling.likelihood import LikelihoodModule\n\n\nclass Fitting(object):\n \"\"\"\n class to find a good estimate of the parameter positions and uncertainties to run a (full) MCMC on\n \"\"\"\n\n def __init__(self, multi_band_list, kwargs_model, kwargs_constraints, kwargs_likelihood, kwargs_params):\n \"\"\"\n\n :return:\n \"\"\"\n self.multi_band_list = multi_band_list\n self.kwargs_model = kwargs_model\n self.kwargs_constraints = kwargs_constraints\n self.kwargs_likelihood = kwargs_likelihood\n\n if kwargs_model.get('lens_model_list', None) is not None:\n self._lens_init, self._lens_sigma, self._lens_fixed, self._lens_lower, self._lens_upper = kwargs_params['lens_model']\n else:\n self._lens_init, self._lens_sigma, self._lens_fixed, self._lens_lower, self._lens_upper = [], [], [], [], []\n if kwargs_model.get('source_light_model_list', None) is not None:\n self._source_init, self._source_sigma, self._source_fixed, self._source_lower, self._source_upper = kwargs_params['source_model']\n else:\n self._source_init, self._source_sigma, self._source_fixed, self._source_lower, self._source_upper = [], [], [], [], []\n if kwargs_model.get('lens_light_model_list', None) is not None:\n self._lens_light_init, self._lens_light_sigma, self._lens_light_fixed, self._lens_light_lower, self._lens_light_upper = kwargs_params['lens_light_model']\n else:\n self._lens_light_init, self._lens_light_sigma, self._lens_light_fixed, self._lens_light_lower, self._lens_light_upper = [], [], [], [], []\n if kwargs_model.get('point_source_model_list', None) is not None:\n self._ps_init, self._ps_sigma, self._ps_fixed, self._ps_lower, self._ps_upper = kwargs_params['point_source_model']\n else:\n self._ps_init, self._ps_sigma, self._ps_fixed, self._ps_lower, self._ps_upper = [], [], [], [], []\n if self.kwargs_likelihood.get('time_delay_likelihood', False) is True or self.kwargs_constraints.get('mass_scaling', False) is True:\n self._cosmo_init, self._cosmo_sigma, self._cosmo_fixed, self._cosmo_lower, self._cosmo_upper = kwargs_params['cosmography']\n else:\n self._cosmo_init, self._cosmo_sigma, self._cosmo_fixed, self._cosmo_lower, self._cosmo_upper = {}, {}, {}, {}, {}\n\n self._paramUpdate = ParamUpdate(self._lens_fixed, self._source_fixed, self._lens_light_fixed, self._ps_fixed, self._cosmo_fixed)\n\n def init_kwargs(self):\n return self._lens_init, self._source_init, self._lens_light_init, self._ps_init, self._cosmo_init\n\n def sigma_kwargs(self):\n return self._lens_sigma, self._source_sigma, self._lens_light_sigma, self._ps_sigma, self._cosmo_sigma\n\n def lower_kwargs(self):\n return self._lens_lower, self._source_lower, self._lens_light_lower, self._ps_lower, self._cosmo_lower\n\n def upper_kwargs(self):\n return self._lens_upper, self._source_upper, self._lens_light_upper, self._ps_upper, self._cosmo_upper\n\n def _run_pso(self, n_particles, n_iterations,\n kwargs_fixed_lens, kwargs_mean_lens, kwargs_sigma_lens,\n kwargs_fixed_source, kwargs_mean_source, kwargs_sigma_source,\n kwargs_fixed_lens_light, kwargs_mean_lens_light, kwargs_sigma_lens_light,\n kwargs_fixed_ps, kwargs_mean_ps, kwargs_sigma_ps,\n kwargs_fixed_cosmo, kwargs_mean_cosmo, kwargs_sigma_cosmo,\n threadCount=1, mpi=False, print_key='PSO', sigma_factor=1, compute_bool=None, fix_solver=False):\n\n # initialise mcmc classes\n param_class = Param(self.kwargs_model, self.kwargs_constraints, kwargs_fixed_lens, kwargs_fixed_source,\n kwargs_fixed_lens_light, kwargs_fixed_ps, kwargs_fixed_cosmo,\n self._lens_lower, self._source_lower, self._lens_light_lower, self._ps_lower,\n self._cosmo_lower,\n self._lens_upper, self._source_upper, self._lens_light_upper, self._ps_upper,\n self._cosmo_upper,\n kwargs_lens_init=kwargs_mean_lens, fix_lens_solver=fix_solver)\n init_pos = param_class.setParams(kwargs_mean_lens, kwargs_mean_source, kwargs_mean_lens_light, kwargs_mean_ps,\n kwargs_mean_cosmo)\n sigma_start = param_class.setParams(kwargs_sigma_lens, kwargs_sigma_source, kwargs_sigma_lens_light,\n kwargs_sigma_ps, kwargs_sigma_cosmo)\n lowerLimit = np.array(init_pos) - np.array(sigma_start)*sigma_factor\n upperLimit = np.array(init_pos) + np.array(sigma_start)*sigma_factor\n num_param, param_list = param_class.num_param()\n\n # initialize ImSim() class\n kwargs_likelihood = copy.deepcopy(self.kwargs_likelihood)\n if compute_bool is not None:\n kwargs_likelihood['bands_compute'] = compute_bool\n imSim_class = class_creator.create_multiband(self.multi_band_list, self.kwargs_model)\n likelihoodModule = LikelihoodModule(imSim_class=imSim_class, param_class=param_class, kwargs_likelihood=kwargs_likelihood)\n # run PSO\n mcmc_class = Sampler(likelihoodModule=likelihoodModule)\n result, chain = mcmc_class.pso(n_particles, n_iterations, lowerLimit, upperLimit, init_pos=init_pos,\n threadCount=threadCount, mpi=mpi, print_key=print_key)\n lens_result, source_result, lens_light_result, ps_result, cosmo_result = param_class.getParams(result,\n bijective=True)\n return lens_result, source_result, lens_light_result, ps_result, cosmo_result, chain, param_list\n\n def _mcmc_run(self, n_burn, n_run, walkerRatio,\n kwargs_fixed_lens, kwargs_mean_lens, kwargs_sigma_lens,\n kwargs_fixed_source, kwargs_mean_source, kwargs_sigma_source,\n kwargs_fixed_lens_light, kwargs_mean_lens_light, kwargs_sigma_lens_light,\n kwargs_fixed_ps, kwargs_mean_ps, kwargs_sigma_ps,\n kwargs_fixed_cosmo, kwargs_mean_cosmo, kwargs_sigma_cosmo,\n threadCount=1, mpi=False, init_samples=None, sigma_factor=1, compute_bool=None, fix_solver=False):\n\n param_class = Param(self.kwargs_model, self.kwargs_constraints, kwargs_fixed_lens, kwargs_fixed_source,\n kwargs_fixed_lens_light, kwargs_fixed_ps, kwargs_fixed_cosmo,\n self._lens_lower, self._source_lower, self._lens_light_lower, self._ps_lower,\n self._cosmo_lower,\n self._lens_upper, self._source_upper, self._lens_light_upper, self._ps_upper,\n self._cosmo_upper,\n kwargs_lens_init=kwargs_mean_lens, fix_lens_solver=fix_solver)\n\n # initialize ImSim() class\n kwargs_likelihood = copy.deepcopy(self.kwargs_likelihood)\n if compute_bool is not None:\n kwargs_likelihood['bands_compute'] = compute_bool\n imSim_class = class_creator.create_multiband(self.multi_band_list, self.kwargs_model)\n likelihoodModule = LikelihoodModule(imSim_class=imSim_class, param_class=param_class,\n kwargs_likelihood=kwargs_likelihood)\n # run PSO\n mcmc_class = Sampler(likelihoodModule=likelihoodModule)\n mean_start = param_class.setParams(kwargs_mean_lens, kwargs_mean_source, kwargs_mean_lens_light, kwargs_mean_ps,\n kwargs_mean_cosmo)\n sigma_start = param_class.setParams(kwargs_sigma_lens, kwargs_sigma_source, kwargs_sigma_lens_light,\n kwargs_sigma_ps, kwargs_sigma_cosmo)\n num_param, param_list = param_class.num_param()\n # run MCMC\n if not init_samples is None:\n initpos = ReusePositionGenerator(init_samples)\n else:\n initpos = None\n samples, dist = mcmc_class.mcmc_CH(walkerRatio, n_run, n_burn, mean_start, np.array(sigma_start)*sigma_factor, threadCount=threadCount,\n mpi=mpi, init_pos=initpos)\n return samples, param_list, dist\n\n def pso_run(self, kwargs_lens, kwargs_source, kwargs_lens_light, kwargs_ps, kwargs_cosmo,\n n_particles, n_iterations, mpi=False, threadCount=1, sigma_factor=1,\n compute_bool=None, fix_lens=False, fix_source=False, fix_lens_light=False, fix_point_source=False,\n fix_cosmo=False, print_key='find_model'):\n \"\"\"\n finds lens light and lens model combined fit\n :return: constraints of lens model\n \"\"\"\n kwargs_fixed_lens, kwargs_fixed_source, kwargs_fixed_lens_light, kwargs_fixed_ps, kwargs_fixed_cosmo = self._paramUpdate.update_fixed_simple(\n kwargs_lens, kwargs_source, kwargs_lens_light, kwargs_ps, kwargs_cosmo, fix_lens=fix_lens, fix_source=fix_source,\n fix_lens_light=fix_lens_light, fix_point_source=fix_point_source, fixed_cosmo=fix_cosmo)\n kwargs_lens_sigma, kwargs_source_sigma, kwargs_lens_light_sigma, kwargs_ps_sigma, kwargs_cosmo_sigma = self.sigma_kwargs()\n lens_result, source_result, lens_light_result, ps_result, cosmo_result, chain, param_list = self._run_pso(\n n_particles, n_iterations,\n kwargs_fixed_lens, kwargs_lens, kwargs_lens_sigma,\n kwargs_fixed_source, kwargs_source, kwargs_source_sigma,\n kwargs_fixed_lens_light, kwargs_lens_light, kwargs_lens_light_sigma,\n kwargs_fixed_ps, kwargs_ps, kwargs_ps_sigma,\n kwargs_fixed_cosmo, kwargs_cosmo, kwargs_cosmo_sigma,\n threadCount=threadCount, mpi=mpi, print_key=print_key, sigma_factor=sigma_factor, compute_bool=compute_bool,\n fix_solver=fix_lens)\n return lens_result, source_result, lens_light_result, ps_result, cosmo_result, chain, param_list\n\n def mcmc_run(self, kwargs_lens, kwargs_source, kwargs_lens_light, kwargs_ps, kwargs_cosmo,\n n_burn, n_run, walkerRatio, threadCount=1, mpi=False, init_samples=None, sigma_factor=1,\n compute_bool=None, fix_lens=False, fix_source=False, fix_lens_light=False,\n fix_point_source=False):\n \"\"\"\n MCMC\n \"\"\"\n kwargs_fixed_lens, kwargs_fixed_source, kwargs_fixed_lens_light, kwargs_fixed_ps, kwargs_fixed_cosmo = self._paramUpdate.update_fixed_simple(\n kwargs_lens, kwargs_source, kwargs_lens_light, kwargs_ps, kwargs_cosmo, fix_lens=fix_lens, fix_source=fix_source,\n fix_lens_light=fix_lens_light, fix_point_source=fix_point_source)\n kwargs_lens_sigma, kwargs_source_sigma, kwargs_lens_light_sigma, kwargs_ps_sigma, kwargs_cosmo_sigma = self.sigma_kwargs()\n samples, param_list, dist = self._mcmc_run(\n n_burn, n_run, walkerRatio,\n kwargs_fixed_lens, kwargs_lens, kwargs_lens_sigma,\n kwargs_fixed_source, kwargs_source, kwargs_source_sigma,\n kwargs_fixed_lens_light, kwargs_lens_light, kwargs_lens_light_sigma,\n kwargs_fixed_ps, kwargs_ps, kwargs_ps_sigma,\n kwargs_fixed_cosmo, kwargs_cosmo, kwargs_cosmo_sigma,\n threadCount=threadCount, mpi=mpi, init_samples=init_samples, sigma_factor=sigma_factor,\n compute_bool=compute_bool, fix_solver=fix_lens)\n return samples, param_list, dist\n\n\nclass ParamUpdate(object):\n\n def __init__(self, kwargs_fixed_lens, kwargs_fixed_source, kwargs_fixed_lens_light, kwargs_fixed_ps,\n kwargs_fixed_cosmo):\n self.kwargs_fixed = copy.deepcopy([kwargs_fixed_lens, kwargs_fixed_source, kwargs_fixed_lens_light,\n kwargs_fixed_ps, kwargs_fixed_cosmo])\n\n def update_fixed_simple(self, kwargs_lens, kwargs_source, kwargs_lens_light, kwargs_ps, kwargs_cosmo, fix_lens=False,\n fix_source=False, fix_lens_light=False, fix_point_source=False, fixed_cosmo=False):\n if fix_lens:\n add_fixed_lens = kwargs_lens\n else:\n add_fixed_lens = None\n if fix_source:\n add_fixed_source = kwargs_source\n else:\n add_fixed_source = None\n if fix_lens_light:\n add_fixed_lens_light = kwargs_lens_light\n else:\n add_fixed_lens_light = None\n if fix_point_source:\n add_fixed_ps = kwargs_ps\n else:\n add_fixed_ps = None\n if fixed_cosmo:\n add_fixed_cosmo = kwargs_cosmo\n else:\n add_fixed_cosmo = None\n kwargs_fixed_lens, kwargs_fixed_source, kwargs_fixed_lens_light, kwargs_fixed_ps, kwargs_fixed_cosmo = self._update_fixed(\n add_fixed_lens=add_fixed_lens, add_fixed_source=add_fixed_source, add_fixed_lens_light=add_fixed_lens_light,\n add_fixed_ps=add_fixed_ps, add_fixed_cosmo=add_fixed_cosmo)\n\n return kwargs_fixed_lens, kwargs_fixed_source, kwargs_fixed_lens_light, kwargs_fixed_ps, kwargs_fixed_cosmo\n\n def _update_fixed(self, add_fixed_lens=None, add_fixed_source=None,\n add_fixed_lens_light=None, add_fixed_ps=None, add_fixed_cosmo=None):\n\n lens_fix = copy.deepcopy(self.kwargs_fixed[0])\n source_fix = copy.deepcopy(self.kwargs_fixed[1])\n lens_light_fix = copy.deepcopy(self.kwargs_fixed[2])\n ps_fix = copy.deepcopy(self.kwargs_fixed[3])\n cosmo_fix = copy.deepcopy(self.kwargs_fixed[4])\n if add_fixed_lens is None:\n kwargs_fixed_lens_updated = lens_fix\n else:\n kwargs_fixed_lens_updated = []\n for k in range(len(lens_fix)):\n kwargs_fixed_lens_updated_k = add_fixed_lens[k].copy()\n kwargs_fixed_lens_updated_k.update(lens_fix[k])\n kwargs_fixed_lens_updated.append(kwargs_fixed_lens_updated_k)\n if add_fixed_source is None:\n kwargs_fixed_source_updated = source_fix\n else:\n kwargs_fixed_source_updated = []\n for k in range(len(source_fix)):\n kwargs_fixed_source_updated_k = add_fixed_source[k].copy()\n kwargs_fixed_source_updated_k.update(source_fix[k])\n kwargs_fixed_source_updated.append(kwargs_fixed_source_updated_k)\n if add_fixed_lens_light is None:\n kwargs_fixed_lens_light_updated = lens_light_fix\n else:\n kwargs_fixed_lens_light_updated = []\n for k in range(len(lens_light_fix)):\n kwargs_fixed_lens_light_updated_k = add_fixed_lens_light[k].copy()\n kwargs_fixed_lens_light_updated_k.update(lens_light_fix[k])\n kwargs_fixed_lens_light_updated.append(kwargs_fixed_lens_light_updated_k)\n kwargs_fixed_ps_updated = []\n if add_fixed_ps is None:\n kwargs_fixed_ps_updated = ps_fix\n else:\n for k in range(len(ps_fix)):\n kwargs_fixed_ps_updated_k = add_fixed_ps[k].copy()\n kwargs_fixed_ps_updated_k.update(ps_fix[k])\n kwargs_fixed_ps_updated.append(kwargs_fixed_ps_updated_k)\n if add_fixed_cosmo is None:\n kwargs_fixed_cosmo_updated = cosmo_fix\n else:\n kwargs_fixed_cosmo_updated = add_fixed_cosmo.copy()\n kwargs_fixed_cosmo_updated.update(cosmo_fix)\n return kwargs_fixed_lens_updated, kwargs_fixed_source_updated, kwargs_fixed_lens_light_updated,\\\n kwargs_fixed_ps_updated, kwargs_fixed_cosmo_updated\n","sub_path":"lenstronomy/Workflow/fitting.py","file_name":"fitting.py","file_ext":"py","file_size_in_byte":16060,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"515118188","text":"import requests\n\nURL = \"https://api.ciscospark.com/v1/messages\"\nACCESS_TOKEN = \"MTU3NmUzZDMtMGRiYi00OGJkLTgxNzItNGVjNWQ3YjA4ODJiY2MyZDVmMTktZTA0\"\n\nHEADERS = {\"Content-type\" : \"application/json; charset=utf-8\", \"Authorization\" : \"Bearer \" + ACCESS_TOKEN}\nPAYLOAD = {\"toPersonEmail\" : \"ltu@sparkbot.io\", \"text\" : \"about\"}\n\nresponse = requests.post(url=URL, json=PAYLOAD, headers=HEADERS)\n\nprint(\"response status code is: \", response.status_code)\nprint(response.text)","sub_path":"itp/code4.py","file_name":"code4.py","file_ext":"py","file_size_in_byte":464,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"355526994","text":"from download_builder import DownloadBuilder\nfrom torrent_file import TorrentInfo\nfrom peer import Peer\n\ndef main():\n peer_test = Peer('208.78.42.32', 53206, \n b'\\x08\\xad\\xa5\\xa7\\xa6\\x18:\\xae\\x1e\\t\\xd81\\xdfgH\\xd5f\\tZ\\x10',\n b'o\\x03\\xf0+w|\\\\\\xa6\\xd4\\x82\\xa0E\\x80\\xf1\\xbe8\\xa0V\\x01\\xa4'\n )\n torrent_info = TorrentInfo(\"sintel.torrent\")\n builder = DownloadBuilder(udp_port=\"6882\", download_folder=\"/home/iestrela/Downloads\")\n pieces_pool = builder._set_torrent_pieces_pool(torrent_info)\n if not peer_test.attach_pieces(pieces_pool):\n return\n if peer_test.has_piece(626):\n peer_test.download_piece(626)\nmain()","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":682,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"185546793","text":"import yaml, subprocess, os.path, sys\n\nthis_dir = os.path.dirname(sys.argv[0])\nservlet_root = os.path.dirname(sys.argv[1])\nanalyze_servlet_script = os.path.join(this_dir, \"analyze_servlet.py\")\n\nsubprocess.check_call([\"python\", analyze_servlet_script, \"--quiet\", \"--very-quiet\", \"--record\", sys.argv[1]])\n\nif os.path.exists(os.path.join(servlet_root, \"_timeout.yml\")):\n with open(sys.argv[2], 'w') as out:\n yaml.dump({\"timeout\": True}, out)\nelse:\n site_loc = os.path.join(servlet_root, \"sites.yml\")\n report_loc = os.path.join(servlet_root, \"reports.yml\")\n assert os.path.exists(site_loc)\n assert os.path.exists(report_loc)\n with open(site_loc, 'r') as site_f:\n site_blob = yaml.load(site_f)\n with open(report_loc, 'r') as report_f:\n report_blob = yaml.load(report_f)\n with open(sys.argv[2], 'w') as out:\n yaml.dump_all([site_blob, report_blob], out)\n","sub_path":"util/aws_analyze_servlet.py","file_name":"aws_analyze_servlet.py","file_ext":"py","file_size_in_byte":901,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"479444230","text":"from rest_framework.serializers import ModelSerializer\nfrom django.contrib.auth import get_user_model\n\nUser = get_user_model()\n\nclass PopulatedUserSerializer(ModelSerializer):\n\n class Meta:\n model = User\n fields = (\n 'id',\n 'username',\n 'email',\n 'profile_picture_url',\n 'country'\n )","sub_path":"jwt_auth/populated.py","file_name":"populated.py","file_ext":"py","file_size_in_byte":362,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"277495759","text":"from openpyxl import Workbook\n\nwb = Workbook()\nsheet = wb.active\n\ndata = [\n ['Item', 'Colour'],\n ['pen', 'brown'],\n ['book', 'black'],\n ['plate', 'white'],\n ['chair', 'brown'],\n ['coin', 'gold'],\n ['bed', 'brown'],\n ['notebook', 'white'],\n] # Matriz de dados, que contem um determinado item se sua respectiva cor associada\n\n# Loop para inserir os dados da matriz na planilha\nfor r in data:\n sheet.append(r)\n\nsheet.auto_filter.ref = 'A1:B8' # Abrangência do filtro\nsheet.auto_filter.add_filter_column(1, ['brown', 'white']) # Adicionando o filtro em uma coluna, que neste caso é a coluna 1, ou seja, a segunda coluna, contendo os valores: brown,white\nsheet.auto_filter.add_sort_condition('B2:B8')\n\nwb.save('filtrado.xlsx') # Escrever no arquivo","sub_path":"filtrar_sortear.py","file_name":"filtrar_sortear.py","file_ext":"py","file_size_in_byte":772,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"636633838","text":"import math\nimport random\nimport time\nfrom gameEngine.player import Player\nfrom QlearningEngineV3.node import Node\nfrom QlearningEngineV3.Qfunction import setNodeExpectation, updateQTable\n\nclass AIV3(Player):\n\n def __init__(self, id, exploration_coeff):\n super().__init__(id, \"IAv3\")\n self.__memorized_opponent_card = None\n self.__previous_node = None\n self.__special = None\n self.__exploration_coeff = exploration_coeff\n self.__remaining_cards = [5,2,2,2,2,1,1,1]\n self.__probas = [0,0,0,0,0,0,0,0]\n self._version = \"AIv3\"\n \n def getSpecial(self):\n return self.__special\n \n def draw(self, draw, renderer, hide=False):\n \"\"\"Same of player draw but counts remainging cards\n\n draw = list of cards\n \"\"\"\n drawn_card = draw.pop(0)\n if not renderer.getSimuMod():\n renderer.draw(self._id, \"back\", len(self._hand), True)\n self._hand.append(drawn_card)\n self.__remaining_cards[drawn_card.getValue()-1]-=1\n\n def setMemorizedOpponentCard(self, card_value):\n self.__memorized_opponent_card = card_value\n\n def updateRemainingCards(self, discard):\n \"\"\"Update remainging unkonwn cards in game\n\n discard = list of cards\n \"\"\"\n for card in discard:\n self.__remaining_cards[card.getValue()-1]-=1\n self.__updateProba()\n\n def __updateProba(self):\n \"\"\"Update probabilities of what card can has the opponent\n \"\"\"\n nb_cards = 0\n for remaining_card in self.__remaining_cards:\n nb_cards+=remaining_card\n if nb_cards != 0:\n index_proba = 0\n for remaining_card in self.__remaining_cards:\n if remaining_card != 0:\n self.__probas[index_proba] = remaining_card/nb_cards\n index_proba+=1\n\n def forgetOpponentCard(self, opponent_discard):\n \"\"\"Check if memorized card was played.\n\n opponent_discard = opponent discard\n \"\"\"\n self.__memorized_opponent_card = None if opponent_discard[len(opponent_discard)-1] == self.__memorized_opponent_card else self.__memorized_opponent_card\n\n def _chooseCard(self, game):\n \"\"\"Choose a card to play thanks to Q-Learning.\n\n game = game object\n\n Return : index of card to play\n \"\"\"\n self.__special = None\n choosen_card = None\n opponent = game.getPlayers()[1] if game.getPlayers()[0].getId() == self._id else game.getPlayers()[0]\n if len(opponent.getDiscard()) != 0:\n self.forgetOpponentCard(opponent.getDiscard())\n nodes=[]\n have_princess = self.__playPrincess()\n if have_princess:\n choosen_card = 1 if self._hand[0].getValue() == 8 else 0\n if self._hand[choosen_card].getValue() == 5 :\n self.__special = opponent._id\n else:\n for card in self._hand:\n node = None\n if(self.__previous_node != None):\n if card.getValue() == 5:\n node = Node(self.__previous_node.getCurrentState().getCard1(), self.__previous_node.getCurrentState().getCard2(), self.__previous_node.getCurrentAction(), self.__previous_node.getCurrentExpectation(), self._hand[0].getValue(), self._hand[1].getValue(), card.getValue(), len(game.getDraw()), False)\n setNodeExpectation(node)\n nodes.append(node)\n node = Node(self.__previous_node.getCurrentState().getCard1(), self.__previous_node.getCurrentState().getCard2(), self.__previous_node.getCurrentAction(), self.__previous_node.getCurrentExpectation(), self._hand[0].getValue(), self._hand[1].getValue(), card.getValue(), len(game.getDraw()), True)\n else:\n node = Node(self.__previous_node.getCurrentState().getCard1(), self.__previous_node.getCurrentState().getCard2(), self.__previous_node.getCurrentAction(), self.__previous_node.getCurrentExpectation(), self._hand[0].getValue(), self._hand[1].getValue(), card.getValue(), len(game.getDraw()), None)\n else:\n if card.getValue() == 5:\n node = Node(None, None, None, None, self._hand[0].getValue(), self._hand[1].getValue(), card.getValue(), len(game.getDraw()), False)\n setNodeExpectation(node)\n nodes.append(node)\n node = Node(None, None, None, None, self._hand[0].getValue(), self._hand[1].getValue(), card.getValue(), len(game.getDraw()), True)\n else:\n node = Node(None, None, None, None, self._hand[0].getValue(), self._hand[1].getValue(), card.getValue(), len(game.getDraw()), None)\n setNodeExpectation(node)\n nodes.append(node)\n \n choosen_card = self.__instaPlay(opponent, have_princess)\n choosen_node = None\n if self.__exploration_coeff > random.random():\n choosen_card = 0 if self._hand[random.randint(0,1)].getValue() == self._hand[0].getValue() else 1\n elif choosen_card == -1:\n if len(nodes) > 2:\n real_prince_expectation = 0\n prince_nodes=[]\n other_node = None\n for node in nodes:\n if node.getCurrentAction() == 5:\n real_prince_expectation+=node.getCurrentExpectation()\n prince_nodes.append(node)\n else:\n other_node = node\n if other_node != None and other_node.getCurrentExpectation() > real_prince_expectation:\n choosen_node = other_node\n else:\n for prince_node in prince_nodes:\n if choosen_node == None or choosen_node.getCurrentExpectation() < prince_node.getCurrentExpectation():\n choosen_node = prince_node\n choosen_card = 0 if choosen_node.getCurrentAction() == self._hand[0].getValue() else 1\n else:\n for node in nodes:\n if(choosen_node == None or choosen_node.getCurrentExpectation() < node.getCurrentExpectation()):\n choosen_node = node\n choosen_card = 0 if node.getCurrentAction() == self._hand[0].getValue() else 1\n if choosen_node is None:\n if len(nodes) == 1:\n choosen_node = nodes[0]\n else:\n if self._hand[choosen_card].getValue() == 5:\n if nodes[0].getCurrentAction() == 5 :\n choosen_node = nodes[random.randint(0,1)]\n else:\n choosen_node = nodes[random.randint(1,2)]\n else:\n if len(nodes) == 3:\n choosen_node = nodes[0] if nodes[0].getCurrentAction() != 5 else nodes[2]\n else:\n choosen_node = nodes[0] if nodes[0].getCurrentAction() == self._hand[choosen_card].getValue() else nodes[1]\n if(self.__previous_node != None):\n updateQTable(choosen_node, 0)\n self.__previous_node = choosen_node\n self.__chooseSpecial(choosen_node, opponent)\n time.sleep(1)\n if not game.getRenderer().getSimuMod():\n game.getRenderer().removeCardHand(self._id, 0, len(self._hand))\n return choosen_card\n\n def __chooseSpecial(self, choosen_node, opponent):\n \"\"\"Ai choose how to play prince and guard\n\n choosen_node = choosen node by Qlearning\n \"\"\"\n if choosen_node.getCurrentAction() == 1 and self.__special == None:\n best_proba = 0\n card_value = 1\n equality = True\n value_remaining_cards=[]\n for proba in self.__probas:\n if proba != 0 and card_value != 1:\n if best_proba != proba:\n equality = False\n value_remaining_cards.append(card_value)\n if best_proba < proba and card_value != 1:\n best_proba = proba\n self.__special = card_value\n card_value+=1\n if equality :\n self.__special = value_remaining_cards[0 if len(value_remaining_cards) == 1 else random.randint(0, len(value_remaining_cards)-1)]\n if best_proba == 0:\n self.__special = 2\n elif choosen_node.getCurrentAction() == 5 and self.__special == None:\n self.__special= self._id if choosen_node.getChoosenPlayer() else opponent._id\n\n\n def lastUpdate(self, r):\n \"\"\"Update reward of last node\n\n r = rewards of last node\n \"\"\"\n if self.__previous_node != None:\n updateQTable(self.__previous_node, r)\n\n def __instaPlay(self, opponent, have_princess):\n \"\"\"Check if a the A.I can instant play\n\n return = card choose if A.I can else -1\n \"\"\"\n have_guard = False\n have_baron = False\n have_prince = False\n for card in self._hand:\n have_guard = False if not have_guard and card.getValue() != 1 else True\n have_baron = False if not have_baron and card.getValue() != 3 else True\n have_prince = False if not have_prince and card.getValue() != 5 else True\n if self.__memorized_opponent_card != None and not opponent.getIsImmune():\n if have_guard and self.__memorized_opponent_card > 1:\n self.__special = self.__memorized_opponent_card\n return 0 if self._hand[0].getValue() == 1 else 1\n if have_baron :\n if self._hand[0].getValue() == 3 and self.__memorized_opponent_card < self._hand[1].getValue():\n return 0\n elif self._hand[1].getValue() == 3 and self.__memorized_opponent_card < self._hand[0].getValue():\n return 1\n if have_prince:\n other_card_value = self._hand[0].getValue() if self._hand[1].getValue() == 5 else self._hand[1].getValue()\n if self.__memorized_opponent_card == 8 or have_princess or other_card_value >= 5:\n self.__special = 1 if self._id == 2 else 2\n return 0 if self._hand[0].getValue() == 1 else 1\n return -1\n\n def __playPrincess(self):\n \"\"\"Check if a the A.I can play princess\n\n return = have_princess\n \"\"\"\n have_princess = False\n for card in self._hand:\n have_princess = False if not have_princess and card.getValue() != 8 else True\n return have_princess\n","sub_path":"QlearningEngineV3/AIV3.py","file_name":"AIV3.py","file_ext":"py","file_size_in_byte":10899,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"14341155","text":"from cv2 import *\r\nfrom numpy import *\r\nimport color2.py\r\nimport matplotlib.pyplot as plt\r\n# initialize the camera\r\ncam = VideoCapture(0) # 0 -> index of camera\r\nwhile 1:\r\n s, img = cam.read()\r\n if s: # frame captured without any errors\r\n for i in range(420):\r\n for j in range(640):\r\n if img[i][j][1]<50 and img[i][j][2]<50 and img[i][j][0]<50:\r\n img[i][j][1]=200\r\n img=img.astype(uint8)\r\n imshow(\"cam-test\",img)\r\n if waitKey(1) == ord('q'):\r\n break\r\nprint()\r\ncam.release()\r\ndestroyAllWindows()\r\n","sub_path":"dst.py","file_name":"dst.py","file_ext":"py","file_size_in_byte":591,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"5870012","text":"from oppgave2 import lagA\nfrom numpy import dot\n\ndef y_e_vektor(L):\n w = 0.3 # m\n t = 0.03 # m\n g = 9.81 # N\n d = 480 # kg/m^3\n E = 1.3 * 10**10 # N/m^2\n I = (w*t**3)/12 # Tverrsnitt m^2\n f_x = -d*w*t*g # egen vekt\n\n y_e = []\n for i in range(0, 10):\n x = (i+1)*0.2\n y_e.append(f_x / 24 / E / I * (x**2) * (x**2 - 4*x*L + 6*L**2))\n\n return y_e\n\ndef oppgave4c():\n L = 2 #m\n n = 10\n # lengden på hver seksjon\n h = L/n\n # Strukturmatrise\n A = lagA(10)\n # Vektor med eksakte y-verdier\n y_e = y_e_vektor(L)\n # vektoren y'''' med numeriske tilnærminger\n return (1 / h**4) * dot(A, y_e)\n\nprint(oppgave4c())","sub_path":"oppgave4c.py","file_name":"oppgave4c.py","file_ext":"py","file_size_in_byte":674,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"298168373","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue May 11 15:17:24 2021\n\n@author: mark.chimes\n\"\"\"\n\n#%% Imports\n\nimport math \nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom matplotlib import cm\n\n\n#%% Display Limits\nx_min, x_max = -1, 1 \ny_min, y_max = -1, 1\n\nx_min_zoom, x_max_zoom = -0.5, 0.5 \ny_min_zoom, y_max_zoom = -0.5, 0.5\n\nxlim = [x_min, x_max]\nylim = [y_min, y_max]\n\nxlim_zoom = [x_min_zoom, x_max_zoom]\nylim_zoom = [y_min_zoom, y_max_zoom]\n\naxlim = [-1, 1]\naylim = [-1, 1]\nazlim = [-1, 1]\n\n#%% Generate Flat Data\n\n# Ring\nNa = 1000\nsiga = 0.1\nellipse_width = 0.7\nellipse_height = 0.7\nthetas = np.linspace(0, 2*math.pi, Na)\n\n#generate deviations\ndevs = np.random.normal(0, siga, Na)\nx_mults = ellipse_width*(np.ones(Na)+devs)\ny_mults = ellipse_width*(np.ones(Na)+devs)\n\nsax = x_mults*np.cos(thetas)\nsay = y_mults*np.sin(thetas)\n\n# Disc\nNb = 1000\nsigb = 0.1\nmu_bx, mu_by, sigma_bx, sigma_by = 0, 0, sigb, sigb # mean and standard deviation\nsbx = np.random.normal(mu_bx, sigma_bx, Nb)\nsby = np.random.normal(mu_by, sigma_by, Nb)\n\n\n#%% Plotting Functions\n\nangles = [(45,45), (45,20), (45,0), (20,0), (0,0), \\\n (0,-20), (0,-45), (20,-45), (45,-45)]\n \ndef standardFlatLimitsAndLabels(plt): \n plt.xlim(xlim)\n plt.ylim(ylim)\n plt.xlabel('X')\n h = plt.ylabel('Y')\n h.set_rotation(0) \n\ndef standardAxLimitsAndLabels(ax): \n ax.set_xlim(axlim)\n ax.set_ylim(aylim)\n ax.set_zlim(azlim)\n ax.set_xlabel('X')\n ax.set_ylabel('Y')\n ax.set_zlabel('Z')\n \ndef x_reflect(angle): \n if 90 < angle and angle <= 270:\n return 1\n if -270 <= angle and angle < -90:\n return 1\n return -1\n return -1\n\ndef y_reflect(angle): \n if 0 <= angle and angle < 180:\n return -1\n if -360 <= angle and angle < -180:\n return -1\n return 1\n\ndef z_reflect(angle): \n if 0 <= angle and angle < 180:\n return -1\n if -360 <= angle and angle < -180:\n return -1\n return 1\n \n\ndef standardFlatLimitsAndLabels(plt): \n plt.xlim(xlim)\n plt.ylim(ylim)\n plt.xlabel('x')\n h = plt.ylabel('y')\n h.set_rotation(0) \n\n\n#%% Plot Flat Data\n\nplt.suptitle('Base Data')\nstandardFlatLimitsAndLabels(plt)\nplt.scatter(sax, say, marker='.', color='red')\nplt.scatter(sbx, sby, marker='.', color='blue')\nplt.show()\n\n\n#%% Generate floating data\n\ndef generatingFunction(x, y): \n return 0.5*x + x**2 + 0.5*y + y**2\n\ngx = gy = np.arange(-0.75, 0.75, 0.1)\ngX, gY = np.meshgrid(gx, gy)\ngZ0 = np.zeros(gX.shape)\ngz = np.array(np.ravel(generatingFunction(gX, gY)))\ngZ = gz.reshape(gX.shape)\n\ndef predictionWireframeFloatAndPredictions(z, main_alph=0.2, proj_alph=0.05, v_angle=0, h_angle=0):\n Z = -np.sqrt(gX**2 + gY**2)\n norm = plt.Normalize(Z.min(), Z.max())\n colors = cm.viridis(norm(Z))\n rcount, ccount, _ = colors.shape\n \n def plot_surfy(ix, iy, iz, ialph): \n ax.plot_surface(ix, iy, iz, facecolors=colors, rcount=rcount, ccount=ccount, alpha=ialph)\n \n plot_surfy(gX, gY, z, 0.2)\n plot_surfy(gX, gY, gZ0+z_reflect(v_angle), 0.05)\n plot_surfy(gX, y_reflect(h_angle), z, 0.05)\n plot_surfy(x_reflect(h_angle), gY, z, 0.05)\n\n#%% Generate floating data\n\nsaz = generatingFunction(sax, say)\nsbz = generatingFunction(sbx, sby)\n\n\ndef floatAndProjections(x,y,z, col='green', main_alph=0.8, proj_alph=0.08, v_angle=0, h_angle=0): \n ax.scatter3D(x, y, z, marker='.', color=col, alpha=main_alph)\n ax.scatter3D(x, y, z_reflect(v_angle), color=col, alpha=proj_alph)\n ax.scatter3D(x, y_reflect(h_angle), z, color=col, alpha=proj_alph)\n ax.scatter3D(x_reflect(h_angle), y, z, color=col, alpha=proj_alph)\n\nfor a, b in angles: \n # Plot the points with true surface.\n ax = plt.axes(projection='3d')\n plt.suptitle('Dataset and \\n' + r'Generating Function Wireframe')\n standardAxLimitsAndLabels(ax)\n ax.view_init(a, b)\n # floatAndProjections(sx, sy, sz, 0.3, 0.03, a, b)\n predictionWireframeFloatAndPredictions(gZ, 0.05, 0.01, a, b)\n floatAndProjections(sax, say, saz, col='red', main_alph=0.5, proj_alph=0.01)\n floatAndProjections(sbx, sby, sbz, col='blue', main_alph=0.5, proj_alph=0.002)\n plt.show()\n \n#%% Stochastic Gradient Descent\n\n\ntotal = Na + Nb\ntest_N = 100\ntrain_N = total - test_N\n\nSX = np.concatenate((sax, sbx))\nSY = np.concatenate((say, sby))\nSZ = generatingFunction(sx, sy)\n\nSC = np.concatenate((np.ones(sax.shape), np.zeros(sbx.shape)))\n\nall_points = np.column_stack((SX, SY, SZ, SC))\n\nnp.random.shuffle(all_points)\n\n\n\n\n\n\n\n\n\n","sub_path":"sgd/sgd-3d.py","file_name":"sgd-3d.py","file_ext":"py","file_size_in_byte":4489,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"651617182","text":"\n# encoding: utf-8\n\nimport csv\nimport math\nimport os\nimport random\nimport time\nimport requests\n\n\"\"\"\n*****************\n可改配置,酌情更改\n*****************\n\"\"\"\nSTART_DATE = '2001-09-20' # 首家农业上市企业的日期\nEND_DATE = str(time.strftime('%Y-%m-%d')) # 默认当前提取,可设定为固定值\nOUT_DIR = '/home/captain/PycharmProjects/reportPDF'\nOUTPUT_FILENAME = '年度审计报告'\n# 板块类型:shmb(沪市主板)、szmb(深市主板)、szzx(中小板)、szcy(创业板)\nPLATE = 'szzx;'\n# 公告类型:category_scgkfx_szsh(首次公开发行及上市)、category_ndbg_szsh(年度报告)、category_bndbg_szsh(半年度报告)\n#CATEGORY = 'category_ndbg_szsh;'\n\"\"\"\n*****************\n固定配置,勿改\n*****************\n\"\"\"\nURL = 'http://www.cninfo.com.cn/cninfo-new/announcement/query'\nHEADER = {\n 'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.62 Safari/537.36',\n 'X-Requested-With': 'XMLHttpRequest'\n}\nMAX_PAGESIZE = 50\nMAX_RELOAD_TIMES = 5\nRESPONSE_TIMEOUT = 10\n\n\n\ndef standardize_dir(dir_str):\n #先判断这个文件夹是否存在,不存在报错\n assert (os.path.exists(dir_str)), 'Such directory \\\"' + str(dir_str) + '\\\" does not exists!'\n if dir_str[len(dir_str) - 1] != '/':\n return dir_str + '/'\n else:\n return dir_str\n\"\"\"\n这有一个问题,目录是提前设置好的,可以调用函数,来提取当前目录,保存到程序存在的目录\n\"\"\"\n\n\n\n\n# 参数:页面id(每页条目个数由MAX_PAGESIZE控制),是否返回总条目数(bool)\ndef get_response(page_num, return_total_count=False):\n query = {\n 'stock': '',\n 'searchkey': '年度审计报告',\n 'plate': '',\n 'category': '',\n 'trade': '',\n 'column': 'szse',\n 'columnTitle': '历史公告查询',\n 'pageNum': page_num,\n 'pageSize': MAX_PAGESIZE,\n 'tabName': 'fulltext',\n 'sortName': '',\n 'sortType': '',\n 'limit': '',\n 'showTitle': '',\n 'seDate': START_DATE + '~' + END_DATE,\n }\n\n result_list = []\n reloading = 0\n while True:\n reloading += 1\n if reloading > MAX_RELOAD_TIMES:\n return []\n elif reloading > 1:\n __sleeping(random.randint(5, 10)) #随机睡眠5~10秒\n print('... reloading: the ' + str(reloading) + ' round ...')\n\n try:\n res = requests.post(URL, query, HEADER, timeout=RESPONSE_TIMEOUT)\n except Exception as e:\n print(e)\n continue\n if res.text == '':\n print(\"-----------空-------------\")\n if res.status_code == requests.codes.ok and res.text != '': #取值之后跳出,否则循环在请求一次\n break\n my_query = res.json()#转化为json?\n\n try:\n res.close()\n except Exception as e:\n print(e)\n if return_total_count:\n return my_query['totalRecordNum']\n else:\n for each in my_query['announcements']: # 链接所在的位置“announcements”\n # 做拼接,我记得有个方法是用来做拼接的----------------------------------------------------------------///标记\n file_link = 'http://www.cninfo.com.cn/' + str(each['adjunctUrl']) # “adjunctUrl”链接位置\n file_name = __filter_illegal_filename(\n str(each['secCode']) + str(each['secName']) + str(each['announcementTitle']) +\n file_link[-file_link[::-1].find('.') - 1:] # 最后一项是获取文件类型后缀名\n )\n result_list.append([file_name, file_link])\n return result_list # 返回了一个列表,记录了当前页内链接的名字和下载地址\n\n\ndef __log_error(err_msg):\n err_msg = str(err_msg)\n print(err_msg)\n with open(error_log, 'a', encoding='gb18030') as err_writer:\n err_writer.write(err_msg + '\\n')\n\n\ndef __sleeping(sec):\n if type(sec) == int:\n print('... sleeping ' + str(sec) + ' secong ...')\n time.sleep(sec)\n\n\ndef __filter_illegal_filename(filename):\n illegal_char = {\n ' ': '',\n '*': '',\n '/': '-',\n '\\\\': '-',\n ':': '-',\n '?': '-',\n '\"': '',\n '<': '',\n '>': '',\n '|': '',\n '-': '-',\n '—': '-',\n '(': '(',\n ')': ')',\n 'A': 'A',\n 'B': 'B',\n 'H': 'H',\n ',': ',',\n '。': '.',\n ':': '-',\n '!': '_',\n '?': '-',\n '“': '\"',\n '”': '\"',\n '‘': '',\n '’': ''\n }\n for item in illegal_char.items():\n filename = filename.replace(item[0], item[1])\n return filename\n\n\nif __name__ == '__main__':\n # 初始化重要变量\n out_dir = standardize_dir(OUT_DIR) #保存路径\n error_log = out_dir + 'error.log'\n output_csv_file = out_dir + OUTPUT_FILENAME.replace('/', '') + '_' + \\\n START_DATE.replace('-', '') + '-' + END_DATE.replace('-', '') + '.csv'\n # 获取记录数、页数\n item_count = get_response(1, True)\n assert (item_count != []), 'Please restart this script!'#如果无记录则退出\n begin_pg = 1\n end_pg = int(math.ceil(item_count / MAX_PAGESIZE))#math.ceil(x)返回大于等于参数x的最小整数,即对浮点数向上取整\n print('Page count: ' + str(end_pg) + '; item count: ' + str(item_count) + '.')\n time.sleep(2)#sleep() 方法暂停给定秒数后执行程序\n\n # 逐页抓取\n with open(output_csv_file, 'w', newline='', encoding='gb18030') as csv_out:\n writer = csv.writer(csv_out)\n for i in range(begin_pg, end_pg + 1):\n row = get_response(i)\n print(row)\n if not row:\n __log_error('Failed to fetch page #' + str(i) +\n ': exceeding max reloading times (' + str(MAX_RELOAD_TIMES) + ').')\n continue\n else:\n writer.writerows(row)\n last_item = i * MAX_PAGESIZE if i < end_pg else item_count\n print('Page ' + str(i) + '/' + str(end_pg) + ' fetched, it contains items: (' +\n str(1 + (i - 1) * MAX_PAGESIZE) + '-' + str(last_item) + ')/' + str(item_count) + '.')\n","sub_path":"JuchaoPDF/post_requests.py","file_name":"post_requests.py","file_ext":"py","file_size_in_byte":6325,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"115464508","text":"from django.shortcuts import render, redirect\n\n\n# Create your views here.\n\n\ndef main(request):\n args = {}\n\n if \"user\" in request.session:\n args[\"user\"] = request.session[\"user\"]\n return redirect(\"/home/\")\n else:\n args[\"user\"] = None\n return render(request, \"index/index.html\", args)\n\n\ndef downloading(request):\n args = {}\n\n if \"user\" in request.session:\n args[\"user\"] = request.session[\"user\"]\n else:\n args[\"user\"] = None\n return render(request, \"index/downloading.html\", args)","sub_path":"index/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":536,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"405661115","text":"#coding=utf-8\n\"\"\"blog_test URL Configuration\nThe `urlpatterns` list routes URLs to views. For more information please see:\n https://docs.djangoproject.com/en/1.10/topics/http/urls/\nExamples:\nFunction views\n 1. Add an import: from my_app import views\n 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')\nClass-based views\n 1. Add an import: from other_app.views import Home\n 2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home')\nIncluding another URLconf\n 1. Import the include() function: from django.conf.urls import url, include\n 2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls'))\n\"\"\"\nfrom django.conf.urls import url\nfrom django.contrib import admin\nfrom django.views.static import serve\nfrom feed import LatestEntriesFeed\nfrom blog import views as blog_views\n\nimport config_web as cfg_w\n\nadmin.autodiscover() \nurlpatterns = [\n url(r'^admin/', admin.site.urls),\n url(r'root/(?P.*)$', serve,\n {'document_root': cfg_w.TEMPLATES_PATH}),\n url(r'^account/login/', blog_views.alogin),\n \turl(r'^account/register/', blog_views.register),\n url(r'^account/logout/', blog_views.alogout), \n# url(r'^essay/(?P\\d+)/$',blog_views.essay_details),\n # url(r'^search/$',blog_views.task),\n \t###执行即时任务\n \turl(r'^task1/$',blog_views.task_rpc),\n \t###执行计划任务\n \turl(r'^task2/$',blog_views.task_ntf),\n \t#url(r'^task3/$',blog_views.file_upload),\n \turl(r'^uploadFile/$',blog_views.upload_file),\n \t#url(r'^downloadFile/$',blog_views.download_file),\n \turl(r'^downloadFile/$',blog_views.readFile),\n \turl(r'^updatesrv/$',blog_views.update_srv),\n url(r'^req1/$',blog_views.query_all_srvstatus),\n url(r'^req2/$',blog_views.query_all_tasklist),\n url(r'^req3/$',blog_views.query_all_taskresult),\n url(r'^req4/$',blog_views.query_all_version),\n url(r'^leavemsg/(?P\\d+)/$',blog_views.leave_comment1),\n url(r'^(?P\\d+)/(?P\\d+)/$',blog_views.index),\n url(r'^latest/feed/$', LatestEntriesFeed()),\n url(r'^',blog_views.index),\n]\n","sub_path":"test/home/test/console/mysite/mysite/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":2055,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"107363670","text":"#\n# Skeleton file for the Python \"Bob\" exercise.\n#\n#Bob is a lackadaisical teenager. In conversation, his responses are very limited.\n#\n#Bob answers 'Sure.' if you ask him a question.\n#\n#He answers 'Whoa, chill out!' if you yell at him.\n#\n#He says 'Fine. Be that way!' if you address him without actually saying\n#anything.\n#\n#He answers 'Whatever.' to anything else.\n\ndef hey(what):\n what = what.strip()\n end = len(what)\n if end == 0:\n return \"Fine. Be that way!\"\n if what[end - 1] == \"?\" and end != 0 and not what.isupper():\n return \"Sure.\"\n elif what.isupper():\n return \"Whoa, chill out!\"\n else:\n return \"Whatever.\"\n","sub_path":"all_data/exercism_data/python/bob/12f6b57638834e63afeff21b5952aa19.py","file_name":"12f6b57638834e63afeff21b5952aa19.py","file_ext":"py","file_size_in_byte":664,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"188977131","text":"# -*- coding: utf-8 -*-\nfrom django.db import models\nfrom filebrowser.fields import FileBrowseField\n\nclass Task(models.Model):\n number = models.PositiveIntegerField('br. zadatka', unique=True)\n question = models.TextField('pitanje', max_length=500)\n hint = models.CharField('naputak', max_length=200)\n answer = models.CharField('odgovor', max_length=200, help_text='Više odgovora se odvajaju s /')\n translation = models.CharField('prijevod', max_length=200)\n explanation = models.TextField('objašnjenje', max_length=500)\n\n class Meta:\n ordering = ['number']\n verbose_name = 'zadatak'\n verbose_name_plural = 'zadaci'\n def __unicode__(self):\n return u'%d. %s' % (self.number, self.translation)\n\n\nclass CheatSheet(models.Model):\n name = models.CharField('naziv', max_length=100)\n image = FileBrowseField('slika', max_length=200, directory='relin/cheatsheet/', extensions=['.jpg'], blank=True, null=True)\n\n class Meta:\n ordering = ['name']\n verbose_name = 'tablica'\n verbose_name_plural = 'tablice'\n def __unicode__(self):\n return u'%s' % self.name\n","sub_path":"main/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":1140,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"460478517","text":"#Correct solution:\n#def rotate(string, n):\n# return string[n:] + string[:n]\n\n\nimport collections\n\ndef clean_string(rotated_string):\n other_string = ''\n symbol_check = False\n for i in rotated_string:\n if i=='!':\n other_string += i\n symbol_check = False\n elif i==' ':\n if symbol_check:\n other_string += i\n symbol_check = False\n continue\n symbol_check = True\n elif i.isalpha():\n symbol_check = False\n other_string += i\n return other_string\n\ndef rotate(string, n):\n \"\"\"Rotate characters in a string.\n Expects string and n (int) for number of characters to move.\n \"\"\"\n if n>0:\n sliced_string1 = list(string[n:])\n sliced_string2 = list(string.replace(string[n:], ''))\n rotated_string = str(sliced_string1 + sliced_string2)\n result_string = clean_string(rotated_string)\n elif n<0:\n sliced_string1 = list(string[:n])\n sliced_string2 = list(string.replace(string[:n], ''))\n rotated_string = str(sliced_string2 + sliced_string1)\n result_string = clean_string(rotated_string)\n\n return result_string\n\n\ndef test_small_rotate():\n assert rotate('hello', 2) == 'llohe'\n assert rotate('hello', -2) == 'lohel'\n\nprint(test_small_rotate())\n\ndef test_bigger_rotation_of_positive_n():\n string = 'bob and julian love pybites!'\n expected = 'love pybites!bob and julian '\n assert rotate(string, 15) == expected\n\nprint(test_bigger_rotation_of_positive_n())\n\ndef test_bigger_rotation_of_negative_n():\n string = 'pybites loves julian and bob!'\n expected = 'julian and bob!pybites loves '\n assert rotate(string, -15) == expected\n\nprint(test_bigger_rotation_of_negative_n())\n\ndef test_rotation_of_n_same_as_len_str():\n string = expected = 'julian and bob!'\n assert rotate(string, len(string)) == expected\n\nprint(test_rotation_of_n_same_as_len_str())\n\ndef test_rotation_of_n_bigger_than_string():\n string = 'julian and bob!'\n expected_solution1 = 'julian and bob!'\n expected_solution2 = ' bob!julian and' # ;)\n assert rotate(string, 100) in (expected_solution1,\n expected_solution2)\n\n # should be the same as doing a rotate with modulo\n # which is 100 % 15 (len string) => n=10\n mod = 100 % len(string) # 10\n assert rotate(string, mod) in (expected_solution1,\n expected_solution2)\n\nprint(test_rotation_of_n_bigger_than_string())\n","sub_path":"string_rotation.py","file_name":"string_rotation.py","file_ext":"py","file_size_in_byte":2546,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"271559484","text":"import time\nimport json\nfrom db_operations import *\n\nwhile True:\n isnew = open(\"watched/update.txt\", \"r\")\n bought = int(isnew.read())\n isnew.close()\n \n isnew = open(\"watched/Rupdate.txt\", \"r\")\n returned = int(isnew.read())\n isnew.close()\n \n # if there was an update\n if bought == 1 or returned == 1:\n \n # Read name\n file = open(\"watched/name.txt\", \"r\")\n newName = file.read()\n file.close()\n \n # Read first name\n file = open(\"watched/fname.txt\", \"r\")\n newfName = file.read()\n file.close()\n \n # Read loc\n file = open(\"watched/loc.txt\", \"r\")\n newLoc = file.read()\n file.close()\n \n if bought:\n if newfName == \"\":\n order_id = buy_cup(newName, newLoc)\n else:\n order_id = buy_cup(newName, newLoc, newfName)\n isnew = open(\"watched/update.txt\", \"w\")\n isnew.write(\"0\")\n \n orderfile = open(\"watched/orderid.txt\", \"w\")\n orderfile.write(str(order_id))\n orderfile.close()\n else:\n # Here I assume the order_id is entered as new name\n try:\n return_cup(newName, newLoc)\n except:\n print(\"Return Faultered\")\n isnew = open(\"watched/Rupdate.txt\", \"w\")\n isnew.write(\"0\")\n \n # open update file as write\n \n # close update file\n isnew.close()\n # sleep half second\n time.sleep(0.5)","sub_path":"read.py","file_name":"read.py","file_ext":"py","file_size_in_byte":1567,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"496239927","text":"\"\"\"\nFlaskアプリのメイン部分である。\n\"\"\"\n\nimport base64\nfrom datetime import datetime\nimport hashlib\nimport hmac\nimport json\nimport secrets\nimport sys\n\nfrom flask import Flask, render_template, request, jsonify\nfrom flask_httpauth import HTTPDigestAuth\n\nimport tw\n\n# adminページのユーザ名 & パスワード\nadmin_users = {\n '': ''\n}\n\n# 必要なflaskのインスタンスを作成\napp = Flask(__name__)\napp.config['SECRET_KEY'] = secrets.token_hex(16)\nauth = HTTPDigestAuth()\n\n# ユーザ名を入力し、パスワードを返す\n@auth.get_password\ndef get_pw(username):\n if username in admin_users:\n return admin_users[username]\n return None\n\n@app.route('/')\ndef page_index():\n return render_template('index.html')\n\n# Rate Limitの取得(セキュリティがまだ良くない)\n@app.route('/get-rate-limit', methods=['POST'])\ndef page_get_rate_limit():\n remaining, reset_sec, _ = tw.OAuth.get_rate_limit()\n json_result = {\n 'remaining': remaining,\n 'reset_sec': reset_sec,\n }\n return jsonify(ResultSet=json.dumps(json_result))\n\n# TwitterのCRC(GET)\n@app.route('/webhooks/twitter', methods=['GET'])\ndef twitter_crc():\n if 'crc_token' in request.args and tw.is_from_twitter(request.remote_addr):\n\n # レスポンスの生成\n crc_token = request.args.get('crc_token')\n sha256_hash_digest = hmac.new(tw.api_secret_key.encode(), msg = crc_token.encode(), digestmod = hashlib.sha256).digest()\n response_token = 'sha256=' + base64.b64encode(sha256_hash_digest).decode()\n response = {'response_token': response_token}\n\n return json.dumps(response), 200, {'Content-Type': 'application/json'}\n\n return 'No Content', 200, {'Content-Type': 'text/plain'}\n\n# TwitterからAccount Activityのデータ受信(POST)\n@app.route('/webhooks/twitter', methods=['POST'])\ndef twitter_activity():\n\n # Twitter社からのPOST\n if tw.is_from_twitter(request.remote_addr):\n print('Got data from Twitter!', file=sys.stdout)\n str_data = request.data.decode('utf-8')\n\n # ログファイルの書き込み\n file = open( './log/' + datetime.now().strftime(\"%Y-%m-%d_%H-%M-%S.%f\") + '.log' , 'a')\n file.write(str_data)\n file.close()\n\n # データベースの更新\n tw.DB.parse_and_update_db(str_data)\n\n # Twitter社以外からのPOST(攻撃の可能性あり)\n else:\n print('[!] Got attack from ' + request.remote_addr, file=sys.stdout)\n\n return 'No Content', 200, {'Content-Type': 'text/plain'}\n\nif __name__ == '__main__':\n app.run()\n","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":2602,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"265957352","text":"# coding = utf-8\n\n\nclass Menu:\n def getMenu(config, key):\n data = []\n menus = config.get('MENU')\n keys = key.split('.')\n\n return Menu.getMenuPath(menus, keys, data)\n\n def getMenuPath(menus, keys, data=[], parent_key=''):\n for menu in menus:\n if menu.get('key') in keys:\n if parent_key:\n menu['full_key'] = parent_key + '_' + menu.get('key')\n else:\n menu['full_key'] = menu.get('key')\n data.append(menu)\n if 'submenu' in menu.keys():\n Menu.getMenuPath(menu.get('submenu'), keys, data,\n menu['full_key'])\n\n return data\n\n # 获取key的配置信息\n def getMenuConfig(config, key):\n menu = config.get('MENU')\n keys = key.split('.')\n\n data = []\n for k, v in enumerate(keys):\n if menu.get(v) is None:\n raise Exception(\"配置错误\" + key)\n data.append(menu[v])\n if menu.get(v).get('submenu') is not None:\n menu = menu[v]['submenu']\n\n return data\n","sub_path":"utils/menu.py","file_name":"menu.py","file_ext":"py","file_size_in_byte":1158,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"546349697","text":"for _ in range(int(input())):\n n=int(input())\n a=list(map(int,input().split()))\n c=1\n for i in range(1,n):\n if a[i]<=a[i-1]:\n c+=1\n else:\n a[i]=a[i-1]\n print(c)\n","sub_path":"Carvans.py","file_name":"Carvans.py","file_ext":"py","file_size_in_byte":212,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"466977365","text":"import turtle\n\n\nclass point:\n def __init__(self, x, y):\n self.x = x\n self.y = y\n\n def __add__(self, other):\n return point(abs(self.x + other.intersection), abs(self.y + other.y))\n\n def __sub__(self, other):\n return point(abs(self.x - other.intersection), abs(self.y - other.y))\n\n def midPoint(self, otherPoint):\n return point(int((float(self.x) + otherPoint.intersection) / 2), int((float(self.y) + otherPoint.y) / 2))\n\n\nclass peak:\n def __init__(self, p1, p2, p3):\n self.p1 = p1\n self.p2 = p2\n self.p3 = p3\n\n def drawPeak(self, t):\n t.up()\n t.goto(self.p1.intersection, self.p1.y)\n t.down()\n t.goto(self.p2.intersection, self.p2.y)\n t.goto(self.p3.intersection, self.p3.y)\n\n\ndef randomTriangle(minBase, maxBase, minAngle, maxAngle, ):\n return\n\n\ndef drawPeaks(t, l, h):\n t.pendown()\n oldPeak = l.pop(0)\n for nextPeak in l:\n t.goto(oldPeak.intersection, oldPeak.y)\n tip = oldPeak.midPoint(nextPeak) + point(0, h)\n t.goto(tip.intersection, tip.y)\n oldPeak = nextPeak\n t.goto(nextPeak.intersection, nextPeak.y)\n t.up()\n\n\ndef fractalMountain(t, n, base=50, offeset=50):\n if n == 1:\n return 1\n t.penup()\n print(n)\n l = []\n otherL = []\n for i in range(n + 1):\n otherL.append([base * i + offeset / 2, offeset / 2])\n l.append(point(base * i + offeset / 2, offeset / 2))\n print(otherL)\n t.penup()\n t.goto(l[0].intersection, l[0].y)\n drawPeaks(t, l, offeset)\n return fractalMountain(t, n - 2, base + base / 2.0, offeset + offeset / 2.0)\n\n\ndef newPeak(t, aPeak, direction=\"L\"):\n if direction == \"L\":\n startPoint = aPeak.p2.midPoint(aPeak.p3)\n endPoint = startPoint + point(2 * (aPeak.p3.intersection - startPoint.intersection), 0)\n elif direction == \"R\":\n startPoint = aPeak.p2.midPoint(aPeak.p1)\n endPoint = startPoint + point(2 * (aPeak.p1.intersection - startPoint.intersection), 0)\n tip = aPeak.p3 + point(0, int(aPeak.p2.y * 1.5))\n return peak(startPoint, tip, endPoint)\n\n\ndef newMountain(generations, t, offset=50, base=[0, 0], tip=[25, 25], baseOffset=[50, 0]):\n peaks = []\n\n for num in range(generations * 2 - 1):\n aPeak = peak(point(base[0], base[1]), point(tip[0], tip[1]), point(baseOffset[0], baseOffset[1]))\n peaks.append(aPeak)\n base[0] += offset\n baseOffset[0] += offset\n tip[0] += offset\n # return newMountain(generations-1, t, offset)\n\n return peaks\n\n\ndef peakLayers(t, peaks, newPeaksList):\n if peaks == []:\n return\n thisPeak = peaks.pop()\n thisPeak.drawPeak(t)\n newPeaksList.append(peaks.pop())\n\n\nt = turtle.Turtle()\nt.speed(1)\n# fractalMountain(t, 5)\npeaks = newMountain(3, t)\n\nwn = turtle.Screen()\n\n\n# peak1 = peak(point(0,0), point(25,25), point(50, 0))\n# peak1.drawPeak(t)\n# peak2 = newPeak(t, peak1)\n# peak3 = peak(point(50,0), point(75,25), point(100, 0))\n# peak4 = newPeak(t, peak2, \"R\")\n# peak2.drawPeak(t)\n# peak3.drawPeak(t)\n# peak4.drawPeak(t)\nwn.exitonclick()\n","sub_path":"class demo/fractalMountain.py","file_name":"fractalMountain.py","file_ext":"py","file_size_in_byte":3099,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"395529589","text":"\n# coding: utf-8\n\n# In[1]:\n\nimport time\nfrom time import gmtime, strftime\nimport hmac\nimport hashlib\nimport requests\nimport os\n\n#Prepare variables for API call\ntimestamp = int(time.time())\nkey = '3jtlkaf4ob4twkwb9belnwoovabcj9fi'\nsecret = '81v2xg21rzi08z70'\nbase = r'https://wbanda.filetransfers.net/api/file_search_site?'\nurl = base + 'api_key=' + str(key) + '×tamp=' + str(timestamp)\nhashed_secret = hashlib.sha1(secret.encode()).hexdigest().encode()\nsignature = hmac.new(hashed_secret, url.encode(), hashlib.sha256).hexdigest()\nfinal_url = url + '&signature=' + signature\n\n\n# In[2]:\n\nresponse = requests.get(final_url)\nresponse.raise_for_status()\nresponse_json = response.json()\n\n\n# In[3]:\n\nftpFiles = {}\nfor file in response_json['fileList']['files']: #Iterate through files in JSON response\n fileID = file['id']\n fileName = file['name']\n #filePath = file['path']\n ftpFiles[fileID] = fileName\n\n\n# In[4]:\n\n#Collect existing file names in Documents\ndocsPath = r'S:\\MarketFo\\Short eCSI Raw Data'\n#docsPath = r'C:\\Users\\90012831\\Documents\\eCSI Short Survey Data\\Raw Data'\nexistingFiles = []\nfor folder, subfolder, files in os.walk(docsPath):\n for file in files:\n existingFiles.append(file)\n\n#Check to see if FTP files do not yet exist in documents\ndiffFiles = {}\nfor file in ftpFiles.values():\n if file.endswith('.xlsx'):\n if file not in existingFiles:\n print(f'{file} NOT YET DOWNLOADED.')\n for ID in ftpFiles: # Append fileID and fileName to diff files dictionary\n if ftpFiles[ID] == file:\n diffFiles[ID] = file\n else:\n None\n #print(f'{file} up to date.')\n\n\n# In[5]:\n\n#Prepare log\ntext_file = open(os.path.join(docsPath, \"eCSI Short Survey Data Log.txt\"), \"a\")\n\n#Download each diff file from FTP to Documents\nfor file_id in diffFiles:\n \n #similar api logic to above\n timestamp = int(time.time())\n base = r'https://wbanda.filetransfers.net/api/file_download?'\n url = base + 'api_key=' + str(key) + '&file_id=' + str(file_id) + '×tamp=' + str(timestamp)\n signature = hmac.new(hashed_secret, url.encode(), hashlib.sha256).hexdigest()\n final_url = url + '&signature=' + signature\n\n response = requests.get(final_url) #excel file\n response.raise_for_status()\n \n #Create destination path\n if \"Count\" in diffFiles[file_id]:\n subfolder = \"Harte Hanks counts files\"\n elif \"Data Sample\" in diffFiles[file_id]:\n subfolder = \"daily data files\"\n else:\n subfolder = \"\"\n \n dlFilePath = os.path.join(docsPath, subfolder, diffFiles[file_id])\n \n with open(dlFilePath, 'wb') as handle: #download Excel file to documents\n for block in response.iter_content(1024):\n handle.write(block)\n print(diffFiles[file_id], \"successfully downloaded\")\n \n current_time = strftime(\"%Y-%m-%d %H:%M:%S\", gmtime())\n text_file.write(f'\\nDownloaded {diffFiles[file_id]} on {current_time}')\n \n\nfileCount = len(diffFiles)\n\nprint(\"\")\nprint(f\"{fileCount} files downloaded:\")\nfor item in diffFiles.values():\n print(item)\n \ntext_file.close()\n\ninput(\"Press enter to exit\")\n\n","sub_path":"src/python/projects/eCSI Short Survey/1-Production/Archived py Files/FTP_to_S_Drive_Transfer.py","file_name":"FTP_to_S_Drive_Transfer.py","file_ext":"py","file_size_in_byte":3191,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"13690863","text":"# -*- coding: utf-8 -*-\n\"\"\"\nvgg16_to_rf.py\nVGG16を特徴量抽出器として使ってみる\n抽出した特徴量をrfで学習させる\n\nCreated on Tue Jun 25 21:57:48 2019\n\n@author: eupho\n\"\"\"\n\n\nfrom keras.preprocessing.image import ImageDataGenerator\nfrom sklearn.metrics import confusion_matrix\nfrom keras.callbacks import EarlyStopping\nfrom keras.preprocessing.image import img_to_array, load_img\nfrom keras.models import Model, Sequential\nfrom keras.layers import Dense, Dropout, Flatten, Input, BatchNormalization\nfrom keras.applications.vgg16 import VGG16\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom sklearn.model_selection import train_test_split\nfrom keras import optimizers\nfrom keras.utils import np_utils\nfrom keras import backend as K\nimport os\nimport seaborn as sn\nimport re\nimport itertools\nimport pandas as pd\nfrom sklearn.svm import SVC\nfrom sklearn.ensemble import RandomForestClassifier\nfrom sklearn.metrics import accuracy_score\nfrom sklearn.model_selection import GridSearchCV\n\n\n#サイズを指定\nim_rows = 224\nim_cols = 224\nim_color = 3\nin_shape = (im_rows,im_cols,im_color)\nnb_classes = 9\n\n\n#ImageDataGenerator と 画像を水増しする関数---------------------------------------#\ndatagen = ImageDataGenerator(\n rotation_range=20,\n width_shift_range=0.01,\n height_shift_range=0.01,\n brightness_range=(0.5, 1.0),\n zoom_range=0.2,#拡大縮小\n shear_range=5,#せん断(引き伸ばし)\n channel_shift_range=5,\n horizontal_flip = True,\n vertical_flip = True\n )\n\ndef images_gen(x_list,y_list):\n output_dir = 'test'\n x_list_add = []\n y_list_add = []\n if os.path.isdir(output_dir) == False:\n os.mkdir(output_dir)\n for x ,y in zip(x_list,y_list):#xは(3, width, height)で受け取る\n x = x.reshape((1,) + x.shape) #(1, 3, width, height)に変換する\n \n i = 0\n for batch in datagen.flow(x, batch_size=32, save_to_dir=output_dir, save_prefix='img', save_format='jpg'):\n batch = batch.astype(np.uint8)#データ型を揃える\n batch = batch.reshape((224, 224, 3))\n x_list_add.append(batch)\n y_list_add.append(y)\n i += 1\n if i > 4:#1枚から5枚作る\n break \n x_np_add = np.array(x_list_add)\n y_np_add = np.array(y_list_add)\n \n\n \n return x_np_add,y_np_add\n#------------------------------------------------------------------------------#\n\n\n\n\n#写真データを読み込みの関数--------------------------------------------------------#\ndef list_pictures(directory, ext='jpg|jpeg|bmp|png|ppm'):\n return [os.path.join(root, f)\n for root, _, files in os.walk(directory) for f in files\n if re.match(r'([\\w]+\\.(?:' + ext + '))', f.lower())]\n#------------------------------------------------------------------------------#\n \n \n\nX = []\nY = []\ncount = 0\n\nfilelist = [\"LateolabraxJaponicus_resize_224\",\"LateolabraxLatus_resize_224\",\"LateolabraxMaculatus_resize_224\",\"ThunnusOrientalis_resize_224\",\"ThunnusAlbacares_resize_224\",\"ThunnusTonggol_resize_224\",\"PagrusMajor_resize_224\",\"EvynnisTumifrons_resize_224\",\"DentexHypselosomusBleeker_resize_224\"]\nfor dir in filelist:\n for picture in list_pictures(dir + '/'):\n img = img_to_array(load_img(picture, target_size=(im_rows,im_cols)))\n X.append(img)\n Y.append(count)\n count += 1\n\n\n# arrayに変換\nX = np.asarray(X)\nY = np.asarray(Y)\n\n# 画素値を0から1の範囲に変換\n#X = X.astype('float32')\n#X = X / 255.0 #最大値で割ることでデータを正規化する\n\n# クラスの形式を変換\nY = np_utils.to_categorical(Y, 9)\n\n# 学習用データとテストデータ\nX_train, X_test, y_train, y_test = train_test_split(X, Y, train_size=0.8, random_state=111)\n#inputtensorをかく\n\n\n#trainデータを水増しする\nX_train_add,y_train_add = images_gen(X_train,y_train)\n\n#水増しなし用\n#X_train = X_train.astype(\"float32\")/255\n#X_test = X_test.astype(\"float32\")/255\n\n\nX_train_add2 = np.concatenate([X_train_add, X_train], axis=0)\n\ny_train_add2 = np.concatenate([y_train_add, y_train], axis=0)\n\nX_train_add2 = X_train_add2.astype(\"float32\")/255\nX_test = X_test.astype(\"float32\")/255\n\n#ワンホット表現 → index番号(カテゴリ番号)\ny_train_add2 = np.argmax(y_train_add2,axis=1)\ny_test = np.argmax(y_test,axis=1)\n\n\n\nprint(X_train.shape) \nprint(y_train.shape)\nprint(X_test.shape) \nprint(y_test.shape)\nprint(X_train_add.shape)\nprint(y_train_add.shape)\nprint(X_train_add2.shape)\nprint(y_train_add2.shape)\n\n\n\n\n\n\n\n# Fully-connected層(FC)はいらないのでinclude_top=False)\ninput_tensor = Input(shape=(im_rows, im_cols, 3))\nmodel_vgg16 = VGG16(weights='imagenet', include_top=False, pooling=\"avg\",input_tensor=input_tensor)\nX_train_vgg16 = model_vgg16.predict(X_train_add2)\nX_test_vgg16 = model_vgg16.predict(X_test)\n#特徴量を抽出\n\n\n\nrf = RandomForestClassifier(bootstrap=False, class_weight=None, criterion='gini',\n max_depth=None, max_features=10, max_leaf_nodes=None,\n min_impurity_decrease=0.0, min_impurity_split=None,\n min_samples_leaf=1, min_samples_split=3,\n min_weight_fraction_leaf=0.0, n_estimators=50, n_jobs=None,\n oob_score=False, random_state=None, verbose=0,\n warm_start=False).fit(X_train_vgg16,y_train_add2)\n#print(\"acc = {}\".format(accuracy_score(rf.predict(X_train_vgg16), y_train_add2)))\nprint(\"acc = {}\".format(accuracy_score(rf.predict(X_test_vgg16), y_test)))\n\n\n#混同行列を表示\ndef plot_confusion_matrix(cm, classes,\n normalize=False,\n title='Confusion matrix',\n cmap=plt.cm.Blues):\n\n if normalize:\n cm = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis]\n print(\"Normalized confusion matrix\")\n else:\n print('Confusion matrix, without normalization')\n\n print(cm)\n\n plt.imshow(cm, interpolation='nearest', cmap=cmap)\n plt.title(title)\n plt.colorbar()\n tick_marks = np.arange(len(classes))\n plt.xticks(tick_marks, classes, rotation=45)\n plt.yticks(tick_marks, classes)\n\n fmt = '.2f' if normalize else 'd'\n thresh = cm.max() / 2.\n for i, j in itertools.product(range(cm.shape[0]), range(cm.shape[1])):\n plt.text(j, i, format(cm[i, j], fmt),\n horizontalalignment=\"center\",\n color=\"white\" if cm[i, j] > thresh else \"black\")\n #plt.figure(figsize=(10,10))\n plt.ylabel('True label')\n plt.xlabel('Predicted label')\n plt.tight_layout()\n\n\npreds = rf.predict(X_test_vgg16)\ncm = confusion_matrix(y_test,preds)\nplt.figure(figsize=(6,5))\nplot_confusion_matrix(cm, classes=['0','1','2','3','4','5','6','7','8'],title='Confusion matrix, without normalization')\nplt.savefig('result//cm_rf.png')\nplt.figure(figsize=(6,5))\nplot_confusion_matrix(cm, classes=['0','1','2','3','4','5','6','7','8'], normalize=True,title='Normalized confusion matrix')\nplt.savefig('result//cm_norm_rf.png')\n\n\n\n","sub_path":"vgg16_to_rf.py","file_name":"vgg16_to_rf.py","file_ext":"py","file_size_in_byte":7277,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"19218739","text":"class Solution:\n \"\"\"\n 509. 斐波那契数\n https://leetcode-cn.com/problems/fibonacci-number/\n 斐波那契数,通常用 F(n) 表示,形成的序列称为斐波那契数列。该数列由 0 和 1 开始,后面的每一项数字都是前面两项数字的和。也就是:\n F(0) = 0, F(1) = 1\n F(N) = F(N - 1) + F(N - 2), 其中 N > 1.\n \"\"\"\n cache = {}\n def fib(self, N: int) -> int:\n if N < 2:\n return N\n\n f = 0\n s = 1\n for i in range(2, N+1):\n s = s + f\n f = s - f\n return s\n\n # 递归\n def fibByRecursive(self, N: int) -> int:\n if N < 2:\n return N\n\n if N in self.cache:\n return self.cache[N]\n\n res = self.fib(N - 1) + self.fib(N - 2)\n self.cache[N] = res\n return res\n\nso = Solution()\nprint(so.fib(10))\n","sub_path":"dp.fibonacci-number.py","file_name":"dp.fibonacci-number.py","file_ext":"py","file_size_in_byte":872,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"198722166","text":"# Definition for binary tree with next pointer.\nclass TreeLinkNode(object):\n def __init__(self, x):\n self.val = x\n self.left = None\n self.right = None\n self.next = None\n\nclass Solution(object):\n def connect(self, root):\n \"\"\"\n :type root: TreeLinkNode\n :rtype: nothing\n \"\"\"\n if root==None:\n return\n nextlevel=self.getFirstChild(root)\n c=root\n while not nextlevel==None:\n while not c==None:\n if c.left:\n if c.right:\n c.left.next=c.right\n else:\n c.left.next=self.getFirstChild(c.next)\n if c.right:\n c.right.next = self.getFirstChild(c.next)\n c=c.next\n c=nextlevel\n tmp=c\n nextlevel=self.getFirstChild(c)\n\n def getFirstChild(self,root):\n while not root==None:\n if not root.left==None:\n return root.left\n if not root.right==None:\n return root.right\n root=root.next\n return None\n\n\na=TreeLinkNode(1)\nb=TreeLinkNode(2)\nc=TreeLinkNode(3)\na.left=b\na.right=c\nd=TreeLinkNode(4)\ne=TreeLinkNode(5)\nf=TreeLinkNode(6)\ng=TreeLinkNode(7)\n# b.left=d\n# b.right=e\nc.left=f\nc.right=g\ns=Solution()\ns.connect(a)\nprint(\"1\")","sub_path":"117connect.py","file_name":"117connect.py","file_ext":"py","file_size_in_byte":1371,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"500034476","text":"#!/usr/bin/env python\n\"\"\"\nUnit tests for train.py\nRun inside container with:\n$ py.test -f /app/tests/test_train.py -v\n\"\"\"\nimport glob\nimport pytest\nimport pandas\nfrom src import train\n\n\n\"\"\"\"\"\nTests\n\"\"\"\"\"\n\ndef test_compute_confusion_matrix():\n gold_labels = ['__label__NEG', '__label__NEG', '__label__NEG',\n '__label__NEUT', '__label__NEUT', '__label__NEUT',\n '__label__POS', '__label__POS', '__label__POS']\n pred_labels = ['__label__NEG', '__label__NEUT', '__label__POS',\n '__label__NEG', '__label__NEUT', '__label__POS',\n '__label__NEG', '__label__NEUT', '__label__POS']\n\n confusion_matrix = train.compute_confusion_matrix(gold_labels, pred_labels)\n\n labels = '__label__NEG __label__NEUT __label__POS'.split()\n expected = pandas.DataFrame(index=labels)\n for label in labels:\n expected[label] = 1\n\n assert confusion_matrix.equals(expected)\n\n\ndef test_skip_training(monkeypatch):\n def mock_glob_return_false(filename):\n return False\n def mock_glob_return_true(filename):\n return True\n\n monkeypatch.setattr(glob, 'glob', mock_glob_return_true)\n assert train.skip_training('given-preprocessed-file-name')\n\n monkeypatch.setattr(glob, 'glob', mock_glob_return_false)\n assert not train.skip_training('given-preprocessed-file-name')\n\n\ndef test_evaluate_test_set():\n \"\"\"\n Uses FastText model.test() and print_confusion_matrix()\n \"\"\"\n pass\n","sub_path":"tests/test_train.py","file_name":"test_train.py","file_ext":"py","file_size_in_byte":1475,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"349895265","text":"import os\r\nfrom PIL import Image\r\nimport pickle\r\nimport torch.utils.data as data\r\nfrom torch.utils.data import DataLoader\r\nfrom torchvision import transforms\r\nimport numpy as np\r\nimport torch\r\nimport util.util\r\n\r\n# def create_parsing_dict(root):\r\n# parsing_dict = {}\r\n# for i in range(len(images)):\r\n# parsing_dict[images[i]] = '{}/{}.png'.format(root, i)\r\n# return parsing_dict\r\n\r\n\r\n\r\ndef read_pkl(root):\r\n file = open(root, 'rb')\r\n content = pickle.load(file)\r\n file.close()\r\n return content\r\n\r\ndef open_txt(path):\r\n content = []\r\n with open(path, 'r') as f: \r\n for line in f.readlines():\r\n line=line.strip('\\n')\r\n content.append(line) \r\n return content\r\n\r\n\r\ndef default_loader(path):\r\n return Image.open(path).convert('RGB')\r\n\r\n\r\ndef make_dataset(dir):\r\n images = []\r\n assert os.path.isdir(dir), '%s is not a valid directory' % dir\r\n\r\n for root, _, fnames in sorted(os.walk(dir)):\r\n for fname in fnames:\r\n if is_image_file(fname):\r\n path = os.path.join(root, fname)\r\n images.append(path)\r\n\r\n return images\r\n\r\n\r\n\r\nclass ImageDataset(data.Dataset):\r\n\r\n def __init__(self, opt, transform=None, loader=default_loader):\r\n images = read_pkl(opt.imgls_root)#\r\n\r\n pairs = read_pkl(opt.pairs_root)# root = 'img_list/train_pairs.pkl' or 'img_list/test_pairs.pkl'\r\n if len(pairs) == 0:\r\n raise(RuntimeError(\"Found 0 images in: \" + opt.pairs_root + \"\\n\"\r\n \"Supported image extensions are: \" +\r\n \",\".join(IMG_EXTENSIONS)))\r\n\r\n self.opt = opt\r\n self.images = images\r\n self.pairs = pairs\r\n self.transform = transform\r\n self.loader = loader\r\n\r\n def __getitem__(self, index):\r\n # load image\r\n if not self.opt.test_single_img:\r\n img_pair = self.pairs[index]\r\n img_path_a = img_pair[0]\r\n img_path_b = img_pair[1]\r\n else:\r\n img_path_a = self.opt.test_img_a\r\n img_path_b = self.opt.test_img_b\r\n img_a = self.loader(img_path_a)\r\n img_b = self.loader(img_path_b)\r\n # load corresponding parsing\r\n parsing_path_a = '{}/{}.pkl'.format(self.opt.parsing_root, self.images.index(img_path_a))\r\n parsing_path_b = '{}/{}.pkl'.format(self.opt.parsing_root, self.images.index(img_path_b))\r\n parsing_a = read_pkl(parsing_path_a)#(h,w,c)\r\n parsing_b = read_pkl(parsing_path_b)\r\n # load corresponding heatmap\r\n heatmap_path_a = '{}/pose{}.pkl'.format(self.opt.heatmap_root, self.images.index(img_path_a))\r\n heatmap_path_b = '{}/pose{}.pkl'.format(self.opt.heatmap_root, self.images.index(img_path_b))\r\n pose_info_a = read_pkl(heatmap_path_a)#(c,h,w)\r\n pose_info_b = read_pkl(heatmap_path_b)\r\n joints_a = util.util.compute_coordinate(pose_info_a)\r\n joints_b = util.util.compute_coordinate(pose_info_b)\r\n\r\n\r\n heatmap_a = util.util.get_heatmap(joints_a, self.opt.image_height, self.opt.image_width)\r\n heatmap_b = util.util.get_heatmap(joints_b, self.opt.image_height, self.opt.image_width)\r\n \r\n #print('parsing_mask:',np.shape(parsing_a))#(n,h,w,c)\r\n \r\n parsing_a = torch.from_numpy(np.array(parsing_a)).long().squeeze(3)\r\n parsing_b = torch.from_numpy(np.array(parsing_b)).long().squeeze(3)\r\n #print('before:', parsing_a.size())\r\n parsing_a = util.util.onehot_encoding(parsing_a, 20).squeeze(0)\r\n parsing_b = util.util.onehot_encoding(parsing_b, 20).squeeze(0)\r\n\r\n\r\n if self.transform is not None:\r\n img_a = self.transform(img_a)\r\n img_b = self.transform(img_b)\r\n\r\n heatmap_a = torch.from_numpy(heatmap_a).float() # [0,1]\r\n heatmap_b = torch.from_numpy(heatmap_b).float()\r\n\r\n img_path_a = img_path_a.replace('/','_')\r\n img_path_b = img_path_b.replace('/', '_')\r\n #print(heatmap_a.size())\r\n #print(parsing_a.size())\r\n return {'img': img_a, 'heatmap': heatmap_a, 'parsing': parsing_a, 'img_path': img_path_a}, {'img': img_b, 'heatmap': heatmap_b, 'parsing': parsing_b, 'img_path': img_path_b}\r\n\r\n def __len__(self):\r\n return len(self.pairs)\r\n\r\n def name(self):\r\n return 'ImageDataset'\r\n\r\n\r\nclass DatasetLoader():\r\n def __init__(self, opt):\r\n self.opt = opt\r\n transform_list = [transforms.ToTensor(),\r\n transforms.Normalize((0.5, 0.5, 0.5),\r\n (0.5, 0.5, 0.5))]\r\n transform = transforms.Compose(transform_list)\r\n \r\n self.dataset = ImageDataset(opt=opt, transform=transform)\r\n self.dataloader = DataLoader(\r\n self.dataset,\r\n batch_size=opt.batchSize,\r\n shuffle=not opt.serial_batches,\r\n num_workers=int(opt.nThreads))\r\n\r\n def load_data(self):\r\n return self.dataloader\r\n\r\n def __len__(self):\r\n return len(self.dataset)\r\n ################\r\n def get_dataset(self):\r\n return self.dataset\r\n\r\n\r\n\r\n\r\n# def get_all_data_loaders(new_size=None, height=256, width=256, crop=False, opt):\r\n# transform_list = [transforms.ToTensor(),\r\n# transforms.Normalize((0.5, 0.5, 0.5),\r\n# (0.5, 0.5, 0.5))]\r\n# transform_list = [transforms.RandomCrop((height, width))] + transform_list if crop else transform_list\r\n# transform_list = [transforms.Resize(new_size)] + transform_list if new_size is not None else transform_list\r\n# test_transform = transforms.Compose(transform_list)\r\n# transform_list = [transforms.RandomHorizontalFlip()] + transform_list\r\n# train_transform = transforms.Compose(transform_list)\r\n\r\n# train_dataset = ImageFolder(opt.trainpairs_root, transform=train_transform, opt=opt)\r\n# test_dataset = ImageFolder(opt.testpairs_root, transform=test_transform, opt=opt)\r\n\r\n# train_loader = DataLoader(dataset=train_dataset, batch_size=opt.batch_size, shuffle=True, drop_last=True, num_workers=opt.num_workers)\r\n# test_loader = DataLoader(dataset=test_dataset, batch_size=opt.batch_size, shuffle=False, drop_last=True, num_workers=opt.num_workers)\r\n# return train_loader, test_loader\r\n\r\n\r\n\r\n","sub_path":"data.py","file_name":"data.py","file_ext":"py","file_size_in_byte":6328,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"261777105","text":"import pytest\n\nfrom ops.model import ActiveStatus, BlockedStatus, WaitingStatus\nfrom ops.testing import Harness\nimport yaml\n\nfrom charm import CoreDNSCharm\n\n\nif yaml.__with_libyaml__:\n _DefaultDumper = yaml.CSafeDumper\nelse:\n _DefaultDumper = yaml.SafeDumper\n\n\n@pytest.fixture\ndef harness():\n return Harness(CoreDNSCharm)\n\n\ndef test_not_leader(harness):\n harness.begin()\n assert isinstance(harness.charm.model.unit.status, WaitingStatus)\n\n\ndef test_missing_image(harness):\n harness.set_leader(True)\n harness.begin_with_initial_hooks()\n assert isinstance(harness.charm.model.unit.status, BlockedStatus)\n\n\ndef test_main(harness):\n harness.set_leader(True)\n harness.add_oci_resource('coredns-image', {\n 'registrypath': 'coredns/coredns:1.6.7',\n 'username': '',\n 'password': '',\n })\n harness.begin_with_initial_hooks()\n assert isinstance(harness.charm.model.unit.status, ActiveStatus)\n # confirm that we can serialize the pod spec\n yaml.dump(harness.get_pod_spec(), Dumper=_DefaultDumper)\n","sub_path":"tests/unit/test_charm.py","file_name":"test_charm.py","file_ext":"py","file_size_in_byte":1051,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"469468914","text":"#\tCalculate weighter rating based on averate rating and number of votes.\r\n#\tProblems with simple metrics-\r\n#\t\tMean rating will favour new movies with very few votes.\r\n#\t\tTotal rating will favour old movies with lots of poor votes.\r\n\r\n# Formula for weighted rating-\r\n#\t\t(v / (v+m)) * R + (m / (v+m)) * C\r\n#\r\n#\t\tv is the number of votes received by the movie.\r\n#\t\tm is the minimum votes required to be listed. Using 90 percentile score.\r\n#\t\tR is the average rating given to the movie.\r\n#\t\tC is the average rating received by all movies in the dataset. Average R.\r\n\r\n# Combine required dataset\r\n\r\nratingdata=pd.read_csv('ratings.csv')\r\nmoviedata=pd.read_csv('movies.csv')\r\n\r\nratingdata.head(50)\r\n#\tSorted by user id then movie id.\r\n#\tRatings between 1-5\r\n\r\nmoviedata['totalRating'] = 0.0\r\nmoviedata['numVotes'] = 0\r\n\r\n#\tUse movie id as index temporarly.\r\nmoviedata.reset_index(inplace=True)\t# Save the index as a column.\r\nmoviedata.set_index('movieId', inplace=True)\r\n\r\ndef collectRatings() :\r\n\tfor i in ratingdata.index :\r\n\t\tmovieId = ratingdata.at[i, 'movieId']\r\n\t\tmoviedata.at[movieId, 'totalRating'] += ratingdata.at[i, 'rating']\r\n\t\tmoviedata.at[movieId, 'numVotes'] += 1\r\n\t\t\r\ncollectRatings()\r\n\r\n# Assign original index.\r\nmoviedata.reset_index(inplace=True)\r\nmoviedata.set_index('index', inplace=True)\r\n\r\n#\tCalculate mean ratings.\r\nmoviedata.totalRating = moviedata.totalRating / moviedata.numVotes\r\nmoviedata.rename(columns={'totalRating' : 'meanRating'}, inplace=True)\r\n\r\n#\tTake m as the 90 percentile value.\r\n#\tI.e. votes received by a movie that has more votes than 90 percent movies in the dataset.\r\nminReqVotes = moviedata.numVotes.quantile(0.9)\r\nmoviedata.to_csv('rated_movies.csv')\r\n\r\n#\tFilter out movies with minimum required votes.\r\nmoviedata = moviedata.loc[moviedata.numVotes > minReqVotes]\r\nmoviedata.shape\r\n#\t\t883 movies left.\r\n\r\n#\tC will be average of average ratings.\r\nC = moviedata.meanRating.mean()\r\n\r\n# Calculate weighted rating\r\nmoviedata['score'] = 0.0\r\nm = minReqVotes\r\nv = moviedata.numVotes\r\nR = moviedata.meanRating\r\nmoviedata.score = (v / (v + m)) * R + (m / (v + m)) * C\r\n\r\n#\tRecommend 15 movies.\r\nmoviedata.sort_values(by='score', ascending=False, inplace=True)\r\nmoviedata.head(15)[['title', 'meanRating', 'numVotes', 'score']]\r\n\r\n# Separate the year from title.\r\nfor i in moviedata.index :\r\n\tmoviedata.at[i, 'year'] = int(moviedata.at[i, 'title'][-5:-1])\r\n\tmoviedata.at[i, 'title'] = moviedata.at[i, 'title'][0:-7]\r\n\r\nmoviedata.to_csv('simple_recommendations.csv', index=False)","sub_path":"Movie Recommender System/Simple Recommender.py","file_name":"Simple Recommender.py","file_ext":"py","file_size_in_byte":2508,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"266858587","text":"import tkinter as tk\nimport tkinter.filedialog as fd\nimport webbrowser\nfrom configparser import ConfigParser\nfrom pathlib import Path\nfrom re import compile\nfrom tkinter import font as tkfont\nfrom tkinter import ttk\n\nfrom csvhandler import handle\nfrom dbupdater import update_database\n\n\nclass Application(tk.Tk):\n \"\"\"Main class for GUI application.\"\"\"\n\n def __init__(self, *args, **kwargs):\n tk.Tk.__init__(self, *args, **kwargs)\n self.geometry('450x460')\n self.title('InfiPLANNER project generator')\n\n self.container = tk.Frame(self)\n\n self.frames = {}\n for page in (MainPage, SettingsPage, HelpPage, AboutPage):\n page_name = page.__name__\n frame = page(parent=self.container, controller=self)\n self.frames[page_name] = frame\n frame.grid(row=0, column=0, sticky='nsew')\n\n self.menu_main = tk.Menu(self)\n self.config(menu=self.menu_main)\n\n self.menu_file = tk.Menu(self.menu_main, tearoff=0)\n self.menu_file.add_command(label='Main page', command=lambda: self.show_frame('MainPage'))\n self.menu_file.add_command(label='Exit', command=self.destroy)\n\n self.menu_settings = tk.Menu(self.menu_main, tearoff=0)\n self.menu_settings.add_command(label='General', command=lambda: self.show_frame('SettingsPage'))\n\n self.menu_help = tk.Menu(self.menu_main, tearoff=0)\n self.menu_help.add_command(label='Help', command=lambda: self.show_frame('HelpPage'))\n self.menu_help.add_command(label='About', command=lambda: self.show_frame('AboutPage'))\n\n self.menu_main.add_cascade(label='File', menu=self.menu_file)\n self.menu_main.add_cascade(label='Settings', menu=self.menu_settings)\n self.menu_main.add_cascade(label='Help', menu=self.menu_help)\n\n self.gui()\n\n def gui(self):\n \"\"\"Show GUI (Window).\"\"\"\n\n self.container.pack(side='top', fill='both', expand=True)\n self.container.grid_rowconfigure(0, weight=1)\n self.container.grid_columnconfigure(0, weight=1)\n\n self.show_frame('MainPage')\n\n def show_frame(self, page_name):\n \"\"\"Show a frame for the given page name\"\"\"\n\n frame = self.frames[page_name]\n frame.tkraise()\n\n\nclass MainPage(tk.Frame):\n \"\"\"Main Page.\"\"\"\n\n def __init__(self, parent, controller):\n tk.Frame.__init__(self, parent)\n self.controller = controller\n\n self.font_lbl = tkfont.Font(family='Arial', size=12, weight='bold')\n self.font_result = tkfont.Font(family='Arial', size=15, weight='bold')\n self.font_btn = tkfont.Font(family='Arial', size=15, weight='bold')\n\n self.var_csv_path = tk.StringVar()\n\n self.frame = tk.Frame(self)\n\n self.info_lbl = tk.Label(self, text='Please upload a CSV file and click Start to continue', font=self.font_lbl)\n self.csv_upl_btn = tk.Button(self, text='Upload file', width=30, height=3,\n command=self.upload_file, font=self.font_btn)\n self.csv_path_txt = tk.Text(self, wrap='word', width=30, height=3, bg='Gray94', relief='flat')\n self.csv_path_txt.config(state='disabled')\n self.start_btn = tk.Button(self, text='Start', width=30, height=5,\n command=self.generate_project, font=self.font_btn)\n self.start_txt = tk.Text(self, wrap='word', width=30, height=3, bg='Gray94',\n relief='flat', font=self.font_result)\n self.start_txt.config(state='disabled')\n self.gui()\n\n def gui(self):\n \"\"\"Show GUI (Window).\"\"\"\n\n self.info_lbl.pack(fill='x', padx=10, pady=10)\n self.csv_upl_btn.pack(padx=10, pady=10)\n self.csv_path_txt.pack(padx=10, pady=10)\n self.start_txt.pack(padx=10, pady=10)\n self.start_btn.pack(side='bottom', padx=30, pady=30)\n self.frame.pack()\n\n self.grid()\n\n def upload_file(self):\n \"\"\"Set path to the xlsx file.\"\"\"\n\n self.var_csv_path.set(fd.askopenfilename(defaultextension='.csv',\n filetypes=(('CSV', '*.csv'), ('All files', '*.*'))))\n self.csv_path_txt.config(state='normal')\n self.csv_path_txt.delete('0.0', 'end')\n self.csv_path_txt.insert('0.0', f'{self.var_csv_path.get()}')\n self.csv_path_txt.tag_add('center', '0.0', 'end')\n self.csv_path_txt.tag_config('center', justify='center')\n self.csv_path_txt.config(state='disabled')\n\n def generate_project(self):\n \"\"\"Start csvhandler.\"\"\"\n try:\n handle(Path(self.var_csv_path.get()))\n self.start_txt.config(state='normal', fg='green')\n self.start_txt.delete('0.0', 'end')\n self.start_txt.insert('0.0', f'Project has been successfully generated')\n self.start_txt.tag_add('center', '0.0', 'end')\n self.start_txt.tag_config('center', justify='center')\n self.start_txt.config(state='disabled')\n except:\n self.start_txt.config(state='normal', fg='red')\n self.start_txt.delete('0.0', 'end')\n self.start_txt.insert('0.0', f'Error')\n self.start_txt.tag_add('center', '0.0', 'end')\n self.start_txt.tag_config('center', justify='center')\n self.start_txt.config(state='disabled')\n\n\nclass SettingsPage(tk.Frame):\n \"\"\"Settings Page.\"\"\"\n\n def __init__(self, parent, controller):\n tk.Frame.__init__(self, parent)\n self.controller = controller\n\n self.font_bold = tkfont.Font(size=10, weight='bold')\n\n self.cfg = ConfigParser(comment_prefixes='/', allow_no_value=True)\n self.cfg_path = Path('config.ini')\n self.cfg.read(self.cfg_path)\n\n # Global settings variables\n self.var_region = tk.StringVar(value=self.cfg.get('Settings', 'region'))\n\n self.var_weigh_xg1000 = tk.IntVar(value=self.cfg.get('Settings', 'weight_xg1000'))\n self.var_weigh_xg500 = tk.IntVar(value=self.cfg.get('Settings', 'weight_xg500'))\n self.var_weigh_quanta = tk.IntVar(value=self.cfg.get('Settings', 'weight_quanta'))\n self.var_weigh_e5000 = tk.IntVar(value=self.cfg.get('Settings', 'weight_e5000'))\n self.var_weigh_r5000_pro = tk.IntVar(value=self.cfg.get('Settings', 'weight_r5000_pro'))\n self.var_weigh_r5000_lite = tk.IntVar(value=self.cfg.get('Settings', 'weight_r5000_lite'))\n self.var_weigh_excl = tk.IntVar(value=self.cfg.get('Settings', 'weight_exclude'))\n\n # Project settings variables\n self.var_pr_req_freq = tk.IntVar(value=self.cfg.get('Project', 'req_freq'))\n self.var_pr_req_bw = tk.IntVar(value=self.cfg.get('Project', 'req_bw'))\n self.var_pr_req_cap = tk.IntVar(value=self.cfg.get('Project', 'req_cap'))\n self.var_pr_req_avb = tk.StringVar(value=self.cfg.get('Project', 'req_avb'))\n self.var_pr_req_excl = tk.StringVar(value=self.cfg.get('Project', 'req_exclude'))\n self.var_pr_req_excl_xg1000 = tk.BooleanVar()\n self.var_pr_req_excl_xg500 = tk.BooleanVar()\n self.var_pr_req_excl_quanta = tk.BooleanVar()\n self.var_pr_req_excl_e5000 = tk.BooleanVar()\n self.var_pr_req_excl_r5000_pro = tk.BooleanVar()\n self.var_pr_req_excl_r5000_lite = tk.BooleanVar()\n self.text_to_var()\n\n # Database settings variables\n if self.cfg.get('Database', 'db_path') == 'default':\n self.var_db_path = tk.StringVar(value=(Path.cwd() / 'devices.db'))\n self.var_db_fld_chng = tk.BooleanVar(value=False)\n else:\n self.var_db_path = tk.StringVar(value=Path(self.cfg.get('Database', 'db_path')))\n self.var_db_fld_chng = tk.BooleanVar(value=True)\n\n if self.cfg.get('Database', 'xls_path') == 'default':\n self.var_xls_path = tk.StringVar(value=(Path.cwd() / 'devices.xlsx'))\n self.var_xls_chng = tk.BooleanVar(value=False)\n else:\n self.var_xls_path = tk.StringVar(value=Path(self.cfg.get('Database', 'xls_path')))\n self.var_xls_chng = tk.BooleanVar(value=True)\n\n # Output settings variables\n if self.cfg.get('Output', 'output_folder') == 'default':\n self.var_out_fld_path = tk.StringVar(value=(Path.cwd() / 'Output'))\n self.var_out_fld_chng = tk.BooleanVar(value=False)\n else:\n self.var_out_fld_path = tk.StringVar(value=Path(self.cfg.get('Output', 'output_folder')))\n self.var_out_fld_chng = tk.BooleanVar(value=True)\n\n if self.cfg.get('Output', 'kmz_name') == 'default':\n self.var_out_kmz = tk.StringVar(value='default')\n else:\n self.var_out_kmz = tk.StringVar(value=Path(self.cfg.get('Output', 'kmz_name')))\n\n if self.cfg.get('Output', 'bom_name') == 'default':\n self.var_out_bom = tk.StringVar(value='default')\n else:\n self.var_out_bom = tk.StringVar(value=Path(self.cfg.get('Output', 'bom_name')))\n\n # Left indent\n self.empty_lbl_1 = tk.Label(self, text=' ')\n\n # Global settings widgets\n self.set_gb_lbl = tk.Label(self, text='Global settings', font=self.font_bold)\n self.set_gb_weigh_xg1000_lbl = tk.Label(self, text='Weight XG 1000')\n self.set_gb_weigh_xg500_lbl = tk.Label(self, text='Weight XG')\n self.set_gb_weigh_quanta_lbl = tk.Label(self, text='Weight Quanta')\n self.set_gb_weigh_e5000_lbl = tk.Label(self, text='Weight Evolution')\n self.set_gb_weigh_r5000_pro_lbl = tk.Label(self, text='Weight R5000 Pro')\n self.set_gb_weigh_r5000_lite_lbl = tk.Label(self, text='Weight R5000 Lite')\n self.set_gb_weigh_excl_lbl = tk.Label(self, text='Weight Exclude')\n self.set_gb_region_lbl = tk.Label(self, text='Region')\n\n self.set_gb_weigh_xg1000_ent = tk.Entry(self, textvariable=self.var_weigh_xg1000, width=15)\n self.set_gb_weigh_xg_ent = tk.Entry(self, textvariable=self.var_weigh_xg500, width=15)\n self.set_gb_weigh_quanta_ent = tk.Entry(self, textvariable=self.var_weigh_quanta, width=15)\n self.set_gb_weigh_e5000_ent = tk.Entry(self, textvariable=self.var_weigh_e5000, width=15)\n self.set_gb_weigh_r5000_pro_ent = tk.Entry(self, textvariable=self.var_weigh_r5000_pro, width=15)\n self.set_gb_weigh_r5000_lite_ent = tk.Entry(self, textvariable=self.var_weigh_r5000_lite, width=15)\n self.set_gb_weigh_excl_ent = tk.Entry(self, textvariable=self.var_weigh_excl, width=15)\n self.region_list = ['rus', 'eng']\n self.set_gb_region_cmbx = ttk.Combobox(self, values=self.region_list, textvariable=self.var_region, width=12)\n\n # Delimeter between Global and Project\n self.empty_lbl_2 = tk.Label(self, text=' ')\n\n # Project settings\n self.set_pr_lbl = tk.Label(self, text='Project settings', font=self.font_bold)\n self.set_pr_req_freq_lbl = tk.Label(self, text='Frequency range')\n self.set_pr_req_bw_lbl = tk.Label(self, text='Bandwidth')\n self.set_pr_req_cap_lbl = tk.Label(self, text='Capacity')\n self.set_pr_req_avb_lbl = tk.Label(self, text='Availability')\n self.set_pr_req_exclude_lbl = tk.Label(self, text='Exclude devices')\n\n self.freq_list = [3, 4, 5, 6, 70]\n self.set_pr_req_freq_cmbx = ttk.Combobox(self, values=self.freq_list,\n textvariable=self.var_pr_req_freq, width=15)\n self.set_pr_req_bw_ent = tk.Entry(self, textvariable=self.var_pr_req_bw, width=18)\n self.set_pr_req_cap_ent = tk.Entry(self, textvariable=self.var_pr_req_cap, width=18)\n self.avb_list = ['99.90', '99.99']\n self.set_pr_req_avb_cmbx = ttk.Combobox(self, values=self.avb_list,\n textvariable=self.var_pr_req_avb, width=15)\n self.set_pr_req_excl_xg1000_chbx = tk.Checkbutton(self, text='XG 1000',\n variable=self.var_pr_req_excl_xg1000)\n self.set_pr_req_excl_xg_chbx = tk.Checkbutton(self, text='XG',\n variable=self.var_pr_req_excl_xg500)\n self.set_pr_req_excl_quanta_chbx = tk.Checkbutton(self, text='Quanta',\n variable=self.var_pr_req_excl_quanta)\n self.set_pr_req_excl_e5000_chbx = tk.Checkbutton(self, text='Evolution',\n variable=self.var_pr_req_excl_e5000)\n self.set_pr_req_excl_r5000_pro_chbx = tk.Checkbutton(self, text='R5000 Pro',\n variable=self.var_pr_req_excl_r5000_pro)\n self.set_pr_req_excl_r5000_lite_chbx = tk.Checkbutton(self, text='R5000 Lite',\n variable=self.var_pr_req_excl_r5000_lite)\n\n # Database settings\n self.set_db_lbl = tk.Label(self, text='Database settings', font=self.font_bold)\n self.set_db_fld_lbl = tk.Label(self, text='Database file')\n self.set_db_btn = tk.Button(self, text='Choose', command=self.choose_db_fld, width=12, height=1)\n self.set_db_txt = tk.Text(self, wrap='word', width=25, height=3, bg='Gray94', relief='flat')\n self.set_db_txt.insert('0.0', f'{self.var_db_path.get()}')\n self.set_db_txt.config(state='disable')\n self.set_xls_fld_lbl = tk.Label(self, text='XLS file')\n self.set_xls_btn = tk.Button(self, text='Choose', command=self.choose_xls, width=12, height=1)\n self.set_xls_txt = tk.Text(self, wrap='word', width=25, height=3, bg='Gray94', relief='flat')\n self.set_xls_txt.insert('0.0', f'{self.var_xls_path.get()}')\n self.set_xls_txt.config(state='disable')\n self.set_db_upd_btn = tk.Button(self, text='Update database', command=self.update_db, width=16, height=1)\n\n # Output settings\n self.set_out_lbl = tk.Label(self, text='Output settings', font=self.font_bold)\n self.set_out_fld_lbl = tk.Label(self, text='Output folder')\n self.set_out_btn = tk.Button(self, text='Set', command=self.choose_out_fld, width=12, height=1)\n self.set_out_txt = tk.Text(self, wrap='word', width=25, height=3, bg='Gray94', relief='flat')\n self.set_out_txt.insert('1.0', f'{self.var_out_fld_path.get()}')\n self.set_out_txt.config(state='disable')\n self.set_out_kmz_lbl = tk.Label(self, text='KMZ name')\n self.set_out_kmz_ent = tk.Entry(self, textvariable=self.var_out_kmz, width=18)\n self.set_out_bom_lbl = tk.Label(self, text='BOM name')\n self.set_out_bom_ent = tk.Entry(self, textvariable=self.var_out_bom, width=18)\n\n # Save button\n self.save_btn = tk.Button(self, text='Save', width=16, command=self.save)\n\n self.gui()\n\n def gui(self):\n \"\"\"Show GUI (SettingsPage).\"\"\"\n\n # Left indent\n self.empty_lbl_1.grid(column=0, row=0, sticky='w')\n\n # Global settings widgets\n self.set_gb_lbl.grid(column=1, row=0, sticky='w', columnspan=2, padx=2, pady=2)\n self.set_gb_weigh_xg1000_lbl.grid(column=1, row=1, sticky='w', padx=2, pady=2)\n self.set_gb_weigh_xg500_lbl.grid(column=1, row=2, sticky='w', padx=2, pady=2)\n self.set_gb_weigh_quanta_lbl.grid(column=1, row=3, sticky='w', padx=2, pady=2)\n self.set_gb_weigh_e5000_lbl.grid(column=1, row=4, sticky='w', padx=2, pady=2)\n self.set_gb_weigh_r5000_pro_lbl.grid(column=1, row=5, sticky='w', padx=2, pady=2)\n self.set_gb_weigh_r5000_lite_lbl.grid(column=1, row=6, sticky='w', padx=2, pady=2)\n self.set_gb_weigh_excl_lbl.grid(column=1, row=7, sticky='w', padx=2, pady=2)\n self.set_gb_region_lbl.grid(column=1, row=8, sticky='w', padx=2, pady=2)\n\n self.set_gb_weigh_xg1000_ent.grid(column=2, row=1, sticky='w')\n self.set_gb_weigh_xg_ent.grid(column=2, row=2, sticky='w')\n self.set_gb_weigh_quanta_ent.grid(column=2, row=3, sticky='w')\n self.set_gb_weigh_e5000_ent.grid(column=2, row=4, sticky='w')\n self.set_gb_weigh_r5000_pro_ent.grid(column=2, row=5, sticky='w')\n self.set_gb_weigh_r5000_lite_ent.grid(column=2, row=6, sticky='w')\n self.set_gb_weigh_excl_ent.grid(column=2, row=7, sticky='w')\n self.set_gb_region_cmbx.grid(column=2, row=8, sticky='w')\n\n # Delimeter between Global and Project\n self.empty_lbl_2.grid(column=3, row=0, sticky='w')\n\n # Project settings\n self.set_pr_lbl.grid(column=4, row=0, sticky='w', columnspan=2, padx=2, pady=2)\n self.set_pr_req_freq_lbl.grid(column=4, row=1, sticky='w', padx=2, pady=2)\n self.set_pr_req_bw_lbl.grid(column=4, row=2, sticky='w', padx=2, pady=2)\n self.set_pr_req_cap_lbl.grid(column=4, row=3, sticky='w', padx=2, pady=2)\n self.set_pr_req_avb_lbl.grid(column=4, row=4, sticky='w', padx=2, pady=2)\n self.set_pr_req_exclude_lbl.grid(column=4, row=5, sticky='w', padx=2, pady=2)\n\n self.set_pr_req_freq_cmbx.grid(column=5, row=1, sticky='w', columnspan=2, padx=2, pady=2)\n self.set_pr_req_bw_ent.grid(column=5, row=2, sticky='w', columnspan=2, padx=2, pady=2)\n self.set_pr_req_cap_ent.grid(column=5, row=3, sticky='w', columnspan=2, padx=2, pady=2)\n self.set_pr_req_avb_cmbx.grid(column=5, row=4, sticky='w', columnspan=2, padx=2, pady=2)\n self.set_pr_req_excl_xg1000_chbx.grid(column=4, row=6, sticky='w')\n self.set_pr_req_excl_xg_chbx.grid(column=4, row=7, sticky='w')\n self.set_pr_req_excl_quanta_chbx.grid(column=4, row=8, sticky='w')\n self.set_pr_req_excl_e5000_chbx.grid(column=5, row=6, sticky='w')\n self.set_pr_req_excl_r5000_pro_chbx.grid(column=5, row=7, sticky='w')\n self.set_pr_req_excl_r5000_lite_chbx.grid(column=5, row=8, sticky='w')\n\n # Database settings\n self.set_db_lbl.grid(column=1, row=9, sticky='w', columnspan=2, padx=2, pady=2)\n self.set_db_fld_lbl.grid(column=1, row=10, sticky='w', padx=2, pady=2)\n self.set_db_btn.grid(column=2, row=10, sticky='e', padx=2, pady=2)\n self.set_db_txt.grid(column=1, row=11, sticky='nsew', columnspan=2, rowspan=3, padx=2, pady=2)\n self.set_db_lbl.grid(column=1, row=9, sticky='w', padx=2, pady=2)\n self.set_xls_fld_lbl.grid(column=1, row=15, sticky='w', padx=2, pady=2)\n self.set_xls_btn.grid(column=2, row=15, sticky='w', padx=2, pady=2)\n self.set_xls_txt.grid(column=1, row=16, sticky='nsew', columnspan=2, rowspan=3, padx=2, pady=2)\n self.set_db_upd_btn.grid(column=1, row=20, sticky='w', columnspan=2, padx=2, pady=2)\n\n # Output settings\n self.set_out_lbl.grid(column=4, row=9, sticky='w', columnspan=2, padx=2, pady=2)\n self.set_out_fld_lbl.grid(column=4, row=10, sticky='w', padx=2, pady=2)\n self.set_out_btn.grid(column=5, row=10, sticky='e', padx=2, pady=2)\n self.set_out_txt.grid(column=4, row=11, sticky='nsew', columnspan=2, rowspan=3, padx=2, pady=2)\n self.set_out_kmz_lbl.grid(column=4, row=15, sticky='w', padx=2, pady=2)\n self.set_out_kmz_ent.grid(column=5, row=15, sticky='w', padx=2, pady=2)\n self.set_out_bom_lbl.grid(column=4, row=16, sticky='w', padx=2, pady=2)\n self.set_out_bom_ent.grid(column=5, row=16, sticky='w', padx=2, pady=2)\n\n # Save button\n self.save_btn.grid(column=4, row=20, sticky='e', columnspan=2, padx=2, pady=2)\n\n self.grid()\n\n def choose_db_fld(self):\n \"\"\"Set path to the database.\"\"\"\n\n self.var_db_path.set(fd.askopenfilename(defaultextension='.db',\n filetypes=(('DB', '*.db'),\n ('JSON', '*.json'),\n ('All files', '*.*'))))\n self.set_db_txt.config(state='normal')\n self.set_db_txt.delete('0.0', 'end')\n self.set_db_txt.insert('0.0', f'{self.var_db_path.get()}')\n self.set_db_txt.config(state='disabled')\n self.var_db_fld_chng.set(True)\n\n def choose_out_fld(self):\n \"\"\"Set path to the output folder.\"\"\"\n\n self.var_out_fld_path.set(fd.askdirectory())\n self.set_out_txt.config(state='normal')\n self.set_out_txt.delete('0.0', 'end')\n self.set_out_txt.insert('0.0', f'{self.var_out_fld_path.get()}')\n self.set_out_txt.config(state='disabled')\n self.var_out_fld_chng.set(True)\n\n def choose_xls(self):\n \"\"\"Set path to the xlsx file.\"\"\"\n\n self.var_xls_path.set(fd.askopenfilename(defaultextension='.xlsx',\n filetypes=(('XLSX', '*.xlsx'),\n ('XLS', '*.xls'),\n ('All files', '*.*'))))\n self.set_xls_txt.config(state='normal')\n self.set_xls_txt.delete('0.0', 'end')\n self.set_xls_txt.insert('0.0', f'{self.var_xls_path.get()}')\n self.set_xls_txt.config(state='disabled')\n self.var_xls_chng.set(True)\n\n def text_to_var(self):\n \"\"\"Get req_exclude variable and parse it.\"\"\"\n\n # Patterns for var_pr_req_excl\n self.pattern_xg1000 = compile(r'(xg1000)')\n self.pattern_xg500 = compile(r'(xg500)')\n self.pattern_quanta = compile(r'(quanta)')\n self.pattern_e5000 = compile(r'(e5000)')\n self.pattern_r5000_pro = compile(r'(r5000_pro)')\n self.pattern_r5000_lite = compile(r'(r5000_lite)')\n\n if self.pattern_xg1000.search(self.var_pr_req_excl.get().lower()) is not None:\n self.var_pr_req_excl_xg1000.set(True)\n if self.pattern_xg500.search(self.var_pr_req_excl.get().lower()) is not None:\n self.var_pr_req_excl_xg500.set(True)\n if self.pattern_quanta.search(self.var_pr_req_excl.get().lower()) is not None:\n self.var_pr_req_excl_quanta.set(True)\n if self.pattern_e5000.search(self.var_pr_req_excl.get().lower()) is not None:\n self.var_pr_req_excl_e5000.set(True)\n if self.pattern_r5000_pro.search(self.var_pr_req_excl.get().lower()) is not None:\n self.var_pr_req_excl_r5000_pro.set(True)\n if self.pattern_r5000_lite.search(self.var_pr_req_excl.get().lower()) is not None:\n self.var_pr_req_excl_r5000_lite.set(True)\n\n def var_to_text(self):\n \"\"\"Get exlclude variables and make req_exclude.\"\"\"\n\n self.temp_var_pr_req_excl = []\n if self.var_pr_req_excl_xg1000.get() is True:\n self.temp_var_pr_req_excl.append('xg1000')\n if self.var_pr_req_excl_xg500.get() is True:\n self.temp_var_pr_req_excl.append('xg500')\n if self.var_pr_req_excl_quanta.get() is True:\n self.temp_var_pr_req_excl.append('quanta')\n if self.var_pr_req_excl_e5000.get() is True:\n self.temp_var_pr_req_excl.append('e5000')\n if self.var_pr_req_excl_r5000_pro.get() is True:\n self.temp_var_pr_req_excl.append('r5000_pro')\n if self.var_pr_req_excl_r5000_lite.get() is True:\n self.temp_var_pr_req_excl.append('r5000_lite')\n if len(self.temp_var_pr_req_excl) == 0:\n self.temp_var_pr_req_excl.append('none')\n return ', '.join(self.temp_var_pr_req_excl)\n\n def update_db(self):\n \"\"\"Update database (dbupdater.py).\"\"\"\n\n try:\n self.db_upd_ok_lbl = tk.Label(self, text='OK', fg='green', font=self.font_bold)\n self.db_upd_error_lbl = tk.Label(self, text='ERROR', fg='red', font=self.font_bold)\n\n update_database(self.var_db_path.get(), self.var_xls_path.get())\n\n self.db_upd_error_lbl.grid_forget()\n self.db_upd_ok_lbl.grid(column=2, row=20, sticky='e', padx=2, pady=2)\n except:\n self.db_upd_ok_lbl.grid_forget()\n self.db_upd_error_lbl.grid(column=2, row=20, sticky='e', padx=2, pady=2)\n\n def save(self):\n \"\"\"Save configuration file (config.ini).\"\"\"\n\n try:\n self.db_save_ok_lbl = tk.Label(self, text='OK ', fg='green', font=self.font_bold)\n self.db_save_error_lbl = tk.Label(self, text='ERROR', fg='red', font=self.font_bold)\n\n # Set global settings\n if self.var_region.get() in ['rus', 'eng']:\n self.cfg.set('Settings', 'region', self.var_region.get())\n else:\n raise\n\n self.cfg.set('Settings', 'weight_xg1000', str(self.var_weigh_xg1000.get()))\n self.cfg.set('Settings', 'weight_xg500', str(self.var_weigh_xg500.get()))\n self.cfg.set('Settings', 'weight_quanta', str(self.var_weigh_quanta.get()))\n self.cfg.set('Settings', 'weight_quanta_70', str(self.var_weigh_quanta.get()))\n self.cfg.set('Settings', 'weight_e5000', str(self.var_weigh_e5000.get()))\n self.cfg.set('Settings', 'weight_r5000_pro', str(self.var_weigh_r5000_pro.get()))\n self.cfg.set('Settings', 'weight_r5000_lite', str(self.var_weigh_r5000_lite.get()))\n self.cfg.set('Settings', 'weight_exclude', str(self.var_weigh_excl.get()))\n\n # Set project settings\n if self.var_pr_req_freq.get() in [3, 4, 5, 6, 70]:\n self.cfg.set('Project', 'req_freq', str(self.var_pr_req_freq.get()))\n else:\n raise\n\n if self.var_pr_req_bw.get() > 0:\n self.cfg.set('Project', 'req_bw', str(self.var_pr_req_bw.get()))\n else:\n raise\n\n if self.var_pr_req_cap.get() > 0:\n self.cfg.set('Project', 'req_cap', str(self.var_pr_req_cap.get()))\n else:\n raise\n\n if self.var_pr_req_avb.get() in ['99.90', '99.99']:\n self.cfg.set('Project', 'req_avb', self.var_pr_req_avb.get())\n else:\n raise\n\n self.cfg.set('Project', 'req_exclude', self.var_to_text())\n\n # Set database settings\n if self.var_db_fld_chng.get() is False or len(self.var_db_path.get()) == 0:\n self.cfg.set('Database', 'db_path', 'default')\n else:\n self.cfg.set('Database', 'db_path', self.var_db_path.get())\n\n if self.var_xls_chng.get() is False or len(self.var_xls_path.get()) == 0:\n self.cfg.set('Database', 'xls_path', 'default')\n else:\n self.cfg.set('Database', 'xls_path', self.var_xls_path.get())\n\n # Output settings\n if self.var_out_fld_chng.get() is False or len(self.var_out_fld_path.get()) == 0:\n self.cfg.set('Output', 'output_folder', 'default')\n else:\n self.cfg.set('Output', 'output_folder', self.var_out_fld_path.get())\n\n self.cfg.set('Output', 'kmz_name', self.var_out_kmz.get())\n self.cfg.set('Output', 'bom_name', self.var_out_bom.get())\n\n with open(self.cfg_path, 'w') as config_file:\n self.cfg.write(config_file)\n\n self.db_save_error_lbl.grid_forget()\n self.db_save_ok_lbl.grid(column=4, row=20, sticky='w', padx=2, pady=2)\n except:\n self.db_save_ok_lbl.grid_forget()\n self.db_save_error_lbl.grid(column=4, row=20, sticky='w', padx=2, pady=2)\n\n\nclass HelpPage(tk.Frame):\n\n def __init__(self, parent, controller):\n tk.Frame.__init__(self, parent)\n self.controller = controller\n\n self.font_help_txt = tkfont.Font(family='Arial', size=8)\n self.font_help_err = tkfont.Font(family='Arial', size=10, weight='bold')\n\n self.var_readme_path = Path.cwd() / 'readme.txt'\n self.var_help_txt = tk.StringVar()\n\n self.frame = tk.Frame(self)\n\n self.gui()\n\n def gui(self):\n \"\"\"Show GUI (HelpPage).\"\"\"\n\n try:\n if self.var_readme_path.is_file() is True:\n with open(self.var_readme_path, 'r') as self.readme_text:\n self.var_help_txt = ''.join(self.readme_text.readlines())\n else:\n raise\n\n self.help_txt = tk.Text(self, wrap='word', font=self.font_help_txt)\n self.help_txt.insert('0.0', f'{self.var_help_txt}')\n self.help_txt.config(state='disable')\n self.help_scrl = tk.Scrollbar(self, command=self.help_txt.yview)\n self.help_scrl.pack(side='right', fill='y')\n self.help_txt.pack(side='top', expand='yes', fill='both', padx=1, pady=1)\n self.frame.pack()\n except:\n self.help_err_lbl = tk.Label(self, text='Help file missing', fg='red', font=self.font_help_err)\n self.help_err_lbl.pack(anchor='center', fill='both', expand='yes')\n self.frame.pack()\n\n self.grid()\n\nclass AboutPage(tk.Frame):\n\n def __init__(self, parent, controller):\n tk.Frame.__init__(self, parent)\n self.controller = controller\n\n self.font_info = tkfont.Font(family='Arial', size=12)\n self.font_other = tkfont.Font(family='Arial', size=10)\n\n self.frame = tk.Frame(self)\n\n # General information\n self.info_lbl = tk.Label(self, text='InfiPLANNER project generator v 1.0.0', font=self.font_info)\n self.info_link_lbl = tk.Label(self, text='www.infiplanner.infinetwireless.com',\n fg='blue', cursor='hand2', font=self.font_other)\n\n self.info_link_lbl.bind('', lambda x: self.callback(r'https://infiplanner.infinetwireless.com/'))\n\n # Contacts\n self.contacts_lbl = tk.Label(self, text=f'If you have any questions, don\\'t hesitate to contact '\n f'me:\\r\\ni.demchuk@infinet.ru', font=self.font_other)\n\n self.gui()\n\n def gui(self):\n \"\"\"Show GUI (AboutPage).\"\"\"\n\n self.info_lbl.pack(side='top', fill='x')\n self.info_link_lbl.pack(side='top', fill='x')\n self.contacts_lbl.pack(side='bottom', fill='x')\n self.frame.pack()\n\n self.grid()\n\n def callback(self, url):\n webbrowser.open_new(url)\n\n\nif __name__=='__main__':\n app = Application()\n app.mainloop()\n","sub_path":"gui.py","file_name":"gui.py","file_ext":"py","file_size_in_byte":30212,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"419954553","text":"from libs.consumer import Consumer\nfrom .messages import Message\nimport logging\n\nclass Alert(Consumer):\n \"\"\"\n Consumes a queue of alerts. Sends an email message to the\n specified user.\n \"\"\"\n\n def handle(self, items):\n for email, matches in items.iteritems():\n alert = Message(email, 'Feed Alert - Found A Match')\n alert.build_template(\n 'main_alert.html',\n matches=matches\n )\n alert.send()\n\n","sub_path":"alerts/alerts.py","file_name":"alerts.py","file_ext":"py","file_size_in_byte":487,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"147403874","text":"import threading\nimport time\nimport unittest\nimport uuid\n\nimport redis\n\nONE_WEEK_IN_SECONDS = 7 * 86400\nVOTE_SCORE = 432\nARTICLES_PER_PAGE = 25\nclient = redis.Redis(host='127.0.0.1', port=6379)\n\n\ndef publisher(n):\n time.sleep(1)\n for i in range(n):\n client.publish('channel', i)\n time.sleep(1)\n\n\ndef run_pubsub():\n threading.Thread(target=publisher, args=(3,)).start()\n pubsub = client.pubsub()\n pubsub.subscribe(['channel'])\n count = 0\n for item in pubsub.listen():\n print(item)\n count += 1\n if count == 4:\n pubsub.unsubscribe()\n if count == 5:\n break\n\n\ndef add_to_cart(conn, session, item, count):\n if count <= 0:\n conn.hrem('cart:' + session, item)\n else:\n conn.hset('cart:' + session, item, count)\n\n\ndef update_token_using_set(conn, token, user, item=None):\n timestamp = time.time()\n conn.hset('login:', token, user)\n conn.zadd('recent:', {token: timestamp})\n if item:\n conn.zadd('viewed:' + token, {item: timestamp})\n conn.zremrangebyrank('viewed:' + token, 0, -26)\n\n\n# \ndef update_token_using_list(conn, token, user, item=None):\n timestamp = time.time()\n conn.hset('login:', token, user)\n conn.zadd('recent:', token, timestamp)\n if item:\n key = 'viewed:' + token\n conn.lrem(key, item)\n conn.rpush(key, item)\n conn.ltrim(key, -25, -1)\n conn.zincrby('viewed:', item, -1)\n\n\n# \n\nclass TestCh03(unittest.TestCase):\n def setUp(self):\n import redis\n self.conn = redis.Redis(db=15)\n\n def test_update_token_using_set(self):\n conn = self.conn\n token = str(uuid.uuid4())\n update_token_using_set(conn, token, 'username', 'itemX')\n print(\"And add an item to the shopping cart\")\n add_to_cart(conn, token, \"itemY\", 3)\n\n # def test_update_token_using_list(self):\n\n\nif __name__ == '__main__':\n # unittest.main()\n run_pubsub()\n","sub_path":"chapter3/listing_source.py","file_name":"listing_source.py","file_ext":"py","file_size_in_byte":2025,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"6461479","text":"import os\r\nimport sys\r\nimport threading\r\nimport progressbar\r\nfrom Classes.Driver import Driver\r\nfrom internal import Internal\r\n\r\ncwd = os.path.dirname(sys.executable) if hasattr(sys, 'frozen') else os.path.dirname(os.path.realpath(sys.argv[0]))\r\nthread = threading.current_thread()\r\nsuspectFunctions = [\"MmMapIoSpace\", \"MmUnmapIoSpace\", \"MmGetPhysicalAddress\", \"ZwMapViewOfSection\", \"MmGetSystemRoutineAddress\", \"MmMapIoSpaceEx\"]\r\n\r\ndef GetDriverInfo(path, file):\r\n thread = threading.current_thread()\r\n driver = Driver(path, file)\r\n if not driver.haveDevice:\r\n setattr(thread, \"driver\", False)\r\n return\r\n for func in suspectFunctions:\r\n if not func in driver.content:\r\n continue\r\n driver.IncreaseSeverity(1)\r\n setattr(thread, \"driver\", driver)\r\n return\r\n\r\n\r\nos.system(\"cls\")\r\nos.system(\"title Possible Vulnerable Driver Tracker\")\r\n\r\nprint(\"Possible Vulnerable Driver Tracker\\n\\t\\tBy M47Z\\n\")\r\n\r\nsearchDir = os.path.abspath(input(\"Directory To Search: \"))\r\n\r\nos.system(\"cls\")\r\n\r\nwith progressbar.ProgressBar(max_value=Internal.CountFilesByExtension(searchDir, \".sys\")) as bar:\r\n print(\"[+] Searching For All Possible Vulnerable Drivers\\n\")\r\n setattr(thread, \"progress\", 0)\r\n setattr(thread, \"bar\", bar)\r\n driversList = Internal.GetAllDriversInPath(searchDir, GetDriverInfo, thread)\r\n\r\nif not os.path.isdir(\"\\\\\".join((cwd, \"result\"))):\r\n os.mkdir(\"\\\\\".join((cwd, \"result\")))\r\n\r\nfor file in os.listdir(\"\\\\\".join((cwd, \"result\"))):\r\n os.remove(\"\\\\\".join((cwd, \"result\", file)))\r\n\r\nfor i in range(1, len(suspectFunctions) + 1):\r\n filteredDriverList = list(filter(lambda driver: driver.severity == i, driversList))\r\n if not len(filteredDriverList) > 0:\r\n continue\r\n file = open(\"\\\\\".join((cwd, \"result\", \".\".join((str(i), \"txt\")))), \"w\")\r\n for driver in filteredDriverList:\r\n file.write(\"{}\\n\".format((\"\" if driver.path[len(driver.path) - 1:] == \"\\\\\" else \"\\\\\").join((driver.path, driver.name)), \"\"))\r\n file.close()\r\n\r\nprint(\"\\n\\nPress Any Key to Exit\")\r\nos.system(\"pause>nul\")\r\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2078,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"186130105","text":"import sys\nimport math\nsys.path.append('../')\nimport stddraw\nimport random\n\nfrom sys import stdin\nfrom ioutils import read_floats\n\n\ndef indexOfFloatInterval(lo, hi, n, val):\n \"Tells where val falls in the interval [lo, hi] subdivided by n\"\n if not lo <= val <= hi:\n return -1\n if lo == val: \n return 0\n if hi == val:\n return n-1\n delta = (hi - lo)/n\n val_ = val - lo\n return math.floor(val_/delta)\n\ndef histogram(array, lo, hi, n):\n hist = [0] * n\n for val in array:\n index = indexOfFloatInterval(lo, hi, n, val)\n if index >= 0:\n hist[index] += 1\n return hist\n\n\n\n\nif __name__ == \"__main__\":\n lo = float(sys.argv[1])\n hi = float(sys.argv[2])\n n = int(sys.argv[3])\n stddraw.setXscale(0, n)\n stddraw.setYscale(0, n+1)\n\n array = read_floats()\n hist = histogram(array, lo, hi, n)\n print(hist)\n for i, val in enumerate(hist):\n stddraw.setPenColor(stddraw.RED)\n stddraw.filledRectangle(i,0,1,val)\n stddraw.setPenColor(stddraw.BLACK)\n stddraw.rectangle(i,0,1,val)\n stddraw.show()\n","sub_path":"histogram.py","file_name":"histogram.py","file_ext":"py","file_size_in_byte":1106,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"249372895","text":"import os\n\nimport build_kaniko as builder\n\n\ndef build_base_image(\n repo_dir: str,\n oci_path: str,\n version_label: str,\n):\n dockerfile_relpath = os.path.join(repo_dir, \"docker\", \"build-image\", \"Dockerfile\")\n print(f'repo_dir is: {repo_dir}')\n\n docker_dirs = ['build', 'build-deb', 'build-image']\n\n for docker_dir in docker_dirs:\n dockerfile_relpath = os.path.join(repo_dir, \"docker\", docker_dir, \"Dockerfile\")\n print(f'---Building now {dockerfile_relpath}')\n build_base_image = 'debian:testing-slim'\n if docker_dir == 'build-deb':\n build_base_image = f'{oci_path}/gardenlinux-build:{version_label}'\n else:\n build_base_image = 'debian:testing-slim'\n context_dir = os.path.join(repo_dir, \"docker\", docker_dir)\n print(f'---Using base image {build_base_image}')\n builder.build_and_push_kaniko(\n dockerfile_path=dockerfile_relpath,\n context_dir=context_dir,\n image_push_path=f'{oci_path}/gardenlinux-{docker_dir}',\n image_tag=version_label,\n additional_tags=['latest'],\n build_args=[f'build_base_image={build_base_image}']\n )\n","sub_path":"ci/steps/build_base_image.py","file_name":"build_base_image.py","file_ext":"py","file_size_in_byte":1192,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"224943980","text":"# Plotting-related code\n\nimport math\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport matplotlib.ticker as ticker\nfrom mpl_toolkits.axes_grid1 import make_axes_locatable\nfrom matplotlib.patches import Ellipse\nfrom skimage.measure import profile_line\n\n\ndef Binomial( n, n_tot, nsigma=1.0, conf_level=None, method=\"wilson\" ):\n\t\"\"\"Computes fraction (aka frequency or rate) of occurances p = (n/n_tot).\n\tAlso computes the lower and upper confidence limits using either the \n\tWilson (1927) or Agresti & Coull (1998) method (method=\"wilson\" or method=\"agresti\");\n\tdefault is to use Wilson method.\n\tDefault is to calculate 68.26895% confidence limits (i.e., 1-sigma in the\n\tGaussian approximation).\n\t\n\tReturns tuple of (p, sigma_minus, sigma_plus).\n\t\"\"\"\n\t\n\tp = (1.0 * n) / n_tot\n\tq = 1.0 - p\n\t\n\tif (conf_level is not None):\n\t\tprint(\"Alternate values of nsigma or conf_limit not yet supported!\")\n\t\talpha = 1.0 - conf_level\n\t\t# R code would be the following:\n\t\t#z_alpha = qnorm(1.0 - alpha/2.0)\n\t\treturn None\n\telse:\n\t\tz_alpha = nsigma # e.g., z_alpha = nsigma = 1.0 for 68.26895% conf. limits\n\t\n\tif (method == \"wald\"):\n\t\t# Wald (aka asymptotic) method -- don't use except for testing purposes!\n\t\tsigma_minus = sigma_plus = z_alpha * np.sqrt(p*q/n_tot)\n\telse:\n\t\tz_alpha2 = z_alpha**2\n\t\tn_tot_mod = n_tot + z_alpha2\n\t\tp_mod = (n + 0.5*z_alpha2) / n_tot_mod\n\t\tif (method == \"wilson\"):\n\t\t\t# Wilson (1927) method\n\t\t\tsigma_mod = np.sqrt(z_alpha2 * n_tot * (p*q + z_alpha2/(4.0*n_tot))) / n_tot_mod\n\t\telif (method == \"agresti\"):\n\t\t\t# Agresti=Coull method\n\t\t\tsigma_mod = np.sqrt(z_alpha2 * p_mod * (1.0 - p_mod) / n_tot_mod)\n\t\telse:\n\t\t\tprint(\"ERROR: method \\\"%s\\\" not implemented in Binomial!\" % method)\n\t\t\treturn None\n\t\tp_upper = p_mod + sigma_mod\n\t\tp_lower = p_mod - sigma_mod\n\t\tsigma_minus = p - p_lower\n\t\tsigma_plus = p_upper - p\n\t\n\treturn (p, sigma_minus, sigma_plus)\n\n\n\n# Nicer-looking logarithmic axis labeling\n\ndef niceLogFunc( x_value, pos ):\n\treturn ('{{:.{:1d}f}}'.format(int(np.maximum(-np.log10(x_value),0)))).format(x_value)\t\nNiceLogFormatter = ticker.FuncFormatter(niceLogFunc)\n\ndef MakeNiceLogAxes( whichAxis=\"xy\", axisObj=None ):\n\t\"\"\"\n\tMakes one or more axes of a figure display tick labels using non-scientific\n\tnotation (e.g., \"0.01\" instead of \"10^{-2}\")\n\t\"\"\"\n\t\n\tif axisObj is None:\n\t\tax = plt.gca()\n\telse:\n\t\tax = axisObj\n\tif whichAxis in [\"x\", \"xy\"]:\n\t\tax.xaxis.set_major_formatter(NiceLogFormatter)\n\tif whichAxis in [\"y\", \"xy\"]:\n\t\tax.yaxis.set_major_formatter(NiceLogFormatter)\n\ndef SetAxesObjTickLabelSize( axesObj, fontsize ):\n axesObj.tick_params(axis='both', which='both', labelsize=fontsize)\n\n\n\ndef add_colorbar( mappable, loc=\"right\", size=\"5%\", pad=0.05, label_pad=2,\n tick_label_size=10 ):\n \"\"\"\n Function which adds a colorbar to a \"mappable\" object (e.g., the result of\n calling plt.imshow).\n\n Example:\n img = plt.imshow(somedata, ...)\n add_colorbar(img, ...)\n\n Parameters\n ----------\n mappable : instance of object implementing \"mappable\" interface\n E.g., instance of Image, ContourSet, etc. -- basically any Artist subclass that\n inherits from the ScalarMappable mixin\n https://matplotlib.org/api/cm_api.html\n\n loc : str, optional\n location for colorbar -- one of \"right\", \"left\", \"top\", \"bottom\"\n\n size : str, optional\n relative size for colorbar as fraction of main plot, as a percentage (e.g. \"2%\")\n\n pad : float, optional\n padding between colorbar and main plot\n\n label_pad : str, optional\n padding between colorbar and its tick labels\n\n tick_lable_size : float, optional\n font size for tick labels\n\n Returns\n -------\n cbar : instance of matplotlib.colorbar.Colorbar\n The generated colorbar\n \"\"\"\n if loc in [\"top\", \"bottom\"]:\n orient = \"horizontal\"\n if loc == \"top\":\n tickPos = 'top'\n else:\n tickPos = 'bottom'\n else:\n orient = \"vertical\"\n if loc == \"left\":\n tickPos = 'left'\n else:\n tickPos = 'right'\n ax = mappable.axes\n fig = ax.figure\n divider = make_axes_locatable(ax)\n cbar_axes = divider.append_axes(loc, size=size, pad=pad)\n cbar = fig.colorbar(mappable, cax=cbar_axes, orientation=orient)\n\n # fiddle with tick label locations\n if loc in [\"left\", \"right\"]:\n cbar_axis = cbar_axes.yaxis\n else:\n cbar_axis = cbar_axes.xaxis\n cbar_axis.set_ticks_position(tickPos)\n cbar_axis.set_label_position(tickPos)\n cbar.ax.tick_params(labelsize=tick_label_size, pad=label_pad)\n return cbar\n\n\ndef ExtractCenteredSubimage( imData, xc, yc, pix, width=None, height=None, verbose=False ):\n \"\"\"Extracts and returns a subimage centered at xc,yc, along with \n corresponding x and y position vectors. If width is None, then the full\n image is returned, along with the corresponding pixel vectors.\n \n Parameters\n ----------\n imData : 2D ndarray of int or float\n the input image\n \n xc, yc : float\n image pixel location (1-based coords) to center extraction around\n \n pix : float\n pixel scale (e.g., arcsec/pix)\n \n width : int or None, optional\n width of subimage to extract, in pixels\n if None, then the entire image is returned (along with xPos, yPos)\n \n height : int or None, optional\n height of subimage to extract, in pixels\n if None, then height = width\n\n verbose : bool, optional\n \n Returns\n -------\n (imdata_ext, xPos, yPos) : tuple of (2D ndarray, 1D ndarray, 1D ndarray; all of float)\n imData_ext = extracted subimage centered on xc,yc (or entire image if\n width = None)\n xPos = array of pixel coordinate values for x-axis, relative to xc\n e.g., [-1.0, 0.0, 1.0] for 3x3 image centered at 1,1 with pix=1\n [-0.2, 0.0, 0.2] for 3x3 image centered at 1,1 with pix=0.2\n xPos = array of pixel coordinate values for y-axis, relative to yc\n \"\"\"\n\n ySize, xSize = imData.shape\n xPos = pix*(np.arange(1.0, xSize + 1.0) - xc)\n yPos = pix*(np.arange(1.0, ySize + 1.0) - yc)\n\n if width is not None:\n if height is None:\n height = width\n halfwidth = int(0.5*width)\n x1 = int(xc - halfwidth - 1)\n if (x1 < 0):\n x1 = 0\n x2 = int(xc + halfwidth)\n if (x2 > xSize):\n x2 = -1\n halfheight = int(0.5*height)\n y1 = int(yc - halfheight - 1)\n if (y1 < 0):\n y1 = 0\n y2 = int(yc + halfheight)\n if (y2 > ySize):\n y2 = -1\n xPos = xPos[x1:x2]\n yPos = yPos[y1:y2]\n imdata_ext = imData[y1:y2,x1:x2]\n if verbose:\n print(\" pu.ExtractCenteredSubimage: extracting imData[y1:y2,x1:x2] = imData[%d:%d,%d:%d]\" % (y1,y2,x1,x2))\n else:\n imdata_ext = imData\n \n return (imdata_ext, xPos, yPos)\n\n\ndef nicecont( imageData, xc=0, yc=0, width=None, height=None, levels=None, pix=1.0,\n axisLabel=\"pixels\", title=None, imageExt=0, log=False, offset=0.0, axesObj=None,\n labelSize=12, labelpad=5, printAxisLabels=\"both\", noErase=False, extraLevels=None,\n color='k', extraColor='r', linewidth=0.5, linestyle='-', secondScale=None,\n secondLabel='kpc', verbose=False ):\n \"\"\"\n Function which contour-plots an image.\n \n Parameters\n ----------\n imageData : 2D ndarray or str\n 2D Numpy array OR FITS image filename (image data is assumed to be\n in 0th header-data unit, unless imageExt is set to something else)\n \n xc, yc : int\n optional center for axes (e.g., center of galaxy) -- by default, these\n are assumed to be IRAF-style 1-based coordinates!\n \n width, height : int\n width and height of subimage (centered on xc,yc) to be plotted;\n if height=None, then a square subimage of size width x width will be extracted\n \n levels : sequence (tuple, list, or Numpy array) of float or None, optional\n contour intensity levels to be plotted (if log=True, then these should be \n log10 of the original values)\n \n pix : float, optional\n pixel scale (e.g., arcsec/pix or kpc/pix, for axis labeling)\n \n axisLabel : str, optional\n label for x and y axes\n \n title : str, optional\n title for plot\n \n imageExt = int or str, optional\n specification of a different header-data unit in input FITS image \n (if imageData points to a file)\n \n log : bool, optional\n if True, convert image data to log10(data)\n\n offset : float, optional\n additive offset to be applied to data (*after* taking log10, if requested)\n\n axesObj : instance of matplotlib.axes.Axes, optional\n Axes instance to receive the plotting commands\n\n labelSize : float, optional\n font sizes of x- and y-axis labels\n \n labelpad : float, optional\n shifts position of axis label relative to axis [default=5]\n\n printAxisLabels : str, optional\n [\"both\" or \"xy\", \"x\", \"y\"] -- specifies which, if any, of the\n x- or y-axis labels to print\n\n extraLevels = a list of one or more contour intensity levels to overplot in a\n different color\n\n color = color for the contours\n \n extraColor = color for contours specified by extraLeveles\n\n noErase = set this equal to True to draw the contours into an existing plot\n window without erase things first (only used if axesObj is None)\n\n linewidth = float\n \n linestyle = one of 'solid', 'dashed', 'dashdot', 'dotted'\n \n secondScale = float\n If set, then a second axis scale is drawn (e.g., for pc or kpc)\n value = conversion from original scale (e.g., kpc/arcsec)\n \n secondLabel = str [default = 'kpc']\n label for axis with second scale\n\n Example:\n >>> nicecont(\"image.fits\", xc=202.4, yc=500.72, levels=np.arange(1.0, 20.0, 0.5))\n \"\"\"\n\n # handle case of user supplying a FITS filename\n if type(imageData) == str:\n hdulist = fits.open(imageData)\n imData = hdulist[imageExt].data\n else:\n imData = imageData\n\n if log is True:\n imData = np.log10(imData)\n imData = imData + offset\n\n # determine xPos,yPos and extract centered subimage, if requested\n (imData, xPos, yPos) = ExtractCenteredSubimage(imData, xc, yc, pix, width, height,\n verbose=verbose)\n\n if axesObj is None:\n if noErase is False:\n plt.clf()\n if levels is not None:\n plt.contour(xPos, yPos, imData, levels, colors=color, linewidths=linewidth,\n linestyles=linestyle)\n else:\n plt.contour(xPos, yPos, imData, colors=color, linewidths=linewidth,\n linestyles=linestyle)\n if extraLevels is not None:\n plt.contour(xPos, yPos, imData, extraLevels, colors=extraColor, linewidths=1.0,\n linestyles=linestyle)\n plt.gca().set_aspect('equal')\n if axisLabel is not None:\n if printAxisLabels in [\"both\", \"xy\", \"x\"]:\n plt.xlabel(axisLabel, fontsize=labelSize)\n if printAxisLabels in [\"both\", \"xy\", \"y\"]:\n plt.ylabel(axisLabel, fontsize=labelSize)\n if title is not None:\n plt.title(title)\n\n if secondScale is not None:\n yrange_orig = np.array(plt.ylim())\n yrange_second = yrange_orig * secondScale\n topy = plt.twinx()\n topy.tick_params(axis='y', length=10)\n topy.tick_params(axis='y', length=5, which=\"minor\")\n topy.set_ylim(yrange_second[0], yrange_second[1])\n plt.ylabel(secondLabel, fontsize=labelSize)\n plt.show()\n\n else: # user supplied a matplotlib.axes.Axes object to receive the plotting commands\n if levels is not None:\n axesObj.contour(xPos, yPos, imData, levels, colors=color, linewidths=linewidth,\n linestyles=linestyle)\n else:\n axesObj.contour(xPos, yPos, imData, colors=color, linewidths=linewidth,\n linestyles=linestyle)\n if extraLevels is not None:\n plt.contour(xPos, yPos, imData, extraLevels, colors=extraColor, linewidths=0.75,\n linestyles=linestyle)\n axesObj.set_aspect('equal')\n if axisLabel is not None:\n if printAxisLabels in [\"both\", \"xy\", \"x\"]:\n axesObj.set_xlabel(axisLabel, fontsize=labelSize, labelpad=labelpad)\n if printAxisLabels in [\"both\", \"xy\", \"y\"]:\n axesObj.set_ylabel(axisLabel, fontsize=labelSize, labelpad=labelpad)\n if title is not None:\n axesObj.set_title(title)\n\n if secondScale is not None:\n xrange_orig = np.array(plt.xlim())\n xrange_second = xrange_orig * secondScale\n topx = plt.twiny()\n topx.tick_params(length=10)\n topx.tick_params(length=5, which=\"minor\")\n topx.set_xlim(xrange_second[0], xrange_second[1])\n plt.xlabel(secondLabel, fontsize=labelSize)\n plt.show()\n\n\n\ndef ExtractCenteredSubimage( imData, xc, yc, pix, width=None, height=None, verbose=False ):\n \"\"\"Extracts and returns a subimage centered at xc,yc, along with \n corresponding x and y position vectors. If width is None, then the full\n image is returned, along with the corresponding pixel vectors.\n \n Parameters\n ----------\n imData : 2D ndarray of int or float\n the input image\n \n xc, yc : float\n image pixel location (1-based coords) to center extraction around\n \n pix : float\n pixel scale (e.g., arcsec/pix)\n \n width : int or None, optional\n width of subimage to extract, in pixels\n if None, then the entire image is returned (along with xPos, yPos)\n \n height : int or None, optional\n height of subimage to extract, in pixels\n if None, then height = width\n\n verbose : bool, optional\n \n Returns\n -------\n (imdata_ext, xPos, yPos) : tuple of (2D ndarray, 1D ndarray, 1D ndarray; all of float)\n imData_ext = extracted subimage centered on xc,yc (or entire image if\n width = None)\n xPos = array of pixel coordinate values for x-axis, relative to xc\n e.g., [-1.0, 0.0, 1.0] for 3x3 image centered at 1,1 with pix=1\n [-0.2, 0.0, 0.2] for 3x3 image centered at 1,1 with pix=0.2\n xPos = array of pixel coordinate values for y-axis, relative to yc\n \"\"\"\n\n ySize, xSize = imData.shape\n xPos = pix*(np.arange(1.0, xSize + 1.0) - xc)\n yPos = pix*(np.arange(1.0, ySize + 1.0) - yc)\n\n if width is not None:\n if height is None:\n height = width\n halfwidth = int(0.5*width)\n x1 = int(xc - halfwidth - 1)\n if (x1 < 0):\n x1 = 0\n x2 = int(xc + halfwidth)\n if (x2 > xSize):\n x2 = -1\n halfheight = int(0.5*height)\n y1 = int(yc - halfheight - 1)\n if (y1 < 0):\n y1 = 0\n y2 = int(yc + halfheight)\n if (y2 > ySize):\n y2 = -1\n xPos = xPos[x1:x2]\n yPos = yPos[y1:y2]\n imdata_ext = imData[y1:y2,x1:x2]\n if verbose:\n print(\" pu.ExtractCenteredSubimage: extracting imData[y1:y2,x1:x2] = imData[%d:%d,%d:%d]\" % (y1,y2,x1,x2))\n else:\n imdata_ext = imData\n \n return (imdata_ext, xPos, yPos)\n\n\ndef PlotImage( imageData, xc=0, yc=0, width=None, height=None, zrange=None, cmap=\"jet\",\n pix=1.0, axisLabel=\"pixels\", title=None, imageExt=0, log=False, axesObj=None,\n labelSize=12, tickLabelSize=11, printAxisLabels=\"both\", colorbar=True, colorbarLoc=\"right\", \n colorbarLabel=None, cbarLabelSize=11, cbarTickLabelSize=10, noErase=False ):\n \"\"\"Function which plots an image, along with axis tick marks and labels and\n (optionally) a colorbar.\n \n Parameters\n ----------\n imageData = 2D Numpy array OR FITS image filename (image data is assumed to be\n in 0th header-data unit, unless imageExt is set to something else)\n \n xc, yc : float, optional\n center for axes (e.g., center of galaxy) in 1-based pixel coords\n \n width, height: int, optional\n width and height in pixels of subimage (centered on xc,yc) to be displayed; \n if height=None, then a square subimage of size width x width will be extracted\n \n zrange : 2-element sequence of float, optional\n two-element list/tuple/array containing lower and upper limits of data\n values (values below/above these limits will be clipped to the limits)\n \n cmap: str, optional\n specification of colormap which maps pixel values to on-screen colors;\n default is to use matplotlib's \"jet\" colormap)\n \n pix: float, optional\n arcsec/pixel scale of image (for axis labeling)\n \n axisLabel: str, optional\n label for x and y axes\n \n title: str, optional\n title for plot\n \n imageExt : int or str, optional\n specification of a header-data unit within the input FITS file \n (if imageData points to a file)\n \n log : bool, optional\n if True, then convert image data to log10(data)\n\n axesObj : matplotlib.axes.Axes instance, optional\n Axes instance to receive plotting commands\n \n labelSize : float, optional\n sizes of x- and y-axis labels\n\n printAxisLabels = [\"both\" or \"xy\", \"x\", \"y\"] -- specifies which, if any, of the\n x- or y-axis labels to print\n \n colorbar : bool, optional\n if True (default), then a colorbar is drawn next to the image\n \n colorbarLoc : str or None, optional\n if not None, then this specifies the colorbar location:\n one of [\"top\", \"bottom\", \"left\", \"right\"]\n \n colorbarLabel : str or None, optional\n if not None, then this is the label for the colorbar\n \n cbarLabelSize : float, optional\n font size for colorbar label\n \n cbarTickLabelSize : float, optional\n font size for colorbar tick labels\n \n noErase : bool, optional\n If true *and* axesObj is None (standard plotting to separate figure), then\n cf() is *not* called first. If axesObj is not None, then this is ignored\n (we assume user wants to draw image on top of pre-existing stuff)\n\n Returns\n -------\n axesImg : instance of matplotlib.image.AxesImage\n \n \n Example:\n >>> PlotImage(\"image.fits\", xc=202.4, yc=500.72))\n \"\"\"\n\n # handle case of user supplying a FITS filename\n if type(imageData) == str:\n hdulist = fits.open(imageData)\n imData = hdulist[imageExt].data\n else:\n imData = imageData\n if log is True:\n imData = np.log10(imData)\n\n # determine xPos,yPos and extract centered subimage, if requested\n (imData, xPos, yPos) = ExtractCenteredSubimage(imData, xc, yc, pix, width, height, verbose=False)\n\n # define x-axis and y-axis ranges for labeling purposes\n xtent = np.array([xPos[0], xPos[-1], yPos[0], yPos[-1]])\n\n zmin = zmax = None\n if zrange is not None:\n if log is True:\n zmin = math.log10(zrange[0])\n zmax = math.log10(zrange[1])\n else:\n zmin = zrange[0]\n zmax = zrange[1]\n\n if cbarLabelSize is None:\n cbarLabelSize = labelSize\n\n if axesObj is None:\n if noErase is False:\n plt.clf()\n axesImg = plt.imshow(imData, interpolation=\"nearest\", origin=\"lower\", extent=xtent,\n vmin=zmin, vmax=zmax, aspect=\"equal\", cmap=cmap)\n if tickLabelSize is not None:\n # axesImg is an AxesImage object, so we have to query its ax() method to\n # get the proper Axes object\n axesObj = axesImg.axes\n SetAxesObjTickLabelSize(axesObj, tickLabelSize)\n if axisLabel is not None:\n if printAxisLabels in [\"both\", \"xy\", \"x\"]:\n print(\"hi there!\")\n plt.xlabel(axisLabel, fontsize=labelSize)\n if printAxisLabels in [\"both\", \"xy\", \"y\"]:\n plt.ylabel(axisLabel, fontsize=labelSize)\n if title is not None:\n plt.title(title)\n if colorbar is True:\n ax = plt.gca()\n cbar = add_colorbar(axesImg, loc=colorbarLoc, size=\"5%\", pad=0.05, label_pad=2,\n tick_label_size=cbarTickLabelSize)\n cbar.solids.set_edgecolor(\"face\") # Remove gaps in PDF http://stackoverflow.com/a/15021541\n if colorbarLabel is not None:\n cbar.set_label(colorbarLabel, fontsize=cbarLabelSize)\n plt.sca(ax) # Activate main plot before returning\n\n else:\n axesImg = axesObj.imshow(imData, interpolation=\"nearest\", origin=\"lower\", extent=xtent,\n vmin=zmin, vmax=zmax, aspect=\"equal\", cmap=cmap)\n if tickLabelSize is not None:\n SetAxesObjTickLabelSize(axesObj, tickLabelSize)\n if axisLabel is not None:\n if printAxisLabels in [\"both\", \"xy\", \"x\"]:\n axesObj.set_xlabel(axisLabel, fontsize=labelSize)\n if printAxisLabels in [\"both\", \"xy\", \"y\"]:\n axesObj.set_ylabel(axisLabel, fontsize=labelSize)\n if title is not None:\n axesObj.set_title(title)\n if colorbar is True:\n cbar = add_colorbar(axesImg, loc=colorbarLoc, size=\"5%\", pad=0.05, label_pad=2,\n tick_label_size=cbarTickLabelSize)\n cbar.solids.set_edgecolor(\"face\") # Remove gaps in PDF http://stackoverflow.com/a/15021541\n if colorbarLabel is not None:\n cbar.set_label(colorbarLabel, fontsize=cbarLabelSize)\n plt.sca(axesObj) # Activate main plot before returning\n\n return axesImg\n\n\n\ndef DrawPALine( PA, radius, fmt='g-', color=None, linewidth=1.0, xc=0.0, yc=0.0,\n addDots=False, dot_ms=6, alpha=1.0, axesObj=None ):\n \"\"\"Given a pre-existing plot, draws a line passing through the central\n coordinates (by default, center = 0,0 in data coordinates) at PA = PA\n relative to *+y axis*, with radius = radius.\n\n PA = position angle CCW from +y axis\n radius = radial length of line (data units)\n fmt = matplotlib format string for line\n color = optional color specification\n linewidth = matplotlib linewidth specification\n xc, yc = coordinates for center of line (data units)\n addDots = if True, small circles are drawn at either end of the line\n dot_ms = markersize value for dots (if addDots is True)\n axesObj = optional matplotlib.axes object, specifying which axes gets\n the ellipse drawn into it\n \"\"\"\n\n if (PA < 0) or (PA > 180):\n print(\"PA must lie between 0 and 180 degrees!\")\n return None\n PA_x = -PA\n dx = radius * math.sin(math.radians(PA_x))\n dy = radius * math.cos(math.radians(PA_x))\n vertical = False\n if (dx == 0.0):\n vertical = True\n else:\n slope = dy/dx\n xx = [xc + dx, xc - dx]\n yy = [yc + dy, yc - dy]\n\n if axesObj is None:\n ax = plt.gca()\n else:\n ax = axesObj\n \n if color is None:\n color = fmt[0]\n linestyle = fmt[1]\n if vertical:\n axvline(xc, color=color, linestyle=linestyle, linewidth=linewidth, alpha=alpha)\n else:\n ax.axline((xc,yc), slope=slope, color=color, linestyle=linestyle, linewidth=linewidth, alpha=alpha)\n if addDots is True:\n ax.plot(xx,yy, color + \"o\", ms=dot_ms, alpha=alpha)\n\n\ndef DrawEllipse( PA, a, ell, edgecolor='g', linestyle='-', linewidth=1.0, fillColor=None,\n alpha=1.0, xc=0.0, yc=0.0, axesObj=None ):\n \"\"\"Given a pre-existing plot, draws an ellipse with semi-major axis a and\n ellipticity ell, with major axis at PA = PA relative to +y-axis,\n centered on coordinates (xc,yc) (by default, = 0,0 in data coordinates).\n\n PA = position angle CCW from +y axis\n a = semi-major axis of ellipse (data units)\n ell = ellipticity (1 - b/a) of ellipse\n edgecolor = color for ellipse outline\n linestyle, linewidth = matplotlib specification for ellipse outline\n fillColor = if not None, then the ellipse is filled using the\n specified color\n fmt = matplotlib format string for line\n color = optional color specification\n linewidth = matplotlib linewidth specification\n xc, yc = coordinates for center of line (data units)\n xc, yc = coordinates for center of ellipse (data units)\n axesObj = optional matplotlib.axes object, specifying which axes gets\n the ellipse drawn into it\n \"\"\"\n\n if axesObj is None:\n ax = plt.gca()\n else:\n ax = axesObj\n b = (1 - ell)*a\n if fillColor is None:\n faceColor = 'None'\n else:\n faceColor = fillColoir\n ellPatch = Ellipse((xc,yc), 2*b, 2*a, angle=PA, facecolor=faceColor, edgecolor=edgecolor,\n linestyle=linestyle, linewidth=linewidth, alpha=alpha)\n ax.add_patch(ellPatch)\n\n\n\ndef ExtractProfile( imdata, x0,y0, x1,y1, width=1 ):\n \"\"\"\n This uses skimage.measure.profile_line to extract a profile from pixel\n coordinate (x0,y0) to pixel coordinate (x1,y1)\n \n This function uses IRAF coordinates (1-based, x = column number)\n \n Parameters\n ----------\n imdata : 2D ndarray of float\n image data array\n\n x0 : int or float\n x-coordinate of start position (1-based)\n\n y0 : int or float\n y-coordinate of start position (1-based)\n\n x1 : int or float\n x-coordinate of end position (1-based)\n\n y1 : int or float\n y-coordinate of end position (1-based)\n \n width : int, optional\n width of profile (perpendicular to profile) in pixels\n\n Returns\n -------\n (rr, ii) : tuple of 1D ndarray of float\n rr = radius vector (r = 0 at start position)\n ii = intensity vector\n \"\"\"\n\n # switch x,y to numpy's y,x and switch to 0-based counting\n try:\n ii = profile_line(imdata, (y0 - 1, x0 - 1), (y1 - 1, x1 - 1), linewidth=width, \n reduce_func=np.nanmean)\n except RuntimeWarning:\n # we don't care whether all the values in a bin were NaN\n pass\n npts = len(ii)\n rr = np.linspace(0, npts - 1, npts)\n return rr,ii\n\n\ndef DrawArrow( startCoord, endCoord=None, PA=None, radius=None, lineWidth=1, headWidth=8,\n headLength=1.6, color=\"black\", text=\"\", alt=True ):\n \"\"\"Draw an arrow from startCoords to endCoord (both should be 2-element\n tuples or lists of (x,y)), with lineWidth and headWidth in points (latter\n is width of arrowhead *base*). headLength specifies the length of the\n arrowhead as a multiple of headWidth (only applies if alt == True).\n text is optional text which will appear at the base of the arrow.\n\n By setting endCoord = None and using PA and radius instead, the arrow can be\n drawn from startCoord in the direction specified by PA (angle CCW from +y axis),\n with distance = radius\n \"\"\"\n\n arrowProperties = dict(width=lineWidth, headwidth=headWidth, color=color)\n if endCoord is None:\n xc,yc = startCoord\n dx = -radius * math.sin(math.radians(PA))\n dy = radius * math.cos(math.radians(PA))\n endCoord = (xc + dx, yc + dy)\n if alt is True:\n x0,y0 = startCoord\n plt.arrow(x0,y0, dx,dy, color=color, width=lineWidth, head_width=headWidth,\n head_length=headLength*headWidth, length_includes_head=True, overhang=0.3)\n else:\n plt.annotate(text, xy=endCoord, xycoords=\"data\", xytext=startCoord,\n arrowprops=arrowProperties, color=color)\n\n return None\n\n\ndef GetProfileAtAngle( imdata, xc,yc, angle, radius, width=1 ):\n \"\"\"\n Returns a 1D profile cut through an image at specified angle, extending to\n specified radius.\n Note: this is designed to imitate pvect, so angles are measured CCW from +x axis!\n \n This function uses IRAF coordinates (1-based, x = column number)\n\n Parameters\n ----------\n imdata : 2D ndarray of float\n image data array\n \n xc : int or float\n x-coordinate of center to extract profile from (IRAF ordering, 1-based)\n \n yc : int or float\n y-coordinate of center to extract profile from (IRAF ordering, 1-based)\n \n angle : float\n angle measured CCW from +x axis, in degrees\n \n radius : int\n length of profile, in pixels\n \n width : int, optional\n width of profile (perpendicular to profile) in pixels\n \n Returns\n -------\n rr,ii : tuple of 1D ndarray of float\n rr = array of radius values (= 0 at (xc,yc))\n ii = data pixel values along profile [= Nan if all pixels for that bin\n were masked]\n \"\"\"\n angle_rad = math.radians(angle)\n x_end = xc + math.cos(angle_rad) * radius\n y_end = yc + math.sin(angle_rad) * radius\n x_start = xc - math.cos(angle_rad) * radius\n y_start = yc - math.sin(angle_rad) * radius\n rr,ii = ExtractProfile(imdata, x_start,y_start, x_end,y_end, width=width)\n rr = rr - radius\n return rr, ii\n\n\ndef PlotFrequency( values, i_1, i_non1, start, stop, step, offset=0, noErase=False, \n\t\t\t\t\taxisObj=None, debug=False, **kwargs ):\n\t\t\t\t\t\n\t\"\"\"\n\tPlots frequencies with binomial 68% confidence intervals (as error bars) in\n\tbins of values, where i_1 are indices defining detections and i_non1 define\n\tnon-detections.\n\n\tvalues = vector of values (e.g., M_star)\n\ti1 = list of indices into values for objects in parent sample \n\t\tand in group 1 (e.g., barred galaxies)\n\ti_non1 = list of indices into values for objects in parent sample \n\t\tbut *not* in group 1 (e.g., unbarred galaxies)\n\tstart, stop, step = start, stop, and spacing for bins\n\t\n\toffset = optional additive offset to x [values] positions of plotted points\n\t\n\taxisObj = optional matplotlib Axes object where plot will be placed\n\t\n\t**kwargs = extra keyword=value pairs passed to plt.errorbar\n\n\tExample:\n\tPlotFrequency(logMstar, ii_boxy, ii_nonboxy, 9.0, 11.6, 0.2)\n\t\"\"\"\n\tbinranges = np.arange(start, stop, step)\n\tn1,bins = np.histogram(np.array(values)[i_1], bins=binranges)\n\tn2,bins = np.histogram(np.array(values)[i_non1], bins=binranges)\n\tnBins = len(n1)\n\n\tff = []\n\tff_low = []\n\tff_high = []\n\tfor i in range(nBins):\n\t\tif n1[i] + n2[i] == 0:\n\t\t\tf = f_low = f_high = np.nan\n\t\telse:\n\t\t\tf,f_low,f_high = Binomial(n1[i], n1[i] + n2[i])\n\t\tff.append(f)\n\t\tff_low.append(f_low)\n\t\tff_high.append(f_high)\n\tx = np.array([0.5*(bins[i] + bins[i + 1]) for i in range(len(bins) - 1)])\n\tif debug:\n\t\tprint(bins)\n\t\tprint(\"n1 (i_1) = \", n1)\n\t\tprint(\"n2 (i_non1) = \", n2)\n\t\tprint(ff)\n\t\n\tif noErase is False:\n\t\tplt.clf()\n\tif axisObj is None:\n\t\tplt.errorbar(x + offset, ff, [ff_low,ff_high], None, elinewidth=1.2, \n\t\t\t\t\tcapthick=1.2, capsize=5, **kwargs)\n\telse:\n\t\taxisObj.errorbar(x + offset, ff, [ff_low,ff_high], None, elinewidth=1.2, \n\t\t\t\t\tcapthick=1.2, capsize=5, **kwargs)\n\n","sub_path":"plotutils.py","file_name":"plotutils.py","file_ext":"py","file_size_in_byte":31227,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"47615441","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n#\n# Copyright 2017, Data61\n# Commonwealth Scientific and Industrial Research Organisation (CSIRO)\n# ABN 41 687 119 230.\n#\n# This software may be distributed and modified according to the terms of\n# the BSD 2-Clause license. Note that NO WARRANTY is provided.\n# See \"LICENSE_BSD2.txt\" for details.\n#\n# @TAG(DATA61_BSD)\n#\n\nfrom __future__ import absolute_import, division, print_function, \\\n unicode_literals\nfrom camkes.internal.seven import cmp, filter, map, zip\n\nfrom camkes.internal.exception import CAmkESError\nimport six\n\nclass ParseError(CAmkESError):\n def __init__(self, content, location=None, filename=None, lineno=None):\n assert isinstance(content, six.string_types) or isinstance(content, Exception)\n if location is not None:\n filename = location.filename\n lineno = location.lineno\n min_col = location.min_col\n max_col = location.max_col\n else:\n min_col = None\n max_col = None\n msg = self._format_message(six.text_type(content), filename, lineno,\n min_col, max_col)\n super(ParseError, self).__init__(msg)\n","sub_path":"tools/camkes/camkes/parser/exception.py","file_name":"exception.py","file_ext":"py","file_size_in_byte":1180,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"499556641","text":"\"\"\"URLs.\"\"\"\n\nfrom django.urls import path\n\nfrom .views import (\n LeaveListView,\n LeaveUpdateView,\n LeaveDetailView,\n LeaveDeleteView,\n LeaveCreateView,\n RoleListView,\n RoleUpdateView,\n RoleDetailView,\n RoleDeleteView,\n RoleCreateView,\n ShiftListView,\n ShiftUpdateView,\n ShiftDetailView,\n ShiftDeleteView,\n ShiftCreateView,\n ShiftRuleListView,\n ShiftRuleUpdateView,\n ShiftRuleDetailView,\n ShiftRuleDeleteView,\n ShiftRuleCreateView,\n ShiftRuleRoleListView,\n ShiftRuleRoleUpdateView,\n ShiftRuleRoleDetailView,\n ShiftRuleRoleDeleteView,\n ShiftRuleRoleCreateView,\n StaffRuleListView,\n StaffRuleUpdateView,\n StaffRuleDetailView,\n StaffRuleDeleteView,\n StaffRuleCreateView,\n StaffRuleShiftListView,\n StaffRuleShiftUpdateView,\n StaffRuleShiftDetailView,\n StaffRuleShiftDeleteView,\n StaffRuleShiftCreateView,\n TimeSlotListView,\n TimeSlotUpdateView,\n TimeSlotDetailView,\n TimeSlotDeleteView,\n TimeSlotCreateView,\n GenerateRosterView,\n SelectRosterView,\n RosterListView,\n PreferenceListView,\n PreferenceUpdateView,\n PreferenceDetailView,\n PreferenceDeleteView,\n PreferenceCreateView,\n download_csv,\n DayGroupListView,\n DayGroupUpdateView,\n DayGroupDetailView,\n DayGroupDeleteView,\n DayGroupCreateView,\n DayGroupDayListView,\n DayGroupDayUpdateView,\n DayGroupDayDetailView,\n DayGroupDayDeleteView,\n DayGroupDayCreateView,\n DayListView,\n DayUpdateView,\n DayDetailView,\n DayDeleteView,\n DayCreateView,\n DaySetCreateView,\n StaffRequestUpdateView,\n StaffRequestListView,\n)\n\nurlpatterns = [\n path(\"leave//edit/\", LeaveUpdateView.as_view(), name=\"leave_edit\"),\n path(\"leave//\", LeaveDetailView.as_view(), name=\"leave_detail\"),\n path(\n \"leave//delete/\",\n LeaveDeleteView.as_view(),\n name=\"leave_delete\",\n ),\n path(\"leave/new/\", LeaveCreateView.as_view(), name=\"leave_new\"),\n path(\"leave/\", LeaveListView.as_view(), name=\"leave_list\"),\n path(\"role//edit/\", RoleUpdateView.as_view(), name=\"role_edit\"),\n path(\"role//\", RoleDetailView.as_view(), name=\"role_detail\"),\n path(\n \"role//delete/\", RoleDeleteView.as_view(), name=\"role_delete\"\n ),\n path(\"role/new/\", RoleCreateView.as_view(), name=\"role_new\"),\n path(\"role/\", RoleListView.as_view(), name=\"role_list\"),\n path(\"shift//edit/\", ShiftUpdateView.as_view(), name=\"shift_edit\"),\n path(\"shift//\", ShiftDetailView.as_view(), name=\"shift_detail\"),\n path(\n \"shift//delete/\",\n ShiftDeleteView.as_view(),\n name=\"shift_delete\",\n ),\n path(\"shift/new/\", ShiftCreateView.as_view(), name=\"shift_new\"),\n path(\"shift/\", ShiftListView.as_view(), name=\"shift_list\"),\n path(\n \"shiftrule//edit/\",\n ShiftRuleUpdateView.as_view(),\n name=\"shift_rule_edit\",\n ),\n path(\n \"shiftrule//\",\n ShiftRuleDetailView.as_view(),\n name=\"shift_rule_detail\",\n ),\n path(\n \"shiftrule//delete/\",\n ShiftRuleDeleteView.as_view(),\n name=\"shift_rule_delete\",\n ),\n path(\n \"shiftrule/new/\", ShiftRuleCreateView.as_view(), name=\"shift_rule_new\"\n ),\n path(\"shiftrule/\", ShiftRuleListView.as_view(), name=\"shift_rule_list\"),\n path(\n \"shiftrulerole//edit/\",\n ShiftRuleRoleUpdateView.as_view(),\n name=\"shift_rule_role_edit\",\n ),\n path(\n \"shiftrulerole//\",\n ShiftRuleRoleDetailView.as_view(),\n name=\"shift_rule_role_detail\",\n ),\n path(\n \"shiftrulerole//delete/\",\n ShiftRuleRoleDeleteView.as_view(),\n name=\"shift_rule_role_delete\",\n ),\n path(\n \"shiftrulerole//new/\",\n ShiftRuleRoleCreateView.as_view(),\n name=\"shift_rule_role_new\",\n ),\n path(\n \"shiftrulerole/\",\n ShiftRuleRoleListView.as_view(),\n name=\"shift_rule_role_list\",\n ),\n path(\n \"staffrule//edit/\",\n StaffRuleUpdateView.as_view(),\n name=\"staff_rule_edit\",\n ),\n path(\n \"staffrule//\",\n StaffRuleDetailView.as_view(),\n name=\"staff_rule_detail\",\n ),\n path(\n \"staffrule//delete/\",\n StaffRuleDeleteView.as_view(),\n name=\"staff_rule_delete\",\n ),\n path(\n \"staffrule/new/\", StaffRuleCreateView.as_view(), name=\"staff_rule_new\"\n ),\n path(\"staffrule/\", StaffRuleListView.as_view(), name=\"staff_rule_list\"),\n path(\n \"staffruleshift//edit/\",\n StaffRuleShiftUpdateView.as_view(),\n name=\"staff_rule_shift_edit\",\n ),\n path(\n \"staffruleshift//\",\n StaffRuleShiftDetailView.as_view(),\n name=\"staff_rule_shift_detail\",\n ),\n path(\n \"staffruleshift//delete/\",\n StaffRuleShiftDeleteView.as_view(),\n name=\"staff_rule_shift_delete\",\n ),\n path(\n \"staffruleshift//new/\",\n StaffRuleShiftCreateView.as_view(),\n name=\"staff_rule_shift_new\",\n ),\n path(\n \"staffruleshift/\",\n StaffRuleShiftListView.as_view(),\n name=\"staff_rule_shift_list\",\n ),\n path(\n \"timeslot//edit/\",\n TimeSlotUpdateView.as_view(),\n name=\"timeslot_edit\",\n ),\n path(\n \"timeslot//\",\n TimeSlotDetailView.as_view(),\n name=\"timeslot_detail\",\n ),\n path(\n \"timeslot//delete/\",\n TimeSlotDeleteView.as_view(),\n name=\"timeslot_delete\",\n ),\n path(\"timeslot/new/\", TimeSlotCreateView.as_view(), name=\"timeslot_new\"),\n path(\"timeslot/\", TimeSlotListView.as_view(), name=\"timeslot_list\"),\n path(\n \"timeslot/generate\",\n GenerateRosterView.as_view(),\n name=\"generate_roster\",\n ),\n path(\"timeslot/select\", SelectRosterView.as_view(), name=\"select_roster\"),\n path(\"roster/\", RosterListView.as_view(), name=\"roster_list\"),\n path(\n \"preference//edit/\",\n PreferenceUpdateView.as_view(),\n name=\"preference_edit\",\n ),\n path(\n \"preference//\",\n PreferenceDetailView.as_view(),\n name=\"preference_detail\",\n ),\n path(\n \"preference//delete/\",\n PreferenceDeleteView.as_view(),\n name=\"preference_delete\",\n ),\n path(\n \"preference/new/\",\n PreferenceCreateView.as_view(),\n name=\"preference_new\",\n ),\n path(\"preference/\", PreferenceListView.as_view(), name=\"preference_list\"),\n path(\"roster/download\", download_csv, name=\"download_csv\"),\n path(\"daygroup/\", DayGroupListView.as_view(), name=\"day_group_list\"),\n path(\n \"daygroup//edit/\",\n DayGroupUpdateView.as_view(),\n name=\"day_group_edit\",\n ),\n path(\n \"daygroup//\",\n DayGroupDetailView.as_view(),\n name=\"day_group_detail\",\n ),\n path(\n \"daygroup//delete/\",\n DayGroupDeleteView.as_view(),\n name=\"day_group_delete\",\n ),\n path(\"daygroup/new/\", DayGroupCreateView.as_view(), name=\"day_group_new\"),\n path(\n \"daygroupday/\",\n DayGroupDayListView.as_view(),\n name=\"day_group_day_list\",\n ),\n path(\n \"daygroupday//edit/\",\n DayGroupDayUpdateView.as_view(),\n name=\"day_group_day_edit\",\n ),\n path(\n \"daygroupday//\",\n DayGroupDayDetailView.as_view(),\n name=\"day_group_day_detail\",\n ),\n path(\n \"daygroupday//delete/\",\n DayGroupDayDeleteView.as_view(),\n name=\"day_group_day_delete\",\n ),\n path(\n \"daygroupday//new/\",\n DayGroupDayCreateView.as_view(),\n name=\"day_group_day_new\",\n ),\n path(\n \"daygroupday/\",\n DayGroupDayListView.as_view(),\n name=\"day_group_day_list\",\n ),\n path(\"day//edit/\", DayUpdateView.as_view(), name=\"day_edit\"),\n path(\"day//\", DayDetailView.as_view(), name=\"day_detail\"),\n path(\"day//delete/\", DayDeleteView.as_view(), name=\"day_delete\"),\n path(\"day/new/\", DayCreateView.as_view(), name=\"day_new\"),\n path(\"day/\", DayListView.as_view(), name=\"day_list\"),\n path(\"dayset/new\", DaySetCreateView.as_view(), name=\"day_set_new\"),\n path(\n \"staffrequest//edit/\",\n StaffRequestUpdateView.as_view(),\n name=\"staff_request_edit\",\n ),\n path(\n \"staffrequest/\",\n StaffRequestListView.as_view(),\n name=\"staff_request_list\",\n ),\n\n]\n","sub_path":"rosters/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":8675,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"207632729","text":"import re\n\nfrom odoo import SUPERUSER_ID, api, models\n\ntry:\n # python 3\n from urllib import parse\nexcept ImportError:\n # python 2\n import urlparse as parse\n\n\nWEBSITE_REFS = [\n \"website_multi_company_demo.website_books\",\n \"website_multi_company_demo.website_bikes\",\n \"website_multi_company_demo.website_watches\",\n]\nWEBSITE_RE = r\"shop\\.(.*)\\.example\"\n\n\nclass Users(models.Model):\n _inherit = \"res.users\"\n\n @classmethod\n def authenticate(cls, db, login, password, user_agent_env):\n \"\"\" Update domain for websites by adding key name after first subdomain, for example:\n if base_location is \"http://db123456.demo.it-projects.info/\",\n then we replace \"shop.SOMETHING.example\"\n to \"db123456.SOMETHING.demo.it-projects.info\"\n \"\"\"\n uid = super(Users, cls).authenticate(db, login, password, user_agent_env)\n with cls.pool.cursor() as cr:\n env = api.Environment(cr, SUPERUSER_ID, {})\n base_location = user_agent_env and user_agent_env.get(\"base_location\")\n if not base_location:\n # Workaround for demo system based on https://it-projects-llc.github.io/odoo-saas-tools/\n #\n # \"Saas Demo\" creates templates with installed modules and then creates copies of that template.\n # So, we shall not make updates inside templates, but only inside final database\n return uid\n\n base = env[\"ir.config_parameter\"].get_param(\"web.base.url\") or base_location\n\n prefix = None\n suffix = None\n if base:\n domain = parse.urlsplit(base).netloc.split(\":\")[0]\n prefix, _, suffix = domain.partition(\".\")\n\n if not (prefix and suffix):\n return uid\n\n for wref in WEBSITE_REFS:\n website = env.ref(wref, raise_if_not_found=False)\n if not website:\n continue\n m = re.search(WEBSITE_RE, website.domain)\n if not m:\n continue\n key = m.group(1)\n website.domain = \"{prefix}.{key}.{suffix}\".format(\n prefix=prefix, suffix=suffix, key=key\n )\n\n return uid\n","sub_path":"website_multi_company_demo/models/res_users.py","file_name":"res_users.py","file_ext":"py","file_size_in_byte":2273,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"631202825","text":"import os\nos.environ['CUDA_VISIBLE_DEVICES'] = '0,1,2,3'\n\nfrom fastai.text import *\nfrom AWDEncClas.eval_clas import *\nfrom AWDLSTM.create_toks_2 import *\nimport matplotlib\nimport matplotlib.pyplot as plt\n\n\n#PATH = Path('/home/waleed/data/eRisk/eRisk_Dep_wr')\n#CLAS_PATH = 'data/nlp_clas/eRisk_dep_wr/eRisk_dep_wr_class'\n#LM_PATH = \"data/nlp_clas/eRisk_dep_wr/eRisk_dep_wr_lm\"\n##CLAS_PATH.mkdir(exist_ok=True)\n##LM_PATH = Path('data/nlp_clas/eRisk_dep/eRisk_dep_lm')\n##LM_PATH.mkdir(exist_ok=True)\n#CLASSES = ['neg', 'pos']\n\n\nPATH = Path('/home/waleed/data/eRisk/eRisk_anx_wr')\nCLAS_PATH = 'data/nlp_clas/eRisk_anx_wr/eRisk_anx_wr_class'\n\n#LM_PATH = \"data/nlp_clas/eRisk_anx_wr/eRisk_anx_wr_lm\"\n\n#CLAS_PATH.mkdir(exist_ok=True)\n#LM_PATH = Path('data/nlp_clas/eRisk_dep/eRisk_dep_lm')\n#LM_PATH.mkdir(exist_ok=True)\nCLASSES = ['neg', 'pos']\n\nlm_id='eRisk_anx_FT2'\nclas_id='eRisk_anx_3_BEST'\n\n#CLAS_PATH_mx = 'data/nlp_clas/eRisk_anx/eRisk_anx_clas'\nLM_PATH = \"data/nlp_clas/eRisk_anx/eRisk_anx_lm\"\n\ndef get_texts(path):\n texts,labels,subjID, chunckID, wrID = [],[], [], [], []\n for idx,label in enumerate(CLASSES):\n for fname in (path/label).glob('*.*'):\n fileName = os.path.splitext(os.path.basename(fname))[0]\n sID, chNum, wrNum = fileName.split(\"_\")\n txt = fname.open('r', encoding='utf-8').read()\n #towri = txt.replace(\"~~\", \" \").replace(\"\\\"\", \"\\\"\\\"\").replace(\"||\", \" \").replace(\"\\n\", \" \").replace(\"\\r\",\"\")\n texts.append(txt)\n labels.append(idx)\n subjID.append(sID)\n chunckID.append(chNum)\n wrID.append(wrNum)\n return texts,labels, subjID, chunckID, wrID\n\n\ndef writeToCSV(df_a, tarFile):\n with open(tarFile, 'w', encoding='utf-8') as trainF:\n for index, row in df_a.iterrows():\n if row['labels'] not in range(0, len(CLASSES)):\n print(\"Error.....!\")\n trainF.write(str(row['labels']) + \",\")\n text = str(row['text'])\n writings = text.split(\"~~\")\n for wri in writings:\n towri = wri.replace(\"\\\"\",\"\\\"\\\"\").replace(\"||\",\" \").replace(\"\\n\", \" \").replace(\"\\r\", \"\")\n trainF.write(\"\\\"\" + towri + \"\\\",\")\n trainF.write(\"\\n\")\n trainF.close()\n\n\ndef writeToCSV_oneFiled(df_a, tarFile):\n with open(tarFile, 'w', encoding='utf-8') as trainF:\n for index, row in df_a.iterrows():\n if row['labels'] not in range(0, len(CLASSES)):\n print(\"Error.....!\")\n trainF.write(str(row['labels']) + \",\")\n text = str(row['text'])\n towri = text.replace(\"~~\",\" \").replace(\"\\\"\", \"\\\"\\\"\").replace(\"||\", \" \").replace(\"\\n\", \" \").replace(\"\\r\", \"\")\n trainF.write(\"\\\"\" + towri + \"\\\"\\n\")\n trainF.close()\n\n\n\n\ndef checkIntegrity(subjIDs,val_labels):\n uniqueSubj = list(set(subjIDs))\n c = []\n for sub in uniq_subID:\n indices = [i for i, x in enumerate(subjIDs) if x == sub]\n labels = [int(val_labels[ind]) for ind in indices]\n uniqLab = set(list(labels))\n if len(uniqLab) > 1:\n c.append(sub)\n #print(c)\n return c\n\n\n\ndef f1_erisk(targs, preds):\n print(confusion_matrix(targs,preds))\n metrics = precision_recall_fscore_support(targs, preds, average=None)\n p = metrics[0]\n r = metrics[1]\n f = metrics[2]\n print(\"p: \" + str(p[len(f) - 1]) + \"\\tR: \" + str(r[len(f) - 1]) + \"\\tF1: \" + str(f[len(f) - 1]))\n return f[len(f) - 1]\n\n\ndef ProcessAcc(df_subj, window):\n df_subj = df_subj.reset_index(drop=True)\n df_subj_proc = df_subj[0:0]\n for index, row in df_subj.iterrows():\n startIdx = max(index - window, 0)\n columnsData = df_subj.loc[startIdx:index, ['text']].values.tolist()\n #print(columnsData)\n df_subj_proc.at[index,:] = df_subj.loc[index,:]\n df_subj_proc.at[index,'text'] = \" \".join([it[0] for it in columnsData])\n\n return df_subj_proc\n\n\n\n\n\n\nval_texts, val_labels, subjIDs, chunkIDs, wrIDs = get_texts(PATH/'test')\n\n\ndf_val_ALL = pd.DataFrame({'text':val_texts, 'labels':val_labels,'chunk_No': list(map(int, chunkIDs)),'wr_No': list(map(int, wrIDs)), 'subj_ID': subjIDs})\ndf_val_ALL = df_val_ALL.sort_values(by=['subj_ID', 'chunk_No', 'wr_No'], ascending=[True, True, True])\nsubjIDs_unq = set(subjIDs)\n\ndf_val_ALL_proc = df_val_ALL[0:0]\nfor sId in subjIDs_unq:\n print(sId)\n df_subj = df_val_ALL.loc[df_val_ALL['subj_ID'] == sId]\n df_subj_proc = ProcessAcc(df_subj,5)\n df_val_ALL_proc = df_val_ALL_proc.append(df_subj_proc)\n\n\n\nval_texts = [it[0] for it in df_val_ALL_proc.loc[:, ['text']].values.tolist()]\nval_labels = [it[0] for it in df_val_ALL_proc.loc[:, ['labels']].values.tolist()]\nsubjIDs = [it[0] for it in df_val_ALL_proc.loc[:, ['subj_ID']].values.tolist()]\nchunkIDs = [it[0] for it in df_val_ALL_proc.loc[:, ['chunk_No']].values.tolist()]\nwrIDs = [it[0] for it in df_val_ALL_proc.loc[:, ['wr_No']].values.tolist()]\n\nnp.save(CLAS_PATH+'/'+'tmp'+'/'+'tests'+'/'+'val_texts.npy', val_texts)\nnp.save(CLAS_PATH+'/'+'tmp'+'/'+'tests'+'/'+'val_labels.npy', val_labels)\nnp.save(CLAS_PATH+'/'+'tmp'+'/'+'tests'+'/'+'subjIDs.npy', subjIDs)\nnp.save(CLAS_PATH+'/'+'tmp'+'/'+'tests'+'/'+'chunkIDs.npy', chunkIDs)\nnp.save(CLAS_PATH+'/'+'tmp'+'/'+'tests'+'/'+'wrIDs.npy', wrIDs)\n\nval_texts = np.load(CLAS_PATH+'/'+'tmp'+'/'+'tests'+'/'+'val_texts.npy')\nval_labels = np.load(CLAS_PATH+'/'+'tmp'+'/'+'tests'+'/'+'val_labels.npy')\nsubjIDs = np.load(CLAS_PATH+'/'+'tmp'+'/'+'tests'+'/'+'subjIDs.npy')\nchunkIDs = np.load(CLAS_PATH+'/'+'tmp'+'/'+'tests'+'/'+'chunkIDs.npy')\nwrIDs = np.load(CLAS_PATH+'/'+'tmp'+'/'+'tests'+'/'+'wrIDs.npy')\n\ncol_names = ['labels','text']\n\n\ndf_val = pd.DataFrame({'text':val_texts, 'labels':val_labels}, columns=col_names)\nwriteToCSV_oneFiled(df_val, CLAS_PATH+'/test_Real1_wr.csv')\n\n\nchunksize = 24000\n\n\ndf_val1 = pd.read_csv(CLAS_PATH+'/'+'test_Real1_wr.csv', header=None, chunksize=chunksize, engine='python')#,names=(range(227)))\n\n\ntok_val, val_labels = get_all_eRisk(df_val1, 1)\n\n\nnp.save(CLAS_PATH+'/'+'tmp'+'/'+'tests'+'/'+'tok_val.npy', tok_val)\n\n\nnp.save(CLAS_PATH+'/'+'tmp'+'/'+'tests'+'/'+'lbl_val.npy', val_labels)\n\n\ntok_val = np.load(CLAS_PATH+'/'+'tmp'+'/'+'tests'+'/'+'tok_val.npy')\nitos = pickle.load(open(LM_PATH+'/'+'tmp'+'/'+'itos.pkl','rb'))\nstoi = collections.defaultdict(lambda:0, {v:k for k,v in enumerate(itos)})\nlen(itos)\n\n\n\nval_clas = np.array([[stoi[o] for o in p] for p in tok_val])\n\nnp.save(CLAS_PATH+'/'+'tmp'+'/'+'tests'+'/'+'val_ids.npy', val_clas)\n\n#prediction = eval_clas_eRisk(str(CLAS_PATH), 2, lm_id='eRisk_dep4_FT', clas_id='eRisk_dep4', attention=False)\n\nprediction, samplIdx, pos_prob = eval_clas_eRisk(str(CLAS_PATH), 2, lm_id=lm_id, clas_id=clas_id, attention=False)\n\n\n\nnp.save(str(CLAS_PATH)+'/'+'tmp/tests'+'/'+'prediction_eRisk_dep_wr.npy', prediction)\nnp.save(str(CLAS_PATH)+'/'+'tmp/tests'+'/'+'samplIdx_eRisk_dep_wr.npy', samplIdx)\nnp.save(str(CLAS_PATH)+'/'+'tmp/tests'+'/'+'pos_prob_eRisk_dep_wr.npy', pos_prob)\n\nprediction = np.load(str(CLAS_PATH)+'/'+'tmp/tests'+'/'+'prediction_eRisk_dep_wr.npy')\nsamplIdx = np.load(str(CLAS_PATH)+'/'+'tmp/tests'+'/'+'samplIdx_eRisk_dep_wr.npy')\npos_prob = np.load(str(CLAS_PATH)+'/'+'tmp/tests'+'/'+'pos_prob_eRisk_dep_wr.npy')\n\n\nsubjIDs = [subjIDs[i] for i in samplIdx]\nval_labels = [val_labels[i] for i in samplIdx]\nchunkIDs = [chunkIDs[i] for i in samplIdx]\nwrIDs = [wrIDs[i] for i in samplIdx]\n\n\nuniq_subID = list(set(subjIDs))\n#results_pred = [[ None ] * 10] * len(uniq_subID)\nresults_pred = [[0]*10 for _ in range(len(uniq_subID))]\nresults_pred_thr = [[0]*10 for _ in range(len(uniq_subID))]\ntotalWrs = [[0]*10 for _ in range(len(uniq_subID))]\nresults_golden = [ None ] * len(uniq_subID)\n\npos_prob_wr = [ [] for _ in range(len(uniq_subID)) ]\n\n#checkIntegrity(subjIDs,val_labels)\nth = 0.9\n\n\n\nfor sid,vLbls,chNum,wr, pred, pos_p in zip(subjIDs,val_labels,chunkIDs,wrIDs, prediction, pos_prob):\n idx = uniq_subID.index(sid)\n if results_golden[idx] != vLbls and results_golden[idx] is not None:\n pass\n else:\n results_golden[idx] = vLbls\n pos_prob_wr[idx].append(pos_p)\n results_pred[idx][int(chNum)-1] = results_pred[idx][int(chNum)-1] + pred\n\n if(pos_p >= th):\n results_pred_thr[idx][int(chNum) - 1] = results_pred_thr[idx][int(chNum) - 1] + 1\n\n totalWrs[idx][int(chNum)-1] = max(totalWrs[idx][int(chNum)-1], int(wr))\n\n#res = [[res/total for res,total in zip(results_pred[i], totalWrs[i])] for i in range(len(results_pred))]\n\nprint(\"F1: \" + str(f1_erisk(val_labels, prediction)))\n\npos_p_avg = [sum(pb)/len(pb) for pb in pos_prob_wr]\n\n#for thr in np.arange(0.0, 1.0, 0.025):\n# print(str(thr) + \":\\t\")\n# prd = [1 if(it >= thr) else 0 for it in pos_p_avg]\n# #print(\"F1: \" + str(f1_erisk(prd, results_golden)))\n# f1_erisk(prd, results_golden)\n#\n\npred_count = [sum(rb) for rb in results_pred_thr]\nfor thr in np.arange(0, 20, 1):\n print(str(thr) + \":\\t\")\n prd = [1 if(it >= thr) else 0 for it in pred_count]\n #print(\"F1: \" + str(f1_erisk(prd, results_golden)))\n f1_erisk(prd, results_golden)\n\nAll_df = pd.DataFrame({'Subject_ID':uniq_subID, 'results_pred':results_pred, 'results_golden':results_golden})\nAll_df.to_csv(str(CLAS_PATH)+'/'+'tmp/tests'+'/'+'Results1_wr.csv', header=False, index=False)\n\n\nprd_5 = [1 if(it >= 5) else 0 for it in pred_count]\ndf_val_ALL_OUT = pd.DataFrame({'text':val_texts, 'labels':val_labels,'chunk_No': list(map(int, chunkIDs)),'wr_No': list(map(int, wrIDs)), 'subj_ID': subjIDs, 'pos_prob': pos_prob})\ndf_val_ALL_OUT = df_val_ALL_OUT.sort_values(by=['subj_ID', 'chunk_No', 'wr_No'], ascending=[True, True, True])\ndf_val_ALL_OUT.to_pickle(str(CLAS_PATH)+'/'+'tmp/tests'+'/'+'df_val_ALL_OUT.pkl')\nsubjIDs_unq = set(subjIDs)\nfor i, sId in enumerate(subjIDs_unq):\n print(sId)\n df_subj = df_val_ALL_OUT.loc[df_val_ALL_OUT['subj_ID'] == sId]\n columnsData = [it[0] for it in df_subj.loc[:, ['pos_prob']].values.tolist()]\n lbl = int(df_subj.loc[:, ['labels']].values.tolist()[0][0])\n plt.plot(columnsData)\n plt.xlabel(sid + \" ---- Pred_results: \" + str(prd_5[i]) )\n plt.savefig('./Figs/eRisk_anx/' + str(lbl) + '/' + sId+ '.png')\n plt.close()\n\n\n\n#res_df = pd.DataFrame({'Subject_ID':uniq_subID, 'results_pred':res, 'results_golden':results_golden})\n#res_df.to_csv(str(CLAS_PATH)+'/'+'tmp/tests'+'/'+'Results1_wr_res.csv', header=False, index=False)\n\n","sub_path":"eRisk_T21_test_wr_mix.py","file_name":"eRisk_T21_test_wr_mix.py","file_ext":"py","file_size_in_byte":10389,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"33437739","text":"\"\"\"\nMIT License\n\nCopyright (c) 2020 Airbyte\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n\"\"\"\n\nimport json\nimport os\nimport tempfile\nimport traceback\nfrom datetime import datetime\nfrom typing import Dict, Generator, List\nfrom urllib.parse import urlparse\n\nimport gcsfs\nimport numpy as np\nimport pandas as pd\nfrom airbyte_protocol import (\n AirbyteCatalog,\n AirbyteConnectionStatus,\n AirbyteMessage,\n AirbyteRecordMessage,\n AirbyteStream,\n ConfiguredAirbyteCatalog,\n Status,\n Type,\n)\nfrom base_python import Source\nfrom botocore import UNSIGNED\nfrom botocore.config import Config\nfrom genson import SchemaBuilder\nfrom google.cloud.storage import Client\nfrom s3fs import S3FileSystem\nfrom smart_open import open\n\n\nclass SourceFile(Source):\n \"\"\"This source aims to provide support for readers of different file formats stored in various locations.\n\n It is optionally using s3fs, gcfs or smart_open libraries to handle efficient streaming of very large files\n (either compressed or not).\n\n Supported examples of URL this can accept are as follows:\n ```\n s3://my_bucket/my_key\n s3://my_key:my_secret@my_bucket/my_key\n gs://my_bucket/my_blob\n azure://my_bucket/my_blob (not tested)\n hdfs:///path/file (not tested)\n hdfs://path/file (not tested)\n webhdfs://host:port/path/file (not tested)\n ./local/path/file\n ~/local/path/file\n local/path/file\n ./local/path/file.gz\n file:///home/user/file\n file:///home/user/file.bz2\n [ssh|scp|sftp]://username@host//path/file\n [ssh|scp|sftp]://username@host/path/file\n [ssh|scp|sftp]://username:password@host/path/file\n ```\n\n The source reader currently leverages `read_csv` but will be extended to readers of different formats for\n more potential sources as described below:\n https://pandas.pydata.org/pandas-docs/stable/user_guide/io.html\n - read_json\n - read_html\n - read_excel\n - read_feather\n - read_parquet\n - read_orc\n - read_pickle\n\n All the options of the readers are exposed to the configuration file of this connector so it is possible to\n override header names, types, encoding, etc\n\n Note that this implementation is handling `url` target as a single file at the moment.\n We will expand the capabilities of this source to discover and load either glob of multiple files,\n content of directories, etc in a latter iteration.\n \"\"\"\n\n def check(self, logger, config: json) -> AirbyteConnectionStatus:\n \"\"\"\n Check involves verifying that the specified file is reachable with\n our credentials.\n \"\"\"\n storage = SourceFile.get_storage_scheme(logger, config[\"provider\"][\"storage\"], config[\"url\"])\n url = SourceFile.get_simple_url(config[\"url\"])\n logger.info(f\"Checking access to {storage}{url}...\")\n try:\n SourceFile.open_file_url(config, logger)\n return AirbyteConnectionStatus(status=Status.SUCCEEDED)\n except Exception as err:\n reason = f\"Failed to load {storage}{url}: {repr(err)}\\n{traceback.format_exc()}\"\n logger.error(reason)\n return AirbyteConnectionStatus(status=Status.FAILED, message=reason)\n\n def discover(self, logger, config: json) -> AirbyteCatalog:\n \"\"\"\n Returns an AirbyteCatalog representing the available streams and fields in this integration. For example, given valid credentials to a\n Remote CSV File, returns an Airbyte catalog where each csv file is a stream, and each column is a field.\n \"\"\"\n storage = SourceFile.get_storage_scheme(logger, config[\"provider\"][\"storage\"], config[\"url\"])\n url = SourceFile.get_simple_url(config[\"url\"])\n name = SourceFile.get_stream_name(config)\n logger.info(f\"Discovering schema of {name} at {storage}{url}...\")\n streams = []\n try:\n # TODO handle discovery of directories of multiple files instead\n if \"format\" in config and config[\"format\"] == \"json\":\n schema = SourceFile.load_nested_json_schema(config, logger)\n json_schema = {\n \"$schema\": \"http://json-schema.org/draft-07/schema#\",\n \"type\": \"object\",\n \"properties\": schema,\n }\n else:\n # Don't skip data when discovering in order to infer column types\n df_list = SourceFile.load_dataframes(config, logger, skip_data=False)\n fields = {}\n for df in df_list:\n for col in df.columns:\n fields[col] = SourceFile.convert_dtype(df[col].dtype)\n json_schema = {\n \"$schema\": \"http://json-schema.org/draft-07/schema#\",\n \"type\": \"object\",\n \"properties\": {field: {\"type\": fields[field]} for field in fields},\n }\n streams.append(AirbyteStream(name=name, json_schema=json_schema))\n except Exception as err:\n reason = f\"Failed to discover schemas of {name} at {storage}{url}: {repr(err)}\\n{traceback.format_exc()}\"\n logger.error(reason)\n raise err\n return AirbyteCatalog(streams=streams)\n\n def read(self, logger, config: json, catalog: ConfiguredAirbyteCatalog, state: Dict[str, any]) -> Generator[AirbyteMessage, None, None]:\n \"\"\"\n Returns a generator of the AirbyteMessages generated by reading the source with the given configuration, catalog, and state.\n \"\"\"\n storage = SourceFile.get_storage_scheme(logger, config[\"provider\"][\"storage\"], config[\"url\"])\n url = SourceFile.get_simple_url(config[\"url\"])\n name = SourceFile.get_stream_name(config)\n logger.info(f\"Reading {name} ({storage}{url})...\")\n selection = SourceFile.parse_catalog(catalog)\n try:\n if \"format\" in config and config[\"format\"] == \"json\":\n data_list = SourceFile.load_nested_json(config, logger)\n for data in data_list:\n yield AirbyteMessage(\n type=Type.RECORD,\n record=AirbyteRecordMessage(stream=name, data=data, emitted_at=int(datetime.now().timestamp()) * 1000),\n )\n else:\n df_list = SourceFile.load_dataframes(config, logger)\n for df in df_list:\n if len(selection) > 0:\n columns = selection.intersection(set(df.columns))\n else:\n columns = df.columns\n df = df.replace(np.nan, \"NaN\", regex=True)\n for data in df[columns].to_dict(orient=\"records\"):\n yield AirbyteMessage(\n type=Type.RECORD,\n record=AirbyteRecordMessage(stream=name, data=data, emitted_at=int(datetime.now().timestamp()) * 1000),\n )\n except Exception as err:\n reason = f\"Failed to read data of {name} at {storage}{url}: {repr(err)}\\n{traceback.format_exc()}\"\n logger.error(reason)\n raise err\n\n @staticmethod\n def get_stream_name(config) -> str:\n if \"dataset_name\" in config:\n name = config[\"dataset_name\"]\n else:\n reader_format = \"csv\"\n if \"format\" in config:\n reader_format = config[\"format\"]\n name = f\"file_{config['provider']['storage']}.{reader_format}\"\n return name\n\n @staticmethod\n def open_file_url(config, logger):\n storage = SourceFile.get_storage_scheme(logger, config[\"provider\"][\"storage\"], config[\"url\"])\n url = SourceFile.get_simple_url(config[\"url\"])\n\n file_to_close = None\n if storage == \"gs://\":\n result, file_to_close = SourceFile.open_gcs_url(config, logger, storage, url)\n elif storage == \"s3://\":\n result = SourceFile.open_aws_url(config, logger, storage, url)\n elif storage == \"webhdfs://\":\n host = config[\"provider\"][\"host\"]\n port = config[\"provider\"][\"port\"]\n result = open(f\"webhdfs://{host}:{port}/{url}\")\n elif storage == \"ssh://\" or storage == \"scp://\" or storage == \"sftp://\":\n user = config[\"provider\"][\"user\"]\n host = config[\"provider\"][\"host\"]\n if \"password\" in config[\"provider\"]:\n password = config[\"provider\"][\"password\"]\n # Explicitly turn off ssh keys stored in ~/.ssh\n transport_params = {\"connect_kwargs\": {\"look_for_keys\": False}}\n result = open(f\"{storage}{user}:{password}@{host}/{url}\", transport_params=transport_params)\n else:\n result = open(f\"{storage}{user}@{host}/{url}\")\n file_to_close = result\n else:\n result = open(f\"{storage}{url}\")\n return result, file_to_close\n\n @staticmethod\n def open_gcs_url(config, logger, storage, url):\n reader_impl = SourceFile.extract_reader_impl(config)\n use_gcs_service_account = \"service_account_json\" in config[\"provider\"] and storage == \"gs://\"\n file_to_close = None\n if reader_impl == \"gcsfs\":\n if use_gcs_service_account:\n try:\n token_dict = json.loads(config[\"provider\"][\"service_account_json\"])\n except json.decoder.JSONDecodeError as err:\n logger.error(f\"Failed to parse gcs service account json: {repr(err)}\\n{traceback.format_exc()}\")\n raise err\n else:\n token_dict = \"anon\"\n fs = gcsfs.GCSFileSystem(token=token_dict)\n file_to_close = fs.open(f\"gs://{url}\")\n result = file_to_close\n else:\n if use_gcs_service_account:\n try:\n credentials = json.dumps(json.loads(config[\"provider\"][\"service_account_json\"]))\n tmp_service_account = tempfile.NamedTemporaryFile(delete=False)\n with open(tmp_service_account, \"w\") as f:\n f.write(credentials)\n tmp_service_account.close()\n client = Client.from_service_account_json(tmp_service_account.name)\n result = open(f\"gs://{url}\", transport_params=dict(client=client))\n os.remove(tmp_service_account.name)\n except json.decoder.JSONDecodeError as err:\n logger.error(f\"Failed to parse gcs service account json: {repr(err)}\\n{traceback.format_exc()}\")\n raise err\n else:\n client = Client.create_anonymous_client()\n result = open(f\"{storage}{url}\", transport_params=dict(client=client))\n return result, file_to_close\n\n @staticmethod\n def open_aws_url(config, _, storage, url):\n reader_impl = SourceFile.extract_reader_impl(config)\n use_aws_account = \"aws_access_key_id\" in config[\"provider\"] and \"aws_secret_access_key\" in config[\"provider\"] and storage == \"s3://\"\n if reader_impl == \"s3fs\":\n if use_aws_account:\n aws_access_key_id = None\n if \"aws_access_key_id\" in config[\"provider\"]:\n aws_access_key_id = config[\"provider\"][\"aws_access_key_id\"]\n aws_secret_access_key = None\n if \"aws_secret_access_key\" in config[\"provider\"]:\n aws_secret_access_key = config[\"provider\"][\"aws_secret_access_key\"]\n s3 = S3FileSystem(anon=False, key=aws_access_key_id, secret=aws_secret_access_key)\n result = s3.open(f\"s3://{url}\", mode=\"r\")\n else:\n s3 = S3FileSystem(anon=True)\n result = s3.open(f\"s3://{url}\", mode=\"r\")\n else:\n if use_aws_account:\n aws_access_key_id = \"\"\n if \"aws_access_key_id\" in config[\"provider\"]:\n aws_access_key_id = config[\"provider\"][\"aws_access_key_id\"]\n aws_secret_access_key = \"\"\n if \"aws_secret_access_key\" in config[\"provider\"]:\n aws_secret_access_key = config[\"provider\"][\"aws_secret_access_key\"]\n result = open(f\"s3://{aws_access_key_id}:{aws_secret_access_key}@{url}\")\n else:\n config = Config(signature_version=UNSIGNED)\n params = {\n \"resource_kwargs\": {\"config\": config},\n }\n result = open(f\"{storage}{url}\", transport_params=params)\n return result\n\n @staticmethod\n def extract_reader_impl(config):\n # default reader impl\n reader_impl = \"\"\n if \"reader_impl\" in config[\"provider\"]:\n reader_impl = config[\"provider\"][\"reader_impl\"]\n return reader_impl\n\n @staticmethod\n def load_nested_json_schema(config, logger) -> dict:\n url, file_to_close = SourceFile.open_file_url(config, logger)\n try:\n # Use Genson Library to take JSON objects and generate schemas that describe them,\n builder = SchemaBuilder()\n builder.add_object(json.load(url))\n result = builder.to_schema()\n if \"items\" in result and \"properties\" in result[\"items\"]:\n result = result[\"items\"][\"properties\"]\n finally:\n if file_to_close:\n file_to_close.close()\n return result\n\n @staticmethod\n def load_nested_json(config, logger) -> list:\n url, file_to_close = SourceFile.open_file_url(config, logger)\n try:\n result = json.load(url)\n if isinstance(result, dict):\n result = [result]\n finally:\n if file_to_close:\n file_to_close.close()\n return result\n\n @staticmethod\n def load_dataframes(config, logger, skip_data=False) -> List:\n \"\"\"From an Airbyte Configuration file, load and return the appropriate pandas dataframe.\n\n :param skip_data: limit reading data\n :param config:\n :param logger:\n :return: a list of dataframe loaded from files described in the configuration\n \"\"\"\n # default format reader\n reader_format = \"csv\"\n if \"format\" in config:\n reader_format = config[\"format\"]\n reader_options: dict = {}\n if \"reader_options\" in config:\n try:\n reader_options = json.loads(config[\"reader_options\"])\n except json.decoder.JSONDecodeError as err:\n logger.error(f\"Failed to parse reader options {repr(err)}\\n{config['reader_options']}\\n{traceback.format_exc()}\")\n if skip_data and reader_format == \"csv\":\n reader_options[\"nrows\"] = 0\n reader_options[\"index_col\"] = 0\n url, file_to_close = SourceFile.open_file_url(config, logger)\n try:\n result = SourceFile.parse_file(logger, reader_format, url, reader_options)\n finally:\n if file_to_close:\n file_to_close.close()\n return result\n\n @staticmethod\n def parse_file(logger, reader_format: str, url, reader_options: dict) -> List:\n result = []\n if reader_format == \"csv\":\n # pandas.read_csv additional arguments can be passed to customize how to parse csv.\n # see https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.read_csv.html\n result.append(pd.read_csv(url, **reader_options))\n elif reader_format == \"flat_json\":\n # We can add option to call to pd.normalize_json to normalize semi-structured JSON data into a flat table\n # by asking user to specify how to flatten the nested columns\n result.append(pd.read_json(url, **reader_options))\n elif reader_format == \"html\":\n result += pd.read_html(url, **reader_options)\n elif reader_format == \"excel\":\n result.append(pd.read_excel(url, **reader_options))\n elif reader_format == \"feather\":\n result.append(pd.read_feather(url, **reader_options))\n elif reader_format == \"parquet\":\n result.append(pd.read_parquet(url, **reader_options))\n elif reader_format == \"orc\":\n result.append(pd.read_orc(url, **reader_options))\n elif reader_format == \"pickle\":\n result.append(pd.read_pickle(url, **reader_options))\n else:\n reason = f\"Reader {reader_format} is not supported\\n{traceback.format_exc()}\"\n logger.error(reason)\n raise Exception(reason)\n return result\n\n @staticmethod\n def get_storage_scheme(logger, storage_name, url) -> str:\n \"\"\"Convert Storage Names to the proper URL Prefix\n\n :param logger: Logger for printing messages\n :param storage_name: Name of the Storage Provider\n :param url: URL of the file in case Storage is not provided but included in the URL\n :return: the corresponding URL prefix / scheme\n \"\"\"\n storage_name = storage_name.upper()\n parse_result = urlparse(url)\n if storage_name == \"GCS\":\n return \"gs://\"\n elif storage_name == \"S3\":\n return \"s3://\"\n elif storage_name == \"HTTPS\":\n return \"https://\"\n elif storage_name == \"SSH\" or storage_name == \"SCP\":\n return \"scp://\"\n elif storage_name == \"SFTP\":\n return \"sftp://\"\n elif storage_name == \"WEBHDFS\":\n return \"webhdfs://\"\n elif storage_name == \"LOCAL\":\n return \"file://\"\n elif parse_result.scheme:\n return parse_result.scheme\n logger.error(f\"Unknown Storage provider in: {storage_name} {url}\")\n return \"\"\n\n @staticmethod\n def get_simple_url(url) -> str:\n \"\"\"Convert URL to remove the URL prefix (scheme)\n\n :param url: URL of the file\n :return: the corresponding URL without URL prefix / scheme\n \"\"\"\n parse_result = urlparse(url)\n if parse_result.scheme:\n return url.split(\"://\")[-1]\n else:\n return url\n\n @staticmethod\n def convert_dtype(dtype) -> str:\n \"\"\"Convert Pandas Dataframe types to Airbyte Types.\n\n :param dtype: Pandas Dataframe type\n :return: Corresponding Airbyte Type\n \"\"\"\n if dtype == object:\n return \"string\"\n elif dtype in (\"int64\", \"float64\"):\n return \"number\"\n elif dtype == \"bool\":\n return \"bool\"\n return \"string\"\n\n @staticmethod\n def parse_catalog(catalog: ConfiguredAirbyteCatalog) -> set:\n columns = set()\n for configured_stream in catalog.streams:\n stream = configured_stream.stream\n for key in stream.json_schema[\"properties\"].keys():\n columns.add(key)\n return columns\n","sub_path":"airbyte-integrations/connectors/source-file/source_file/source.py","file_name":"source.py","file_ext":"py","file_size_in_byte":19949,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"305655839","text":"#coding=utf-8\n\nfrom __future__ import unicode_literals, division, print_function\n\nimport os\nimport codecs\nimport matplotlib.pyplot as plt; plt.rcdefaults()\nimport numpy as np\n\nfrom detectores import StaticDetector\nfrom analisis import Rectangle\n\n\ndef analizar_overlapping_por_parametro(matfile, scenenamenum, objname, objnum,\n param, path,\n include_detections_in_following=False):\n # Minimal overlapping area\n min_overlap_area = 0.3\n\n # Creo el objeto que provee los datos del ground truth\n ground_truth = StaticDetector(\n matfile,\n objname,\n objnum,\n )\n\n # Obtengo los valores del parametro para analizar\n objnamenum = '{name}_{num}'.format(name=objname, num=objnum)\n param_values = os.listdir(\n os.path.join(path, scenenamenum, objnamenum, param)\n )\n param_values = [pv for pv in param_values\n if os.path.isdir(os.path.join(path, scenenamenum, objnamenum, param, pv))]\n param_values.sort()\n\n if len(param_values) == 0:\n param_values = ['']\n\n # Aqui guardare la informacion recolectada\n index = {}\n\n # Para cada valor del parametro voy a juntar la informacion de todas las\n # corridas\n for param_value in param_values:\n param_path = os.path.join(\n path,\n scenenamenum,\n objnamenum,\n param,\n param_value,\n )\n overlapping_areas = []\n frames = 0\n times_object_appear = 0\n times_object_detected = 0\n times_object_followed = 0\n\n fp = 0 # False positives\n fn = 0 # False negatives\n tp = 0 # True positives\n tn = 0 # True negatives\n\n # Obtengo las direcciones de cada corrida y busco la informacion\n run_nums = os.listdir(param_path)\n run_nums = [rn for rn in run_nums if os.path.isdir(os.path.join(param_path, rn))]\n if len(run_nums) == 0:\n run_nums = ['']\n\n for run_num in run_nums:\n resultfile = os.path.join(param_path, run_num, 'results.txt')\n with codecs.open(resultfile, 'r', 'utf-8') as file_:\n\n # Salteo los valores de los parametros\n reach_result_zone = False\n while not reach_result_zone:\n line = file_.next()\n reach_result_zone = line.startswith('RESULTS_SECTION')\n\n # Junto los valores por linea/frame\n for line in file_:\n # Cuento los frames\n frames += 1\n\n # Valores devueltos por el algoritmo\n values = [int(v) for v in line.split(';')]\n nframe = values[0]\n fue_exitoso = values[1]\n metodo = values[2]\n fila_sup = values[3]\n col_izq = values[4]\n fila_inf = values[5]\n col_der = values[6]\n\n # Valores segun el ground truth\n ground_truth.update({'nframe': nframe})\n gt_fue_exitoso, gt_desc = ground_truth.detect()\n gt_col_izq = gt_desc['topleft'][1]\n gt_fila_sup = gt_desc['topleft'][0]\n gt_col_der = gt_desc['bottomright'][1]\n gt_fila_inf = gt_desc['bottomright'][0]\n\n # Armo rectangulos con los resultados\n rectangle_found = Rectangle(\n (fila_sup, col_izq),\n (fila_inf, col_der)\n )\n found_area = rectangle_found.area()\n ground_truth_rectangle = Rectangle(\n (gt_fila_sup, gt_col_izq),\n (gt_fila_inf, gt_col_der)\n )\n ground_truth_area = ground_truth_rectangle.area()\n intersection = rectangle_found.intersection(\n ground_truth_rectangle\n )\n intersection_area = intersection.area()\n\n # To be considered a correct detection, the area of\n # overlap A0 between the predicted bounding box Bp and\n # ground truth bounding box Bgt must exceed 50% by the\n # formula:\n # A0 = area(Bp intersection Bgt) / area(Bp union Bgt)\n se_solaparon_poco = True\n overlap_area = 0\n if found_area > 0 and ground_truth_area > 0:\n union_area = (\n found_area + ground_truth_area - intersection_area\n )\n overlap_area = intersection_area / union_area\n se_solaparon_poco = overlap_area < min_overlap_area\n\n # Chequeo de falsos positivos y negativos y\n # verdaderos negativos y positivos\n estaba_y_no_se_encontro = gt_fue_exitoso and not fue_exitoso\n\n no_estaba_y_se_encontro = (\n ground_truth_area == 0 and found_area > 0\n )\n\n no_estaba_y_no_se_encontro = (\n not (gt_fue_exitoso or fue_exitoso)\n )\n\n estaba_y_se_encontro = (\n fue_exitoso and ground_truth_area > 0\n )\n\n if (estaba_y_no_se_encontro or\n (estaba_y_se_encontro and se_solaparon_poco)):\n fn += 1\n elif no_estaba_y_se_encontro:\n fp += 1\n elif no_estaba_y_no_se_encontro:\n tn += 1\n elif estaba_y_se_encontro and not se_solaparon_poco:\n tp += 1\n if metodo == 0:\n times_object_detected += 1\n else:\n times_object_followed += 1\n else:\n raise Exception('Algo anda mal. Revisar condiciones')\n\n # El objeto aparece siempre que el ground truth asi lo\n # indique, o si estando en un borde el algoritmo igual lo\n # detecto\n if gt_fue_exitoso or (found_area > 0 and\n ground_truth_area > 0):\n times_object_appear += 1\n\n # Incluyo el solapamiento si asi se necesita\n if include_detections_in_following or metodo == 1:\n overlapping_areas.append(overlap_area)\n\n if tp + tn + fp + fn != frames:\n raise Exception('No da bien el analisis de fp,fn,tp,tn')\n\n # Obtengo la media de los solapamientos\n mean = np.mean(overlapping_areas) if overlapping_areas else 0\n\n # Obtengo el desvío estandar de los solapamientos\n std = np.std(overlapping_areas) if overlapping_areas else 0\n\n # Almaceno estos valores\n index[param_value] = {\n 'mean': mean,\n 'std': std,\n 'total_frames': frames,\n 'times_object_appear': times_object_appear,\n 'times_object_detected': times_object_detected,\n 'times_object_followed': times_object_followed,\n 'false_positives': fp,\n 'false_negatives': fn,\n 'true_positives': tp,\n 'true_negatives': tn,\n }\n\n # Imprimo en pantalla para cada valor del parametro el promedio de\n # solapamiento en la escena para cada corrida y el promedio de todas las\n # corridas\n print('###############')\n print('Analizando {p} para el objeto {o} en la escena {e}'.format(\n p=param.upper(),\n o=objnamenum,\n e=scenenamenum,\n ))\n print('###############')\n just = 15\n print('Param. value'.rjust(just), end=' ')\n print('~Overlap'.rjust(just), end=' ')\n # print('Std. Dev. Overlap'.rjust(just), end=' ')\n print('# appear obj'.rjust(just), end=' ')\n print('% follow/appear'.rjust(just), end=' ')\n print('% FP'.rjust(just), end=' ')\n print('% FN'.rjust(just), end=' ')\n print('% TP'.rjust(just), end=' ')\n print('% TN'.rjust(just), end=' ')\n print('F-measure'.rjust(just), end=' ')\n print('Accuracy'.rjust(just))\n\n try:\n ordered_items = sorted(index.items(), key=lambda a: float(a[0]))\n except ValueError:\n ordered_items = sorted(index.items())\n\n for val, dd in ordered_items:\n avg = dd['mean']\n # std = dd['std']\n\n # Param value\n print('{a}'.format(a=val).rjust(just), end=' ')\n\n # Prom. overlap\n print(\n '{a}'.format(a=round(np.array(avg) * 100, 2)).rjust(just),\n end=' '\n )\n\n # Standard deviation\n # print(\n # '{a:{j}.2f}'.format(a=round(np.array(std) * 100, 2), j=just),\n # end=' '\n # )\n\n # Times obj. appeared\n print('{a:d}'.format(a=dd['times_object_appear']).rjust(just), end=' ')\n\n # % obj followed\n times_followed = dd['times_object_followed']\n if include_detections_in_following:\n times_followed += dd['times_object_detected']\n\n try:\n a = round(times_followed / dd['times_object_appear'] * 100, 2)\n except ZeroDivisionError:\n a = 0\n print(\n '{a}%'.format(\n a=a,\n ).rjust(just),\n end=' ',\n )\n\n # % false positives\n print(\n '{a}%'.format(\n a=round(dd['false_positives'] / dd['total_frames'] * 100, 2),\n ).rjust(just),\n end=' ',\n )\n\n # % false negatives\n print(\n '{a}%'.format(\n a=round(dd['false_negatives'] / dd['total_frames'] * 100, 2),\n ).rjust(just),\n end=' ',\n )\n\n # % true positives\n print(\n '{a}%'.format(\n a=round(dd['true_positives'] / dd['total_frames'] * 100, 2),\n ).rjust(just),\n end=' ',\n )\n\n # % true negatives\n print(\n '{a}%'.format(\n a=round(dd['true_negatives'] / dd['total_frames'] * 100, 2),\n ).rjust(just),\n end=' ',\n )\n\n # F-measure\n try:\n precision = (\n dd['true_positives'] /\n (dd['true_positives'] + dd['false_positives'])\n )\n except ZeroDivisionError:\n precision = 0\n\n try:\n recall = (\n dd['true_positives'] /\n (dd['true_positives'] + dd['false_negatives'])\n )\n except ZeroDivisionError:\n recall = 0\n\n try:\n fmeasure = 2 * precision * recall / (precision + recall)\n except ZeroDivisionError:\n fmeasure = 0\n\n print('{a}'.format(a=round(fmeasure, 2)).rjust(just), end=' ')\n\n # Accuracy\n tptn = dd['true_positives'] + dd['true_negatives']\n fpfn = dd['false_positives'] + dd['false_negatives']\n accuracy = (\n tptn / (tptn + fpfn)\n )\n print('{a}'.format(a=round(accuracy * 100, 2)).rjust(just))\n\n\nif __name__ == '__main__':\n ###########################################################################\n # INICIO DEFINITIVOS #\n ###########################################################################\n ##########################################\n # STATIC DETECTION y definitivo RGB y HSV\n ##########################################\n # analizar_overlapping_por_parametro(\n # matfile='videos/rgbd/scenes/desk/desk_1.mat',\n # scenenamenum='desk_1',\n # objname='coffee_mug',\n # objnum='5',\n # param='definitivo_RGB_staticdet',\n # path='pruebas_guardadas',\n # )\n # analizar_overlapping_por_parametro(\n # matfile='videos/rgbd/scenes/desk/desk_1.mat',\n # scenenamenum='desk_1',\n # objname='cap',\n # objnum='4',\n # param='definitivo_RGB_staticdet',\n # path='pruebas_guardadas',\n # )\n # analizar_overlapping_por_parametro(\n # matfile='videos/rgbd/scenes/desk/desk_2.mat',\n # scenenamenum='desk_2',\n # objname='bowl',\n # objnum='3',\n # param='definitivo_RGB_staticdet',\n # path='pruebas_guardadas',\n # )\n # analizar_overlapping_por_parametro(\n # matfile='videos/rgbd/scenes/table/table_1.mat',\n # scenenamenum='table_1',\n # objname='coffee_mug',\n # objnum='1',\n # param='definitivo_RGB_staticdet',\n # path='pruebas_guardadas',\n # )\n # analizar_overlapping_por_parametro(\n # matfile='videos/rgbd/scenes/table/table_1.mat',\n # scenenamenum='table_1',\n # objname='soda_can',\n # objnum='4',\n # param='definitivo_RGB_staticdet',\n # path='pruebas_guardadas',\n # )\n # analizar_overlapping_por_parametro(\n # matfile='videos/rgbd/scenes/table_small/table_small_2.mat',\n # scenenamenum='table_small_2',\n # objname='cereal_box',\n # objnum='4',\n # param='definitivo_RGB_staticdet',\n # path='pruebas_guardadas',\n # )\n\n ##########################################################\n # STATIC DETECTION y definitivo DEPTH\n ##########################################################\n # analizar_overlapping_por_parametro(\n # matfile='videos/rgbd/scenes/desk/desk_1.mat',\n # scenenamenum='desk_1',\n # objname='coffee_mug',\n # objnum='5',\n # param='definitivo_DEPTH',\n # path='pruebas_guardadas',\n # )\n # analizar_overlapping_por_parametro(\n # matfile='videos/rgbd/scenes/desk/desk_1.mat',\n # scenenamenum='desk_1',\n # objname='cap',\n # objnum='4',\n # param='definitivo_DEPTH',\n # path='pruebas_guardadas',\n # )\n # analizar_overlapping_por_parametro(\n # matfile='videos/rgbd/scenes/desk/desk_2.mat',\n # scenenamenum='desk_2',\n # objname='bowl',\n # objnum='3',\n # param='definitivo_DEPTH',\n # path='pruebas_guardadas',\n # )\n # analizar_overlapping_por_parametro(\n # matfile='videos/rgbd/scenes/table/table_1.mat',\n # scenenamenum='table_1',\n # objname='coffee_mug',\n # objnum='1',\n # param='definitivo_DEPTH',\n # path='pruebas_guardadas',\n # )\n # analizar_overlapping_por_parametro(\n # matfile='videos/rgbd/scenes/table/table_1.mat',\n # scenenamenum='table_1',\n # objname='soda_can',\n # objnum='4',\n # param='definitivo_DEPTH',\n # path='pruebas_guardadas',\n # )\n # analizar_overlapping_por_parametro(\n # matfile='videos/rgbd/scenes/table_small/table_small_2.mat',\n # scenenamenum='table_small_2',\n # objname='cereal_box',\n # objnum='4',\n # param='definitivo_DEPTH',\n # path='pruebas_guardadas',\n # )\n\n ##################################################################\n # STATIC DETECTION y seguimiento RGB-D, preferentemente D\n ##################################################################\n # analizar_overlapping_por_parametro(\n # matfile='videos/rgbd/scenes/desk/desk_1.mat',\n # scenenamenum='desk_1',\n # objname='coffee_mug',\n # objnum='5',\n # param='definitivo_RGBD_preferD',\n # path='pruebas_guardadas',\n # )\n #\n # analizar_overlapping_por_parametro(\n # matfile='videos/rgbd/scenes/desk/desk_1.mat',\n # scenenamenum='desk_1',\n # objname='cap',\n # objnum='4',\n # param='definitivo_RGBD_preferD',\n # path='pruebas_guardadas',\n # )\n #\n # analizar_overlapping_por_parametro(\n # matfile='videos/rgbd/scenes/desk/desk_2.mat',\n # scenenamenum='desk_2',\n # objname='bowl',\n # objnum='3',\n # param='definitivo_RGBD_preferD',\n # path='pruebas_guardadas',\n # )\n # analizar_overlapping_por_parametro(\n # matfile='videos/rgbd/scenes/table/table_1.mat',\n # scenenamenum='table_1',\n # objname='coffee_mug',\n # objnum='1',\n # param='definitivo_RGBD_preferD',\n # path='pruebas_guardadas',\n # )\n # analizar_overlapping_por_parametro(\n # matfile='videos/rgbd/scenes/table/table_1.mat',\n # scenenamenum='table_1',\n # objname='soda_can',\n # objnum='4',\n # param='definitivo_RGBD_preferD',\n # path='pruebas_guardadas',\n # )\n # analizar_overlapping_por_parametro(\n # matfile='videos/rgbd/scenes/table_small/table_small_2.mat',\n # scenenamenum='table_small_2',\n # objname='cereal_box',\n # objnum='4',\n # param='definitivo_RGBD_preferD',\n # path='pruebas_guardadas',\n # )\n\n ##################################################################\n # STATIC DETECTION y seguimiento RGB-D, preferentemente RGB\n ##################################################################\n # analizar_overlapping_por_parametro(\n # matfile='videos/rgbd/scenes/desk/desk_1.mat',\n # scenenamenum='desk_1',\n # objname='coffee_mug',\n # objnum='5',\n # param='definitivo_RGBD_preferRGB',\n # path='pruebas_guardadas',\n # )\n #\n # analizar_overlapping_por_parametro(\n # matfile='videos/rgbd/scenes/desk/desk_1.mat',\n # scenenamenum='desk_1',\n # objname='cap',\n # objnum='4',\n # param='definitivo_RGBD_preferRGB',\n # path='pruebas_guardadas',\n # )\n #\n # analizar_overlapping_por_parametro(\n # matfile='videos/rgbd/scenes/desk/desk_2.mat',\n # scenenamenum='desk_2',\n # objname='bowl',\n # objnum='3',\n # param='definitivo_RGBD_preferRGB',\n # path='pruebas_guardadas',\n # )\n # analizar_overlapping_por_parametro(\n # matfile='videos/rgbd/scenes/table/table_1.mat',\n # scenenamenum='table_1',\n # objname='coffee_mug',\n # objnum='1',\n # param='definitivo_RGBD_preferRGB',\n # path='pruebas_guardadas',\n # )\n # analizar_overlapping_por_parametro(\n # matfile='videos/rgbd/scenes/table/table_1.mat',\n # scenenamenum='table_1',\n # objname='soda_can',\n # objnum='4',\n # param='definitivo_RGBD_preferRGB',\n # path='pruebas_guardadas',\n # )\n # analizar_overlapping_por_parametro(\n # matfile='videos/rgbd/scenes/table_small/table_small_2.mat',\n # scenenamenum='table_small_2',\n # objname='cereal_box',\n # objnum='4',\n # param='definitivo_RGBD_preferRGB',\n # path='pruebas_guardadas',\n # )\n\n ##################################################################\n # Definitivo sistema RGBD priorizando D en seguimiento\n ##################################################################\n # analizar_overlapping_por_parametro(\n # matfile='videos/rgbd/scenes/desk/desk_1.mat',\n # scenenamenum='desk_1',\n # objname='coffee_mug',\n # objnum='5',\n # param='definitivo_automatico_RGBD',\n # path='pruebas_guardadas',\n # include_detections_in_following=True,\n # )\n #\n # analizar_overlapping_por_parametro(\n # matfile='videos/rgbd/scenes/desk/desk_1.mat',\n # scenenamenum='desk_1',\n # objname='cap',\n # objnum='4',\n # param='definitivo_automatico_RGBD',\n # path='pruebas_guardadas',\n # include_detections_in_following=True,\n # )\n #\n # analizar_overlapping_por_parametro(\n # matfile='videos/rgbd/scenes/desk/desk_2.mat',\n # scenenamenum='desk_2',\n # objname='bowl',\n # objnum='3',\n # param='definitivo_automatico_RGBD',\n # path='pruebas_guardadas',\n # include_detections_in_following=True,\n # )\n # analizar_overlapping_por_parametro(\n # matfile='videos/rgbd/scenes/table/table_1.mat',\n # scenenamenum='table_1',\n # objname='coffee_mug',\n # objnum='1',\n # param='definitivo_automatico_RGBD',\n # path='pruebas_guardadas',\n # include_detections_in_following=True,\n # )\n # analizar_overlapping_por_parametro(\n # matfile='videos/rgbd/scenes/table/table_1.mat',\n # scenenamenum='table_1',\n # objname='soda_can',\n # objnum='4',\n # param='definitivo_automatico_RGBD',\n # path='pruebas_guardadas',\n # include_detections_in_following=True,\n # )\n # analizar_overlapping_por_parametro(\n # matfile='videos/rgbd/scenes/table_small/table_small_2.mat',\n # scenenamenum='table_small_2',\n # objname='cereal_box',\n # objnum='4',\n # param='definitivo_automatico_RGBD',\n # path='pruebas_guardadas',\n # include_detections_in_following=True,\n # )\n\n ##################################################################\n # Definitivo sistema RGBD priorizando RGB en seguimiento\n ##################################################################\n # analizar_overlapping_por_parametro(\n # matfile='videos/rgbd/scenes/desk/desk_1.mat',\n # scenenamenum='desk_1',\n # objname='coffee_mug',\n # objnum='5',\n # param='definitivo_automatico_RGB_RGBD',\n # path='pruebas_guardadas',\n # include_detections_in_following=True,\n # )\n #\n # analizar_overlapping_por_parametro(\n # matfile='videos/rgbd/scenes/desk/desk_1.mat',\n # scenenamenum='desk_1',\n # objname='cap',\n # objnum='4',\n # param='definitivo_automatico_RGB_RGBD',\n # path='pruebas_guardadas',\n # include_detections_in_following=True,\n # )\n #\n # analizar_overlapping_por_parametro(\n # matfile='videos/rgbd/scenes/desk/desk_2.mat',\n # scenenamenum='desk_2',\n # objname='bowl',\n # objnum='3',\n # param='definitivo_automatico_RGB_RGBD',\n # path='pruebas_guardadas',\n # include_detections_in_following=True,\n # )\n # analizar_overlapping_por_parametro(\n # matfile='videos/rgbd/scenes/table/table_1.mat',\n # scenenamenum='table_1',\n # objname='coffee_mug',\n # objnum='1',\n # param='definitivo_automatico_RGB_RGBD',\n # path='pruebas_guardadas',\n # include_detections_in_following=True,\n # )\n # analizar_overlapping_por_parametro(\n # matfile='videos/rgbd/scenes/table/table_1.mat',\n # scenenamenum='table_1',\n # objname='soda_can',\n # objnum='4',\n # param='definitivo_automatico_RGB_RGBD',\n # path='pruebas_guardadas',\n # include_detections_in_following=True,\n # )\n # analizar_overlapping_por_parametro(\n # matfile='videos/rgbd/scenes/table_small/table_small_2.mat',\n # scenenamenum='table_small_2',\n # objname='cereal_box',\n # objnum='4',\n # param='definitivo_automatico_RGB_RGBD',\n # path='pruebas_guardadas',\n # include_detections_in_following=True,\n # )\n\n ############################################################################\n # FIN DEFINITIVOS #\n ############################################################################\n\n\n # Pruebas deteccion Nadia\n # analizar_overlapping_por_parametro(\n # matfile='videos/rgbd/scenes/desk/desk_1.mat',\n # scenenamenum='desk_1',\n # objname='coffee_mug',\n # objnum='5',\n # param='ap_inlier_fraction',\n # path='pruebas_guardadas',\n # include_detections_in_following=False,\n # )\n #\n # analizar_overlapping_por_parametro(\n # matfile='videos/rgbd/scenes/desk/desk_1.mat',\n # scenenamenum='desk_1',\n # objname='cap',\n # objnum='4',\n # param='ap_inlier_fraction',\n # path='pruebas_guardadas',\n # include_detections_in_following=False,\n # )\n #\n # analizar_overlapping_por_parametro(\n # matfile='videos/rgbd/scenes/desk/desk_2.mat',\n # scenenamenum='desk_2',\n # objname='bowl',\n # objnum='3',\n # param='ap_inlier_fraction',\n # path='pruebas_guardadas',\n # include_detections_in_following=False,\n # )\n #\n # analizar_overlapping_por_parametro(\n # matfile='videos/rgbd/scenes/desk/desk_1.mat',\n # scenenamenum='desk_1',\n # objname='coffee_mug',\n # objnum='5',\n # param='ap_simil_threshold',\n # path='pruebas_guardadas',\n # include_detections_in_following=False,\n # )\n #\n # analizar_overlapping_por_parametro(\n # matfile='videos/rgbd/scenes/desk/desk_1.mat',\n # scenenamenum='desk_1',\n # objname='cap',\n # objnum='4',\n # param='ap_simil_threshold',\n # path='pruebas_guardadas',\n # include_detections_in_following=False,\n # )\n #\n # analizar_overlapping_por_parametro(\n # matfile='videos/rgbd/scenes/desk/desk_2.mat',\n # scenenamenum='desk_2',\n # objname='bowl',\n # objnum='3',\n # param='ap_simil_threshold',\n # path='pruebas_guardadas',\n # include_detections_in_following=False,\n # )\n #\n # analizar_overlapping_por_parametro(\n # matfile='videos/rgbd/scenes/desk/desk_1.mat',\n # scenenamenum='desk_1',\n # objname='coffee_mug',\n # objnum='5',\n # param='ap_inlier_threshold',\n # path='pruebas_guardadas',\n # include_detections_in_following=False,\n # )\n #\n # analizar_overlapping_por_parametro(\n # matfile='videos/rgbd/scenes/desk/desk_1.mat',\n # scenenamenum='desk_1',\n # objname='cap',\n # objnum='4',\n # param='ap_inlier_threshold',\n # path='pruebas_guardadas',\n # include_detections_in_following=False,\n # )\n #\n # analizar_overlapping_por_parametro(\n # matfile='videos/rgbd/scenes/desk/desk_2.mat',\n # scenenamenum='desk_2',\n # objname='bowl',\n # objnum='3',\n # param='ap_inlier_threshold',\n # path='pruebas_guardadas',\n # include_detections_in_following=False,\n # )\n #\n # analizar_overlapping_por_parametro(\n # matfile='videos/rgbd/scenes/desk/desk_1.mat',\n # scenenamenum='desk_1',\n # objname='coffee_mug',\n # objnum='5',\n # param='ap_points_to_sample',\n # path='pruebas_guardadas',\n # include_detections_in_following=False,\n # )\n #\n # analizar_overlapping_por_parametro(\n # matfile='videos/rgbd/scenes/desk/desk_1.mat',\n # scenenamenum='desk_1',\n # objname='cap',\n # objnum='4',\n # param='ap_points_to_sample',\n # path='pruebas_guardadas',\n # include_detections_in_following=False,\n # )\n #\n # analizar_overlapping_por_parametro(\n # matfile='videos/rgbd/scenes/desk/desk_2.mat',\n # scenenamenum='desk_2',\n # objname='bowl',\n # objnum='3',\n # param='ap_points_to_sample',\n # path='pruebas_guardadas',\n # include_detections_in_following=False,\n # )\n\n # analizar_overlapping_por_parametro(\n # matfile='videos/rgbd/scenes/desk/desk_1.mat',\n # scenenamenum='desk_1',\n # objname='coffee_mug',\n # objnum='5',\n # param='casi_definitivo_NADIA',\n # path='pruebas_guardadas',\n # include_detections_in_following=True,\n # )\n #\n # analizar_overlapping_por_parametro(\n # matfile='videos/rgbd/scenes/desk/desk_1.mat',\n # scenenamenum='desk_1',\n # objname='cap',\n # objnum='4',\n # param='casi_definitivo_NADIA',\n # path='pruebas_guardadas',\n # include_detections_in_following=True,\n # )\n #\n # analizar_overlapping_por_parametro(\n # matfile='videos/rgbd/scenes/desk/desk_2.mat',\n # scenenamenum='desk_2',\n # objname='bowl',\n # objnum='3',\n # param='casi_definitivo_NADIA',\n # path='pruebas_guardadas',\n # include_detections_in_following=True,\n # )\n # analizar_overlapping_por_parametro(\n # matfile='videos/rgbd/scenes/table/table_1.mat',\n # scenenamenum='table_1',\n # objname='coffee_mug',\n # objnum='1',\n # param='casi_definitivo_NADIA',\n # path='pruebas_guardadas',\n # include_detections_in_following=True,\n # )\n #\n # analizar_overlapping_por_parametro(\n # matfile='videos/rgbd/scenes/table/table_1.mat',\n # scenenamenum='table_1',\n # objname='soda_can',\n # objnum='4',\n # param='casi_definitivo_NADIA',\n # path='pruebas_guardadas',\n # include_detections_in_following=True,\n # )\n #\n # analizar_overlapping_por_parametro(\n # matfile='videos/rgbd/scenes/table_small/table_small_2.mat',\n # scenenamenum='table_small_2',\n # objname='cereal_box',\n # objnum='4',\n # param='casi_definitivo_NADIA',\n # path='pruebas_guardadas',\n # include_detections_in_following=True,\n # )\n analyse = [\n ('desk', '1', 'coffee_mug', '5'),\n ('desk', '1', 'cap', '4'),\n ('desk', '1', 'soda_can', '6'),\n ('desk', '2', 'bowl', '3'),\n ('desk', '2', 'soda_can', '4'),\n ('table', '1', 'coffee_mug', '1'),\n ('table', '1', 'coffee_mug', '4'),\n ('table', '1', 'bowl', '2'),\n ('table', '1', 'cap', '1'),\n ('table', '1', 'cap', '4'),\n ('table', '1', 'cereal_box', '4'),\n ('table', '1', 'soda_can', '4'),\n ]\n for scene, scenenum, obj, objnum in analyse:\n analizar_overlapping_por_parametro(\n matfile='videos/rgbd/scenes/{scn}/{scn}_{scnnum}.mat'.format(\n scn=scene,\n scnnum=scenenum,\n ),\n scenenamenum='{scn}_{scnnum}'.format(\n scn=scene,\n scnnum=scenenum,\n ),\n objname='{obj}'.format(obj=obj),\n objnum='{objnum}'.format(objnum=objnum),\n param='probando_frames_parejos_con_ap',\n path='pruebas_guardadas',\n include_detections_in_following=True,\n )\n","sub_path":"codigo/analisis_overlapping_tablas.py","file_name":"analisis_overlapping_tablas.py","file_ext":"py","file_size_in_byte":30466,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"388864381","text":"\"\"\"\nQuestion 202\nWrite an algorithm to determine if a number is \"happy\".\n\nA happy number is a number defined by the following process: Starting with any positive integer, replace the number by the sum of the squares of its digits, and repeat the process until the number equals 1 (where it will stay), or it loops endlessly in a cycle which does not include 1. Those numbers for which this process ends in 1 are happy numbers.\n\nExample: 19 is a happy number\n\n1^2 + 9^2 = 82\n8^2 + 2^2 = 68\n6^2 + 8^2 = 100\n1^2 + 0^2 + 0^2 = 1\nCredits:\n\"\"\"\nclass Solution(object):\n def isHappy(self, n):\n \"\"\"\n :type n: int\n :rtype: bool\n \"\"\"\n freq = {}\n while True:\n if freq.get(n, 0) != 0:#这一步是为了确定会不会产生环\n return False\n else:\n freq.setdefault(n, 1)\n digits = self.divide(n)\n n = reduce(self.computing_sum, digits)\n if n == 1:\n return True\n\n def divide(self, n):#因为reduce函数接受两个参数 所以要把数组的第一个数字设置为零\n results = [0]\n while n / 10 > 0:\n mod = n % 10\n results.append(mod)\n n = (n - mod) / 10\n results.append(n)\n return results\n\n def computing_sum(self, val, y):\n return val + y * y\n","sub_path":"set_and_map/happyNumber.py","file_name":"happyNumber.py","file_ext":"py","file_size_in_byte":1356,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"492668641","text":"#!/usr/bin/env python\n\"\"\"Run Redis-REST with referencing.\"\"\"\nimport argparse\nfrom src.server import app\n\nparser = argparse.ArgumentParser(description='Start REST interface for Redis.')\nparser.add_argument('--host', default='0.0.0.0', type=str)\nparser.add_argument('--port', default=6380, type=int)\n\nargs = parser.parse_args()\n\napp.run(\n host=args.host,\n port=args.port,\n debug=False,\n)\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":395,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"592627440","text":"#!/usr/bin/python\n# -*- coding: utf-8 -*-\n\n# ---------------------------------------------------------------------\n# Copyright (c) 2012 Michael Hull.\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\n# 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\n# the documentation and/or other materials provided with the\n# distribution.\n#\n# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS\n# \"AS IS\" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT\n# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR\n# A 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\n# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,\n# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY\n# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\n# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE\n# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\n# ----------------------------------------------------------------------\nfrom morphforge.stdimports import *\nfrom morphforgecontrib.stdimports import *\n\ndef main():\n\n \"\"\" Change parameters from 3 and show a single spiking and mutltiple spiking neuron in one plot\"\"\"\n \n \"\"\"In this example, we build a single section neuron, with passive channels,\n and stimulate it with a current clamp\"\"\"\n \n \n \n \n env = NEURONEnvironment()\n morphDict1 = {'root': {'length': 20, 'diam': 20, 'id': 'soma'}}\n m1 = MorphologyTree.fromDictionary(morphDict1)\n \n \n def getKSInfTau(env):\n i = InfTauInterpolation(\n V = [-100, -80, -40, 0, 40],\n inf = [0.0, 0.0, 0.2, 0.5, 1.0],\n tau = [0.0, 50, 12, 15, 10]\n )\n \n ks_vars = {'ks': i}\n \n \n ks_chl = env.Channel(\n MM_InfTauInterpolatedChannel,\n name='InfTau1',\n equation='ks*ks*ks*ks',\n conductance='2.:pS/um2',\n reversalpotential='-80:mV',\n statevars_new=ks_vars,\n )\n return ks_chl\n \n \n tr0 = get_voltageclamp_soma_current_trace(env=env, V='-50:mV',\n channel_functor=getKSInfTau, morphology=m1)\n tr1 = get_voltageclamp_soma_current_trace(env=env, V='-20:mV',\n channel_functor=getKSInfTau, morphology=m1)\n tr2 = get_voltageclamp_soma_current_trace(env=env, V='20:mV',\n channel_functor=getKSInfTau, morphology=m1)\n \n \n TagViewer([tr0, tr1, tr2])\n \n \n \n \n \n \n \n #def build_simulation(gbar_multiplier):\n # # Create the morphology for the cell:\n # morphDict1 = {'root': {'length': 20, 'diam': 20, 'id':'soma'} }\n # m1 = MorphologyTree.fromDictionary(morphDict1, name=\"SimpleMorphology1\")\n #\n #\n # # Create the environment:\n # env = NEURONEnvironment()\n #\n # # Create the simulation:\n # sim = env.Simulation(name=\"TestSim1\")\n # cell = sim.create_cell(name=\"Cell1\", morphology=m1)\n #\n #\n # parameters = {\n # 'e_rev': qty('50:mV'),\n # 'gbar': qty('120:pS/um2'),\n #\n # 'm_alpha_a': qty('13.01e3:s-1'),\n # 'm_alpha_b': qty('0e0:V-1 s'),\n # 'm_alpha_c': qty('4.0:'),\n # 'm_alpha_d': qty('6.01e-3:V'),\n # 'm_alpha_e': qty('-12.56e-3:V'),\n #\n # 'm_beta_a': qty('5.73e3:s-1'),\n # 'm_beta_b': qty('0e3:V-1 s'),\n # 'm_beta_c': qty('1.0:'),\n # 'm_beta_d': qty('16.01e-3:V'),\n # 'm_beta_e': qty('9.69e-3:V'),\n #\n # 'h_alpha_a': qty('0.04e3:s-1'),\n # 'h_alpha_b': qty('0.0e3:V-1 s'),\n # 'h_alpha_c': qty('1.0:'),\n # 'h_alpha_d': qty('29.88e-3:V'),\n # 'h_alpha_e': qty('26e-3:V'),\n #\n # 'h_beta_a': qty('2.04e3:s-1'),\n # 'h_beta_b': qty('0.0e3:V-1 s'),\n # 'h_beta_c': qty('1:'),\n # 'h_beta_d': qty('-8.09e-3:V'),\n # 'h_beta_e': qty('-10.21e-3:V'),\n # }\n #\n #\n # ks = getKSInfTau(env)\n #\n #\n #\n #\n # eqnset = EquationSetLoader.load('std_leak_chl.txt',\n # dir=LocMgr.getTestEqnSetsPath())\n # lk_chl = env.Channel(EqnSetChl, eqnset=eqnset,\n # chlname='LeakChls', \n # parameters={'gl': qty('5:pS/um2'), 'e_rev': qty('-70:mV')}\n # )\n #\n #\n #\n #\n #\n # # Apply the mechanisms to the cells\n # cell.apply_channel( lk_chl)\n # cell.apply_channel( ks)\n #\n # cell.set_passive( PassiveProperty.SpecificCapacitance, qty('1.0:uF/cm2'))\n #\n #\n # sim.record(cell, what=StandardTags.Voltage, name=\"SomaVoltage\", cell_location = cell.soma, description='Membrane Voltage (gbar_multiplier = %2.2f)'%gbar_multiplier)\n #\n #\n # sim.create_currentclamp(name='Stim1', amp=qty('200:pA'),\n # dur=qty('100:ms'), delay=qty('100:ms'),\n # cell_location=cell.soma)\n #\n #\n # result = sim.run()\n # return result\n #\n #\n #results = [\n # build_simulation(gbar_multiplier = 1.0),\n # \n # ]\n #\n #TagViewer(results, timerange=(95, 200)*units.ms)\n #pylab.show()\n\nif __name__=='__main__':\n main()\n","sub_path":"src/morphforgecontrib/indev/testInfTau.py","file_name":"testInfTau.py","file_ext":"py","file_size_in_byte":5846,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"169555078","text":"''' Get access to OS libraries: '''\nimport os\n\n''' Import Flask support: '''\nfrom flask import Flask, request, session, redirect, render_template\n\n''' Import OAuth2 libraries: '''\nfrom requests_oauthlib import OAuth2Session\nfrom requests_oauthlib.compliance_fixes import linkedin_compliance_fix\n\n''' Import configuration loader: '''\nfrom loader import ConfigLoader\n\n''' Allow OAuth 2 to work without SSL (only for dev): '''\nos.environ[\"OAUTHLIB_INSECURE_TRANSPORT\"] = \"1\"\n\n''' Load configuration file: '''\nloader = ConfigLoader(os.path.dirname(os.path.realpath(__file__)) + \"/config.ini\")\n\n''' Print database configuration: '''\noauth = loader.get('oauth')\n\n''' Track LinkedIn connection: '''\nlinkedin = None\nstate = None\n\n''' Create Flask application: '''\napp = Flask(__name__)\n\n\n''' Landing page: '''\n@app.route(\"/\")\ndef details():\n data = None\n if linkedin is not None:\n data = linkedin.get(oauth[\"profile_info_url\"]).json()\n return render_template(\"details.html\", title=\"LinkedIn Platform\", data=data)\n\n\n''' Login page which will automatically redirect to the LinkedIn access request page: '''\n@app.route(\"/login\")\ndef login():\n global linkedin, state\n linkedin = linkedin_compliance_fix(OAuth2Session(oauth[\"client_id\"], redirect_uri=oauth[\"redirect_uri\"]))\n authorization_url, state = linkedin.authorization_url(oauth[\"authorization_base_url\"])\n return redirect(authorization_url)\n\n\n''' Callback page for LinkeDIn authorisation: '''\n@app.route(\"/auth\")\ndef auth():\n try:\n linkedin.fetch_token(oauth[\"token_url\"], client_secret=oauth[\"client_secret\"], authorization_response=request.url)\n except:\n print(\"Error : Not ready to authenticate\")\n return redirect(\"/\")\n\n\n''' Run application '''\nif __name__ == \"__main__\":\n app.run()","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1784,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"19360271","text":"import multiprocessing\n\nname = 'django_gunicorn'\nbind = 'unix:/project/django_gunicorn.sock'\nworkers = multiprocessing.cpu_count() * 2 + 1\nkeepalive = 32\nworker_connections = 1000 * workers\nworker_class = \"gevent\"\nreload = True\nloglevel = 'info'\nlogfile = '-'\nspew = False\n\nmax_requests = 1000\nmax_requests_jitter = 50\ngraceful_timeout = 15\ntimeout = 15\n\nBASE_DIR = \"/project\"\npythonpath = BASE_DIR\nchdir = BASE_DIR\n\npreload_app = False\n","sub_path":"d08/gunicorn_conf.py","file_name":"gunicorn_conf.py","file_ext":"py","file_size_in_byte":437,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"25030407","text":"import basic_info\r\nimport requests\r\n\r\nurl = \"https://na1.api.riotgames.com/lol/match/v4/matchlists/by-account/{basic_info.account_id}\"\r\n\r\nrecent_data = requests.get(url).json()[0]\r\n\r\nchampion = requests.get(url).json()[\"champion\"]\r\nmatch_id = requests.get(url).json()[\"gameId\"]\r\n\r\nurl_game = \"https://na1.api.riotgames.com/lol/match/v4/matches/{match_id}\"\r\ngame_data = requests.get(url_game).json()\r\nparticipant_id = 0\r\n\r\nfor players in game_data[\"participantIdentities\"]:\r\n if players[\"player\"][\"summonerName\"] == basic_info.summoner_name:\r\n participant_id = players[\"participantId\"]\r\n\r\nbanned_champ = []\r\nbanned = 0\r\nfirst_dragon = True\r\n\r\n\r\nif participant_id < 5:\r\n banned_champ = game_data[\"teams\"][1][\"bans\"]\r\n if not(game_data[\"teams\"][0][\"firstDragon\"]):\r\n first_dragon = False\r\n \r\nelse:\r\n banned_champ = game_data[\"teams\"][0][\"bans\"]\r\n if not(game_data[\"teams\"][1][\"firstDragon\"]):\r\n first_dragon = False\r\n\r\ndef banning():\r\n for x in banned_champ:\r\n if participant_id == x[\"pickTurn\"]:\r\n banned = x[\"championId\"]\r\n\r\nbanned_champid = banning()","sub_path":"functions.py","file_name":"functions.py","file_ext":"py","file_size_in_byte":1110,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"30019234","text":"# Julián Toledano Díaz\n\nimport redis\nimport datetime\nfrom datetime import timedelta\n\nr = redis.StrictRedis(host='localhost', port=6379, charset=\"utf-8\", decode_responses=True)\nr.setnx('usuarios',1)\n\ndef crear_usuario(nombre, password):\n # Crea el usuario\n id_usuario = r.get('usuarios')\n r.incr('usuarios')\n key_usuario = \"usuario:\"+str(id_usuario)\n r.hset(key_usuario,'nombre', nombre)\n r.hset(key_usuario, 'pass', password)\n r.hset(key_usuario, 'cookies', key_usuario+\":cookies\")\n r.hset(key_usuario, 'seguidores', key_usuario+\":seguidores\")\n r.hset(key_usuario, 'seguidos', key_usuario+\":seguidos\")\n r.hset(key_usuario, 'retransmisiones', key_usuario+\":retransmisiones\")\n r.hset(key_usuario, 'likes', key_usuario+\":likes\") \n\n key_cookie = key_usuario + \":cookie\"\n r.hset(key_usuario, 'cookies', key_cookie)\n r.sadd(key_cookie, \"cookies\")\n d = timedelta(days = 7)\n r.expire(key_cookie,d)\n\ndef seguir(id_seguidor, id_seguido):\n # Añade el seguido a al set de seguidos de seguidor.\n key_seguidor = r.hget(id_seguidor, 'seguidos')\n r.sadd(key_seguidor, id_seguido)\n # Añade al seguidor al set de seguidores de seguido.\n key_seguido = r.hget(id_seguido, 'seguidores')\n r.sadd(key_seguido, id_seguidor)\n\ndef comenzar_retransmision(id_usuario, hashtags):\n contador_retransmisiones = id_usuario+\":total\"\n r.setnx(contador_retransmisiones, 1)\n key_retransmision = id_usuario+\":retransmision:\"+str(r.get(contador_retransmisiones))\n\n # Guardamos todas la retransmisión en el total.\n r.zadd(r.hget(id_usuario, 'retransmisiones'),r.get(contador_retransmisiones), key_retransmision)\n\n # meter los hahstags\n r.hset(key_retransmision, 'hashtags', key_retransmision+\":hashtags\")\n for i in hashtags:\n r.zadd(key_retransmision+\":hashtags\", convertir_ASCII(i), i)\n\n # Está activa\n r.hset(key_retransmision, 'activa', \"True\")\n r.zadd(\"retransmisiones:activas\", r.get(contador_retransmisiones), key_retransmision)\n\n # fecha\n date = datetime.date.today()\n r.hset(key_retransmision, 'fecha', date.strftime('%d-%m-%Y'))\n r.zadd(\"retransmisiones\", fecha_to_int(date.strftime('%Y-%m-%d')), key_retransmision) # Sorted set donde se guardan todas las retrasmisiones ordenadas por fecha\n\n r.hset(key_retransmision, 'likes', key_retransmision+\":likes\") # Usuarios que han dado a like en la retransmision\n r.set(key_retransmision+\":total\", 0)\n r.hset(key_retransmision, 'total_likes', r.get(key_retransmision+\":total\")) # Total de likes\n r.hset(key_retransmision, 'comentarios', key_retransmision+\":comentarios\") # Comentarios\n # Usuarios que han comentado\n r.hset(key_retransmision, 'usuarios', key_retransmision+\":usuarios\") # Usuarios que han comentado\n\n # Avisamos a los seguidores de que comienza una retrasmisión.\n notificar(id_usuario)\n\ndef comentar(id_usuario, retransmision, comentario):\n # Añade el usuario al set de usuarios que comentaron en la retransmision.\n r.sadd(r.hget(retransmision, 'usuarios'), id_usuario)\n # Añade el comentario al set de comentarios\n r.sadd(r.hget(retransmision, 'comentarios'), comentario)\n # notificar a todos los usuarios que se ha realizado un comentario.\n r.publish(\"channel.\"+retransmision[8]+\".comentarios\", \"nuevo comentario\")\n\ndef like(id_usuario, retransmision):\n # Añade el id del usuario al set de usuarios que dieron like.\n r.sadd(r.hget(retransmision, 'likes'), id_usuario)\n # Añade la retransmisión al set de retransmisiones que le gustaron al usuario.\n r.sadd(r.hget(id_usuario,'likes'),retransmision)\n # Incrementa en uno el total de likes que ha recibido la retransmisión.\n r.incr(retransmision+\":total\")\n r.hset(retransmision, 'total_likes', r.get(retransmision+\":total\"))\n # Notificar al resto de usuarios que han dado like.\n r.publish(\"channel.\"+retransmision[8]+\".likes\", \"nuevo like\")\n\ndef terminar_retransmision(id_usuario, retransmision):\n # Incrementa en uno el número de retransmisiones que ha hecho el usuario.\n r.incr(id_usuario+\":total\")\n # Indica que la retransmisión ya no está activa.\n r.hset(retransmision, 'activa', \"False\")\n # Añadimos a retransmisiones no activas,\n r.sadd(\"retransmisiones:no_activas\", retransmision)\n # y la borramos del set de activas.\n r.zrem(\"retransmisiones:activas\", retransmision)\n\n# O(n)\ndef buscar(hashtag):\n # Recorremos el total de las retransmisiones\n total = r.zscan(\"retransmisiones\",0,\"*\")[1]\n # Por cada retransmisión comprobamos si contiene ese hashtag.\n for i in total:\n score = convertir_ASCII(hashtag)\n x = r.zrangebyscore(i[0]+\":hashtags\", score, score)\n if x[0] == hashtag:\n print (i[0])\n\ndef notificar(usuario):\n id_ = usuario[-1:]\n r.publish(\"channel.\"+str(id_), \"comienza una retransmision\")\n\n# No funciona. Devuleve None. El mismo proceso desde una terminal sí funciona.\n# Para notificar de nuevos likes y comentarios sería un proceso similar.\n# Funciona desde terminal.¿?\ndef comprobar(publi, oye):\n seguidos = r.smembers(oye+\":seguidos\")\n for i in seguidos:\n if i == publi:\n sub = r.pubsub()\n sub.subscribe(\"channel.\"+str(publi[-1:]))\n men = sub.get_message()\n print(men)\n\n# En vez de utilizar un iterador he optado por un range.\ndef ultimas_retransmisiones():\n retrans = r.zrevrange(\"retransmisiones\",0,2)\n for i in retrans:\n print(i)\n# Elimina los guiones de la string que devuelve la clase date de datetime.\ndef fecha_to_int(fecha):\n return int(fecha.replace('-',''))\n\n# Concatena los valores ASCII de una cadena con el fin de crear un score único\ndef convertir_ASCII(hashtag):\n hashh = ''.join(str(ord(c)) for c in hashtag)\n return int(hashh)\n","sub_path":"practicaRedis/julian_redis.py","file_name":"julian_redis.py","file_ext":"py","file_size_in_byte":5952,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"151094910","text":"'''\nimport pdfquery\npdf = pdfquery.PDFQuery(\"pdfs/Combined-agenda-and-documents.pdf\")\npdf.load()\npdf.tree.write('test.xml', pretty_print=True)\n'''\n# Adapted from https://reachtim.com/articles/PDF-Manipulation.html\n# Updated to python 3 by Austin Crapo\n# File Split Implemented by Gregory Gould\nfrom io import StringIO\nfrom pdfminer.pdfinterp import PDFResourceManager, PDFPageInterpreter\nfrom pdfminer.converter import TextConverter\nfrom pdfminer.layout import LAParams\nfrom pdfminer.pdfpage import PDFPage\nimport sys\n\ndef convert(fname, pages=None):\n\tif not pages:\n\t\tpagenums = set()\n\telse:\n\t\tpagenums = set(pages)\n\n\toutput = StringIO()\n\tmanager = PDFResourceManager()\n\tconverter = TextConverter(manager, output, laparams=LAParams())\n\tinterpreter = PDFPageInterpreter(manager, converter)\n\n\tinfile = open(fname, 'rb')\n\tfor page in PDFPage.get_pages(infile, pagenums):\n\t\tinterpreter.process_page(page)\n\tinfile.close()\n\tconverter.close()\n\ttext = output.getvalue()\n\toutput.close\n\t\n\treturn text\n\n\ndef parse(fileName):\n\tlineCount = 0\n\tpageCount = 0\n\ti= 0\n\twith open(fileName,'rb') as file:\n\t\tfor text in file:\n\t\t\t# Line Count to show progress\n\t\t\tlineCount = lineCount + 1\n\t\t\tif (lineCount % 23 == 0): #23 lines/page at 12pt font\n\t\t\t\tpageCount = pageCount + 1\n\t\t\t\tprint(\"Pages Printed: \"+str(pageCount))\t\t\t\n\t\t\t# Read lines\n\t\t\tif keywords[i] in text:\n\t\t\t\ti = i + 1\n\t\t\t\tprint(\"i: \"+str(i-1)+\"|\"+str(keywords[i-1]))\n\t\t\tif i > 0:\n\t\t\t\tfilePointers[i-1].write(text)\t\n\t\nprint(\"Begin Approved-Minutes Scraper \\n\")\n\nfileName = 'Approved-Minutes-GFC-NO-27'\n\n\noutput = convert(fileName + '.pdf')\nfh = open(fileName+\".txt\",\"wb\")\noutput = output.encode('utf-8').strip()\nfh.write(output)\nfh.close() #Save text stripped PDF\n\n# Define deliniators \nkeywords = []\nfilePointers = []\n\nsplitNames = [\"ATTENDEES\",\"OPENING_SESSION\",\"DISCUSSION_ITEMS\", \"ACTION_ITEMS\", \"QUESTION_PERIOD\", \"INFORMATION_REPORTS\", \"CLOSING_SESSION\"]\n\nsplitStrings = [\"ATTENDEES\",\"OPENING SESSION\",\"DISCUSSION ITEMS\", \"ACTION ITEMS\", \"DISCUSSION ITEMS\", \"INFORMATION REPORTS\", \"CLOSING SESSION\"]\nnumberSplit = len(splitStrings)\n\n# Create Files for each individual thing\ni = 0\nwhile (i < numberSplit):\n\tkeywords.append(splitStrings[i].encode('utf-8'))\n\tfp = open(fileName + \"_\" + splitNames[i], 'wb')\n\tfilePointers.append(fp)\n\t#print(str(splitNames[i])+\" Pointer i: \"+str(i))\n\ti = i + 1\n\nkeywords.append(splitStrings[0].encode('utf-8')) #Add an extra\n\n\nparse(\"scrapeTest.txt\")\n\t\t\t\n# Close files\nfor file in filePointers:\n\t#print(\"Closing: \" + str(file))\n\tfile.close()\nprint()\t\nprint(fileName + \" is finished being processed\")","sub_path":"pdf_scrape/pdf_scraper.py","file_name":"pdf_scraper.py","file_ext":"py","file_size_in_byte":2573,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"93335948","text":"\nfrom django.db import models\n\n# Create your models here.\n\n\n\nclass Faq(models.Model):\n title = models.CharField(max_length=30, db_column='title')\n content = models.TextField(db_column='content')\n\n class Meta:\n db_table = 'faq'\n verbose_name_plural = 'Faq'","sub_path":"faq/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":278,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"95569188","text":"from __future__ import division\nfrom __future__ import unicode_literals\n\nfrom django.core.urlresolvers import reverse\nfrom django.test import TestCase\nfrom django.test.utils import override_settings\n\n\n@override_settings(LANGUAGE_CODE='en')\nclass NormalizeLanguageCodeMiddlewareTestCase(TestCase):\n def setUp(self):\n self.url = reverse('auth_login')\n\n def test_simple_positive_case(self):\n \"\"\"test that a request with no accept-language header gets the default language\"\"\"\n response = self.client.get(self.url)\n self.assertEqual(200, response.status_code)\n self.assertContains(response, ' theta x\n self.wignerfunction = fftpack.fft(self.wignerfunction, axis=0, overwrite_x=True)\n self.wignerfunction *= expV\n\n # theta x -> p x\n self.wignerfunction = fftpack.ifft(self.wignerfunction, axis=0, overwrite_x=True)\n\n # p x -> p lambda\n self.wignerfunction = fftpack.fft(self.wignerfunction, axis=1, overwrite_x=True)\n self.wignerfunction *= self.get_expK(self.t)\n\n # p lambda -> p x\n self.wignerfunction = fftpack.ifft(self.wignerfunction, axis=1, overwrite_x=True)\n\n # p x -> theta x\n self.wignerfunction = fftpack.fft(self.wignerfunction, axis=0, overwrite_x=True)\n self.wignerfunction *= expV\n\n # theta x -> p x\n self.wignerfunction = fftpack.ifft(self.wignerfunction, axis=0, overwrite_x=True)\n\n # normalization\n self.wignerfunction /= self.wignerfunction.sum() * dXdP\n\n # calculate the Ehrenfest theorems\n self.get_Ehrenfest(self.t)\n\n # increment current time\n self.t += self.dt\n\n return self.wignerfunction\n\n def get_Ehrenfest(self, t):\n \"\"\"\n Calculate observables entering the Ehrenfest theorems at time (t)\n \"\"\"\n if self.isEhrenfest:\n # calculate the coordinate density\n density_coord = self.wignerfunction.real.sum(axis=0)\n # normalize\n density_coord /= density_coord.sum()\n\n # save the current value of \n self.X_average.append(\n np.dot(density_coord, self.X.reshape(-1))\n )\n self.P_average_RHS.append(\n -np.dot(density_coord, self.get_diff_V(t).reshape(-1))\n )\n\n # calculate density in the momentum representation\n density_momentum = self.wignerfunction.real.sum(axis=1)\n # normalize\n density_momentum /= density_momentum.sum()\n\n # save the current value of

    \n self.P_average.append(\n np.dot(density_momentum, self.P.reshape(-1))\n )\n self.X_average_RHS.append(\n np.dot(density_momentum, self.get_diff_K(t).reshape(-1))\n )\n\n # save the current expectation value of energy\n self.hamiltonian_average.append(\n np.dot(density_momentum, self.get_K(t).reshape(-1))\n +\n np.dot(density_coord, self.get_V(t).reshape(-1))\n )\n\n def get_expV(self, t):\n \"\"\"\n Return the exponent of the potential energy difference at time (t)\n \"\"\"\n try:\n # aces the pre-calculated value\n return self._expV\n except AttributeError:\n # Calculate in efficient way\n result = -self.dt*0.5j*(self.V(self.X - 0.5*self.Theta, t) - self.V(self.X + 0.5*self.Theta, t))\n return np.exp(result, out=result)\n\n def get_expK(self, t):\n \"\"\"\n Return the exponent of the kinetic energy difference at time (t)\n \"\"\"\n try:\n # aces the pre-calculated value\n return self._expK\n except AttributeError:\n # Calculate result = np.exp(*self.K(self.P1, self.P2, t))\n result = -self.dt*1j*(self.K(self.P + 0.5*self.Lambda, t) - self.K(self.P - 0.5*self.Lambda, t))\n return np.exp(result, out=result)\n\n def get_diff_V(self, t):\n \"\"\"\n Return the RHS for the Ehrenfest theorem at time (t)\n \"\"\"\n try:\n # access the pre-calculated value\n return self._diff_V\n except AttributeError:\n return self.diff_V(self.X, t)\n\n def get_diff_K(self, t):\n \"\"\"\n Return the RHS for the Ehrenfest theorem at time (t)\n \"\"\"\n try:\n # access the pre-calculated value\n return self._diff_K\n except AttributeError:\n return self.diff_K(self.P, t)\n\n def get_K(self, t):\n \"\"\"\n Return the kinetic energy at time (t)\n \"\"\"\n try:\n return self._K\n except AttributeError:\n return self.K(self.P, t)\n\n def get_V(self, t):\n \"\"\"\n Return the potential energy at time (t)\n \"\"\"\n try:\n return self._V\n except AttributeError:\n return self.V(self.X, t)\n\n def set_wignerfunction(self, new_wigner_func):\n \"\"\"\n Set the initial Wigner function\n :param new_wigner_func: 2D numoy array contaning the wigner function\n :return: self\n \"\"\"\n # perform the consistency checks\n assert new_wigner_func.shape == (self.P.size, self.X.size), \\\n \"The grid sizes does not match with the Wigner function\"\n\n # make sure the Wigner function is stored as a complex array\n self.wignerfunction = new_wigner_func + 0j\n\n # normalize\n self.wignerfunction /= self.wignerfunction.sum() * self.dX*self.dP\n\n return self\n\n##############################################################################\n#\n# Run some examples\n#\n##############################################################################\n\nif __name__ == '__main__':\n\n # load tools for creating animation\n import sys\n\n if sys.platform == 'darwin':\n # only for MacOS\n import matplotlib\n matplotlib.use('TKAgg')\n\n import matplotlib.pyplot as plt\n from matplotlib.animation import FuncAnimation\n\n # Use the documentation string for the developed class\n print(SplitOpWignerMoyal.__doc__)\n\n\n class VisualizeDynamicsPhaseSpace:\n \"\"\"\n Class to visualize the Wigner function function dynamics in phase space.\n \"\"\"\n def __init__(self, fig):\n \"\"\"\n Initialize all propagators and frame\n :param fig: matplotlib figure object\n \"\"\"\n # Initialize systems\n self.set_quantum_sys()\n\n #################################################################\n #\n # Initialize plotting facility\n #\n #################################################################\n\n self.fig = fig\n\n ax = fig.add_subplot(111)\n\n ax.set_title('Wigner function, $W(x,p,t)$')\n extent=[self.quant_sys.X.min(), self.quant_sys.X.max(), self.quant_sys.P.min(), self.quant_sys.P.max()]\n\n # import utility to visualize the wigner function\n from wigner_normalize import WignerNormalize\n\n # generate empty plot\n self.img = ax.imshow([[]],\n extent=extent,\n origin='lower',\n cmap='seismic',\n norm=WignerNormalize(vmin=-0.01, vmax=0.1)\n )\n\n self.fig.colorbar(self.img)\n\n ax.set_xlabel('$x$ (a.u.)')\n ax.set_ylabel('$p$ (a.u.)')\n\n def set_quantum_sys(self):\n \"\"\"\n Initialize quantum propagator\n :param self:\n :return:\n \"\"\"\n omega_square = np.random.uniform(1, 3)\n\n self.quant_sys = SplitOpWignerMoyal(\n t=0,\n dt=0.005,\n X_gridDIM=256,\n X_amplitude=8.,\n P_gridDIM=256,\n P_amplitude=7.,\n\n # kinetic energy part of the hamiltonian\n K=lambda p: 0.5*p**2,\n\n # potential energy part of the hamiltonian\n V=lambda x: 0.5*omega_square*x**2,\n\n # these functions are used for evaluating the Ehrenfest theorems\n diff_K=lambda p: p,\n diff_V=lambda x: omega_square*x,\n )\n\n # parameter controling the width of the wigner function\n sigma = np.random.uniform(0.5, 3.)\n\n # set randomised initial condition\n self.quant_sys.set_wignerfunction(\n np.exp(\n # randomized position\n -sigma*(self.quant_sys.X + np.random.uniform(-1., 1.))**2\n # randomized initial velocity\n -(1./sigma)*(self.quant_sys.P + np.random.uniform(-1., 1.))**2\n )\n )\n\n def empty_frame(self):\n \"\"\"\n Make empty frame and reinitialize quantum system\n :param self:\n :return: image object\n \"\"\"\n self.set_quantum_sys()\n self.img.set_array([[]])\n return self.img,\n\n def __call__(self, frame_num):\n \"\"\"\n Draw a new frame\n :param frame_num: current frame number\n :return: image objects\n \"\"\"\n # propagate the wigner function\n self.img.set_array(self.quant_sys.propagate(20).real)\n return self.img,\n\n\n fig = plt.gcf()\n visualizer = VisualizeDynamicsPhaseSpace(fig)\n animation = FuncAnimation(fig, visualizer, frames=np.arange(100),\n init_func=visualizer.empty_frame, repeat=True, blit=True)\n plt.show()\n\n # extract the reference to quantum system\n quant_sys = visualizer.quant_sys\n\n # Analyze how well the energy was preseved\n h = np.array(quant_sys.hamiltonian_average)\n print(\n \"\\nHamiltonian is preserved within the accuracy of %f percent\" % ((1. - h.min() / h.max()) * 100)\n )\n\n #################################################################\n #\n # Plot the Ehrenfest theorems after the animation is over\n #\n #################################################################\n\n # generate time step grid\n dt = quant_sys.dt\n times = np.arange(dt, dt + dt * len(quant_sys.X_average), dt)\n\n plt.subplot(131)\n plt.title(\"The first Ehrenfest theorem verification\")\n\n plt.plot(times, np.gradient(quant_sys.X_average, dt), 'r-', label='$d\\\\langle x \\\\rangle/dt$')\n plt.plot(times, quant_sys.X_average_RHS, 'b--', label='$\\\\langle p \\\\rangle$')\n\n plt.legend()\n plt.xlabel('time $t$ (a.u.)')\n\n plt.subplot(132)\n plt.title(\"The second Ehrenfest theorem verification\")\n\n plt.plot(times, np.gradient(quant_sys.P_average, dt), 'r-', label='$d\\\\langle p \\\\rangle/dt$')\n plt.plot(times, quant_sys.P_average_RHS, 'b--', label='$\\\\langle -\\\\partial \\\\partial V/\\\\partial x \\\\rangle$')\n\n plt.legend()\n plt.xlabel('time $t$ (a.u.)')\n\n plt.subplot(133)\n plt.title('Hamiltonian')\n plt.plot(times, h)\n plt.xlabel('time $t$ (a.u.)')\n\n plt.show()\n\n","sub_path":"split_op_wigner_moyal_complex.py","file_name":"split_op_wigner_moyal_complex.py","file_ext":"py","file_size_in_byte":16995,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"212871547","text":"# Python\nimport simplejson\nimport urllib\nimport urllib2\nimport hmac\nimport hashlib\nfrom datetime import datetime, timedelta\n\n# Django \nfrom django.db import models\nfrom django.db.models.aggregates import Avg, Max, Count\nfrom django.contrib.auth.models import User\nfrom django.contrib.contenttypes.models import ContentType\nfrom django.core.exceptions import ValidationError\nfrom django.core.urlresolvers import reverse\nfrom django import forms\nfrom django.conf import settings\nfrom django.utils.functional import curry\nfrom django.utils.translation import ugettext_lazy as _\nfrom django.template import loader, Context\n\n# A+\nfrom inheritance.models import ModelWithInheritance\nfrom course.models import *\nfrom lib import MultipartPostHandler\nfrom lib.fields import PercentField\nfrom exercise.exercise_page import ExercisePage\nfrom userprofile.models import UserProfile\n\nclass CourseModule(models.Model):\n \"\"\" \n CourseModule objects connect learning objects to logical sets of each other and \n course instances. They also contain information about the opening times and \n deadlines for exercises. \n \"\"\"\n name = models.CharField(max_length=255)\n points_to_pass = models.PositiveIntegerField(default=0)\n \n # A textual introduction to this exercise round\n introduction = models.TextField(blank=True)\n \n # Relations\n course_instance = models.ForeignKey(CourseInstance, related_name=u\"course_modules\")\n \n # Fields related to the opening of the rounds\n opening_time = models.DateTimeField(default=datetime.now)\n closing_time = models.DateTimeField(default=datetime.now)\n \n def get_exercises(self):\n return BaseExercise.objects.filter(course_module=self)\n \n \"\"\"\n Functionality related to early bonuses has been disabled. The following lines\n are commented out so that they can be restored later if necessary.\n \n # Settings related to early submission bonuses\n early_submissions_allowed= models.BooleanField(default=False)\n early_submissions_start = models.DateTimeField(default=datetime.now, blank=True, null=True)\n early_submission_bonus = PercentField(default=0.1, \n help_text=_(\"Multiplier of points to reward, as decimal. 0.1 = 10%\"))\n \"\"\"\n # Settings that can be used to allow late submissions to exercises\n late_submissions_allowed= models.BooleanField(default=False)\n late_submission_deadline= models.DateTimeField(default=datetime.now)\n late_submission_penalty = PercentField(default=0.5, \n help_text=_(\"Multiplier of points to reduce, as decimal. 0.1 = 10%\"))\n \n def is_late_submission_open(self):\n return self.late_submissions_allowed and \\\n self.closing_time <= datetime.now() <= self.late_submission_deadline\n \n def is_open(self, when=None):\n when = when or datetime.now()\n return self.opening_time <= when <= self.closing_time\n \n def is_after_open(self, when=None):\n \"\"\"\n Returns True if current time is past the round opening time.\n \"\"\"\n when = when or datetime.now()\n return self.opening_time <= when\n\n def __unicode__(self):\n return self.name\n \n def get_breadcrumb(self):\n \"\"\" \n Returns a list of tuples containing the names and URL \n addresses of parent objects and self. \n \"\"\"\n return self.course_instance.get_breadcrumb()\n \n class Meta:\n app_label = 'exercise'\n ordering = ['closing_time', 'id']\n\n\nclass LearningObjectCategory(models.Model):\n name = models.CharField(max_length=35)\n description = models.TextField(blank=True)\n points_to_pass = models.PositiveIntegerField(default=0)\n\n course_instance = models.ForeignKey(CourseInstance,\n related_name=u\"categories\")\n\n hidden_to = models.ManyToManyField(\n UserProfile,\n related_name=\"hidden_categories\",\n blank=True,\n null=True)\n\n class Meta:\n unique_together = (\"name\", \"course_instance\")\n\n def __unicode__(self):\n return self.name + u\" -- \" + unicode(self.course_instance)\n\n def is_hidden_to(self, profile):\n return profile in self.hidden_to.all()\n\n def set_hidden_to(self, profile, hide=True):\n if hide and not self.is_hidden_to(profile):\n self.hidden_to.add(profile)\n elif not hide and self.is_hidden_to(profile):\n self.hidden_to.remove(profile)\n\n\nclass LearningObject(ModelWithInheritance):\n # The order for sorting the exercises within an exercise round\n order = models.IntegerField(default=0)\n \n # Instruction related fields\n name = models.CharField(max_length=255)\n description = models.TextField(blank=True)\n instructions = models.TextField(blank=True)\n\n # TODO: deprecated\n # verify_exists is deprecated in Django 1.4 and removed in Django 1.5 because of security issues\n # However, in Django 1.3.0, it defaults to True, which is undesired, so we must have verify_exists=False with\n # this version of Django\n service_url = models.URLField(verify_exists=False, blank=True)\n \n # Relations\n course_module = models.ForeignKey(CourseModule, related_name=\"learning_objects\")\n category = models.ForeignKey(LearningObjectCategory,\n related_name=\"learning_objects\")\n\n def clean(self):\n course_instance_error = ValidationError(\"course_module and category \"\n \"must relate to the same \"\n \"CourseInstance object\")\n\n try:\n if (self.course_module.course_instance\n != self.category.course_instance):\n raise course_instance_error\n except (LearningObjectCategory.DoesNotExist,\n CourseModule.DoesNotExist):\n raise course_instance_error\n\n def get_course_instance(self):\n return self.course_module.course_instance\n course_instance = property(get_course_instance)\n\n\nclass BaseExercise(LearningObject):\n # Switch for giving assistants permission to grade this exercise\n allow_assistant_grading = models.BooleanField(default=False)\n \n # Submission related fields\n min_group_size = models.PositiveIntegerField(default=1)\n max_group_size = models.PositiveIntegerField(default=1)\n max_submissions = models.PositiveIntegerField(default=10)\n max_points = models.PositiveIntegerField(default=100)\n points_to_pass = models.PositiveIntegerField(default=40)\n \n def get_deadline(self):\n return self.course_module.closing_time\n def get_page(self, submission_url):\n \"\"\" \n Retrieves the page for this exercise from the exercise service. \n \n @param submission_url: the submission url where the service may return submissions\n @return: an ExercisePage object created from data retrieved from exercise service \n \"\"\"\n \n # Build the URL with a callback address, max points etc.\n url = self.build_service_url(submission_url)\n \n opener = urllib2.build_opener()\n page_content = opener.open(url, timeout=20).read()\n \n return ExercisePage(self, page_content)\n\n def have_submissions_left(self, students):\n \"\"\"\n Figures if all the students in the given set have submissions left for\n this exercise. Considers the possible MaxSubmissionsRuleDeviations for\n each student.\n @param students: an iterable of UserProfile objects\n @return: True if everyone has submissions left or False if anyone has\n exceeded the maximum amount of submissions allowed for him.\n \"\"\"\n if self.max_submissions == 0:\n return True\n\n # Different group members might have different amount of submissions to\n # this exercise. Thus, we count the submissions separately for each\n # student.\n for student in students:\n if not self.submissions_left(student) > 0:\n return False\n\n # All had submissions left.\n return True\n\n def max_submissions_for(self, student):\n \"\"\"\n Calculates student specific max_submissions considering the possible\n MaxSubmissionsRuleDeviation for this student.\n @param student: UserProfile object\n @return: max_submissions\n \"\"\"\n try:\n msr_deviation = MaxSubmissionsRuleDeviation.objects.get(\n exercise=self,\n submitter=student)\n if self.max_submissions == 0:\n return self.max_submissions\n else:\n return msr_deviation.extra_submissions + self.max_submissions\n except MaxSubmissionsRuleDeviation.DoesNotExist:\n return self.max_submissions\n\n def submissions_left(self, student):\n \"\"\"\n Calculates submissions left for the given student considering the\n possible MaxSubmissionsRuleDeviation for this student.\n @param student: UserProfile object\n @return: submissions left or None if there is no submission limit\n \"\"\"\n if self.max_submissions == 0:\n return None\n\n count = self.submissions.filter(submitters=student).count()\n return self.max_submissions - count\n \n def submit(self, submission):\n \"\"\" \n This method sends the given submission to the exercise service \n along with the files related to the submission. \n \"\"\"\n \n # Make sure that this is the correct exercise for the submission\n assert self.id == submission.exercise.id\n \n # Create an empty list for HTTP request parameters\n post_params = []\n \n # Parameters are appended to the list as key, value tuples. \n # Using tuples makes it possible to add two values for the same key.\n for (key, value) in submission.submission_data:\n post_params.append( (key, value) )\n \n # Then the files are appended as key, file handle tuples\n for submitted_file in submission.files.all():\n param_name = submitted_file.param_name\n file_handle = open(submitted_file.file_object.path, \"rb\")\n post_params.append( (param_name, file_handle) )\n \n # Allow to make necessary modifications to POST parameters\n self.modify_post_params(post_params)\n\n # Build the service URL, which contains maximum points for this exercise\n # and a callback URL to which the service may return the grading\n url = self.build_service_url( submission.get_callback_url() )\n \n opener = urllib2.build_opener(MultipartPostHandler.MultipartPostHandler)\n response_body = opener.open(url.encode('ascii'), post_params, timeout=50).read()\n \n # Close all opened file handles\n for (key, value) in post_params:\n if type(value) == file:\n value.close()\n \n return ExercisePage(self, response_body)\n \n def modify_post_params(self, post_params):\n \"\"\"\n Allows to modify POST parameters before they are sent to the grader.\n @param post_params: original POST parameters \n \"\"\"\n pass\n\n def is_open(self, when=None):\n \"\"\"\n Returns True if submissions are allowed for this exercise.\n \"\"\"\n when = when or datetime.now()\n return self.course_module.is_open(when=when)\n\n def is_open_for(self, students, when=None):\n \"\"\"\n Considers the is_open and the DeadlineRuleDeviations.\n @param students: An iterable of UserProfiles\n @return: boolean\n \"\"\"\n\n when = when or datetime.now()\n\n if not self.is_open(when=when):\n # Lets check if there are DeadlineExceptions for the given\n # students.\n dlr_deviations = DeadlineRuleDeviation.objects.filter(\n exercise=self,\n submitter__in=students).distinct()\n\n if len(dlr_deviations) > 0:\n # Now we need to check if there are enough extra time given for\n # each of the students.\n base_dl = self.get_deadline()\n # Initialise the dict with Falses meaning that the exercise is\n # closed for each of the students.\n is_open_booleans_by_submitters = {s: False for s in students}\n\n for dlrd in dlr_deviations:\n if when <= base_dl + timedelta(\n minutes=dlrd.extra_minutes):\n assert(\n dlrd.submitter in is_open_booleans_by_submitters)\n is_open_booleans_by_submitters[dlrd.submitter] = True\n\n if False in is_open_booleans_by_submitters.values():\n # Not all the submitters had enough extra time given.\n return False\n else:\n # All the submitters had enough extra time given.\n return True\n else:\n # No exceptions for any of the submitters.\n return False\n\n else:\n # The exercise is open for given students in given time.\n return True\n \n def is_submission_allowed(self, students):\n \"\"\"\n Returns True or False based whether the submission \n to this exercise is allowed or not based on the parameters.\n \n @param students: the students who are submitting this exercise\n @return: boolean indicating if submissions should be accepted\n @return: errors as a list of strings\n \"\"\"\n \n errors = []\n\n # Check if the number of students is allowed for this exercise\n allowed_group_size = (self.min_group_size\n <= students.count() <=\n self.max_group_size)\n \n if not self.have_submissions_left(students):\n if students.count() == 1:\n errors.append(_('You already have used the maximum amount of '\n 'submissions allowed to this exercise.'))\n else:\n errors.append(_('One of the group members already has used '\n 'the maximum amount of submissions allowed to '\n 'this exercise.'))\n\n # Check if the exercise is open for the given students.\n # Submissions by superusers, staff, course teachers and course instance\n # assistants are still allowed.\n if (not self.is_open_for(students)\n and not self.is_late_submission_allowed()\n and not (\n students.count() == 1 and (\n students[0].user.is_superuser\n or students[0].user.is_staff\n or self.course_module.course_instance.course.is_teacher(\n students[0]\n )\n or self.course_module.course_instance.is_assistant(\n students[0]\n )))):\n errors.append('This exercise is not open for submissions.')\n \n if not allowed_group_size:\n errors.append(_('This exercise can be submitted in groups of %d to'\n ' %d students.') % (self.min_group_size,\n self.max_group_size)\n + \" \"\n + _('The size of your current group is %d.')\n % students.count())\n \n success = len(errors) == 0\n return success, errors\n \n def is_late_submission_allowed(self):\n return self.course_module.late_submissions_allowed\n \n def get_late_submission_penalty(self):\n return self.course_module.late_submission_penalty\n \n def build_service_url(self, submission_url):\n \"\"\"\n Generates and returns a complete URL with added parameters to the exercise service.\n \n @param submission_url: the URL where the service may return grading details\n \"\"\"\n full_url = settings.BASE_URL + submission_url\n \n params = {\"max_points\" : self.max_points,\n \"submission_url\" : full_url,\n }\n \n # If there is already a question mark in the url, use ampersand as delimiter. Otherwise \n # use question mark.\n delimiter = (\"?\", \"&\")[\"?\" in self.service_url]\n \n url = self.service_url + delimiter + urllib.urlencode(params)\n return url\n \n def get_submissions_for_student(self, userprofile):\n \"\"\" \n Returns all submissions for the given user profile for this exercise.\n \n @param userprofile: the user's profile whose submissions to find\n @return: a QuerySet of matching submissions \n \"\"\"\n return userprofile.submissions.filter(exercise=self)\n \n def __unicode__(self):\n return self.name\n \n def get_absolute_url(self):\n return reverse(\"exercise.views.view_exercise\", kwargs={\"exercise_id\": self.id})\n \n def get_submission_parameters_for_students(self, students):\n '''\n @param students: a QuerySet of UserProfiles\n @return: a string with UserProfile ids and a hash\n @return: a string with UserProfile ids and a hash\n '''\n student_str = \"-\".join( str(userprofile.id) for userprofile in students )\n identifier = \"%s.%d\" % (student_str, self.id)\n hash = hmac.new(settings.SECRET_KEY, \n msg=identifier, \n digestmod=hashlib.sha256).hexdigest()\n return student_str, hash\n \n def get_submission_url_for_students(self, students):\n '''\n Creates and returns an URL where a submission can be made for the given students\n \n @param students: a QuerySet of UserProfile objects for the students submitting the exercise\n @return: an URL where submissions are accepted for the students\n '''\n student_str, hash = self.get_submission_parameters_for_students(students)\n \n return reverse(\"exercise.async_views.new_async_submission\", \n kwargs={\"student_ids\": student_str,\n \"exercise_id\": self.id,\n \"hash\": hash})\n \n def __get_summary(self):\n \"\"\"\n Returns a dictionary which has summarized statistics of this exercise. The dictionary is\n generated only once and saved into a private field to improve performance with subsequent\n calls.\n \n @return: a dictionary keys: submission_count, average_grade, average_submissions and\n submitter_count\n \"\"\"\n if not hasattr(self, \"temp_summary\"):\n submission_count = self.submissions.count()\n submitter_count = UserProfile.objects.distinct().filter(submissions__exercise=self).count()\n \n average_grade = UserProfile.objects.distinct().filter(submissions__exercise=self).annotate(best_grade=Max('submissions__grade')).aggregate(average_grade=Avg('best_grade'))[\"average_grade\"]\n average_submissions = UserProfile.objects.distinct().filter(submissions__exercise=self).annotate(submission_count=Count('submissions')).aggregate(avg_submissions=Avg('submission_count'))[\"avg_submissions\"]\n \n if average_grade == None:\n average_grade = 0\n if average_submissions == None:\n average_submissions = 0\n \n self.temp_summary = {\"submission_count\" : submission_count,\n \"average_grade\" : average_grade,\n \"submitter_count\" : submitter_count,\n \"average_submissions\": average_submissions,\n }\n return self.temp_summary\n \n summary = property(__get_summary)\n \n @classmethod\n def get_exercise(cls, *args, **kwargs):\n \"\"\"\n Returns an object matching the given query parameters as an \n instance of the exercise's actual class, not the super class.\n \"\"\"\n return cls.objects.get(*args, **kwargs).as_leaf_class()\n \n def get_breadcrumb(self):\n \"\"\" \n Returns a list of tuples containing the names and url \n addresses of parent objects and self. \n \"\"\"\n crumb = self.course_module.get_breadcrumb()\n crumb_tuple = (str(self), self.get_absolute_url())\n crumb.append(crumb_tuple)\n return crumb\n \n def can_edit(self, userprofile):\n \"\"\"\n Returns a boolean value indicating if the given user profile is allowed to edit \n this exercise. Superusers and teachers are allowed to edit exercises.\n \n @param userprofile: the user profile whose permissions are checked\n @return: True if is allowed, False otherwise\n \"\"\"\n if userprofile.user.is_superuser:\n return True\n \n if self.course_module.course_instance.course.is_teacher(userprofile):\n return True\n \n return False\n \n class Meta:\n app_label = 'exercise'\n ordering = ['course_module__closing_time', 'course_module', 'order', 'id']\n\n\nclass AsynchronousExercise(BaseExercise):\n \"\"\" \n Asynchronous exercises are used when the assessment service does not grade the \n exercises immediately after submission. Instead, the exercise system will call \n a submission URL after assessing and generating feedback. \n \"\"\"\n pass\n\n\nclass SynchronousExercise(BaseExercise):\n \"\"\" \n Synchronous exercises are submitted and assessed during a single HTTP request.\n The exercise service will respond to POST requests with a number of points and \n a feedback for the student. \n \"\"\"\n pass\n\n\nclass StaticExercise(BaseExercise):\n \"\"\" \n Static exercises are used for storing submissions on the server, but not automatically \n assessing them. Static exercises may be retrieved by other services through the API. \n \"\"\"\n \n exercise_page_content = models.TextField()\n submission_page_content = models.TextField()\n \n \n def get_page(self, submission_url=None):\n \"\"\"\n @param submission_url: the submission url where the service may return submissions\n @return: an ExercisePage object created from data retrieved from exercise service \n \"\"\"\n page = ExercisePage(self)\n page.content = self.exercise_page_content\n return page\n \n def submit(self, submission):\n page = ExercisePage(self)\n page.content = self.submission_page_content\n page.is_accepted= True\n return page\n\ndef build_upload_dir(instance, filename):\n \"\"\" \n Returns the path where the attachement should be saved. \n \n @param instance: the ExerciseWithAttachment object\n @param filename: the actual name of the submitted file\n @return: a path where the file should be stored, relative to MEDIA_ROOT directory \n \"\"\"\n\n return \"exercise_attachments/exercise_%d/%s\" % (instance.id, filename)\n\nclass ExerciseWithAttachment(BaseExercise):\n \"\"\"\n ExerciseWithAttachment is an exercise type where the exercise instructions\n are stored locally and the exercise will be graded by sending an additional\n attachment to the grader together with other POST data. The exercise page\n will contain a submission form for the files the user should submit if the\n files to be submitted are defined. Otherwise the instructions must contain\n the submission form.\n \"\"\"\n\n files_to_submit = models.CharField(max_length=200, blank=True,\n help_text=_(\"File names that user should submit, use pipe character to separate files\"))\n attachment = models.FileField(upload_to=build_upload_dir)\n\n class Meta:\n verbose_name_plural = \"exercises with attachment\"\n\n def get_files_to_submit(self):\n \"\"\"\n Returns a list of the file names that user should submit with this exercise.\n \"\"\"\n if len(self.files_to_submit.strip()) == 0:\n return []\n else:\n files = self.files_to_submit.split(\"|\")\n return [filename.strip() for filename in files]\n\n def modify_post_params(self, post_params):\n \"\"\"\n Adds the attachment to POST request. It will be added before the first original\n item of the file array with the same field name or if no files are found it\n will be added as first parameter using name file[].\n @param post_params: original POST parameters, assumed to be a list\n \"\"\"\n\n found = False\n for i in range(len(post_params)):\n if type(post_params[i][1]) == file and post_params[i][0].endswith(\"[]\"):\n handle = open(self.attachment.path, \"rb\")\n post_params.insert(i, (post_params[i][0], handle))\n found = True\n break\n\n if not found:\n post_params.insert(0, ('file[]', open(self.attachment.path, \"rb\")))\n\n def get_page(self, submission_url=None):\n \"\"\"\n @param submission_url: the submission url where the service may return submissions\n @return: an ExercisePage containing the exercise instructions and possibly a submit form \n \"\"\"\n page = ExercisePage(self)\n page.content = self.instructions\n\n # Adds the submission form to the content if there are files to be submitted.\n # A template is used to avoid hard-coded HTML here.\n if self.get_files_to_submit():\n template = loader.get_template('exercise/_file_submit_form.html')\n context = Context({'files' : self.get_files_to_submit()})\n page.content += template.render(context)\n\n return page\n\n\nclass SubmissionRuleDeviation(models.Model):\n \"\"\"\n An abstract model binding a user to an exercise stating that there is some\n kind of deviation from the normal submission boundaries, that is, special\n treatment related to the submissions of that particular user to that\n particular exercise.\n\n If there are many submitters submitting an exercise out of bounds of the\n default bounds, all of the submitters must have an allowing instance of\n SubmissionRuleDeviation subclass in order for the submission to be allowed.\n \"\"\"\n exercise = models.ForeignKey(BaseExercise,\n related_name=\"%(class)ss\")\n submitter = models.ForeignKey(UserProfile)\n\n class Meta:\n abstract = True\n unique_together = [\"exercise\", \"submitter\"]\n app_label = 'exercise'\n\n\nclass DeadlineRuleDeviation(SubmissionRuleDeviation):\n extra_minutes = models.IntegerField()\n\n class Meta(SubmissionRuleDeviation.Meta):\n pass\n\n def get_extra_time(self):\n return timedelta(minutes=self.extra_minutes)\n\n def get_new_deadline(self):\n return self.get_normal_deadline() + self.get_extra_time()\n\n def get_normal_deadline(self):\n return self.exercise.get_deadline()\n\n\nclass MaxSubmissionsRuleDeviation(SubmissionRuleDeviation):\n extra_submissions = models.IntegerField()\n\n class Meta(SubmissionRuleDeviation.Meta):\n pass\n","sub_path":"exercise/exercise_models.py","file_name":"exercise_models.py","file_ext":"py","file_size_in_byte":27862,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"270275107","text":"# -*- coding: utf-8 -*-\nimport logging\nimport random\nimport json\nfrom tornado import gen\nfrom tornado.log import gen_log\nfrom datetime import datetime, timedelta\nfrom base.config import Config\nimport time\n\nfrom comm.consts import *\nfrom util.es import ES\n\nlogger = logging.getLogger(__name__)\n\n\nclass HomeArticle(object):\n\tdef __init__(self, redis_conn, device_id='', smzdm_id='', page=1, nums=20):\n\t\tself._device_id = device_id\n\t\tself._smzdm_id = smzdm_id\n\t\tself._page = page\n\t\tself._nums = nums\n\t\tself._editor_nums = self._nums - PAGE_RECOMMEND_SIZE\n\t\tself._redis_conn = redis_conn\n\t\tself._cate_prefer = {}\n\t\tself._tag_prefer = {}\n\t\tself._brand_prefer = {}\n\t\tself._history_key = HISTORY_KEY % self._device_id\n\t\t# 偏好获取\n\t\tif device_id:\n\t\t\t# 品类偏好\n\t\t\tlevel_key = \"%s_level\" % device_id\n\t\t\ttag_key = \"%s_tag\" % device_id\n\t\t\tbrand_key = \"%s_brand\" % device_id\n\t\t\tgen_log.info(\"level_key: %s, tag_key: %s, brand_key: %s\", level_key, tag_key, brand_key)\n\t\t\ttry:\n\t\t\t\t# TODO 新的偏好key暂时为设备id,后面需要调整有前缀\n\t\t\t\tif self._redis_conn.exists(self._device_id):\n\t\t\t\t\tv = self._redis_conn.get(self._device_id)\n\t\t\t\t\tv_json = HomeArticle._parse_prefer_to_json(v)\n\t\t\t\t\tif PREFER_USER_KEY in v_json.keys():\n\t\t\t\t\t\tself._cate_prefer = v_json.get(PREFER_USER_KEY, {}).get(\"level\", {})\n\t\t\t\t\t\tself._tag_prefer = v_json.get(PREFER_USER_KEY, {}).get(\"tag\", {})\n\t\t\t\t\t\tself._brand_prefer = v_json.get(PREFER_USER_KEY, {}).get(\"brand\", {})\n\t\t\t\t\telif PREFER_DEVICE_KEY in v_json.keys():\n\t\t\t\t\t\tself._cate_prefer = v_json.get(PREFER_DEVICE_KEY, {}).get(\"level\", {})\n\t\t\t\t\t\tself._tag_prefer = v_json.get(PREFER_DEVICE_KEY, {}).get(\"tag\", {})\n\t\t\t\t\t\tself._brand_prefer = v_json.get(PREFER_DEVICE_KEY, {}).get(\"brand\", {})\n\t\t\t\t#\n\t\t\t\t# if self._redis_conn.exists(level_key):\n\t\t\t\t# \tcate_prefer = self._redis_conn.get(level_key)\n\t\t\t\t# \tself._cate_prefer = HomeArticle._parse_prefer_to_json(cate_prefer)\n\t\t\t\t#\n\t\t\t\t# # 标签偏好\n\t\t\t\t# if self._redis_conn.exists(tag_key):\n\t\t\t\t# \ttag_prefer = self._redis_conn.get(tag_key)\n\t\t\t\t# \tself._tag_prefer = HomeArticle._parse_prefer_to_json(tag_prefer)\n\t\t\t\t#\n\t\t\t\t# # 品牌偏好\n\t\t\t\t# if self._redis_conn.exists(brand_key):\n\t\t\t\t# \tbrand_prefer = self._redis_conn.get(brand_key)\n\t\t\t\t# \tself._brand_prefer = HomeArticle._parse_prefer_to_json(brand_prefer)\n\t\t\texcept Exception as e:\n\t\t\t\tgen_log.warn(\"get user(device_id: %s) prefer from redis exception(%s)\", self._device_id, str(e))\n\t\t\t\t\n\t\tgen_log.info(\"device_id: %s, cate_prefer: %s, tag_prefer: %s, brand_prefer: %s\",\n\t\t device_id, self._cate_prefer, self._tag_prefer, self._brand_prefer)\n\t\t\n\t\t# 获取不感兴趣的文章id和channel\n\t\tdislike_key = DISLIKE_KEY % (smzdm_id if smzdm_id != '0' else '', device_id)\n\t\tself._dislike_list = []\n\t\tif self._redis_conn.exists(dislike_key):\n\t\t\tdislike_value = self._redis_conn.lrange(dislike_key, 0, -1)\n\t\t\tfor d in dislike_value:\n\t\t\t\tif COLON in d:\n\t\t\t\t\tarticle_id, channel_id = d.split(COLON)\n\t\t\t\t\tif int(channel_id) in YOUHUI_CHANNEL_MAP:\n\t\t\t\t\t\tchannel_id = 3\n\t\t\t\t\tv = \"%s:%s\" % (article_id, channel_id)\n\t\t\t\t\t# 将不再不感兴趣列表中的值添加到列表中\n\t\t\t\t\tif v not in self._dislike_list:\n\t\t\t\t\t\tself._dislike_list.append(v)\n\n\t\tgen_log.info(\"dislike_key: %s\", dislike_key)\n\t\tgen_log.debug(\"dislike_value: %s\", self._dislike_list)\n\t\t\n\t\t# 计算时间半小时,1小时,3小时,12小时,24小时时间,供文章对时间的加权使用\n\t\tnow = datetime.now()\n\t\tself._half_hour_ago = (now - timedelta(minutes=30)).strftime(\"%Y-%m-%d %H:%M:%S\")\n\t\tself._one_hour_ago = (now - timedelta(hours=1)).strftime(\"%Y-%m-%d %H:%M:%S\")\n\t\tself._three_hour_ago = (now - timedelta(hours=3)).strftime(\"%Y-%m-%d %H:%M:%S\")\n\t\tself._twelve_hour_ago = (now - timedelta(hours=12)).strftime(\"%Y-%m-%d %H:%M:%S\")\n\t\tself._twenty_four_hour_ago = (now - timedelta(hours=24)).strftime(\"%Y-%m-%d %H:%M:%S\")\n\t\t\n\t@staticmethod\n\tdef _parse_cate_prefer(value):\n\t\t\"\"\"\n\t\t\tdesc: 解析品类偏好字符串\n\t\t\t\t优惠: 精确偏好 + 泛偏好\n\t\t\t\t原创: 精确偏好\n\t\t:param value:\n\t\t:return:\n\t\t\"\"\"\n\t\taccurate_set = set()\n\t\tblur_set = set()\n\t\tif value:\n\t\t\taccurate, blur = value.strip().split(DOT)\n\t\t\tif accurate:\n\t\t\t\t_, accurate_value = accurate.split(COLON)\n\t\t\t\taccurate_set = HomeArticle._parse_str_to_set(accurate_value)\n\t\t\t\n\t\t\tif blur:\n\t\t\t\t_, blur_value = blur.split(COLON)\n\t\t\t\tblur_set = HomeArticle._parse_str_to_set(blur_set, VERTICAL_LINE)\n\t\t\t\t\n\t\tcate_prefer_dict = {\n\t\t\t\"accurate\": accurate_set,\n\t\t\t\"blur\": blur_set,\n\t\t}\n\t\treturn cate_prefer_dict\n\t\n\t@staticmethod\n\tdef _parse_prefer_to_json(value):\n\t\t\"\"\"\n\t\tdesc: 从redis中获取的偏好解析为json格式\n\t\t:param value: value的取值举例\n\t\t\t# 品类\n\t\t\tvalue = {\n\t\t\t\t\"youhui\": {\n\t\t\t\t\t\"accurate\": set([\"1\",\"2\",\"3\"]),\n\t\t\t\t\t\"blur\": set([\"1\",\"2\",\"3\"])\n\t\t\t\t},\n\t\t\t\t\"yuanchuang\": set([\"1\",\"2\",\"3\"])\n\t\t\t}\n\t\t\t\n\t\t\t# 标签\n\t\t\tvalue = {\n\t\t\t\t\"youhui\": set([\"1\",\"2\",\"3\"]),\n\t\t\t\t\"yuanchuang\": set([\"1\",\"2\",\"3\"]),\n\t\t\t}\n\t\t\t\n\t\t\t# 品牌\n\t\t\tvalue = {\n\t\t\t\t\"youhui\": set([\"1\",\"2\",\"3\"]),\n\t\t\t\t\"yuanchuang\": set([\"1\",\"2\",\"3\"]),\n\t\t\t}\n\n\t\t:return:\n\t\t\"\"\"\n\t\td = {}\n\t\tif value:\n\t\t\td = json.loads(value)\n\t\treturn d\n\t\n\t@staticmethod\n\tdef _parse_str_to_set(value, seq=DOT):\n\t\t\"\"\"\n\t\tdesc: 解析逗号字符串,并返回一个set值; 默认返回set()\n\t\t:param value:\n\t\t:return:\n\t\t\"\"\"\n\t\tresult_set = set()\n\t\tif value:\n\t\t\tresult_set = set(value.strip().split(seq))\n\t\treturn result_set\n\t\t\n\t@gen.coroutine\n\tdef _get_query_dict(self, gte_time, lte_time, home=True, is_top=0):\n\t\t\"\"\"\n\t\t# 从es查询数据条件\n\t\t:param gte_time:\n\t\t:param lte_time:\n\t\t:return:\n\t\t\"\"\"\n\t\tquery_dict = {\n\t\t\t\t\"size\": self._nums * PAGE_NUM,\n\t\t\t\t\"from\": 0,\n\t\t\t\t\"sort\": [\n\t\t\t\t\t{\n\t\t\t\t\t\t\"sync_home_time\": {\n\t\t\t\t\t\t\t\"order\": \"desc\"\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t],\n\t\t\t\t\"query\": {\n\t\t\t\t\t\"filtered\": {\n\t\t\t\t\t\t\"query\": {\n\t\t\t\t\t\t\t\"match_all\": {}\n\t\t\t\t\t\t},\n\t\t\t\t\t\t\"filter\": {\n\t\t\t\t\t\t\t\"bool\": {\n\t\t\t\t\t\t\t\t\"must\": [\n\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\t\"term\": {\n\t\t\t\t\t\t\t\t\t\t\t\"status\": 0\n\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\t\"term\": {\n\t\t\t\t\t\t\t\t\t\t\t\"machine_report\": 0\n\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\t\"term\": {\n\t\t\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t\t\t\"is_top\": is_top\n\t\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\t],\n\t\t\t\t\t\t\t\t\"must_not\": [\n\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t]\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\n\t\tcondition = [\n\t\t\t{\n\t\t\t\t\"term\": {\n\t\t\t\t\t\"sync_home\": 1\n\t\t\t\t}\n\t\t\t},\n\t\t\t{\n\t\t\t\t\"range\": {\n\t\t\t\t\t\"sync_home_time\": {\n\t\t\t\t\t\t\"gte\": gte_time,\n\t\t\t\t\t\t\"lt\": lte_time\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t]\n\t\t\n\t\t# 非同步到首页的优惠和原创数据\n\t\tif not home:\n\t\t\tcondition = [\n\t\t\t\t{\n\t\t\t\t\t\"term\": {\n\t\t\t\t\t\t\"sync_home\": 0\n\t\t\t\t\t}\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\t\"terms\": {\n\t\t\t\t\t\t\"channel\": [\"yh\", \"yc\"]\n\t\t\t\t\t}\n\t\t\t\t},\n\t\t\t\t{\n\t\t\t\t\t\"range\": {\n\t\t\t\t\t\t\"sync_home_time\": {\n\t\t\t\t\t\t\t\"gte\": gte_time,\n\t\t\t\t\t\t\t\"lt\": lte_time\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\t\n\t\t\t]\n\t\tquery_dict[\"query\"][\"filtered\"][\"filter\"][\"bool\"][\"must\"].extend(condition)\n\t\t\n\t\treturn query_dict\n\t\n\t@gen.coroutine\n\tdef get_home_article_list(self):\n\t\t# 一页数据结果\n\t\tresult_list = []\n\t\t\n\t\t# 获取推荐列表\n\t\t# 首先��缓存中获取该用户的文章列表; 缓存中没有,则查询es并根据该用户偏好计算权值,存入es,并写入缓存\n\t\t# 取老的数据,如果不够一页,则仍要取之前的数据\n\t\t# page = 1 第一页\n\t\ttimeout = (HOUR_CONST - int(datetime.now().strftime(\"%H\"))) * 3600\n\t\tpull_down_last_time_key = PULL_DOWN_LAST_TIME_PREFIX_KEY + self._device_id\n\t\tpull_up_last_time_key = PULL_UP_LAST_TIME_PREFIX_KEY + self._device_id\n\t\thour_24_ago = (datetime.now() - timedelta(hours=24)).strftime(\"%Y-%m-%d 00:00:00\")\n\t\t\n\t\t# 是否设置过期时间\n\t\tif 1 == self._page:\n\t\t\tredis_flag = False\n\t\t\tif not self._redis_conn.exists(self._history_key):\n\t\t\t\tredis_flag = True\n\t\t\t# 从缓存中获取上一次下拉的时间\n\t\t\tpull_down_start_time = self._redis_conn.get(pull_down_last_time_key)\n\t\t\t# pull_up_start_time = pull_down_start_time if pull_down_start_time else datetime.now().strftime(\"%Y-%m-%d 00:00:00\")\n\t\t\tpull_down_start_time = pull_down_start_time if pull_down_start_time else hour_24_ago\n\t\t\t\n\t\t\tpull_down_end_time = datetime.now().strftime(\"%Y-%m-%d %H:%M:%S\")\n\t\t\tgen_log.info(\"pull_down_last_time_key: %s, start_time: %s, end_time: %s\", pull_down_last_time_key, pull_down_start_time, pull_down_end_time)\n\t\t\t# 下拉的最后时间记录为当前时间\n\t\t\tself._redis_conn.set(pull_down_last_time_key, pull_down_end_time, timeout)\n\t\t\t\n\t\t\t# 获取小编和推荐数据\n\t\t\t# 不需要重新排序\n\t\t\teditor_data = yield self._get_es_article(pull_down_start_time, pull_down_end_time)\n\t\t\t# 推荐侧的非同步到首页的文章, 需要加权排序\n\t\t\trecommend_data = yield self._get_es_article(pull_down_start_time, pull_down_end_time, False)\n\t\t\trecommend_data = yield self._calc_one_page_article_weight_or_sort(recommend_data, 1, True)\n\t\t\t\n\t\t\teditor_data_len = len(editor_data)\n\t\t\tgen_log.debug(\"page=%d, editor_data len: %d, recommend_data len: %d\", self._page, editor_data_len, len(recommend_data))\n\t\t\t\n\t\t\t# TODO 小编的数据为null,是否获取推荐的数据进行补充; 小编和推荐数据的时间范围一样,可能需要调整\n\t\t\t# 如果下拉的新数据为0,则从用户的历史浏览缓存中读取一页数据并返回\n\t\t\tif 0 == editor_data_len:\n\t\t\t\tredis_data = self._redis_conn.lrange(self._history_key, (self._page - 1) * self._nums, self._page * self._nums - 1)\n\t\t\t\tresult_list = [json.loads(d) for d in redis_data]\n\t\t\t\tfilter_list = yield self._filter_dislike_cache(result_list)\n\t\t\t\tgen_log.debug(\"page=%d, return result filter list: %s\", self._page, filter_list)\n\t\t\t\traise gen.Return(filter_list)\n\n\t\t\t# 获取的数据如果大于 self._nums * (PAGE_NUM - 2),删除历史缓存\n\t\t\tif editor_data_len > (self._editor_nums * (PAGE_NUM - 2)):\n\t\t\t\tredis_flag = True\n\t\t\t\tself._redis_conn.delete(self._history_key)\n\t\t\t\n\t\t\ts_page = editor_data_len / self._editor_nums\n\t\t\tif editor_data_len % self._editor_nums != 0:\n\t\t\t\ts_page += 1\n\t\t\t\n\t\t\t# 写入缓存\n\t\t\tfor i in range(0, s_page):\n\t\t\t\tstart_index = (s_page - i - 1) * PAGE_SIZE\n\t\t\t\tdata = editor_data[start_index: (s_page - i) * PAGE_SIZE]\n\t\t\t\thome_article_weight = yield self._calc_one_page_article_weight_or_sort(data)\n\t\t\t\t# 推荐的数据每次从列表中获取PAGE_RECOMMEND_SIZE记录\n\t\t\t\trecommend_article_list = recommend_data[i * PAGE_RECOMMEND_SIZE: (i+1) * PAGE_RECOMMEND_SIZE]\n\t\t\t\tyield self._merge_and_save_redis(home_article_weight, recommend_article_list)\n\t\t\t\n\t\t\tif redis_flag:\n\t\t\t\tself._redis_conn.expire(self._history_key, timeout)\n\t\t\t\t# 设置pull_up_end_time 时间\n\t\t\t\tself._redis_conn.set(pull_up_last_time_key, editor_data[-1][\"_source\"][\"sync_home_time\"], timeout)\n\t\telse:\n\t\t\t# page > 1 时, 直接取缓存中的列表数据\n\t\t\tredis_data = self._redis_conn.lrange(self._history_key, (self._page - 1) * self._nums, self._page * self._nums - 1)\n\t\t\tresult_list = [json.loads(d) for d in redis_data]\n\t\t\tresult_list_len = len(result_list)\n\t\t\t\n\t\t\t# 过滤已经缓存的不感兴趣\n\t\t\tresult_list = yield self._filter_dislike_cache(result_list)\n\t\t\t\n\t\t\tgen_log.debug(\"page=%d, redis_data len: %d, filter result len: %d\", self._page, result_list_len, len(result_list))\n\t\t\t\n\t\t\t# 取出的数据为一页数据\n\t\t\tif PAGE_SIZE == result_list_len:\n\t\t\t\traise gen.Return(result_list)\n\t\t\t\t\n\t\t\t# 超过24小时时间,则最后一页,返回不足一页的数据\n\t\t\tpull_up_end_time = self._redis_conn.get(pull_up_last_time_key)\n\t\t\t\n\t\t\tgen_log.info(\"pull up start_time: %s, pull_up_end_time: %s\", hour_24_ago, pull_up_end_time)\n\t\t\teditor_data = yield self._get_es_article(hour_24_ago, pull_up_end_time)\n\t\t\teditor_data_len = len(editor_data)\n\t\t\tgen_log.debug(\"page=%d, editor_data len: %d\", self._page, editor_data_len)\n\t\t\tif 0 == editor_data_len:\n\t\t\t\traise gen.Return(result_list)\n\t\t\t\n\t\t\t# 取推荐侧非同步到首页的数据并且排序\n\t\t\trecommend_data = yield self._get_es_article(hour_24_ago, pull_up_end_time, False)\n\t\t\trecommend_data = yield self._calc_one_page_article_weight_or_sort(recommend_data, 1, True)\n\t\t\t\n\t\t\tgen_log.debug(\"page=%d, recommend_data len: %d\", self._page, len(recommend_data))\n\t\t\t# 将新数据写入到缓存中\n\t\t\t\n\t\t\ts_page = editor_data_len / self._editor_nums\n\t\t\tif editor_data_len % self._editor_nums != 0:\n\t\t\t\ts_page += 1\n\t\t\tfor i in range(0, s_page):\n\t\t\t\tstart_index = i * PAGE_SIZE\n\t\t\t\tdata = editor_data[start_index: start_index + PAGE_SIZE]\n\t\t\t\thome_article_weight = yield self._calc_one_page_article_weight_or_sort(data)\n\t\t\t\t# 推荐的数据每次从列表中获取PAGE_RECOMMEND_SIZE记录\n\t\t\t\trecommend_article_list = recommend_data[i * PAGE_RECOMMEND_SIZE: (i + 1) * PAGE_RECOMMEND_SIZE]\n\t\t\t\tyield self._merge_and_save_redis(home_article_weight, recommend_article_list, False)\n\t\t\t\t\n\t\t\t# 设置pull_up_end_time 时间\n\t\t\tif editor_data:\n\t\t\t\tself._redis_conn.set(pull_up_last_time_key, editor_data[-1][\"_source\"][\"sync_home_time\"], timeout)\n\t\t\t\t\n\t\t# 从缓存中取一页数据返回\n\t\tresult_list = self._redis_conn.lrange(self._history_key, (self._page - 1) * self._nums, self._page * self._nums - 1)\n\t\tresult_list = [json.loads(d) for d in result_list]\n\t\traise gen.Return(result_list)\n\t\n\t@gen.coroutine\n\tdef _filter_sex_porduct(self, article):\n\t\t# 夜间不过滤成人用品\n\t\tnow = datetime.now().strftime(\"%H:%M:%D\")\n\t\tif (now > SEX_PRODUCT_START_TIME) or (now < SEX_PRODUCT_END_TIME):\n\t\t\traise gen.Return(article)\n\t\tresult_list = []\n\t\tlevel1_filter_set = set(Config[\"sex_product.level1\"].split(DOT))\n\t\tlevel2_filter_set = set(Config[\"sex_product.level2\"].split(DOT))\n\t\tlevel3_filter_set = set(Config[\"sex_product.level2\"].split(DOT))\n\t\tlevel4_filter_set = set(Config[\"sex_product.level2\"].split(DOT))\n\t\t\n\t\tfor d in article:\n\t\t\tlevel1_ids_set = set(d[\"_source\"][\"level1_ids\"].split(DOT))\n\t\t\tlevel2_ids_set = set(d[\"_source\"][\"level2_ids\"].split(DOT))\n\t\t\tlevel3_ids_set = set(d[\"_source\"][\"level3_ids\"].split(DOT))\n\t\t\tlevel4_ids_set = set(d[\"_source\"][\"level4_ids\"].split(DOT))\n\t\t\tif level1_filter_set.intersection(level1_ids_set) \\\n\t\t\t\tor level2_filter_set.intersection(level2_ids_set) \\\n\t\t\t\tor level3_filter_set.intersection(level3_ids_set) \\\n\t\t\t\tor level4_filter_set.intersection(level4_ids_set):\n\t\t\t\tcontinue\n\t\t\t\n\t\t\tresult_list.append(d)\n\t\traise gen.Return(result_list)\n\t\n\t@gen.coroutine\n\tdef _filter_dislike(self, article):\n\t\tresult_list = []\n\t\tif self._dislike_list:\n\t\t\tfor d in article:\n\t\t\t\tdislike = \"%s:%s\" % (d[\"_source\"][\"article_id\"], d[\"_source\"][\"channel_id\"])\n\t\t\t\tif dislike in self._dislike_list:\n\t\t\t\t\tcontinue\n\t\t\t\tresult_list.append(d)\n\t\telse:\n\t\t\traise gen.Return(article)\n\t\traise gen.Return(result_list)\n\t\n\t@gen.coroutine\n\tdef _filter_dislike_cache(self, article):\n\t\tresult_list = []\n\t\tif self._dislike_list:\n\t\t\tfor d in article:\n\t\t\t\tdislike = \"%s:%s\" % (d[\"article_id\"], d[\"channel\"])\n\t\t\t\tif dislike in self._dislike_list:\n\t\t\t\t\tcontinue\n\t\t\t\tresult_list.append(d)\n\t\telse:\n\t\t\traise gen.Return(article)\n\t\traise gen.Return(result_list)\n\t\t\t\t\n\t@gen.coroutine\n\tdef _get_es_article(self, pull_start_time, pull_end_time, home=True):\n\t\tes = ES()\n\t\tr_query_dict = yield self._get_query_dict(pull_start_time, pull_end_time, home)\n\t\thome_es_index = Config[\"es.index\"]\n\t\tarticle = yield es.search(home_es_index, r_query_dict)\n\t\t# es结果过滤\n\t\tfilter_article = yield self._filter_sex_porduct(article)\n\t\tfilter_dislike = yield self._filter_dislike(filter_article)\n\t\traise gen.Return(filter_dislike)\n\t\n\t@gen.coroutine\n\tdef get_top_article(self, pull_start_time, pull_end_time, home=True, is_top=0):\n\t\tif self._redis_conn.exists(TOP_ARTICLE_KEY):\n\t\t\ttop_data = self._redis_conn.get(TOP_ARTICLE_KEY)\n\t\t\traise gen.Return([json.loads(top_data)])\n\t\t\t\n\t\tes = ES()\n\t\tr_query_dict = yield self._get_query_dict(pull_start_time, pull_end_time, home, is_top)\n\t\thome_es_index = Config[\"es.index\"]\n\t\tarticle = yield es.search(home_es_index, r_query_dict)\n\t\ttop_data = []\n\t\tif article:\n\t\t\tarticle = article[0]\n\t\t\ttime_sort = datetime.strptime(article[\"_source\"][\"sync_home_time\"], \"%Y-%m-%d %H:%M:%S\")\n\t\t\ttime_sort_timestamp = int(time.mktime(time_sort.timetuple()))\n\t\t\tone_row_dict = {\n\t\t\t \"id\": article[\"_source\"][\"id\"],\n\t\t\t \"article_id\": article[\"_source\"][\"article_id\"],\n\t\t\t \"channel\": article[\"_source\"][\"channel_id\"],\n\t\t\t # \"is_delete\": 0 if d[\"_source\"][\"sync_home\"] == 0 else d[\"_source\"][\"sync_home\"],\n\t\t\t \"is_top\": article[\"_source\"][\"is_top\"],\n\t\t\t \"time_sort\": time_sort_timestamp,\n\t\t\t \"type\": 1,\n\t\t\t \"score\": 10\n\t\t\t\n\t\t\t}\n\t\t\ttop_data.append(one_row_dict)\n\t\t\tself._redis_conn.set(TOP_ARTICLE_KEY, json.dumps(one_row_dict), 60)\n\t\traise gen.Return(top_data)\n\t\n\t@gen.coroutine\n\tdef _merge_and_save_redis(self, home_list, recommend_list, if_list_head=True):\n\t\t\"\"\"\n\t\tdesc: 对每个文章进行加权; 排序;写入redis\n\t\t:param data:\n\t\t:param redis_conn:\n\t\t:param if_list_head:\n\t\t:param result_list:\n\t\t:param if_append:\n\t\t:return:\n\t\t\"\"\"\n\t\t# 编辑流和推荐流合并\n\t\thome_list.extend(recommend_list)\n\t\t\n\t\t# 将合并的编辑流和推荐流排序\n\t\thome_sort_list = yield self._sort(home_list)\n\t\t\n\t\tif if_list_head:\n\t\t\tsort_list_length = len(home_sort_list)\n\t\t\tfor i in range(0, sort_list_length):\n\t\t\t\tself._redis_conn.lpush(self._history_key, json.dumps(home_sort_list[sort_list_length - i - 1]))\n\t\telse:\n\t\t\tfor i in home_sort_list:\n\t\t\t\tself._redis_conn.rpush(self._history_key, json.dumps(i))\n\t\t\t\t\n\t\t\n\t@gen.coroutine\n\tdef _merge_recommend_and_save_redis(self, home_list, recommend_list, if_list_head=True, result_list=[], if_append=False):\n\t\t\"\"\"\n\t\tdesc: 对每个文章进行加权; 排序;写入redis\n\t\t:param data:\n\t\t:param redis_conn:\n\t\t:param if_list_head:\n\t\t:param result_list:\n\t\t:param if_append:\n\t\t:return:\n\t\t\"\"\"\n\t\t# 编辑流和推荐流合并\n\t\thome_list.extend(recommend_list)\n\t\t\n\t\t# 将合并的编辑流和推荐流排序\n\t\thome_sort_list = yield self._sort(home_list)\n\n\t\tif if_append:\n\t\t\tresult_list.extend(home_sort_list)\n\t\t\n\t\tif if_list_head:\n\t\t\tsort_list_length = len(home_sort_list)\n\t\t\tfor i in range(0, sort_list_length):\n\t\t\t\tself._redis_conn.lpush(self._device_id, json.dumps(home_sort_list[sort_list_length-i-1]))\n\t\telse:\n\t\t\tfor i in home_sort_list:\n\t\t\t\tself._redis_conn.rpush(self._device_id, json.dumps(i))\n\t\t\t\t\n\t@gen.coroutine\n\tdef _sort(self, data_list, reverse=True):\n\t\tdata_list.sort(cmp=lambda x, y: cmp(x[\"score\"], y[\"score\"]), reverse=reverse)\n\t\t\n\t\traise gen.Return(data_list)\n\t\t\n\t@gen.coroutine\n\tdef _calc_one_page_article_weight_or_sort(self, data, is_home=0, if_sort=False):\n\t\tweight_list_or_sort = []\n\t\tfor d in data:\n\t\t\tscore = yield self._calc_score(d)\n\t\t\ttime_sort = datetime.strptime(d[\"_source\"][\"sync_home_time\"], \"%Y-%m-%d %H:%M:%S\")\n\t\t\ttime_sort_timestamp = int(time.mktime(time_sort.timetuple()))\n\t\t\tone_row_dict = {\n\t\t\t\t\"id\": d[\"_source\"][\"id\"],\n\t\t\t\t\"article_id\": d[\"_source\"][\"article_id\"],\n\t\t\t\t\"channel\": d[\"_source\"][\"channel_id\"],\n\t\t\t\t# \"is_delete\": 0 if d[\"_source\"][\"sync_home\"] == 0 else d[\"_source\"][\"sync_home\"],\n\t\t\t\t\"is_top\": d[\"_source\"][\"is_top\"],\n\t\t\t\t\"time_sort\": time_sort_timestamp,\n\t\t\t\t\"type\": is_home,\n\t\t\t\t\"score\": score\n\t\t\t}\n\t\t\tweight_list_or_sort.append(one_row_dict)\n\t\tif if_sort:\n\t\t\tweight_list_or_sort = yield self._sort(weight_list_or_sort)\n\t\t\n\t\traise gen.Return(weight_list_or_sort)\n\n\t@gen.coroutine\n\tdef _calc_score(self, data):\n\t\t\"\"\"\n\t\tdesc: 对每篇文章加权\n\t\t:param data: 一篇文章的数据\n\t\t:return:\n\t\t\"\"\"\n\t\tscore = 0.0\n\t\tif data:\n\t\t\tlevel1_ids = data[\"_source\"][\"level1_ids\"]\n\t\t\tlevel2_ids = data[\"_source\"][\"level2_ids\"]\n\t\t\tlevel3_ids = data[\"_source\"][\"level3_ids\"]\n\t\t\tlevel4_ids = data[\"_source\"][\"level4_ids\"]\n\t\t\ttag_ids = data[\"_source\"][\"tag_ids\"]\n\t\t\tbrand_ids = data[\"_source\"][\"brand_ids\"]\n\t\t\tchannel = data[\"_source\"][\"channel\"]\n\t\t\tsync_home = data[\"_source\"][\"sync_home\"]\n\t\t\t\n\t\t\tlevel1_ids_set = set(level1_ids.split(DOT))\n\t\t\tlevel2_ids_set = set(level2_ids.split(DOT))\n\t\t\tlevel3_ids_set = set(level3_ids.split(DOT))\n\t\t\tlevel4_ids_set = set(level4_ids.split(DOT))\n\t\t\ttag_ids_set = set(tag_ids.split(DOT))\n\t\t\tbrand_ids_set = set(brand_ids.split(DOT))\n\t\t\t\n\t\t\ttry:\n\t\t\t\n\t\t\t\tif channel == YOUHUI_CHANNEL:\n\t\t\t\t\t# 品类精确偏好\n\t\t\t\t\tyouhui_accurate_prefer = set(self._cate_prefer.get(YOUHUI_KEY, {}).get(\"accurate\", set()))\n\t\t\t\t\tyouhui_blur_prefer = set(self._cate_prefer.get(YOUHUI_KEY, {}).get(\"blur\", set()))\n\t\t\t\t\t\n\t\t\t\t\tif level1_ids_set - youhui_accurate_prefer:\n\t\t\t\t\t\tscore += SUB_PORTRAIT_WIGHT[\"ACCURATE_CATE\"]\n\t\t\t\t\t# 品类模糊偏好\n\t\t\t\t\tif (level3_ids_set - youhui_blur_prefer) or (level4_ids_set - youhui_blur_prefer):\n\t\t\t\t\t\tscore += SUB_PORTRAIT_WIGHT[\"BLUR_CATE\"]\n\t\t\t\t\t# 标签偏好\n\t\t\t\t\tif tag_ids_set - set(self._tag_prefer.get(YOUHUI_KEY, set())):\n\t\t\t\t\t\tscore += SUB_PORTRAIT_WIGHT[\"TAG\"]\n\t\t\t\t\t\t\n\t\t\t\t\t# 品牌偏好\n\t\t\t\t\tif brand_ids_set - set(self._brand_prefer.get(YOUHUI_KEY, set())):\n\t\t\t\t\t\tscore += SUB_PORTRAIT_WIGHT[\"BRAND\"]\n\t\t\t\telif channel == YUANCHUANG_CHANNEL:\n\t\t\t\t\tif level2_ids_set - set(self._cate_prefer.get(YUANCHUANG_KEY, set())):\n\t\t\t\t\t\tscore += PORTRAIT_TOTAL_WEIGHT\n\t\t\t\t\t\t\n\t\t\t\t\t# 标签偏好\n\t\t\t\t\tif tag_ids_set - set(self._tag_prefer.get(YUANCHUANG_KEY, set())):\n\t\t\t\t\t\tscore += SUB_PORTRAIT_WIGHT[\"TAG\"]\n\t\t\t\t\t\n\t\t\t\t\t# 品牌偏好\n\t\t\t\t\tif brand_ids_set - set(self._brand_prefer.get(YUANCHUANG_KEY, set())):\n\t\t\t\t\t\tscore += SUB_PORTRAIT_WIGHT[\"BRAND\"]\n\t\t\texcept Exception as e:\n\t\t\t\tlogger.error(\"_calc_score error(%s)\", e.message)\n\t\t\t\t\n\t\t\t# 同步到首页的文章\n\t\t\tif sync_home > 0:\n\t\t\t\tscore += EDITOR_SYNC_TOTAL_WEIGHT\n\t\t\t\t\n\t\t\t\t# 同步到首页的非好价好文的文章, 给以随机的权重\n\t\t\t\tif channel != YOUHUI_CHANNEL and channel != YUANCHUANG_CHANNEL:\n\t\t\t\t\tscore += (PORTRAIT_TOTAL_WEIGHT * round(random.uniform(0, 1.0), 2))\n\t\t\t\n\t\t\t# 时间段加权\n\t\t\tsync_home_time = data[\"_source\"][\"sync_home_time\"]\n\t\t\tif sync_home_time >= self._half_hour_ago:\n\t\t\t\tscore += SUB_TIME_WEIGHT[\"HALF_HOUR\"]\n\t\t\telif sync_home_time >= self._one_hour_ago:\n\t\t\t\tscore += SUB_TIME_WEIGHT[\"HOUR_1\"]\n\t\t\telif sync_home_time >= self._three_hour_ago:\n\t\t\t\tscore += SUB_TIME_WEIGHT[\"HOUR_3\"]\n\t\t\telif sync_home_time >= self._twelve_hour_ago:\n\t\t\t\tscore += SUB_TIME_WEIGHT[\"HOUR_12\"]\n\t\t\telif sync_home_time >= self._twenty_four_hour_ago:\n\t\t\t\tscore += SUB_TIME_WEIGHT[\"HOUR_24\"]\n\t\t\t\t\n\t\traise gen.Return(score)\n","sub_path":"DM/smzdm_recommend/biz/home_article.py","file_name":"home_article.py","file_ext":"py","file_size_in_byte":22013,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"529432120","text":"\"\"\"\nContains some common filter as utilities\n\"\"\"\nfrom django.template import Library\nregister = Library()\n\n@register.filter\ndef euro(value):\n \"\"\"\n Transforms a number in euro format\n \"\"\"\n try:\n val = u\"%.2f\" % (float(value))\n except:\n return u''\n return val.replace('.', ',')\n\n@register.filter\ndef comma2dot(value):\n \"\"\"\n Replaces comma with dot in a string\n \"\"\"\n val = unicode(value).split()\n if not val:\n return value\n return val[0].replace(',', '.')","sub_path":"upy/templatetags/upytags.py","file_name":"upytags.py","file_ext":"py","file_size_in_byte":509,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"603252154","text":"from base64 import b64decode\nfrom Crypto.Cipher import AES\nfrom random import randint\nimport os\n\ndef pkcs7_pad(message, block_size):\n if len(message) % block_size == 0:\n \treturn message\n ch = block_size - len(message) % block_size\n return message + bytes([ch] * ch)\n\ndef is_pkcs7_padded(data):\n\tpadding = data[-data[-1]:]\n\treturn all(padding[b] == len(padding) for b in range(len(padding)))\n\ndef pkcs7_unpad(data):\n\tif len(data) == 0:\n\t\treturn \"Data must have at least one byte\"\n\tif not is_pkcs7_padded(data):\n\t\treturn data\n\tpad_bytes = data[-1]\n\treturn data[:-pad_bytes]\n\ndef get_blocks(data, block_size):\n\treturn [data[i:i + block_size] for i in range(0, len(data), block_size)]\n\ndef AES_ECB_decrypt(data, key):\n\tcipher = AES.new(key, AES.MODE_ECB)\n\treturn cipher.decrypt(data)\n\ndef AES_ECB_encrypt(data, key):\n\tcipher = AES.new(key, AES.MODE_ECB)\n\treturn cipher.encrypt(pkcs7_pad(data, block_size))\n\ndef generate_random(block_size):\n\treturn os.urandom(16)\n\ndef random_padding():\n\tx = randint(1,255)\n\treturn os.urandom(x)\n\ndef ECB_oracle(data):\n\tplaintext = padding_prefix + data + secret\n\treturn AES_ECB_encrypt(plaintext,key)\t\n\ndef find_block_length():\n\tinput_data = b'A'\n\tciphertext = ECB_oracle(input_data)\n\tlength = len(ciphertext)\n\tnew_length = length\n\twhile length == new_length:\n\t\tinput_data += b'A'\n\t\tciphertext = ECB_oracle(input_data)\n\t\tnew_length = len(ciphertext)\n\treturn new_length - length\n\ndef detect_AES_Method(data):\n\tblocks = get_blocks(data, block_size)\n\tif len(blocks) != len(set(blocks)):\n\t\treturn \"ECB\"\n\treturn \"CBC\"\n\ndef repeated_block(blocks):\n\tfor i in range(len(blocks)-1):\n\t\tif blocks[i] == blocks[i+1]:\n\t\t\treturn True\n\treturn False\n \ndef find_padding_block():\n\tc1 = ECB_oracle(b'0')\n\tc2 = ECB_oracle(b'1')\n\tb1 = get_blocks(c1, block_size)\n\tb2 = get_blocks(c2, block_size)\n\tfor i in range(len(b1)):\n\t\tif b1[i] != b2[i]:\n\t\t\treturn i\n\ndef find_padding_byte():\n\tfor i in range(block_size):\n\t\tprobe = bytes([0]*(2*block_size + i))\n\t\tcipher = ECB_oracle(probe)\n\t\tcipher_blocks = get_blocks(cipher, block_size)\n\t\tif repeated_block(cipher_blocks):\n\t\t\treturn block_size - i\n\ndef find_byte(block_size, padding_size, recovered):\n\tinput_length = (block_size - padding_size - (1 + len(recovered)))% block_size\n\tinput_data = b'A' * input_length\n\tlength_completed = input_length + padding_size + len(recovered) + 1\n\t\n\tciphertext = ECB_oracle(input_data)\n\n\tfor i in range(256):\n\t\tguess = ECB_oracle(input_data + recovered + bytes([i]))\n\t\tif guess[:length_completed] == ciphertext[:length_completed]:\n\t\t\treturn bytes([i])\n\telse:\n\t\treturn b''\n\ndef crack_ECB_byte_by_byte():\n\tblock_size = find_block_length()\n\ttest_input = bytes([0]*64)\n\tassert detect_AES_Method(ECB_oracle(test_input)) == 'ECB'\n\tpadding_size = block_size * find_padding_block() + find_padding_byte()\n\tmessage_length = len(ECB_oracle(b'')) - padding_size\n\trecovered = b''\n\tfor i in range(message_length):\n\t\trecovered += find_byte(block_size, padding_size ,recovered)\n\treturn pkcs7_unpad(recovered)\n\n\nblock_size = 16\nkey = generate_random(block_size)\npadding_prefix = random_padding()\n\nwith open('s2c12.txt', 'r') as f:\n\tsecret = b64decode(f.read())\n\nprint(crack_ECB_byte_by_byte().decode())\n\n\n\n\n\n\n\n\n\n\n\n","sub_path":"s2c14.py","file_name":"s2c14.py","file_ext":"py","file_size_in_byte":3193,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"398871655","text":"from airflow.contrib.hooks.bigquery_hook import BigQueryHook\nfrom airflow.models import BaseOperator\nfrom airflow.hooks.base_hook import BaseHook\nfrom pytz import timezone\nfrom datetime import datetime, timedelta\n\n\"\"\"\n 사용자 정의 모듈(쿼리모음)\n\"\"\"\nfrom sqls.car_zone_day import car_zone_day_query\nfrom sqls.finance_raw import finance_raw_query\nfrom sqls.reservation_biz_detail import reservation_biz_detail_query\n\n\nclass SocarBizParamOperator(BaseOperator):\n def __init__(self,\n bq_conn_id,\n *args,\n **kwargs):\n super(SocarBizParamOperator, self).__init__(*args, **kwargs)\n self.bq_conn_id = bq_conn_id\n\n def execute(self, context):\n retry_count = 5\n for count in range(retry_count):\n try:\n self.do_weekly_works(context)\n break\n except Exception as e:\n self.log.exception(e)\n time.sleep(180)\n\n def init(self):\n self.bq_hook = BigQueryHook(bigquery_conn_id=self.bq_conn_id, use_legacy_sql=False)\n bq_conn = self.bq_hook.get_conn()\n self.bq_cursor = bq_conn.cursor()\n \n def do_weekly_works(self, context):\n try:\n self.init()\n \n self.execution_date = context.get(\"execution_date\")\n KST = timezone('Asia/Seoul')\n exec_date = datetime.strptime(self.execution_date.astimezone(KST).strftime('%Y-%m-%d'),'%Y-%m-%d')\n date_suffix = exec_date.strftime('%Y%m%d')\n\n ##########\n query_01 = car_zone_day_query.format(date_suffix = exec_date.strftime('%Y-%m-%d'))\n self.log.info(f\"execution query - car_zone_day_query [{query_01}]\")\n self.do_query(query = query_01,\n destination_dataset_table = 'socar-data.socar_biz_param.car_zone_day${date_suffix}'.format(date_suffix = date_suffix),\n write_disposition = 'WRITE_TRUNCATE') \n\n ##########\n query_02 = finance_raw_query.format(date_suffix = exec_date.strftime('%Y-%m-%d'))\n self.log.info(f\"execution query - finance_raw [{query_02}]\")\n self.do_query(query = query_02,\n destination_dataset_table = 'socar-data.socar_biz_param.finance_raw${date_suffix}'.format(date_suffix = date_suffix),\n write_disposition = 'WRITE_TRUNCATE') \n\n ##########\n query_03 = reservation_biz_detail_query.format(date_suffix = exec_date.strftime('%Y-%m-%d'))\n self.log.info(f\"execution query - reservation_biz_detail [{query_03}]\")\n self.do_query(query = query_03,\n destination_dataset_table = 'socar-data.socar_biz_param.reservation_biz_detail${date_suffix}'.format(date_suffix = date_suffix),\n write_disposition = 'WRITE_TRUNCATE') \n \n except Exception as e:\n self.log.exception(e)\n raise\n \n def do_query(self, query, destination_dataset_table, write_disposition):\n results = self.bq_cursor.run_query(sql=query,\n destination_dataset_table=destination_dataset_table,\n write_disposition=write_disposition,\n use_legacy_sql=False)\n\n","sub_path":"dags/dependencies/socar_biz_param_operator.py","file_name":"socar_biz_param_operator.py","file_ext":"py","file_size_in_byte":3398,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"540157835","text":"import os\nimport pickle\nimport traceback\nfrom time import sleep, time as ttime\nfrom collections import defaultdict\nfrom threading import Thread\n\nimport rlp\nfrom ethereum import utils\n\nfrom plasma.config import plasma_config\nfrom plasma.utils.utils import send_transaction_sync\nfrom .block import Block\nfrom .exceptions import (InvalidBlockMerkleException,\n InvalidBlockSignatureException,\n InvalidTxSignatureException, TxAlreadySpentException,\n TxAmountMismatchException, InvalidTxOutputsException,\n InvalidTxInputsException, TxExpiredException,\n BlockExpiredException, )\nfrom .transaction import Transaction, UnsignedTransaction0\nfrom .snapshot import make_snapshot\n\n\nclass RootChainListener(Thread):\n def __init__(self, child_chain, root_chain, interval=None, **kwargs):\n super(RootChainListener, self).__init__(**kwargs)\n self.child_chain = child_chain\n self.root_chain = root_chain\n if interval is None:\n interval = plasma_config[\"ROOT_CHAIN_LISTENER_INTERVAL\"]\n self.interval = float(interval)\n # self.event_filter = self.root_chain.web3.eth.filter({\"fromBlock\": \"latest\", \"address\": plasma_config[\"ROOT_CHAIN_CONTRACT_ADDRESS\"]}) # {'blockHash': HexBytes('0xecfaa038f78cd3d6e67f64d317240da49c84f9c0acc8c61694bba5c83456b215'), 'data': '0x000000000000000000000000fd02ecee62797e75d86bcff1642eb0844afb28c70000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000006400000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000002', 'transactionIndex': 11, 'blockNumber': 3562847, 'logIndex': 13, 'address': '0x15AB8DFbb99D72423eb618591836689a5E87dC7a', 'topics': [HexBytes('0x4e2ca0515ed1aef1395f66b5303bb5d6f1bf9d61a353fa53f73f8ac9973fa9f6')], 'transactionHash': HexBytes('0xc549c7b4dac27999a211f2fea4df9842d05f0fba4a7ea63b5779d8a6198c066e'), 'removed': False}\n\n # self.event_filters = []\n # self.event_filters.append(self.root_chain.events.Deposit.createFilter(fromBlock=\"latest\"))\n # self.event_filters.append(self.root_chain.events.ExitStarted.createFilter(fromBlock=\"latest\"))\n # for event_filter in self.event_filters:\n # print(event_filter)\n\n def get_events(self):\n current_ether_block_number = self.child_chain.current_ether_block_number\n node_ether_block_number = self.root_chain.web3.eth.blockNumber\n to_block = node_ether_block_number - plasma_config[\"ROOT_CHAIN_CONFIRM_BLOCKS\"]\n if current_ether_block_number > to_block:\n return []\n\n print(\"getting events, from block: %s, to block: %s\" % (current_ether_block_number, to_block))\n\n res = []\n for event_func in [self.root_chain.events.Deposit, self.root_chain.events.ExitStarted]:\n event_filter = event_func.createFilter(fromBlock=current_ether_block_number, toBlock=to_block)\n res += event_filter.get_all_entries()\n\n self.child_chain.current_ether_block_number = to_block + 1\n self.child_chain.save()\n return res\n\n def run(self):\n while True:\n try:\n events = self.get_events()\n except Exception as e:\n print(\"get events error\")\n traceback.print_exc()\n else:\n # for event_filter in self.event_filters:\n # events = event_filter.get_new_entries()\n for event in events:\n try:\n self.child_chain.handle_event(event)\n except Exception as e:\n print(\"root chain listener error\")\n traceback.print_exc()\n sleep(self.interval)\n\n\nclass ChildChain(object):\n\n def __init__(self, authority, root_chain, partially_signed_transaction_pool=None, load=True):\n self.root_chain = root_chain\n self.partially_signed_transaction_pool = partially_signed_transaction_pool\n self.authority = authority\n self.blocks = {}\n self.child_block_interval = 1000\n self.current_block_number = self.child_block_interval\n self.current_block = Block()\n self.pending_transactions = []\n self.current_ether_block_number = None\n\n if load:\n self.load()\n\n if self.current_ether_block_number is None:\n self.current_ether_block_number = self.root_chain.web3.eth.blockNumber - plasma_config[\"ROOT_CHAIN_CONFIRM_BLOCKS\"]\n\n # Register for deposit event listener\n self.root_chain_listener = RootChainListener(self, self.root_chain)\n self.root_chain_listener.start()\n \n def handle_event(self, event):\n # AttributeDict({'blockHash': HexBytes('0x5913f5ad31934d9e3dd6da378f6443598dc0503245401deb1d918d51b4eaf7a7'), 'transactionHash': HexBytes('0x5137d9634681ceb5fad4ad23e32a30d424b3b5a3b080973b994379a18e8e872a'), 'event': 'Deposit', 'blockNumber': 3562832, 'args': AttributeDict({'amount': 100, 'depositBlock': 1, 'tokenId': 0, 'depositor': '0xfd02EcEE62797e75D86BCff1642EB0844afB28c7', 'contractAddress': '0x0000000000000000000000000000000000000000'}), 'logIndex': 5, 'address': '0x15AB8DFbb99D72423eb618591836689a5E87dC7a', 'transactionIndex': 6})\n if event.event == \"Deposit\":\n self.apply_deposit(event)\n elif event.event == \"ExitStarted\":\n self.apply_exit_start(event)\n else:\n print(\"unexpected event\", event)\n\n @property\n def save_field_names(self):\n return [\"blocks\", \"current_block_number\", \"current_block\", \"pending_transactions\", \"current_ether_block_number\"]\n \n def save(self):\n # print(\"skip save\")\n # return None\n\n if not os.path.exists(plasma_config[\"PICKLE_DIR\"]):\n os.mkdir(plasma_config[\"PICKLE_DIR\"])\n\n make_snapshot()\n\n for field_name in self.save_field_names:\n# print('saving %s...' % field_name)\n with open(os.path.join(plasma_config[\"PICKLE_DIR\"], field_name + \".pickle\"), \"wb\") as f:\n pickle.dump(getattr(self, field_name), f, pickle.HIGHEST_PROTOCOL)\n print('child chain saved')\n \n def load(self):\n if os.path.exists(plasma_config[\"PICKLE_DIR\"]):\n for field_name in self.save_field_names:\n print('loading %s...' % field_name)\n try:\n with open(os.path.join(plasma_config[\"PICKLE_DIR\"], field_name + \".pickle\"), 'rb') as f:\n setattr(self, field_name, pickle.load(f))\n except Exception as e:\n print(\"load %s failed: %s\" % (field_name, str(e)))\n\n def apply_deposit(self, event):\n event_args = event['args']\n newowner1 = event_args['depositor']\n contractaddress1 = event_args['contractAddress']\n amount1 = event_args['amount']\n tokenid1 = event_args['tokenId']\n blknum1 = event_args['depositBlock']\n\n deposit_tx = Transaction(blknum1, 0, 0, 0, 0, 0,\n newowner1, contractaddress1, amount1, tokenid1,\n b'\\x00' * 20, 0, 0, 0)\n deposit_block = Block([deposit_tx])\n\n self.blocks[blknum1] = deposit_block\n print(\"Deposit Block Number: %s\" % blknum1)\n \n self.save()\n \n def challenge_exit(self, utxopos, blknum, txindex, oindex):\n for block_number, block in self.blocks.items():\n if block_number >= blknum:\n for transaction_index, transaction in enumerate(block.transaction_set):\n e_utxo_index = None\n if transaction.blknum1 == blknum and \\\n transaction.txindex1 == txindex and \\\n transaction.oindex1 == oindex:\n e_utxo_index = 0\n if transaction.blknum2 == blknum and \\\n transaction.txindex2 == txindex and \\\n transaction.oindex2 == oindex:\n e_utxo_index = 1\n if e_utxo_index is not None:\n block.merklize_transaction_set()\n proof = block.merkle.create_membership_proof(transaction.merkle_hash)\n send_transaction_sync(self.root_chain.web3, self.root_chain.functions.challengeExit(\n block_number * 1000000000 + transaction_index * 10000,\n e_utxo_index,\n rlp.encode(transaction, UnsignedTransaction0),\n proof,\n transaction.sig1 + transaction.sig2), options={})\n # self.root_chain.transact({'from': '0x' + self.authority.hex()}).challengeExit(\n # block_number * 1000000000 + transaction_index * 10000,\n # e_utxo_index,\n # rlp.encode(transaction, UnsignedTransaction0),\n # proof,\n # transaction.sig1 + transaction.sig2)\n print(\"Exiting Challenged Send, UTXOPos: %s\" % utxopos)\n return None\n print(\"Exiting Challenge Does Not Exists, UTXOPos: %s\" % utxopos)\n \n def apply_exit_start(self, event):\n event_args = event['args']\n exitor = event_args['exitor']\n utxopos = event_args['utxoPos']\n contractaddress = event_args['contractAddress']\n amount = event_args['amount']\n tokenid = event_args['tokenId']\n \n blknum = utxopos // 1000000000\n txindex = (utxopos % 1000000000) // 10000\n oindex = utxopos - blknum * 1000000000 - txindex * 10000\n \n block = self.blocks.get(blknum)\n if block is None:\n print(\"Exiting Block Does Not Exists, UTXOPos: %s\" % utxopos)\n return None\n \n try:\n transaction = block.transaction_set[txindex]\n except IndexError:\n print(\"Exiting Transaction Does Not Exists, UTXOPos: %s\" % utxopos)\n return None\n \n if oindex == 0:\n if utils.normalize_address(transaction.newowner1) != utils.normalize_address(exitor) or \\\n utils.normalize_address(transaction.contractaddress1) != utils.normalize_address(contractaddress) or \\\n transaction.amount1 != amount or \\\n transaction.tokenid1 != tokenid:\n print(\"Exiting UTXO Does Not Match, UTXOPos: %s\" % utxopos)\n return None\n if transaction.spent1:\n return self.challenge_exit(utxopos, blknum, txindex, oindex)\n else:\n if utils.normalize_address(transaction.newowner2) != utils.normalize_address(exitor) or \\\n utils.normalize_address(transaction.contractaddress2) != utils.normalize_address(contractaddress) or \\\n transaction.amount2 != amount or \\\n transaction.tokenid2 != tokenid:\n print(\"Exiting UTXO Does Not Match, UTXOPos: %s\" % utxopos)\n return None\n if transaction.spent2:\n return self.challenge_exit(utxopos, blknum, txindex, oindex)\n \n self.mark_utxo_spent(blknum, txindex, oindex)\n print(\"Exit Start %s %s %s\" % (blknum, txindex, oindex))\n \n self.save()\n\n def apply_transaction(self, transaction):\n tx = rlp.decode(utils.decode_hex(transaction), Transaction)\n\n # Validate the transaction\n self.validate_tx(tx)\n\n # Mark the inputs as spent\n self.mark_utxo_spent(tx.blknum1, tx.txindex1, tx.oindex1)\n self.mark_utxo_spent(tx.blknum2, tx.txindex2, tx.oindex2)\n\n self.current_block.transaction_set.append(tx)\n self.blocks[self.current_block_number] = self.current_block\n \n# if self.partially_signed_transaction_pool is not None:\n# self.partially_signed_transaction_pool.remove_ps_transaction(tx)\n \n self.save()\n \n return tx.hash0.hex()\n\n def validate_outputs(self, contractaddress, amount, tokenid):\n if amount < 0 or tokenid < 0:\n raise InvalidTxOutputsException('failed to validate tx')\n if contractaddress == utils.normalize_address(0) and \\\n amount == 0 and \\\n tokenid == 0:\n return True\n if amount == 0 and tokenid == 0:\n raise InvalidTxOutputsException('failed to validate tx')\n\n if contractaddress == utils.normalize_address(0):\n if tokenid != 0:\n raise InvalidTxOutputsException('failed to validate tx')\n elif amount == 0:\n if tokenid == 0:\n raise InvalidTxOutputsException('failed to validate tx')\n else:\n if tokenid != 0:\n raise InvalidTxOutputsException('failed to validate tx')\n return True\n\n def validate_tx(self, tx):\n if tx.sig1 == b'\\x00' * 65 or tx.sig2 == b'\\x00' * 65:\n raise InvalidTxSignatureException('failed to validate tx')\n \n if (tx.blknum1, tx.txindex1, tx.oindex1) == (tx.blknum2, tx.txindex2, tx.oindex2):\n raise InvalidTxInputsException('failed to validate tx')\n \n if (int(ttime()) + plasma_config[\"TX_EXPIRE_BUFFER_SECONDS\"] > tx.expiretimestamp):\n raise TxExpiredException('failed to validate tx')\n \n self.validate_outputs(tx.contractaddress1, tx.amount1, tx.tokenid1)\n self.validate_outputs(tx.contractaddress2, tx.amount2, tx.tokenid2)\n \n if tx.tokenid1 != 0 and \\\n tx.tokenid2 != 0 and \\\n tx.tokenid1 == tx.tokenid2 and \\\n tx.contractaddress1 == tx.contractaddress2:\n raise InvalidTxOutputsException('failed to validate tx')\n \n output_amounts = defaultdict(int)\n if tx.amount1 != 0:\n output_amounts[tx.contractaddress1] += tx.amount1\n if tx.amount2 != 0:\n output_amounts[tx.contractaddress2] += tx.amount2\n \n output_nfts = []\n if tx.tokenid1 != 0:\n output_nfts.append((tx.contractaddress1, tx.tokenid1))\n if tx.tokenid2 != 0:\n output_nfts.append((tx.contractaddress2, tx.tokenid2))\n \n inputs = [(tx.blknum1, tx.txindex1, tx.oindex1), (tx.blknum2, tx.txindex2, tx.oindex2)]\n\n input_amounts = defaultdict(int)\n input_nfts = []\n\n for i, (blknum, txindex, oindex) in enumerate(inputs):\n # Assume empty inputs and are valid\n if blknum == 0:\n continue\n \n curSign = getattr(tx, \"sign\" + str(i + 1))\n curSender = getattr(tx, \"sender\" + str(i + 1))\n \n transaction = self.blocks[blknum].transaction_set[txindex]\n\n if oindex == 0:\n valid_signature = curSign != b'\\x00' * 65 and transaction.newowner1 == curSender\n spent = transaction.spent1\n if transaction.amount1 != 0:\n input_amounts[transaction.contractaddress1] += transaction.amount1\n if transaction.tokenid1 != 0:\n input_nfts.append((transaction.contractaddress1, transaction.tokenid1))\n else:\n valid_signature = curSign != b'\\x00' * 65 and transaction.newowner2 == curSender\n spent = transaction.spent2\n if transaction.amount2 != 0:\n input_amounts[transaction.contractaddress2] += transaction.amount2\n if transaction.tokenid2 != 0:\n input_nfts.append((transaction.contractaddress2, transaction.tokenid2))\n if spent:\n raise TxAlreadySpentException('failed to validate tx')\n if not valid_signature:\n raise InvalidTxSignatureException('failed to validate tx')\n \n if sorted(output_amounts.items()) != sorted(input_amounts.items()):\n raise TxAmountMismatchException('failed to validate tx')\n \n if sorted(output_nfts) != sorted(input_nfts):\n raise TxAmountMismatchException('failed to validate tx')\n\n def mark_utxo_spent(self, blknum, txindex, oindex):\n if blknum == 0:\n return\n\n if oindex == 0:\n self.blocks[blknum].transaction_set[txindex].spent1 = True\n else:\n self.blocks[blknum].transaction_set[txindex].spent2 = True\n \n if self.partially_signed_transaction_pool is not None:\n self.partially_signed_transaction_pool.utxo_spent(blknum, txindex, oindex)\n\n def _submit_block(self, block):\n send_transaction_sync(self.root_chain.web3, self.root_chain.functions.submitBlock(block.merkle.root, block.min_expire_timestamp), options={})\n # self.root_chain.transact({'from': '0x' + self.authority.hex()}).submitBlock(block.merkle.root, block.min_expire_timestamp)\n # TODO: iterate through block and validate transactions\n self.blocks[self.current_block_number] = self.current_block\n self.current_block_number += self.child_block_interval\n self.current_block = Block()\n self.save()\n \n\n def submit_curblock(self):\n block = self.current_block\n if len(block.transaction_set) > 0:\n if (int(ttime()) + plasma_config[\"BLOCK_EXPIRE_BUFFER_SECONDS\"] > block.min_expire_timestamp):\n print('block expired, drop it')\n self.current_block = Block()\n self.blocks[self.current_block_number] = self.current_block\n \n self.save()\n else:\n block.sign(plasma_config[\"AUTHORITY_KEY\"])\n block.merklize_transaction_set()\n print(\"submit block #%s\" % self.current_block_number)\n self._submit_block(block)\n \n def submit_block(self, block):\n block = rlp.decode(utils.decode_hex(block), Block)\n if block.merklize_transaction_set() != self.current_block.merklize_transaction_set():\n raise InvalidBlockMerkleException('input block merkle mismatch with the current block')\n\n valid_signature = block.sig != b'\\x00' * 65 and block.sender == self.authority\n if not valid_signature:\n raise InvalidBlockSignatureException('failed to submit block')\n \n if len(block.transaction_set) == 0:\n print(\"no transaction in block, do nothing\")\n return\n \n if (int(ttime()) + plasma_config[\"BLOCK_EXPIRE_BUFFER_SECONDS\"] > block.min_expire_timestamp):\n# raise BlockExpiredException('failed to submit block')\n print('block expired, drop it!')\n self.current_block = Block()\n \n self.save()\n\n print(\"submit block ...\")\n self._submit_block(block)\n\n def get_transaction(self, blknum, txindex):\n return rlp.encode(self.blocks[blknum].transaction_set[txindex]).hex()\n\n def get_block(self, blknum):\n return rlp.encode(self.blocks[blknum]).hex()\n\n def get_current_block(self):\n return rlp.encode(self.current_block).hex()\n\n def get_current_block_num(self):\n return self.current_block_number\n\n #\n # MetaMask Interface\n #\n def get_version(self):\n return \"0x100\"\n\n def get_balance(self, address, block):\n if block != \"latest\":\n raise Exception(\"only support block: latest\")\n if not address:\n raise Exception(\"address required\")\n\n output_amounts = defaultdict(int)\n output_nfts = []\n\n for block_number, block in self.blocks.items():\n for tx in block.transaction_set:\n # check if utxo belongs to the owner and is not spent\n if tx.newowner1 == utils.normalize_address(address) and tx.spent1 == False:\n if tx.amount1 != 0:\n output_amounts[utils.decode_addr(tx.contractaddress1)] += tx.amount1\n if tx.tokenid1 != 0:\n output_nfts.append((utils.decode_addr(tx.contractaddress1), tx.tokenid1))\n if tx.newowner2 == utils.normalize_address(address) and tx.spent2 == False:\n if tx.amount2 != 0:\n output_amounts[utils.decode_addr(tx.contractaddress2)] += tx.amount2\n if tx.tokenid2 != 0:\n output_nfts.append((utils.decode_addr(tx.contractaddress2), tx.tokenid2))\n res = {\n \"FT\": sorted(output_amounts.items()),\n \"NFT\": sorted(output_nfts),\n }\n print(\"balance: %s\" % res)\n return res\n\n def get_block_by_num(self, block, deep):\n print(\"get_block_by_num with %s and %s\" %(block, deep))\n try:\n rlp.encode(self.blocks[self.current_block_number-1]).hex()\n except KeyError:\n return {}\n \n def get_utxo(self, address, block):\n if block != \"latest\":\n raise Exception(\"only support block: latest\")\n\n utxo = []\n for block_number, block in self.blocks.items():\n for tx_index, tx in enumerate(block.transaction_set):\n # check if utxo belongs to the owner and is not spent\n if tx.newowner1 == utils.normalize_address(address) and tx.spent1 == False and not (tx.amount1 == 0 and tx.tokenid1 == 0):\n utxo.append([block_number, tx_index, 0, utils.decode_addr(tx.contractaddress1), tx.amount1, tx.tokenid1])\n if tx.newowner2 == utils.normalize_address(address) and tx.spent2 == False and not (tx.amount2 == 0 and tx.tokenid2 == 0):\n utxo.append([block_number, tx_index, 1, utils.decode_addr(tx.contractaddress2), tx.amount2, tx.tokenid2])\n return utxo\n\n def get_all_transactions(self):\n res = []\n for block_number, block in self.blocks.items():\n for tx_index, tx in enumerate(block.transaction_set):\n res.append([block_number, tx_index, str(tx)])\n return res\n \n def get_transactions_after(self, block_number, tx_index):\n res = []\n for cur_block_number in sorted(self.blocks.keys()):\n if cur_block_number >= block_number and cur_block_number % self.child_block_interval == 0:\n block = self.blocks[cur_block_number]\n for cur_tx_index, tx in enumerate(block.transaction_set):\n if cur_block_number == block_number and cur_tx_index <= tx_index:\n continue\n res.append([cur_block_number, cur_tx_index, tx.to_json()])\n return res\n\n def eth_raw_transaction(self, raw_tx):\n # print(raw_tx[2:])\n return self.apply_transaction(raw_tx[2:])\n","sub_path":"plasma/child_chain/child_chain.py","file_name":"child_chain.py","file_ext":"py","file_size_in_byte":22958,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"548070904","text":"import json\nimport boto3\nimport sys, traceback\nimport uuid\nimport os\nfrom fssi_common import *\nimport simplejson\nimport time\n\ndef getOccupancy(experienceId):\n # get latest occupancy for the experience\n # the occupancy is an array of visitor IDs (QR codes)\n occupancyTable = dynamoDbResource.Table(FssiResources.DynamoDB.Occupancy)\n result = occupancyTable.get_item(Key={'id' : experienceId})\n if 'Item' in result:\n return result['Item']['occupancy']\n return None\n\ndef getVisitorExposure(visitorId):\n response = timeseriesGetLatestForKey(FssiResources.DynamoDB.VisitorExposureTs,\n keyName='visitor_id', keyValue=visitorId)\n\n if response['Count'] > 0:\n return ExposureVector(json.loads(response['Items'][0]['exposure']['S']))\n return ExposureVector({})\n\ndef publishSns(experienceId, exposureV):\n snsMessageBody = { 'experience_id' : experienceId,\n 'exposure' : exposureV.encode(),\n 't': time.time()}\n mySnsClient = boto3.client('sns')\n response = mySnsClient.publish(TopicArn=getSnsTopicByName(FssiResources.Sns.ExposureUpdates),\n Message=simplejson.dumps(snsMessageBody))\n if response and type(response) == dict and 'MessageId' in response:\n return\n else:\n print(\"unable to send SNS message: \", response)\n\ndef lambda_handler(event, context):\n try:\n # change it or get it from event dictionary\n xpId = 'tactile'\n xpOccupancy = getOccupancy(xpId)\n print('experience {}. occupancy {}'.format(xpId, xpOccupancy))\n\n # get experience exposure\n reply = timeseriesGetLatestForKey(FssiResources.DynamoDB.ExperienceExposureTs, 'experience_id', xpId)\n pyDict = unmarshallAwsDataItem(reply['Items'][0])\n xpExposure = ExposureVector(json.loads(pyDict['exposure']))\n print('experience aggregate exposure {}'.format(xpExposure))\n\n # get each visitor's exposure\n visitorExposures = []\n for userId in xpOccupancy:\n vExp = getVisitorExposure(userId)\n visitorExposures.append(vExp)\n print('occupant {} exposure {}'.format(userId, vExp))\n\n # get experience emission\n reply = timeseriesGetLatestForKey(FssiResources.DynamoDB.ExperienceEmissionTs, 'experience_id', xpId)\n pyDict = unmarshallAwsDataItem(reply['Items'][0])\n pyDict['state'] = json.loads(pyDict['state'])\n xpEmission = ExperienceState(pyDict)\n print('experience {} last emission: {}'.format(xpEmission.experienceId_, xpEmission.emissionVector_))\n\n # get identity info here\n\n raise ValueError('do processing here')\n except:\n type, err, tb = sys.exc_info()\n print('caught exception:', err)\n traceback.print_exc(file=sys.stdout)\n return lambdaReply(420, str(err))\n\n return processedReply()\n\n# for local testing\nif __name__ == '__main__':\n lambda_handler(None, None)\n","sub_path":"lambda/recommender-scaffold/lambda_function.py","file_name":"lambda_function.py","file_ext":"py","file_size_in_byte":2945,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"598478332","text":"from django.shortcuts import render\n\nfrom introduction.form import ReplyForm\nfrom introduction.models import Experience, Work, Ability, Contact\n\n\ndef index(request):\n experiences = Experience.objects.all()\n works = Work.objects.all()\n abilities = Ability.objects.all()\n reply = ReplyForm()\n if request.method == 'POST':\n reply = ReplyForm(request.POST)\n if reply.is_valid():\n Contact.objects.create(name=request.POST['name'], email=request.POST['email'],\n message=request.POST['message'])\n reply = ReplyForm()\n return render(request, \"index.html\", locals())\n\n# Create your views here.\n","sub_path":"introduction/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":673,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"557943097","text":"#!/usr/bin/env python\n\nimport pprint\npp = pprint.PrettyPrinter(indent=4)\n\n\nimport logging\n#perhaps add more complexity as time goes on\nlogger = logging.getLogger()\nformatter = logging.Formatter('%(asctime)s - %(name)30s - %(levelname)10s - %(message)s')\nlogger.setLevel(logging.INFO)\n\nsh = logging.StreamHandler()\nsh.setFormatter(formatter)\nlogger.addHandler(sh)\n","sub_path":"pyameritrade/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":363,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"459665538","text":"\"\"\"\nLinear projection widget\n------------------------\n\n\"\"\"\n\nfrom functools import reduce\nfrom operator import itemgetter\nfrom types import SimpleNamespace as namespace\nfrom xml.sax.saxutils import escape\n\nfrom scipy.spatial import distance\nimport pkg_resources\n\nfrom PyQt4 import QtGui, QtCore\n\nfrom PyQt4.QtGui import (\n QListView, QSizePolicy, QApplication, QAction, QKeySequence,\n QGraphicsLineItem, QSlider, QPainterPath\n)\nfrom PyQt4.QtCore import Qt, QObject, QEvent, QSize, QRectF, QLineF, QPointF\nfrom PyQt4.QtCore import pyqtSignal as Signal, pyqtSlot as Slot\n\nimport numpy\n\nimport pyqtgraph.graphicsItems.ScatterPlotItem\nimport pyqtgraph as pg\nimport Orange\n\nfrom Orange.widgets import widget, gui, settings\nfrom Orange.widgets.utils import itemmodels, colorpalette\nfrom Orange.widgets.visualize.owscatterplotgraph import LegendItem, legend_anchor_pos\n\nfrom .utils.axisitem import AxisItem\n\n\nclass DnDVariableListModel(itemmodels.VariableListModel):\n\n MimeType = \"application/x-orange-variable-list\"\n\n def supportedDropActions(self):\n return Qt.MoveAction\n\n def supportedDragActions(self):\n return Qt.MoveAction\n\n def mimeTypes(self):\n return [DnDVariableListModel.MimeType]\n\n def mimeData(self, indexlist):\n variables = []\n itemdata = []\n for index in indexlist:\n variables.append(self[index.row()])\n itemdata.append(self.itemData(index))\n\n mime = QtCore.QMimeData()\n mime.setData(self.MimeType, b\"see properties\")\n mime.setProperty(\"variables\", variables)\n mime.setProperty(\"itemdata\", itemdata)\n return mime\n\n def dropMimeData(self, mime, action, row, column, parent):\n if action == Qt.IgnoreAction:\n return True\n elif not mime.hasFormat(self.MimeType):\n return False\n\n variables = mime.property(\"variables\")\n itemdata = mime.property(\"itemdata\")\n\n if variables is None:\n return False\n\n if row == -1:\n row = len(self)\n\n # Insert variables at row and restore other item data\n self[row:row] = variables\n for i, data in enumerate(itemdata):\n self.setItemData(self.index(row + i), data)\n return True\n\n def flags(self, index):\n flags = super().flags(index)\n if index.isValid():\n flags |= Qt.ItemIsDragEnabled\n else:\n flags |= Qt.ItemIsDropEnabled\n return flags\n\n\nclass ScatterPlotItem(pg.ScatterPlotItem):\n Symbols = pyqtgraph.graphicsItems.ScatterPlotItem.Symbols\n\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n\n def paint(self, painter, option, widget=None):\n if self.opts[\"pxMode\"]:\n painter.setRenderHint(QtGui.QPainter.SmoothPixmapTransform, True)\n\n if self.opts[\"antialias\"]:\n painter.setRenderHint(QtGui.QPainter.Antialiasing, True)\n\n super().paint(painter, option, widget)\n\n\nclass LegendItem(LegendItem):\n def clear(self):\n \"\"\"\n Clear all legend items.\n \"\"\"\n items = list(self.items)\n self.items = []\n for sample, label in items:\n # yes, the LegendItem shadows QGraphicsWidget.layout() with\n # an instance attribute.\n self.layout.removeItem(sample)\n self.layout.removeItem(label)\n sample.hide()\n label.hide()\n\n self.updateSize()\n\n def mousePressEvent(self, event):\n if event.button() == Qt.LeftButton:\n event.accept()\n else:\n event.ignore()\n\n def mouseMoveEvent(self, event):\n if event.buttons() & Qt.LeftButton:\n event.accept()\n if self.parentItem() is not None:\n self.autoAnchor(\n self.pos() + (event.pos() - event.lastPos()) / 2)\n else:\n event.ignore()\n\n def mouseReleaseEvent(self, event):\n if event.button() == Qt.LeftButton:\n event.accept()\n else:\n event.ignore()\n\n\nclass OWLinearProjection(widget.OWWidget):\n name = \"Linear Projection\"\n description = \"A multi-axes projection of data to a two-dimension plane.\"\n icon = \"icons/LinearProjection.svg\"\n replaces = [\"Orange.widgets.visualize.owlinearprojection.OWLinearProjection\"]\n priority = 2000\n\n inputs = [(\"Data\", Orange.data.Table, \"set_data\", widget.Default),\n (\"Data Subset\", Orange.data.Table, \"set_subset_data\"),\n (\"Projection\", Orange.data.Table, \"set_projection\")]\n outputs = [(\"Selected Data\", Orange.data.Table)]\n\n settingsHandler = settings.DomainContextHandler()\n\n variable_state = settings.ContextSetting({})\n\n optimization = settings.Setting(0)\n\n color_index = settings.ContextSetting(0)\n shape_index = settings.ContextSetting(0)\n size_index = settings.ContextSetting(0)\n\n point_size = settings.Setting(10)\n alpha_value = settings.Setting(255)\n jitter_value = settings.Setting(0)\n hide_radius = settings.Setting(0)\n\n auto_commit = settings.Setting(True)\n\n legend_anchor = settings.Setting(((1, 0), (1, 0)))\n MinPointSize = 6\n\n ReplotRequest = QEvent.registerEventType()\n\n graph_name = \"viewbox\"\n\n def __init__(self):\n super().__init__()\n\n self.data = None\n self.projection = None\n self.subset_data = None\n self._subset_mask = None\n self._selection_mask = None\n self._item = None\n self._axes = None\n self._max_dist = 0\n self.__legend = None\n self.__selection_item = None\n self.__replot_requested = False\n\n box = gui.widgetBox(self.controlArea, \"Axes\")\n\n box1 = gui.widgetBox(box, \"Displayed\", margin=0)\n box1.setFlat(True)\n self.active_view = view = QListView(\n sizePolicy=QSizePolicy(QSizePolicy.Minimum, QSizePolicy.Ignored),\n selectionMode=QListView.ExtendedSelection,\n dragEnabled=True,\n defaultDropAction=Qt.MoveAction,\n dragDropOverwriteMode=False,\n dragDropMode=QListView.DragDrop,\n showDropIndicator=True,\n minimumHeight=100,\n )\n\n view.viewport().setAcceptDrops(True)\n movedown = QAction(\n \"Move down\", view,\n shortcut=QKeySequence(Qt.AltModifier | Qt.Key_Down),\n triggered=self.__deactivate_selection\n )\n view.addAction(movedown)\n\n self.varmodel_selected = model = DnDVariableListModel(\n parent=self)\n\n model.rowsInserted.connect(self._invalidate_plot)\n model.rowsRemoved.connect(self._invalidate_plot)\n model.rowsMoved.connect(self._invalidate_plot)\n\n view.setModel(model)\n\n box1.layout().addWidget(view)\n\n box1 = gui.widgetBox(box, \"Other\", margin=0)\n box1.setFlat(True)\n self.other_view = view = QListView(\n sizePolicy=QSizePolicy(QSizePolicy.Minimum, QSizePolicy.Ignored),\n selectionMode=QListView.ExtendedSelection,\n dragEnabled=True,\n defaultDropAction=Qt.MoveAction,\n dragDropOverwriteMode=False,\n dragDropMode=QListView.DragDrop,\n showDropIndicator=True,\n minimumHeight=150\n )\n view.viewport().setAcceptDrops(True)\n moveup = QtGui.QAction(\n \"Move up\", view,\n shortcut=QKeySequence(Qt.AltModifier | Qt.Key_Up),\n triggered=self.__activate_selection\n )\n view.addAction(moveup)\n\n self.varmodel_other = model = DnDVariableListModel(parent=self)\n view.setModel(model)\n\n box1.layout().addWidget(view)\n\n box = gui.widgetBox(self.controlArea, \"Optimization\")\n self.opt_radio = gui.radioButtonsInBox(\n box, self, \"optimization\",\n btnLabels=[\"Circular (no optimization)\",\n \"LDA\",\n \"Use input projection\"],\n callback=self._invalidate_plot\n )\n box.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Fixed)\n\n box = gui.widgetBox(self.controlArea, \"Jittering\")\n gui.comboBox(box, self, \"jitter_value\",\n items=[\"None\", \"0.01%\", \"0.1%\", \"0.5%\", \"1%\", \"2%\"],\n callback=self._invalidate_plot)\n box.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Fixed)\n\n box = gui.widgetBox(self.controlArea, \"Points\")\n box.setSizePolicy(QSizePolicy.Minimum, QSizePolicy.Maximum)\n\n self.colorvar_model = itemmodels.VariableListModel(parent=self)\n self.shapevar_model = itemmodels.VariableListModel(parent=self)\n self.sizevar_model = itemmodels.VariableListModel(parent=self)\n\n form = QtGui.QFormLayout(\n formAlignment=Qt.AlignLeft,\n labelAlignment=Qt.AlignLeft,\n fieldGrowthPolicy=QtGui.QFormLayout.AllNonFixedFieldsGrow,\n spacing=8\n )\n box.layout().addLayout(form)\n\n cb = gui.comboBox(box, self, \"color_index\",\n callback=self._on_color_change)\n cb.setModel(self.colorvar_model)\n\n form.addRow(\"Colors\", cb)\n alpha_slider = QSlider(\n Qt.Horizontal, minimum=10, maximum=255, pageStep=25,\n tickPosition=QSlider.TicksBelow, value=self.alpha_value)\n alpha_slider.valueChanged.connect(self._set_alpha)\n\n form.addRow(\"Opacity\", alpha_slider)\n\n cb = gui.comboBox(box, self, \"shape_index\",\n callback=self._on_shape_change)\n cb.setModel(self.shapevar_model)\n\n form.addRow(\"Shape\", cb)\n\n cb = gui.comboBox(box, self, \"size_index\",\n callback=self._on_size_change)\n cb.setModel(self.sizevar_model)\n\n form.addRow(\"Size\", cb)\n size_slider = QSlider(\n Qt.Horizontal, minimum=3, maximum=30, value=self.point_size,\n pageStep=3,\n tickPosition=QSlider.TicksBelow)\n\n size_slider.valueChanged.connect(self._set_size)\n form.addRow(\"\", size_slider)\n\n radius_slider = QSlider(\n Qt.Horizontal, minimum=0, maximum=100, pageStep=10,\n tickPosition=QSlider.TicksBelow, value=self.hide_radius)\n radius_slider.valueChanged.connect(self._set_hide_radius)\n\n form.addRow(\"Hide radius\", radius_slider)\n toolbox = gui.widgetBox(self.controlArea, \"Zoom/Select\")\n toollayout = QtGui.QHBoxLayout()\n toolbox.layout().addLayout(toollayout)\n\n gui.auto_commit(self.controlArea, self, \"auto_commit\", \"Commit\")\n\n self.controlArea.setSizePolicy(\n QSizePolicy.Preferred, QSizePolicy.Expanding)\n\n # Main area plot\n self.view = pg.GraphicsView(background=\"w\")\n self.view.setRenderHint(QtGui.QPainter.Antialiasing, True)\n self.view.setFrameStyle(QtGui.QFrame.StyledPanel)\n self.viewbox = pg.ViewBox(enableMouse=True, enableMenu=False)\n self.viewbox.grabGesture(Qt.PinchGesture)\n self.view.setCentralItem(self.viewbox)\n\n self.mainArea.layout().addWidget(self.view)\n\n self.selection = PlotSelectionTool(self)\n self.selection.setViewBox(self.viewbox)\n self.selection.selectionFinished.connect(self._selection_finish)\n\n self.zoomtool = PlotZoomTool(self)\n self.pantool = PlotPanTool(self)\n self.pinchtool = PlotPinchZoomTool(self)\n self.pinchtool.setViewBox(self.viewbox)\n\n self.continuous_palette = colorpalette.ContinuousPaletteGenerator(\n QtGui.QColor(220, 220, 220),\n QtGui.QColor(0, 0, 0),\n False\n )\n self.discrete_palette = colorpalette.ColorPaletteGenerator(13)\n\n def icon(name):\n path = \"icons/Dlg_{}.png\".format(name)\n path = pkg_resources.resource_filename(widget.__name__, path)\n return QtGui.QIcon(path)\n\n actions = namespace(\n zoomtofit=QAction(\n \"Zoom to fit\", self, icon=icon(\"zoom_reset\"),\n shortcut=QKeySequence(Qt.ControlModifier | Qt.Key_0),\n triggered=lambda:\n self.viewbox.setRange(QRectF(-1.05, -1.05, 2.1, 2.1))),\n zoomin=QAction(\n \"Zoom in\", self,\n shortcut=QKeySequence(QKeySequence.ZoomIn),\n triggered=lambda: self.viewbox.scaleBy((1 / 1.25, 1 / 1.25))),\n zoomout=QAction(\n \"Zoom out\", self,\n shortcut=QKeySequence(QKeySequence.ZoomOut),\n triggered=lambda: self.viewbox.scaleBy((1.25, 1.25))),\n select=QAction(\n \"Select\", self, checkable=True, icon=icon(\"arrow\"),\n shortcut=QKeySequence(Qt.ControlModifier + Qt.Key_1)),\n zoom=QAction(\n \"Zoom\", self, checkable=True, icon=icon(\"zoom\"),\n shortcut=QKeySequence(Qt.ControlModifier + Qt.Key_2)),\n pan=QAction(\n \"Pan\", self, checkable=True, icon=icon(\"pan_hand\"),\n shortcut=QKeySequence(Qt.ControlModifier + Qt.Key_3)),\n )\n self.addActions([actions.zoomtofit, actions.zoomin, actions.zoomout])\n\n group = QtGui.QActionGroup(self, exclusive=True)\n group.addAction(actions.select)\n group.addAction(actions.zoom)\n group.addAction(actions.pan)\n\n actions.select.setChecked(True)\n\n currenttool = self.selection\n\n def activated(action):\n nonlocal currenttool\n if action is actions.select:\n tool, cursor = self.selection, Qt.ArrowCursor\n elif action is actions.zoom:\n tool, cursor = self.zoomtool, Qt.ArrowCursor\n elif action is actions.pan:\n tool, cursor = self.pantool, Qt.OpenHandCursor\n else:\n assert False\n currenttool.setViewBox(None)\n tool.setViewBox(self.viewbox)\n self.viewbox.setCursor(QtGui.QCursor(cursor))\n currenttool = tool\n\n group.triggered[QAction].connect(activated)\n\n def button(action):\n b = QtGui.QToolButton()\n b.setDefaultAction(action)\n return b\n\n toollayout.addWidget(button(actions.select))\n toollayout.addWidget(button(actions.zoom))\n toollayout.addWidget(button(actions.pan))\n\n toollayout.addSpacing(4)\n toollayout.addWidget(button(actions.zoomtofit))\n toollayout.addStretch()\n toolbox.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Maximum)\n\n def sizeHint(self):\n return QSize(800, 500)\n\n def clear(self):\n self.data = None\n self._subset_mask = None\n self._selection_mask = None\n\n self.varmodel_selected[:] = []\n self.varmodel_other[:] = []\n\n self.colorvar_model[:] = []\n self.sizevar_model[:] = []\n self.shapevar_model[:] = []\n\n self.color_index = 0\n self.size_index = 0\n self.shape_index = 0\n\n self.clear_plot()\n\n def clear_plot(self):\n if self._item is not None:\n self._item.setParentItem(None)\n self.viewbox.removeItem(self._item)\n self._item = None\n\n if self.__legend is not None:\n anchor = legend_anchor_pos(self.__legend)\n if anchor is not None:\n self.legend_anchor = anchor\n\n self.__legend.setParentItem(None)\n self.__legend.clear()\n self.__legend.setVisible(False)\n self._axes = None\n self.viewbox.clear()\n\n def _invalidate_plot(self):\n \"\"\"\n Schedule a delayed replot.\n \"\"\"\n if not self.__replot_requested:\n self.__replot_requested = True\n QApplication.postEvent(self, QEvent(self.ReplotRequest),\n Qt.LowEventPriority - 10)\n\n def set_projection(self, projection):\n self.warning(0)\n if projection and len(projection) < 2:\n self.warning(0, \"Input projection has less than 2 components\")\n projection = None\n self.projection = projection\n self._invalidate_plot()\n\n def set_data(self, data):\n \"\"\"\n Set the input dataset.\n \"\"\"\n self.closeContext()\n self.clear()\n self.data = data\n if data is not None:\n self._initialize(data)\n # get the default encoded state, replacing the position with Inf\n state = self._encode_var_state(\n [list(self.varmodel_selected), list(self.varmodel_other)]\n )\n state = {key: (source_ind, numpy.inf) for key, (source_ind, _)\n in state.items()}\n\n self.openContext(data.domain)\n selected_keys = [key for key, (sind, _) in self.variable_state.items()\n if sind == 0]\n\n if set(selected_keys).issubset(set(state.keys())):\n pass\n\n # update the defaults state (the encoded state must contain\n # all variables in the input domain)\n state.update(self.variable_state)\n # ... and restore it with saved positions taking precedence over\n # the defaults\n selected, other = self._decode_var_state(\n state, [list(self.varmodel_selected),\n list(self.varmodel_other)]\n )\n self.varmodel_selected[:] = selected\n self.varmodel_other[:] = other\n\n def clip_index(value, maxv):\n return max(0, min(value, maxv))\n\n self.color_index = clip_index(\n self.color_index, len(self.colorvar_model) - 1)\n self.shape_index = clip_index(\n self.shape_index, len(self.shapevar_model) - 1)\n self.size_index = clip_index(\n self.size_index, len(self.sizevar_model) - 1)\n\n self._invalidate_plot()\n\n def set_subset_data(self, subset):\n \"\"\"\n Set the supplementary input subset dataset.\n \"\"\"\n self.subset_data = subset\n self._subset_mask = None\n\n def check_possible_opt(self):\n for b in self.opt_radio.buttons:\n b.setEnabled(True)\n if self.data and not self.data.domain.has_discrete_class:\n self.opt_radio.buttons[1].setEnabled(False)\n if self.optimization == 1:\n self.optimization = 0\n if not self.projection:\n self.opt_radio.buttons[2].setEnabled(False)\n if self.optimization == 2:\n self.optimization = 0\n\n def handleNewSignals(self):\n self.check_possible_opt()\n if self.subset_data is not None and self._subset_mask is None:\n # Update the plot's highlight items\n if self.data is not None:\n dataids = self.data.ids.ravel()\n subsetids = numpy.unique(self.subset_data.ids)\n self._subset_mask = numpy.in1d(\n dataids, subsetids, assume_unique=True)\n self._invalidate_plot()\n self.commit()\n\n def customEvent(self, event):\n if event.type() == OWLinearProjection.ReplotRequest:\n self.__replot_requested = False\n self._setup_plot()\n else:\n super().customEvent(event)\n\n def closeContext(self):\n self.variable_state = self._encode_var_state(\n [list(self.varmodel_selected), list(self.varmodel_other)]\n )\n super().closeContext()\n\n def _encode_var_state(self, lists):\n return {(type(var), var.name): (source_ind, pos)\n for source_ind, var_list in enumerate(lists)\n for pos, var in enumerate(var_list)\n if isinstance(var, Orange.data.Variable)}\n\n def _decode_var_state(self, state, lists):\n all_vars = reduce(list.__iadd__, lists, [])\n\n newlists = [[] for _ in lists]\n for var in all_vars:\n source, pos = state[(type(var), var.name)]\n newlists[source].append((pos, var))\n return [[var for _, var in sorted(newlist, key=itemgetter(0))]\n for newlist in newlists]\n\n def color_var(self):\n \"\"\"\n Current selected color variable or None (if not selected).\n \"\"\"\n if 1 <= self.color_index < len(self.colorvar_model):\n return self.colorvar_model[self.color_index]\n else:\n return None\n\n def size_var(self):\n \"\"\"\n Current selected size variable or None (if not selected).\n \"\"\"\n if 1 <= self.size_index < len(self.sizevar_model):\n return self.sizevar_model[self.size_index]\n else:\n return None\n\n def shape_var(self):\n \"\"\"\n Current selected shape variable or None (if not selected).\n \"\"\"\n if 1 <= self.shape_index < len(self.shapevar_model):\n return self.shapevar_model[self.shape_index]\n else:\n return None\n\n def _initialize(self, data):\n # Initialize the GUI controls from data's domain.\n all_vars = list(data.domain.variables)\n cont_vars = [var for var in data.domain.variables\n if var.is_continuous]\n disc_vars = [var for var in data.domain.variables\n if var.is_discrete]\n\n self.all_vars = data.domain.variables\n self.varmodel_selected[:] = cont_vars[:3]\n self.varmodel_other[:] = cont_vars[3:]\n\n self.colorvar_model[:] = [\"Same color\"] + all_vars\n self.sizevar_model[:] = [\"Same size\"] + cont_vars\n self.shapevar_model[:] = [\"Same shape\"] + disc_vars\n\n if data.domain.has_discrete_class:\n self.color_index = all_vars.index(data.domain.class_var) + 1\n\n def __activate_selection(self):\n view = self.other_view\n model = self.varmodel_other\n indices = view.selectionModel().selectedRows()\n\n variables = [model.data(ind, Qt.EditRole) for ind in indices]\n\n for i in sorted((ind.row() for ind in indices), reverse=True):\n del model[i]\n\n self.varmodel_selected.extend(variables)\n\n def __deactivate_selection(self):\n view = self.active_view\n model = self.varmodel_selected\n indices = view.selectionModel().selectedRows()\n\n variables = [model.data(ind, Qt.EditRole) for ind in indices]\n\n for i in sorted((ind.row() for ind in indices), reverse=True):\n del model[i]\n\n self.varmodel_other.extend(variables)\n\n def _get_data(self, var):\n \"\"\"Return the column data for variable `var`.\"\"\"\n X, _ = self.data.get_column_view(var)\n return X.ravel()\n\n def lda(self, data):\n import sklearn.lda as skl_lda\n from Orange.preprocess import Impute\n data = Impute(data)\n lda = skl_lda.LDA(solver='eigen', n_components=2)\n lda.fit(data.X, data.Y)\n return lda.scalings_[:, :2].T\n\n def _setup_plot(self):\n self.__replot_requested = False\n self.clear_plot()\n\n variables = list(self.varmodel_selected)\n if not variables:\n return\n\n coords = [self._get_data(var) for var in variables]\n coords = numpy.vstack(coords)\n p, N = coords.shape\n assert N == len(self.data), p == len(variables)\n\n axes = linproj.defaultaxes(len(variables))\n self.warning(0)\n if self.optimization == 1:\n axes = self.lda(self.data[:, variables + [self.data.domain.class_var]])\n if self.optimization == 2 and self.projection:\n if set(self.projection.domain.attributes).issuperset(variables):\n axes = self.projection[:2, variables].X\n elif set(f.name for f in self.projection.domain.attributes).issuperset(f.name for f in variables):\n axes = self.projection[:2, [f.name for f in variables]].X\n else:\n self.warning(0, \"Projection and Data domains do not match.\")\n\n assert axes.shape == (2, p)\n\n mask = ~numpy.logical_or.reduce(numpy.isnan(coords), axis=0)\n coords = coords[:, mask]\n\n X, Y = numpy.dot(axes, coords)\n X = plotutils.normalized(X)\n Y = plotutils.normalized(Y)\n\n pen_data, brush_data = self._color_data(mask)\n size_data = self._size_data(mask)\n shape_data = self._shape_data(mask)\n\n if self.jitter_value > 0:\n value = [0, 0.01, 0.1, 0.5, 1, 2][self.jitter_value]\n\n rstate = numpy.random.RandomState(0)\n jitter_x = (rstate.random_sample(X.shape) * 2 - 1) * value / 100\n rstate = numpy.random.RandomState(1)\n jitter_y = (rstate.random_sample(Y.shape) * 2 - 1) * value / 100\n X += jitter_x\n Y += jitter_y\n\n self._item = ScatterPlotItem(\n X, Y,\n pen=pen_data,\n brush=brush_data,\n size=size_data,\n shape=shape_data,\n antialias=True,\n data=numpy.arange(len(self.data))[mask]\n )\n self._item._mask = mask\n\n self.viewbox.addItem(self._item)\n\n self._axes = []\n for i, axis in enumerate(axes.T):\n axis_item = AxisItem(line=QLineF(0, 0, axis[0], axis[1]),\n text=variables[i].name)\n axis_item.setPen(pg.mkPen((100, 100, 100)))\n self.viewbox.addItem(axis_item)\n dist = distance.euclidean((0, 0), (axis[0], axis[1]))\n self._axes.append([axis_item, dist])\n self._max_dist = numpy.max([axis[1] for axis in self._axes])\n self._on_hide_radius_change()\n\n self.viewbox.setRange(QtCore.QRectF(-1.05, -1.05, 2.1, 2.1))\n self._update_legend()\n\n def _color_data(self, mask=None):\n color_var = self.color_var()\n if color_var is not None:\n color_data = self._get_data(color_var)\n if color_var.is_continuous:\n color_data = plotutils.continuous_colors(color_data)\n else:\n color_data = plotutils.discrete_colors(\n color_data, len(color_var.values)\n )\n if mask is not None:\n color_data = color_data[mask]\n\n pen_data = numpy.array(\n [pg.mkPen((r, g, b), width=1.5)\n for r, g, b in color_data * 0.8],\n dtype=object)\n\n brush_data = numpy.array(\n [pg.mkBrush((r, g, b, self.alpha_value))\n for r, g, b in color_data],\n dtype=object)\n else:\n color = QtGui.QColor(Qt.darkGray)\n pen_data = QtGui.QPen(color, 1.5)\n pen_data.setCosmetic(True)\n color = QtGui.QColor(Qt.lightGray)\n color.setAlpha(self.alpha_value)\n brush_data = QtGui.QBrush(color)\n\n if self._subset_mask is not None:\n assert self._subset_mask.shape == (len(self.data),)\n if mask is not None:\n subset_mask = self._subset_mask[mask]\n else:\n subset_mask = self._subset_mask\n\n if isinstance(brush_data, QtGui.QBrush):\n brush_data = numpy.array([brush_data] * subset_mask.size,\n dtype=object)\n\n brush_data[~subset_mask] = QtGui.QBrush(Qt.NoBrush)\n\n if self._selection_mask is not None:\n assert self._selection_mask.shape == (len(self.data),)\n if mask is not None:\n selection_mask = self._selection_mask[mask]\n else:\n selection_mask = self._selection_mask\n\n if isinstance(pen_data, QtGui.QPen):\n pen_data = numpy.array([pen_data] * selection_mask.size,\n dtype=object)\n\n pen_data[selection_mask] = pg.mkPen((200, 200, 0, 150), width=4)\n return pen_data, brush_data\n\n def _on_color_change(self):\n if self.data is None or self._item is None:\n return\n\n pen, brush = self._color_data()\n\n if isinstance(pen, QtGui.QPen):\n # Reset the brush for all points\n self._item.data[\"pen\"] = None\n self._item.setPen(pen)\n else:\n self._item.setPen(pen[self._item._mask])\n\n if isinstance(brush, QtGui.QBrush):\n # Reset the brush for all points\n self._item.data[\"brush\"] = None\n self._item.setBrush(brush)\n else:\n self._item.setBrush(brush[self._item._mask])\n\n self._update_legend()\n\n def _shape_data(self, mask):\n shape_var = self.shape_var()\n if shape_var is None:\n shape_data = numpy.array([\"o\"] * len(self.data))\n else:\n assert shape_var.is_discrete\n max_symbol = len(ScatterPlotItem.Symbols) - 1\n shape = self._get_data(shape_var)\n shape_mask = numpy.isnan(shape)\n shape = shape % (max_symbol - 1)\n shape[shape_mask] = max_symbol\n\n symbols = numpy.array(list(ScatterPlotItem.Symbols))\n shape_data = symbols[numpy.asarray(shape, dtype=int)]\n if mask is None:\n return shape_data\n else:\n return shape_data[mask]\n\n def _on_shape_change(self):\n if self.data is None:\n return\n\n self.set_shape(self._shape_data(mask=None))\n self._update_legend()\n\n def _size_data(self, mask=None):\n size_var = self.size_var()\n if size_var is None:\n size_data = numpy.full((len(self.data),), self.point_size)\n else:\n size_data = plotutils.normalized(self._get_data(size_var))\n size_data -= numpy.nanmin(size_data)\n size_mask = numpy.isnan(size_data)\n size_data = \\\n size_data * self.point_size + OWLinearProjection.MinPointSize\n size_data[size_mask] = OWLinearProjection.MinPointSize - 2\n if mask is None:\n return size_data\n else:\n return size_data[mask]\n\n def _on_size_change(self):\n if self.data is None:\n return\n self.set_size(self._size_data(mask=None))\n\n def _update_legend(self):\n if self.__legend is None:\n self.__legend = legend = LegendItem()\n legend.setParentItem(self.viewbox)\n legend.setZValue(self.viewbox.zValue() + 10)\n legend.anchor(*self.legend_anchor)\n else:\n legend = self.__legend\n\n legend.clear()\n\n color_var, shape_var = self.color_var(), self.shape_var()\n if color_var is not None and not color_var.is_discrete:\n color_var = None\n assert shape_var is None or shape_var.is_discrete\n if color_var is None and shape_var is None:\n legend.setParentItem(None)\n legend.hide()\n return\n else:\n if legend.parentItem() is None:\n legend.setParentItem(self.viewbox)\n legend.setVisible(True)\n\n palette = self.discrete_palette\n symbols = list(ScatterPlotItem.Symbols)\n\n if shape_var is color_var:\n items = [(palette[i], symbols[i], name)\n for i, name in enumerate(color_var.values)]\n else:\n colors = shapes = []\n if color_var is not None:\n colors = [(palette[i], \"o\", name)\n for i, name in enumerate(color_var.values)]\n if shape_var is not None:\n shapes = [(QtGui.QColor(Qt.gray),\n symbols[i % (len(symbols) - 1)], name)\n for i, name in enumerate(shape_var.values)]\n items = colors + shapes\n\n for color, symbol, name in items:\n legend.addItem(\n ScatterPlotItem(pen=color, brush=color, symbol=symbol, size=10),\n escape(name)\n )\n\n def set_shape(self, shape):\n \"\"\"\n Set (update) the current point shape map.\n \"\"\"\n if self._item is not None:\n self._item.setSymbol(shape[self._item._mask])\n\n def set_size(self, size):\n \"\"\"\n Set (update) the current point size.\n \"\"\"\n if self._item is not None:\n self._item.setSize(size[self._item._mask])\n\n def _set_alpha(self, value):\n self.alpha_value = value\n self._on_color_change()\n\n def _set_size(self, value):\n self.point_size = value\n self._on_size_change()\n\n def _set_hide_radius(self, value):\n self.hide_radius = value\n self._on_hide_radius_change()\n\n def _on_hide_radius_change(self):\n if not self.opt_radio.buttons[1].isChecked():\n return\n for axis_item, dist in self._axes:\n axis_item.setVisible(dist >=\n self.hide_radius * self._max_dist / 100)\n\n def _selection_finish(self, path):\n self.select(path)\n\n def select(self, selectionshape):\n item = self._item\n if item is None:\n return\n\n indices = [spot.data()\n for spot in item.points()\n if selectionshape.contains(spot.pos())]\n\n self.select_indices(indices, QApplication.keyboardModifiers())\n\n def select_indices(self, indices, modifiers=Qt.NoModifier):\n if self.data is None:\n return\n\n if self._selection_mask is None or \\\n not modifiers & (Qt.ControlModifier | Qt.ShiftModifier |\n Qt.AltModifier):\n self._selection_mask = numpy.zeros(len(self.data), dtype=bool)\n\n if modifiers & Qt.ControlModifier:\n self._selection_mask[indices] = False\n elif modifiers & Qt.AltModifier:\n self._selection_mask[indices] = ~self._selection_mask[indices]\n else:\n self._selection_mask[indices] = True\n\n self._on_color_change()\n self.commit()\n\n def commit(self):\n subset = None\n if self.data is not None and self._selection_mask is not None:\n indices = numpy.flatnonzero(self._selection_mask)\n if len(indices) > 0:\n subset = self.data[indices]\n\n self.send(\"Selected Data\", subset)\n\n\nclass PlotTool(QObject):\n \"\"\"\n An abstract tool operating on a pg.ViewBox.\n\n Subclasses of `PlotTool` implement various actions responding to\n user input events. For instance `PlotZoomTool` when active allows\n the user to select/draw a rectangular region on a plot in which to\n zoom.\n\n The tool works by installing itself as an `eventFilter` on to the\n `pg.ViewBox` instance and dispatching events to the appropriate\n event handlers `mousePressEvent`, ...\n\n When subclassing note that the event handlers (`mousePressEvent`, ...)\n are actually event filters and need to return a boolean value\n indicating if the event was handled (filtered) and should not propagate\n further to the view box.\n\n See Also\n --------\n PyQt4.QtCore.QObject.eventFilter\n\n \"\"\"\n def __init__(self, parent=None, **kwargs):\n super().__init__(parent, **kwargs)\n self.__viewbox = None\n\n def setViewBox(self, viewbox):\n \"\"\"\n Set the view box to operate on.\n\n Call ``setViewBox(None)`` to remove the tool from the current\n view box. If an existing view box is already set it is first\n removed.\n\n .. note::\n The PlotTool will install itself as an event filter on the\n view box.\n\n Parameters\n ----------\n viewbox : pg.ViewBox or None\n\n \"\"\"\n if self.__viewbox is viewbox:\n return\n if self.__viewbox is not None:\n self.__viewbox.removeEventFilter(self)\n self.__viewbox.destroyed.disconnect(self.__viewdestroyed)\n\n self.__viewbox = viewbox\n\n if self.__viewbox is not None:\n self.__viewbox.installEventFilter(self)\n self.__viewbox.destroyed.connect(self.__viewdestroyed)\n\n def viewBox(self):\n \"\"\"\n Return the view box.\n\n Returns\n -------\n viewbox : pg.ViewBox\n \"\"\"\n return self.__viewbox\n\n @Slot(QObject)\n def __viewdestroyed(self, obj):\n self.__viewbox = None\n\n def mousePressEvent(self, event):\n \"\"\"\n Handle a mouse press event.\n\n Parameters\n ----------\n event : QGraphicsSceneMouseEvent\n The event.\n\n Returns\n -------\n status : bool\n True if the event was handled (and should not\n propagate further to the view box) and False otherwise.\n \"\"\"\n return False\n\n def mouseMoveEvent(self, event):\n \"\"\"\n Handle a mouse move event.\n\n Parameters\n ----------\n event : QGraphicsSceneMouseEvent\n The event\n\n Returns\n -------\n status : bool\n True if the event was handled (and should not\n propagate further to the view box) and False otherwise.\n \"\"\"\n return False\n\n def mouseReleaseEvent(self, event):\n \"\"\"\n Handle a mouse release event.\n\n Parameters\n ----------\n event : QGraphicsSceneMouseEvent\n The event\n\n Returns\n -------\n status : bool\n True if the event was handled (and should not\n propagate further to the view box) and False otherwise.\n \"\"\"\n return False\n\n def mouseDoubleClickEvent(self, event):\n \"\"\"\n Handle a mouse double click event.\n\n Parameters\n ----------\n event : QGraphicsSceneMouseEvent\n The event.\n\n Returns\n -------\n status : bool\n True if the event was handled (and should not\n propagate further to the view box) and False otherwise.\n \"\"\"\n return False\n\n def gestureEvent(self, event):\n \"\"\"\n Handle a gesture event.\n\n Parameters\n ----------\n event : QGraphicsSceneGestureEvent\n The event.\n\n Returns\n -------\n status : bool\n True if the event was handled (and should not\n propagate further to the view box) and False otherwise.\n \"\"\"\n return False\n\n def eventFilter(self, obj, event):\n \"\"\"\n Reimplemented from `QObject.eventFilter`.\n \"\"\"\n if obj is self.__viewbox:\n if event.type() == QEvent.GraphicsSceneMousePress:\n return self.mousePressEvent(event)\n elif event.type() == QEvent.GraphicsSceneMouseMove:\n return self.mouseMoveEvent(event)\n elif event.type() == QEvent.GraphicsSceneMouseRelease:\n return self.mouseReleaseEvent(event)\n elif event.type() == QEvent.GraphicsSceneMouseDoubleClick:\n return self.mouseDoubleClickEvent(event)\n elif event.type() == QEvent.Gesture:\n return self.gestureEvent(event)\n return super().eventFilter(obj, event)\n\n\nclass PlotSelectionTool(PlotTool):\n \"\"\"\n A tool for selecting a region on a plot.\n\n \"\"\"\n #: Selection modes\n Rect, Lasso = 1, 2\n\n #: Selection was started by the user.\n selectionStarted = Signal(QPainterPath)\n #: The current selection has been updated\n selectionUpdated = Signal(QPainterPath)\n #: The selection has finished (user has released the mouse button)\n selectionFinished = Signal(QPainterPath)\n\n def __init__(self, parent=None, selectionMode=Rect, **kwargs):\n super().__init__(parent, **kwargs)\n self.__mode = selectionMode\n self.__path = None\n self.__item = None\n\n def setSelectionMode(self, mode):\n \"\"\"\n Set the selection mode (rectangular or lasso selection).\n\n Parameters\n ----------\n mode : int\n PlotSelectionTool.Rect or PlotSelectionTool.Lasso\n\n \"\"\"\n assert mode in {PlotSelectionTool.Rect, PlotSelectionTool.Lasso}\n if self.__mode != mode:\n if self.__path is not None:\n self.selectionFinished.emit()\n self.__mode = mode\n self.__path = None\n\n def selectionMode(self):\n \"\"\"\n Return the current selection mode.\n \"\"\"\n return self.__mode\n\n def selectionShape(self):\n \"\"\"\n Return the current selection shape.\n\n This is the area selected/drawn by the user.\n\n Returns\n -------\n shape : QPainterPath\n The selection shape in view coordinates.\n \"\"\"\n if self.__path is not None:\n shape = QPainterPath(self.__path)\n shape.closeSubpath()\n else:\n shape = QPainterPath()\n viewbox = self.viewBox()\n\n if viewbox is None:\n return QPainterPath()\n\n return viewbox.childGroup.mapFromParent(shape)\n\n def mousePressEvent(self, event):\n if event.button() == Qt.LeftButton:\n pos = event.pos()\n if self.__mode == PlotSelectionTool.Rect:\n rect = QRectF(pos, pos)\n self.__path = QPainterPath()\n self.__path.addRect(rect)\n else:\n self.__path = QPainterPath()\n self.__path.moveTo(event.pos())\n self.selectionStarted.emit(self.selectionShape())\n self.__updategraphics()\n event.accept()\n return True\n else:\n return False\n\n def mouseMoveEvent(self, event):\n if event.buttons() & Qt.LeftButton:\n if self.__mode == PlotSelectionTool.Rect:\n rect = QRectF(event.buttonDownPos(Qt.LeftButton), event.pos())\n self.__path = QPainterPath()\n self.__path.addRect(rect)\n else:\n self.__path.lineTo(event.pos())\n self.selectionUpdated.emit(self.selectionShape())\n self.__updategraphics()\n event.accept()\n return True\n else:\n return False\n\n def mouseReleaseEvent(self, event):\n if event.button() == Qt.LeftButton:\n if self.__mode == PlotSelectionTool.Rect:\n rect = QRectF(event.buttonDownPos(Qt.LeftButton), event.pos())\n self.__path = QPainterPath()\n self.__path.addRect(rect)\n else:\n self.__path.lineTo(event.pos())\n self.selectionFinished.emit(self.selectionShape())\n self.__path = QPainterPath()\n self.__updategraphics()\n event.accept()\n return True\n else:\n return False\n\n def __updategraphics(self):\n viewbox = self.viewBox()\n if viewbox is None:\n return\n\n if self.__path.isEmpty():\n if self.__item is not None:\n self.__item.setParentItem(None)\n viewbox.removeItem(self.__item)\n if self.__item.scene():\n self.__item.scene().removeItem(self.__item)\n self.__item = None\n else:\n if self.__item is None:\n item = QtGui.QGraphicsPathItem()\n color = QtGui.QColor(Qt.yellow)\n item.setPen(QtGui.QPen(color, 0))\n color.setAlpha(50)\n item.setBrush(QtGui.QBrush(color))\n self.__item = item\n viewbox.addItem(item)\n\n self.__item.setPath(self.selectionShape())\n\n\nclass PlotZoomTool(PlotTool):\n \"\"\"\n A zoom tool.\n\n Allows the user to draw a rectangular region to zoom in.\n \"\"\"\n\n zoomStarted = Signal(QRectF)\n zoomUpdated = Signal(QRectF)\n zoomFinished = Signal(QRectF)\n\n def __init__(self, parent=None, autoZoom=True, **kwargs):\n super().__init__(parent, **kwargs)\n self.__zoomrect = QRectF()\n self.__zoomitem = None\n self.__autozoom = autoZoom\n\n def zoomRect(self):\n \"\"\"\n Return the current drawn rectangle (region of interest)\n\n Returns\n -------\n zoomrect : QRectF\n \"\"\"\n view = self.viewBox()\n if view is None:\n return QRectF()\n return view.childGroup.mapRectFromParent(self.__zoomrect)\n\n def mousePressEvent(self, event):\n if event.button() == Qt.LeftButton:\n self.__zoomrect = QRectF(event.pos(), event.pos())\n self.zoomStarted.emit(self.zoomRect())\n self.__updategraphics()\n event.accept()\n return True\n elif event.button() == Qt.RightButton:\n event.accept()\n return True\n else:\n return False\n\n def mouseMoveEvent(self, event):\n if event.buttons() & Qt.LeftButton:\n self.__zoomrect = QRectF(\n event.buttonDownPos(Qt.LeftButton), event.pos()).normalized()\n self.zoomUpdated.emit(self.zoomRect())\n self.__updategraphics()\n event.accept()\n return True\n elif event.buttons() & Qt.RightButton:\n event.accept()\n return True\n else:\n return False\n\n def mouseReleaseEvent(self, event):\n if event.button() == Qt.LeftButton:\n self.__zoomrect = QRectF(\n event.buttonDownPos(Qt.LeftButton), event.pos()).normalized()\n\n if self.__autozoom:\n PlotZoomTool.pushZoomRect(self.viewBox(), self.zoomRect())\n\n self.zoomFinished.emit(self.zoomRect())\n self.__zoomrect = QRectF()\n self.__updategraphics()\n event.accept()\n return True\n elif event.button() == Qt.RightButton:\n PlotZoomTool.popZoomStack(self.viewBox())\n event.accept()\n return True\n else:\n return False\n\n def __updategraphics(self):\n viewbox = self.viewBox()\n if viewbox is None:\n return\n if not self.__zoomrect.isValid():\n if self.__zoomitem is not None:\n self.__zoomitem.setParentItem(None)\n viewbox.removeItem(self.__zoomitem)\n if self.__zoomitem.scene() is not None:\n self.__zoomitem.scene().removeItem(self.__zoomitem)\n self.__zoomitem = None\n else:\n if self.__zoomitem is None:\n self.__zoomitem = QtGui.QGraphicsRectItem()\n color = QtGui.QColor(Qt.yellow)\n self.__zoomitem.setPen(QtGui.QPen(color, 0))\n color.setAlpha(50)\n self.__zoomitem.setBrush(QtGui.QBrush(color))\n viewbox.addItem(self.__zoomitem)\n\n self.__zoomitem.setRect(self.zoomRect())\n\n @staticmethod\n def pushZoomRect(viewbox, rect):\n viewbox.showAxRect(rect)\n viewbox.axHistoryPointer += 1\n viewbox.axHistory[viewbox.axHistoryPointer:] = [rect]\n\n @staticmethod\n def popZoomStack(viewbox):\n if viewbox.axHistoryPointer == 0:\n viewbox.autoRange()\n viewbox.axHistory = []\n viewbox.axHistoryPointer = -1\n else:\n viewbox.scaleHistory(-1)\n\n\nclass PlotPanTool(PlotTool):\n \"\"\"\n Pan/translate tool.\n \"\"\"\n panStarted = Signal()\n translated = Signal(QPointF)\n panFinished = Signal()\n\n def __init__(self, parent=None, autoPan=True, **kwargs):\n super().__init__(parent, **kwargs)\n self.__autopan = autoPan\n\n def mousePressEvent(self, event):\n if event.button() == Qt.LeftButton:\n self.panStarted.emit()\n event.accept()\n return True\n else:\n return False\n\n def mouseMoveEvent(self, event):\n if event.buttons() & Qt.LeftButton:\n viewbox = self.viewBox()\n delta = (viewbox.mapToView(event.pos()) -\n viewbox.mapToView(event.lastPos()))\n if self.__autopan:\n viewbox.translateBy(-delta / 2)\n self.translated.emit(-delta / 2)\n event.accept()\n return True\n else:\n return False\n\n def mouseReleaseEvent(self, event):\n if event.button() == Qt.LeftButton:\n self.panFinished.emit()\n event.accept()\n return True\n else:\n return False\n\n\nclass PlotPinchZoomTool(PlotTool):\n \"\"\"\n A tool implementing a \"Pinch to zoom\".\n \"\"\"\n\n def gestureEvent(self, event):\n gesture = event.gesture(Qt.PinchGesture)\n if gesture.state() == Qt.GestureStarted:\n event.accept(gesture)\n return True\n elif gesture.changeFlags() & QtGui.QPinchGesture.ScaleFactorChanged:\n viewbox = self.viewBox()\n center = viewbox.mapSceneToView(gesture.centerPoint())\n scale_prev = gesture.lastScaleFactor()\n scale = gesture.scaleFactor()\n if scale_prev != 0:\n scale = scale / scale_prev\n if scale > 0:\n viewbox.scaleBy((1 / scale, 1 / scale), center)\n event.accept()\n return True\n elif gesture.state() == Qt.GestureFinished:\n viewbox = self.viewBox()\n PlotZoomTool.pushZoomRect(viewbox, viewbox.viewRect())\n event.accept()\n return True\n else:\n return False\n\n\nclass plotutils:\n @ staticmethod\n def continuous_colors(data, palette=None):\n if palette is None:\n palette = colorpalette.ContinuousPaletteGenerator(\n QtGui.QColor(220, 220, 220),\n QtGui.QColor(0, 0, 0),\n False\n )\n amin, amax = numpy.nanmin(data), numpy.nanmax(data)\n span = amax - amin\n data = (data - amin) / (span or 1)\n\n mask = numpy.isnan(data)\n # Unknown values as gray\n # TODO: This should already be a part of palette\n colors = numpy.empty((len(data), 3))\n colors[mask] = (128, 128, 128)\n colors[~mask] = [palette.getRGB(v) for v in data[~mask]]\n return colors\n\n @staticmethod\n def discrete_colors(data, nvalues, palette=None):\n if palette is None:\n palette = colorpalette.ColorPaletteGenerator(nvalues)\n\n color_index = palette.getRGB(numpy.arange(nvalues + 1))\n # Unknown values as gray\n # TODO: This should already be a part of palette\n color_index[nvalues] = (128, 128, 128)\n\n data = numpy.where(numpy.isnan(data), nvalues, data)\n data = data.astype(int)\n return color_index[data]\n\n @staticmethod\n def normalized(a):\n amin, amax = numpy.nanmin(a), numpy.nanmax(a)\n span = amax - amin\n mean = numpy.nanmean(a)\n return (a - mean) / (span or 1)\n\n\nclass linproj:\n @staticmethod\n def defaultaxes(naxes):\n \"\"\"\n Return the default axes for linear projection.\n \"\"\"\n assert naxes > 0\n\n if naxes == 1:\n axes_angle = [0]\n elif naxes == 2:\n axes_angle = [0, numpy.pi / 2]\n else:\n axes_angle = numpy.linspace(0, 2 * numpy.pi, naxes, endpoint=False)\n\n axes = numpy.vstack(\n (numpy.cos(axes_angle),\n numpy.sin(axes_angle))\n )\n return axes\n\n @staticmethod\n def project(axes, X):\n return numpy.dot(axes, X)\n\n\ndef test_main(argv=None):\n import sys\n import sip\n\n argv = sys.argv[1:] if argv is None else argv\n if argv:\n filename = argv[0]\n else:\n filename = \"iris\"\n\n data = Orange.data.Table(filename)\n\n app = QApplication([])\n w = OWLinearProjection()\n w.set_data(data)\n w.set_subset_data(data[::10])\n w.handleNewSignals()\n w.show()\n w.raise_()\n r = app.exec()\n w.set_data(None)\n w.saveSettings()\n sip.delete(w)\n del w\n return r\n\n\nif __name__ == \"__main__\":\n import sys\n sys.exit(test_main())\n","sub_path":"orangecontrib/prototypes/widgets/owlinearprojection.py","file_name":"owlinearprojection.py","file_ext":"py","file_size_in_byte":51928,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"599448941","text":"def get_prime_numbers (n):\n not_a_prime=[]\n prime = []\n if type(n)!=int:\n raise TypeError\n for j in range(2,n):\n for i in range(2,j):\n if j % i == 0:\n not_a_prime.append(j)\n for i in range(2,n):\n if i not in not_a_prime:\n prime.append(i)\n return prime\nprint (get_prime_numbers(10))","sub_path":"prime_number.py","file_name":"prime_number.py","file_ext":"py","file_size_in_byte":357,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"35406881","text":"# coding=utf-8\r\nimport tensorflow as tf\r\nimport data.cnews_loader\r\nimport funcLib\r\nfrom sys import argv\r\n\r\n'''\r\nnum1 = argv[1]\r\nnum2 = argv[2]\r\nsum = int(num1) + int(num2)\r\nprint(sum)\r\n'''\r\ndef perdictSentences(sentenceList):\r\n wordsList, word2id = data.cnews_loader.read_vocab(\"./data/cnews/cnews.vocab.txt\")\r\n graph = tf.Graph()\r\n\r\n with tf.Session(graph=graph) as sess:\r\n # 若不希望重复定义计算图上的运算,可通过此方法直接将之前的图加载出来\r\n saver = tf.train.import_meta_graph(\"checkpoints/sentiment.ckpt.meta\")\r\n # 此方法从保存的文件中读取已经训练过的神经网络参数\r\n saver.restore(sess, tf.train.latest_checkpoint('checkpoints'))\r\n # 通过 Tensor 的名称获得对应的张量\r\n\r\n inputs_ = tf.get_default_graph().get_tensor_by_name(\"inputs:0\")\r\n labels_ = tf.get_default_graph().get_tensor_by_name(\"labels:0\")\r\n keep_prob = tf.get_default_graph().get_tensor_by_name(\"keep_prob:0\")\r\n accuracy = tf.get_default_graph().get_tensor_by_name(\"accuracy:0\")\r\n correct_pred = tf.get_default_graph().get_tensor_by_name(\"correct_pred:0\")\r\n predict_output = tf.get_default_graph().get_tensor_by_name(\"fully_connected/Sigmoid:0\")\r\n prediction_index = tf.get_default_graph().get_tensor_by_name(\"prediction_index:0\")\r\n\r\n\r\n sentenceList = funcLib.processEnglish(sentenceList)\r\n sentenceList = funcLib.transformVec2Id(sentenceList, word2id)\r\n feed = {inputs_: sentenceList,\r\n keep_prob: 1}\r\n predict_index = sess.run(predict_output, feed_dict=feed)\r\n\r\n ResultLabelList = []\r\n # print(\"Prediction output : \" + str(pred_output))\r\n for singleIndex in predict_index:\r\n if funcLib.compare(singleIndex[0],singleIndex[1],singleIndex[2],singleIndex[3]) :\r\n ResultLabelList.append((\"P\",singleIndex[0]))\r\n elif funcLib.compare(singleIndex[1],singleIndex[0],singleIndex[2],singleIndex[3]):\r\n ResultLabelList.append((\"I\",singleIndex[1]))\r\n elif funcLib.compare(singleIndex[2],singleIndex[0],singleIndex[1],singleIndex[3]):\r\n ResultLabelList.append((\"O\",singleIndex[2]))\r\n else:\r\n ResultLabelList.append((\"U\",singleIndex[3]))\r\n return ResultLabelList","sub_path":"predict.py","file_name":"predict.py","file_ext":"py","file_size_in_byte":2348,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"211097364","text":"'''\n4 SUM \n- Approach 1 (iterative)- does not clear all the cases 240/282 \n- Approach 2 (recurssion)\n\n'''\nclass Solution:\n def fourSum(self, nums, target):\n \"\"\"\n :type nums: List[int]\n :type target: int\n :rtype: List[List[int]]\n \"\"\"\n res=[]\n if len(nums)<4:return []\n if len(list(set(nums)))==1 and sum(nums)==target:\n res.append([nums[0]]*4)\n return res\n nums=sorted(nums)\n for j in range(len(nums)-3):\n if j>0 and nums[j]==nums[j-1]:\n continue\n for i in range(j+1,len(nums)-2):\n if i>1 and nums[i]==nums[i-1]:\n continue\n l,r=i+1,len(nums)-1\n while ltarget:\n r-=1\n else:\n res.append([nums[i], nums[l], nums[r], nums[j]])\n if nums[l]==nums[l+1]:\n l+=1\n if nums[r]==nums[r-1]:\n r-=1\n l+=1\n r-=1\n return res\n\n def fourSum2(self, nums, target):\n \"\"\"\n :type nums: List[int]\n :type target: int\n :rtype: List[List[int]]\n \"\"\"\n def findnSums(nums, target, N, curr):\n if len(nums)target:\n r-=1\n \n else:\n for j in range(len(nums)-N+1):\n if j == 0 or nums[j-1] != nums[j]:\n findnSums(nums[j+1:], target-nums[j], N-1, curr+[nums[j]])\n\n res=[]\n nums=sorted(nums)\n findnSums(nums, target, 4, [])\n return [val for val in res if len(val)==4]\nobj = Solution()\nprint(obj.fourSum2([0,1,5,0,1,5,5,-4],11))\n \n ","sub_path":"Dp_Recurssion/4sum.py","file_name":"4sum.py","file_ext":"py","file_size_in_byte":2638,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"264999005","text":"#!/usr/bin/env python3\n\nimport string\nimport subprocess\nimport re \nimport os\nimport sys\nimport ninja_syntax\nimport yaml\n\nexports = {}\n\n# Legacy regex to match variables in makefiles and dragon bash configs\ndragon_match = '(.*)=\"?(.*)\"\"?#?'\nmake_match = '(.*)=(.*)#?'\n\n# Regex for functions in new DragonMake kinda-yaml syntax\ndm_wildcard = '\\$wildcard\\(\"(.*)\",.*\"(.*)\"\\)'\ndm_eval = '\\$eval\\(\"(.*)\"\\)'\n\ndragonvars = {}\ndragonvars['pdirname'] = '.dragon'\ndragonvars['builddir'] = '$pdirname/build'\ndragonvars['objdir'] = '$pdirname/obj'\ndragonvars['signdir'] = '$pdirname/sign'\n\n# These are variables set as default per project type.\n# They sometimes get modified by uvars, when the relevant uvar is specified\nbvars = {'all':{},'tweak':{}, 'bundle':{}, 'library':{}, 'cli':{}, 'raw':{}}\n\nbvars['all']['libs'] = ['objc', 'c++']\nbvars['all']['lopts'] = ''\nbvars['all']['frameworks'] = []\n\nbvars['tweak']['location'] = '/Library/MobileSubstrate/DynamicLibraries/'\nbvars['tweak']['target'] = '$pdirname/_$location$name.dylib'\nbvars['tweak']['libs'] = ['substrate']\nbvars['tweak']['lopts'] = '-dynamiclib -ggdb -lsystem.b -Xlinker -segalign -Xlinker 4000'\nbvars['tweak']['frameworks'] = ['CoreFoundation', 'Foundation', 'UIKit', 'CoreGraphics', 'QuartzCore', 'CoreImage', 'AudioToolbox']\nbvars['tweak']['stage2'] = 'cp $name.plist .dragon/_/Library/MobileSubstrate/DynamicLibraries/$name.plist'\n\n# This is the default location for a pref bundle, which we can assume is what the user wants by default\nbvars['bundle']['location'] = '/Library/PreferenceBundles/$name.bundle/'\nbvars['bundle']['target'] = '$pdirname/_$location$name'\nbvars['bundle']['libs'] = []\nbvars['bundle']['lopts']= '-dynamiclib -ggdb -lsystem.b -Xlinker -segalign -Xlinker 4000'\nbvars['bundle']['frameworks'] = ['CoreFoundation', 'Foundation', 'UIKit', 'CoreGraphics', 'QuartzCore', 'CoreImage', 'AudioToolbox']\nbvars['bundle']['stage2'] = ''\n\nbvars['library']['location'] = '/usr/lib/'\nbvars['library']['target'] = '$pdirname/_$location$name.dylib'\nbvars['library']['libs'] = []\nbvars['library']['lopts']= '-dynamiclib -ggdb -lsystem.b -Xlinker -segalign -Xlinker 4000'\nbvars['library']['frameworks'] = []\nbvars['library']['stage2'] = ''\n\nbvars['cli']['location'] = '/usr/bin'\nbvars['cli']['target'] = '$pdirname/_$location$name'\nbvars['cli']['libs'] = []\nbvars['cli']['lopts'] = ''\nbvars['cli']['frameworks'] = []\nbvars['cli']['stage2'] = ''\n\n# User modifiable variables\n\ndef read_dragon_configuration():\n f = open(\"DragonMake\", 'r')\n config = yaml.safe_load(f)\n project_dirs = ''\n\n for i in config:\n if i == 'package_name':\n exports['package_name'] = config[i]\n continue \n elif i == 'install_command':\n exports['install_command'] = config[i]\n continue\n elif i == 'exports': \n exports.update(config[i])\n\n package_config = {'name':i, 'dir':'.'}\n package_config.update(config[i])\n project_config = process_package(package_config)\n\n f = open(f\"{project_config['dir']}/build.ninja\", 'w+')\n ninja = ninja_syntax.Writer(f)\n create_buildfile(ninja, project_config['type'], project_config)\n f.close()\n project_dirs = project_dirs + ' ' + project_config['dir']\n \n exports['project_dirs'] = project_dirs\n\n\ndef process_package(package_config):\n uvars = {}\n\n uvars['name'] = ''\n uvars['type'] = ''\n\n uvars['prelogos_files'] = []\n uvars['logos_files'] = []\n uvars['files'] = []\n uvars['plists'] = []\n\n uvars['dragondir'] = '$$DRAGONBUILD'\n uvars['targetios'] = '10.0'\n uvars['archs'] = ['armv7', 'arm64', 'arm64e']\n uvars['sysroot'] = '$dragondir/sdks/iPhoneOS.sdk'\n uvars['cc'] = 'clang++'\n uvars['ld'] = 'clang++'\n uvars['ldid'] = 'ldid'\n uvars['dsym'] = 'dsymutil'\n uvars['plutil'] = 'plutil'\n uvars['logos']= '$dragondir/bin/logos.pl'\n uvars['stage'] = 'true;'\n uvars['arc'] = '-fobjc-arc'\n uvars['targ'] = '-DTARGET_IPHONE=1'\n\n uvars['warnings'] = '-Wall' #'-W' + this\n uvars['optim'] = '0'\n uvars['debug'] = '-fcolor-diagnostics'\n\n uvars['libs'] = []\n uvars['frameworks'] = []\n\n uvars['cflags'] = ''\n uvars['ldflags'] = ''\n uvars['ldidflags']= '-S'\n\n uvars['installLocation'] = ''\n uvars['resourceDir'] = 'Resources'\n uvars['nocomp'] = 0\n\n uvars['frameworkSearchDirs'] = ['$sysroot/System/Library/Frameworks', '$sysroot/System/Library/PrivateFrameworks', '$dragondir/frameworks']\n uvars['additionalFrameworkSearchDirs'] = []\n\n uvars['librarySearchDirs'] = ['$dragondir/lib', '.']\n uvars['additionalLibrarySearchDirs'] = []\n\n uvars['cinclude'] = '-I$dragondir/include -I$dragondir/vendor/include -I$dragondir/include/_fallback -I$DRAGONBUILD/headers/ -I$pwd'\n\n uvars.update(package_config)\n\n return uvars\n\n\ndef create_buildfile(ninja, type, uvars):\n ninja.variable('name', uvars['name'])\n ninja.variable('lowername', uvars['name'].lower())\n ninja.newline()\n ninja.newline()\n\n ninja.variable('pdirname', dragonvars['pdirname'])\n ninja.newline()\n\n ninja.variable('location', bvars[type]['location'].replace(' ', '$ ') if uvars['installLocation'] == '' else uvars['installLocation'].replace(' ', '$ '))\n ninja.variable('resourcedir', uvars['resourceDir'].replace(' ', '$ '))\n ninja.variable('target', bvars[type]['target'])\n ninja.newline()\n ninja.variable('stage2', bvars[type]['stage2'])\n ninja.newline()\n\n ninja.variable('builddir', dragonvars['builddir'])\n ninja.variable('objdir', dragonvars['objdir'])\n ninja.variable('signdir', dragonvars['signdir'])\n ninja.variable('signtarget', '$signdir/$target.unsigned')\n ninja.variable('symtarget', '$signdir/$target.unsym')\n ninja.newline()\n\n ninja.variable('dragondir', uvars['dragondir'])\n ninja.variable('pwd', '.')\n ninja.variable('sysroot', uvars['sysroot'])\n ninja.newline()\n\n ninja.variable('fwSearch', '-F' + ' -F'.join(uvars['frameworkSearchDirs'] + uvars['additionalFrameworkSearchDirs']))\n ninja.variable('libSearch', '-L' + ' -L'.join(uvars['librarySearchDirs'] + uvars['additionalLibrarySearchDirs']))\n ninja.newline()\n\n ninja.variable('cc', uvars['cc'])\n ninja.variable('ld', uvars['ld'])\n ninja.variable('ldid', uvars['ldid'])\n ninja.variable('dsym', uvars['dsym'])\n ninja.variable('logos', uvars['logos'])\n ninja.variable('plutil', uvars['plutil'])\n ninja.variable('stage', uvars['stage'] if isinstance(uvars['stage'], str) else '; '.join(uvars['stage']))\n ninja.newline()\n\n ninja.variable('targetios', uvars['targetios'])\n ninja.newline()\n fws = uvars['frameworks'] + bvars[type]['frameworks'] + bvars['all']['frameworks']\n if len(fws) > 0:\n ninja.variable('frameworks','-framework ' + ' -framework '.join(fws))\n\n ninja.newline()\n ninja.variable('libs', '-l' + ' -l'.join(uvars['libs'] + bvars[type]['libs'] + bvars['all']['libs']))\n ninja.newline()\n ninja.variable('arcs', '-arch ' + ' -arch '.join(uvars['archs']))\n ninja.newline()\n\n ninja.variable('arc', uvars['arc'])\n ninja.variable('btarg', uvars['targ'])\n ninja.variable('warnings', uvars['warnings'])\n ninja.variable('optim', '-O' + uvars['optim'])\n ninja.variable('debug', uvars['debug'])\n ninja.newline()\n\n ninja.variable('cinclude', uvars['cinclude'])\n ninja.newline()\n\n ninja.variable('usrCflags', uvars['cflags'])\n ninja.variable('usrLDflags', uvars['ldflags'])\n ninja.variable('usrLDIDFlags', uvars['ldidflags'])\n ninja.newline()\n\n ninja.variable('lopt', bvars['all']['lopts'] + bvars[type]['lopts'])\n ninja.newline()\n\n cflags = '$cinclude $arcs $arc $fwSearch -miphoneos-version-min=$targetios -isysroot $sysroot $btarg $warnings $optim $debug $usrCflags'\n ninja.variable('cflags', cflags)\n ninja.newline()\n\n lflags = '$cflags $frameworks $libs $lopt $libSearch $usrLDflags'\n ninja.variable('lflags', lflags)\n ninja.newline()\n\n ninja.variable('ldflags', '$usrLDFlags')\n ninja.newline()\n\n # rules\n\n ninja.pool('solo', '1')\n ninja.newline()\n\n ninja.rule('prelogos', description=\"Processing $in with Pre/Logos\",command=\"cat $in | python3 $$DRAGONBUILD/bin/prelogos.py > $out\")\n ninja.newline()\n ninja.rule('logos', description=\"Processing $in with Logos\",command=\"$logos $in > $out\")\n ninja.newline()\n ninja.rule('compile', description=\"Compiling $in\", command=\"$cc $cflags -c $in -o $out\")\n ninja.newline()\n ninja.rule('link', description=\"Linking $name\", command=\"$ld $lflags -o $out $in\")\n ninja.newline()\n ninja.rule('bundle', description=\"Copying Bundle Resources\", command=\"mkdir -p \\\".dragon/_$location/\\\" && cp -r \\\"$resourcedir/\\\" \\\".dragon/_$location\\\" && cp $in $out && find \\\".dragon/_$location\\\" -type f -name \\\"*.plist\\\" -exec $plutil -convert binary1 \\\"{}\\\" \\;\", pool='solo')\n ninja.newline()\n ninja.rule('plist', description=\"Converting $in\", command=\"$plutil -convert binary1 $in -o $out\")\n ninja.newline()\n ninja.rule('debug', description=\"Generating Debug Symbols for $name\", command=\"$dsym \\\"$in\\\" 2&> /dev/null; mv $in $out\")\n ninja.newline()\n ninja.rule('sign', description=\"Signing $name\", command=\"$ldid $usrLDIDFlags $in && mv $in $target\")\n ninja.newline()\n ninja.rule('stage', description=\"Running Stage for $name\", command=\"$stage $stage2\")\n ninja.newline()\n\n outputs = []\n targets = ['$target'] if uvars['nocomp'] == 0 else []\n prelogos = uvars['prelogos_files']\n logos = uvars['logos_files']\n files = uvars['files']\n plists = uvars['plists']\n if uvars['nocomp'] == 0:\n for i in prelogos:\n wc = re.match(dm_wildcard, i)\n ev = re.match(dm_eval, i)\n if wc:\n out = subprocess.check_output(f'ls {wc.group(1)}{wc.group(2)} | xargs', shell=True).decode(sys.stdout.encoding).strip()\n elif ev:\n out = subprocess.check_output(f'{ev.group(1)} | xargs', shell=True).decode(sys.stdout.encoding).strip()\n else:\n if uvars['dir'] != '.':\n i = '../' + i\n continue \n\n if uvars['dir'] != '.':\n prelogos += ' ../'.join(('../'+str(out)).split(' ')).split(' ')\n else:\n prelogos += str(out).split(' ')\n prelogos.remove(i)\n for i in logos:\n wc = re.match(dm_wildcard, i)\n ev = re.match(dm_eval, i)\n if wc:\n out = subprocess.check_output(f'ls {wc.group(1)}{wc.group(2)} | xargs', shell=True).decode(sys.stdout.encoding).strip()\n elif ev:\n out = subprocess.check_output(f'{ev.group(1)} | xargs', shell=True).decode(sys.stdout.encoding).strip()\n else:\n if uvars['dir'] != '.':\n i = '../' + i\n continue \n\n if uvars['dir'] != '.':\n logos += ' ../'.join(('../'+str(out)).split(' ')).split(' ')\n else:\n logos += str(out).split(' ')\n logos.remove(i)\n \n for i in files:\n wc = re.match(dm_wildcard, i)\n ev = re.match(dm_eval, i)\n if wc:\n out = subprocess.check_output(f'ls {wc.group(1)}{wc.group(2)} | xargs', shell=True).decode(sys.stdout.encoding).strip()\n elif ev:\n out = subprocess.check_output(f'{ev.group(1)} | xargs', shell=True).decode(sys.stdout.encoding).strip()\n else:\n if uvars['dir'] != '.':\n i = '../' + i\n continue \n\n if uvars['dir'] != '.':\n files += ' ../'.join(('../'+str(out)).split(' ')).split(' ')\n else:\n files += str(out).split(' ')\n files.remove(i)\n\n for i in plists:\n wc = re.match(dm_wildcard, i)\n ev = re.match(dm_eval, i)\n if wc:\n out = subprocess.check_output(f'ls {wc.group(1)}{wc.group(2)} | xargs', shell=True).decode(sys.stdout.encoding).strip()\n elif ev:\n out = subprocess.check_output(f'{ev.group(1)} | xargs', shell=True).decode(sys.stdout.encoding).strip()\n else:\n if uvars['dir'] != '.':\n i = '../' + i\n continue \n\n if uvars['dir'] != '.':\n plists += ' ../'.join(('../'+str(out)).split(' ')).split(' ')\n else:\n plists += str(out).split(' ')\n plists.remove(i)\n\n for f in prelogos:\n ninja.build(f'$builddir/{os.path.split(f)[1]}.xm', 'prelogos', f)\n logos.append(f'$builddir/{os.path.split(f)[1]}.xm')\n ninja.newline()\n\n for f in logos:\n ninja.build(f'$builddir/{os.path.split(f)[1]}.mm', 'logos', f)\n files.append(f'$builddir/{os.path.split(f)[1]}.mm')\n ninja.newline()\n\n for f in files:\n ninja.build(f'$builddir/{os.path.split(f)[1]}.o', 'compile', f)\n outputs.append(f'$builddir/{os.path.split(f)[1]}.o')\n ninja.newline()\n\n\n if type == 'bundle':\n # Use the build file itself as a way to trick ninja into working without a specific file\n ninja.build('$builddir/trash/bundles', 'bundle', 'build.ninja') \n targets.append('$builddir/trash/bundles')\n ninja.newline()\n \n ninja.build('$builddir/trash/stage', 'stage', ('$target' if uvars['nocomp'] == 0 else 'build.ninja'))\n targets.append('$builddir/trash/stage')\n ninja.newline()\n\n ninja.build('$symtarget', 'link', outputs)\n ninja.newline()\n\n ninja.build('$signtarget', 'debug', '$symtarget')\n ninja.newline()\n\n ninja.build('$target', 'sign', '$signtarget')\n ninja.newline()\n\n for f in plists:\n ninja.build(f'.dragon/_$location./{os.path.split(f)[1]}', 'plist', f)\n targets.append(f'.dragon/_$location./{os.path.split(f)[1]}')\n ninja.newline()\n\n ninja.default(targets)\n ninja.newline()\n\n\ndef main():\n read_dragon_configuration()\n\n for i in exports:\n print(f'export {i}=\"{exports[i]}\"')\n \ndef getmakevars(filename, filter):\n variables = {}\n fp = open(filename)\n try:\n while 1:\n line = fp.readline()\n match = re.search(make_match, line)\n if match:\n one_tuple = match.group(1,2)\n variables[one_tuple[0]] = one_tuple[1]\n if not line:\n break\n finally:\n fp.close()\n return variables\n\nif __name__ == \"__main__\":\n main()","sub_path":"DragonGen/DragonGen.py","file_name":"DragonGen.py","file_ext":"py","file_size_in_byte":14596,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"298030511","text":"# coding: utf-8\n# 提取网络爬虫百科词条中,词条摘要中相关词条的连接\n\nimport re\nfrom bs4 import BeautifulSoup\nimport requests\n\nurl = 'https://baike.baidu.com/item/网络爬虫/5162711?fr=aladdin'\n# url = 'https://www.baidu.com/'\nuser_agent = 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.99 Safari/537.36'\nheaders = {'User-Agent': user_agent}\n # 请求获取网址\nr = requests.get(url, headers=headers)\nr.encoding = 'utf-8' # 解决中文乱码的问题\nprint(type(r.text)) # \n\n# 指定原始文档的编码格式\nsoup = BeautifulSoup(r.text, 'html.parser', from_encoding='utf-8')\n\n# 方法1:使用正则提取代码中部分a标签\nlinks = soup.find_all('a', href=re.compile(r'/item/%E8%9'))\n# links = soup.select(\".lemma-summary a::attr(href)\").extract_first()\nprint(len(links))\nprint(links)\nfor link in links:\n # 提取href的属性,既URL地址\n new_url = link['href']\n print(new_url)\nprint('\\n')\n\n# 方法2:查找唯一的一个标签\ntitle = soup.find('dd', class_='lemmaWgt-lemmaTitle-title').find('h1')\nprint(title)\nprint(title.get_text())\nprint('\\n')\nsummary = soup.find('div', class_='lemma-summary')\nprint(summary.get_text())\n\n# 方法3:查找唯一的标签,然后找出里面所有的a标签,提取a标签的连接属性\nlinks = soup.find('div', class_='lemma-summary').find_all('a')\nprint(links)\nfor link in links:\n # 提取href的属性,既URL地址\n new_url = link['href']\n print(new_url)\n\n# 方法4,使用CSS选择器,但是查找a标签会提示伪类错误\n\n\n\n\n\n","sub_path":"04_Python_expand_knowledge_解析相关_正则XPathBS4CSS/005_lxml_BS4解析(来自TLXY_study_note)/67_7_2_requests.get_bs4_html.parser_传入字符串_查找标签_配合正则使用_提取标签属性.py","file_name":"67_7_2_requests.get_bs4_html.parser_传入字符串_查找标签_配合正则使用_提取标签属性.py","file_ext":"py","file_size_in_byte":1613,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"238849558","text":"from django.shortcuts import render_to_response\nfrom personalapp.models import Post\nfrom django.core.context_processors import csrf\n\ndef home(request):\n\tposts = Post.objects.all()\n\tposts = posts.reverse()\n\td = dict(title=\"Alexander Ledovskiy's blog\", posts=posts)\n\treturn render_to_response(\"home.html\", d)\n\ndef post(request, post_id):\n\tpost = Post.objects.get(id=post_id)\n\t\n\td = dict(title=\"Alexander Ledovskiy's blog\", post=post)\n\td.update(csrf(request))\n\treturn render_to_response(\"post.html\", d)\n","sub_path":"personalapp/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":500,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"33"} +{"seq_id":"418158404","text":"# Created by CubicVirtuoso\nimport sys\nfrom net.sf.l2j.gameserver.model.quest import State\nfrom net.sf.l2j.gameserver.model.quest import QuestState\nfrom net.sf.l2j.gameserver.model.quest.jython import QuestJython as JQuest\n\n#NPCs\nJASMINE = 7134\nROSELYN = 7355\nHARNE = 7144\n\n#ITEM\nROSELYNS_NOTE = 7573\n\n#REWARDS\nADENA = 57\nSCROLL_OF_ESCAPE_GIRAN = 7559\nMARK_OF_TRAVELER = 7570\n\nclass Quest (JQuest) :\n\n def __init__(self,id,name,descr):\n JQuest.__init__(self,id,name,descr)\n self.questItemIds = [ROSELYNS_NOTE]\n\n def onEvent (self,event,st) :\n htmltext = event\n if event == \"7134-03.htm\" :\n st.set(\"cond\",\"1\")\n st.setState(STARTED)\n st.playSound(\"ItemSound.quest_accept\")\n elif event == \"7355-02.htm\" :\n st.giveItems(ROSELYNS_NOTE,1)\n st.set(\"cond\",\"2\")\n st.set(\"id\",\"2\")\n st.playSound(\"ItemSound.quest_middle\")\n elif event == \"7144-02.htm\" :\n st.takeItems(ROSELYNS_NOTE,-1)\n st.set(\"cond\",\"3\")\n st.set(\"id\",\"3\")\n st.playSound(\"ItemSound.quest_middle\")\n elif event == \"7134-06.htm\" :\n st.giveItems(SCROLL_OF_ESCAPE_GIRAN,1)\n st.giveItems(MARK_OF_TRAVELER, 1)\n st.set(\"cond\",\"0\")\n st.setState(COMPLETED)\n st.playSound(\"ItemSound.quest_finish\")\n return htmltext\n\n def onTalk (Self,npc,st):\n htmltext = \"I have nothing to say to you.\"\n npcId = npc.getNpcId()\n cond = st.getInt(\"cond\")\n id = st.getState()\n if id == CREATED :\n st.set(\"cond\",\"0\")\n if st.getPlayer().getRace().ordinal() == 2 :\n if st.getPlayer().getLevel() >= 3 :\n htmltext = \"7134-02.htm\"\n else :\n htmltext = \"Quest for characters level 3 and above.\"\n st.exitQuest(1)\n else :\n htmltext = \"7134-01.htm\"\n st.exitQuest(1)\n elif npcId == JASMINE and id == COMPLETED :\n htmltext = \"I can't supply you with another Giran Scroll of Escape. Sorry traveller.\"\n elif npcId == JASMINE and cond == 1 :\n htmltext = \"7134-04.htm\"\n elif npcId == ROSELYN and cond :\n if st.getQuestItemsCount(ROSELYNS_NOTE) == 0 :\n htmltext = \"7355-01.htm\"\n else :\n htmltext = \"7355-03.htm\"\n elif npcId == HARNE and cond == 2 and st.getQuestItemsCount(ROSELYNS_NOTE) > 0 :\n htmltext = \"7144-01.htm\"\n elif npcId == JASMINE and cond == 3 :\n htmltext = \"7134-05.htm\"\n return htmltext\n\nQUEST = Quest(8,\"8_AnAdventureBegins\",\"An Adventure Begins\")\nCREATED = State('Start', QUEST)\nSTARTED = State('Started', QUEST)\nCOMPLETED = State('Completed', QUEST)\n\nQUEST.setInitialState(CREATED)\nQUEST.addStartNpc(JASMINE)\n\nQUEST.addTalkId(JASMINE)\nQUEST.addTalkId(ROSELYN)\nQUEST.addTalkId(HARNE)","sub_path":"compile/gameserver/data/scripts/quests/8_AnAdventureBegins/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":2717,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"96583038","text":"import tornado.ioloop\nimport tornado.web\nimport os\nimport pandas as pd\nimport seaborn as sns\nfrom matplotlib import pyplot as plt\nimport numpy as np\nimport math\nimport random\nimport datetime \nimport time\nsns.set_style(\"darkgrid\")\n\nclass MainHandler(tornado.web.RequestHandler):\n def get(self):\n self.render(\"dino_map.html\")\n\nclass DinoUser(tornado.web.RequestHandler):\n def get(self):\n self.render(\"dino_user.html\")\n\nclass DinoFilter(tornado.web.RequestHandler):\n def get(self):\n self.render(\"dino_filter.html\")\n\nclass FilterData(tornado.web.RequestHandler):\n def get(self):\n x_min = float(self.get_argument(\"x_min\"))\n x_max = float(self.get_argument(\"x_max\"))\n y_min = float(self.get_argument(\"y_min\"))\n y_max = float(self.get_argument(\"y_max\"))\n t_min = np.datetime64(int(self.get_argument(\"t_min\")),\"ms\")\n t_max = np.datetime64(int(self.get_argument(\"t_max\")),\"ms\")\n\n df = self.df\n area = (df[\"X\"]<=x_max) & (df[\"X\"]>=x_min) & (df[\"Y\"]<=y_max) & (df[\"Y\"]>=y_min)\n time = (df[\"time\"] >= t_min) & (df[\"time\"] <= t_max)\n # as int\n guests = sorted(df.loc[area & time,\"id\"].unique().tolist())\n self.write({\"guests\" : guests})\n\n def initialize(self, df):\n self.df = df\n\n\nclass DataHandler(tornado.web.RequestHandler):\n def get(self):\n df = self.df\n guest_id = self.get_argument(\"id\", None)\n if guest_id is None:\n guest_id = np.random.choice(df[\"id\"])\n else:\n guest_id = int(guest_id)\n guest_df = df.loc[df[\"id\"]==guest_id]\n guest_df_list = guest_df.to_dict(\"records\") \n self.write({\"array\" :guest_df_list})\n\n def initialize(self, df):\n self.df = df[[\"X\",\"Y\",\"id\",\"Timestamp\",\"type\"]]\n\nclass DistanceHandler(tornado.web.RequestHandler):\n\n def obtainTotalDistanceByUser(self,guest_df):\n i = 1\n velocity_list = []\n guest_matrix = guest_df.values\n total_distance = 0\n d = 0\n v = 0\n t = 0\n \n while i < len(guest_df):\n\n # Distance math...\n\n xi = int(guest_matrix[i-1][3])\n yi = int(guest_matrix[i-1][4])\n\n xf = int(guest_matrix[i][3])\n yf = int(guest_matrix[i][4])\n\n d = math.sqrt(pow((xf-xi),2)+pow((yf-yi),2))\n total_distance += d\n\n # Time math\n\n ti = datetime.datetime.strptime(guest_matrix[i-1][0], '%Y-%m-%d %H:%M:%S')\n tf = datetime.datetime.strptime(guest_matrix[i][0], '%Y-%m-%d %H:%M:%S')\n \n t = (tf-ti).total_seconds()\n \n # Velocity math\n v = d/t\n \n velocity_list.append(v)\n i += 1\n return total_distance\n \n def get(self):\n df = self.df\n guest_id = self.get_argument(\"id\", None)\n guest_id = int(guest_id)\n\n guest_df = df.loc[df[\"id\"]==guest_id]\n response = self.obtainTotalDistanceByUser(guest_df)\n self.write({\"response\" :response})\n\n def initialize(self, df):\n self.df = df\n\nclass FilterByCheckin(tornado.web.RequestHandler):\n def get(self):\n num = int(self.get_argument(\"num\"))\n df = self.df\n # From the notebook\n checkin_filter = df['type'] == 'check-in'\n checkin_df = df[checkin_filter]\n groupUserCheckin = checkin_df['id'].value_counts()\n \n checkInFiltered = groupUserCheckin[groupUserCheckin < num]\n checkin_df = pd.DataFrame(checkInFiltered, columns=['number'])\n self.write({\"checkins\" :checkin_df.to_dict()})\n def initialize(self, df):\n self.df = df\n\nsettings = {\"template_path\" : os.path.dirname(__file__),\n \"static_path\" : os.path.join(os.path.dirname(__file__),\"static\"),\n \"debug\" : True\n } \n\nif __name__ == \"__main__\":\n path = os.path.join(os.path.dirname(__file__), \"C:/MC1 2015 Data/park-movement-Fri.csv\")\n print('loading...')\n df = pd.read_csv(path)\n # df = df.loc[df[\"id\"]==103006] #temp...\n print('converting time...')\n df[\"time\"] = pd.to_datetime(df.Timestamp, format=\"%Y-%m-%d %H:%M:%S\")\n\n application = tornado.web.Application([\n (r\"/\", MainHandler),\n (r\"/data\", DataHandler,{\"df\":df}),\n (r\"/filter\", DinoFilter),\n (r\"/filter_data\", FilterData,{\"df\":df}),\n (r\"/static/(.*)\", tornado.web.StaticFileHandler,\n {\"path\": settings[\"static_path\"]}),\n (r\"/dinoUser\", DinoUser),\n (r\"/checkins\", FilterByCheckin,{\"df\":df}),\n (r\"/distance\", DistanceHandler,{\"df\":df}),\n\n ], **settings)\n application.listen(8100)\n print(\"ready\")\n tornado.ioloop.IOLoop.current().start()\n\n","sub_path":"web_viewer/dino_server.py","file_name":"dino_server.py","file_ext":"py","file_size_in_byte":4745,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"524741401","text":"from __future__ import unicode_literals\n\nfrom django.contrib.auth.models import User\nfrom django.core.exceptions import ValidationError\nfrom django.db import models\nfrom django.utils import six, timezone\nfrom django.utils.encoding import python_2_unicode_compatible\nfrom django.utils.translation import ugettext_lazy as _\nfrom djblets.db.fields import JSONField\n\nfrom reviewboard.site.models import LocalSite\nfrom reviewboard.webapi.managers import WebAPITokenManager\n\n\n@python_2_unicode_compatible\nclass WebAPIToken(models.Model):\n \"\"\"An access token used for authenticating with the API.\n\n Each token can be used to authenticate the token's owner with the API,\n without requiring a username or password to be provided. Tokens can\n be revoked, and new tokens added.\n\n Tokens can store policy information, which will later be used for\n restricting access to the API.\n \"\"\"\n user = models.ForeignKey(User, related_name='webapi_tokens')\n local_site = models.ForeignKey(LocalSite, related_name='webapi_tokens',\n blank=True, null=True)\n\n token = models.CharField(max_length=40, unique=True)\n time_added = models.DateTimeField(default=timezone.now)\n last_updated = models.DateTimeField(default=timezone.now)\n\n note = models.TextField(blank=True)\n policy = JSONField(default={})\n\n extra_data = JSONField(default={})\n\n objects = WebAPITokenManager()\n\n def is_accessible_by(self, user):\n return user.is_superuser or self.user == user\n\n def is_mutable_by(self, user):\n return user.is_superuser or self.user == user\n\n def is_deletable_by(self, user):\n return user.is_superuser or self.user == user\n\n def __str__(self):\n return 'Web API token for %s' % self.user\n\n @classmethod\n def validate_policy(cls, policy):\n \"\"\"Validates an API policy.\n\n This will check to ensure that the policy is in a suitable format\n and contains the information required in a format that can be parsed.\n\n If a failure is found, a ValidationError will be raised describing\n the error and where it was found.\n \"\"\"\n from reviewboard.webapi.resources import resources\n\n if not isinstance(policy, dict):\n raise ValidationError(_('The policy must be a JSON object.'))\n\n if policy == {}:\n # Empty policies are equivalent to allowing full access. If this\n # is empty, we can stop here.\n return\n\n if 'resources' not in policy:\n raise ValidationError(\n _(\"The policy is missing a 'resources' section.\"))\n\n resources_section = policy['resources']\n\n if not isinstance(resources_section, dict):\n raise ValidationError(\n _(\"The policy's 'resources' section must be a JSON object.\"))\n\n if not resources_section:\n raise ValidationError(\n _(\"The policy's 'resources' section must not be empty.\"))\n\n if '*' in resources_section:\n cls._validate_policy_section(resources_section, '*',\n 'resources.*')\n\n resource_policies = [\n (section_name, section)\n for section_name, section in six.iteritems(resources_section)\n if section_name != '*'\n ]\n\n if resource_policies:\n valid_policy_ids = cls._get_valid_policy_ids(resources.root)\n\n for policy_id, section in resource_policies:\n if policy_id not in valid_policy_ids:\n raise ValidationError(\n _(\"'%s' is not a valid resource policy ID.\")\n % policy_id)\n\n for subsection_name, subsection in six.iteritems(section):\n if not isinstance(subsection_name, six.text_type):\n raise ValidationError(\n _(\"%s must be a string in 'resources.%s'\")\n % (subsection_name, policy_id))\n\n cls._validate_policy_section(\n section, subsection_name,\n 'resources.%s.%s' % (policy_id, subsection_name))\n\n @classmethod\n def _validate_policy_section(cls, parent_section, section_name,\n full_section_name):\n section = parent_section[section_name]\n\n if not isinstance(section, dict):\n raise ValidationError(\n _(\"The '%s' section must be a JSON object.\")\n % full_section_name)\n\n if 'allow' not in section and 'block' not in section:\n raise ValidationError(\n _(\"The '%s' section must have 'allow' and/or 'block' \"\n \"rules.\")\n % full_section_name)\n\n if 'allow' in section and not isinstance(section['allow'], list):\n raise ValidationError(\n _(\"The '%s' section's 'allow' rule must be a list.\")\n % full_section_name)\n\n if 'block' in section and not isinstance(section['block'], list):\n raise ValidationError(\n _(\"The '%s' section's 'block' rule must be a list.\")\n % full_section_name)\n\n @classmethod\n def _get_valid_policy_ids(cls, resource, result=None):\n if result is None:\n result = set()\n\n if hasattr(resource, 'policy_id'):\n result.add(resource.policy_id)\n\n for child_resource in resource.list_child_resources:\n cls._get_valid_policy_ids(child_resource, result)\n\n for child_resource in resource.item_child_resources:\n cls._get_valid_policy_ids(child_resource, result)\n\n return result\n\n class Meta:\n verbose_name = _('Web API token')\n verbose_name_plural = _('Web API tokens')\n","sub_path":"reviewboard/webapi/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":5823,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"431038810","text":"# coding=utf-8\n# Copyright 2019 The SEED Authors\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\"\"\"Flags and configuration.\"\"\"\n\nimport tempfile\n\nfrom absl import flags\nfrom absl import logging\nimport atari_py \nimport gym\nfrom seed_rl.atari import agents\nfrom seed_rl.atari import atari_preprocessing\nimport tensorflow as tf\n\n\nFLAGS = flags.FLAGS\n\n# COMMON FLAGS\n\nflags.DEFINE_string('logdir', '/tmp/agent', 'TensorFlow log directory.')\nflags.DEFINE_alias('job-dir', 'logdir')\nflags.DEFINE_string('server_address', 'localhost:8686', 'Server address.')\n\n# LEARNER\n\n# Training.\nflags.DEFINE_integer('save_checkpoint_secs', 1800,\n 'Checkpoint save period in seconds.')\nflags.DEFINE_integer('total_environment_frames', int(1e9),\n 'Total environment frames to train for.')\nflags.DEFINE_integer('batch_size', 2, 'Batch size for training.')\nflags.DEFINE_float('replay_ratio', 1.5,\n 'Average number of times each observation is replayed and '\n 'used for training. '\n 'The default of 1.5 corresponds to an interpretation of the '\n 'R2D2 paper using the end of section 2.3.')\nflags.DEFINE_integer('inference_batch_size', 2, 'Batch size for inference.')\nflags.DEFINE_integer('unroll_length', 100, 'Unroll length in agent steps.')\nflags.DEFINE_integer('num_training_tpus', 1, 'Number of TPUs for training.')\nflags.DEFINE_integer('update_target_every_n_step',\n 2500,\n 'Update the target network at this frequency (expressed '\n 'in number of training steps)')\nflags.DEFINE_integer('replay_buffer_size', 100,\n 'Size of the replay buffer (in number of unrolls stored).')\nflags.DEFINE_integer('replay_buffer_min_size', 10,\n 'Learning only starts when there is at least this number '\n 'of unrolls in the replay buffer')\nflags.DEFINE_float('priority_exponent', 0.9,\n 'Priority exponent used when sampling in the replay buffer. '\n '0.9 comes from R2D2 paper, table 2.')\nflags.DEFINE_integer('unroll_queue_max_size', 100,\n 'Max size of the unroll queue')\nflags.DEFINE_integer('burn_in', 40,\n 'Length of the RNN burn-in prefix. This is the number of '\n 'time steps on which we update each stored RNN state '\n 'before computing the actual loss. The effective length '\n 'of unrolls will be burn_in + unroll_length, and two '\n 'consecutive unrolls will overlap on burn_in steps.')\nflags.DEFINE_float('importance_sampling_exponent', 0.6,\n 'Exponent used when computing the importance sampling '\n 'correction. 0 means no importance sampling correction. '\n '1 means full importance sampling correction.')\nflags.DEFINE_integer('stack_size', 4, 'Number of frames to stack.')\nflags.DEFINE_float('clip_norm', 40, 'We clip gradient norm to this value.')\nflags.DEFINE_float('value_function_rescaling_epsilon', 1e-3,\n 'Epsilon used for value function rescaling.')\nflags.DEFINE_integer('n_steps', 5,\n 'n-step returns: how far ahead we look for computing the '\n 'Bellman targets.')\n\n# Loss settings.\nflags.DEFINE_float('discounting', .997, 'Discounting factor.')\n\n# Optimizer settings.\nflags.DEFINE_float('learning_rate', 0.00048, 'Learning rate.')\nflags.DEFINE_float('adam_epsilon', 1e-3, 'Adam epsilon.')\n\n# ACTOR\n\nflags.DEFINE_integer('task', 0, 'Task id.')\nflags.DEFINE_integer('num_actors', 4,\n 'Total number of actors. The last --num_eval_actors will '\n 'be reserved for evaluation and not used for training.')\n\n# Environment settings.\nflags.DEFINE_string('game', 'Pong', 'Game name.')\nflags.DEFINE_integer('num_action_repeats', 4, 'Number of action repeats.')\nflags.DEFINE_integer('max_random_noops', 30,\n 'Maximal number of random no-ops at the beginning of each '\n 'episode.')\nflags.DEFINE_boolean('sticky_actions', False,\n 'When sticky actions are enabled, the environment repeats '\n 'the previous action with probability 0.25, instead of '\n 'playing the action given by the agent. Used to introduce '\n 'stochasticity in ATARI-57 environments, see '\n 'Machado et al. (2017).')\n\n# Eval settings\nflags.DEFINE_float('eval_epsilon', 1e-3,\n 'Epsilon (as in epsilon-greedy) used for evaluation.')\nflags.DEFINE_integer('num_eval_actors', 2,\n 'Number of actors whose transitions will be used for '\n 'eval.')\n\n\ndef create_environment(task): \n logging.info('Creating environment: %s', FLAGS.game)\n\n\n game_version = 'v0' if FLAGS.sticky_actions else 'v4'\n full_game_name = '{}NoFrameskip-{}'.format(FLAGS.game, game_version)\n env = gym.make(full_game_name, full_action_space=True)\n env.seed(task)\n\n if not isinstance(env, gym.wrappers.TimeLimit):\n raise ValueError('We expected gym.make to wrap the env with TimeLimit. '\n 'Got {}.'.format(type(env)))\n # Change TimeLimit wrapper to 108,000 steps (30 min) as default in the\n # litterature instead of OpenAI Gym's default of 100,000 steps.\n env = gym.wrappers.TimeLimit(env.env, max_episode_steps=108000)\n return atari_preprocessing.AtariPreprocessing(\n env, frame_skip=FLAGS.num_action_repeats,\n max_random_noops=FLAGS.max_random_noops)\n\n\ndef create_optimizer(unused_final_iteration):\n learning_rate_fn = lambda iteration: FLAGS.learning_rate\n optimizer = tf.keras.optimizers.Adam(FLAGS.learning_rate,\n epsilon=FLAGS.adam_epsilon)\n return optimizer, learning_rate_fn\n\n\ndef create_agent(env_output_specs, num_actions):\n return agents.DuelingLSTMDQNNet(\n num_actions, env_output_specs.observation.shape, FLAGS.stack_size)\n","sub_path":"atari/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":6558,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"127956811","text":"\"\"\"\nThe only object you should have to import. Access all of the API from here.\n\"\"\"\nfrom .constants import USER_AGENT\nfrom datetime import datetime\nimport dateutil.parser\nimport logging\nimport requests\nfrom .transport_adapter import Basecamp3TransportAdapter\nimport traceback\n\nfrom basecampy3.exc import *\nfrom .config import BasecampConfig\nfrom .token_requestor import TokenRequester\nfrom .endpoints import answers\nfrom .endpoints import campfires\nfrom .endpoints import campfire_lines\nfrom .endpoints import messages\nfrom .endpoints import message_boards\nfrom .endpoints import message_categories\nfrom .endpoints import people\nfrom .endpoints import projects\nfrom .endpoints import project_constructions\nfrom .endpoints import templates\nfrom .endpoints import todolists\nfrom .endpoints import todolist_groups\nfrom .endpoints import todos\nfrom .endpoints import todosets\n\n\nclass Basecamp3(object):\n OAUTH_DOMAIN = \"launchpad.37signals.com\"\n ACCESS_TOKEN_URL = \"https://{domain}/authorization/token?type=web_server&client_id={client_id}&\" \\\n \"redirect_uri={redirect_uri}&client_secret={client_secret}&code={code}\"\n REFRESH_TOKEN_URL = \"https://{domain}/authorization/token?type=refresh&refresh_token={0.refresh_token}&\" \\\n \"client_id={0.client_id}&redirect_uri={0.redirect_uri}&client_secret={0.client_secret}\"\n\n def __init__(self, client_id=None, client_secret=None, redirect_uri=None, access_token=None, access_expires=None,\n refresh_token=None, user_email=None, user_pass=None, conf=None):\n \"\"\"\n Create a new Basecamp 3 API connection. The following combinations of parameters are valid:\n\n 1. `access_token` only\n Can access the API for now, but when this `access_token` expires you'll have to provide a new one. Not\n ideal for automation.\n 2. `refresh_token`\n With `client_id`, `client_secret`, `redirect_uri`, and a `refresh_token`, we can obtain and refresh our\n own `access_token`. `refresh_token`s don't seem to have a limit so this is ideal for automation.\n 3. `user_email` and `user_pass`\n With `user_email`, `user_pass`, `client_id`, `client_secret`, and `redirect_uri`, we can obtain our own\n `refresh_token` and therefore our own `access_token`. This is ideal for first runs. If your configuration\n file is in a writable spot, your `access_token` and `refresh_token` can be written to it automatically.\n Once you have obtained a `refresh_token`, you should remove your `user_email` and `user_pass` from the\n configuration and then change your password on Basecamp's site as a best practice.\n\n `client_id`, `client_secret`, and `redirect_uri` can be obtained by creating a new app here:\n https://launchpad.37signals.com/integrations\n\n `redirect_uri` doesn't have to be a real URL, but it does have to match what you put when you registered your\n app at the site above.\n\n `access_token` and `refresh_token` are normally obtained when a user clicks your app integration page and\n presses the big green \"Yes, I'll allow access\" button, which redirects them to your `redirect_uri` with a\n authorization code attached to it. Your app then uses its client_secret and client_id to obtain the tokens with\n this authorization code. Since that is a long and confusing process that requires you to set up a web server\n to answer the `redirect_uri`, see below on how this API makes it easy to obtain.\n\n `user_email` and `user_pass` is a login for Basecamp. It is NOT recommended to use this long term. If your\n Basecamp configuration file is in a writeable location, this API will write the `access_token` and\n `refresh_token` to it. You can then delete your username and password from the configuration file. Refresh\n tokens have no limit. There is no reason to continue using your username and password once you have obtained it.\n\n :param client_id: your app's client_id is given to you when you create a new app\n :type client_id: str\n :param client_secret: your app's client_secret is given to you when you create a new app\n :type client_secret: str\n :param redirect_uri: your app's redirect_uri can be fake but it needs to match on your app page\n :type redirect_uri: str\n :param access_token: an access token you have obtained from a user\n :type access_token: str\n :param access_expires: (optional) when the access token will expire as a datetime or datetime.timestamp float\n :type access_expires: datetime.datetime|float\n :param refresh_token: a refresh token obtained from a user, used for obtaining a new access_token\n :type refresh_token: str\n :param user_email: a user's login email for Basecamp 3. Only used to obtain refresh_token.\n :type user_email: str\n :param user_pass: a user's login password for Basecamp 3. Only used to obtain refresh_token.\n :type user_pass: str\n :param conf: a BasecampConfig object with all the settings we need so that we don't have to fill out all\n these parameters\n :type conf: basecampy3.config.BasecampConfig\n \"\"\"\n can_request_our_own_refresh_tokens = client_id and client_secret and redirect_uri and user_email and user_pass\n can_refresh_access_tokens = refresh_token and client_id and client_secret and redirect_uri\n if access_token or can_refresh_access_tokens or can_request_our_own_refresh_tokens:\n conf = BasecampConfig(client_id=client_id, client_secret=client_secret, redirect_uri=redirect_uri,\n user_email=user_email, user_pass=user_pass, access_token=access_token,\n refresh_token=refresh_token, access_expires=access_expires)\n elif conf is None:\n conf = BasecampConfig.load_from_default_paths()\n elif conf is not None:\n pass\n else:\n raise ValueError(\"Need a valid BasecampConfig object, a refresh token, an access token, or enough \"\n \"information to get our own refresh tokens (client_id, client_secret, redirect_uri, \"\n \"username, and password)\")\n\n self._conf = conf\n self._session = requests.session()\n self._session.mount(\"https://\", adapter=Basecamp3TransportAdapter())\n self._session.headers['User-Agent'] = USER_AGENT\n self.account_id = None\n self._authorize()\n self.answers = answers.Answers(self)\n self.campfires = campfires.Campfires(self)\n self.campfire_lines = campfire_lines.CampfireLines(self)\n self.messages = messages.Messages(self)\n self.message_boards = message_boards.MessageBoards(self)\n self.message_categories = message_categories.MessageCategories(self)\n self.people = people.People(self)\n self.projects = projects.Projects(self)\n self.project_constructions = project_constructions.ProjectConstructions(self)\n self.templates = templates.Templates(self)\n self.todolists = todolists.TodoLists(self)\n self.todolist_groups = todolist_groups.TodoListGroups(self)\n self.todos = todos.Todos(self)\n self.todosets = todosets.TodoSets(self)\n\n @property\n def who_am_i(self):\n data = self._get_data(\"https://%s/authorization.json\" % self.OAUTH_DOMAIN)\n return data.json()\n\n @classmethod\n def trade_user_code_for_access_token(cls, client_id, redirect_uri, client_secret, code, session=None):\n access_token_url = cls.ACCESS_TOKEN_URL.format(domain=cls.OAUTH_DOMAIN, client_id=client_id,\n redirect_uri=redirect_uri, client_secret=client_secret,\n code=code)\n if session is None:\n session = requests.session()\n resp = session.post(access_token_url) # this should be a JSON response with our access and refresh tokens\n if not resp.ok:\n raise InvalidUserCodeError(response=resp)\n\n token_json = resp.json() # the None values should be replaced with the JSON values now\n return token_json\n\n def _get_data(self, url, auto_reauthorize=True):\n times_to_try = 2 if auto_reauthorize else 1\n resp = None\n for attempt in range(0, times_to_try):\n resp = self._session.get(url)\n if resp.status_code == 401 and auto_reauthorize:\n if attempt == (times_to_try - 1): # was our last attempt\n break\n else:\n self._authorize() # reauthorize\n continue\n break # we were authorized so we can stop attempting\n\n code = resp.status_code\n\n if code == 401:\n raise UnauthorizedError(message=\"Unable to authorize ourselves to Basecamp.\", response=resp)\n return resp\n\n def _authorize(self):\n \"\"\"\n Determine if we have the credentials at our disposal to make API calls.\n :return:\n \"\"\"\n\n if self._is_token_expired():\n self._get_access_token()\n self._apply_token_to_headers() # set our access token to the Authorization header for this session\n self.account_id = self._get_account_id() # set our Basecamp account ID used in many API calls\n\n def _apply_token_to_headers(self):\n self._session.headers['Authorization'] = 'Bearer %s' % self._conf.access_token\n\n def _get_access_token(self):\n if self._conf.refresh_token:\n try:\n token_json = self._refresh_access_token()\n self._save_token_json(token_json)\n return # if there wasn't an error, the access token is ready to go\n except InvalidRefreshTokenError:\n self._conf.refresh_token = None # this is a bad token\n\n token_req = TokenRequester(self._conf.client_id, self._conf.redirect_uri,\n self._conf.user_email, self._conf.user_pass)\n code = token_req.get_user_code()\n\n token_json = self.trade_user_code_for_access_token(client_id=self._conf.client_id,\n redirect_uri=self._conf.redirect_uri,\n client_secret=self._conf.client_secret, code=code)\n self._save_token_json(token_json)\n\n def _get_account_id(self):\n identity = self.who_am_i\n for acct in identity['accounts']:\n if acct['product'] == 'bc3':\n return acct['id']\n raise UnknownAccountIDError(\"Could not determine this Basecamp account's ID\")\n\n def _is_token_expired(self):\n \"\"\"\n Check the access token in our configuration and see if it's expired. If it is expired or there isn't an access\n token, return Trues\n :return: True if token is missing or expired, False if the token is still valid\n \"\"\"\n if not self._conf.access_token:\n return True\n self._apply_token_to_headers() # ok then lets apply this token to our session if it's not there already\n try:\n resp = self._get_data(\"https://%s/authorization.json\" % self.OAUTH_DOMAIN, False)\n except Exception as ex:\n logging.debug(\"Token is expired: %s\" % traceback.format_exc())\n return True\n expires_at = dateutil.parser.parse(resp.json()['expires_at'])\n expires_at = expires_at.replace(tzinfo=None)\n return datetime.utcnow() >= expires_at\n\n def _refresh_access_token(self):\n url = self.REFRESH_TOKEN_URL.format(self._conf, domain=self.OAUTH_DOMAIN)\n resp = self._session.post(url)\n if resp.status_code != 200:\n raise InvalidRefreshTokenError(response=resp)\n token_json = resp.json()\n\n return token_json\n\n def _save_token_json(self, token_json):\n if 'access_token' in token_json:\n self._conf.access_token = token_json['access_token']\n if 'refresh_token' in token_json:\n self._conf.refresh_token = token_json['refresh_token']\n if 'expires_in' in token_json:\n self._conf.access_expires = token_json['expires_in']\n self._conf.save()\n","sub_path":"basecampy3/bc3_api.py","file_name":"bc3_api.py","file_ext":"py","file_size_in_byte":12430,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"164037661","text":"import sys\nimport glob\nimport os\nimport numpy\nfrom pylab import plot, show, figure, imshow\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport essentia\nfrom essentia.standard import MonoLoader, PredominantPitchMelodia, MonoWriter\n# set plot sizes to something larger than default\nplt.rcParams['figure.figsize'] = (15, 6)\n\nsys.setrecursionlimit(20000)\n###############################Melody detection#################################\n\n# Create folder for segments\n\nsample_rate = 44100\nhS = 512\nfS = 2048\n\n\n# Extract the pitch curve\n# PitchMelodia takes the entire audio signal as input (no frame-wise processing is required)\n\n\ndef audio_segments_generator(audio):\n pitch_extractor = PredominantPitchMelodia(frameSize=fS,\n hopSize=1024,\n filterIterations=3,\n # harmonic weighting parameter (weight decay ratio between two consequent harmonics, =1 for no decay)\n harmonicWeight=0.8,\n # spectral peak magnitude threshold (maximum allowed difference from the highest peak in dBs)\n magnitudeThreshold=40,\n guessUnvoiced=False,\n # the minimum allowed contour duration [ms]\n minDuration=10,\n numberHarmonics=20,\n timeContinuity=100, # the maximum allowed gap duration for a pitch contour\n voiceVibrato=False,\n # allowed deviation below the average contour mean salience of all contours (fraction of the standard deviation)\n voicingTolerance=0.8,\n # 27.5625 pitch continuity cue (maximum allowed pitch change during 1 ms time period) [cents]\n pitchContinuity=27.5625,\n # 0.45 funcionó para bach partita de violin per-frame salience threshold factor (fraction of the highest peak salience in a frame)) # These are samples!!! To write in audio we need to use frames\n peakFrameThreshold=0.7)\n # Pitch is estimated on frames. Compute frame time positions\n pitch_values, _ = pitch_extractor(audio)\n prev_index = 0\n sample_indexes = []\n # Filter segments from data retrived\n for i in range(len(pitch_values)):\n num = pitch_values[i]\n if num > 0 and prev_index == 0:\n sample_indexes.append(i)\n prev_index = num\n # Convert the sample_indexes into samples\n sample_list = [n*hS for n in sample_indexes]\n audioSize = audio.size\n sample_list.insert(0, 0)\n sample_list.append(audioSize)\n return sample_list\n\n\n# Load audio files from folder\ndef concat_audio(out_dir, frame_count, segment_count, segment_list, audio_list, file_index, output_data):\n if not os.path.exists(out_dir):\n os.makedirs(out_dir)\n print(\"frame, segment\", frame_count, segment_count, file_index)\n if frame_count < len(segment_list[segment_count])-1:\n startFrame = segment_list[segment_count][frame_count]\n endFrame = segment_list[segment_count][frame_count + 1]\n filename = os.path.abspath(\n os.path.join(out_dir, str(file_index)+\".wav\"))\n length = endFrame - startFrame\n if length > 0:\n output_data.append(\n {\"index\": file_index,\n \"path\": filename,\n \"start\": startFrame,\n \"end\": endFrame,\n \"length\": length,\n \"length-seconds\": (endFrame - startFrame)/sample_rate,\n \"sample_rate\": sample_rate})\n MonoWriter(filename=filename, format='wav', sampleRate=sample_rate)(\n audio_list[segment_count][startFrame:endFrame])\n concat_audio(out_dir, frame_count+1, segment_count,\n segment_list, audio_list, file_index+1, output_data)\n else:\n if segment_count < len(segment_list)-1:\n concat_audio(out_dir, 0, segment_count+1, segment_list,\n audio_list, file_index, output_data)\n return output_data\n\n\ndef process_file(out_dir, filename):\n allSampleList = []\n allAudio = []\n audio = MonoLoader(filename=filename)()\n sampleSegments = audio_segments_generator(audio)\n allSampleList.append(sampleSegments)\n allAudio.append(audio)\n files = concat_audio(out_dir, 0, 0, allSampleList, allAudio, 0, [])\n return files\n","sub_path":"Trabajando_con_Essentia/melody_segmentation_study_version.py","file_name":"melody_segmentation_study_version.py","file_ext":"py","file_size_in_byte":4842,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"504747599","text":"import sys\nimport time\nimport os\nimport glob\nimport numpy as np\nfrom skimage import io\nfrom sklearn.externals import joblib\n\nimport shutil\nimport _mypath\n\nimport preprocess.image_graph as igraph\nimport preprocess.utils as my_utils\nimport scene_props.scene_props as sprops\n\n\nclass scene_info:\n def __init__(self, img_src, gp_model_path, grid_size=(60,80), b_pca=True, b_scaler=True, visualise=False, dump_path=None, n_iter=20):\n\n # initialize class memebers\n self.img_src = img_src\n self.gp_model_path = gp_model_path\n self.grid_size = grid_size\n self.b_pca = b_pca\n self.b_scaler = b_scaler\n self.visualise = visualise\n self.dump_path = dump_path\n\n self.sp_obj = sprops.scene_props(self.img_src, grid_size=self.grid_size, visualise=self.visualise, dump_path = self.dump_path, max_iter_slic=n_iter)\n\n def predict_scene_id(self):\n\n # features for edges\n e_descriptor, edge_map, s_descriptor, s_map = self.sp_obj.get_scene_features()\n\n scene_descriptor = np.hstack([e_descriptor[0:244], s_descriptor])\n\n sc_model_path = self.gp_model_path + 'scene_categories/cluster_model/'\n\n km_model_path = sc_model_path + 'cluster.pkl'\n pca_model_path = sc_model_path + 'pca.pkl'\n scaler_model_path = sc_model_path + 'scaler.pkl'\n\n km_model = joblib.load(km_model_path)\n pca_model = joblib.load(pca_model_path)\n scaler_model = joblib.load(scaler_model_path)\n\n # preprocess features\n scene_descriptor = scaler_model.transform(scene_descriptor.reshape(1,-1))\n scene_descriptor = pca_model.transform(scene_descriptor.reshape(1,-1))\n \n scene_id = km_model.predict(scene_descriptor.reshape(1,-1))\n\n return scene_id\n\n def get_num_people(self):\n return self.sp_obj.num_faces\n\n\n def get_salient_objects(self):\n\n s_objects = self.sp_obj.get_salient_objects()\n\n return s_objects\n\n def get_pobj_for_graph(self, num_people, m_position, m_size):\n\n s_objects = self.sp_obj.get_pobj_for_graph(num_people, m_position, m_size)\n\n return s_objects\n\n","sub_path":"src/gpa_package_server/lib/server_code/scene_identification.py","file_name":"scene_identification.py","file_ext":"py","file_size_in_byte":2139,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"20732666","text":"# coding:iso-8859-9 Türkçe\r\n# p_31506.py: Izgaralık/GridSpec ile altşekli ölçekleme ve konumlandırma örneği.\r\n\r\nimport matplotlib.pyplot as mp\r\nfrom matplotlib.gridspec import GridSpec\r\nfrom p_315 import Renk\r\n\r\nşekil = mp.figure()\r\nızgara = GridSpec (1, 1) # Tek satır ve tek sütun...\r\nşekil.add_subplot (ızgara [0, 0] ) # altşekil...\r\nmp.show()\r\n#-------------------------------------------------------------------------------------------------\r\n\r\nmp.style.use (\"dark_background\")\r\nşekil = mp.figure()\r\nızgara = GridSpec (1, 1,\r\n bottom=0.25, # [0,0]'dan uzaklığı=%25\r\n left=0.15, # %15\r\n top=0.99) # %99\r\nşekil.add_subplot (ızgara [0, 0] ) # altşekil...\r\nmp.show()\r\n#-------------------------------------------------------------------------------------------------\r\n\r\nşekil = mp.figure()\r\nşekil.set_facecolor (Renk.renk())\r\nızgara = GridSpec (1, 1,\r\n bottom=0.3, # [0,0]'dan uzaklığı=%30\r\n left=0.099, # %9.9\r\n top=0.7) # %70\r\nşekil.add_subplot (ızgara [0, 0] ).set_facecolor (Renk.renk())\r\nmp.show()\r\n","sub_path":"Bernd Klein (520) ile Python/p_31506.py","file_name":"p_31506.py","file_ext":"py","file_size_in_byte":1055,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"108873944","text":"import re\n\nfrom datetime import datetime\nfrom utils.helper import ar_to_en_num\n\n\nclass Translate:\n \"\"\"\" A class to Translate and get needed information from\n different kinds of offers, counter-offers and transfer_rules.\n \"\"\"\n\n @staticmethod\n def order(text):\n \"\"\"\" Gets an order instuction as a text, Extracts needed information and returns it as a dictionary.\n :param text: the instruction that is supposed to be translated\n :returns a dictionary that contains price_limit, amount and type of order\n :returns None if the pattern of an order instruction is not found.\n \"\"\"\n\n obj = re.fullmatch('^(\\d+)(\\s*)([خف])(\\s*)(ف?)(\\s*)(\\d+)(\\s*)(ت)?(تا)?(\\s*)(یج|یجا)?', text)\n\n if obj is not None:\n if obj.group(3) == \"ف\":\n op = 'sell'\n elif obj.group(3) == 'خ':\n op = 'buy'\n\n if obj.group(5) == 'ف':\n today_tomorrow = 'tomorrow'\n else:\n today_tomorrow = 'today'\n\n if (obj.group(12) == 'یجا'):\n dividable = False\n print('here')\n else:\n print('there')\n dividable = True\n ret = {'price': int(obj.group(1)),\n 'op': op,\n 'today_tomorrow': today_tomorrow,\n 'amount': int(obj.group(7)),\n 'dividable': dividable}\n return ret\n else:\n return None\n\n @staticmethod\n def order_counter_offer(text):\n \"\"\"\" Gets an order_counter_offer instruction as a text, Extracts needed information and returns it as a dictionary.\n :param text: the counter-offer instruction that is supposed to be translated\n :returns a dictionary that contains amount of counter-offer\n :returns None if the pattern of an order counter-offer is not found.\n \"\"\"\n obj = re.fullmatch(\"(ب*)(\\s*)(\\d+)(\\s*)(ب*)\", text)\n\n if obj is not None:\n return int(obj.group(3))\n else:\n return None\n\n @staticmethod\n def get_prices(text):\n\n obj = re.fullmatch('^(\\d+)(\\s+)(\\d+)', text)\n\n if obj is not None:\n prices = text.split()\n prices = [int(price) for price in prices]\n prices.sort()\n\n return prices\n else:\n return None\n\n @staticmethod\n def get_time(text):\n text = ar_to_en_num(text)\n print(text)\n obj = re.fullmatch('^(\\d{1,2})(:)(\\d{1,2})', text)\n\n if obj is not None:\n # text = ar_to_en_num(text)\n return datetime.strptime(text, \"%H:%M\").time().replace(second=0, microsecond=0)\n else:\n return None\n\n @staticmethod\n def complete_accept(text):\n obj = re.fullmatch('^(ب*)$', text)\n if obj is not None:\n return 1\n else:\n return None\n\n# print(Translate.order(input()))\n","sub_path":"src/engine/translate.py","file_name":"translate.py","file_ext":"py","file_size_in_byte":2983,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"164774829","text":"#_*_ coding:utf-8 _*_\nfrom SlothServer.SocketServer import SocketServer\nfrom Sloth.BinaryReader import BinaryReader\nfrom Sloth.MessageCenter import MessageCenter\n\ndef process_message(message):\n if None is not message:\n print(message.info)\n\ndef process_socket(buf):\n binary_reader = BinaryReader(buf)\n MessageCenter.get_instance().process(binary_reader)\n\nif __name__ == '__main__':\n # 初始化消息回调\n # MessageCenter.get_instance().register(HelloMessage(), process_message)\n\n # 创建socket\n config = ServerConfig('Config/Server.json')\n socketServer = SocketServer(config.ip, config.port)\n socketServer.listen(config.max_link, process_socket)\n ","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":690,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"180988076","text":"import cv2\nimport numpy as np\n#轮廓检测\nimg = np.zeros((200,200), dtype=np.uint8)\nimg[50:150, 50:150] = 255\nret, thresh = cv2.threshold(img, 127, 255, 0)\n#findContours会修改原图,最好使用img.copy()\n#RETR_TREE会得到整体的层次结构,以此建立轮廓之间的关系\n#cv2.RETR_EXTERNAL得到最外面的轮廓\nimage, contours, hierarchy = cv2.findContours(thresh,\n cv2.RETR_TREE,\n cv2.CHAIN_APPROX_SIMPLE)\ncolor = cv2.cvtColor(img, cv2.COLOR_GRAY2BGR)\nimg = cv2.drawContours(color, contours, -1, (255,0,255),2)\ncv2.imshow(\"contours\", color)\ncv2.waitKey()\ncv2.destroyAllWindows()","sub_path":"openCV/Chapter3/drawContour.py","file_name":"drawContour.py","file_ext":"py","file_size_in_byte":690,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"153402322","text":"import logging\nimport sys\n\nfrom lbrynet.lbrynet_gui.GuiApp import DownloaderApp\nfrom twisted.internet import reactor, task\nimport locale\n\n\ndef start_gui():\n\n log_format = \"(%(asctime)s)[%(filename)s:%(lineno)s] %(funcName)s(): %(message)s\"\n formatter = logging.Formatter(log_format)\n\n logger = logging.getLogger()\n logger.setLevel(logging.DEBUG)\n file_handler = logging.FileHandler(\"gui.log\")\n file_handler.setFormatter(formatter)\n file_handler.addFilter(logging.Filter(\"lbrynet\"))\n logger.addHandler(file_handler)\n\n sys.stdout = open(\"gui.out.log\", 'w')\n sys.stderr = open(\"gui.err.log\", 'w')\n\n locale.setlocale(locale.LC_ALL, '')\n\n app = DownloaderApp()\n\n d = task.deferLater(reactor, 0, app.start)\n\n reactor.run()\n\nif __name__ == \"__main__\":\n start_gui()","sub_path":"lbrynet/lbrynet_gui/gui.py","file_name":"gui.py","file_ext":"py","file_size_in_byte":802,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"514458511","text":"import six\nimport math\nimport inspect\nimport functools\nimport numpy as np\nimport scipy as sp\n\n\nclass _Node(object):\n def __init__(self,\n name,\n derived=False,\n readonly=False,\n nullable=False,\n default_or_starting_value=None,\n callable=None,\n callable_args=None,\n callable_kwargs=None,\n callable_is_method=False,\n always_dirty=False,\n trace=False,\n ):\n self._callable = callable\n self._name = name\n self._value = default_or_starting_value\n self._readonly = readonly\n self._trace = trace\n self._callable = callable\n self._callable_args = self._transform_args(callable_args or [])\n self._callable_kwargs = self._transform_kwargs(callable_kwargs or {})\n self._callable_is_method = callable_is_method\n self._always_dirty = always_dirty\n\n self._self_reference = self\n\n # cache node operations that have already been done\n self._node_op_cache = {}\n\n if callable:\n self._callable._node_wrapper = None # not known until program start\n self._dependencies = {self._callable: (self._callable_args, self._callable_kwargs)}\n else:\n self._dependencies = {}\n\n if derived:\n self._dirty = True\n else:\n self._dirty = False\n\n def _transform_args(self, args):\n return args\n\n def _transform_kwargs(self, kwargs):\n return kwargs\n\n def _with_self(self, other_self):\n self._self_reference = other_self\n return self\n\n def _compute_from_dependencies(self):\n if self._dependencies:\n for deps in six.itervalues(self._dependencies):\n # recompute args\n for arg in deps[0]:\n arg._recompute()\n\n # recompute kwargs\n for kwarg in six.itervalues(deps[1]):\n kwarg._recompute()\n\n k = list(self._dependencies.keys())[0]\n\n if self._callable_is_method:\n new_value = k(self._self_reference, *self._dependencies[k][0], **self._dependencies[k][1])\n else:\n new_value = k(*self._dependencies[k][0], **self._dependencies[k][1])\n\n if isinstance(new_value, _Node):\n k._node_wrapper = new_value\n new_value = new_value() # get value\n\n if self._trace:\n if new_value != self._value:\n print('recomputing: %s#%d' % (self._name, id(self)))\n self._value = new_value\n return self._value\n\n def _subtree_dirty(self):\n for call, deps in six.iteritems(self._dependencies):\n # callable node\n if hasattr(call, '_node_wrapper') and \\\n call._node_wrapper is not None:\n if call._node_wrapper._dirty or call._node_wrapper._subtree_dirty() or call._node_wrapper._always_dirty:\n return True\n\n # check args\n for arg in deps[0]:\n if arg._dirty or arg._subtree_dirty() or arg._always_dirty:\n return True\n\n # check kwargs\n for kwarg in six.itervalues(deps[1]):\n if kwarg._dirty or kwarg._subtree_dirty() or kwarg._always_dirty:\n return True\n return False\n\n def _recompute(self):\n self._dirty = self._dirty or self._subtree_dirty() or self._always_dirty\n if self._dirty:\n self._value = self._compute_from_dependencies()\n self._dirty = False\n\n def _gennode(self, name, foo, foo_args, trace=False):\n if name not in self._node_op_cache:\n self._node_op_cache[name] = \\\n _Node(name=name,\n derived=True,\n callable=foo,\n callable_args=foo_args,\n trace=trace)\n return self._node_op_cache[name]\n\n def _tonode(self, other, trace=False):\n if isinstance(other, _Node):\n return other\n if str(other) not in self._node_op_cache:\n self._node_op_cache[str(other)] = \\\n _Node(name='var(' + str(other)[:5] + ')',\n derived=True,\n default_or_starting_value=other,\n trace=trace)\n return self._node_op_cache[str(other)]\n\n def set(self, **kwargs):\n for k, v in six.iteritems(kwargs):\n _set = False\n for deps in six.itervalues(self._dependencies):\n # try to set args\n for arg in deps[0]:\n if arg._name == k:\n arg._dirty = arg._value != v\n arg._value = v\n _set = True\n break\n\n if _set:\n continue\n\n # try to set kwargs\n for kwarg in six.itervalues(deps[1]):\n if kwarg._name == k:\n kwarg._dirty = kwarg._value != v\n kwarg._value = v\n _set = True\n break\n\n def value(self):\n return self._value\n\n def _print(self, counter=0, cache=None):\n if cache is None:\n cache = {}\n\n key = cache.get(id(self), str(self) + ' (#' + str(counter) + ')')\n cache[id(self)] = key\n\n if self._dirty or self._subtree_dirty() or self._always_dirty:\n key += '(dirty)'\n\n ret = {key: []}\n counter += 1\n\n if self._dependencies:\n for call, deps in six.iteritems(self._dependencies):\n # callable node\n if hasattr(call, '_node_wrapper') and \\\n call._node_wrapper is not None:\n val, counter = call._node_wrapper._print(counter, cache)\n ret[key].append(val)\n\n # args\n for arg in deps[0]:\n val, counter = arg._print(counter, cache)\n ret[key].append(val)\n\n # kwargs\n for kwarg in six.itervalues(deps[1]):\n val, counter = kwarg._print(counter, cache)\n ret[key].append(val)\n\n return ret, counter\n\n def print(self):\n return self._print(0, {})[0]\n\n def graph(self):\n return self.print()\n\n def graphviz(self):\n d = self.graph()\n\n from graphviz import Digraph\n dot = Digraph(self._name, strict=True)\n dot.format = 'png'\n\n def rec(nodes, parent):\n for d in nodes:\n if not isinstance(d, dict):\n if '(dirty)' in d:\n dot.node(d.replace('(dirty)', ''), color='red')\n dot.edge(d.replace('(dirty)', ''), parent.replace('(dirty)', ''), color='red')\n else:\n dot.node(d)\n dot.edge(d, parent.replace('(dirty)', ''))\n else:\n for k in d:\n if '(dirty)' in k:\n dot.node(k.replace('(dirty)', ''), color='red')\n rec(d[k], k)\n dot.edge(k.replace('(dirty)', ''), parent.replace('(dirty)', ''), color='red')\n else:\n dot.node(k)\n rec(d[k], k)\n dot.edge(k, parent.replace('(dirty)', ''))\n\n for k in d:\n if '(dirty)' in k:\n dot.node(k.replace('(dirty)', ''), color='red')\n else:\n dot.node(k)\n rec(d[k], k)\n return dot\n\n def networkx(self):\n d = self.graph()\n # FIXME deduplicate\n from pygraphviz import AGraph\n import networkx as nx\n dot = AGraph(strict=True, directed=True)\n\n def rec(nodes, parent):\n for d in nodes:\n if not isinstance(d, dict):\n if '(dirty)' in d:\n d = d.replace('(dirty)', '')\n dot.add_node(d, label=d, color='red')\n dot.add_edge(d, parent, color='red')\n else:\n dot.add_node(d, label=d)\n dot.add_edge(d, parent)\n else:\n for k in d:\n if '(dirty)' in k:\n k = k.replace('(dirty)', '')\n dot.add_node(k, label=k, color='red')\n rec(d[k], k)\n dot.add_edge(k, parent, color='red')\n else:\n dot.add_node(k, label=k)\n rec(d[k], k)\n dot.add_edge(k, parent)\n\n for k in d:\n dot.add_node(k, label=k)\n rec(d[k], k)\n return nx.nx_agraph.from_agraph(dot)\n\n def __call__(self):\n self._recompute()\n return self.value()\n\n def __add__(self, other):\n other = self._tonode(other)\n if isinstance(self._self_reference, _Node):\n return self._gennode(self._name + '+' + other._name, (lambda x, y: x.value() + y.value()), [self._self_reference, other], self._trace or other._trace)\n return self._gennode(self._name + '+' + other._name, (lambda x, y: x.value() + y.value()), [self, other], self._trace or other._trace)\n\n __radd__ = __add__\n\n def __sub__(self, other):\n other = self._tonode(other)\n if isinstance(self._self_reference, _Node):\n return self._gennode(self._name + '-' + other._name, (lambda x, y: x.value() - y.value()), [self._self_reference, other], self._trace or other._trace)\n return self._gennode(self._name + '-' + other._name, (lambda x, y: x.value() - y.value()), [self, other], self._trace or other._trace)\n\n __rsub__ = __sub__\n\n def __mul__(self, other):\n other = self._tonode(other)\n if isinstance(self._self_reference, _Node):\n return self._gennode(self._name + '*' + other._name, (lambda x, y: x.value() * y.value()), [self._self_reference, other], self._trace or other._trace)\n return self._gennode(self._name + '*' + other._name, (lambda x, y: x.value() * y.value()), [self, other], self._trace or other._trace)\n\n __rmul__ = __mul__\n\n def __div__(self, other):\n other = self._tonode(other)\n if isinstance(self._self_reference, _Node):\n return self._gennode(self._name + '/' + other._name, (lambda x, y: x.value() / y.value()), [self._self_reference, other], self._trace or other._trace)\n return self._gennode(self._name + '/' + other._name, (lambda x, y: x.value() / y.value()), [self, other], self._trace or other._trace)\n\n __rdiv__ = __div__\n\n def __truediv__(self, other):\n other = self._tonode(other)\n if isinstance(self._self_reference, _Node):\n return self._gennode(self._name + '/' + other._name, (lambda x, y: x.value() / y.value()), [self._self_reference, other], self._trace or other._trace)\n return self._gennode(self._name + '/' + other._name, (lambda x, y: x.value() / y.value()), [self, other], self._trace or other._trace)\n\n __rtruediv__ = __truediv__\n\n def __pow__(self, other):\n other = self._tonode(other)\n if isinstance(self._self_reference, _Node):\n return self._gennode(self._name + '^' + other._name, (lambda x, y: x.value() ** y.value()), [self._self_reference, other], self._trace or other._trace)\n return self._gennode(self._name + '^' + other._name, (lambda x, y: x.value() ** y.value()), [self, other], self._trace or other._trace)\n\n def sin(self):\n return self._gennode('sin(' + self._name + ')', (lambda x: math.sin(self.value())), [self], self._trace)\n\n def cos(self):\n return self._gennode('cos(' + self._name + ')', (lambda x: math.cos(self.value())), [self], self._trace)\n\n def tan(self):\n return self._gennode('tan(' + self._name + ')', (lambda x: math.tan(self.value())), [self], self._trace)\n\n def arcsin(self):\n return self._gennode('sin(' + self._name + ')', (lambda x: math.arcsin(self.value())), [self], self._trace)\n\n def arccos(self):\n return self._gennode('arccos(' + self._name + ')', (lambda x: math.arccos(self.value())), [self], self._trace)\n\n def arctan(self):\n return self._gennode('arctan(' + self._name + ')', (lambda x: math.arctan(self.value())), [self], self._trace)\n\n def sqrt(self):\n return self._gennode('sqrt(' + self._name + ')', (lambda x: math.sqrt(self.value())), [self], self._trace)\n\n def log(self):\n return self._gennode('log(' + self._name + ')', (lambda x: math.log(self.value())), [self], self._trace)\n\n def exp(self):\n return self._gennode('exp(' + self._name + ')', (lambda x: math.exp(self.value())), [self], self._trace)\n\n def erf(self):\n return self._gennode('erf(' + self._name + ')', (lambda x: math.erf(self.value())), [self], self._trace)\n\n def __float__(self):\n return self._gennode('float(' + self._name + ')', (lambda x: float(self.value())), [self], self._trace)\n\n def __int__(self):\n return self._gennode('int(' + self._name + ')', (lambda x: int(self.value())), [self], self._trace)\n\n def __len__(self):\n return self._gennode('len(' + self._name + ')', (lambda x: len(self.value())), [self], self._trace)\n\n def __array_ufunc__(self, ufunc, method, *inputs, **kwargs):\n if ufunc == np.add:\n if isinstance(inputs[0], _Node):\n return inputs[0].__add__(inputs[1])\n else:\n return inputs[1].__add__(inputs[0])\n elif ufunc == np.subtract:\n if isinstance(inputs[0], _Node):\n return inputs[0].__sub__(inputs[1])\n else:\n return inputs[1].__sub__(inputs[0])\n elif ufunc == np.multiply:\n if isinstance(inputs[0], _Node):\n return inputs[0].__mul__(inputs[1])\n else:\n return inputs[1].__mul__(inputs[0])\n elif ufunc == np.divide:\n if isinstance(inputs[0], _Node):\n return inputs[0].__truedivide__(inputs[1])\n else:\n return inputs[1].__truedivide__(inputs[0])\n elif ufunc == np.sin:\n return inputs[0].sin()\n elif ufunc == np.cos:\n return inputs[0].cos()\n elif ufunc == np.tan:\n return inputs[0].tan()\n elif ufunc == np.arcsin:\n return inputs[0].arcsin()\n elif ufunc == np.arccos:\n return inputs[0].arccos()\n elif ufunc == np.arctan:\n return inputs[0].arctan()\n elif ufunc == np.exp:\n return inputs[0].exp()\n elif ufunc == sp.special.erf:\n return inputs[0].erf()\n else:\n raise NotImplementedError('Not Implemented!')\n\n def __neg__(self):\n return self._gennode('(-' + self._name + ')', (lambda x: -self.value()), [self], self._trace)\n\n def __bool__(self):\n if self.value() is None:\n return False\n return self.value()\n\n __nonzero__ = __bool__ # Py2 compat\n\n def __eq__(self, other):\n if isinstance(other, _Node) and super(_Node, self).__eq__(other):\n return True\n\n other = self._tonode(other)\n if isinstance(self._self_reference, _Node):\n return self._gennode(self._name + '==' + other._name, (lambda x, y: x() == y()), [self._self_reference, other], self._trace or other._trace)\n return self._gennode(self._name + '==' + other._name, (lambda x, y: x() == y()), [self, other], self._trace or other._trace)\n\n def __ne__(self, other):\n if isinstance(other, _Node) and super(_Node, self).__eq__(other):\n return False\n\n other = self._tonode(other)\n if isinstance(self._self_reference, _Node):\n return self._gennode(self._name + '!=' + other._name, (lambda x, y: x() != y()), [self._self_reference, other], self._trace or other._trace)\n return self._gennode(self._name + '!=' + other._name, (lambda x, y: x() != y()), [self, other], self._trace or other._trace)\n\n def __ge__(self, other):\n if isinstance(other, _Node) and super(_Node, self).__eq__(other):\n return True\n\n other = self._tonode(other)\n if isinstance(self._self_reference, _Node):\n return self._gennode(self._name + '>=' + other._name, (lambda x, y: x() >= y()), [self._self_reference, other], self._trace or other._trace)\n return self._gennode(self._name + '>=' + other._name, (lambda x, y: x() >= y()), [self, other], self._trace or other._trace)\n\n def __gt__(self, other):\n if isinstance(other, _Node) and super(_Node, self).__eq__(other):\n return False\n\n other = self._tonode(other)\n if isinstance(self._self_reference, _Node):\n return self._gennode(self._name + '>' + other._name, (lambda x, y: x() > y()), [self._self_reference, other], self._trace or other._trace)\n return self._gennode(self._name + '>' + other._name, (lambda x, y: x() > y()), [self, other], self._trace or other._trace)\n\n def __le__(self, other):\n if isinstance(other, _Node) and super(_Node, self).__eq__(other):\n return True\n\n other = self._tonode(other)\n if isinstance(self._self_reference, _Node):\n return self._gennode(self._name + '<=' + other._name, (lambda x, y: x() <= y()), [self._self_reference, other], self._trace or other._trace)\n return self._gennode(self._name + '<=' + other._name, (lambda x, y: x() <= y()), [self, other], self._trace or other._trace)\n\n def __lt__(self, other):\n if isinstance(other, _Node) and super(_Node, self).__eq__(other):\n return False\n other = self._tonode(other)\n if isinstance(self._self_reference, _Node):\n return self._gennode(self._name + '<' + other._name, (lambda x, y: x() < y()), [self._self_reference, other], self._trace or other._trace)\n return self._gennode(self._name + '<' + other._name, (lambda x, y: x() < y()), [self, other], self._trace or other._trace)\n\n def __repr__(self):\n return self._name\n\n\nclass BaseClass(object):\n def __init__(self, *args, **kwargs):\n pass\n\n def node(self, name, readonly=False, nullable=True, default_or_starting_value=None, trace=False):\n if not hasattr(self, '_BaseClass__nodes'):\n self.__nodes = {}\n\n if name not in self.__nodes:\n self.__nodes[name] = _Node(name=name,\n derived=False,\n readonly=readonly,\n nullable=nullable,\n default_or_starting_value=default_or_starting_value,\n trace=trace)\n setattr(self, name, self.__nodes[name])\n return self.__nodes[name]\n\n def __getattribute__(self, name):\n if name == '_BaseClass__nodes' or name == '__nodes':\n return super(BaseClass, self).__getattribute__(name)\n elif hasattr(self, '_BaseClass__nodes') and name in super(BaseClass, self).__getattribute__('_BaseClass__nodes'):\n # return super(BaseClass, self).__getattribute__('_BaseClass__nodes')[name]._value\n return super(BaseClass, self).__getattribute__('_BaseClass__nodes')[name]\n else:\n return super(BaseClass, self).__getattribute__(name)\n\n def __setattr__(self, name, value):\n if hasattr(self, '_BaseClass__nodes') and name in super(BaseClass, self).__getattribute__('_BaseClass__nodes'):\n node = super(BaseClass, self).__getattribute__('_BaseClass__nodes')[name]\n if isinstance(value, _Node) and node == value:\n return\n elif isinstance(value, _Node):\n raise Exception('Cannot set to node')\n else:\n node._dirty = (node._value != value) or abs(node._value - value) > 10**-5\n node._value = value\n else:\n super(BaseClass, self).__setattr__(name, value)\n\n\ndef _either_type(f):\n @functools.wraps(f)\n def new_dec(*args, **kwargs):\n if len(args) == 1 and len(kwargs) == 0 and callable(args[0]):\n # actual decorated function\n return f(args[0])\n else:\n # decorator arguments\n return lambda realf: f(realf, *args, **kwargs)\n return new_dec\n\n\n@_either_type\ndef node(meth, memoize=True, trace=False):\n argspec = inspect.getfullargspec(meth)\n # args = argspec.args\n # varargs = argspec.varargs\n # varkw = argspec.varkw\n # defaults = argspec.defaults\n # kwonlyargs = argspec.kwonlyargs\n # kwonlydefaults = args.kwonlydefaults\n\n if argspec.varargs:\n raise Exception('varargs not supported yet!')\n if argspec.varkw:\n raise Exception('varargs not supported yet!')\n\n node_args = []\n node_kwargs = {}\n is_method = False\n\n for i, arg in enumerate(argspec.args):\n if arg == 'self':\n # TODO\n is_method = True\n continue\n\n if (is_method and len(argspec.defaults or []) >= i) or \\\n (not is_method and len(argspec.defaults or []) > i):\n default_or_starting_value = argspec.defaults[0]\n nullable = True\n else:\n default_or_starting_value = None\n nullable = False\n\n node_args.append(_Node(name=arg,\n derived=True,\n readonly=False,\n nullable=nullable,\n default_or_starting_value=default_or_starting_value,\n trace=trace))\n\n for k, v in six.iteritems(argspec.kwonlydefaults or {}):\n node_kwargs[k] = _Node(name=k,\n derived=True,\n readonly=False,\n nullable=True,\n default_or_starting_value=v,\n trace=trace)\n\n def meth_wrapper(self, *args, **kwargs):\n if len(args) > len(node_args):\n raise Exception('Missing args (call or preprocessing error has occurred)')\n\n if len(kwargs) > len(node_kwargs):\n raise Exception('Missing kwargs (call or preprocessing error has occurred)')\n\n if is_method:\n val = meth(self, *(arg.value() for arg in args), **kwargs)\n else:\n val = meth(*(arg.value() for arg in args), **kwargs)\n return val\n\n new_node = _Node(name=meth.__name__,\n derived=True,\n callable=meth_wrapper,\n callable_args=node_args,\n callable_kwargs=node_kwargs,\n callable_is_method=is_method,\n always_dirty=not memoize,\n trace=trace)\n\n if is_method:\n ret = lambda self, *args, **kwargs: new_node._with_self(self) # noqa: E731\n else:\n ret = lambda *args, **kwargs: new_node # noqa: E731\n\n ret._node_wrapper = new_node\n return ret\n","sub_path":"tributary/lazy/base.py","file_name":"base.py","file_ext":"py","file_size_in_byte":23460,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"636234926","text":"from django.shortcuts import render\nfrom django.http import HttpRequest\nfrom django.http import HttpResponse\nfrom django.views.decorators.csrf import csrf_exempt\nimport operator\n\n@csrf_exempt\ndef view(request):\n return render(request, 'view.html')\n@csrf_exempt\ndef count(request):\n wordCount = request.POST['wordContent']\n wordList = wordCount.split()\n wordDictionary = {}\n for word in wordList:\n if word in wordDictionary:\n wordDictionary[word] += 1\n else:\n wordDictionary[word] = 1\n maxWord = 'No words entered' if not wordDictionary else max(wordDictionary, key=wordDictionary.get)\n sortedWords = sorted(wordDictionary.items(), key=operator.itemgetter(1), reverse=True)\n return render(request, 'count.html',{'wordContent': wordCount, 'wordList': wordList, 'wordListLength': len(wordList), 'wordDict': sortedWords, 'maxWord': maxWord})","sub_path":"wordcounter/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":897,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"93497106","text":"import socket\nimport ssl\nimport packet\n\n# 可配置的参数信息\n## 服务器信息\ndst_addr = \"uc21.yealink.com\"\ndst_port = 8090\n\n## 一次请求服务器返回的数据部分大小\nreq_data_size = 50*1024*1024\n## 请求的次数限制\nreq_count_limit = 1\n## 发起的请求报文中数据部分大小\nreq_packet_size = 128\n\nclass client_ssl:\n def send_request(self,):\n #CA_FILE = \"ca.crt\"\n #KEY_FILE = \"client.key\"\n #CERT_FILE = \"client.crt\"\n\n context = ssl.SSLContext(ssl.PROTOCOL_TLS)\n context.check_hostname = False\n #context.load_cert_chain(certfile=CERT_FILE, keyfile=KEY_FILE)\n #context.load_verify_locations(CA_FILE)\n #context.verify_mode = ssl.CERT_REQUIRED\n \n # 与服务端建立socket连接\n with socket.socket() as sock:\n # 将socket打包成SSL socket\n with context.wrap_socket(sock, server_side=False) as ssock:\n ssock.connect((dst_addr, dst_port))\n i = 0\n while True:\n # 向服务端发送信息\n if i > req_count_limit:\n break\n\n msg = packet.encode_client_request(req_data_size, req_packet_size)\n ssock.send(msg)\n # 接收服务端返回的信息\n\n recv_len = 0\n recv_buf_size = ssock.getsockopt(socket.SOL_SOCKET, socket.SO_RCVBUF)\n packet_head = None\n while True:\n if recv_len >= req_data_size:\n break\n\n msg = ssock.recv(2048)\n if not len(msg):\n break\n\n if not packet_head:\n packet_head = packet.decode_server_response(msg)\n if len(msg) < packet.server_rsp_packet_head_size:\n break\n recv_len = len(msg) - packet.server_rsp_packet_head_size\n\n else:\n recv_len += len(msg)\n print(f\"\\t recv_len:[{recv_len} bytes] rsp_id:[{packet_head[0]}] req_id[{packet.client_req_packet_id}]\")\n if packet.print_server_rsp_packet_detail:\n packet.print_packet(\"\", msg)\n ssock.close()\n\nif __name__ == \"__main__\":\n client = client_ssl()\n client.send_request()\n","sub_path":"tls/client.py","file_name":"client.py","file_ext":"py","file_size_in_byte":2511,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"331707145","text":"import requests as rq\nfrom bs4 import BeautifulSoup\nfrom flask import request, make_response\nfrom flask_restful import Resource\nimport pandas as pd\nimport json\nfrom flask import Response\nimport numpy as np\n\nfrom rest_api.service import createData, checkRobots, findAllUrl, dfToJson, createDataTag\n\n\nclass Scrap_page(Resource):\n def get(self,url,prefix,check):\n url = url.replace(\"X\", \"/\")\n tmp = str(url).find(\"/\")\n if tmp > 0:\n main_url = str(url)[0:tmp]\n else:\n main_url = url\n url_rob = prefix + \"://\" + main_url + \"/robots.txt\"\n disallow = checkRobots(url_rob)\n if \"*\" in disallow:\n return Response({\"Error\": \"This page can't scrap\"}, status=200, mimetype='application/json')\n try:\n url_1=prefix+\"://\"+url\n page = rq.get(url_1)\n soup = BeautifulSoup(page.content, 'html.parser')\n next_p=[]\n if check==\"True\":\n tag_a= soup.find_all(\"a\")\n next_p=findAllUrl(tag_a,disallow,main_url)\n\n columns =['tag', 'class', 'value']\n data= pd.DataFrame(columns=columns)\n data = data.fillna(0)\n if not next_p:\n elm =soup.find_all()\n data = createData(elm, data)\n df=dfToJson(data)\n return Response(df, mimetype='application/json')\n else:\n tmp_2=str(url)[tmp:len(url)]\n tmp_2 = tmp_2.replace(\"/\",\"\",1)\n if tmp_2 not in next_p:\n next_p.append(tmp_2)\n next_p.remove(\"#\")\n for postfix in next_p:\n page = rq.get(prefix+\"://\"+main_url+\"/\"+postfix)\n soup = BeautifulSoup(page.content, 'html.parser')\n elm =soup.find_all()\n data = createData(elm, data)\n df= dfToJson(data)\n return Response(df, mimetype='application/json')\n except:\n return Response({},status=400, mimetype='application/json')\n\nclass Download_data(Resource):\n def post(self):\n data = request.get_data()\n data=data.decode(\"utf8\")\n if str(data).startswith(\"b\"):\n data = str(data).replace(\"b\",\"\",1)\n data= data.replace(\"'\",\"\").replace(\"\\\\n\",\" \")\n data = json.loads(data)\n columns =['tag', 'class', 'value']\n df= pd.DataFrame(columns=columns)\n for i in data:\n df=df.append({'tag':i[\"element\"],'class':i[\"classes\"],'value':i[\"value\"]},ignore_index=True)\n output = make_response(df.to_csv())\n output.headers[\"Content-Disposition\"] = \"attachment; filename=export.csv\"\n output.headers[\"Content-Type\"] = \"text/csv\"\n return output\n\n\nclass Scrap_from_tag(Resource):\n def post(self):\n body= request.get_data()\n if str(body).startswith(\"b\"):\n body = str(body).replace(\"b\",\"\",1)\n if str(body).startswith(\"'\"):\n body= body.replace(\"'\",\"\")\n js = json.loads(body)\n try:\n page = rq.get(js['url'])\n soup = BeautifulSoup(page.content, 'html.parser')\n href = soup.find_all('a', href=True)\n pages=[]\n for h in href:\n if str(h.attrs.get(\"href\")).find(\"page\")>0:\n pages.append(str(h.attrs.get(\"href\")))\n elm =soup.find_all(js['tag'], {\"class\": js['classes']})\n data = createDataTag(elm)\n if pages !=[]:\n next_page= pages[len(pages)-1]\n else:\n next_page =\"#\"\n while next_page != \"#\":\n url = str(js['url'])\n if url.startswith(\"https\"):\n tmp = str(url).find(\"/\",9,len(url))\n if tmp > 0:\n url = str(url)[0:tmp]\n elif url.startswith(\"http\"):\n tmp = str(url).find(\"/\",8,len(url))\n if tmp > 0:\n url = str(url)[0:tmp]\n next_p = url+next_page\n page = rq.get(next_p)\n soup = BeautifulSoup(page.content, 'html.parser')\n elm =soup.find_all(js['tag'], {\"class\": js['classes']})\n d= createDataTag(elm)\n for index, row in d.iterrows():\n l = len(data)\n row[\"id\"]=l+1\n data= data.append(row, ignore_index=True)\n href = soup.find_all('a', href=True)\n pages=[]\n for h in href:\n if str(h.attrs.get(\"href\")).find(\"page\")>0 or str(h.attrs.get(\"href\"))==\"#\":\n pages.append(str(h.attrs.get(\"href\")))\n next_page= pages[len(pages)-1]\n data.drop(\" \", inplace=True, axis=1)\n data = data.loc[:,data.isin([\"\",None,\"NULL\",\"null\",0,np.nan]).mean()<.6]\n #data.to_csv(\"test.csv\")\n df=dfToJson(data)\n\n return Response(df, mimetype='application/json')\n except:\n return Response({},status=400, mimetype='application/json')\n","sub_path":"rest_api/scrap.py","file_name":"scrap.py","file_ext":"py","file_size_in_byte":5157,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"530705096","text":"#!/usr/bin/env python\nimport netCDF4 as nc\nimport numpy as np\nimport sys\n\ndef fix_rodepth(infile):\n \"\"\"\n Simple script to enforce rodepth = 1 at missing values\n \"\"\"\n with nc.Dataset(infile, 'r+') as f:\n rodepth= f.variables['rodepth'][:]\n idx = rodepth == 0\n if np.any(idx):\n print(\"Switching zeros to 1\")\n rodepth[idx] = 1\n f.variables['rodepth'][:] = rodepth\n \nif __name__ == \"__main__\":\n fix_rodepth(sys.argv[1])\n","sub_path":"agrif/fix_rivers_month.py","file_name":"fix_rivers_month.py","file_ext":"py","file_size_in_byte":488,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"370697221","text":"import unittest\nimport urlparse\nimport json\n\nfrom leonardo import graph\n\nfrom . import DATA_DIR\n\n\nclass GraphTest(unittest.TestCase):\n \n maxDiff = None\n\n def test_graph_init(self):\n g = graph.GraphiteGraph(\"%s/cpu.graph\" % DATA_DIR)\n self.assertEqual( g.properties.get(\"title\") , \"Combined CPU Usage\")\n\n def test_url(self):\n g = graph.GraphiteGraph(\"%s/cpu.graph\" % DATA_DIR)\n parts = urlparse.parse_qs( g.url(), keep_blank_values=True)\n self.assertEqual ( parts, \n { 'from' : ['-1hour'], \n 'target': ['cactiStyle(alias(sumSeries(collectd.server-1.cpu.*.cpu.wait.value),\"IO Wait\"),\"si\")', \n 'cactiStyle(alias(sumSeries(collectd.server-1.cpu.*.cpu.system.value),\"System\"),\"si\")', \n 'cactiStyle(alias(sumSeries(collectd.server-1.cpu.*.cpu.user.value),\"User\"),\"si\")'], \n 'title': ['Combined CPU Usage'], \n 'areaMode': ['stacked'], \n 'height': ['None'], \n 'width': ['None'], \n 'vtitle': ['percent'], \n 'until': ['Now']\n }\n )\n\n def test_get_graph_spec(self):\n g = graph.GraphiteGraph(\"%s/cpu.graph\" % DATA_DIR)\n expected_result = { u'url': u'title=Combined CPU Usage&vtitle=percent&from=-1hour&width=None&height=None&until=Now&areaMode=stacked&target=cactiStyle(alias(sumSeries(collectd.server-1.cpu.*.cpu.wait.value),\"IO Wait\"),\"si\")&target=cactiStyle(alias(sumSeries(collectd.server-1.cpu.*.cpu.system.value),\"System\"),\"si\")&target=cactiStyle(alias(sumSeries(collectd.server-1.cpu.*.cpu.user.value),\"User\"),\"si\")&format=json',\n u'properties':\n { u'ymaxright': None,\n u'yunit_system': None,\n u'height': None,\n u'hide_y_axis': None,\n u'timezone': None,\n u'hide_axes': None,\n u'ymin': None,\n u'background_color': None,\n u'vtitle_right': None,\n u'draw_null_as_zero': False,\n u'fontbold': False,\n u'linewidth': None,\n u'from': u'-1hour',\n u'ymax': None,\n u'title': u'Combined CPU Usage',\n u'minor_grid_line_color': None,\n u'foreground_color': None,\n u'width': None,\n u'theme': None,\n u'area_alpha': None,\n u'hide_grid': None,\n u'until': u'Now',\n u'linemode': None,\n u'description': u'The combined CPU usage',\n u'graphtype': None,\n u'fontsize': None,\n u'vtitle': u'percent',\n u'logbase': None,\n u'placeholders': None,\n u'surpress': False,\n u'yminright': None,\n u'major_grid_line_color': None,\n u'area': u'stacked',\n u'unique_legend': None,\n u'fontname': None,\n u'xformat': None,\n u'hide_legend': None}}\n\n self.assertEqual( expected_result, g.get_graph_spec() )\n\n","sub_path":"tests/test_graph.py","file_name":"test_graph.py","file_ext":"py","file_size_in_byte":3938,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"571531988","text":"# Copyright (c) 2014 Hewlett-Packard Development Company, L.P.\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\n# implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport argparse\nimport logging\nimport sys\n\nfrom cliff import app\nfrom cliff import commandmanager as cm\nfrom cliff import help\n\n\nclass DockstackApp(app.App):\n\n log = logging.getLogger(__name__)\n\n def __init__(self):\n super(DockstackApp, self).__init__(\n description='Docker-based OpenStack Development Environment',\n version='',\n command_manager=cm.CommandManager('dockstack.cmd'),\n )\n self.CONSOLE_MESSAGE_FORMAT = '%(levelname)s|%(name)s|%(message)s'\n self.LOG_FILE_MESSAGE_FORMAT = ('[%(asctime)s]|' +\n self.CONSOLE_MESSAGE_FORMAT)\n\n def build_option_parser(self, description, version,\n argparse_kwargs=None):\n \"\"\"Return an argparse option parser for this application.\n\n Subclasses may override this method to extend\n the parser with more global options.\n\n :param description: full description of the application\n :paramtype description: str\n :param version: version number for the application\n :paramtype version: str\n :param argparse_kwargs: extra keyword argument passed to the\n ArgumentParser constructor\n :paramtype extra_kwargs: dict\n \"\"\"\n argparse_kwargs = argparse_kwargs or {}\n parser = argparse.ArgumentParser(\n description=description,\n add_help=False,\n **argparse_kwargs\n )\n parser.add_argument(\n '--log-file',\n action='store',\n default=None,\n help='Specify a file to log output. Disabled by default.',\n )\n parser.add_argument(\n '-q', '--quiet',\n action='store_true',\n dest='quiet',\n default=False,\n help='Suppress output except warnings and errors.',\n )\n parser.add_argument(\n '-h', '--help',\n action=help.HelpAction,\n nargs=0,\n default=self, # tricky\n help=\"Show this help message and exit.\",\n )\n parser.add_argument(\n '-d', '--debug',\n default=False,\n action='store_true',\n help='Show debug output.',\n )\n return parser\n\n def configure_logging(self):\n \"\"\"Create logging handlers for any log output.\n \"\"\"\n root_logger = logging.getLogger('')\n\n if self.options.debug:\n root_logger.setLevel(logging.DEBUG)\n elif self.options.quiet:\n root_logger.setLevel(logging.WARN)\n else:\n root_logger.setLevel(logging.INFO)\n\n # Set up logging to a file\n if self.options.log_file:\n file_handler = logging.FileHandler(\n filename=self.options.log_file,\n )\n formatter = logging.Formatter(self.LOG_FILE_MESSAGE_FORMAT)\n file_handler.setFormatter(formatter)\n root_logger.addHandler(file_handler)\n\n # Always send higher-level messages to the console via stderr\n console = logging.StreamHandler(self.stderr)\n formatter = logging.Formatter(self.CONSOLE_MESSAGE_FORMAT)\n console.setFormatter(formatter)\n root_logger.addHandler(console)\n return\n\n\ndef main(argv=sys.argv[1:]):\n app = DockstackApp()\n return app.run(argv)\n","sub_path":"dockstack/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3984,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"175952448","text":"from math import *\nfrom scipy.optimize import fsolve\nimport numpy as np\n\nclass bsimbulk:\n \"\"\"\n BSIM-BULK 107.0.0 model\n \"\"\"\n ntype = 1\n q = 1.60219e-19\n EPS0 = 8.85418e-12\n KboQ = 8.617087e-5 # Joule/degree\n P_CELSIUS0 = 273.15\n Oneby3 = 0.33333333333333333\n DELTA_1 = 0.02\n REFTEMP = 300.15 # 27 degrees C\n EXPL_THRESHOLD = 80.0\n MAX_EXPL = 5.540622384e34\n MIN_EXPL = 1.804851387e-35\n M_PI = 3.14159265358979323846\n\n def __repr__(self):\n return f\"A bsimbulk class\"\n\n # Clamped exponential function\n def lexp(self, x):\n if (x > 80.0):\n return 5.540622384e34 * (1.0 + x - 80.0)\n elif (x < -80.0):\n return 1.804851387e-35\n else:\n return exp(x)\n\n # Smoothing def for (max of x, x0 with deltax)\n def Smooth(self, x, x0, deltax):\n return 0.5 * (x + x0 + sqrt((x - x0) * (x - x0) + 0.25 * deltax * deltax))\n\n # Smoothing def for (min of x, x0 with deltax)\n def Smooth2(self, x, x0, deltax):\n return 0.5 * (x + x0 - sqrt((x - x0) * (x - x0) + 0.25 * deltax * deltax)) + 0.25 * deltax\n\n # Clamped log function\n def lln(self, x):\n return log(max(x, 1.0e-38))\n\n # Hyperbolic smoothing function\n def hypsmooth(self, x, c):\n return 0.5 * (x + sqrt(x * x + 4.0 * c * c))\n\n # Junction capacitance macro between S/D and bulk\n def JunCap(self, Czbx, Vbx_jct, PBX_t, MJX, czbx_p1, czbx_p2):\n if (Czbx > 0.0):\n T1 = Vbx_jct / PBX_t\n if (T1 < 0.9):\n arg = 1.0 - T1\n if (MJX == 0.5):\n sarg = 1.0 / sqrt(arg)\n else:\n sarg = self.lexp(-MJX * self.lln(arg))\n return PBX_t * Czbx * (1.0 - arg * sarg) / (1.0 - MJX)\n else:\n T2 = czbx_p1 * (T1 - 1.0) * (5.0 * MJX * (T1 - 1.0) + (1.0 + MJX))\n return PBX_t * Czbx * (T2 + czbx_p2)\n else:\n return 0.0\n\n # Normalized pinch-off voltage including PD\n def PO_psip(self, vg_vfb, gamma, DPD):\n T1 = 1.0 + DPD\n vgfbPD = vg_vfb / T1\n gammaPD = gamma / T1\n T1 = 0.5 * vgfbPD - 3.0 * (1.0 + gammaPD / 1.41421356237309504880)\n T2 = T1 + sqrt(T1 * T1 + 6.0 * vgfbPD)\n if (vgfbPD < 0.0):\n T3 = (vgfbPD - T2) / gammaPD\n return -self.lln(1.0 - T2 + T3 * T3)\n else:\n T3 = self.lexp(-T2)\n T1 = 0.5 * gammaPD\n T2 = sqrt(vgfbPD - 1.0 + T3 + T1 * T1) - T1\n return T2 * T2 + 1.0 - T3\n\n # Normalized charge-voltage relationship\n def BSIM_q(self, psip, phib, vch, gam):\n T8 = 0.5 * (psip + 1.0 + sqrt((psip - 1.0) * (psip - 1.0) + 0.25 * 2.0 * 2.0))\n sqrtpsip = sqrt(T8)\n T9 = 1.0 + gam / (2.0 * sqrtpsip)\n T0 = (1.0 + (gam / (2.0 * sqrtpsip))) / gam\n T1 = psip - 2.0 * phib - vch\n T2 = T1 - self.lln(4.0 * T0 * sqrtpsip)\n T8 = 0.5 * (T2 - 0.201491 - sqrt(T2 * (T2 + 0.402982) + 2.446562))\n sqrtpsisa = sqrtpsip\n if (T8 <= -68.0):\n T4 = -100.0\n T5 = 20.0\n if (T8 < T4 - 0.5 * T5):\n T3 = self.lexp(T4)\n else:\n if (T8 > T4 + 0.5 * T5):\n T3 = self.lexp(T8)\n else:\n T2 = (T8 - T4) / T5\n T6 = T2 * T2\n T3 = self.lexp(T4 + T5 * ((5.0 / 64.0) + 0.5 * T2 + T6 * ((15.0 / 16.0) - T6 * (1.25 - T6))))\n return T3 * (1.0 + T1 - T8 - self.lln(2.0 * T0 * (T3 * 2.0 * T0 + 2.0 * sqrtpsisa)))\n else:\n T3 = self.lexp(T8)\n sqrtpsisainv = 1.0 / sqrtpsisa\n T4 = 2.0 * T3 + self.lln(T3 * 2.0 * T0 * (T3 * 2.0 * T0 + 2.0 * sqrtpsisa)) - T1\n T5 = 2.0 + (1.0 / T3) + (T0 + sqrtpsisainv) / (T0 * T3 + sqrtpsisa)\n T3 = T3 - T4 / T5\n T4 = 2.0 * T3 + self.lln(T3 * 2.0 * T0 * (T3 * 2.0 * T0 + 2.0 * sqrtpsisa)) - T1\n T5 = 2.0 + (1.0 / T3) + (T0 + sqrtpsisainv) / (T0 * T3 + sqrtpsisa)\n T6 = ((T0 + sqrtpsisainv) / (T0 * T3 + sqrtpsisa)) * ((T0 + sqrtpsisainv) / (T0 * T3 + sqrtpsisa))\n T7 = -((1.0 / T3) * (1.0 / T3)) - (1.0 / (sqrtpsisa * sqrtpsisa * sqrtpsisa * (T0 * T3 + sqrtpsisa))) - T6\n return T3 - (T4 / T5) * (1.0 + T4 * T7 / (2.0 * T5 * T5))\n\n # Define GEOMOD and RGEOMOD in the modelcard\n def BSIMBULKNumFingerDiff(self, nf, minSD):\n if (nf % 2) != 0:\n nuEndD = 1\n nuIntD = 2 * max((nf - 1) / 2, 0)\n nuEndS = 1\n nuIntS = nuIntD\n else:\n if (minSD == 1):\n nuEndD = 2\n nuIntD = 2 * max((nf / 2 - 1), 0.0)\n nuEndS = 0\n nuIntS = nf\n else:\n nuEndD = 0\n nuIntD = nf\n nuEndS = 2\n nuIntS = 2 * max((nf / 2 - 1), 0)\n return nuEndD, nuIntD, nuEndS, nuIntS\n\n def BSIMBULKRdsEndIso(self, Weffcj, Rsh, DMCG, DMCI, DMDG, nuEnd, rgeo, SRCFLAG):\n if (SRCFLAG == 1):\n if (rgeo == 1) or (rgeo == 2) or (rgeo == 5):\n if (nuEnd == 0):\n Rend = 0.0\n else:\n Rend = Rsh * DMCG / (Weffcj * nuEnd)\n elif (rgeo == 3) or (rgeo == 4) or (rgeo == 6):\n if ((DMCG + DMCI) == 0.0):\n print(\"(DMCG + DMCI) can not be equal to zero\")\n if (nuEnd == 0):\n Rend = 0.0\n else:\n Rend = Rsh * Weffcj / (3.0 * nuEnd * (DMCG + DMCI))\n else:\n print(\"Warning: (instance %M) Specified RGEO = %d not matched (self.BSIMBULKRdsEndIso), Rend is set to zero.\", rgeo)\n Rend = 0.0\n else:\n if (rgeo == 1) or (rgeo == 3) or (rgeo == 7):\n if (nuEnd == 0):\n Rend = 0.0\n else:\n Rend = Rsh * DMCG / (Weffcj * nuEnd)\n elif (rgeo == 2) or (rgeo == 4) or (rgeo == 8):\n if ((DMCG + DMCI) == 0.0):\n print(\"(DMCG + DMCI) can not be equal to zero\")\n if (nuEnd == 0):\n Rend = 0.0\n else:\n Rend = Rsh * Weffcj / (3.0 * nuEnd * (DMCG + DMCI))\n else:\n print(\"Warning: (instance %M) Specified RGEO=%d not matched (self.BSIMBULKRdsEndIso type 2), Rend is set to zero.\", rgeo)\n Rend = 0.0\n return Rend\n\n def BSIMBULKRdsEndSha(self, Weffcj, Rsh, DMCG, DMCI, DMDG, nuEnd, rgeo, SRCFLAG):\n if (SRCFLAG == 1):\n if (rgeo == 1) or (rgeo == 2) or (rgeo == 5):\n if (nuEnd == 0):\n Rend = 0.0\n else:\n Rend = Rsh * DMCG / (Weffcj * nuEnd)\n elif (rgeo == 3) or (rgeo == 4) or (rgeo == 6):\n if (DMCG == 0.0):\n print(\"DMCG can not be equal to zero\")\n if (nuEnd == 0):\n Rend = 0.0\n else:\n Rend = Rsh * Weffcj / (6.0 * nuEnd * DMCG)\n else:\n print(\"Warning: (instance %M) Specified RGEO = %d not matched (self.BSIMBULKRdsEndSha), Rend is set to zero.\", rgeo)\n Rend = 0.0\n else:\n if (rgeo == 1) or (rgeo == 3) or (rgeo == 7):\n if (nuEnd == 0):\n Rend = 0.0\n else:\n Rend = Rsh * DMCG / (Weffcj * nuEnd)\n elif (rgeo == 2) or (rgeo == 4) or (rgeo == 8):\n if (DMCG == 0.0):\n print(\"DMCG can not be equal to zero\")\n if (nuEnd == 0):\n Rend = 0.0\n else:\n Rend = Rsh * Weffcj / (6.0 * nuEnd * DMCG)\n else:\n print(\"Warning: (instance %M) Specified RGEO=%d not matched (self.BSIMBULKRdsEndSha type 2), Rend is set to zero.\", rgeo)\n Rend = 0.0\n return Rend\n\n def BSIMBULKRdseffGeo(self, nf, geo, rgeo, minSD, Weffcj, Rsh, DMCG, DMCI, DMDG, SRCFLAG):\n if (geo < 9):\n nuEndD, nuIntD, nuEndS, nuIntS = self.BSIMBULKNumFingerDiff(nf, minSD)\n if (SRCFLAG == 1):\n if (nuIntS == 0):\n Rint = 0.0\n else:\n Rint = Rsh * DMCG / ( Weffcj * nuIntS)\n else:\n if (nuIntD == 0):\n Rint = 0.0\n else:\n Rint = Rsh * DMCG / ( Weffcj * nuIntD)\n if (geo == 0):\n if (SRCFLAG == 1):\n Rend = self.BSIMBULKRdsEndIso(Weffcj, Rsh, DMCG, DMCI, DMDG, nuEndS, rgeo, 1)\n else:\n Rend = self.BSIMBULKRdsEndIso(Weffcj, Rsh, DMCG, DMCI, DMDG, nuEndD, rgeo, 0)\n elif (geo == 1):\n if (SRCFLAG == 1):\n Rend = self.BSIMBULKRdsEndIso(Weffcj, Rsh, DMCG, DMCI, DMDG, nuEndS, rgeo, 1)\n else:\n Rend = self.BSIMBULKRdsEndSha(Weffcj, Rsh, DMCG, DMCI, DMDG, nuEndD, rgeo, 0)\n elif (geo == 2):\n if (SRCFLAG == 1):\n Rend = self.BSIMBULKRdsEndSha(Weffcj, Rsh, DMCG, DMCI, DMDG, nuEndS, rgeo, 1)\n else:\n Rend = self.BSIMBULKRdsEndIso(Weffcj, Rsh, DMCG, DMCI, DMDG, nuEndD, rgeo, 0)\n elif (geo == 3):\n if (SRCFLAG == 1):\n Rend = self.BSIMBULKRdsEndSha(Weffcj, Rsh, DMCG, DMCI, DMDG, nuEndS, rgeo, 1)\n else:\n Rend = self.BSIMBULKRdsEndSha(Weffcj, Rsh, DMCG, DMCI, DMDG, nuEndD, rgeo, 0)\n elif (geo == 4):\n if (SRCFLAG == 1):\n Rend = self.BSIMBULKRdsEndIso(Weffcj, Rsh, DMCG, DMCI, DMDG, nuEndS, rgeo, 1)\n else:\n Rend = Rsh * DMDG / Weffcj\n elif (geo == 5):\n if (SRCFLAG == 1):\n Rend = self.BSIMBULKRdsEndSha(Weffcj, Rsh, DMCG, DMCI, DMDG, nuEndS, rgeo, 1)\n else:\n if (nuEndD == 0):\n Rend = 0.0\n else:\n Rend = Rsh * DMDG / (Weffcj * nuEndD)\n elif (geo == 6):\n if (SRCFLAG == 1):\n Rend = Rsh * DMDG / Weffcj\n else:\n Rend = self.BSIMBULKRdsEndIso(Weffcj, Rsh, DMCG, DMCI, DMDG, nuEndD, rgeo, 0)\n elif (geo == 7):\n if (SRCFLAG == 1):\n if (nuEndS == 0):\n Rend = 0.0\n else:\n Rend = Rsh * DMDG / (Weffcj * nuEndS)\n else:\n Rend = self.BSIMBULKRdsEndSha(Weffcj, Rsh, DMCG, DMCI, DMDG, nuEndD, rgeo, 0)\n elif (geo == 8):\n Rend = Rsh * DMDG / Weffcj\n elif (geo == 9): # all wide contacts assumed for geo = 9 and 10\n if (SRCFLAG == 1):\n Rend = 0.5 * Rsh * DMCG / Weffcj\n if (nf == 2):\n Rint = 0.0\n else:\n Rint = Rsh * DMCG / (Weffcj * (nf - 2.0))\n else:\n Rend = 0.0\n Rint = Rsh * DMCG / (Weffcj * nf)\n elif (geo == 10):\n if (SRCFLAG == 1):\n Rend = 0.0\n Rint = Rsh * DMCG / (Weffcj * nf)\n else:\n Rend = 0.5 * Rsh * DMCG / Weffcj\n if (nf == 2):\n Rint = 0.0\n else:\n Rint = Rsh * DMCG / (Weffcj * (nf - 2.0))\n else:\n print(\"Warning: (instance %M) Specified GEO=%d not matched (self.BSIMBULKRdseffGeo), Rint is set to zero.\", geo)\n Rint = 0.0\n if (Rint <= 0.0):\n Rtot = Rend\n elif (Rend <= 0.0):\n Rtot = Rint\n else:\n Rtot = Rint * Rend / (Rint + Rend)\n if (Rtot == 0.0):\n print(\"Warning: (instance %M) Zero resistance returned from RdseffGeo\")\n return Rtot\n\n # Effective PS, PD, AS, AD calculation, Ref: BSIM4\n def BSIMBULKPAeffGeo(self, nf, geo, minSD, Weffcj, DMCG, DMCI, DMDG):\n if (geo < 9):\n nuEndD, nuIntD, nuEndS, nuIntS = self.BSIMBULKNumFingerDiff(nf, minSD)\n T0 = DMCG + DMCI\n T1 = DMCG + DMCG\n T2 = DMDG + DMDG\n PSiso = T0 + T0 + Weffcj\n PDiso = T0 + T0 + Weffcj\n PSsha = T1\n PDsha = T1\n PSmer = T2\n PDmer = T2\n ASiso = T0 * Weffcj\n ADiso = T0 * Weffcj\n ASsha = DMCG * Weffcj\n ADsha = DMCG * Weffcj\n ASmer = DMDG * Weffcj\n ADmer = DMDG * Weffcj\n if (geo == 0):\n Ps = nuEndS * PSiso + nuIntS * PSsha\n Pd = nuEndD * PDiso + nuIntD * PDsha\n As = nuEndS * ASiso + nuIntS * ASsha\n Ad = nuEndD * ADiso + nuIntD * ADsha\n elif (geo == 1):\n Ps = nuEndS * PSiso + nuIntS * PSsha\n Pd = (nuEndD + nuIntD) * PDsha\n As = nuEndS * ASiso + nuIntS * ASsha\n Ad = (nuEndD + nuIntD) * ADsha\n elif (geo == 2):\n Ps = (nuEndS + nuIntS) * PSsha\n Pd = nuEndD * PDiso + nuIntD * PDsha\n As = (nuEndS + nuIntS) * ASsha\n Ad = nuEndD * ADiso + nuIntD * ADsha\n elif (geo == 3):\n Ps = (nuEndS + nuIntS) * PSsha\n Pd = (nuEndD + nuIntD) * PDsha\n As = (nuEndS + nuIntS) * ASsha\n Ad = (nuEndD + nuIntD) * ADsha\n elif (geo == 4):\n Ps = nuEndS * PSiso + nuIntS * PSsha\n Pd = nuEndD * PDmer + nuIntD * PDsha\n As = nuEndS * ASiso + nuIntS * ASsha\n Ad = nuEndD * ADmer + nuIntD * ADsha\n elif (geo == 5):\n Ps = (nuEndS + nuIntS) * PSsha\n Pd = nuEndD * PDmer + nuIntD * PDsha\n As = (nuEndS + nuIntS) * ASsha\n Ad = nuEndD * ADmer + nuIntD * ADsha\n elif (geo == 6):\n Ps = nuEndS * PSmer + nuIntS * PSsha\n Pd = nuEndD * PDiso + nuIntD * PDsha\n As = nuEndS * ASmer + nuIntS * ASsha\n Ad = nuEndD * ADiso + nuIntD * ADsha\n elif (geo == 7):\n Ps = nuEndS * PSmer + nuIntS * PSsha\n Pd = (nuEndD + nuIntD) * PDsha\n As = nuEndS * ASmer + nuIntS * ASsha\n Ad = (nuEndD + nuIntD) * ADsha\n elif (geo == 8):\n Ps = nuEndS * PSmer + nuIntS * PSsha\n Pd = nuEndD * PDmer + nuIntD * PDsha\n As = nuEndS * ASmer + nuIntS * ASsha\n Ad = nuEndD * ADmer + nuIntD * ADsha\n elif (geo == 9):\n Ps = PSiso + (nf - 1.0) * PSsha\n Pd = nf * PDsha\n As = ASiso + (nf - 1.0) * ASsha\n Ad = nf * ADsha\n elif (geo == 10):\n Ps = nf * PSsha\n Pd = PDiso + (nf - 1.0) * PDsha\n As = nf * ASsha\n Ad = ADiso + (nf - 1.0) * ADsha\n else:\n print(\"Warning: (instance %M) Specified GEO=%d not matched (self.BSIMBULKPAeffGeo), PS,PD,AS,AD set to zero.\", geo)\n Ps = 0\n Pd = 0\n As = 0\n Ad = 0\n return Ps, Pd, As, Ad\n\n # Set param ungiven first, then call param_update()\n def __init__(self):\n self.VDgiven = False\n self.VGgiven = False\n self.VSgiven = False\n self.VBgiven = False\n self.TEMPgiven = False\n self.Lgiven = False\n self.Wgiven = False\n self.NFgiven = False\n self.NRSgiven = False\n self.NRDgiven = False\n self.VFBSDOFFgiven = False\n self.MINZgiven = False\n self.RGATEMODgiven = False\n self.RBODYMODgiven = False\n self.GEOMODgiven = False\n self.RGEOMODgiven = False\n self.RBPBgiven = False\n self.RBPDgiven = False\n self.RBPSgiven = False\n self.RBDBgiven = False\n self.RBSBgiven = False\n self.SAgiven = False\n self.SBgiven = False\n self.SDgiven = False\n self.SCAgiven = False\n self.SCBgiven = False\n self.SCCgiven = False\n self.SCgiven = False\n self.ASgiven = False\n self.ADgiven = False\n self.PSgiven = False\n self.PDgiven = False\n self.XGWgiven = False\n self.NGCONgiven = False\n self.DTEMPgiven = False\n self.MULU0given = False\n self.DELVTOgiven = False\n self.IDS0MULTgiven = False\n self.EDGEFETgiven = False\n self.SSLMODgiven = False\n self.TYPEgiven = False\n self.CVMODgiven = False\n self.COVMODgiven = False\n self.RDSMODgiven = False\n self.WPEMODgiven = False\n self.ASYMMODgiven = False\n self.GIDLMODgiven = False\n self.IGCMODgiven = False\n self.IGBMODgiven = False\n self.TNOIMODgiven = False\n self.SHMODgiven = False\n self.MOBSCALEgiven = False\n self.LLONGgiven = False\n self.LMLTgiven = False\n self.WMLTgiven = False\n self.XLgiven = False\n self.WWIDEgiven = False\n self.XWgiven = False\n self.LINTgiven = False\n self.LLgiven = False\n self.LWgiven = False\n self.LWLgiven = False\n self.LLNgiven = False\n self.LWNgiven = False\n self.WINTgiven = False\n self.WLgiven = False\n self.WWgiven = False\n self.WWLgiven = False\n self.WLNgiven = False\n self.WWNgiven = False\n self.DLCgiven = False\n self.LLCgiven = False\n self.LWCgiven = False\n self.LWLCgiven = False\n self.DWCgiven = False\n self.WLCgiven = False\n self.WWCgiven = False\n self.WWLCgiven = False\n self.TOXEgiven = False\n self.TOXPgiven = False\n self.DTOXgiven = False\n self.NDEPgiven = False\n self.NDEPL1given = False\n self.NDEPLEXP1given = False\n self.NDEPL2given = False\n self.NDEPLEXP2given = False\n self.NDEPWgiven = False\n self.NDEPWEXPgiven = False\n self.NDEPWLgiven = False\n self.NDEPWLEXPgiven = False\n self.LNDEPgiven = False\n self.WNDEPgiven = False\n self.PNDEPgiven = False\n self.NDEPCVgiven = False\n self.NDEPCVL1given = False\n self.NDEPCVLEXP1given = False\n self.NDEPCVL2given = False\n self.NDEPCVLEXP2given = False\n self.NDEPCVWgiven = False\n self.NDEPCVWEXPgiven = False\n self.NDEPCVWLgiven = False\n self.NDEPCVWLEXPgiven = False\n self.LNDEPCVgiven = False\n self.WNDEPCVgiven = False\n self.PNDEPCVgiven = False\n self.NGATEgiven = False\n self.LNGATEgiven = False\n self.WNGATEgiven = False\n self.PNGATEgiven = False\n self.EASUBgiven = False\n self.NI0SUBgiven = False\n self.BG0SUBgiven = False\n self.EPSRSUBgiven = False\n self.EPSROXgiven = False\n self.XJgiven = False\n self.LXJgiven = False\n self.WXJgiven = False\n self.PXJgiven = False\n self.VFBgiven = False\n self.LVFBgiven = False\n self.WVFBgiven = False\n self.PVFBgiven = False\n self.VFBCVgiven = False\n self.LVFBCVgiven = False\n self.WVFBCVgiven = False\n self.PVFBCVgiven = False\n self.VFBCVLgiven = False\n self.VFBCVLEXPgiven = False\n self.VFBCVWgiven = False\n self.VFBCVWEXPgiven = False\n self.VFBCVWLgiven = False\n self.VFBCVWLEXPgiven = False\n self.DELVFBACCgiven = False\n self.PERMODgiven = False\n self.DWJgiven = False\n self.NSDgiven = False\n self.LNSDgiven = False\n self.WNSDgiven = False\n self.PNSDgiven = False\n self.DVTP0given = False\n self.LDVTP0given = False\n self.WDVTP0given = False\n self.PDVTP0given = False\n self.DVTP1given = False\n self.LDVTP1given = False\n self.WDVTP1given = False\n self.PDVTP1given = False\n self.DVTP2given = False\n self.LDVTP2given = False\n self.WDVTP2given = False\n self.PDVTP2given = False\n self.DVTP3given = False\n self.LDVTP3given = False\n self.WDVTP3given = False\n self.PDVTP3given = False\n self.DVTP4given = False\n self.LDVTP4given = False\n self.WDVTP4given = False\n self.PDVTP4given = False\n self.DVTP5given = False\n self.LDVTP5given = False\n self.WDVTP5given = False\n self.PDVTP5given = False\n self.PHINgiven = False\n self.LPHINgiven = False\n self.WPHINgiven = False\n self.PPHINgiven = False\n self.ETA0given = False\n self.LETA0given = False\n self.WETA0given = False\n self.PETA0given = False\n self.ETA0Rgiven = False\n self.LETA0Rgiven = False\n self.WETA0Rgiven = False\n self.PETA0Rgiven = False\n self.DSUBgiven = False\n self.ETABgiven = False\n self.ETABEXPgiven = False\n self.LETABgiven = False\n self.WETABgiven = False\n self.PETABgiven = False\n self.K1given = False\n self.K1Lgiven = False\n self.K1LEXPgiven = False\n self.K1Wgiven = False\n self.K1WEXPgiven = False\n self.K1WLgiven = False\n self.K1WLEXPgiven = False\n self.LK1given = False\n self.WK1given = False\n self.PK1given = False\n self.K2given = False\n self.K2Lgiven = False\n self.K2LEXPgiven = False\n self.K2Wgiven = False\n self.K2WEXPgiven = False\n self.K2WLgiven = False\n self.K2WLEXPgiven = False\n self.LK2given = False\n self.WK2given = False\n self.PK2given = False\n self.ADOSgiven = False\n self.BDOSgiven = False\n self.QM0given = False\n self.ETAQMgiven = False\n self.CITgiven = False\n self.LCITgiven = False\n self.WCITgiven = False\n self.PCITgiven = False\n self.NFACTORgiven = False\n self.NFACTORLgiven = False\n self.NFACTORLEXPgiven = False\n self.NFACTORWgiven = False\n self.NFACTORWEXPgiven = False\n self.NFACTORWLgiven = False\n self.NFACTORWLEXPgiven = False\n self.LNFACTORgiven = False\n self.WNFACTORgiven = False\n self.PNFACTORgiven = False\n self.CDSCDgiven = False\n self.CDSCDLgiven = False\n self.CDSCDLEXPgiven = False\n self.LCDSCDgiven = False\n self.WCDSCDgiven = False\n self.PCDSCDgiven = False\n self.CDSCDRgiven = False\n self.CDSCDLRgiven = False\n self.LCDSCDRgiven = False\n self.WCDSCDRgiven = False\n self.PCDSCDRgiven = False\n self.CDSCBgiven = False\n self.CDSCBLgiven = False\n self.CDSCBLEXPgiven = False\n self.LCDSCBgiven = False\n self.WCDSCBgiven = False\n self.PCDSCBgiven = False\n self.VSATgiven = False\n self.LVSATgiven = False\n self.WVSATgiven = False\n self.PVSATgiven = False\n self.VSATLgiven = False\n self.VSATLEXPgiven = False\n self.VSATWgiven = False\n self.VSATWEXPgiven = False\n self.VSATWLgiven = False\n self.VSATWLEXPgiven = False\n self.VSATRgiven = False\n self.LVSATRgiven = False\n self.WVSATRgiven = False\n self.PVSATRgiven = False\n self.DELTAgiven = False\n self.LDELTAgiven = False\n self.WDELTAgiven = False\n self.PDELTAgiven = False\n self.DELTALgiven = False\n self.DELTALEXPgiven = False\n self.VSATCVgiven = False\n self.LVSATCVgiven = False\n self.WVSATCVgiven = False\n self.PVSATCVgiven = False\n self.VSATCVLgiven = False\n self.VSATCVLEXPgiven = False\n self.VSATCVWgiven = False\n self.VSATCVWEXPgiven = False\n self.VSATCVWLgiven = False\n self.VSATCVWLEXPgiven = False\n self.UP1given = False\n self.LP1given = False\n self.UP2given = False\n self.LP2given = False\n self.U0given = False\n self.U0Lgiven = False\n self.U0LEXPgiven = False\n self.LU0given = False\n self.WU0given = False\n self.PU0given = False\n self.U0Rgiven = False\n self.LU0Rgiven = False\n self.WU0Rgiven = False\n self.PU0Rgiven = False\n self.ETAMOBgiven = False\n self.UAgiven = False\n self.UALgiven = False\n self.UALEXPgiven = False\n self.UAWgiven = False\n self.UAWEXPgiven = False\n self.UAWLgiven = False\n self.UAWLEXPgiven = False\n self.LUAgiven = False\n self.WUAgiven = False\n self.PUAgiven = False\n self.UARgiven = False\n self.LUARgiven = False\n self.WUARgiven = False\n self.PUARgiven = False\n self.EUgiven = False\n self.LEUgiven = False\n self.WEUgiven = False\n self.PEUgiven = False\n self.EULgiven = False\n self.EULEXPgiven = False\n self.EUWgiven = False\n self.EUWEXPgiven = False\n self.EUWLgiven = False\n self.EUWLEXPgiven = False\n self.UDgiven = False\n self.UDLgiven = False\n self.UDLEXPgiven = False\n self.LUDgiven = False\n self.WUDgiven = False\n self.PUDgiven = False\n self.UDRgiven = False\n self.LUDRgiven = False\n self.WUDRgiven = False\n self.PUDRgiven = False\n self.UCSgiven = False\n self.LUCSgiven = False\n self.WUCSgiven = False\n self.PUCSgiven = False\n self.UCSRgiven = False\n self.LUCSRgiven = False\n self.WUCSRgiven = False\n self.PUCSRgiven = False\n self.UCgiven = False\n self.UCLgiven = False\n self.UCLEXPgiven = False\n self.UCWgiven = False\n self.UCWEXPgiven = False\n self.UCWLgiven = False\n self.UCWLEXPgiven = False\n self.LUCgiven = False\n self.WUCgiven = False\n self.PUCgiven = False\n self.UCRgiven = False\n self.LUCRgiven = False\n self.WUCRgiven = False\n self.PUCRgiven = False\n self.PCLMgiven = False\n self.PCLMLgiven = False\n self.PCLMLEXPgiven = False\n self.LPCLMgiven = False\n self.WPCLMgiven = False\n self.PPCLMgiven = False\n self.PCLMRgiven = False\n self.LPCLMRgiven = False\n self.WPCLMRgiven = False\n self.PPCLMRgiven = False\n self.PCLMGgiven = False\n self.PCLMCVgiven = False\n self.PCLMCVLgiven = False\n self.PCLMCVLEXPgiven = False\n self.LPCLMCVgiven = False\n self.WPCLMCVgiven = False\n self.PPCLMCVgiven = False\n self.PSCBE1given = False\n self.LPSCBE1given = False\n self.WPSCBE1given = False\n self.PPSCBE1given = False\n self.PSCBE2given = False\n self.LPSCBE2given = False\n self.WPSCBE2given = False\n self.PPSCBE2given = False\n self.PDITSgiven = False\n self.LPDITSgiven = False\n self.WPDITSgiven = False\n self.PPDITSgiven = False\n self.PDITSLgiven = False\n self.PDITSDgiven = False\n self.LPDITSDgiven = False\n self.WPDITSDgiven = False\n self.PPDITSDgiven = False\n self.RSHgiven = False\n self.PRWGgiven = False\n self.LPRWGgiven = False\n self.WPRWGgiven = False\n self.PPRWGgiven = False\n self.PRWBgiven = False\n self.LPRWBgiven = False\n self.WPRWBgiven = False\n self.PPRWBgiven = False\n self.PRWBLgiven = False\n self.PRWBLEXPgiven = False\n self.WRgiven = False\n self.LWRgiven = False\n self.WWRgiven = False\n self.PWRgiven = False\n self.RSWMINgiven = False\n self.LRSWMINgiven = False\n self.WRSWMINgiven = False\n self.PRSWMINgiven = False\n self.RSWgiven = False\n self.LRSWgiven = False\n self.WRSWgiven = False\n self.PRSWgiven = False\n self.RSWLgiven = False\n self.RSWLEXPgiven = False\n self.RDWMINgiven = False\n self.LRDWMINgiven = False\n self.WRDWMINgiven = False\n self.PRDWMINgiven = False\n self.RDWgiven = False\n self.LRDWgiven = False\n self.WRDWgiven = False\n self.PRDWgiven = False\n self.RDWLgiven = False\n self.RDWLEXPgiven = False\n self.RDSWMINgiven = False\n self.LRDSWMINgiven = False\n self.WRDSWMINgiven = False\n self.PRDSWMINgiven = False\n self.RDSWgiven = False\n self.RDSWLgiven = False\n self.RDSWLEXPgiven = False\n self.LRDSWgiven = False\n self.WRDSWgiven = False\n self.PRDSWgiven = False\n self.PSATgiven = False\n self.LPSATgiven = False\n self.WPSATgiven = False\n self.PPSATgiven = False\n self.PSATLgiven = False\n self.PSATLEXPgiven = False\n self.PSATBgiven = False\n self.PSATRgiven = False\n self.LPSATRgiven = False\n self.WPSATRgiven = False\n self.PPSATRgiven = False\n self.LPSATBgiven = False\n self.WPSATBgiven = False\n self.PPSATBgiven = False\n self.PSATXgiven = False\n self.PTWGgiven = False\n self.LPTWGgiven = False\n self.WPTWGgiven = False\n self.PPTWGgiven = False\n self.PTWGLgiven = False\n self.PTWGLEXPgiven = False\n self.PTWGRgiven = False\n self.LPTWGRgiven = False\n self.WPTWGRgiven = False\n self.PPTWGRgiven = False\n self.PTWGLRgiven = False\n self.PTWGLEXPRgiven = False\n self.A1given = False\n self.LA1given = False\n self.WA1given = False\n self.PA1given = False\n self.A11given = False\n self.LA11given = False\n self.WA11given = False\n self.PA11given = False\n self.A2given = False\n self.LA2given = False\n self.WA2given = False\n self.PA2given = False\n self.A21given = False\n self.LA21given = False\n self.WA21given = False\n self.PA21given = False\n self.PDIBLCgiven = False\n self.PDIBLCLgiven = False\n self.PDIBLCLEXPgiven = False\n self.LPDIBLCgiven = False\n self.WPDIBLCgiven = False\n self.PPDIBLCgiven = False\n self.PDIBLCRgiven = False\n self.PDIBLCLRgiven = False\n self.PDIBLCLEXPRgiven = False\n self.LPDIBLCRgiven = False\n self.WPDIBLCRgiven = False\n self.PPDIBLCRgiven = False\n self.PDIBLCBgiven = False\n self.LPDIBLCBgiven = False\n self.WPDIBLCBgiven = False\n self.PPDIBLCBgiven = False\n self.PVAGgiven = False\n self.LPVAGgiven = False\n self.WPVAGgiven = False\n self.PPVAGgiven = False\n self.FPROUTgiven = False\n self.FPROUTLgiven = False\n self.FPROUTLEXPgiven = False\n self.LFPROUTgiven = False\n self.WFPROUTgiven = False\n self.PFPROUTgiven = False\n self.ALPHA0given = False\n self.ALPHA0Lgiven = False\n self.ALPHA0LEXPgiven = False\n self.LALPHA0given = False\n self.WALPHA0given = False\n self.PALPHA0given = False\n self.BETA0given = False\n self.LBETA0given = False\n self.WBETA0given = False\n self.PBETA0given = False\n self.AIGBACCgiven = False\n self.BIGBACCgiven = False\n self.CIGBACCgiven = False\n self.NIGBACCgiven = False\n self.AIGBINVgiven = False\n self.BIGBINVgiven = False\n self.CIGBINVgiven = False\n self.EIGBINVgiven = False\n self.NIGBINVgiven = False\n self.AIGCgiven = False\n self.BIGCgiven = False\n self.CIGCgiven = False\n self.AIGSgiven = False\n self.BIGSgiven = False\n self.CIGSgiven = False\n self.AIGDgiven = False\n self.BIGDgiven = False\n self.CIGDgiven = False\n self.DLCIGgiven = False\n self.DLCIGDgiven = False\n self.POXEDGEgiven = False\n self.NTOXgiven = False\n self.TOXREFgiven = False\n self.PIGCDgiven = False\n self.AIGCLgiven = False\n self.AIGCWgiven = False\n self.AIGSLgiven = False\n self.AIGSWgiven = False\n self.AIGDLgiven = False\n self.AIGDWgiven = False\n self.PIGCDLgiven = False\n self.LAIGBINVgiven = False\n self.WAIGBINVgiven = False\n self.PAIGBINVgiven = False\n self.LBIGBINVgiven = False\n self.WBIGBINVgiven = False\n self.PBIGBINVgiven = False\n self.LCIGBINVgiven = False\n self.WCIGBINVgiven = False\n self.PCIGBINVgiven = False\n self.LEIGBINVgiven = False\n self.WEIGBINVgiven = False\n self.PEIGBINVgiven = False\n self.LNIGBINVgiven = False\n self.WNIGBINVgiven = False\n self.PNIGBINVgiven = False\n self.LAIGBACCgiven = False\n self.WAIGBACCgiven = False\n self.PAIGBACCgiven = False\n self.LBIGBACCgiven = False\n self.WBIGBACCgiven = False\n self.PBIGBACCgiven = False\n self.LCIGBACCgiven = False\n self.WCIGBACCgiven = False\n self.PCIGBACCgiven = False\n self.LNIGBACCgiven = False\n self.WNIGBACCgiven = False\n self.PNIGBACCgiven = False\n self.LAIGCgiven = False\n self.WAIGCgiven = False\n self.PAIGCgiven = False\n self.LBIGCgiven = False\n self.WBIGCgiven = False\n self.PBIGCgiven = False\n self.LCIGCgiven = False\n self.WCIGCgiven = False\n self.PCIGCgiven = False\n self.LAIGSgiven = False\n self.WAIGSgiven = False\n self.PAIGSgiven = False\n self.LBIGSgiven = False\n self.WBIGSgiven = False\n self.PBIGSgiven = False\n self.LCIGSgiven = False\n self.WCIGSgiven = False\n self.PCIGSgiven = False\n self.LAIGDgiven = False\n self.WAIGDgiven = False\n self.PAIGDgiven = False\n self.LBIGDgiven = False\n self.WBIGDgiven = False\n self.PBIGDgiven = False\n self.LCIGDgiven = False\n self.WCIGDgiven = False\n self.PCIGDgiven = False\n self.LPOXEDGEgiven = False\n self.WPOXEDGEgiven = False\n self.PPOXEDGEgiven = False\n self.LDLCIGgiven = False\n self.WDLCIGgiven = False\n self.PDLCIGgiven = False\n self.LDLCIGDgiven = False\n self.WDLCIGDgiven = False\n self.PDLCIGDgiven = False\n self.LNTOXgiven = False\n self.WNTOXgiven = False\n self.PNTOXgiven = False\n self.AGIDLgiven = False\n self.AGIDLLgiven = False\n self.AGIDLWgiven = False\n self.LAGIDLgiven = False\n self.WAGIDLgiven = False\n self.PAGIDLgiven = False\n self.BGIDLgiven = False\n self.LBGIDLgiven = False\n self.WBGIDLgiven = False\n self.PBGIDLgiven = False\n self.CGIDLgiven = False\n self.LCGIDLgiven = False\n self.WCGIDLgiven = False\n self.PCGIDLgiven = False\n self.EGIDLgiven = False\n self.LEGIDLgiven = False\n self.WEGIDLgiven = False\n self.PEGIDLgiven = False\n self.AGISLgiven = False\n self.AGISLLgiven = False\n self.AGISLWgiven = False\n self.LAGISLgiven = False\n self.WAGISLgiven = False\n self.PAGISLgiven = False\n self.BGISLgiven = False\n self.LBGISLgiven = False\n self.WBGISLgiven = False\n self.PBGISLgiven = False\n self.CGISLgiven = False\n self.LCGISLgiven = False\n self.WCGISLgiven = False\n self.PCGISLgiven = False\n self.EGISLgiven = False\n self.LEGISLgiven = False\n self.WEGISLgiven = False\n self.PEGISLgiven = False\n self.CFgiven = False\n self.LCFgiven = False\n self.WCFgiven = False\n self.PCFgiven = False\n self.CFRCOEFFgiven = False\n self.CGSOgiven = False\n self.CGDOgiven = False\n self.CGBOgiven = False\n self.CGSLgiven = False\n self.LCGSLgiven = False\n self.WCGSLgiven = False\n self.PCGSLgiven = False\n self.CGDLgiven = False\n self.LCGDLgiven = False\n self.WCGDLgiven = False\n self.PCGDLgiven = False\n self.CKAPPASgiven = False\n self.LCKAPPASgiven = False\n self.WCKAPPASgiven = False\n self.PCKAPPASgiven = False\n self.CKAPPADgiven = False\n self.LCKAPPADgiven = False\n self.WCKAPPADgiven = False\n self.PCKAPPADgiven = False\n self.DMCGgiven = False\n self.DMCIgiven = False\n self.DMDGgiven = False\n self.DMCGTgiven = False\n self.XGLgiven = False\n self.RSHGgiven = False\n self.CJSgiven = False\n self.CJDgiven = False\n self.CJSWSgiven = False\n self.CJSWDgiven = False\n self.CJSWGSgiven = False\n self.CJSWGDgiven = False\n self.PBSgiven = False\n self.PBDgiven = False\n self.PBSWSgiven = False\n self.PBSWDgiven = False\n self.PBSWGSgiven = False\n self.PBSWGDgiven = False\n self.MJSgiven = False\n self.MJDgiven = False\n self.MJSWSgiven = False\n self.MJSWDgiven = False\n self.MJSWGSgiven = False\n self.MJSWGDgiven = False\n self.JSSgiven = False\n self.JSDgiven = False\n self.JSWSgiven = False\n self.JSWDgiven = False\n self.JSWGSgiven = False\n self.JSWGDgiven = False\n self.NJSgiven = False\n self.NJDgiven = False\n self.IJTHSFWDgiven = False\n self.IJTHDFWDgiven = False\n self.IJTHSREVgiven = False\n self.IJTHDREVgiven = False\n self.BVSgiven = False\n self.BVDgiven = False\n self.XJBVSgiven = False\n self.XJBVDgiven = False\n self.JTSSgiven = False\n self.JTSDgiven = False\n self.JTSSWSgiven = False\n self.JTSSWDgiven = False\n self.JTSSWGSgiven = False\n self.JTSSWGDgiven = False\n self.JTWEFFgiven = False\n self.NJTSgiven = False\n self.NJTSDgiven = False\n self.NJTSSWgiven = False\n self.NJTSSWDgiven = False\n self.NJTSSWGgiven = False\n self.NJTSSWGDgiven = False\n self.VTSSgiven = False\n self.VTSDgiven = False\n self.VTSSWSgiven = False\n self.VTSSWDgiven = False\n self.VTSSWGSgiven = False\n self.VTSSWGDgiven = False\n self.XRCRG1given = False\n self.XRCRG2given = False\n self.GBMINgiven = False\n self.RBPS0given = False\n self.RBPSLgiven = False\n self.RBPSWgiven = False\n self.RBPSNFgiven = False\n self.RBPD0given = False\n self.RBPDLgiven = False\n self.RBPDWgiven = False\n self.RBPDNFgiven = False\n self.RBPBX0given = False\n self.RBPBXLgiven = False\n self.RBPBXWgiven = False\n self.RBPBXNFgiven = False\n self.RBPBY0given = False\n self.RBPBYLgiven = False\n self.RBPBYWgiven = False\n self.RBPBYNFgiven = False\n self.RBSBX0given = False\n self.RBSBY0given = False\n self.RBDBX0given = False\n self.RBDBY0given = False\n self.RBSDBXLgiven = False\n self.RBSDBXWgiven = False\n self.RBSDBXNFgiven = False\n self.RBSDBYLgiven = False\n self.RBSDBYWgiven = False\n self.RBSDBYNFgiven = False\n self.EFgiven = False\n self.EMgiven = False\n self.NOIAgiven = False\n self.NOIBgiven = False\n self.NOICgiven = False\n self.LINTNOIgiven = False\n self.NOIA1given = False\n self.NOIAXgiven = False\n self.NTNOIgiven = False\n self.RNOIAgiven = False\n self.RNOIBgiven = False\n self.RNOICgiven = False\n self.TNOIAgiven = False\n self.TNOIBgiven = False\n self.TNOICgiven = False\n self.BINUNITgiven = False\n self.DLBINgiven = False\n self.DWBINgiven = False\n self.TNOMgiven = False\n self.TBGASUBgiven = False\n self.TBGBSUBgiven = False\n self.TNFACTORgiven = False\n self.UTEgiven = False\n self.LUTEgiven = False\n self.WUTEgiven = False\n self.PUTEgiven = False\n self.UTELgiven = False\n self.UA1given = False\n self.LUA1given = False\n self.WUA1given = False\n self.PUA1given = False\n self.UA1Lgiven = False\n self.UC1given = False\n self.LUC1given = False\n self.WUC1given = False\n self.PUC1given = False\n self.UD1given = False\n self.LUD1given = False\n self.WUD1given = False\n self.PUD1given = False\n self.UD1Lgiven = False\n self.EU1given = False\n self.LEU1given = False\n self.WEU1given = False\n self.PEU1given = False\n self.UCSTEgiven = False\n self.LUCSTEgiven = False\n self.WUCSTEgiven = False\n self.PUCSTEgiven = False\n self.TETA0given = False\n self.PRTgiven = False\n self.LPRTgiven = False\n self.WPRTgiven = False\n self.PPRTgiven = False\n self.ATgiven = False\n self.LATgiven = False\n self.WATgiven = False\n self.PATgiven = False\n self.ATLgiven = False\n self.TDELTAgiven = False\n self.PTWGTgiven = False\n self.LPTWGTgiven = False\n self.WPTWGTgiven = False\n self.PPTWGTgiven = False\n self.PTWGTLgiven = False\n self.KT1given = False\n self.KT1EXPgiven = False\n self.KT1Lgiven = False\n self.LKT1given = False\n self.WKT1given = False\n self.PKT1given = False\n self.KT2given = False\n self.LKT2given = False\n self.WKT2given = False\n self.PKT2given = False\n self.IITgiven = False\n self.LIITgiven = False\n self.WIITgiven = False\n self.PIITgiven = False\n self.IGTgiven = False\n self.LIGTgiven = False\n self.WIGTgiven = False\n self.PIGTgiven = False\n self.TGIDLgiven = False\n self.LTGIDLgiven = False\n self.WTGIDLgiven = False\n self.PTGIDLgiven = False\n self.TCJgiven = False\n self.TCJSWgiven = False\n self.TCJSWGgiven = False\n self.TPBgiven = False\n self.TPBSWgiven = False\n self.TPBSWGgiven = False\n self.XTISgiven = False\n self.XTIDgiven = False\n self.XTSSgiven = False\n self.XTSDgiven = False\n self.XTSSWSgiven = False\n self.XTSSWDgiven = False\n self.XTSSWGSgiven = False\n self.XTSSWGDgiven = False\n self.TNJTSgiven = False\n self.TNJTSDgiven = False\n self.TNJTSSWgiven = False\n self.TNJTSSWDgiven = False\n self.TNJTSSWGgiven = False\n self.TNJTSSWGDgiven = False\n self.RTH0given = False\n self.CTH0given = False\n self.WTH0given = False\n self.SAREFgiven = False\n self.SBREFgiven = False\n self.WLODgiven = False\n self.KU0given = False\n self.KVSATgiven = False\n self.TKU0given = False\n self.LKU0given = False\n self.WKU0given = False\n self.PKU0given = False\n self.LLODKU0given = False\n self.WLODKU0given = False\n self.KVTH0given = False\n self.LKVTH0given = False\n self.WKVTH0given = False\n self.PKVTH0given = False\n self.LLODVTHgiven = False\n self.WLODVTHgiven = False\n self.STK2given = False\n self.LODK2given = False\n self.STETA0given = False\n self.LODETA0given = False\n self.WEBgiven = False\n self.WECgiven = False\n self.KVTH0WEgiven = False\n self.LKVTH0WEgiven = False\n self.WKVTH0WEgiven = False\n self.PKVTH0WEgiven = False\n self.K2WEgiven = False\n self.LK2WEgiven = False\n self.WK2WEgiven = False\n self.PK2WEgiven = False\n self.KU0WEgiven = False\n self.LKU0WEgiven = False\n self.WKU0WEgiven = False\n self.PKU0WEgiven = False\n self.SCREFgiven = False\n self.SSL0given = False\n self.SSL1given = False\n self.SSL2given = False\n self.SSL3given = False\n self.SSL4given = False\n self.SSL5given = False\n self.SSLEXP1given = False\n self.SSLEXP2given = False\n self.AVDSXgiven = False\n self.WEDGEgiven = False\n self.DGAMMAEDGEgiven = False\n self.DGAMMAEDGELgiven = False\n self.DGAMMAEDGELEXPgiven = False\n self.DVTEDGEgiven = False\n self.NDEPEDGEgiven = False\n self.LNDEPEDGEgiven = False\n self.WNDEPEDGEgiven = False\n self.PNDEPEDGEgiven = False\n self.NFACTOREDGEgiven = False\n self.LNFACTOREDGEgiven = False\n self.WNFACTOREDGEgiven = False\n self.PNFACTOREDGEgiven = False\n self.CITEDGEgiven = False\n self.LCITEDGEgiven = False\n self.WCITEDGEgiven = False\n self.PCITEDGEgiven = False\n self.CDSCDEDGEgiven = False\n self.LCDSCDEDGEgiven = False\n self.WCDSCDEDGEgiven = False\n self.PCDSCDEDGEgiven = False\n self.CDSCBEDGEgiven = False\n self.LCDSCBEDGEgiven = False\n self.WCDSCBEDGEgiven = False\n self.PCDSCBEDGEgiven = False\n self.ETA0EDGEgiven = False\n self.LETA0EDGEgiven = False\n self.WETA0EDGEgiven = False\n self.PETA0EDGEgiven = False\n self.ETABEDGEgiven = False\n self.LETABEDGEgiven = False\n self.WETABEDGEgiven = False\n self.PETABEDGEgiven = False\n self.KT1EDGEgiven = False\n self.LKT1EDGEgiven = False\n self.WKT1EDGEgiven = False\n self.PKT1EDGEgiven = False\n self.KT1LEDGEgiven = False\n self.LKT1LEDGEgiven = False\n self.WKT1LEDGEgiven = False\n self.PKT1LEDGEgiven = False\n self.KT2EDGEgiven = False\n self.LKT2EDGEgiven = False\n self.WKT2EDGEgiven = False\n self.PKT2EDGEgiven = False\n self.KT1EXPEDGEgiven = False\n self.LKT1EXPEDGEgiven = False\n self.WKT1EXPEDGEgiven = False\n self.PKT1EXPEDGEgiven = False\n self.TNFACTOREDGEgiven = False\n self.LTNFACTOREDGEgiven = False\n self.WTNFACTOREDGEgiven = False\n self.PTNFACTOREDGEgiven = False\n self.TETA0EDGEgiven = False\n self.LTETA0EDGEgiven = False\n self.WTETA0EDGEgiven = False\n self.PTETA0EDGEgiven = False\n self.DVT0EDGEgiven = False\n self.DVT1EDGEgiven = False\n self.DVT2EDGEgiven = False\n self.K2EDGEgiven = False\n self.LK2EDGEgiven = False\n self.WK2EDGEgiven = False\n self.PK2EDGEgiven = False\n self.KVTH0EDGEgiven = False\n self.LKVTH0EDGEgiven = False\n self.WKVTH0EDGEgiven = False\n self.PKVTH0EDGEgiven = False\n self.STK2EDGEgiven = False\n self.LSTK2EDGEgiven = False\n self.WSTK2EDGEgiven = False\n self.PSTK2EDGEgiven = False\n self.STETA0EDGEgiven = False\n self.LSTETA0EDGEgiven = False\n self.WSTETA0EDGEgiven = False\n self.PSTETA0EDGEgiven = False\n self.IGCLAMPgiven = False\n self.LPgiven = False\n self.RNOIKgiven = False\n self.TNOIKgiven = False\n self.TNOIK2given = False\n self.K0given = False\n self.LK0given = False\n self.WK0given = False\n self.PK0given = False\n self.K01given = False\n self.LK01given = False\n self.WK01given = False\n self.PK01given = False\n self.M0given = False\n self.LM0given = False\n self.WM0given = False\n self.PM0given = False\n self.M01given = False\n self.LM01given = False\n self.WM01given = False\n self.PM01given = False\n self.NEDGEgiven = False\n self.NOIA1_EDGEgiven = False\n self.NOIAX_EDGEgiven = False\n self.FNOIMODgiven = False\n self.LHgiven = False\n self.NOIA2given = False\n self.HNDEPgiven = False\n self.ABULKgiven = False\n self.C0given = False\n self.LC0given = False\n self.WC0given = False\n self.PC0given = False\n self.C01given = False\n self.LC01given = False\n self.WC01given = False\n self.PC01given = False\n self.C0SIgiven = False\n self.LC0SIgiven = False\n self.WC0SIgiven = False\n self.PC0SIgiven = False\n self.C0SI1given = False\n self.LC0SI1given = False\n self.WC0SI1given = False\n self.PC0SI1given = False\n self.C0SISATgiven = False\n self.LC0SISATgiven = False\n self.WC0SISATgiven = False\n self.PC0SISATgiven = False\n self.C0SISAT1given = False\n self.LC0SISAT1given = False\n self.WC0SISAT1given = False\n self.PC0SISAT1given = False\n self.minrgiven = False\n self.HVMODgiven = False\n self.HVCAPgiven = False\n self.HVCAPSgiven = False\n self.IIMODgiven = False\n self.NDRIFTDgiven = False\n self.VDRIFTgiven = False\n self.MDRIFTgiven = False\n self.NDRIFTSgiven = False\n self.RDLCWgiven = False\n self.RSLCWgiven = False\n self.PDRWBgiven = False\n self.VFBDRIFTgiven = False\n self.VFBOVgiven = False\n self.LOVERgiven = False\n self.LOVERACCgiven = False\n self.NDRgiven = False\n self.SLHVgiven = False\n self.SLHV1given = False\n self.ALPHADRgiven = False\n self.BETADRgiven = False\n self.PRTHVgiven = False\n self.ATHVgiven = False\n self.HVFACTORgiven = False\n self.DRII1given = False\n self.DRII2given = False\n self.DELTAIIgiven = False\n self.par_update()\n\n # Param initialization and later update\n def par_update(self, **param):\n if 'VD' in param:\n self.VD = param['VD']\n self.VDgiven = True\n else:\n if self.VDgiven == False:\n self.VD = 1.0\n self.VDI = self.VD\n if 'VG' in param:\n self.VG = param['VG']\n self.VGgiven = True\n else:\n if self.VGgiven == False:\n self.VG = 1.0\n if 'VS' in param:\n self.VS = param['VS']\n self.VSgiven = True\n else:\n if self.VSgiven == False:\n self.VS = 0.0\n self.VSI = self.VS\n if 'VB' in param:\n self.VB = param['VB']\n self.VBgiven = True\n else:\n if self.VBgiven == False:\n self.VB = 0.0\n if 'TEMP' in param:\n self.TEMP = param['TEMP']\n self.TEMPgiven = True\n else:\n if self.TEMPgiven == False:\n self.TEMP = 25.0\n if 'L' in param:\n self.L = param['L']\n self.Lgiven = True\n elif 'L'.swapcase() in param:\n self.L = param['L'.swapcase()]\n self.Lgiven = True\n else:\n if self.Lgiven == False:\n self.L = 1e-05\n if 'W' in param:\n self.W = param['W']\n self.Wgiven = True\n elif 'W'.swapcase() in param:\n self.W = param['W'.swapcase()]\n self.Wgiven = True\n else:\n if self.Wgiven == False:\n self.W = 1e-05\n if 'NF' in param:\n self.NF = param['NF']\n self.NFgiven = True\n elif 'NF'.swapcase() in param:\n self.NF = param['NF'.swapcase()]\n self.NFgiven = True\n else:\n if self.NFgiven == False:\n self.NF = 1.0\n if 'NRS' in param:\n self.NRS = param['NRS']\n self.NRSgiven = True\n elif 'NRS'.swapcase() in param:\n self.NRS = param['NRS'.swapcase()]\n self.NRSgiven = True\n else:\n if self.NRSgiven == False:\n self.NRS = 1.0\n if 'NRD' in param:\n self.NRD = param['NRD']\n self.NRDgiven = True\n elif 'NRD'.swapcase() in param:\n self.NRD = param['NRD'.swapcase()]\n self.NRDgiven = True\n else:\n if self.NRDgiven == False:\n self.NRD = 1.0\n if 'VFBSDOFF' in param:\n self.VFBSDOFF = param['VFBSDOFF']\n self.VFBSDOFFgiven = True\n elif 'VFBSDOFF'.swapcase() in param:\n self.VFBSDOFF = param['VFBSDOFF'.swapcase()]\n self.VFBSDOFFgiven = True\n else:\n if self.VFBSDOFFgiven == False:\n self.VFBSDOFF = 0.0\n if 'MINZ' in param:\n self.MINZ = param['MINZ']\n self.MINZgiven = True\n elif 'MINZ'.swapcase() in param:\n self.MINZ = param['MINZ'.swapcase()]\n self.MINZgiven = True\n else:\n if self.MINZgiven == False:\n self.MINZ = 0.0\n if 'RGATEMOD' in param:\n self.RGATEMOD = param['RGATEMOD']\n self.RGATEMODgiven = True\n elif 'RGATEMOD'.swapcase() in param:\n self.RGATEMOD = param['RGATEMOD'.swapcase()]\n self.RGATEMODgiven = True\n else:\n if self.RGATEMODgiven == False:\n self.RGATEMOD = 0.0\n if 'RBODYMOD' in param:\n self.RBODYMOD = param['RBODYMOD']\n self.RBODYMODgiven = True\n elif 'RBODYMOD'.swapcase() in param:\n self.RBODYMOD = param['RBODYMOD'.swapcase()]\n self.RBODYMODgiven = True\n else:\n if self.RBODYMODgiven == False:\n self.RBODYMOD = 0.0\n if 'GEOMOD' in param:\n self.GEOMOD = param['GEOMOD']\n self.GEOMODgiven = True\n elif 'GEOMOD'.swapcase() in param:\n self.GEOMOD = param['GEOMOD'.swapcase()]\n self.GEOMODgiven = True\n else:\n if self.GEOMODgiven == False:\n self.GEOMOD = 0.0\n if 'RGEOMOD' in param:\n self.RGEOMOD = param['RGEOMOD']\n self.RGEOMODgiven = True\n elif 'RGEOMOD'.swapcase() in param:\n self.RGEOMOD = param['RGEOMOD'.swapcase()]\n self.RGEOMODgiven = True\n else:\n if self.RGEOMODgiven == False:\n self.RGEOMOD = 0.0\n if 'RBPB' in param:\n self.RBPB = param['RBPB']\n self.RBPBgiven = True\n elif 'RBPB'.swapcase() in param:\n self.RBPB = param['RBPB'.swapcase()]\n self.RBPBgiven = True\n else:\n if self.RBPBgiven == False:\n self.RBPB = 50.0\n if 'RBPD' in param:\n self.RBPD = param['RBPD']\n self.RBPDgiven = True\n elif 'RBPD'.swapcase() in param:\n self.RBPD = param['RBPD'.swapcase()]\n self.RBPDgiven = True\n else:\n if self.RBPDgiven == False:\n self.RBPD = 50.0\n if 'RBPS' in param:\n self.RBPS = param['RBPS']\n self.RBPSgiven = True\n elif 'RBPS'.swapcase() in param:\n self.RBPS = param['RBPS'.swapcase()]\n self.RBPSgiven = True\n else:\n if self.RBPSgiven == False:\n self.RBPS = 50.0\n if 'RBDB' in param:\n self.RBDB = param['RBDB']\n self.RBDBgiven = True\n elif 'RBDB'.swapcase() in param:\n self.RBDB = param['RBDB'.swapcase()]\n self.RBDBgiven = True\n else:\n if self.RBDBgiven == False:\n self.RBDB = 50.0\n if 'RBSB' in param:\n self.RBSB = param['RBSB']\n self.RBSBgiven = True\n elif 'RBSB'.swapcase() in param:\n self.RBSB = param['RBSB'.swapcase()]\n self.RBSBgiven = True\n else:\n if self.RBSBgiven == False:\n self.RBSB = 50.0\n if 'SA' in param:\n self.SA = param['SA']\n self.SAgiven = True\n elif 'SA'.swapcase() in param:\n self.SA = param['SA'.swapcase()]\n self.SAgiven = True\n else:\n if self.SAgiven == False:\n self.SA = 0.0\n if 'SB' in param:\n self.SB = param['SB']\n self.SBgiven = True\n elif 'SB'.swapcase() in param:\n self.SB = param['SB'.swapcase()]\n self.SBgiven = True\n else:\n if self.SBgiven == False:\n self.SB = 0.0\n if 'SD' in param:\n self.SD = param['SD']\n self.SDgiven = True\n elif 'SD'.swapcase() in param:\n self.SD = param['SD'.swapcase()]\n self.SDgiven = True\n else:\n if self.SDgiven == False:\n self.SD = 0.0\n if 'SCA' in param:\n self.SCA = param['SCA']\n self.SCAgiven = True\n elif 'SCA'.swapcase() in param:\n self.SCA = param['SCA'.swapcase()]\n self.SCAgiven = True\n else:\n if self.SCAgiven == False:\n self.SCA = 0.0\n if 'SCB' in param:\n self.SCB = param['SCB']\n self.SCBgiven = True\n elif 'SCB'.swapcase() in param:\n self.SCB = param['SCB'.swapcase()]\n self.SCBgiven = True\n else:\n if self.SCBgiven == False:\n self.SCB = 0.0\n if 'SCC' in param:\n self.SCC = param['SCC']\n self.SCCgiven = True\n elif 'SCC'.swapcase() in param:\n self.SCC = param['SCC'.swapcase()]\n self.SCCgiven = True\n else:\n if self.SCCgiven == False:\n self.SCC = 0.0\n if 'SC' in param:\n self.SC = param['SC']\n self.SCgiven = True\n elif 'SC'.swapcase() in param:\n self.SC = param['SC'.swapcase()]\n self.SCgiven = True\n else:\n if self.SCgiven == False:\n self.SC = 0.0\n if 'AS' in param:\n self.AS = param['AS']\n self.ASgiven = True\n elif 'AS'.swapcase() in param:\n self.AS = param['AS'.swapcase()]\n self.ASgiven = True\n else:\n if self.ASgiven == False:\n self.AS = 0.0\n if 'AD' in param:\n self.AD = param['AD']\n self.ADgiven = True\n elif 'AD'.swapcase() in param:\n self.AD = param['AD'.swapcase()]\n self.ADgiven = True\n else:\n if self.ADgiven == False:\n self.AD = 0.0\n if 'PS' in param:\n self.PS = param['PS']\n self.PSgiven = True\n elif 'PS'.swapcase() in param:\n self.PS = param['PS'.swapcase()]\n self.PSgiven = True\n else:\n if self.PSgiven == False:\n self.PS = 0.0\n if 'PD' in param:\n self.PD = param['PD']\n self.PDgiven = True\n elif 'PD'.swapcase() in param:\n self.PD = param['PD'.swapcase()]\n self.PDgiven = True\n else:\n if self.PDgiven == False:\n self.PD = 0.0\n if 'XGW' in param:\n self.XGW = param['XGW']\n self.XGWgiven = True\n elif 'XGW'.swapcase() in param:\n self.XGW = param['XGW'.swapcase()]\n self.XGWgiven = True\n else:\n if self.XGWgiven == False:\n self.XGW = 0.0\n if 'NGCON' in param:\n self.NGCON = param['NGCON']\n self.NGCONgiven = True\n elif 'NGCON'.swapcase() in param:\n self.NGCON = param['NGCON'.swapcase()]\n self.NGCONgiven = True\n else:\n if self.NGCONgiven == False:\n self.NGCON = 1.0\n if 'DTEMP' in param:\n self.DTEMP = param['DTEMP']\n self.DTEMPgiven = True\n elif 'DTEMP'.swapcase() in param:\n self.DTEMP = param['DTEMP'.swapcase()]\n self.DTEMPgiven = True\n else:\n if self.DTEMPgiven == False:\n self.DTEMP = 0.0\n if 'MULU0' in param:\n self.MULU0 = param['MULU0']\n self.MULU0given = True\n elif 'MULU0'.swapcase() in param:\n self.MULU0 = param['MULU0'.swapcase()]\n self.MULU0given = True\n else:\n if self.MULU0given == False:\n self.MULU0 = 1.0\n if 'DELVTO' in param:\n self.DELVTO = param['DELVTO']\n self.DELVTOgiven = True\n elif 'DELVTO'.swapcase() in param:\n self.DELVTO = param['DELVTO'.swapcase()]\n self.DELVTOgiven = True\n else:\n if self.DELVTOgiven == False:\n self.DELVTO = 0.0\n if 'IDS0MULT' in param:\n self.IDS0MULT = param['IDS0MULT']\n self.IDS0MULTgiven = True\n elif 'IDS0MULT'.swapcase() in param:\n self.IDS0MULT = param['IDS0MULT'.swapcase()]\n self.IDS0MULTgiven = True\n else:\n if self.IDS0MULTgiven == False:\n self.IDS0MULT = 1.0\n if 'EDGEFET' in param:\n self.EDGEFET = param['EDGEFET']\n self.EDGEFETgiven = True\n elif 'EDGEFET'.swapcase() in param:\n self.EDGEFET = param['EDGEFET'.swapcase()]\n self.EDGEFETgiven = True\n else:\n if self.EDGEFETgiven == False:\n self.EDGEFET = 0.0\n if 'SSLMOD' in param:\n self.SSLMOD = param['SSLMOD']\n self.SSLMODgiven = True\n elif 'SSLMOD'.swapcase() in param:\n self.SSLMOD = param['SSLMOD'.swapcase()]\n self.SSLMODgiven = True\n else:\n if self.SSLMODgiven == False:\n self.SSLMOD = 0.0\n if 'TYPE' in param:\n self.TYPE = param['TYPE']\n self.TYPEgiven = True\n elif 'TYPE'.swapcase() in param:\n self.TYPE = param['TYPE'.swapcase()]\n self.TYPEgiven = True\n else:\n if self.TYPEgiven == False:\n self.TYPE = self.ntype\n if 'CVMOD' in param:\n self.CVMOD = param['CVMOD']\n self.CVMODgiven = True\n elif 'CVMOD'.swapcase() in param:\n self.CVMOD = param['CVMOD'.swapcase()]\n self.CVMODgiven = True\n else:\n if self.CVMODgiven == False:\n self.CVMOD = 0.0\n if 'COVMOD' in param:\n self.COVMOD = param['COVMOD']\n self.COVMODgiven = True\n elif 'COVMOD'.swapcase() in param:\n self.COVMOD = param['COVMOD'.swapcase()]\n self.COVMODgiven = True\n else:\n if self.COVMODgiven == False:\n self.COVMOD = 0.0\n if 'RDSMOD' in param:\n self.RDSMOD = param['RDSMOD']\n self.RDSMODgiven = True\n elif 'RDSMOD'.swapcase() in param:\n self.RDSMOD = param['RDSMOD'.swapcase()]\n self.RDSMODgiven = True\n else:\n if self.RDSMODgiven == False:\n self.RDSMOD = 0.0\n if 'WPEMOD' in param:\n self.WPEMOD = param['WPEMOD']\n self.WPEMODgiven = True\n elif 'WPEMOD'.swapcase() in param:\n self.WPEMOD = param['WPEMOD'.swapcase()]\n self.WPEMODgiven = True\n else:\n if self.WPEMODgiven == False:\n self.WPEMOD = 0.0\n if 'ASYMMOD' in param:\n self.ASYMMOD = param['ASYMMOD']\n self.ASYMMODgiven = True\n elif 'ASYMMOD'.swapcase() in param:\n self.ASYMMOD = param['ASYMMOD'.swapcase()]\n self.ASYMMODgiven = True\n else:\n if self.ASYMMODgiven == False:\n self.ASYMMOD = 0.0\n if 'GIDLMOD' in param:\n self.GIDLMOD = param['GIDLMOD']\n self.GIDLMODgiven = True\n elif 'GIDLMOD'.swapcase() in param:\n self.GIDLMOD = param['GIDLMOD'.swapcase()]\n self.GIDLMODgiven = True\n else:\n if self.GIDLMODgiven == False:\n self.GIDLMOD = 0.0\n if 'IGCMOD' in param:\n self.IGCMOD = param['IGCMOD']\n self.IGCMODgiven = True\n elif 'IGCMOD'.swapcase() in param:\n self.IGCMOD = param['IGCMOD'.swapcase()]\n self.IGCMODgiven = True\n else:\n if self.IGCMODgiven == False:\n self.IGCMOD = 0.0\n if 'IGBMOD' in param:\n self.IGBMOD = param['IGBMOD']\n self.IGBMODgiven = True\n elif 'IGBMOD'.swapcase() in param:\n self.IGBMOD = param['IGBMOD'.swapcase()]\n self.IGBMODgiven = True\n else:\n if self.IGBMODgiven == False:\n self.IGBMOD = 0.0\n if 'TNOIMOD' in param:\n self.TNOIMOD = param['TNOIMOD']\n self.TNOIMODgiven = True\n elif 'TNOIMOD'.swapcase() in param:\n self.TNOIMOD = param['TNOIMOD'.swapcase()]\n self.TNOIMODgiven = True\n else:\n if self.TNOIMODgiven == False:\n self.TNOIMOD = 0.0\n if 'SHMOD' in param:\n self.SHMOD = param['SHMOD']\n self.SHMODgiven = True\n elif 'SHMOD'.swapcase() in param:\n self.SHMOD = param['SHMOD'.swapcase()]\n self.SHMODgiven = True\n else:\n if self.SHMODgiven == False:\n self.SHMOD = 0.0\n if 'MOBSCALE' in param:\n self.MOBSCALE = param['MOBSCALE']\n self.MOBSCALEgiven = True\n elif 'MOBSCALE'.swapcase() in param:\n self.MOBSCALE = param['MOBSCALE'.swapcase()]\n self.MOBSCALEgiven = True\n else:\n if self.MOBSCALEgiven == False:\n self.MOBSCALE = 0.0\n if 'LLONG' in param:\n self.LLONG = param['LLONG']\n self.LLONGgiven = True\n elif 'LLONG'.swapcase() in param:\n self.LLONG = param['LLONG'.swapcase()]\n self.LLONGgiven = True\n else:\n if self.LLONGgiven == False:\n self.LLONG = 1e-05\n if 'LMLT' in param:\n self.LMLT = param['LMLT']\n self.LMLTgiven = True\n elif 'LMLT'.swapcase() in param:\n self.LMLT = param['LMLT'.swapcase()]\n self.LMLTgiven = True\n else:\n if self.LMLTgiven == False:\n self.LMLT = 1.0\n if 'WMLT' in param:\n self.WMLT = param['WMLT']\n self.WMLTgiven = True\n elif 'WMLT'.swapcase() in param:\n self.WMLT = param['WMLT'.swapcase()]\n self.WMLTgiven = True\n else:\n if self.WMLTgiven == False:\n self.WMLT = 1.0\n if 'XL' in param:\n self.XL = param['XL']\n self.XLgiven = True\n elif 'XL'.swapcase() in param:\n self.XL = param['XL'.swapcase()]\n self.XLgiven = True\n else:\n if self.XLgiven == False:\n self.XL = 0.0\n if 'WWIDE' in param:\n self.WWIDE = param['WWIDE']\n self.WWIDEgiven = True\n elif 'WWIDE'.swapcase() in param:\n self.WWIDE = param['WWIDE'.swapcase()]\n self.WWIDEgiven = True\n else:\n if self.WWIDEgiven == False:\n self.WWIDE = 1e-05\n if 'XW' in param:\n self.XW = param['XW']\n self.XWgiven = True\n elif 'XW'.swapcase() in param:\n self.XW = param['XW'.swapcase()]\n self.XWgiven = True\n else:\n if self.XWgiven == False:\n self.XW = 0.0\n if 'LINT' in param:\n self.LINT = param['LINT']\n self.LINTgiven = True\n elif 'LINT'.swapcase() in param:\n self.LINT = param['LINT'.swapcase()]\n self.LINTgiven = True\n else:\n if self.LINTgiven == False:\n self.LINT = 0.0\n if 'LL' in param:\n self.LL = param['LL']\n self.LLgiven = True\n elif 'LL'.swapcase() in param:\n self.LL = param['LL'.swapcase()]\n self.LLgiven = True\n else:\n if self.LLgiven == False:\n self.LL = 0.0\n if 'LW' in param:\n self.LW = param['LW']\n self.LWgiven = True\n elif 'LW'.swapcase() in param:\n self.LW = param['LW'.swapcase()]\n self.LWgiven = True\n else:\n if self.LWgiven == False:\n self.LW = 0.0\n if 'LWL' in param:\n self.LWL = param['LWL']\n self.LWLgiven = True\n elif 'LWL'.swapcase() in param:\n self.LWL = param['LWL'.swapcase()]\n self.LWLgiven = True\n else:\n if self.LWLgiven == False:\n self.LWL = 0.0\n if 'LLN' in param:\n self.LLN = param['LLN']\n self.LLNgiven = True\n elif 'LLN'.swapcase() in param:\n self.LLN = param['LLN'.swapcase()]\n self.LLNgiven = True\n else:\n if self.LLNgiven == False:\n self.LLN = 1.0\n if 'LWN' in param:\n self.LWN = param['LWN']\n self.LWNgiven = True\n elif 'LWN'.swapcase() in param:\n self.LWN = param['LWN'.swapcase()]\n self.LWNgiven = True\n else:\n if self.LWNgiven == False:\n self.LWN = 1.0\n if 'WINT' in param:\n self.WINT = param['WINT']\n self.WINTgiven = True\n elif 'WINT'.swapcase() in param:\n self.WINT = param['WINT'.swapcase()]\n self.WINTgiven = True\n else:\n if self.WINTgiven == False:\n self.WINT = 0.0\n if 'WL' in param:\n self.WL = param['WL']\n self.WLgiven = True\n elif 'WL'.swapcase() in param:\n self.WL = param['WL'.swapcase()]\n self.WLgiven = True\n else:\n if self.WLgiven == False:\n self.WL = 0.0\n if 'WW' in param:\n self.WW = param['WW']\n self.WWgiven = True\n elif 'WW'.swapcase() in param:\n self.WW = param['WW'.swapcase()]\n self.WWgiven = True\n else:\n if self.WWgiven == False:\n self.WW = 0.0\n if 'WWL' in param:\n self.WWL = param['WWL']\n self.WWLgiven = True\n elif 'WWL'.swapcase() in param:\n self.WWL = param['WWL'.swapcase()]\n self.WWLgiven = True\n else:\n if self.WWLgiven == False:\n self.WWL = 0.0\n if 'WLN' in param:\n self.WLN = param['WLN']\n self.WLNgiven = True\n elif 'WLN'.swapcase() in param:\n self.WLN = param['WLN'.swapcase()]\n self.WLNgiven = True\n else:\n if self.WLNgiven == False:\n self.WLN = 1.0\n if 'WWN' in param:\n self.WWN = param['WWN']\n self.WWNgiven = True\n elif 'WWN'.swapcase() in param:\n self.WWN = param['WWN'.swapcase()]\n self.WWNgiven = True\n else:\n if self.WWNgiven == False:\n self.WWN = 1.0\n if 'DLC' in param:\n self.DLC = param['DLC']\n self.DLCgiven = True\n elif 'DLC'.swapcase() in param:\n self.DLC = param['DLC'.swapcase()]\n self.DLCgiven = True\n else:\n if self.DLCgiven == False:\n self.DLC = 0.0\n if 'LLC' in param:\n self.LLC = param['LLC']\n self.LLCgiven = True\n elif 'LLC'.swapcase() in param:\n self.LLC = param['LLC'.swapcase()]\n self.LLCgiven = True\n else:\n if self.LLCgiven == False:\n self.LLC = 0.0\n if 'LWC' in param:\n self.LWC = param['LWC']\n self.LWCgiven = True\n elif 'LWC'.swapcase() in param:\n self.LWC = param['LWC'.swapcase()]\n self.LWCgiven = True\n else:\n if self.LWCgiven == False:\n self.LWC = 0.0\n if 'LWLC' in param:\n self.LWLC = param['LWLC']\n self.LWLCgiven = True\n elif 'LWLC'.swapcase() in param:\n self.LWLC = param['LWLC'.swapcase()]\n self.LWLCgiven = True\n else:\n if self.LWLCgiven == False:\n self.LWLC = 0.0\n if 'DWC' in param:\n self.DWC = param['DWC']\n self.DWCgiven = True\n elif 'DWC'.swapcase() in param:\n self.DWC = param['DWC'.swapcase()]\n self.DWCgiven = True\n else:\n if self.DWCgiven == False:\n self.DWC = 0.0\n if 'WLC' in param:\n self.WLC = param['WLC']\n self.WLCgiven = True\n elif 'WLC'.swapcase() in param:\n self.WLC = param['WLC'.swapcase()]\n self.WLCgiven = True\n else:\n if self.WLCgiven == False:\n self.WLC = 0.0\n if 'WWC' in param:\n self.WWC = param['WWC']\n self.WWCgiven = True\n elif 'WWC'.swapcase() in param:\n self.WWC = param['WWC'.swapcase()]\n self.WWCgiven = True\n else:\n if self.WWCgiven == False:\n self.WWC = 0.0\n if 'WWLC' in param:\n self.WWLC = param['WWLC']\n self.WWLCgiven = True\n elif 'WWLC'.swapcase() in param:\n self.WWLC = param['WWLC'.swapcase()]\n self.WWLCgiven = True\n else:\n if self.WWLCgiven == False:\n self.WWLC = 0.0\n if 'TOXE' in param:\n self.TOXE = param['TOXE']\n self.TOXEgiven = True\n elif 'TOXE'.swapcase() in param:\n self.TOXE = param['TOXE'.swapcase()]\n self.TOXEgiven = True\n else:\n if self.TOXEgiven == False:\n self.TOXE = 3e-09\n if 'TOXP' in param:\n self.TOXP = param['TOXP']\n self.TOXPgiven = True\n elif 'TOXP'.swapcase() in param:\n self.TOXP = param['TOXP'.swapcase()]\n self.TOXPgiven = True\n else:\n if self.TOXPgiven == False:\n self.TOXP = self.TOXE\n if 'DTOX' in param:\n self.DTOX = param['DTOX']\n self.DTOXgiven = True\n elif 'DTOX'.swapcase() in param:\n self.DTOX = param['DTOX'.swapcase()]\n self.DTOXgiven = True\n else:\n if self.DTOXgiven == False:\n self.DTOX = 0.0\n if 'NDEP' in param:\n self.NDEP = param['NDEP']\n self.NDEPgiven = True\n elif 'NDEP'.swapcase() in param:\n self.NDEP = param['NDEP'.swapcase()]\n self.NDEPgiven = True\n else:\n if self.NDEPgiven == False:\n self.NDEP = 1e+24\n if 'NDEPL1' in param:\n self.NDEPL1 = param['NDEPL1']\n self.NDEPL1given = True\n elif 'NDEPL1'.swapcase() in param:\n self.NDEPL1 = param['NDEPL1'.swapcase()]\n self.NDEPL1given = True\n else:\n if self.NDEPL1given == False:\n self.NDEPL1 = 0.0\n if 'NDEPLEXP1' in param:\n self.NDEPLEXP1 = param['NDEPLEXP1']\n self.NDEPLEXP1given = True\n elif 'NDEPLEXP1'.swapcase() in param:\n self.NDEPLEXP1 = param['NDEPLEXP1'.swapcase()]\n self.NDEPLEXP1given = True\n else:\n if self.NDEPLEXP1given == False:\n self.NDEPLEXP1 = 1.0\n if 'NDEPL2' in param:\n self.NDEPL2 = param['NDEPL2']\n self.NDEPL2given = True\n elif 'NDEPL2'.swapcase() in param:\n self.NDEPL2 = param['NDEPL2'.swapcase()]\n self.NDEPL2given = True\n else:\n if self.NDEPL2given == False:\n self.NDEPL2 = 0.0\n if 'NDEPLEXP2' in param:\n self.NDEPLEXP2 = param['NDEPLEXP2']\n self.NDEPLEXP2given = True\n elif 'NDEPLEXP2'.swapcase() in param:\n self.NDEPLEXP2 = param['NDEPLEXP2'.swapcase()]\n self.NDEPLEXP2given = True\n else:\n if self.NDEPLEXP2given == False:\n self.NDEPLEXP2 = 2.0\n if 'NDEPW' in param:\n self.NDEPW = param['NDEPW']\n self.NDEPWgiven = True\n elif 'NDEPW'.swapcase() in param:\n self.NDEPW = param['NDEPW'.swapcase()]\n self.NDEPWgiven = True\n else:\n if self.NDEPWgiven == False:\n self.NDEPW = 0.0\n if 'NDEPWEXP' in param:\n self.NDEPWEXP = param['NDEPWEXP']\n self.NDEPWEXPgiven = True\n elif 'NDEPWEXP'.swapcase() in param:\n self.NDEPWEXP = param['NDEPWEXP'.swapcase()]\n self.NDEPWEXPgiven = True\n else:\n if self.NDEPWEXPgiven == False:\n self.NDEPWEXP = 1.0\n if 'NDEPWL' in param:\n self.NDEPWL = param['NDEPWL']\n self.NDEPWLgiven = True\n elif 'NDEPWL'.swapcase() in param:\n self.NDEPWL = param['NDEPWL'.swapcase()]\n self.NDEPWLgiven = True\n else:\n if self.NDEPWLgiven == False:\n self.NDEPWL = 0.0\n if 'NDEPWLEXP' in param:\n self.NDEPWLEXP = param['NDEPWLEXP']\n self.NDEPWLEXPgiven = True\n elif 'NDEPWLEXP'.swapcase() in param:\n self.NDEPWLEXP = param['NDEPWLEXP'.swapcase()]\n self.NDEPWLEXPgiven = True\n else:\n if self.NDEPWLEXPgiven == False:\n self.NDEPWLEXP = 1.0\n if 'LNDEP' in param:\n self.LNDEP = param['LNDEP']\n self.LNDEPgiven = True\n elif 'LNDEP'.swapcase() in param:\n self.LNDEP = param['LNDEP'.swapcase()]\n self.LNDEPgiven = True\n else:\n if self.LNDEPgiven == False:\n self.LNDEP = 0.0\n if 'WNDEP' in param:\n self.WNDEP = param['WNDEP']\n self.WNDEPgiven = True\n elif 'WNDEP'.swapcase() in param:\n self.WNDEP = param['WNDEP'.swapcase()]\n self.WNDEPgiven = True\n else:\n if self.WNDEPgiven == False:\n self.WNDEP = 0.0\n if 'PNDEP' in param:\n self.PNDEP = param['PNDEP']\n self.PNDEPgiven = True\n elif 'PNDEP'.swapcase() in param:\n self.PNDEP = param['PNDEP'.swapcase()]\n self.PNDEPgiven = True\n else:\n if self.PNDEPgiven == False:\n self.PNDEP = 0.0\n if 'NDEPCV' in param:\n self.NDEPCV = param['NDEPCV']\n self.NDEPCVgiven = True\n elif 'NDEPCV'.swapcase() in param:\n self.NDEPCV = param['NDEPCV'.swapcase()]\n self.NDEPCVgiven = True\n else:\n if self.NDEPCVgiven == False:\n self.NDEPCV = 1e+24\n if 'NDEPCVL1' in param:\n self.NDEPCVL1 = param['NDEPCVL1']\n self.NDEPCVL1given = True\n elif 'NDEPCVL1'.swapcase() in param:\n self.NDEPCVL1 = param['NDEPCVL1'.swapcase()]\n self.NDEPCVL1given = True\n else:\n if self.NDEPCVL1given == False:\n self.NDEPCVL1 = 0.0\n if 'NDEPCVLEXP1' in param:\n self.NDEPCVLEXP1 = param['NDEPCVLEXP1']\n self.NDEPCVLEXP1given = True\n elif 'NDEPCVLEXP1'.swapcase() in param:\n self.NDEPCVLEXP1 = param['NDEPCVLEXP1'.swapcase()]\n self.NDEPCVLEXP1given = True\n else:\n if self.NDEPCVLEXP1given == False:\n self.NDEPCVLEXP1 = 1.0\n if 'NDEPCVL2' in param:\n self.NDEPCVL2 = param['NDEPCVL2']\n self.NDEPCVL2given = True\n elif 'NDEPCVL2'.swapcase() in param:\n self.NDEPCVL2 = param['NDEPCVL2'.swapcase()]\n self.NDEPCVL2given = True\n else:\n if self.NDEPCVL2given == False:\n self.NDEPCVL2 = 0.0\n if 'NDEPCVLEXP2' in param:\n self.NDEPCVLEXP2 = param['NDEPCVLEXP2']\n self.NDEPCVLEXP2given = True\n elif 'NDEPCVLEXP2'.swapcase() in param:\n self.NDEPCVLEXP2 = param['NDEPCVLEXP2'.swapcase()]\n self.NDEPCVLEXP2given = True\n else:\n if self.NDEPCVLEXP2given == False:\n self.NDEPCVLEXP2 = 2.0\n if 'NDEPCVW' in param:\n self.NDEPCVW = param['NDEPCVW']\n self.NDEPCVWgiven = True\n elif 'NDEPCVW'.swapcase() in param:\n self.NDEPCVW = param['NDEPCVW'.swapcase()]\n self.NDEPCVWgiven = True\n else:\n if self.NDEPCVWgiven == False:\n self.NDEPCVW = 0.0\n if 'NDEPCVWEXP' in param:\n self.NDEPCVWEXP = param['NDEPCVWEXP']\n self.NDEPCVWEXPgiven = True\n elif 'NDEPCVWEXP'.swapcase() in param:\n self.NDEPCVWEXP = param['NDEPCVWEXP'.swapcase()]\n self.NDEPCVWEXPgiven = True\n else:\n if self.NDEPCVWEXPgiven == False:\n self.NDEPCVWEXP = 1.0\n if 'NDEPCVWL' in param:\n self.NDEPCVWL = param['NDEPCVWL']\n self.NDEPCVWLgiven = True\n elif 'NDEPCVWL'.swapcase() in param:\n self.NDEPCVWL = param['NDEPCVWL'.swapcase()]\n self.NDEPCVWLgiven = True\n else:\n if self.NDEPCVWLgiven == False:\n self.NDEPCVWL = 0.0\n if 'NDEPCVWLEXP' in param:\n self.NDEPCVWLEXP = param['NDEPCVWLEXP']\n self.NDEPCVWLEXPgiven = True\n elif 'NDEPCVWLEXP'.swapcase() in param:\n self.NDEPCVWLEXP = param['NDEPCVWLEXP'.swapcase()]\n self.NDEPCVWLEXPgiven = True\n else:\n if self.NDEPCVWLEXPgiven == False:\n self.NDEPCVWLEXP = 1.0\n if 'LNDEPCV' in param:\n self.LNDEPCV = param['LNDEPCV']\n self.LNDEPCVgiven = True\n elif 'LNDEPCV'.swapcase() in param:\n self.LNDEPCV = param['LNDEPCV'.swapcase()]\n self.LNDEPCVgiven = True\n else:\n if self.LNDEPCVgiven == False:\n self.LNDEPCV = 0.0\n if 'WNDEPCV' in param:\n self.WNDEPCV = param['WNDEPCV']\n self.WNDEPCVgiven = True\n elif 'WNDEPCV'.swapcase() in param:\n self.WNDEPCV = param['WNDEPCV'.swapcase()]\n self.WNDEPCVgiven = True\n else:\n if self.WNDEPCVgiven == False:\n self.WNDEPCV = 0.0\n if 'PNDEPCV' in param:\n self.PNDEPCV = param['PNDEPCV']\n self.PNDEPCVgiven = True\n elif 'PNDEPCV'.swapcase() in param:\n self.PNDEPCV = param['PNDEPCV'.swapcase()]\n self.PNDEPCVgiven = True\n else:\n if self.PNDEPCVgiven == False:\n self.PNDEPCV = 0.0\n if 'NGATE' in param:\n self.NGATE = param['NGATE']\n self.NGATEgiven = True\n elif 'NGATE'.swapcase() in param:\n self.NGATE = param['NGATE'.swapcase()]\n self.NGATEgiven = True\n else:\n if self.NGATEgiven == False:\n self.NGATE = 5e+25\n if 'LNGATE' in param:\n self.LNGATE = param['LNGATE']\n self.LNGATEgiven = True\n elif 'LNGATE'.swapcase() in param:\n self.LNGATE = param['LNGATE'.swapcase()]\n self.LNGATEgiven = True\n else:\n if self.LNGATEgiven == False:\n self.LNGATE = 0.0\n if 'WNGATE' in param:\n self.WNGATE = param['WNGATE']\n self.WNGATEgiven = True\n elif 'WNGATE'.swapcase() in param:\n self.WNGATE = param['WNGATE'.swapcase()]\n self.WNGATEgiven = True\n else:\n if self.WNGATEgiven == False:\n self.WNGATE = 0.0\n if 'PNGATE' in param:\n self.PNGATE = param['PNGATE']\n self.PNGATEgiven = True\n elif 'PNGATE'.swapcase() in param:\n self.PNGATE = param['PNGATE'.swapcase()]\n self.PNGATEgiven = True\n else:\n if self.PNGATEgiven == False:\n self.PNGATE = 0.0\n if 'EASUB' in param:\n self.EASUB = param['EASUB']\n self.EASUBgiven = True\n elif 'EASUB'.swapcase() in param:\n self.EASUB = param['EASUB'.swapcase()]\n self.EASUBgiven = True\n else:\n if self.EASUBgiven == False:\n self.EASUB = 4.05\n if 'NI0SUB' in param:\n self.NI0SUB = param['NI0SUB']\n self.NI0SUBgiven = True\n elif 'NI0SUB'.swapcase() in param:\n self.NI0SUB = param['NI0SUB'.swapcase()]\n self.NI0SUBgiven = True\n else:\n if self.NI0SUBgiven == False:\n self.NI0SUB = 1.1e+16\n if 'BG0SUB' in param:\n self.BG0SUB = param['BG0SUB']\n self.BG0SUBgiven = True\n elif 'BG0SUB'.swapcase() in param:\n self.BG0SUB = param['BG0SUB'.swapcase()]\n self.BG0SUBgiven = True\n else:\n if self.BG0SUBgiven == False:\n self.BG0SUB = 1.17\n if 'EPSRSUB' in param:\n self.EPSRSUB = param['EPSRSUB']\n self.EPSRSUBgiven = True\n elif 'EPSRSUB'.swapcase() in param:\n self.EPSRSUB = param['EPSRSUB'.swapcase()]\n self.EPSRSUBgiven = True\n else:\n if self.EPSRSUBgiven == False:\n self.EPSRSUB = 11.9\n if 'EPSROX' in param:\n self.EPSROX = param['EPSROX']\n self.EPSROXgiven = True\n elif 'EPSROX'.swapcase() in param:\n self.EPSROX = param['EPSROX'.swapcase()]\n self.EPSROXgiven = True\n else:\n if self.EPSROXgiven == False:\n self.EPSROX = 3.9\n if 'XJ' in param:\n self.XJ = param['XJ']\n self.XJgiven = True\n elif 'XJ'.swapcase() in param:\n self.XJ = param['XJ'.swapcase()]\n self.XJgiven = True\n else:\n if self.XJgiven == False:\n self.XJ = 1.5e-07\n if 'LXJ' in param:\n self.LXJ = param['LXJ']\n self.LXJgiven = True\n elif 'LXJ'.swapcase() in param:\n self.LXJ = param['LXJ'.swapcase()]\n self.LXJgiven = True\n else:\n if self.LXJgiven == False:\n self.LXJ = 0.0\n if 'WXJ' in param:\n self.WXJ = param['WXJ']\n self.WXJgiven = True\n elif 'WXJ'.swapcase() in param:\n self.WXJ = param['WXJ'.swapcase()]\n self.WXJgiven = True\n else:\n if self.WXJgiven == False:\n self.WXJ = 0.0\n if 'PXJ' in param:\n self.PXJ = param['PXJ']\n self.PXJgiven = True\n elif 'PXJ'.swapcase() in param:\n self.PXJ = param['PXJ'.swapcase()]\n self.PXJgiven = True\n else:\n if self.PXJgiven == False:\n self.PXJ = 0.0\n if 'VFB' in param:\n self.VFB = param['VFB']\n self.VFBgiven = True\n elif 'VFB'.swapcase() in param:\n self.VFB = param['VFB'.swapcase()]\n self.VFBgiven = True\n else:\n if self.VFBgiven == False:\n self.VFB = -0.5\n if 'LVFB' in param:\n self.LVFB = param['LVFB']\n self.LVFBgiven = True\n elif 'LVFB'.swapcase() in param:\n self.LVFB = param['LVFB'.swapcase()]\n self.LVFBgiven = True\n else:\n if self.LVFBgiven == False:\n self.LVFB = 0.0\n if 'WVFB' in param:\n self.WVFB = param['WVFB']\n self.WVFBgiven = True\n elif 'WVFB'.swapcase() in param:\n self.WVFB = param['WVFB'.swapcase()]\n self.WVFBgiven = True\n else:\n if self.WVFBgiven == False:\n self.WVFB = 0.0\n if 'PVFB' in param:\n self.PVFB = param['PVFB']\n self.PVFBgiven = True\n elif 'PVFB'.swapcase() in param:\n self.PVFB = param['PVFB'.swapcase()]\n self.PVFBgiven = True\n else:\n if self.PVFBgiven == False:\n self.PVFB = 0.0\n if 'VFBCV' in param:\n self.VFBCV = param['VFBCV']\n self.VFBCVgiven = True\n elif 'VFBCV'.swapcase() in param:\n self.VFBCV = param['VFBCV'.swapcase()]\n self.VFBCVgiven = True\n else:\n if self.VFBCVgiven == False:\n self.VFBCV = -0.5\n if 'LVFBCV' in param:\n self.LVFBCV = param['LVFBCV']\n self.LVFBCVgiven = True\n elif 'LVFBCV'.swapcase() in param:\n self.LVFBCV = param['LVFBCV'.swapcase()]\n self.LVFBCVgiven = True\n else:\n if self.LVFBCVgiven == False:\n self.LVFBCV = 0.0\n if 'WVFBCV' in param:\n self.WVFBCV = param['WVFBCV']\n self.WVFBCVgiven = True\n elif 'WVFBCV'.swapcase() in param:\n self.WVFBCV = param['WVFBCV'.swapcase()]\n self.WVFBCVgiven = True\n else:\n if self.WVFBCVgiven == False:\n self.WVFBCV = 0.0\n if 'PVFBCV' in param:\n self.PVFBCV = param['PVFBCV']\n self.PVFBCVgiven = True\n elif 'PVFBCV'.swapcase() in param:\n self.PVFBCV = param['PVFBCV'.swapcase()]\n self.PVFBCVgiven = True\n else:\n if self.PVFBCVgiven == False:\n self.PVFBCV = 0.0\n if 'VFBCVL' in param:\n self.VFBCVL = param['VFBCVL']\n self.VFBCVLgiven = True\n elif 'VFBCVL'.swapcase() in param:\n self.VFBCVL = param['VFBCVL'.swapcase()]\n self.VFBCVLgiven = True\n else:\n if self.VFBCVLgiven == False:\n self.VFBCVL = 0.0\n if 'VFBCVLEXP' in param:\n self.VFBCVLEXP = param['VFBCVLEXP']\n self.VFBCVLEXPgiven = True\n elif 'VFBCVLEXP'.swapcase() in param:\n self.VFBCVLEXP = param['VFBCVLEXP'.swapcase()]\n self.VFBCVLEXPgiven = True\n else:\n if self.VFBCVLEXPgiven == False:\n self.VFBCVLEXP = 1.0\n if 'VFBCVW' in param:\n self.VFBCVW = param['VFBCVW']\n self.VFBCVWgiven = True\n elif 'VFBCVW'.swapcase() in param:\n self.VFBCVW = param['VFBCVW'.swapcase()]\n self.VFBCVWgiven = True\n else:\n if self.VFBCVWgiven == False:\n self.VFBCVW = 0.0\n if 'VFBCVWEXP' in param:\n self.VFBCVWEXP = param['VFBCVWEXP']\n self.VFBCVWEXPgiven = True\n elif 'VFBCVWEXP'.swapcase() in param:\n self.VFBCVWEXP = param['VFBCVWEXP'.swapcase()]\n self.VFBCVWEXPgiven = True\n else:\n if self.VFBCVWEXPgiven == False:\n self.VFBCVWEXP = 1.0\n if 'VFBCVWL' in param:\n self.VFBCVWL = param['VFBCVWL']\n self.VFBCVWLgiven = True\n elif 'VFBCVWL'.swapcase() in param:\n self.VFBCVWL = param['VFBCVWL'.swapcase()]\n self.VFBCVWLgiven = True\n else:\n if self.VFBCVWLgiven == False:\n self.VFBCVWL = 0.0\n if 'VFBCVWLEXP' in param:\n self.VFBCVWLEXP = param['VFBCVWLEXP']\n self.VFBCVWLEXPgiven = True\n elif 'VFBCVWLEXP'.swapcase() in param:\n self.VFBCVWLEXP = param['VFBCVWLEXP'.swapcase()]\n self.VFBCVWLEXPgiven = True\n else:\n if self.VFBCVWLEXPgiven == False:\n self.VFBCVWLEXP = 1.0\n if 'DELVFBACC' in param:\n self.DELVFBACC = param['DELVFBACC']\n self.DELVFBACCgiven = True\n elif 'DELVFBACC'.swapcase() in param:\n self.DELVFBACC = param['DELVFBACC'.swapcase()]\n self.DELVFBACCgiven = True\n else:\n if self.DELVFBACCgiven == False:\n self.DELVFBACC = 0.0\n if 'PERMOD' in param:\n self.PERMOD = param['PERMOD']\n self.PERMODgiven = True\n elif 'PERMOD'.swapcase() in param:\n self.PERMOD = param['PERMOD'.swapcase()]\n self.PERMODgiven = True\n else:\n if self.PERMODgiven == False:\n self.PERMOD = 1.0\n if 'DWJ' in param:\n self.DWJ = param['DWJ']\n self.DWJgiven = True\n elif 'DWJ'.swapcase() in param:\n self.DWJ = param['DWJ'.swapcase()]\n self.DWJgiven = True\n else:\n if self.DWJgiven == False:\n self.DWJ = self.DWC\n if 'NSD' in param:\n self.NSD = param['NSD']\n self.NSDgiven = True\n elif 'NSD'.swapcase() in param:\n self.NSD = param['NSD'.swapcase()]\n self.NSDgiven = True\n else:\n if self.NSDgiven == False:\n self.NSD = 1e+26\n if 'LNSD' in param:\n self.LNSD = param['LNSD']\n self.LNSDgiven = True\n elif 'LNSD'.swapcase() in param:\n self.LNSD = param['LNSD'.swapcase()]\n self.LNSDgiven = True\n else:\n if self.LNSDgiven == False:\n self.LNSD = 0.0\n if 'WNSD' in param:\n self.WNSD = param['WNSD']\n self.WNSDgiven = True\n elif 'WNSD'.swapcase() in param:\n self.WNSD = param['WNSD'.swapcase()]\n self.WNSDgiven = True\n else:\n if self.WNSDgiven == False:\n self.WNSD = 0.0\n if 'PNSD' in param:\n self.PNSD = param['PNSD']\n self.PNSDgiven = True\n elif 'PNSD'.swapcase() in param:\n self.PNSD = param['PNSD'.swapcase()]\n self.PNSDgiven = True\n else:\n if self.PNSDgiven == False:\n self.PNSD = 0.0\n if 'DVTP0' in param:\n self.DVTP0 = param['DVTP0']\n self.DVTP0given = True\n elif 'DVTP0'.swapcase() in param:\n self.DVTP0 = param['DVTP0'.swapcase()]\n self.DVTP0given = True\n else:\n if self.DVTP0given == False:\n self.DVTP0 = 0.0\n if 'LDVTP0' in param:\n self.LDVTP0 = param['LDVTP0']\n self.LDVTP0given = True\n elif 'LDVTP0'.swapcase() in param:\n self.LDVTP0 = param['LDVTP0'.swapcase()]\n self.LDVTP0given = True\n else:\n if self.LDVTP0given == False:\n self.LDVTP0 = 0.0\n if 'WDVTP0' in param:\n self.WDVTP0 = param['WDVTP0']\n self.WDVTP0given = True\n elif 'WDVTP0'.swapcase() in param:\n self.WDVTP0 = param['WDVTP0'.swapcase()]\n self.WDVTP0given = True\n else:\n if self.WDVTP0given == False:\n self.WDVTP0 = 0.0\n if 'PDVTP0' in param:\n self.PDVTP0 = param['PDVTP0']\n self.PDVTP0given = True\n elif 'PDVTP0'.swapcase() in param:\n self.PDVTP0 = param['PDVTP0'.swapcase()]\n self.PDVTP0given = True\n else:\n if self.PDVTP0given == False:\n self.PDVTP0 = 0.0\n if 'DVTP1' in param:\n self.DVTP1 = param['DVTP1']\n self.DVTP1given = True\n elif 'DVTP1'.swapcase() in param:\n self.DVTP1 = param['DVTP1'.swapcase()]\n self.DVTP1given = True\n else:\n if self.DVTP1given == False:\n self.DVTP1 = 0.0\n if 'LDVTP1' in param:\n self.LDVTP1 = param['LDVTP1']\n self.LDVTP1given = True\n elif 'LDVTP1'.swapcase() in param:\n self.LDVTP1 = param['LDVTP1'.swapcase()]\n self.LDVTP1given = True\n else:\n if self.LDVTP1given == False:\n self.LDVTP1 = 0.0\n if 'WDVTP1' in param:\n self.WDVTP1 = param['WDVTP1']\n self.WDVTP1given = True\n elif 'WDVTP1'.swapcase() in param:\n self.WDVTP1 = param['WDVTP1'.swapcase()]\n self.WDVTP1given = True\n else:\n if self.WDVTP1given == False:\n self.WDVTP1 = 0.0\n if 'PDVTP1' in param:\n self.PDVTP1 = param['PDVTP1']\n self.PDVTP1given = True\n elif 'PDVTP1'.swapcase() in param:\n self.PDVTP1 = param['PDVTP1'.swapcase()]\n self.PDVTP1given = True\n else:\n if self.PDVTP1given == False:\n self.PDVTP1 = 0.0\n if 'DVTP2' in param:\n self.DVTP2 = param['DVTP2']\n self.DVTP2given = True\n elif 'DVTP2'.swapcase() in param:\n self.DVTP2 = param['DVTP2'.swapcase()]\n self.DVTP2given = True\n else:\n if self.DVTP2given == False:\n self.DVTP2 = 0.0\n if 'LDVTP2' in param:\n self.LDVTP2 = param['LDVTP2']\n self.LDVTP2given = True\n elif 'LDVTP2'.swapcase() in param:\n self.LDVTP2 = param['LDVTP2'.swapcase()]\n self.LDVTP2given = True\n else:\n if self.LDVTP2given == False:\n self.LDVTP2 = 0.0\n if 'WDVTP2' in param:\n self.WDVTP2 = param['WDVTP2']\n self.WDVTP2given = True\n elif 'WDVTP2'.swapcase() in param:\n self.WDVTP2 = param['WDVTP2'.swapcase()]\n self.WDVTP2given = True\n else:\n if self.WDVTP2given == False:\n self.WDVTP2 = 0.0\n if 'PDVTP2' in param:\n self.PDVTP2 = param['PDVTP2']\n self.PDVTP2given = True\n elif 'PDVTP2'.swapcase() in param:\n self.PDVTP2 = param['PDVTP2'.swapcase()]\n self.PDVTP2given = True\n else:\n if self.PDVTP2given == False:\n self.PDVTP2 = 0.0\n if 'DVTP3' in param:\n self.DVTP3 = param['DVTP3']\n self.DVTP3given = True\n elif 'DVTP3'.swapcase() in param:\n self.DVTP3 = param['DVTP3'.swapcase()]\n self.DVTP3given = True\n else:\n if self.DVTP3given == False:\n self.DVTP3 = 0.0\n if 'LDVTP3' in param:\n self.LDVTP3 = param['LDVTP3']\n self.LDVTP3given = True\n elif 'LDVTP3'.swapcase() in param:\n self.LDVTP3 = param['LDVTP3'.swapcase()]\n self.LDVTP3given = True\n else:\n if self.LDVTP3given == False:\n self.LDVTP3 = 0.0\n if 'WDVTP3' in param:\n self.WDVTP3 = param['WDVTP3']\n self.WDVTP3given = True\n elif 'WDVTP3'.swapcase() in param:\n self.WDVTP3 = param['WDVTP3'.swapcase()]\n self.WDVTP3given = True\n else:\n if self.WDVTP3given == False:\n self.WDVTP3 = 0.0\n if 'PDVTP3' in param:\n self.PDVTP3 = param['PDVTP3']\n self.PDVTP3given = True\n elif 'PDVTP3'.swapcase() in param:\n self.PDVTP3 = param['PDVTP3'.swapcase()]\n self.PDVTP3given = True\n else:\n if self.PDVTP3given == False:\n self.PDVTP3 = 0.0\n if 'DVTP4' in param:\n self.DVTP4 = param['DVTP4']\n self.DVTP4given = True\n elif 'DVTP4'.swapcase() in param:\n self.DVTP4 = param['DVTP4'.swapcase()]\n self.DVTP4given = True\n else:\n if self.DVTP4given == False:\n self.DVTP4 = 0.0\n if 'LDVTP4' in param:\n self.LDVTP4 = param['LDVTP4']\n self.LDVTP4given = True\n elif 'LDVTP4'.swapcase() in param:\n self.LDVTP4 = param['LDVTP4'.swapcase()]\n self.LDVTP4given = True\n else:\n if self.LDVTP4given == False:\n self.LDVTP4 = 0.0\n if 'WDVTP4' in param:\n self.WDVTP4 = param['WDVTP4']\n self.WDVTP4given = True\n elif 'WDVTP4'.swapcase() in param:\n self.WDVTP4 = param['WDVTP4'.swapcase()]\n self.WDVTP4given = True\n else:\n if self.WDVTP4given == False:\n self.WDVTP4 = 0.0\n if 'PDVTP4' in param:\n self.PDVTP4 = param['PDVTP4']\n self.PDVTP4given = True\n elif 'PDVTP4'.swapcase() in param:\n self.PDVTP4 = param['PDVTP4'.swapcase()]\n self.PDVTP4given = True\n else:\n if self.PDVTP4given == False:\n self.PDVTP4 = 0.0\n if 'DVTP5' in param:\n self.DVTP5 = param['DVTP5']\n self.DVTP5given = True\n elif 'DVTP5'.swapcase() in param:\n self.DVTP5 = param['DVTP5'.swapcase()]\n self.DVTP5given = True\n else:\n if self.DVTP5given == False:\n self.DVTP5 = 0.0\n if 'LDVTP5' in param:\n self.LDVTP5 = param['LDVTP5']\n self.LDVTP5given = True\n elif 'LDVTP5'.swapcase() in param:\n self.LDVTP5 = param['LDVTP5'.swapcase()]\n self.LDVTP5given = True\n else:\n if self.LDVTP5given == False:\n self.LDVTP5 = 0.0\n if 'WDVTP5' in param:\n self.WDVTP5 = param['WDVTP5']\n self.WDVTP5given = True\n elif 'WDVTP5'.swapcase() in param:\n self.WDVTP5 = param['WDVTP5'.swapcase()]\n self.WDVTP5given = True\n else:\n if self.WDVTP5given == False:\n self.WDVTP5 = 0.0\n if 'PDVTP5' in param:\n self.PDVTP5 = param['PDVTP5']\n self.PDVTP5given = True\n elif 'PDVTP5'.swapcase() in param:\n self.PDVTP5 = param['PDVTP5'.swapcase()]\n self.PDVTP5given = True\n else:\n if self.PDVTP5given == False:\n self.PDVTP5 = 0.0\n if 'PHIN' in param:\n self.PHIN = param['PHIN']\n self.PHINgiven = True\n elif 'PHIN'.swapcase() in param:\n self.PHIN = param['PHIN'.swapcase()]\n self.PHINgiven = True\n else:\n if self.PHINgiven == False:\n self.PHIN = 0.045\n if 'LPHIN' in param:\n self.LPHIN = param['LPHIN']\n self.LPHINgiven = True\n elif 'LPHIN'.swapcase() in param:\n self.LPHIN = param['LPHIN'.swapcase()]\n self.LPHINgiven = True\n else:\n if self.LPHINgiven == False:\n self.LPHIN = 0.0\n if 'WPHIN' in param:\n self.WPHIN = param['WPHIN']\n self.WPHINgiven = True\n elif 'WPHIN'.swapcase() in param:\n self.WPHIN = param['WPHIN'.swapcase()]\n self.WPHINgiven = True\n else:\n if self.WPHINgiven == False:\n self.WPHIN = 0.0\n if 'PPHIN' in param:\n self.PPHIN = param['PPHIN']\n self.PPHINgiven = True\n elif 'PPHIN'.swapcase() in param:\n self.PPHIN = param['PPHIN'.swapcase()]\n self.PPHINgiven = True\n else:\n if self.PPHINgiven == False:\n self.PPHIN = 0.0\n if 'ETA0' in param:\n self.ETA0 = param['ETA0']\n self.ETA0given = True\n elif 'ETA0'.swapcase() in param:\n self.ETA0 = param['ETA0'.swapcase()]\n self.ETA0given = True\n else:\n if self.ETA0given == False:\n self.ETA0 = 0.08\n if 'LETA0' in param:\n self.LETA0 = param['LETA0']\n self.LETA0given = True\n elif 'LETA0'.swapcase() in param:\n self.LETA0 = param['LETA0'.swapcase()]\n self.LETA0given = True\n else:\n if self.LETA0given == False:\n self.LETA0 = 0.0\n if 'WETA0' in param:\n self.WETA0 = param['WETA0']\n self.WETA0given = True\n elif 'WETA0'.swapcase() in param:\n self.WETA0 = param['WETA0'.swapcase()]\n self.WETA0given = True\n else:\n if self.WETA0given == False:\n self.WETA0 = 0.0\n if 'PETA0' in param:\n self.PETA0 = param['PETA0']\n self.PETA0given = True\n elif 'PETA0'.swapcase() in param:\n self.PETA0 = param['PETA0'.swapcase()]\n self.PETA0given = True\n else:\n if self.PETA0given == False:\n self.PETA0 = 0.0\n if 'ETA0R' in param:\n self.ETA0R = param['ETA0R']\n self.ETA0Rgiven = True\n elif 'ETA0R'.swapcase() in param:\n self.ETA0R = param['ETA0R'.swapcase()]\n self.ETA0Rgiven = True\n else:\n if self.ETA0Rgiven == False:\n self.ETA0R = self.ETA0\n if 'LETA0R' in param:\n self.LETA0R = param['LETA0R']\n self.LETA0Rgiven = True\n elif 'LETA0R'.swapcase() in param:\n self.LETA0R = param['LETA0R'.swapcase()]\n self.LETA0Rgiven = True\n else:\n if self.LETA0Rgiven == False:\n self.LETA0R = self.LETA0\n if 'WETA0R' in param:\n self.WETA0R = param['WETA0R']\n self.WETA0Rgiven = True\n elif 'WETA0R'.swapcase() in param:\n self.WETA0R = param['WETA0R'.swapcase()]\n self.WETA0Rgiven = True\n else:\n if self.WETA0Rgiven == False:\n self.WETA0R = self.WETA0\n if 'PETA0R' in param:\n self.PETA0R = param['PETA0R']\n self.PETA0Rgiven = True\n elif 'PETA0R'.swapcase() in param:\n self.PETA0R = param['PETA0R'.swapcase()]\n self.PETA0Rgiven = True\n else:\n if self.PETA0Rgiven == False:\n self.PETA0R = self.PETA0\n if 'DSUB' in param:\n self.DSUB = param['DSUB']\n self.DSUBgiven = True\n elif 'DSUB'.swapcase() in param:\n self.DSUB = param['DSUB'.swapcase()]\n self.DSUBgiven = True\n else:\n if self.DSUBgiven == False:\n self.DSUB = 1.0\n if 'ETAB' in param:\n self.ETAB = param['ETAB']\n self.ETABgiven = True\n elif 'ETAB'.swapcase() in param:\n self.ETAB = param['ETAB'.swapcase()]\n self.ETABgiven = True\n else:\n if self.ETABgiven == False:\n self.ETAB = -0.07\n if 'ETABEXP' in param:\n self.ETABEXP = param['ETABEXP']\n self.ETABEXPgiven = True\n elif 'ETABEXP'.swapcase() in param:\n self.ETABEXP = param['ETABEXP'.swapcase()]\n self.ETABEXPgiven = True\n else:\n if self.ETABEXPgiven == False:\n self.ETABEXP = 1.0\n if 'LETAB' in param:\n self.LETAB = param['LETAB']\n self.LETABgiven = True\n elif 'LETAB'.swapcase() in param:\n self.LETAB = param['LETAB'.swapcase()]\n self.LETABgiven = True\n else:\n if self.LETABgiven == False:\n self.LETAB = 0.0\n if 'WETAB' in param:\n self.WETAB = param['WETAB']\n self.WETABgiven = True\n elif 'WETAB'.swapcase() in param:\n self.WETAB = param['WETAB'.swapcase()]\n self.WETABgiven = True\n else:\n if self.WETABgiven == False:\n self.WETAB = 0.0\n if 'PETAB' in param:\n self.PETAB = param['PETAB']\n self.PETABgiven = True\n elif 'PETAB'.swapcase() in param:\n self.PETAB = param['PETAB'.swapcase()]\n self.PETABgiven = True\n else:\n if self.PETABgiven == False:\n self.PETAB = 0.0\n if 'K1' in param:\n self.K1 = param['K1']\n self.K1given = True\n elif 'K1'.swapcase() in param:\n self.K1 = param['K1'.swapcase()]\n self.K1given = True\n else:\n if self.K1given == False:\n self.K1 = 0.0\n if 'K1L' in param:\n self.K1L = param['K1L']\n self.K1Lgiven = True\n elif 'K1L'.swapcase() in param:\n self.K1L = param['K1L'.swapcase()]\n self.K1Lgiven = True\n else:\n if self.K1Lgiven == False:\n self.K1L = 0.0\n if 'K1LEXP' in param:\n self.K1LEXP = param['K1LEXP']\n self.K1LEXPgiven = True\n elif 'K1LEXP'.swapcase() in param:\n self.K1LEXP = param['K1LEXP'.swapcase()]\n self.K1LEXPgiven = True\n else:\n if self.K1LEXPgiven == False:\n self.K1LEXP = 1.0\n if 'K1W' in param:\n self.K1W = param['K1W']\n self.K1Wgiven = True\n elif 'K1W'.swapcase() in param:\n self.K1W = param['K1W'.swapcase()]\n self.K1Wgiven = True\n else:\n if self.K1Wgiven == False:\n self.K1W = 0.0\n if 'K1WEXP' in param:\n self.K1WEXP = param['K1WEXP']\n self.K1WEXPgiven = True\n elif 'K1WEXP'.swapcase() in param:\n self.K1WEXP = param['K1WEXP'.swapcase()]\n self.K1WEXPgiven = True\n else:\n if self.K1WEXPgiven == False:\n self.K1WEXP = 1.0\n if 'K1WL' in param:\n self.K1WL = param['K1WL']\n self.K1WLgiven = True\n elif 'K1WL'.swapcase() in param:\n self.K1WL = param['K1WL'.swapcase()]\n self.K1WLgiven = True\n else:\n if self.K1WLgiven == False:\n self.K1WL = 0.0\n if 'K1WLEXP' in param:\n self.K1WLEXP = param['K1WLEXP']\n self.K1WLEXPgiven = True\n elif 'K1WLEXP'.swapcase() in param:\n self.K1WLEXP = param['K1WLEXP'.swapcase()]\n self.K1WLEXPgiven = True\n else:\n if self.K1WLEXPgiven == False:\n self.K1WLEXP = 1.0\n if 'LK1' in param:\n self.LK1 = param['LK1']\n self.LK1given = True\n elif 'LK1'.swapcase() in param:\n self.LK1 = param['LK1'.swapcase()]\n self.LK1given = True\n else:\n if self.LK1given == False:\n self.LK1 = 0.0\n if 'WK1' in param:\n self.WK1 = param['WK1']\n self.WK1given = True\n elif 'WK1'.swapcase() in param:\n self.WK1 = param['WK1'.swapcase()]\n self.WK1given = True\n else:\n if self.WK1given == False:\n self.WK1 = 0.0\n if 'PK1' in param:\n self.PK1 = param['PK1']\n self.PK1given = True\n elif 'PK1'.swapcase() in param:\n self.PK1 = param['PK1'.swapcase()]\n self.PK1given = True\n else:\n if self.PK1given == False:\n self.PK1 = 0.0\n if 'K2' in param:\n self.K2 = param['K2']\n self.K2given = True\n elif 'K2'.swapcase() in param:\n self.K2 = param['K2'.swapcase()]\n self.K2given = True\n else:\n if self.K2given == False:\n self.K2 = 0.0\n if 'K2L' in param:\n self.K2L = param['K2L']\n self.K2Lgiven = True\n elif 'K2L'.swapcase() in param:\n self.K2L = param['K2L'.swapcase()]\n self.K2Lgiven = True\n else:\n if self.K2Lgiven == False:\n self.K2L = 0.0\n if 'K2LEXP' in param:\n self.K2LEXP = param['K2LEXP']\n self.K2LEXPgiven = True\n elif 'K2LEXP'.swapcase() in param:\n self.K2LEXP = param['K2LEXP'.swapcase()]\n self.K2LEXPgiven = True\n else:\n if self.K2LEXPgiven == False:\n self.K2LEXP = 1.0\n if 'K2W' in param:\n self.K2W = param['K2W']\n self.K2Wgiven = True\n elif 'K2W'.swapcase() in param:\n self.K2W = param['K2W'.swapcase()]\n self.K2Wgiven = True\n else:\n if self.K2Wgiven == False:\n self.K2W = 0.0\n if 'K2WEXP' in param:\n self.K2WEXP = param['K2WEXP']\n self.K2WEXPgiven = True\n elif 'K2WEXP'.swapcase() in param:\n self.K2WEXP = param['K2WEXP'.swapcase()]\n self.K2WEXPgiven = True\n else:\n if self.K2WEXPgiven == False:\n self.K2WEXP = 1.0\n if 'K2WL' in param:\n self.K2WL = param['K2WL']\n self.K2WLgiven = True\n elif 'K2WL'.swapcase() in param:\n self.K2WL = param['K2WL'.swapcase()]\n self.K2WLgiven = True\n else:\n if self.K2WLgiven == False:\n self.K2WL = 0.0\n if 'K2WLEXP' in param:\n self.K2WLEXP = param['K2WLEXP']\n self.K2WLEXPgiven = True\n elif 'K2WLEXP'.swapcase() in param:\n self.K2WLEXP = param['K2WLEXP'.swapcase()]\n self.K2WLEXPgiven = True\n else:\n if self.K2WLEXPgiven == False:\n self.K2WLEXP = 1.0\n if 'LK2' in param:\n self.LK2 = param['LK2']\n self.LK2given = True\n elif 'LK2'.swapcase() in param:\n self.LK2 = param['LK2'.swapcase()]\n self.LK2given = True\n else:\n if self.LK2given == False:\n self.LK2 = 0.0\n if 'WK2' in param:\n self.WK2 = param['WK2']\n self.WK2given = True\n elif 'WK2'.swapcase() in param:\n self.WK2 = param['WK2'.swapcase()]\n self.WK2given = True\n else:\n if self.WK2given == False:\n self.WK2 = 0.0\n if 'PK2' in param:\n self.PK2 = param['PK2']\n self.PK2given = True\n elif 'PK2'.swapcase() in param:\n self.PK2 = param['PK2'.swapcase()]\n self.PK2given = True\n else:\n if self.PK2given == False:\n self.PK2 = 0.0\n if 'ADOS' in param:\n self.ADOS = param['ADOS']\n self.ADOSgiven = True\n elif 'ADOS'.swapcase() in param:\n self.ADOS = param['ADOS'.swapcase()]\n self.ADOSgiven = True\n else:\n if self.ADOSgiven == False:\n self.ADOS = 0.0\n if 'BDOS' in param:\n self.BDOS = param['BDOS']\n self.BDOSgiven = True\n elif 'BDOS'.swapcase() in param:\n self.BDOS = param['BDOS'.swapcase()]\n self.BDOSgiven = True\n else:\n if self.BDOSgiven == False:\n self.BDOS = 1.0\n if 'QM0' in param:\n self.QM0 = param['QM0']\n self.QM0given = True\n elif 'QM0'.swapcase() in param:\n self.QM0 = param['QM0'.swapcase()]\n self.QM0given = True\n else:\n if self.QM0given == False:\n self.QM0 = 0.001\n if 'ETAQM' in param:\n self.ETAQM = param['ETAQM']\n self.ETAQMgiven = True\n elif 'ETAQM'.swapcase() in param:\n self.ETAQM = param['ETAQM'.swapcase()]\n self.ETAQMgiven = True\n else:\n if self.ETAQMgiven == False:\n self.ETAQM = 0.54\n if 'CIT' in param:\n self.CIT = param['CIT']\n self.CITgiven = True\n elif 'CIT'.swapcase() in param:\n self.CIT = param['CIT'.swapcase()]\n self.CITgiven = True\n else:\n if self.CITgiven == False:\n self.CIT = 0.0\n if 'LCIT' in param:\n self.LCIT = param['LCIT']\n self.LCITgiven = True\n elif 'LCIT'.swapcase() in param:\n self.LCIT = param['LCIT'.swapcase()]\n self.LCITgiven = True\n else:\n if self.LCITgiven == False:\n self.LCIT = 0.0\n if 'WCIT' in param:\n self.WCIT = param['WCIT']\n self.WCITgiven = True\n elif 'WCIT'.swapcase() in param:\n self.WCIT = param['WCIT'.swapcase()]\n self.WCITgiven = True\n else:\n if self.WCITgiven == False:\n self.WCIT = 0.0\n if 'PCIT' in param:\n self.PCIT = param['PCIT']\n self.PCITgiven = True\n elif 'PCIT'.swapcase() in param:\n self.PCIT = param['PCIT'.swapcase()]\n self.PCITgiven = True\n else:\n if self.PCITgiven == False:\n self.PCIT = 0.0\n if 'NFACTOR' in param:\n self.NFACTOR = param['NFACTOR']\n self.NFACTORgiven = True\n elif 'NFACTOR'.swapcase() in param:\n self.NFACTOR = param['NFACTOR'.swapcase()]\n self.NFACTORgiven = True\n else:\n if self.NFACTORgiven == False:\n self.NFACTOR = 0.0\n if 'NFACTORL' in param:\n self.NFACTORL = param['NFACTORL']\n self.NFACTORLgiven = True\n elif 'NFACTORL'.swapcase() in param:\n self.NFACTORL = param['NFACTORL'.swapcase()]\n self.NFACTORLgiven = True\n else:\n if self.NFACTORLgiven == False:\n self.NFACTORL = 0.0\n if 'NFACTORLEXP' in param:\n self.NFACTORLEXP = param['NFACTORLEXP']\n self.NFACTORLEXPgiven = True\n elif 'NFACTORLEXP'.swapcase() in param:\n self.NFACTORLEXP = param['NFACTORLEXP'.swapcase()]\n self.NFACTORLEXPgiven = True\n else:\n if self.NFACTORLEXPgiven == False:\n self.NFACTORLEXP = 1.0\n if 'NFACTORW' in param:\n self.NFACTORW = param['NFACTORW']\n self.NFACTORWgiven = True\n elif 'NFACTORW'.swapcase() in param:\n self.NFACTORW = param['NFACTORW'.swapcase()]\n self.NFACTORWgiven = True\n else:\n if self.NFACTORWgiven == False:\n self.NFACTORW = 0.0\n if 'NFACTORWEXP' in param:\n self.NFACTORWEXP = param['NFACTORWEXP']\n self.NFACTORWEXPgiven = True\n elif 'NFACTORWEXP'.swapcase() in param:\n self.NFACTORWEXP = param['NFACTORWEXP'.swapcase()]\n self.NFACTORWEXPgiven = True\n else:\n if self.NFACTORWEXPgiven == False:\n self.NFACTORWEXP = 1.0\n if 'NFACTORWL' in param:\n self.NFACTORWL = param['NFACTORWL']\n self.NFACTORWLgiven = True\n elif 'NFACTORWL'.swapcase() in param:\n self.NFACTORWL = param['NFACTORWL'.swapcase()]\n self.NFACTORWLgiven = True\n else:\n if self.NFACTORWLgiven == False:\n self.NFACTORWL = 0.0\n if 'NFACTORWLEXP' in param:\n self.NFACTORWLEXP = param['NFACTORWLEXP']\n self.NFACTORWLEXPgiven = True\n elif 'NFACTORWLEXP'.swapcase() in param:\n self.NFACTORWLEXP = param['NFACTORWLEXP'.swapcase()]\n self.NFACTORWLEXPgiven = True\n else:\n if self.NFACTORWLEXPgiven == False:\n self.NFACTORWLEXP = 1.0\n if 'LNFACTOR' in param:\n self.LNFACTOR = param['LNFACTOR']\n self.LNFACTORgiven = True\n elif 'LNFACTOR'.swapcase() in param:\n self.LNFACTOR = param['LNFACTOR'.swapcase()]\n self.LNFACTORgiven = True\n else:\n if self.LNFACTORgiven == False:\n self.LNFACTOR = 0.0\n if 'WNFACTOR' in param:\n self.WNFACTOR = param['WNFACTOR']\n self.WNFACTORgiven = True\n elif 'WNFACTOR'.swapcase() in param:\n self.WNFACTOR = param['WNFACTOR'.swapcase()]\n self.WNFACTORgiven = True\n else:\n if self.WNFACTORgiven == False:\n self.WNFACTOR = 0.0\n if 'PNFACTOR' in param:\n self.PNFACTOR = param['PNFACTOR']\n self.PNFACTORgiven = True\n elif 'PNFACTOR'.swapcase() in param:\n self.PNFACTOR = param['PNFACTOR'.swapcase()]\n self.PNFACTORgiven = True\n else:\n if self.PNFACTORgiven == False:\n self.PNFACTOR = 0.0\n if 'CDSCD' in param:\n self.CDSCD = param['CDSCD']\n self.CDSCDgiven = True\n elif 'CDSCD'.swapcase() in param:\n self.CDSCD = param['CDSCD'.swapcase()]\n self.CDSCDgiven = True\n else:\n if self.CDSCDgiven == False:\n self.CDSCD = 1e-09\n if 'CDSCDL' in param:\n self.CDSCDL = param['CDSCDL']\n self.CDSCDLgiven = True\n elif 'CDSCDL'.swapcase() in param:\n self.CDSCDL = param['CDSCDL'.swapcase()]\n self.CDSCDLgiven = True\n else:\n if self.CDSCDLgiven == False:\n self.CDSCDL = 0.0\n if 'CDSCDLEXP' in param:\n self.CDSCDLEXP = param['CDSCDLEXP']\n self.CDSCDLEXPgiven = True\n elif 'CDSCDLEXP'.swapcase() in param:\n self.CDSCDLEXP = param['CDSCDLEXP'.swapcase()]\n self.CDSCDLEXPgiven = True\n else:\n if self.CDSCDLEXPgiven == False:\n self.CDSCDLEXP = 1.0\n if 'LCDSCD' in param:\n self.LCDSCD = param['LCDSCD']\n self.LCDSCDgiven = True\n elif 'LCDSCD'.swapcase() in param:\n self.LCDSCD = param['LCDSCD'.swapcase()]\n self.LCDSCDgiven = True\n else:\n if self.LCDSCDgiven == False:\n self.LCDSCD = 0.0\n if 'WCDSCD' in param:\n self.WCDSCD = param['WCDSCD']\n self.WCDSCDgiven = True\n elif 'WCDSCD'.swapcase() in param:\n self.WCDSCD = param['WCDSCD'.swapcase()]\n self.WCDSCDgiven = True\n else:\n if self.WCDSCDgiven == False:\n self.WCDSCD = 0.0\n if 'PCDSCD' in param:\n self.PCDSCD = param['PCDSCD']\n self.PCDSCDgiven = True\n elif 'PCDSCD'.swapcase() in param:\n self.PCDSCD = param['PCDSCD'.swapcase()]\n self.PCDSCDgiven = True\n else:\n if self.PCDSCDgiven == False:\n self.PCDSCD = 0.0\n if 'CDSCDR' in param:\n self.CDSCDR = param['CDSCDR']\n self.CDSCDRgiven = True\n elif 'CDSCDR'.swapcase() in param:\n self.CDSCDR = param['CDSCDR'.swapcase()]\n self.CDSCDRgiven = True\n else:\n if self.CDSCDRgiven == False:\n self.CDSCDR = self.CDSCD\n if 'CDSCDLR' in param:\n self.CDSCDLR = param['CDSCDLR']\n self.CDSCDLRgiven = True\n elif 'CDSCDLR'.swapcase() in param:\n self.CDSCDLR = param['CDSCDLR'.swapcase()]\n self.CDSCDLRgiven = True\n else:\n if self.CDSCDLRgiven == False:\n self.CDSCDLR = self.CDSCDL\n if 'LCDSCDR' in param:\n self.LCDSCDR = param['LCDSCDR']\n self.LCDSCDRgiven = True\n elif 'LCDSCDR'.swapcase() in param:\n self.LCDSCDR = param['LCDSCDR'.swapcase()]\n self.LCDSCDRgiven = True\n else:\n if self.LCDSCDRgiven == False:\n self.LCDSCDR = self.LCDSCD\n if 'WCDSCDR' in param:\n self.WCDSCDR = param['WCDSCDR']\n self.WCDSCDRgiven = True\n elif 'WCDSCDR'.swapcase() in param:\n self.WCDSCDR = param['WCDSCDR'.swapcase()]\n self.WCDSCDRgiven = True\n else:\n if self.WCDSCDRgiven == False:\n self.WCDSCDR = self.WCDSCD\n if 'PCDSCDR' in param:\n self.PCDSCDR = param['PCDSCDR']\n self.PCDSCDRgiven = True\n elif 'PCDSCDR'.swapcase() in param:\n self.PCDSCDR = param['PCDSCDR'.swapcase()]\n self.PCDSCDRgiven = True\n else:\n if self.PCDSCDRgiven == False:\n self.PCDSCDR = self.PCDSCD\n if 'CDSCB' in param:\n self.CDSCB = param['CDSCB']\n self.CDSCBgiven = True\n elif 'CDSCB'.swapcase() in param:\n self.CDSCB = param['CDSCB'.swapcase()]\n self.CDSCBgiven = True\n else:\n if self.CDSCBgiven == False:\n self.CDSCB = 0.0\n if 'CDSCBL' in param:\n self.CDSCBL = param['CDSCBL']\n self.CDSCBLgiven = True\n elif 'CDSCBL'.swapcase() in param:\n self.CDSCBL = param['CDSCBL'.swapcase()]\n self.CDSCBLgiven = True\n else:\n if self.CDSCBLgiven == False:\n self.CDSCBL = 0.0\n if 'CDSCBLEXP' in param:\n self.CDSCBLEXP = param['CDSCBLEXP']\n self.CDSCBLEXPgiven = True\n elif 'CDSCBLEXP'.swapcase() in param:\n self.CDSCBLEXP = param['CDSCBLEXP'.swapcase()]\n self.CDSCBLEXPgiven = True\n else:\n if self.CDSCBLEXPgiven == False:\n self.CDSCBLEXP = 1.0\n if 'LCDSCB' in param:\n self.LCDSCB = param['LCDSCB']\n self.LCDSCBgiven = True\n elif 'LCDSCB'.swapcase() in param:\n self.LCDSCB = param['LCDSCB'.swapcase()]\n self.LCDSCBgiven = True\n else:\n if self.LCDSCBgiven == False:\n self.LCDSCB = 0.0\n if 'WCDSCB' in param:\n self.WCDSCB = param['WCDSCB']\n self.WCDSCBgiven = True\n elif 'WCDSCB'.swapcase() in param:\n self.WCDSCB = param['WCDSCB'.swapcase()]\n self.WCDSCBgiven = True\n else:\n if self.WCDSCBgiven == False:\n self.WCDSCB = 0.0\n if 'PCDSCB' in param:\n self.PCDSCB = param['PCDSCB']\n self.PCDSCBgiven = True\n elif 'PCDSCB'.swapcase() in param:\n self.PCDSCB = param['PCDSCB'.swapcase()]\n self.PCDSCBgiven = True\n else:\n if self.PCDSCBgiven == False:\n self.PCDSCB = 0.0\n if 'VSAT' in param:\n self.VSAT = param['VSAT']\n self.VSATgiven = True\n elif 'VSAT'.swapcase() in param:\n self.VSAT = param['VSAT'.swapcase()]\n self.VSATgiven = True\n else:\n if self.VSATgiven == False:\n self.VSAT = 100000.0\n if 'LVSAT' in param:\n self.LVSAT = param['LVSAT']\n self.LVSATgiven = True\n elif 'LVSAT'.swapcase() in param:\n self.LVSAT = param['LVSAT'.swapcase()]\n self.LVSATgiven = True\n else:\n if self.LVSATgiven == False:\n self.LVSAT = 0.0\n if 'WVSAT' in param:\n self.WVSAT = param['WVSAT']\n self.WVSATgiven = True\n elif 'WVSAT'.swapcase() in param:\n self.WVSAT = param['WVSAT'.swapcase()]\n self.WVSATgiven = True\n else:\n if self.WVSATgiven == False:\n self.WVSAT = 0.0\n if 'PVSAT' in param:\n self.PVSAT = param['PVSAT']\n self.PVSATgiven = True\n elif 'PVSAT'.swapcase() in param:\n self.PVSAT = param['PVSAT'.swapcase()]\n self.PVSATgiven = True\n else:\n if self.PVSATgiven == False:\n self.PVSAT = 0.0\n if 'VSATL' in param:\n self.VSATL = param['VSATL']\n self.VSATLgiven = True\n elif 'VSATL'.swapcase() in param:\n self.VSATL = param['VSATL'.swapcase()]\n self.VSATLgiven = True\n else:\n if self.VSATLgiven == False:\n self.VSATL = 0.0\n if 'VSATLEXP' in param:\n self.VSATLEXP = param['VSATLEXP']\n self.VSATLEXPgiven = True\n elif 'VSATLEXP'.swapcase() in param:\n self.VSATLEXP = param['VSATLEXP'.swapcase()]\n self.VSATLEXPgiven = True\n else:\n if self.VSATLEXPgiven == False:\n self.VSATLEXP = 1.0\n if 'VSATW' in param:\n self.VSATW = param['VSATW']\n self.VSATWgiven = True\n elif 'VSATW'.swapcase() in param:\n self.VSATW = param['VSATW'.swapcase()]\n self.VSATWgiven = True\n else:\n if self.VSATWgiven == False:\n self.VSATW = 0.0\n if 'VSATWEXP' in param:\n self.VSATWEXP = param['VSATWEXP']\n self.VSATWEXPgiven = True\n elif 'VSATWEXP'.swapcase() in param:\n self.VSATWEXP = param['VSATWEXP'.swapcase()]\n self.VSATWEXPgiven = True\n else:\n if self.VSATWEXPgiven == False:\n self.VSATWEXP = 1.0\n if 'VSATWL' in param:\n self.VSATWL = param['VSATWL']\n self.VSATWLgiven = True\n elif 'VSATWL'.swapcase() in param:\n self.VSATWL = param['VSATWL'.swapcase()]\n self.VSATWLgiven = True\n else:\n if self.VSATWLgiven == False:\n self.VSATWL = 0.0\n if 'VSATWLEXP' in param:\n self.VSATWLEXP = param['VSATWLEXP']\n self.VSATWLEXPgiven = True\n elif 'VSATWLEXP'.swapcase() in param:\n self.VSATWLEXP = param['VSATWLEXP'.swapcase()]\n self.VSATWLEXPgiven = True\n else:\n if self.VSATWLEXPgiven == False:\n self.VSATWLEXP = 1.0\n if 'VSATR' in param:\n self.VSATR = param['VSATR']\n self.VSATRgiven = True\n elif 'VSATR'.swapcase() in param:\n self.VSATR = param['VSATR'.swapcase()]\n self.VSATRgiven = True\n else:\n if self.VSATRgiven == False:\n self.VSATR = self.VSAT\n if 'LVSATR' in param:\n self.LVSATR = param['LVSATR']\n self.LVSATRgiven = True\n elif 'LVSATR'.swapcase() in param:\n self.LVSATR = param['LVSATR'.swapcase()]\n self.LVSATRgiven = True\n else:\n if self.LVSATRgiven == False:\n self.LVSATR = self.LVSAT\n if 'WVSATR' in param:\n self.WVSATR = param['WVSATR']\n self.WVSATRgiven = True\n elif 'WVSATR'.swapcase() in param:\n self.WVSATR = param['WVSATR'.swapcase()]\n self.WVSATRgiven = True\n else:\n if self.WVSATRgiven == False:\n self.WVSATR = self.WVSAT\n if 'PVSATR' in param:\n self.PVSATR = param['PVSATR']\n self.PVSATRgiven = True\n elif 'PVSATR'.swapcase() in param:\n self.PVSATR = param['PVSATR'.swapcase()]\n self.PVSATRgiven = True\n else:\n if self.PVSATRgiven == False:\n self.PVSATR = self.PVSAT\n if 'DELTA' in param:\n self.DELTA = param['DELTA']\n self.DELTAgiven = True\n elif 'DELTA'.swapcase() in param:\n self.DELTA = param['DELTA'.swapcase()]\n self.DELTAgiven = True\n else:\n if self.DELTAgiven == False:\n self.DELTA = 0.125\n if 'LDELTA' in param:\n self.LDELTA = param['LDELTA']\n self.LDELTAgiven = True\n elif 'LDELTA'.swapcase() in param:\n self.LDELTA = param['LDELTA'.swapcase()]\n self.LDELTAgiven = True\n else:\n if self.LDELTAgiven == False:\n self.LDELTA = 0.0\n if 'WDELTA' in param:\n self.WDELTA = param['WDELTA']\n self.WDELTAgiven = True\n elif 'WDELTA'.swapcase() in param:\n self.WDELTA = param['WDELTA'.swapcase()]\n self.WDELTAgiven = True\n else:\n if self.WDELTAgiven == False:\n self.WDELTA = 0.0\n if 'PDELTA' in param:\n self.PDELTA = param['PDELTA']\n self.PDELTAgiven = True\n elif 'PDELTA'.swapcase() in param:\n self.PDELTA = param['PDELTA'.swapcase()]\n self.PDELTAgiven = True\n else:\n if self.PDELTAgiven == False:\n self.PDELTA = 0.0\n if 'DELTAL' in param:\n self.DELTAL = param['DELTAL']\n self.DELTALgiven = True\n elif 'DELTAL'.swapcase() in param:\n self.DELTAL = param['DELTAL'.swapcase()]\n self.DELTALgiven = True\n else:\n if self.DELTALgiven == False:\n self.DELTAL = 0.0\n if 'DELTALEXP' in param:\n self.DELTALEXP = param['DELTALEXP']\n self.DELTALEXPgiven = True\n elif 'DELTALEXP'.swapcase() in param:\n self.DELTALEXP = param['DELTALEXP'.swapcase()]\n self.DELTALEXPgiven = True\n else:\n if self.DELTALEXPgiven == False:\n self.DELTALEXP = 1.0\n if 'VSATCV' in param:\n self.VSATCV = param['VSATCV']\n self.VSATCVgiven = True\n elif 'VSATCV'.swapcase() in param:\n self.VSATCV = param['VSATCV'.swapcase()]\n self.VSATCVgiven = True\n else:\n if self.VSATCVgiven == False:\n self.VSATCV = 100000.0\n if 'LVSATCV' in param:\n self.LVSATCV = param['LVSATCV']\n self.LVSATCVgiven = True\n elif 'LVSATCV'.swapcase() in param:\n self.LVSATCV = param['LVSATCV'.swapcase()]\n self.LVSATCVgiven = True\n else:\n if self.LVSATCVgiven == False:\n self.LVSATCV = 0.0\n if 'WVSATCV' in param:\n self.WVSATCV = param['WVSATCV']\n self.WVSATCVgiven = True\n elif 'WVSATCV'.swapcase() in param:\n self.WVSATCV = param['WVSATCV'.swapcase()]\n self.WVSATCVgiven = True\n else:\n if self.WVSATCVgiven == False:\n self.WVSATCV = 0.0\n if 'PVSATCV' in param:\n self.PVSATCV = param['PVSATCV']\n self.PVSATCVgiven = True\n elif 'PVSATCV'.swapcase() in param:\n self.PVSATCV = param['PVSATCV'.swapcase()]\n self.PVSATCVgiven = True\n else:\n if self.PVSATCVgiven == False:\n self.PVSATCV = 0.0\n if 'VSATCVL' in param:\n self.VSATCVL = param['VSATCVL']\n self.VSATCVLgiven = True\n elif 'VSATCVL'.swapcase() in param:\n self.VSATCVL = param['VSATCVL'.swapcase()]\n self.VSATCVLgiven = True\n else:\n if self.VSATCVLgiven == False:\n self.VSATCVL = 0.0\n if 'VSATCVLEXP' in param:\n self.VSATCVLEXP = param['VSATCVLEXP']\n self.VSATCVLEXPgiven = True\n elif 'VSATCVLEXP'.swapcase() in param:\n self.VSATCVLEXP = param['VSATCVLEXP'.swapcase()]\n self.VSATCVLEXPgiven = True\n else:\n if self.VSATCVLEXPgiven == False:\n self.VSATCVLEXP = 1.0\n if 'VSATCVW' in param:\n self.VSATCVW = param['VSATCVW']\n self.VSATCVWgiven = True\n elif 'VSATCVW'.swapcase() in param:\n self.VSATCVW = param['VSATCVW'.swapcase()]\n self.VSATCVWgiven = True\n else:\n if self.VSATCVWgiven == False:\n self.VSATCVW = 0.0\n if 'VSATCVWEXP' in param:\n self.VSATCVWEXP = param['VSATCVWEXP']\n self.VSATCVWEXPgiven = True\n elif 'VSATCVWEXP'.swapcase() in param:\n self.VSATCVWEXP = param['VSATCVWEXP'.swapcase()]\n self.VSATCVWEXPgiven = True\n else:\n if self.VSATCVWEXPgiven == False:\n self.VSATCVWEXP = 1.0\n if 'VSATCVWL' in param:\n self.VSATCVWL = param['VSATCVWL']\n self.VSATCVWLgiven = True\n elif 'VSATCVWL'.swapcase() in param:\n self.VSATCVWL = param['VSATCVWL'.swapcase()]\n self.VSATCVWLgiven = True\n else:\n if self.VSATCVWLgiven == False:\n self.VSATCVWL = 0.0\n if 'VSATCVWLEXP' in param:\n self.VSATCVWLEXP = param['VSATCVWLEXP']\n self.VSATCVWLEXPgiven = True\n elif 'VSATCVWLEXP'.swapcase() in param:\n self.VSATCVWLEXP = param['VSATCVWLEXP'.swapcase()]\n self.VSATCVWLEXPgiven = True\n else:\n if self.VSATCVWLEXPgiven == False:\n self.VSATCVWLEXP = 1.0\n if 'UP1' in param:\n self.UP1 = param['UP1']\n self.UP1given = True\n elif 'UP1'.swapcase() in param:\n self.UP1 = param['UP1'.swapcase()]\n self.UP1given = True\n else:\n if self.UP1given == False:\n self.UP1 = 0.0\n if 'LP1' in param:\n self.LP1 = param['LP1']\n self.LP1given = True\n elif 'LP1'.swapcase() in param:\n self.LP1 = param['LP1'.swapcase()]\n self.LP1given = True\n else:\n if self.LP1given == False:\n self.LP1 = 1e-08\n if 'UP2' in param:\n self.UP2 = param['UP2']\n self.UP2given = True\n elif 'UP2'.swapcase() in param:\n self.UP2 = param['UP2'.swapcase()]\n self.UP2given = True\n else:\n if self.UP2given == False:\n self.UP2 = 0.0\n if 'LP2' in param:\n self.LP2 = param['LP2']\n self.LP2given = True\n elif 'LP2'.swapcase() in param:\n self.LP2 = param['LP2'.swapcase()]\n self.LP2given = True\n else:\n if self.LP2given == False:\n self.LP2 = 1e-08\n if 'U0' in param:\n self.U0 = param['U0']\n self.U0given = True\n elif 'U0'.swapcase() in param:\n self.U0 = param['U0'.swapcase()]\n self.U0given = True\n else:\n if self.U0given == False:\n self.U0 = 0.067\n if 'U0L' in param:\n self.U0L = param['U0L']\n self.U0Lgiven = True\n elif 'U0L'.swapcase() in param:\n self.U0L = param['U0L'.swapcase()]\n self.U0Lgiven = True\n else:\n if self.U0Lgiven == False:\n self.U0L = 0.0\n if 'U0LEXP' in param:\n self.U0LEXP = param['U0LEXP']\n self.U0LEXPgiven = True\n elif 'U0LEXP'.swapcase() in param:\n self.U0LEXP = param['U0LEXP'.swapcase()]\n self.U0LEXPgiven = True\n else:\n if self.U0LEXPgiven == False:\n self.U0LEXP = 1.0\n if 'LU0' in param:\n self.LU0 = param['LU0']\n self.LU0given = True\n elif 'LU0'.swapcase() in param:\n self.LU0 = param['LU0'.swapcase()]\n self.LU0given = True\n else:\n if self.LU0given == False:\n self.LU0 = 0.0\n if 'WU0' in param:\n self.WU0 = param['WU0']\n self.WU0given = True\n elif 'WU0'.swapcase() in param:\n self.WU0 = param['WU0'.swapcase()]\n self.WU0given = True\n else:\n if self.WU0given == False:\n self.WU0 = 0.0\n if 'PU0' in param:\n self.PU0 = param['PU0']\n self.PU0given = True\n elif 'PU0'.swapcase() in param:\n self.PU0 = param['PU0'.swapcase()]\n self.PU0given = True\n else:\n if self.PU0given == False:\n self.PU0 = 0.0\n if 'U0R' in param:\n self.U0R = param['U0R']\n self.U0Rgiven = True\n elif 'U0R'.swapcase() in param:\n self.U0R = param['U0R'.swapcase()]\n self.U0Rgiven = True\n else:\n if self.U0Rgiven == False:\n self.U0R = self.U0\n if 'LU0R' in param:\n self.LU0R = param['LU0R']\n self.LU0Rgiven = True\n elif 'LU0R'.swapcase() in param:\n self.LU0R = param['LU0R'.swapcase()]\n self.LU0Rgiven = True\n else:\n if self.LU0Rgiven == False:\n self.LU0R = self.LU0\n if 'WU0R' in param:\n self.WU0R = param['WU0R']\n self.WU0Rgiven = True\n elif 'WU0R'.swapcase() in param:\n self.WU0R = param['WU0R'.swapcase()]\n self.WU0Rgiven = True\n else:\n if self.WU0Rgiven == False:\n self.WU0R = self.WU0\n if 'PU0R' in param:\n self.PU0R = param['PU0R']\n self.PU0Rgiven = True\n elif 'PU0R'.swapcase() in param:\n self.PU0R = param['PU0R'.swapcase()]\n self.PU0Rgiven = True\n else:\n if self.PU0Rgiven == False:\n self.PU0R = self.PU0\n if 'ETAMOB' in param:\n self.ETAMOB = param['ETAMOB']\n self.ETAMOBgiven = True\n elif 'ETAMOB'.swapcase() in param:\n self.ETAMOB = param['ETAMOB'.swapcase()]\n self.ETAMOBgiven = True\n else:\n if self.ETAMOBgiven == False:\n self.ETAMOB = 1.0\n if 'UA' in param:\n self.UA = param['UA']\n self.UAgiven = True\n elif 'UA'.swapcase() in param:\n self.UA = param['UA'.swapcase()]\n self.UAgiven = True\n else:\n if self.UAgiven == False:\n self.UA = 0.001\n if 'UAL' in param:\n self.UAL = param['UAL']\n self.UALgiven = True\n elif 'UAL'.swapcase() in param:\n self.UAL = param['UAL'.swapcase()]\n self.UALgiven = True\n else:\n if self.UALgiven == False:\n self.UAL = 0.0\n if 'UALEXP' in param:\n self.UALEXP = param['UALEXP']\n self.UALEXPgiven = True\n elif 'UALEXP'.swapcase() in param:\n self.UALEXP = param['UALEXP'.swapcase()]\n self.UALEXPgiven = True\n else:\n if self.UALEXPgiven == False:\n self.UALEXP = 1.0\n if 'UAW' in param:\n self.UAW = param['UAW']\n self.UAWgiven = True\n elif 'UAW'.swapcase() in param:\n self.UAW = param['UAW'.swapcase()]\n self.UAWgiven = True\n else:\n if self.UAWgiven == False:\n self.UAW = 0.0\n if 'UAWEXP' in param:\n self.UAWEXP = param['UAWEXP']\n self.UAWEXPgiven = True\n elif 'UAWEXP'.swapcase() in param:\n self.UAWEXP = param['UAWEXP'.swapcase()]\n self.UAWEXPgiven = True\n else:\n if self.UAWEXPgiven == False:\n self.UAWEXP = 1.0\n if 'UAWL' in param:\n self.UAWL = param['UAWL']\n self.UAWLgiven = True\n elif 'UAWL'.swapcase() in param:\n self.UAWL = param['UAWL'.swapcase()]\n self.UAWLgiven = True\n else:\n if self.UAWLgiven == False:\n self.UAWL = 0.0\n if 'UAWLEXP' in param:\n self.UAWLEXP = param['UAWLEXP']\n self.UAWLEXPgiven = True\n elif 'UAWLEXP'.swapcase() in param:\n self.UAWLEXP = param['UAWLEXP'.swapcase()]\n self.UAWLEXPgiven = True\n else:\n if self.UAWLEXPgiven == False:\n self.UAWLEXP = 1.0\n if 'LUA' in param:\n self.LUA = param['LUA']\n self.LUAgiven = True\n elif 'LUA'.swapcase() in param:\n self.LUA = param['LUA'.swapcase()]\n self.LUAgiven = True\n else:\n if self.LUAgiven == False:\n self.LUA = 0.0\n if 'WUA' in param:\n self.WUA = param['WUA']\n self.WUAgiven = True\n elif 'WUA'.swapcase() in param:\n self.WUA = param['WUA'.swapcase()]\n self.WUAgiven = True\n else:\n if self.WUAgiven == False:\n self.WUA = 0.0\n if 'PUA' in param:\n self.PUA = param['PUA']\n self.PUAgiven = True\n elif 'PUA'.swapcase() in param:\n self.PUA = param['PUA'.swapcase()]\n self.PUAgiven = True\n else:\n if self.PUAgiven == False:\n self.PUA = 0.0\n if 'UAR' in param:\n self.UAR = param['UAR']\n self.UARgiven = True\n elif 'UAR'.swapcase() in param:\n self.UAR = param['UAR'.swapcase()]\n self.UARgiven = True\n else:\n if self.UARgiven == False:\n self.UAR = self.UA\n if 'LUAR' in param:\n self.LUAR = param['LUAR']\n self.LUARgiven = True\n elif 'LUAR'.swapcase() in param:\n self.LUAR = param['LUAR'.swapcase()]\n self.LUARgiven = True\n else:\n if self.LUARgiven == False:\n self.LUAR = self.LUA\n if 'WUAR' in param:\n self.WUAR = param['WUAR']\n self.WUARgiven = True\n elif 'WUAR'.swapcase() in param:\n self.WUAR = param['WUAR'.swapcase()]\n self.WUARgiven = True\n else:\n if self.WUARgiven == False:\n self.WUAR = self.WUA\n if 'PUAR' in param:\n self.PUAR = param['PUAR']\n self.PUARgiven = True\n elif 'PUAR'.swapcase() in param:\n self.PUAR = param['PUAR'.swapcase()]\n self.PUARgiven = True\n else:\n if self.PUARgiven == False:\n self.PUAR = self.PUA\n if 'EU' in param:\n self.EU = param['EU']\n self.EUgiven = True\n elif 'EU'.swapcase() in param:\n self.EU = param['EU'.swapcase()]\n self.EUgiven = True\n else:\n if self.EUgiven == False:\n self.EU = 1.5\n if 'LEU' in param:\n self.LEU = param['LEU']\n self.LEUgiven = True\n elif 'LEU'.swapcase() in param:\n self.LEU = param['LEU'.swapcase()]\n self.LEUgiven = True\n else:\n if self.LEUgiven == False:\n self.LEU = 0.0\n if 'WEU' in param:\n self.WEU = param['WEU']\n self.WEUgiven = True\n elif 'WEU'.swapcase() in param:\n self.WEU = param['WEU'.swapcase()]\n self.WEUgiven = True\n else:\n if self.WEUgiven == False:\n self.WEU = 0.0\n if 'PEU' in param:\n self.PEU = param['PEU']\n self.PEUgiven = True\n elif 'PEU'.swapcase() in param:\n self.PEU = param['PEU'.swapcase()]\n self.PEUgiven = True\n else:\n if self.PEUgiven == False:\n self.PEU = 0.0\n if 'EUL' in param:\n self.EUL = param['EUL']\n self.EULgiven = True\n elif 'EUL'.swapcase() in param:\n self.EUL = param['EUL'.swapcase()]\n self.EULgiven = True\n else:\n if self.EULgiven == False:\n self.EUL = 0.0\n if 'EULEXP' in param:\n self.EULEXP = param['EULEXP']\n self.EULEXPgiven = True\n elif 'EULEXP'.swapcase() in param:\n self.EULEXP = param['EULEXP'.swapcase()]\n self.EULEXPgiven = True\n else:\n if self.EULEXPgiven == False:\n self.EULEXP = 1.0\n if 'EUW' in param:\n self.EUW = param['EUW']\n self.EUWgiven = True\n elif 'EUW'.swapcase() in param:\n self.EUW = param['EUW'.swapcase()]\n self.EUWgiven = True\n else:\n if self.EUWgiven == False:\n self.EUW = 0.0\n if 'EUWEXP' in param:\n self.EUWEXP = param['EUWEXP']\n self.EUWEXPgiven = True\n elif 'EUWEXP'.swapcase() in param:\n self.EUWEXP = param['EUWEXP'.swapcase()]\n self.EUWEXPgiven = True\n else:\n if self.EUWEXPgiven == False:\n self.EUWEXP = 1.0\n if 'EUWL' in param:\n self.EUWL = param['EUWL']\n self.EUWLgiven = True\n elif 'EUWL'.swapcase() in param:\n self.EUWL = param['EUWL'.swapcase()]\n self.EUWLgiven = True\n else:\n if self.EUWLgiven == False:\n self.EUWL = 0.0\n if 'EUWLEXP' in param:\n self.EUWLEXP = param['EUWLEXP']\n self.EUWLEXPgiven = True\n elif 'EUWLEXP'.swapcase() in param:\n self.EUWLEXP = param['EUWLEXP'.swapcase()]\n self.EUWLEXPgiven = True\n else:\n if self.EUWLEXPgiven == False:\n self.EUWLEXP = 1.0\n if 'UD' in param:\n self.UD = param['UD']\n self.UDgiven = True\n elif 'UD'.swapcase() in param:\n self.UD = param['UD'.swapcase()]\n self.UDgiven = True\n else:\n if self.UDgiven == False:\n self.UD = 0.001\n if 'UDL' in param:\n self.UDL = param['UDL']\n self.UDLgiven = True\n elif 'UDL'.swapcase() in param:\n self.UDL = param['UDL'.swapcase()]\n self.UDLgiven = True\n else:\n if self.UDLgiven == False:\n self.UDL = 0.0\n if 'UDLEXP' in param:\n self.UDLEXP = param['UDLEXP']\n self.UDLEXPgiven = True\n elif 'UDLEXP'.swapcase() in param:\n self.UDLEXP = param['UDLEXP'.swapcase()]\n self.UDLEXPgiven = True\n else:\n if self.UDLEXPgiven == False:\n self.UDLEXP = 1.0\n if 'LUD' in param:\n self.LUD = param['LUD']\n self.LUDgiven = True\n elif 'LUD'.swapcase() in param:\n self.LUD = param['LUD'.swapcase()]\n self.LUDgiven = True\n else:\n if self.LUDgiven == False:\n self.LUD = 0.0\n if 'WUD' in param:\n self.WUD = param['WUD']\n self.WUDgiven = True\n elif 'WUD'.swapcase() in param:\n self.WUD = param['WUD'.swapcase()]\n self.WUDgiven = True\n else:\n if self.WUDgiven == False:\n self.WUD = 0.0\n if 'PUD' in param:\n self.PUD = param['PUD']\n self.PUDgiven = True\n elif 'PUD'.swapcase() in param:\n self.PUD = param['PUD'.swapcase()]\n self.PUDgiven = True\n else:\n if self.PUDgiven == False:\n self.PUD = 0.0\n if 'UDR' in param:\n self.UDR = param['UDR']\n self.UDRgiven = True\n elif 'UDR'.swapcase() in param:\n self.UDR = param['UDR'.swapcase()]\n self.UDRgiven = True\n else:\n if self.UDRgiven == False:\n self.UDR = self.UD\n if 'LUDR' in param:\n self.LUDR = param['LUDR']\n self.LUDRgiven = True\n elif 'LUDR'.swapcase() in param:\n self.LUDR = param['LUDR'.swapcase()]\n self.LUDRgiven = True\n else:\n if self.LUDRgiven == False:\n self.LUDR = self.LUD\n if 'WUDR' in param:\n self.WUDR = param['WUDR']\n self.WUDRgiven = True\n elif 'WUDR'.swapcase() in param:\n self.WUDR = param['WUDR'.swapcase()]\n self.WUDRgiven = True\n else:\n if self.WUDRgiven == False:\n self.WUDR = self.WUD\n if 'PUDR' in param:\n self.PUDR = param['PUDR']\n self.PUDRgiven = True\n elif 'PUDR'.swapcase() in param:\n self.PUDR = param['PUDR'.swapcase()]\n self.PUDRgiven = True\n else:\n if self.PUDRgiven == False:\n self.PUDR = self.PUD\n if 'UCS' in param:\n self.UCS = param['UCS']\n self.UCSgiven = True\n elif 'UCS'.swapcase() in param:\n self.UCS = param['UCS'.swapcase()]\n self.UCSgiven = True\n else:\n if self.UCSgiven == False:\n self.UCS = 2.0\n if 'LUCS' in param:\n self.LUCS = param['LUCS']\n self.LUCSgiven = True\n elif 'LUCS'.swapcase() in param:\n self.LUCS = param['LUCS'.swapcase()]\n self.LUCSgiven = True\n else:\n if self.LUCSgiven == False:\n self.LUCS = 0.0\n if 'WUCS' in param:\n self.WUCS = param['WUCS']\n self.WUCSgiven = True\n elif 'WUCS'.swapcase() in param:\n self.WUCS = param['WUCS'.swapcase()]\n self.WUCSgiven = True\n else:\n if self.WUCSgiven == False:\n self.WUCS = 0.0\n if 'PUCS' in param:\n self.PUCS = param['PUCS']\n self.PUCSgiven = True\n elif 'PUCS'.swapcase() in param:\n self.PUCS = param['PUCS'.swapcase()]\n self.PUCSgiven = True\n else:\n if self.PUCSgiven == False:\n self.PUCS = 0.0\n if 'UCSR' in param:\n self.UCSR = param['UCSR']\n self.UCSRgiven = True\n elif 'UCSR'.swapcase() in param:\n self.UCSR = param['UCSR'.swapcase()]\n self.UCSRgiven = True\n else:\n if self.UCSRgiven == False:\n self.UCSR = self.UCS\n if 'LUCSR' in param:\n self.LUCSR = param['LUCSR']\n self.LUCSRgiven = True\n elif 'LUCSR'.swapcase() in param:\n self.LUCSR = param['LUCSR'.swapcase()]\n self.LUCSRgiven = True\n else:\n if self.LUCSRgiven == False:\n self.LUCSR = self.LUCS\n if 'WUCSR' in param:\n self.WUCSR = param['WUCSR']\n self.WUCSRgiven = True\n elif 'WUCSR'.swapcase() in param:\n self.WUCSR = param['WUCSR'.swapcase()]\n self.WUCSRgiven = True\n else:\n if self.WUCSRgiven == False:\n self.WUCSR = self.WUCS\n if 'PUCSR' in param:\n self.PUCSR = param['PUCSR']\n self.PUCSRgiven = True\n elif 'PUCSR'.swapcase() in param:\n self.PUCSR = param['PUCSR'.swapcase()]\n self.PUCSRgiven = True\n else:\n if self.PUCSRgiven == False:\n self.PUCSR = self.PUCS\n if 'UC' in param:\n self.UC = param['UC']\n self.UCgiven = True\n elif 'UC'.swapcase() in param:\n self.UC = param['UC'.swapcase()]\n self.UCgiven = True\n else:\n if self.UCgiven == False:\n self.UC = 0.0\n if 'UCL' in param:\n self.UCL = param['UCL']\n self.UCLgiven = True\n elif 'UCL'.swapcase() in param:\n self.UCL = param['UCL'.swapcase()]\n self.UCLgiven = True\n else:\n if self.UCLgiven == False:\n self.UCL = 0.0\n if 'UCLEXP' in param:\n self.UCLEXP = param['UCLEXP']\n self.UCLEXPgiven = True\n elif 'UCLEXP'.swapcase() in param:\n self.UCLEXP = param['UCLEXP'.swapcase()]\n self.UCLEXPgiven = True\n else:\n if self.UCLEXPgiven == False:\n self.UCLEXP = 1.0\n if 'UCW' in param:\n self.UCW = param['UCW']\n self.UCWgiven = True\n elif 'UCW'.swapcase() in param:\n self.UCW = param['UCW'.swapcase()]\n self.UCWgiven = True\n else:\n if self.UCWgiven == False:\n self.UCW = 0.0\n if 'UCWEXP' in param:\n self.UCWEXP = param['UCWEXP']\n self.UCWEXPgiven = True\n elif 'UCWEXP'.swapcase() in param:\n self.UCWEXP = param['UCWEXP'.swapcase()]\n self.UCWEXPgiven = True\n else:\n if self.UCWEXPgiven == False:\n self.UCWEXP = 1.0\n if 'UCWL' in param:\n self.UCWL = param['UCWL']\n self.UCWLgiven = True\n elif 'UCWL'.swapcase() in param:\n self.UCWL = param['UCWL'.swapcase()]\n self.UCWLgiven = True\n else:\n if self.UCWLgiven == False:\n self.UCWL = 0.0\n if 'UCWLEXP' in param:\n self.UCWLEXP = param['UCWLEXP']\n self.UCWLEXPgiven = True\n elif 'UCWLEXP'.swapcase() in param:\n self.UCWLEXP = param['UCWLEXP'.swapcase()]\n self.UCWLEXPgiven = True\n else:\n if self.UCWLEXPgiven == False:\n self.UCWLEXP = 1.0\n if 'LUC' in param:\n self.LUC = param['LUC']\n self.LUCgiven = True\n elif 'LUC'.swapcase() in param:\n self.LUC = param['LUC'.swapcase()]\n self.LUCgiven = True\n else:\n if self.LUCgiven == False:\n self.LUC = 0.0\n if 'WUC' in param:\n self.WUC = param['WUC']\n self.WUCgiven = True\n elif 'WUC'.swapcase() in param:\n self.WUC = param['WUC'.swapcase()]\n self.WUCgiven = True\n else:\n if self.WUCgiven == False:\n self.WUC = 0.0\n if 'PUC' in param:\n self.PUC = param['PUC']\n self.PUCgiven = True\n elif 'PUC'.swapcase() in param:\n self.PUC = param['PUC'.swapcase()]\n self.PUCgiven = True\n else:\n if self.PUCgiven == False:\n self.PUC = 0.0\n if 'UCR' in param:\n self.UCR = param['UCR']\n self.UCRgiven = True\n elif 'UCR'.swapcase() in param:\n self.UCR = param['UCR'.swapcase()]\n self.UCRgiven = True\n else:\n if self.UCRgiven == False:\n self.UCR = self.UC\n if 'LUCR' in param:\n self.LUCR = param['LUCR']\n self.LUCRgiven = True\n elif 'LUCR'.swapcase() in param:\n self.LUCR = param['LUCR'.swapcase()]\n self.LUCRgiven = True\n else:\n if self.LUCRgiven == False:\n self.LUCR = self.LUC\n if 'WUCR' in param:\n self.WUCR = param['WUCR']\n self.WUCRgiven = True\n elif 'WUCR'.swapcase() in param:\n self.WUCR = param['WUCR'.swapcase()]\n self.WUCRgiven = True\n else:\n if self.WUCRgiven == False:\n self.WUCR = self.WUC\n if 'PUCR' in param:\n self.PUCR = param['PUCR']\n self.PUCRgiven = True\n elif 'PUCR'.swapcase() in param:\n self.PUCR = param['PUCR'.swapcase()]\n self.PUCRgiven = True\n else:\n if self.PUCRgiven == False:\n self.PUCR = self.PUC\n if 'PCLM' in param:\n self.PCLM = param['PCLM']\n self.PCLMgiven = True\n elif 'PCLM'.swapcase() in param:\n self.PCLM = param['PCLM'.swapcase()]\n self.PCLMgiven = True\n else:\n if self.PCLMgiven == False:\n self.PCLM = 0.0\n if 'PCLML' in param:\n self.PCLML = param['PCLML']\n self.PCLMLgiven = True\n elif 'PCLML'.swapcase() in param:\n self.PCLML = param['PCLML'.swapcase()]\n self.PCLMLgiven = True\n else:\n if self.PCLMLgiven == False:\n self.PCLML = 0.0\n if 'PCLMLEXP' in param:\n self.PCLMLEXP = param['PCLMLEXP']\n self.PCLMLEXPgiven = True\n elif 'PCLMLEXP'.swapcase() in param:\n self.PCLMLEXP = param['PCLMLEXP'.swapcase()]\n self.PCLMLEXPgiven = True\n else:\n if self.PCLMLEXPgiven == False:\n self.PCLMLEXP = 1.0\n if 'LPCLM' in param:\n self.LPCLM = param['LPCLM']\n self.LPCLMgiven = True\n elif 'LPCLM'.swapcase() in param:\n self.LPCLM = param['LPCLM'.swapcase()]\n self.LPCLMgiven = True\n else:\n if self.LPCLMgiven == False:\n self.LPCLM = 0.0\n if 'WPCLM' in param:\n self.WPCLM = param['WPCLM']\n self.WPCLMgiven = True\n elif 'WPCLM'.swapcase() in param:\n self.WPCLM = param['WPCLM'.swapcase()]\n self.WPCLMgiven = True\n else:\n if self.WPCLMgiven == False:\n self.WPCLM = 0.0\n if 'PPCLM' in param:\n self.PPCLM = param['PPCLM']\n self.PPCLMgiven = True\n elif 'PPCLM'.swapcase() in param:\n self.PPCLM = param['PPCLM'.swapcase()]\n self.PPCLMgiven = True\n else:\n if self.PPCLMgiven == False:\n self.PPCLM = 0.0\n if 'PCLMR' in param:\n self.PCLMR = param['PCLMR']\n self.PCLMRgiven = True\n elif 'PCLMR'.swapcase() in param:\n self.PCLMR = param['PCLMR'.swapcase()]\n self.PCLMRgiven = True\n else:\n if self.PCLMRgiven == False:\n self.PCLMR = self.PCLM\n if 'LPCLMR' in param:\n self.LPCLMR = param['LPCLMR']\n self.LPCLMRgiven = True\n elif 'LPCLMR'.swapcase() in param:\n self.LPCLMR = param['LPCLMR'.swapcase()]\n self.LPCLMRgiven = True\n else:\n if self.LPCLMRgiven == False:\n self.LPCLMR = self.LPCLM\n if 'WPCLMR' in param:\n self.WPCLMR = param['WPCLMR']\n self.WPCLMRgiven = True\n elif 'WPCLMR'.swapcase() in param:\n self.WPCLMR = param['WPCLMR'.swapcase()]\n self.WPCLMRgiven = True\n else:\n if self.WPCLMRgiven == False:\n self.WPCLMR = self.WPCLM\n if 'PPCLMR' in param:\n self.PPCLMR = param['PPCLMR']\n self.PPCLMRgiven = True\n elif 'PPCLMR'.swapcase() in param:\n self.PPCLMR = param['PPCLMR'.swapcase()]\n self.PPCLMRgiven = True\n else:\n if self.PPCLMRgiven == False:\n self.PPCLMR = self.PPCLM\n if 'PCLMG' in param:\n self.PCLMG = param['PCLMG']\n self.PCLMGgiven = True\n elif 'PCLMG'.swapcase() in param:\n self.PCLMG = param['PCLMG'.swapcase()]\n self.PCLMGgiven = True\n else:\n if self.PCLMGgiven == False:\n self.PCLMG = 0.0\n if 'PCLMCV' in param:\n self.PCLMCV = param['PCLMCV']\n self.PCLMCVgiven = True\n elif 'PCLMCV'.swapcase() in param:\n self.PCLMCV = param['PCLMCV'.swapcase()]\n self.PCLMCVgiven = True\n else:\n if self.PCLMCVgiven == False:\n self.PCLMCV = self.PCLM\n if 'PCLMCVL' in param:\n self.PCLMCVL = param['PCLMCVL']\n self.PCLMCVLgiven = True\n elif 'PCLMCVL'.swapcase() in param:\n self.PCLMCVL = param['PCLMCVL'.swapcase()]\n self.PCLMCVLgiven = True\n else:\n if self.PCLMCVLgiven == False:\n self.PCLMCVL = self.PCLML\n if 'PCLMCVLEXP' in param:\n self.PCLMCVLEXP = param['PCLMCVLEXP']\n self.PCLMCVLEXPgiven = True\n elif 'PCLMCVLEXP'.swapcase() in param:\n self.PCLMCVLEXP = param['PCLMCVLEXP'.swapcase()]\n self.PCLMCVLEXPgiven = True\n else:\n if self.PCLMCVLEXPgiven == False:\n self.PCLMCVLEXP = self.PCLMLEXP\n if 'LPCLMCV' in param:\n self.LPCLMCV = param['LPCLMCV']\n self.LPCLMCVgiven = True\n elif 'LPCLMCV'.swapcase() in param:\n self.LPCLMCV = param['LPCLMCV'.swapcase()]\n self.LPCLMCVgiven = True\n else:\n if self.LPCLMCVgiven == False:\n self.LPCLMCV = self.LPCLM\n if 'WPCLMCV' in param:\n self.WPCLMCV = param['WPCLMCV']\n self.WPCLMCVgiven = True\n elif 'WPCLMCV'.swapcase() in param:\n self.WPCLMCV = param['WPCLMCV'.swapcase()]\n self.WPCLMCVgiven = True\n else:\n if self.WPCLMCVgiven == False:\n self.WPCLMCV = self.WPCLM\n if 'PPCLMCV' in param:\n self.PPCLMCV = param['PPCLMCV']\n self.PPCLMCVgiven = True\n elif 'PPCLMCV'.swapcase() in param:\n self.PPCLMCV = param['PPCLMCV'.swapcase()]\n self.PPCLMCVgiven = True\n else:\n if self.PPCLMCVgiven == False:\n self.PPCLMCV = self.PPCLM\n if 'PSCBE1' in param:\n self.PSCBE1 = param['PSCBE1']\n self.PSCBE1given = True\n elif 'PSCBE1'.swapcase() in param:\n self.PSCBE1 = param['PSCBE1'.swapcase()]\n self.PSCBE1given = True\n else:\n if self.PSCBE1given == False:\n self.PSCBE1 = 424000000.0\n if 'LPSCBE1' in param:\n self.LPSCBE1 = param['LPSCBE1']\n self.LPSCBE1given = True\n elif 'LPSCBE1'.swapcase() in param:\n self.LPSCBE1 = param['LPSCBE1'.swapcase()]\n self.LPSCBE1given = True\n else:\n if self.LPSCBE1given == False:\n self.LPSCBE1 = 0.0\n if 'WPSCBE1' in param:\n self.WPSCBE1 = param['WPSCBE1']\n self.WPSCBE1given = True\n elif 'WPSCBE1'.swapcase() in param:\n self.WPSCBE1 = param['WPSCBE1'.swapcase()]\n self.WPSCBE1given = True\n else:\n if self.WPSCBE1given == False:\n self.WPSCBE1 = 0.0\n if 'PPSCBE1' in param:\n self.PPSCBE1 = param['PPSCBE1']\n self.PPSCBE1given = True\n elif 'PPSCBE1'.swapcase() in param:\n self.PPSCBE1 = param['PPSCBE1'.swapcase()]\n self.PPSCBE1given = True\n else:\n if self.PPSCBE1given == False:\n self.PPSCBE1 = 0.0\n if 'PSCBE2' in param:\n self.PSCBE2 = param['PSCBE2']\n self.PSCBE2given = True\n elif 'PSCBE2'.swapcase() in param:\n self.PSCBE2 = param['PSCBE2'.swapcase()]\n self.PSCBE2given = True\n else:\n if self.PSCBE2given == False:\n self.PSCBE2 = 1e-08\n if 'LPSCBE2' in param:\n self.LPSCBE2 = param['LPSCBE2']\n self.LPSCBE2given = True\n elif 'LPSCBE2'.swapcase() in param:\n self.LPSCBE2 = param['LPSCBE2'.swapcase()]\n self.LPSCBE2given = True\n else:\n if self.LPSCBE2given == False:\n self.LPSCBE2 = 0.0\n if 'WPSCBE2' in param:\n self.WPSCBE2 = param['WPSCBE2']\n self.WPSCBE2given = True\n elif 'WPSCBE2'.swapcase() in param:\n self.WPSCBE2 = param['WPSCBE2'.swapcase()]\n self.WPSCBE2given = True\n else:\n if self.WPSCBE2given == False:\n self.WPSCBE2 = 0.0\n if 'PPSCBE2' in param:\n self.PPSCBE2 = param['PPSCBE2']\n self.PPSCBE2given = True\n elif 'PPSCBE2'.swapcase() in param:\n self.PPSCBE2 = param['PPSCBE2'.swapcase()]\n self.PPSCBE2given = True\n else:\n if self.PPSCBE2given == False:\n self.PPSCBE2 = 0.0\n if 'PDITS' in param:\n self.PDITS = param['PDITS']\n self.PDITSgiven = True\n elif 'PDITS'.swapcase() in param:\n self.PDITS = param['PDITS'.swapcase()]\n self.PDITSgiven = True\n else:\n if self.PDITSgiven == False:\n self.PDITS = 0.0\n if 'LPDITS' in param:\n self.LPDITS = param['LPDITS']\n self.LPDITSgiven = True\n elif 'LPDITS'.swapcase() in param:\n self.LPDITS = param['LPDITS'.swapcase()]\n self.LPDITSgiven = True\n else:\n if self.LPDITSgiven == False:\n self.LPDITS = 0.0\n if 'WPDITS' in param:\n self.WPDITS = param['WPDITS']\n self.WPDITSgiven = True\n elif 'WPDITS'.swapcase() in param:\n self.WPDITS = param['WPDITS'.swapcase()]\n self.WPDITSgiven = True\n else:\n if self.WPDITSgiven == False:\n self.WPDITS = 0.0\n if 'PPDITS' in param:\n self.PPDITS = param['PPDITS']\n self.PPDITSgiven = True\n elif 'PPDITS'.swapcase() in param:\n self.PPDITS = param['PPDITS'.swapcase()]\n self.PPDITSgiven = True\n else:\n if self.PPDITSgiven == False:\n self.PPDITS = 0.0\n if 'PDITSL' in param:\n self.PDITSL = param['PDITSL']\n self.PDITSLgiven = True\n elif 'PDITSL'.swapcase() in param:\n self.PDITSL = param['PDITSL'.swapcase()]\n self.PDITSLgiven = True\n else:\n if self.PDITSLgiven == False:\n self.PDITSL = 0.0\n if 'PDITSD' in param:\n self.PDITSD = param['PDITSD']\n self.PDITSDgiven = True\n elif 'PDITSD'.swapcase() in param:\n self.PDITSD = param['PDITSD'.swapcase()]\n self.PDITSDgiven = True\n else:\n if self.PDITSDgiven == False:\n self.PDITSD = 0.0\n if 'LPDITSD' in param:\n self.LPDITSD = param['LPDITSD']\n self.LPDITSDgiven = True\n elif 'LPDITSD'.swapcase() in param:\n self.LPDITSD = param['LPDITSD'.swapcase()]\n self.LPDITSDgiven = True\n else:\n if self.LPDITSDgiven == False:\n self.LPDITSD = 0.0\n if 'WPDITSD' in param:\n self.WPDITSD = param['WPDITSD']\n self.WPDITSDgiven = True\n elif 'WPDITSD'.swapcase() in param:\n self.WPDITSD = param['WPDITSD'.swapcase()]\n self.WPDITSDgiven = True\n else:\n if self.WPDITSDgiven == False:\n self.WPDITSD = 0.0\n if 'PPDITSD' in param:\n self.PPDITSD = param['PPDITSD']\n self.PPDITSDgiven = True\n elif 'PPDITSD'.swapcase() in param:\n self.PPDITSD = param['PPDITSD'.swapcase()]\n self.PPDITSDgiven = True\n else:\n if self.PPDITSDgiven == False:\n self.PPDITSD = 0.0\n if 'RSH' in param:\n self.RSH = param['RSH']\n self.RSHgiven = True\n elif 'RSH'.swapcase() in param:\n self.RSH = param['RSH'.swapcase()]\n self.RSHgiven = True\n else:\n if self.RSHgiven == False:\n self.RSH = 0.0\n if 'PRWG' in param:\n self.PRWG = param['PRWG']\n self.PRWGgiven = True\n elif 'PRWG'.swapcase() in param:\n self.PRWG = param['PRWG'.swapcase()]\n self.PRWGgiven = True\n else:\n if self.PRWGgiven == False:\n self.PRWG = 1.0\n if 'LPRWG' in param:\n self.LPRWG = param['LPRWG']\n self.LPRWGgiven = True\n elif 'LPRWG'.swapcase() in param:\n self.LPRWG = param['LPRWG'.swapcase()]\n self.LPRWGgiven = True\n else:\n if self.LPRWGgiven == False:\n self.LPRWG = 0.0\n if 'WPRWG' in param:\n self.WPRWG = param['WPRWG']\n self.WPRWGgiven = True\n elif 'WPRWG'.swapcase() in param:\n self.WPRWG = param['WPRWG'.swapcase()]\n self.WPRWGgiven = True\n else:\n if self.WPRWGgiven == False:\n self.WPRWG = 0.0\n if 'PPRWG' in param:\n self.PPRWG = param['PPRWG']\n self.PPRWGgiven = True\n elif 'PPRWG'.swapcase() in param:\n self.PPRWG = param['PPRWG'.swapcase()]\n self.PPRWGgiven = True\n else:\n if self.PPRWGgiven == False:\n self.PPRWG = 0.0\n if 'PRWB' in param:\n self.PRWB = param['PRWB']\n self.PRWBgiven = True\n elif 'PRWB'.swapcase() in param:\n self.PRWB = param['PRWB'.swapcase()]\n self.PRWBgiven = True\n else:\n if self.PRWBgiven == False:\n self.PRWB = 0.0\n if 'LPRWB' in param:\n self.LPRWB = param['LPRWB']\n self.LPRWBgiven = True\n elif 'LPRWB'.swapcase() in param:\n self.LPRWB = param['LPRWB'.swapcase()]\n self.LPRWBgiven = True\n else:\n if self.LPRWBgiven == False:\n self.LPRWB = 0.0\n if 'WPRWB' in param:\n self.WPRWB = param['WPRWB']\n self.WPRWBgiven = True\n elif 'WPRWB'.swapcase() in param:\n self.WPRWB = param['WPRWB'.swapcase()]\n self.WPRWBgiven = True\n else:\n if self.WPRWBgiven == False:\n self.WPRWB = 0.0\n if 'PPRWB' in param:\n self.PPRWB = param['PPRWB']\n self.PPRWBgiven = True\n elif 'PPRWB'.swapcase() in param:\n self.PPRWB = param['PPRWB'.swapcase()]\n self.PPRWBgiven = True\n else:\n if self.PPRWBgiven == False:\n self.PPRWB = 0.0\n if 'PRWBL' in param:\n self.PRWBL = param['PRWBL']\n self.PRWBLgiven = True\n elif 'PRWBL'.swapcase() in param:\n self.PRWBL = param['PRWBL'.swapcase()]\n self.PRWBLgiven = True\n else:\n if self.PRWBLgiven == False:\n self.PRWBL = 0.0\n if 'PRWBLEXP' in param:\n self.PRWBLEXP = param['PRWBLEXP']\n self.PRWBLEXPgiven = True\n elif 'PRWBLEXP'.swapcase() in param:\n self.PRWBLEXP = param['PRWBLEXP'.swapcase()]\n self.PRWBLEXPgiven = True\n else:\n if self.PRWBLEXPgiven == False:\n self.PRWBLEXP = 1.0\n if 'WR' in param:\n self.WR = param['WR']\n self.WRgiven = True\n elif 'WR'.swapcase() in param:\n self.WR = param['WR'.swapcase()]\n self.WRgiven = True\n else:\n if self.WRgiven == False:\n self.WR = 1.0\n if 'LWR' in param:\n self.LWR = param['LWR']\n self.LWRgiven = True\n elif 'LWR'.swapcase() in param:\n self.LWR = param['LWR'.swapcase()]\n self.LWRgiven = True\n else:\n if self.LWRgiven == False:\n self.LWR = 0.0\n if 'WWR' in param:\n self.WWR = param['WWR']\n self.WWRgiven = True\n elif 'WWR'.swapcase() in param:\n self.WWR = param['WWR'.swapcase()]\n self.WWRgiven = True\n else:\n if self.WWRgiven == False:\n self.WWR = 0.0\n if 'PWR' in param:\n self.PWR = param['PWR']\n self.PWRgiven = True\n elif 'PWR'.swapcase() in param:\n self.PWR = param['PWR'.swapcase()]\n self.PWRgiven = True\n else:\n if self.PWRgiven == False:\n self.PWR = 0.0\n if 'RSWMIN' in param:\n self.RSWMIN = param['RSWMIN']\n self.RSWMINgiven = True\n elif 'RSWMIN'.swapcase() in param:\n self.RSWMIN = param['RSWMIN'.swapcase()]\n self.RSWMINgiven = True\n else:\n if self.RSWMINgiven == False:\n self.RSWMIN = 0.0\n if 'LRSWMIN' in param:\n self.LRSWMIN = param['LRSWMIN']\n self.LRSWMINgiven = True\n elif 'LRSWMIN'.swapcase() in param:\n self.LRSWMIN = param['LRSWMIN'.swapcase()]\n self.LRSWMINgiven = True\n else:\n if self.LRSWMINgiven == False:\n self.LRSWMIN = 0.0\n if 'WRSWMIN' in param:\n self.WRSWMIN = param['WRSWMIN']\n self.WRSWMINgiven = True\n elif 'WRSWMIN'.swapcase() in param:\n self.WRSWMIN = param['WRSWMIN'.swapcase()]\n self.WRSWMINgiven = True\n else:\n if self.WRSWMINgiven == False:\n self.WRSWMIN = 0.0\n if 'PRSWMIN' in param:\n self.PRSWMIN = param['PRSWMIN']\n self.PRSWMINgiven = True\n elif 'PRSWMIN'.swapcase() in param:\n self.PRSWMIN = param['PRSWMIN'.swapcase()]\n self.PRSWMINgiven = True\n else:\n if self.PRSWMINgiven == False:\n self.PRSWMIN = 0.0\n if 'RSW' in param:\n self.RSW = param['RSW']\n self.RSWgiven = True\n elif 'RSW'.swapcase() in param:\n self.RSW = param['RSW'.swapcase()]\n self.RSWgiven = True\n else:\n if self.RSWgiven == False:\n self.RSW = 10.0\n if 'LRSW' in param:\n self.LRSW = param['LRSW']\n self.LRSWgiven = True\n elif 'LRSW'.swapcase() in param:\n self.LRSW = param['LRSW'.swapcase()]\n self.LRSWgiven = True\n else:\n if self.LRSWgiven == False:\n self.LRSW = 0.0\n if 'WRSW' in param:\n self.WRSW = param['WRSW']\n self.WRSWgiven = True\n elif 'WRSW'.swapcase() in param:\n self.WRSW = param['WRSW'.swapcase()]\n self.WRSWgiven = True\n else:\n if self.WRSWgiven == False:\n self.WRSW = 0.0\n if 'PRSW' in param:\n self.PRSW = param['PRSW']\n self.PRSWgiven = True\n elif 'PRSW'.swapcase() in param:\n self.PRSW = param['PRSW'.swapcase()]\n self.PRSWgiven = True\n else:\n if self.PRSWgiven == False:\n self.PRSW = 0.0\n if 'RSWL' in param:\n self.RSWL = param['RSWL']\n self.RSWLgiven = True\n elif 'RSWL'.swapcase() in param:\n self.RSWL = param['RSWL'.swapcase()]\n self.RSWLgiven = True\n else:\n if self.RSWLgiven == False:\n self.RSWL = 0.0\n if 'RSWLEXP' in param:\n self.RSWLEXP = param['RSWLEXP']\n self.RSWLEXPgiven = True\n elif 'RSWLEXP'.swapcase() in param:\n self.RSWLEXP = param['RSWLEXP'.swapcase()]\n self.RSWLEXPgiven = True\n else:\n if self.RSWLEXPgiven == False:\n self.RSWLEXP = 1.0\n if 'RDWMIN' in param:\n self.RDWMIN = param['RDWMIN']\n self.RDWMINgiven = True\n elif 'RDWMIN'.swapcase() in param:\n self.RDWMIN = param['RDWMIN'.swapcase()]\n self.RDWMINgiven = True\n else:\n if self.RDWMINgiven == False:\n self.RDWMIN = self.RSWMIN\n if 'LRDWMIN' in param:\n self.LRDWMIN = param['LRDWMIN']\n self.LRDWMINgiven = True\n elif 'LRDWMIN'.swapcase() in param:\n self.LRDWMIN = param['LRDWMIN'.swapcase()]\n self.LRDWMINgiven = True\n else:\n if self.LRDWMINgiven == False:\n self.LRDWMIN = self.LRSWMIN\n if 'WRDWMIN' in param:\n self.WRDWMIN = param['WRDWMIN']\n self.WRDWMINgiven = True\n elif 'WRDWMIN'.swapcase() in param:\n self.WRDWMIN = param['WRDWMIN'.swapcase()]\n self.WRDWMINgiven = True\n else:\n if self.WRDWMINgiven == False:\n self.WRDWMIN = self.WRSWMIN\n if 'PRDWMIN' in param:\n self.PRDWMIN = param['PRDWMIN']\n self.PRDWMINgiven = True\n elif 'PRDWMIN'.swapcase() in param:\n self.PRDWMIN = param['PRDWMIN'.swapcase()]\n self.PRDWMINgiven = True\n else:\n if self.PRDWMINgiven == False:\n self.PRDWMIN = self.PRSWMIN\n if 'RDW' in param:\n self.RDW = param['RDW']\n self.RDWgiven = True\n elif 'RDW'.swapcase() in param:\n self.RDW = param['RDW'.swapcase()]\n self.RDWgiven = True\n else:\n if self.RDWgiven == False:\n self.RDW = self.RSW\n if 'LRDW' in param:\n self.LRDW = param['LRDW']\n self.LRDWgiven = True\n elif 'LRDW'.swapcase() in param:\n self.LRDW = param['LRDW'.swapcase()]\n self.LRDWgiven = True\n else:\n if self.LRDWgiven == False:\n self.LRDW = self.LRSW\n if 'WRDW' in param:\n self.WRDW = param['WRDW']\n self.WRDWgiven = True\n elif 'WRDW'.swapcase() in param:\n self.WRDW = param['WRDW'.swapcase()]\n self.WRDWgiven = True\n else:\n if self.WRDWgiven == False:\n self.WRDW = self.WRSW\n if 'PRDW' in param:\n self.PRDW = param['PRDW']\n self.PRDWgiven = True\n elif 'PRDW'.swapcase() in param:\n self.PRDW = param['PRDW'.swapcase()]\n self.PRDWgiven = True\n else:\n if self.PRDWgiven == False:\n self.PRDW = self.PRSW\n if 'RDWL' in param:\n self.RDWL = param['RDWL']\n self.RDWLgiven = True\n elif 'RDWL'.swapcase() in param:\n self.RDWL = param['RDWL'.swapcase()]\n self.RDWLgiven = True\n else:\n if self.RDWLgiven == False:\n self.RDWL = self.RSWL\n if 'RDWLEXP' in param:\n self.RDWLEXP = param['RDWLEXP']\n self.RDWLEXPgiven = True\n elif 'RDWLEXP'.swapcase() in param:\n self.RDWLEXP = param['RDWLEXP'.swapcase()]\n self.RDWLEXPgiven = True\n else:\n if self.RDWLEXPgiven == False:\n self.RDWLEXP = self.RSWLEXP\n if 'RDSWMIN' in param:\n self.RDSWMIN = param['RDSWMIN']\n self.RDSWMINgiven = True\n elif 'RDSWMIN'.swapcase() in param:\n self.RDSWMIN = param['RDSWMIN'.swapcase()]\n self.RDSWMINgiven = True\n else:\n if self.RDSWMINgiven == False:\n self.RDSWMIN = 0.0\n if 'LRDSWMIN' in param:\n self.LRDSWMIN = param['LRDSWMIN']\n self.LRDSWMINgiven = True\n elif 'LRDSWMIN'.swapcase() in param:\n self.LRDSWMIN = param['LRDSWMIN'.swapcase()]\n self.LRDSWMINgiven = True\n else:\n if self.LRDSWMINgiven == False:\n self.LRDSWMIN = 0.0\n if 'WRDSWMIN' in param:\n self.WRDSWMIN = param['WRDSWMIN']\n self.WRDSWMINgiven = True\n elif 'WRDSWMIN'.swapcase() in param:\n self.WRDSWMIN = param['WRDSWMIN'.swapcase()]\n self.WRDSWMINgiven = True\n else:\n if self.WRDSWMINgiven == False:\n self.WRDSWMIN = 0.0\n if 'PRDSWMIN' in param:\n self.PRDSWMIN = param['PRDSWMIN']\n self.PRDSWMINgiven = True\n elif 'PRDSWMIN'.swapcase() in param:\n self.PRDSWMIN = param['PRDSWMIN'.swapcase()]\n self.PRDSWMINgiven = True\n else:\n if self.PRDSWMINgiven == False:\n self.PRDSWMIN = 0.0\n if 'RDSW' in param:\n self.RDSW = param['RDSW']\n self.RDSWgiven = True\n elif 'RDSW'.swapcase() in param:\n self.RDSW = param['RDSW'.swapcase()]\n self.RDSWgiven = True\n else:\n if self.RDSWgiven == False:\n self.RDSW = 20.0\n if 'RDSWL' in param:\n self.RDSWL = param['RDSWL']\n self.RDSWLgiven = True\n elif 'RDSWL'.swapcase() in param:\n self.RDSWL = param['RDSWL'.swapcase()]\n self.RDSWLgiven = True\n else:\n if self.RDSWLgiven == False:\n self.RDSWL = 0.0\n if 'RDSWLEXP' in param:\n self.RDSWLEXP = param['RDSWLEXP']\n self.RDSWLEXPgiven = True\n elif 'RDSWLEXP'.swapcase() in param:\n self.RDSWLEXP = param['RDSWLEXP'.swapcase()]\n self.RDSWLEXPgiven = True\n else:\n if self.RDSWLEXPgiven == False:\n self.RDSWLEXP = 1.0\n if 'LRDSW' in param:\n self.LRDSW = param['LRDSW']\n self.LRDSWgiven = True\n elif 'LRDSW'.swapcase() in param:\n self.LRDSW = param['LRDSW'.swapcase()]\n self.LRDSWgiven = True\n else:\n if self.LRDSWgiven == False:\n self.LRDSW = 0.0\n if 'WRDSW' in param:\n self.WRDSW = param['WRDSW']\n self.WRDSWgiven = True\n elif 'WRDSW'.swapcase() in param:\n self.WRDSW = param['WRDSW'.swapcase()]\n self.WRDSWgiven = True\n else:\n if self.WRDSWgiven == False:\n self.WRDSW = 0.0\n if 'PRDSW' in param:\n self.PRDSW = param['PRDSW']\n self.PRDSWgiven = True\n elif 'PRDSW'.swapcase() in param:\n self.PRDSW = param['PRDSW'.swapcase()]\n self.PRDSWgiven = True\n else:\n if self.PRDSWgiven == False:\n self.PRDSW = 0.0\n if 'PSAT' in param:\n self.PSAT = param['PSAT']\n self.PSATgiven = True\n elif 'PSAT'.swapcase() in param:\n self.PSAT = param['PSAT'.swapcase()]\n self.PSATgiven = True\n else:\n if self.PSATgiven == False:\n self.PSAT = 1.0\n if 'LPSAT' in param:\n self.LPSAT = param['LPSAT']\n self.LPSATgiven = True\n elif 'LPSAT'.swapcase() in param:\n self.LPSAT = param['LPSAT'.swapcase()]\n self.LPSATgiven = True\n else:\n if self.LPSATgiven == False:\n self.LPSAT = 0.0\n if 'WPSAT' in param:\n self.WPSAT = param['WPSAT']\n self.WPSATgiven = True\n elif 'WPSAT'.swapcase() in param:\n self.WPSAT = param['WPSAT'.swapcase()]\n self.WPSATgiven = True\n else:\n if self.WPSATgiven == False:\n self.WPSAT = 0.0\n if 'PPSAT' in param:\n self.PPSAT = param['PPSAT']\n self.PPSATgiven = True\n elif 'PPSAT'.swapcase() in param:\n self.PPSAT = param['PPSAT'.swapcase()]\n self.PPSATgiven = True\n else:\n if self.PPSATgiven == False:\n self.PPSAT = 0.0\n if 'PSATL' in param:\n self.PSATL = param['PSATL']\n self.PSATLgiven = True\n elif 'PSATL'.swapcase() in param:\n self.PSATL = param['PSATL'.swapcase()]\n self.PSATLgiven = True\n else:\n if self.PSATLgiven == False:\n self.PSATL = 0.0\n if 'PSATLEXP' in param:\n self.PSATLEXP = param['PSATLEXP']\n self.PSATLEXPgiven = True\n elif 'PSATLEXP'.swapcase() in param:\n self.PSATLEXP = param['PSATLEXP'.swapcase()]\n self.PSATLEXPgiven = True\n else:\n if self.PSATLEXPgiven == False:\n self.PSATLEXP = 1.0\n if 'PSATB' in param:\n self.PSATB = param['PSATB']\n self.PSATBgiven = True\n elif 'PSATB'.swapcase() in param:\n self.PSATB = param['PSATB'.swapcase()]\n self.PSATBgiven = True\n else:\n if self.PSATBgiven == False:\n self.PSATB = 0.0\n if 'PSATR' in param:\n self.PSATR = param['PSATR']\n self.PSATRgiven = True\n elif 'PSATR'.swapcase() in param:\n self.PSATR = param['PSATR'.swapcase()]\n self.PSATRgiven = True\n else:\n if self.PSATRgiven == False:\n self.PSATR = self.PSAT\n if 'LPSATR' in param:\n self.LPSATR = param['LPSATR']\n self.LPSATRgiven = True\n elif 'LPSATR'.swapcase() in param:\n self.LPSATR = param['LPSATR'.swapcase()]\n self.LPSATRgiven = True\n else:\n if self.LPSATRgiven == False:\n self.LPSATR = self.LPSAT\n if 'WPSATR' in param:\n self.WPSATR = param['WPSATR']\n self.WPSATRgiven = True\n elif 'WPSATR'.swapcase() in param:\n self.WPSATR = param['WPSATR'.swapcase()]\n self.WPSATRgiven = True\n else:\n if self.WPSATRgiven == False:\n self.WPSATR = self.WPSAT\n if 'PPSATR' in param:\n self.PPSATR = param['PPSATR']\n self.PPSATRgiven = True\n elif 'PPSATR'.swapcase() in param:\n self.PPSATR = param['PPSATR'.swapcase()]\n self.PPSATRgiven = True\n else:\n if self.PPSATRgiven == False:\n self.PPSATR = self.PPSAT\n if 'LPSATB' in param:\n self.LPSATB = param['LPSATB']\n self.LPSATBgiven = True\n elif 'LPSATB'.swapcase() in param:\n self.LPSATB = param['LPSATB'.swapcase()]\n self.LPSATBgiven = True\n else:\n if self.LPSATBgiven == False:\n self.LPSATB = 0.0\n if 'WPSATB' in param:\n self.WPSATB = param['WPSATB']\n self.WPSATBgiven = True\n elif 'WPSATB'.swapcase() in param:\n self.WPSATB = param['WPSATB'.swapcase()]\n self.WPSATBgiven = True\n else:\n if self.WPSATBgiven == False:\n self.WPSATB = 0.0\n if 'PPSATB' in param:\n self.PPSATB = param['PPSATB']\n self.PPSATBgiven = True\n elif 'PPSATB'.swapcase() in param:\n self.PPSATB = param['PPSATB'.swapcase()]\n self.PPSATBgiven = True\n else:\n if self.PPSATBgiven == False:\n self.PPSATB = 0.0\n if 'PSATX' in param:\n self.PSATX = param['PSATX']\n self.PSATXgiven = True\n elif 'PSATX'.swapcase() in param:\n self.PSATX = param['PSATX'.swapcase()]\n self.PSATXgiven = True\n else:\n if self.PSATXgiven == False:\n self.PSATX = 1.0\n if 'PTWG' in param:\n self.PTWG = param['PTWG']\n self.PTWGgiven = True\n elif 'PTWG'.swapcase() in param:\n self.PTWG = param['PTWG'.swapcase()]\n self.PTWGgiven = True\n else:\n if self.PTWGgiven == False:\n self.PTWG = 0.0\n if 'LPTWG' in param:\n self.LPTWG = param['LPTWG']\n self.LPTWGgiven = True\n elif 'LPTWG'.swapcase() in param:\n self.LPTWG = param['LPTWG'.swapcase()]\n self.LPTWGgiven = True\n else:\n if self.LPTWGgiven == False:\n self.LPTWG = 0.0\n if 'WPTWG' in param:\n self.WPTWG = param['WPTWG']\n self.WPTWGgiven = True\n elif 'WPTWG'.swapcase() in param:\n self.WPTWG = param['WPTWG'.swapcase()]\n self.WPTWGgiven = True\n else:\n if self.WPTWGgiven == False:\n self.WPTWG = 0.0\n if 'PPTWG' in param:\n self.PPTWG = param['PPTWG']\n self.PPTWGgiven = True\n elif 'PPTWG'.swapcase() in param:\n self.PPTWG = param['PPTWG'.swapcase()]\n self.PPTWGgiven = True\n else:\n if self.PPTWGgiven == False:\n self.PPTWG = 0.0\n if 'PTWGL' in param:\n self.PTWGL = param['PTWGL']\n self.PTWGLgiven = True\n elif 'PTWGL'.swapcase() in param:\n self.PTWGL = param['PTWGL'.swapcase()]\n self.PTWGLgiven = True\n else:\n if self.PTWGLgiven == False:\n self.PTWGL = 0.0\n if 'PTWGLEXP' in param:\n self.PTWGLEXP = param['PTWGLEXP']\n self.PTWGLEXPgiven = True\n elif 'PTWGLEXP'.swapcase() in param:\n self.PTWGLEXP = param['PTWGLEXP'.swapcase()]\n self.PTWGLEXPgiven = True\n else:\n if self.PTWGLEXPgiven == False:\n self.PTWGLEXP = 1.0\n if 'PTWGR' in param:\n self.PTWGR = param['PTWGR']\n self.PTWGRgiven = True\n elif 'PTWGR'.swapcase() in param:\n self.PTWGR = param['PTWGR'.swapcase()]\n self.PTWGRgiven = True\n else:\n if self.PTWGRgiven == False:\n self.PTWGR = self.PTWG\n if 'LPTWGR' in param:\n self.LPTWGR = param['LPTWGR']\n self.LPTWGRgiven = True\n elif 'LPTWGR'.swapcase() in param:\n self.LPTWGR = param['LPTWGR'.swapcase()]\n self.LPTWGRgiven = True\n else:\n if self.LPTWGRgiven == False:\n self.LPTWGR = self.LPTWG\n if 'WPTWGR' in param:\n self.WPTWGR = param['WPTWGR']\n self.WPTWGRgiven = True\n elif 'WPTWGR'.swapcase() in param:\n self.WPTWGR = param['WPTWGR'.swapcase()]\n self.WPTWGRgiven = True\n else:\n if self.WPTWGRgiven == False:\n self.WPTWGR = self.WPTWG\n if 'PPTWGR' in param:\n self.PPTWGR = param['PPTWGR']\n self.PPTWGRgiven = True\n elif 'PPTWGR'.swapcase() in param:\n self.PPTWGR = param['PPTWGR'.swapcase()]\n self.PPTWGRgiven = True\n else:\n if self.PPTWGRgiven == False:\n self.PPTWGR = self.PPTWG\n if 'PTWGLR' in param:\n self.PTWGLR = param['PTWGLR']\n self.PTWGLRgiven = True\n elif 'PTWGLR'.swapcase() in param:\n self.PTWGLR = param['PTWGLR'.swapcase()]\n self.PTWGLRgiven = True\n else:\n if self.PTWGLRgiven == False:\n self.PTWGLR = self.PTWGL\n if 'PTWGLEXPR' in param:\n self.PTWGLEXPR = param['PTWGLEXPR']\n self.PTWGLEXPRgiven = True\n elif 'PTWGLEXPR'.swapcase() in param:\n self.PTWGLEXPR = param['PTWGLEXPR'.swapcase()]\n self.PTWGLEXPRgiven = True\n else:\n if self.PTWGLEXPRgiven == False:\n self.PTWGLEXPR = self.PTWGLEXP\n if 'A1' in param:\n self.A1 = param['A1']\n self.A1given = True\n elif 'A1'.swapcase() in param:\n self.A1 = param['A1'.swapcase()]\n self.A1given = True\n else:\n if self.A1given == False:\n self.A1 = 0.0\n if 'LA1' in param:\n self.LA1 = param['LA1']\n self.LA1given = True\n elif 'LA1'.swapcase() in param:\n self.LA1 = param['LA1'.swapcase()]\n self.LA1given = True\n else:\n if self.LA1given == False:\n self.LA1 = 0.0\n if 'WA1' in param:\n self.WA1 = param['WA1']\n self.WA1given = True\n elif 'WA1'.swapcase() in param:\n self.WA1 = param['WA1'.swapcase()]\n self.WA1given = True\n else:\n if self.WA1given == False:\n self.WA1 = 0.0\n if 'PA1' in param:\n self.PA1 = param['PA1']\n self.PA1given = True\n elif 'PA1'.swapcase() in param:\n self.PA1 = param['PA1'.swapcase()]\n self.PA1given = True\n else:\n if self.PA1given == False:\n self.PA1 = 0.0\n if 'A11' in param:\n self.A11 = param['A11']\n self.A11given = True\n elif 'A11'.swapcase() in param:\n self.A11 = param['A11'.swapcase()]\n self.A11given = True\n else:\n if self.A11given == False:\n self.A11 = 0.0\n if 'LA11' in param:\n self.LA11 = param['LA11']\n self.LA11given = True\n elif 'LA11'.swapcase() in param:\n self.LA11 = param['LA11'.swapcase()]\n self.LA11given = True\n else:\n if self.LA11given == False:\n self.LA11 = 0.0\n if 'WA11' in param:\n self.WA11 = param['WA11']\n self.WA11given = True\n elif 'WA11'.swapcase() in param:\n self.WA11 = param['WA11'.swapcase()]\n self.WA11given = True\n else:\n if self.WA11given == False:\n self.WA11 = 0.0\n if 'PA11' in param:\n self.PA11 = param['PA11']\n self.PA11given = True\n elif 'PA11'.swapcase() in param:\n self.PA11 = param['PA11'.swapcase()]\n self.PA11given = True\n else:\n if self.PA11given == False:\n self.PA11 = 0.0\n if 'A2' in param:\n self.A2 = param['A2']\n self.A2given = True\n elif 'A2'.swapcase() in param:\n self.A2 = param['A2'.swapcase()]\n self.A2given = True\n else:\n if self.A2given == False:\n self.A2 = 0.0\n if 'LA2' in param:\n self.LA2 = param['LA2']\n self.LA2given = True\n elif 'LA2'.swapcase() in param:\n self.LA2 = param['LA2'.swapcase()]\n self.LA2given = True\n else:\n if self.LA2given == False:\n self.LA2 = 0.0\n if 'WA2' in param:\n self.WA2 = param['WA2']\n self.WA2given = True\n elif 'WA2'.swapcase() in param:\n self.WA2 = param['WA2'.swapcase()]\n self.WA2given = True\n else:\n if self.WA2given == False:\n self.WA2 = 0.0\n if 'PA2' in param:\n self.PA2 = param['PA2']\n self.PA2given = True\n elif 'PA2'.swapcase() in param:\n self.PA2 = param['PA2'.swapcase()]\n self.PA2given = True\n else:\n if self.PA2given == False:\n self.PA2 = 0.0\n if 'A21' in param:\n self.A21 = param['A21']\n self.A21given = True\n elif 'A21'.swapcase() in param:\n self.A21 = param['A21'.swapcase()]\n self.A21given = True\n else:\n if self.A21given == False:\n self.A21 = 0.0\n if 'LA21' in param:\n self.LA21 = param['LA21']\n self.LA21given = True\n elif 'LA21'.swapcase() in param:\n self.LA21 = param['LA21'.swapcase()]\n self.LA21given = True\n else:\n if self.LA21given == False:\n self.LA21 = 0.0\n if 'WA21' in param:\n self.WA21 = param['WA21']\n self.WA21given = True\n elif 'WA21'.swapcase() in param:\n self.WA21 = param['WA21'.swapcase()]\n self.WA21given = True\n else:\n if self.WA21given == False:\n self.WA21 = 0.0\n if 'PA21' in param:\n self.PA21 = param['PA21']\n self.PA21given = True\n elif 'PA21'.swapcase() in param:\n self.PA21 = param['PA21'.swapcase()]\n self.PA21given = True\n else:\n if self.PA21given == False:\n self.PA21 = 0.0\n if 'PDIBLC' in param:\n self.PDIBLC = param['PDIBLC']\n self.PDIBLCgiven = True\n elif 'PDIBLC'.swapcase() in param:\n self.PDIBLC = param['PDIBLC'.swapcase()]\n self.PDIBLCgiven = True\n else:\n if self.PDIBLCgiven == False:\n self.PDIBLC = 0.0\n if 'PDIBLCL' in param:\n self.PDIBLCL = param['PDIBLCL']\n self.PDIBLCLgiven = True\n elif 'PDIBLCL'.swapcase() in param:\n self.PDIBLCL = param['PDIBLCL'.swapcase()]\n self.PDIBLCLgiven = True\n else:\n if self.PDIBLCLgiven == False:\n self.PDIBLCL = 0.0\n if 'PDIBLCLEXP' in param:\n self.PDIBLCLEXP = param['PDIBLCLEXP']\n self.PDIBLCLEXPgiven = True\n elif 'PDIBLCLEXP'.swapcase() in param:\n self.PDIBLCLEXP = param['PDIBLCLEXP'.swapcase()]\n self.PDIBLCLEXPgiven = True\n else:\n if self.PDIBLCLEXPgiven == False:\n self.PDIBLCLEXP = 1.0\n if 'LPDIBLC' in param:\n self.LPDIBLC = param['LPDIBLC']\n self.LPDIBLCgiven = True\n elif 'LPDIBLC'.swapcase() in param:\n self.LPDIBLC = param['LPDIBLC'.swapcase()]\n self.LPDIBLCgiven = True\n else:\n if self.LPDIBLCgiven == False:\n self.LPDIBLC = 0.0\n if 'WPDIBLC' in param:\n self.WPDIBLC = param['WPDIBLC']\n self.WPDIBLCgiven = True\n elif 'WPDIBLC'.swapcase() in param:\n self.WPDIBLC = param['WPDIBLC'.swapcase()]\n self.WPDIBLCgiven = True\n else:\n if self.WPDIBLCgiven == False:\n self.WPDIBLC = 0.0\n if 'PPDIBLC' in param:\n self.PPDIBLC = param['PPDIBLC']\n self.PPDIBLCgiven = True\n elif 'PPDIBLC'.swapcase() in param:\n self.PPDIBLC = param['PPDIBLC'.swapcase()]\n self.PPDIBLCgiven = True\n else:\n if self.PPDIBLCgiven == False:\n self.PPDIBLC = 0.0\n if 'PDIBLCR' in param:\n self.PDIBLCR = param['PDIBLCR']\n self.PDIBLCRgiven = True\n elif 'PDIBLCR'.swapcase() in param:\n self.PDIBLCR = param['PDIBLCR'.swapcase()]\n self.PDIBLCRgiven = True\n else:\n if self.PDIBLCRgiven == False:\n self.PDIBLCR = self.PDIBLC\n if 'PDIBLCLR' in param:\n self.PDIBLCLR = param['PDIBLCLR']\n self.PDIBLCLRgiven = True\n elif 'PDIBLCLR'.swapcase() in param:\n self.PDIBLCLR = param['PDIBLCLR'.swapcase()]\n self.PDIBLCLRgiven = True\n else:\n if self.PDIBLCLRgiven == False:\n self.PDIBLCLR = self.PDIBLCL\n if 'PDIBLCLEXPR' in param:\n self.PDIBLCLEXPR = param['PDIBLCLEXPR']\n self.PDIBLCLEXPRgiven = True\n elif 'PDIBLCLEXPR'.swapcase() in param:\n self.PDIBLCLEXPR = param['PDIBLCLEXPR'.swapcase()]\n self.PDIBLCLEXPRgiven = True\n else:\n if self.PDIBLCLEXPRgiven == False:\n self.PDIBLCLEXPR = self.PDIBLCLEXP\n if 'LPDIBLCR' in param:\n self.LPDIBLCR = param['LPDIBLCR']\n self.LPDIBLCRgiven = True\n elif 'LPDIBLCR'.swapcase() in param:\n self.LPDIBLCR = param['LPDIBLCR'.swapcase()]\n self.LPDIBLCRgiven = True\n else:\n if self.LPDIBLCRgiven == False:\n self.LPDIBLCR = self.LPDIBLC\n if 'WPDIBLCR' in param:\n self.WPDIBLCR = param['WPDIBLCR']\n self.WPDIBLCRgiven = True\n elif 'WPDIBLCR'.swapcase() in param:\n self.WPDIBLCR = param['WPDIBLCR'.swapcase()]\n self.WPDIBLCRgiven = True\n else:\n if self.WPDIBLCRgiven == False:\n self.WPDIBLCR = self.WPDIBLC\n if 'PPDIBLCR' in param:\n self.PPDIBLCR = param['PPDIBLCR']\n self.PPDIBLCRgiven = True\n elif 'PPDIBLCR'.swapcase() in param:\n self.PPDIBLCR = param['PPDIBLCR'.swapcase()]\n self.PPDIBLCRgiven = True\n else:\n if self.PPDIBLCRgiven == False:\n self.PPDIBLCR = self.PPDIBLC\n if 'PDIBLCB' in param:\n self.PDIBLCB = param['PDIBLCB']\n self.PDIBLCBgiven = True\n elif 'PDIBLCB'.swapcase() in param:\n self.PDIBLCB = param['PDIBLCB'.swapcase()]\n self.PDIBLCBgiven = True\n else:\n if self.PDIBLCBgiven == False:\n self.PDIBLCB = 0.0\n if 'LPDIBLCB' in param:\n self.LPDIBLCB = param['LPDIBLCB']\n self.LPDIBLCBgiven = True\n elif 'LPDIBLCB'.swapcase() in param:\n self.LPDIBLCB = param['LPDIBLCB'.swapcase()]\n self.LPDIBLCBgiven = True\n else:\n if self.LPDIBLCBgiven == False:\n self.LPDIBLCB = 0.0\n if 'WPDIBLCB' in param:\n self.WPDIBLCB = param['WPDIBLCB']\n self.WPDIBLCBgiven = True\n elif 'WPDIBLCB'.swapcase() in param:\n self.WPDIBLCB = param['WPDIBLCB'.swapcase()]\n self.WPDIBLCBgiven = True\n else:\n if self.WPDIBLCBgiven == False:\n self.WPDIBLCB = 0.0\n if 'PPDIBLCB' in param:\n self.PPDIBLCB = param['PPDIBLCB']\n self.PPDIBLCBgiven = True\n elif 'PPDIBLCB'.swapcase() in param:\n self.PPDIBLCB = param['PPDIBLCB'.swapcase()]\n self.PPDIBLCBgiven = True\n else:\n if self.PPDIBLCBgiven == False:\n self.PPDIBLCB = 0.0\n if 'PVAG' in param:\n self.PVAG = param['PVAG']\n self.PVAGgiven = True\n elif 'PVAG'.swapcase() in param:\n self.PVAG = param['PVAG'.swapcase()]\n self.PVAGgiven = True\n else:\n if self.PVAGgiven == False:\n self.PVAG = 1.0\n if 'LPVAG' in param:\n self.LPVAG = param['LPVAG']\n self.LPVAGgiven = True\n elif 'LPVAG'.swapcase() in param:\n self.LPVAG = param['LPVAG'.swapcase()]\n self.LPVAGgiven = True\n else:\n if self.LPVAGgiven == False:\n self.LPVAG = 0.0\n if 'WPVAG' in param:\n self.WPVAG = param['WPVAG']\n self.WPVAGgiven = True\n elif 'WPVAG'.swapcase() in param:\n self.WPVAG = param['WPVAG'.swapcase()]\n self.WPVAGgiven = True\n else:\n if self.WPVAGgiven == False:\n self.WPVAG = 0.0\n if 'PPVAG' in param:\n self.PPVAG = param['PPVAG']\n self.PPVAGgiven = True\n elif 'PPVAG'.swapcase() in param:\n self.PPVAG = param['PPVAG'.swapcase()]\n self.PPVAGgiven = True\n else:\n if self.PPVAGgiven == False:\n self.PPVAG = 0.0\n if 'FPROUT' in param:\n self.FPROUT = param['FPROUT']\n self.FPROUTgiven = True\n elif 'FPROUT'.swapcase() in param:\n self.FPROUT = param['FPROUT'.swapcase()]\n self.FPROUTgiven = True\n else:\n if self.FPROUTgiven == False:\n self.FPROUT = 0.0\n if 'FPROUTL' in param:\n self.FPROUTL = param['FPROUTL']\n self.FPROUTLgiven = True\n elif 'FPROUTL'.swapcase() in param:\n self.FPROUTL = param['FPROUTL'.swapcase()]\n self.FPROUTLgiven = True\n else:\n if self.FPROUTLgiven == False:\n self.FPROUTL = 0.0\n if 'FPROUTLEXP' in param:\n self.FPROUTLEXP = param['FPROUTLEXP']\n self.FPROUTLEXPgiven = True\n elif 'FPROUTLEXP'.swapcase() in param:\n self.FPROUTLEXP = param['FPROUTLEXP'.swapcase()]\n self.FPROUTLEXPgiven = True\n else:\n if self.FPROUTLEXPgiven == False:\n self.FPROUTLEXP = 1.0\n if 'LFPROUT' in param:\n self.LFPROUT = param['LFPROUT']\n self.LFPROUTgiven = True\n elif 'LFPROUT'.swapcase() in param:\n self.LFPROUT = param['LFPROUT'.swapcase()]\n self.LFPROUTgiven = True\n else:\n if self.LFPROUTgiven == False:\n self.LFPROUT = 0.0\n if 'WFPROUT' in param:\n self.WFPROUT = param['WFPROUT']\n self.WFPROUTgiven = True\n elif 'WFPROUT'.swapcase() in param:\n self.WFPROUT = param['WFPROUT'.swapcase()]\n self.WFPROUTgiven = True\n else:\n if self.WFPROUTgiven == False:\n self.WFPROUT = 0.0\n if 'PFPROUT' in param:\n self.PFPROUT = param['PFPROUT']\n self.PFPROUTgiven = True\n elif 'PFPROUT'.swapcase() in param:\n self.PFPROUT = param['PFPROUT'.swapcase()]\n self.PFPROUTgiven = True\n else:\n if self.PFPROUTgiven == False:\n self.PFPROUT = 0.0\n if 'ALPHA0' in param:\n self.ALPHA0 = param['ALPHA0']\n self.ALPHA0given = True\n elif 'ALPHA0'.swapcase() in param:\n self.ALPHA0 = param['ALPHA0'.swapcase()]\n self.ALPHA0given = True\n else:\n if self.ALPHA0given == False:\n self.ALPHA0 = 0.0\n if 'ALPHA0L' in param:\n self.ALPHA0L = param['ALPHA0L']\n self.ALPHA0Lgiven = True\n elif 'ALPHA0L'.swapcase() in param:\n self.ALPHA0L = param['ALPHA0L'.swapcase()]\n self.ALPHA0Lgiven = True\n else:\n if self.ALPHA0Lgiven == False:\n self.ALPHA0L = 0.0\n if 'ALPHA0LEXP' in param:\n self.ALPHA0LEXP = param['ALPHA0LEXP']\n self.ALPHA0LEXPgiven = True\n elif 'ALPHA0LEXP'.swapcase() in param:\n self.ALPHA0LEXP = param['ALPHA0LEXP'.swapcase()]\n self.ALPHA0LEXPgiven = True\n else:\n if self.ALPHA0LEXPgiven == False:\n self.ALPHA0LEXP = 1.0\n if 'LALPHA0' in param:\n self.LALPHA0 = param['LALPHA0']\n self.LALPHA0given = True\n elif 'LALPHA0'.swapcase() in param:\n self.LALPHA0 = param['LALPHA0'.swapcase()]\n self.LALPHA0given = True\n else:\n if self.LALPHA0given == False:\n self.LALPHA0 = 0.0\n if 'WALPHA0' in param:\n self.WALPHA0 = param['WALPHA0']\n self.WALPHA0given = True\n elif 'WALPHA0'.swapcase() in param:\n self.WALPHA0 = param['WALPHA0'.swapcase()]\n self.WALPHA0given = True\n else:\n if self.WALPHA0given == False:\n self.WALPHA0 = 0.0\n if 'PALPHA0' in param:\n self.PALPHA0 = param['PALPHA0']\n self.PALPHA0given = True\n elif 'PALPHA0'.swapcase() in param:\n self.PALPHA0 = param['PALPHA0'.swapcase()]\n self.PALPHA0given = True\n else:\n if self.PALPHA0given == False:\n self.PALPHA0 = 0.0\n if 'BETA0' in param:\n self.BETA0 = param['BETA0']\n self.BETA0given = True\n elif 'BETA0'.swapcase() in param:\n self.BETA0 = param['BETA0'.swapcase()]\n self.BETA0given = True\n else:\n if self.BETA0given == False:\n self.BETA0 = 0.0\n if 'LBETA0' in param:\n self.LBETA0 = param['LBETA0']\n self.LBETA0given = True\n elif 'LBETA0'.swapcase() in param:\n self.LBETA0 = param['LBETA0'.swapcase()]\n self.LBETA0given = True\n else:\n if self.LBETA0given == False:\n self.LBETA0 = 0.0\n if 'WBETA0' in param:\n self.WBETA0 = param['WBETA0']\n self.WBETA0given = True\n elif 'WBETA0'.swapcase() in param:\n self.WBETA0 = param['WBETA0'.swapcase()]\n self.WBETA0given = True\n else:\n if self.WBETA0given == False:\n self.WBETA0 = 0.0\n if 'PBETA0' in param:\n self.PBETA0 = param['PBETA0']\n self.PBETA0given = True\n elif 'PBETA0'.swapcase() in param:\n self.PBETA0 = param['PBETA0'.swapcase()]\n self.PBETA0given = True\n else:\n if self.PBETA0given == False:\n self.PBETA0 = 0.0\n if 'AIGBACC' in param:\n self.AIGBACC = param['AIGBACC']\n self.AIGBACCgiven = True\n elif 'AIGBACC'.swapcase() in param:\n self.AIGBACC = param['AIGBACC'.swapcase()]\n self.AIGBACCgiven = True\n else:\n if self.AIGBACCgiven == False:\n self.AIGBACC = 0.0136\n if 'BIGBACC' in param:\n self.BIGBACC = param['BIGBACC']\n self.BIGBACCgiven = True\n elif 'BIGBACC'.swapcase() in param:\n self.BIGBACC = param['BIGBACC'.swapcase()]\n self.BIGBACCgiven = True\n else:\n if self.BIGBACCgiven == False:\n self.BIGBACC = 0.00171\n if 'CIGBACC' in param:\n self.CIGBACC = param['CIGBACC']\n self.CIGBACCgiven = True\n elif 'CIGBACC'.swapcase() in param:\n self.CIGBACC = param['CIGBACC'.swapcase()]\n self.CIGBACCgiven = True\n else:\n if self.CIGBACCgiven == False:\n self.CIGBACC = 0.075\n if 'NIGBACC' in param:\n self.NIGBACC = param['NIGBACC']\n self.NIGBACCgiven = True\n elif 'NIGBACC'.swapcase() in param:\n self.NIGBACC = param['NIGBACC'.swapcase()]\n self.NIGBACCgiven = True\n else:\n if self.NIGBACCgiven == False:\n self.NIGBACC = 1.0\n if 'AIGBINV' in param:\n self.AIGBINV = param['AIGBINV']\n self.AIGBINVgiven = True\n elif 'AIGBINV'.swapcase() in param:\n self.AIGBINV = param['AIGBINV'.swapcase()]\n self.AIGBINVgiven = True\n else:\n if self.AIGBINVgiven == False:\n self.AIGBINV = 0.0111\n if 'BIGBINV' in param:\n self.BIGBINV = param['BIGBINV']\n self.BIGBINVgiven = True\n elif 'BIGBINV'.swapcase() in param:\n self.BIGBINV = param['BIGBINV'.swapcase()]\n self.BIGBINVgiven = True\n else:\n if self.BIGBINVgiven == False:\n self.BIGBINV = 0.000949\n if 'CIGBINV' in param:\n self.CIGBINV = param['CIGBINV']\n self.CIGBINVgiven = True\n elif 'CIGBINV'.swapcase() in param:\n self.CIGBINV = param['CIGBINV'.swapcase()]\n self.CIGBINVgiven = True\n else:\n if self.CIGBINVgiven == False:\n self.CIGBINV = 0.006\n if 'EIGBINV' in param:\n self.EIGBINV = param['EIGBINV']\n self.EIGBINVgiven = True\n elif 'EIGBINV'.swapcase() in param:\n self.EIGBINV = param['EIGBINV'.swapcase()]\n self.EIGBINVgiven = True\n else:\n if self.EIGBINVgiven == False:\n self.EIGBINV = 1.1\n if 'NIGBINV' in param:\n self.NIGBINV = param['NIGBINV']\n self.NIGBINVgiven = True\n elif 'NIGBINV'.swapcase() in param:\n self.NIGBINV = param['NIGBINV'.swapcase()]\n self.NIGBINVgiven = True\n else:\n if self.NIGBINVgiven == False:\n self.NIGBINV = 3.0\n if 'AIGC' in param:\n self.AIGC = param['AIGC']\n self.AIGCgiven = True\n elif 'AIGC'.swapcase() in param:\n self.AIGC = param['AIGC'.swapcase()]\n self.AIGCgiven = True\n else:\n if self.AIGCgiven == False:\n self.AIGC = 1.36e-2 if (self.TYPE == self.ntype) else 9.8e-3\n if 'BIGC' in param:\n self.BIGC = param['BIGC']\n self.BIGCgiven = True\n elif 'BIGC'.swapcase() in param:\n self.BIGC = param['BIGC'.swapcase()]\n self.BIGCgiven = True\n else:\n if self.BIGCgiven == False:\n self.BIGC = 1.71e-3 if (self.TYPE == self.ntype) else 7.59e-4\n if 'CIGC' in param:\n self.CIGC = param['CIGC']\n self.CIGCgiven = True\n elif 'CIGC'.swapcase() in param:\n self.CIGC = param['CIGC'.swapcase()]\n self.CIGCgiven = True\n else:\n if self.CIGCgiven == False:\n self.CIGC = 0.075 if (self.TYPE == self.ntype) else 0.03\n if 'AIGS' in param:\n self.AIGS = param['AIGS']\n self.AIGSgiven = True\n elif 'AIGS'.swapcase() in param:\n self.AIGS = param['AIGS'.swapcase()]\n self.AIGSgiven = True\n else:\n if self.AIGSgiven == False:\n self.AIGS = 1.36e-2 if (self.TYPE == self.ntype) else 9.8e-3\n if 'BIGS' in param:\n self.BIGS = param['BIGS']\n self.BIGSgiven = True\n elif 'BIGS'.swapcase() in param:\n self.BIGS = param['BIGS'.swapcase()]\n self.BIGSgiven = True\n else:\n if self.BIGSgiven == False:\n self.BIGS = 1.71e-3 if (self.TYPE == self.ntype) else 7.59e-4\n if 'CIGS' in param:\n self.CIGS = param['CIGS']\n self.CIGSgiven = True\n elif 'CIGS'.swapcase() in param:\n self.CIGS = param['CIGS'.swapcase()]\n self.CIGSgiven = True\n else:\n if self.CIGSgiven == False:\n self.CIGS = 0.075 if (self.TYPE == self.ntype) else 0.03\n if 'AIGD' in param:\n self.AIGD = param['AIGD']\n self.AIGDgiven = True\n elif 'AIGD'.swapcase() in param:\n self.AIGD = param['AIGD'.swapcase()]\n self.AIGDgiven = True\n else:\n if self.AIGDgiven == False:\n self.AIGD = 1.36e-2 if (self.TYPE == self.ntype) else 9.8e-3\n if 'BIGD' in param:\n self.BIGD = param['BIGD']\n self.BIGDgiven = True\n elif 'BIGD'.swapcase() in param:\n self.BIGD = param['BIGD'.swapcase()]\n self.BIGDgiven = True\n else:\n if self.BIGDgiven == False:\n self.BIGD = 1.71e-3 if (self.TYPE == self.ntype) else 7.59e-4\n if 'CIGD' in param:\n self.CIGD = param['CIGD']\n self.CIGDgiven = True\n elif 'CIGD'.swapcase() in param:\n self.CIGD = param['CIGD'.swapcase()]\n self.CIGDgiven = True\n else:\n if self.CIGDgiven == False:\n self.CIGD = 0.075 if (self.TYPE == self.ntype) else 0.03\n if 'DLCIG' in param:\n self.DLCIG = param['DLCIG']\n self.DLCIGgiven = True\n elif 'DLCIG'.swapcase() in param:\n self.DLCIG = param['DLCIG'.swapcase()]\n self.DLCIGgiven = True\n else:\n if self.DLCIGgiven == False:\n self.DLCIG = self.LINT\n if 'DLCIGD' in param:\n self.DLCIGD = param['DLCIGD']\n self.DLCIGDgiven = True\n elif 'DLCIGD'.swapcase() in param:\n self.DLCIGD = param['DLCIGD'.swapcase()]\n self.DLCIGDgiven = True\n else:\n if self.DLCIGDgiven == False:\n self.DLCIGD = self.DLCIG\n if 'POXEDGE' in param:\n self.POXEDGE = param['POXEDGE']\n self.POXEDGEgiven = True\n elif 'POXEDGE'.swapcase() in param:\n self.POXEDGE = param['POXEDGE'.swapcase()]\n self.POXEDGEgiven = True\n else:\n if self.POXEDGEgiven == False:\n self.POXEDGE = 1.0\n if 'NTOX' in param:\n self.NTOX = param['NTOX']\n self.NTOXgiven = True\n elif 'NTOX'.swapcase() in param:\n self.NTOX = param['NTOX'.swapcase()]\n self.NTOXgiven = True\n else:\n if self.NTOXgiven == False:\n self.NTOX = 1.0\n if 'TOXREF' in param:\n self.TOXREF = param['TOXREF']\n self.TOXREFgiven = True\n elif 'TOXREF'.swapcase() in param:\n self.TOXREF = param['TOXREF'.swapcase()]\n self.TOXREFgiven = True\n else:\n if self.TOXREFgiven == False:\n self.TOXREF = 3e-09\n if 'PIGCD' in param:\n self.PIGCD = param['PIGCD']\n self.PIGCDgiven = True\n elif 'PIGCD'.swapcase() in param:\n self.PIGCD = param['PIGCD'.swapcase()]\n self.PIGCDgiven = True\n else:\n if self.PIGCDgiven == False:\n self.PIGCD = 1.0\n if 'AIGCL' in param:\n self.AIGCL = param['AIGCL']\n self.AIGCLgiven = True\n elif 'AIGCL'.swapcase() in param:\n self.AIGCL = param['AIGCL'.swapcase()]\n self.AIGCLgiven = True\n else:\n if self.AIGCLgiven == False:\n self.AIGCL = 0.0\n if 'AIGCW' in param:\n self.AIGCW = param['AIGCW']\n self.AIGCWgiven = True\n elif 'AIGCW'.swapcase() in param:\n self.AIGCW = param['AIGCW'.swapcase()]\n self.AIGCWgiven = True\n else:\n if self.AIGCWgiven == False:\n self.AIGCW = 0.0\n if 'AIGSL' in param:\n self.AIGSL = param['AIGSL']\n self.AIGSLgiven = True\n elif 'AIGSL'.swapcase() in param:\n self.AIGSL = param['AIGSL'.swapcase()]\n self.AIGSLgiven = True\n else:\n if self.AIGSLgiven == False:\n self.AIGSL = 0.0\n if 'AIGSW' in param:\n self.AIGSW = param['AIGSW']\n self.AIGSWgiven = True\n elif 'AIGSW'.swapcase() in param:\n self.AIGSW = param['AIGSW'.swapcase()]\n self.AIGSWgiven = True\n else:\n if self.AIGSWgiven == False:\n self.AIGSW = 0.0\n if 'AIGDL' in param:\n self.AIGDL = param['AIGDL']\n self.AIGDLgiven = True\n elif 'AIGDL'.swapcase() in param:\n self.AIGDL = param['AIGDL'.swapcase()]\n self.AIGDLgiven = True\n else:\n if self.AIGDLgiven == False:\n self.AIGDL = 0.0\n if 'AIGDW' in param:\n self.AIGDW = param['AIGDW']\n self.AIGDWgiven = True\n elif 'AIGDW'.swapcase() in param:\n self.AIGDW = param['AIGDW'.swapcase()]\n self.AIGDWgiven = True\n else:\n if self.AIGDWgiven == False:\n self.AIGDW = 0.0\n if 'PIGCDL' in param:\n self.PIGCDL = param['PIGCDL']\n self.PIGCDLgiven = True\n elif 'PIGCDL'.swapcase() in param:\n self.PIGCDL = param['PIGCDL'.swapcase()]\n self.PIGCDLgiven = True\n else:\n if self.PIGCDLgiven == False:\n self.PIGCDL = 0.0\n if 'LAIGBINV' in param:\n self.LAIGBINV = param['LAIGBINV']\n self.LAIGBINVgiven = True\n elif 'LAIGBINV'.swapcase() in param:\n self.LAIGBINV = param['LAIGBINV'.swapcase()]\n self.LAIGBINVgiven = True\n else:\n if self.LAIGBINVgiven == False:\n self.LAIGBINV = 0.0\n if 'WAIGBINV' in param:\n self.WAIGBINV = param['WAIGBINV']\n self.WAIGBINVgiven = True\n elif 'WAIGBINV'.swapcase() in param:\n self.WAIGBINV = param['WAIGBINV'.swapcase()]\n self.WAIGBINVgiven = True\n else:\n if self.WAIGBINVgiven == False:\n self.WAIGBINV = 0.0\n if 'PAIGBINV' in param:\n self.PAIGBINV = param['PAIGBINV']\n self.PAIGBINVgiven = True\n elif 'PAIGBINV'.swapcase() in param:\n self.PAIGBINV = param['PAIGBINV'.swapcase()]\n self.PAIGBINVgiven = True\n else:\n if self.PAIGBINVgiven == False:\n self.PAIGBINV = 0.0\n if 'LBIGBINV' in param:\n self.LBIGBINV = param['LBIGBINV']\n self.LBIGBINVgiven = True\n elif 'LBIGBINV'.swapcase() in param:\n self.LBIGBINV = param['LBIGBINV'.swapcase()]\n self.LBIGBINVgiven = True\n else:\n if self.LBIGBINVgiven == False:\n self.LBIGBINV = 0.0\n if 'WBIGBINV' in param:\n self.WBIGBINV = param['WBIGBINV']\n self.WBIGBINVgiven = True\n elif 'WBIGBINV'.swapcase() in param:\n self.WBIGBINV = param['WBIGBINV'.swapcase()]\n self.WBIGBINVgiven = True\n else:\n if self.WBIGBINVgiven == False:\n self.WBIGBINV = 0.0\n if 'PBIGBINV' in param:\n self.PBIGBINV = param['PBIGBINV']\n self.PBIGBINVgiven = True\n elif 'PBIGBINV'.swapcase() in param:\n self.PBIGBINV = param['PBIGBINV'.swapcase()]\n self.PBIGBINVgiven = True\n else:\n if self.PBIGBINVgiven == False:\n self.PBIGBINV = 0.0\n if 'LCIGBINV' in param:\n self.LCIGBINV = param['LCIGBINV']\n self.LCIGBINVgiven = True\n elif 'LCIGBINV'.swapcase() in param:\n self.LCIGBINV = param['LCIGBINV'.swapcase()]\n self.LCIGBINVgiven = True\n else:\n if self.LCIGBINVgiven == False:\n self.LCIGBINV = 0.0\n if 'WCIGBINV' in param:\n self.WCIGBINV = param['WCIGBINV']\n self.WCIGBINVgiven = True\n elif 'WCIGBINV'.swapcase() in param:\n self.WCIGBINV = param['WCIGBINV'.swapcase()]\n self.WCIGBINVgiven = True\n else:\n if self.WCIGBINVgiven == False:\n self.WCIGBINV = 0.0\n if 'PCIGBINV' in param:\n self.PCIGBINV = param['PCIGBINV']\n self.PCIGBINVgiven = True\n elif 'PCIGBINV'.swapcase() in param:\n self.PCIGBINV = param['PCIGBINV'.swapcase()]\n self.PCIGBINVgiven = True\n else:\n if self.PCIGBINVgiven == False:\n self.PCIGBINV = 0.0\n if 'LEIGBINV' in param:\n self.LEIGBINV = param['LEIGBINV']\n self.LEIGBINVgiven = True\n elif 'LEIGBINV'.swapcase() in param:\n self.LEIGBINV = param['LEIGBINV'.swapcase()]\n self.LEIGBINVgiven = True\n else:\n if self.LEIGBINVgiven == False:\n self.LEIGBINV = 0.0\n if 'WEIGBINV' in param:\n self.WEIGBINV = param['WEIGBINV']\n self.WEIGBINVgiven = True\n elif 'WEIGBINV'.swapcase() in param:\n self.WEIGBINV = param['WEIGBINV'.swapcase()]\n self.WEIGBINVgiven = True\n else:\n if self.WEIGBINVgiven == False:\n self.WEIGBINV = 0.0\n if 'PEIGBINV' in param:\n self.PEIGBINV = param['PEIGBINV']\n self.PEIGBINVgiven = True\n elif 'PEIGBINV'.swapcase() in param:\n self.PEIGBINV = param['PEIGBINV'.swapcase()]\n self.PEIGBINVgiven = True\n else:\n if self.PEIGBINVgiven == False:\n self.PEIGBINV = 0.0\n if 'LNIGBINV' in param:\n self.LNIGBINV = param['LNIGBINV']\n self.LNIGBINVgiven = True\n elif 'LNIGBINV'.swapcase() in param:\n self.LNIGBINV = param['LNIGBINV'.swapcase()]\n self.LNIGBINVgiven = True\n else:\n if self.LNIGBINVgiven == False:\n self.LNIGBINV = 0.0\n if 'WNIGBINV' in param:\n self.WNIGBINV = param['WNIGBINV']\n self.WNIGBINVgiven = True\n elif 'WNIGBINV'.swapcase() in param:\n self.WNIGBINV = param['WNIGBINV'.swapcase()]\n self.WNIGBINVgiven = True\n else:\n if self.WNIGBINVgiven == False:\n self.WNIGBINV = 0.0\n if 'PNIGBINV' in param:\n self.PNIGBINV = param['PNIGBINV']\n self.PNIGBINVgiven = True\n elif 'PNIGBINV'.swapcase() in param:\n self.PNIGBINV = param['PNIGBINV'.swapcase()]\n self.PNIGBINVgiven = True\n else:\n if self.PNIGBINVgiven == False:\n self.PNIGBINV = 0.0\n if 'LAIGBACC' in param:\n self.LAIGBACC = param['LAIGBACC']\n self.LAIGBACCgiven = True\n elif 'LAIGBACC'.swapcase() in param:\n self.LAIGBACC = param['LAIGBACC'.swapcase()]\n self.LAIGBACCgiven = True\n else:\n if self.LAIGBACCgiven == False:\n self.LAIGBACC = 0.0\n if 'WAIGBACC' in param:\n self.WAIGBACC = param['WAIGBACC']\n self.WAIGBACCgiven = True\n elif 'WAIGBACC'.swapcase() in param:\n self.WAIGBACC = param['WAIGBACC'.swapcase()]\n self.WAIGBACCgiven = True\n else:\n if self.WAIGBACCgiven == False:\n self.WAIGBACC = 0.0\n if 'PAIGBACC' in param:\n self.PAIGBACC = param['PAIGBACC']\n self.PAIGBACCgiven = True\n elif 'PAIGBACC'.swapcase() in param:\n self.PAIGBACC = param['PAIGBACC'.swapcase()]\n self.PAIGBACCgiven = True\n else:\n if self.PAIGBACCgiven == False:\n self.PAIGBACC = 0.0\n if 'LBIGBACC' in param:\n self.LBIGBACC = param['LBIGBACC']\n self.LBIGBACCgiven = True\n elif 'LBIGBACC'.swapcase() in param:\n self.LBIGBACC = param['LBIGBACC'.swapcase()]\n self.LBIGBACCgiven = True\n else:\n if self.LBIGBACCgiven == False:\n self.LBIGBACC = 0.0\n if 'WBIGBACC' in param:\n self.WBIGBACC = param['WBIGBACC']\n self.WBIGBACCgiven = True\n elif 'WBIGBACC'.swapcase() in param:\n self.WBIGBACC = param['WBIGBACC'.swapcase()]\n self.WBIGBACCgiven = True\n else:\n if self.WBIGBACCgiven == False:\n self.WBIGBACC = 0.0\n if 'PBIGBACC' in param:\n self.PBIGBACC = param['PBIGBACC']\n self.PBIGBACCgiven = True\n elif 'PBIGBACC'.swapcase() in param:\n self.PBIGBACC = param['PBIGBACC'.swapcase()]\n self.PBIGBACCgiven = True\n else:\n if self.PBIGBACCgiven == False:\n self.PBIGBACC = 0.0\n if 'LCIGBACC' in param:\n self.LCIGBACC = param['LCIGBACC']\n self.LCIGBACCgiven = True\n elif 'LCIGBACC'.swapcase() in param:\n self.LCIGBACC = param['LCIGBACC'.swapcase()]\n self.LCIGBACCgiven = True\n else:\n if self.LCIGBACCgiven == False:\n self.LCIGBACC = 0.0\n if 'WCIGBACC' in param:\n self.WCIGBACC = param['WCIGBACC']\n self.WCIGBACCgiven = True\n elif 'WCIGBACC'.swapcase() in param:\n self.WCIGBACC = param['WCIGBACC'.swapcase()]\n self.WCIGBACCgiven = True\n else:\n if self.WCIGBACCgiven == False:\n self.WCIGBACC = 0.0\n if 'PCIGBACC' in param:\n self.PCIGBACC = param['PCIGBACC']\n self.PCIGBACCgiven = True\n elif 'PCIGBACC'.swapcase() in param:\n self.PCIGBACC = param['PCIGBACC'.swapcase()]\n self.PCIGBACCgiven = True\n else:\n if self.PCIGBACCgiven == False:\n self.PCIGBACC = 0.0\n if 'LNIGBACC' in param:\n self.LNIGBACC = param['LNIGBACC']\n self.LNIGBACCgiven = True\n elif 'LNIGBACC'.swapcase() in param:\n self.LNIGBACC = param['LNIGBACC'.swapcase()]\n self.LNIGBACCgiven = True\n else:\n if self.LNIGBACCgiven == False:\n self.LNIGBACC = 0.0\n if 'WNIGBACC' in param:\n self.WNIGBACC = param['WNIGBACC']\n self.WNIGBACCgiven = True\n elif 'WNIGBACC'.swapcase() in param:\n self.WNIGBACC = param['WNIGBACC'.swapcase()]\n self.WNIGBACCgiven = True\n else:\n if self.WNIGBACCgiven == False:\n self.WNIGBACC = 0.0\n if 'PNIGBACC' in param:\n self.PNIGBACC = param['PNIGBACC']\n self.PNIGBACCgiven = True\n elif 'PNIGBACC'.swapcase() in param:\n self.PNIGBACC = param['PNIGBACC'.swapcase()]\n self.PNIGBACCgiven = True\n else:\n if self.PNIGBACCgiven == False:\n self.PNIGBACC = 0.0\n if 'LAIGC' in param:\n self.LAIGC = param['LAIGC']\n self.LAIGCgiven = True\n elif 'LAIGC'.swapcase() in param:\n self.LAIGC = param['LAIGC'.swapcase()]\n self.LAIGCgiven = True\n else:\n if self.LAIGCgiven == False:\n self.LAIGC = 0.0\n if 'WAIGC' in param:\n self.WAIGC = param['WAIGC']\n self.WAIGCgiven = True\n elif 'WAIGC'.swapcase() in param:\n self.WAIGC = param['WAIGC'.swapcase()]\n self.WAIGCgiven = True\n else:\n if self.WAIGCgiven == False:\n self.WAIGC = 0.0\n if 'PAIGC' in param:\n self.PAIGC = param['PAIGC']\n self.PAIGCgiven = True\n elif 'PAIGC'.swapcase() in param:\n self.PAIGC = param['PAIGC'.swapcase()]\n self.PAIGCgiven = True\n else:\n if self.PAIGCgiven == False:\n self.PAIGC = 0.0\n if 'LBIGC' in param:\n self.LBIGC = param['LBIGC']\n self.LBIGCgiven = True\n elif 'LBIGC'.swapcase() in param:\n self.LBIGC = param['LBIGC'.swapcase()]\n self.LBIGCgiven = True\n else:\n if self.LBIGCgiven == False:\n self.LBIGC = 0.0\n if 'WBIGC' in param:\n self.WBIGC = param['WBIGC']\n self.WBIGCgiven = True\n elif 'WBIGC'.swapcase() in param:\n self.WBIGC = param['WBIGC'.swapcase()]\n self.WBIGCgiven = True\n else:\n if self.WBIGCgiven == False:\n self.WBIGC = 0.0\n if 'PBIGC' in param:\n self.PBIGC = param['PBIGC']\n self.PBIGCgiven = True\n elif 'PBIGC'.swapcase() in param:\n self.PBIGC = param['PBIGC'.swapcase()]\n self.PBIGCgiven = True\n else:\n if self.PBIGCgiven == False:\n self.PBIGC = 0.0\n if 'LCIGC' in param:\n self.LCIGC = param['LCIGC']\n self.LCIGCgiven = True\n elif 'LCIGC'.swapcase() in param:\n self.LCIGC = param['LCIGC'.swapcase()]\n self.LCIGCgiven = True\n else:\n if self.LCIGCgiven == False:\n self.LCIGC = 0.0\n if 'WCIGC' in param:\n self.WCIGC = param['WCIGC']\n self.WCIGCgiven = True\n elif 'WCIGC'.swapcase() in param:\n self.WCIGC = param['WCIGC'.swapcase()]\n self.WCIGCgiven = True\n else:\n if self.WCIGCgiven == False:\n self.WCIGC = 0.0\n if 'PCIGC' in param:\n self.PCIGC = param['PCIGC']\n self.PCIGCgiven = True\n elif 'PCIGC'.swapcase() in param:\n self.PCIGC = param['PCIGC'.swapcase()]\n self.PCIGCgiven = True\n else:\n if self.PCIGCgiven == False:\n self.PCIGC = 0.0\n if 'LAIGS' in param:\n self.LAIGS = param['LAIGS']\n self.LAIGSgiven = True\n elif 'LAIGS'.swapcase() in param:\n self.LAIGS = param['LAIGS'.swapcase()]\n self.LAIGSgiven = True\n else:\n if self.LAIGSgiven == False:\n self.LAIGS = 0.0\n if 'WAIGS' in param:\n self.WAIGS = param['WAIGS']\n self.WAIGSgiven = True\n elif 'WAIGS'.swapcase() in param:\n self.WAIGS = param['WAIGS'.swapcase()]\n self.WAIGSgiven = True\n else:\n if self.WAIGSgiven == False:\n self.WAIGS = 0.0\n if 'PAIGS' in param:\n self.PAIGS = param['PAIGS']\n self.PAIGSgiven = True\n elif 'PAIGS'.swapcase() in param:\n self.PAIGS = param['PAIGS'.swapcase()]\n self.PAIGSgiven = True\n else:\n if self.PAIGSgiven == False:\n self.PAIGS = 0.0\n if 'LBIGS' in param:\n self.LBIGS = param['LBIGS']\n self.LBIGSgiven = True\n elif 'LBIGS'.swapcase() in param:\n self.LBIGS = param['LBIGS'.swapcase()]\n self.LBIGSgiven = True\n else:\n if self.LBIGSgiven == False:\n self.LBIGS = 0.0\n if 'WBIGS' in param:\n self.WBIGS = param['WBIGS']\n self.WBIGSgiven = True\n elif 'WBIGS'.swapcase() in param:\n self.WBIGS = param['WBIGS'.swapcase()]\n self.WBIGSgiven = True\n else:\n if self.WBIGSgiven == False:\n self.WBIGS = 0.0\n if 'PBIGS' in param:\n self.PBIGS = param['PBIGS']\n self.PBIGSgiven = True\n elif 'PBIGS'.swapcase() in param:\n self.PBIGS = param['PBIGS'.swapcase()]\n self.PBIGSgiven = True\n else:\n if self.PBIGSgiven == False:\n self.PBIGS = 0.0\n if 'LCIGS' in param:\n self.LCIGS = param['LCIGS']\n self.LCIGSgiven = True\n elif 'LCIGS'.swapcase() in param:\n self.LCIGS = param['LCIGS'.swapcase()]\n self.LCIGSgiven = True\n else:\n if self.LCIGSgiven == False:\n self.LCIGS = 0.0\n if 'WCIGS' in param:\n self.WCIGS = param['WCIGS']\n self.WCIGSgiven = True\n elif 'WCIGS'.swapcase() in param:\n self.WCIGS = param['WCIGS'.swapcase()]\n self.WCIGSgiven = True\n else:\n if self.WCIGSgiven == False:\n self.WCIGS = 0.0\n if 'PCIGS' in param:\n self.PCIGS = param['PCIGS']\n self.PCIGSgiven = True\n elif 'PCIGS'.swapcase() in param:\n self.PCIGS = param['PCIGS'.swapcase()]\n self.PCIGSgiven = True\n else:\n if self.PCIGSgiven == False:\n self.PCIGS = 0.0\n if 'LAIGD' in param:\n self.LAIGD = param['LAIGD']\n self.LAIGDgiven = True\n elif 'LAIGD'.swapcase() in param:\n self.LAIGD = param['LAIGD'.swapcase()]\n self.LAIGDgiven = True\n else:\n if self.LAIGDgiven == False:\n self.LAIGD = 0.0\n if 'WAIGD' in param:\n self.WAIGD = param['WAIGD']\n self.WAIGDgiven = True\n elif 'WAIGD'.swapcase() in param:\n self.WAIGD = param['WAIGD'.swapcase()]\n self.WAIGDgiven = True\n else:\n if self.WAIGDgiven == False:\n self.WAIGD = 0.0\n if 'PAIGD' in param:\n self.PAIGD = param['PAIGD']\n self.PAIGDgiven = True\n elif 'PAIGD'.swapcase() in param:\n self.PAIGD = param['PAIGD'.swapcase()]\n self.PAIGDgiven = True\n else:\n if self.PAIGDgiven == False:\n self.PAIGD = 0.0\n if 'LBIGD' in param:\n self.LBIGD = param['LBIGD']\n self.LBIGDgiven = True\n elif 'LBIGD'.swapcase() in param:\n self.LBIGD = param['LBIGD'.swapcase()]\n self.LBIGDgiven = True\n else:\n if self.LBIGDgiven == False:\n self.LBIGD = 0.0\n if 'WBIGD' in param:\n self.WBIGD = param['WBIGD']\n self.WBIGDgiven = True\n elif 'WBIGD'.swapcase() in param:\n self.WBIGD = param['WBIGD'.swapcase()]\n self.WBIGDgiven = True\n else:\n if self.WBIGDgiven == False:\n self.WBIGD = 0.0\n if 'PBIGD' in param:\n self.PBIGD = param['PBIGD']\n self.PBIGDgiven = True\n elif 'PBIGD'.swapcase() in param:\n self.PBIGD = param['PBIGD'.swapcase()]\n self.PBIGDgiven = True\n else:\n if self.PBIGDgiven == False:\n self.PBIGD = 0.0\n if 'LCIGD' in param:\n self.LCIGD = param['LCIGD']\n self.LCIGDgiven = True\n elif 'LCIGD'.swapcase() in param:\n self.LCIGD = param['LCIGD'.swapcase()]\n self.LCIGDgiven = True\n else:\n if self.LCIGDgiven == False:\n self.LCIGD = 0.0\n if 'WCIGD' in param:\n self.WCIGD = param['WCIGD']\n self.WCIGDgiven = True\n elif 'WCIGD'.swapcase() in param:\n self.WCIGD = param['WCIGD'.swapcase()]\n self.WCIGDgiven = True\n else:\n if self.WCIGDgiven == False:\n self.WCIGD = 0.0\n if 'PCIGD' in param:\n self.PCIGD = param['PCIGD']\n self.PCIGDgiven = True\n elif 'PCIGD'.swapcase() in param:\n self.PCIGD = param['PCIGD'.swapcase()]\n self.PCIGDgiven = True\n else:\n if self.PCIGDgiven == False:\n self.PCIGD = 0.0\n if 'LPOXEDGE' in param:\n self.LPOXEDGE = param['LPOXEDGE']\n self.LPOXEDGEgiven = True\n elif 'LPOXEDGE'.swapcase() in param:\n self.LPOXEDGE = param['LPOXEDGE'.swapcase()]\n self.LPOXEDGEgiven = True\n else:\n if self.LPOXEDGEgiven == False:\n self.LPOXEDGE = 0.0\n if 'WPOXEDGE' in param:\n self.WPOXEDGE = param['WPOXEDGE']\n self.WPOXEDGEgiven = True\n elif 'WPOXEDGE'.swapcase() in param:\n self.WPOXEDGE = param['WPOXEDGE'.swapcase()]\n self.WPOXEDGEgiven = True\n else:\n if self.WPOXEDGEgiven == False:\n self.WPOXEDGE = 0.0\n if 'PPOXEDGE' in param:\n self.PPOXEDGE = param['PPOXEDGE']\n self.PPOXEDGEgiven = True\n elif 'PPOXEDGE'.swapcase() in param:\n self.PPOXEDGE = param['PPOXEDGE'.swapcase()]\n self.PPOXEDGEgiven = True\n else:\n if self.PPOXEDGEgiven == False:\n self.PPOXEDGE = 0.0\n if 'LDLCIG' in param:\n self.LDLCIG = param['LDLCIG']\n self.LDLCIGgiven = True\n elif 'LDLCIG'.swapcase() in param:\n self.LDLCIG = param['LDLCIG'.swapcase()]\n self.LDLCIGgiven = True\n else:\n if self.LDLCIGgiven == False:\n self.LDLCIG = 0.0\n if 'WDLCIG' in param:\n self.WDLCIG = param['WDLCIG']\n self.WDLCIGgiven = True\n elif 'WDLCIG'.swapcase() in param:\n self.WDLCIG = param['WDLCIG'.swapcase()]\n self.WDLCIGgiven = True\n else:\n if self.WDLCIGgiven == False:\n self.WDLCIG = 0.0\n if 'PDLCIG' in param:\n self.PDLCIG = param['PDLCIG']\n self.PDLCIGgiven = True\n elif 'PDLCIG'.swapcase() in param:\n self.PDLCIG = param['PDLCIG'.swapcase()]\n self.PDLCIGgiven = True\n else:\n if self.PDLCIGgiven == False:\n self.PDLCIG = 0.0\n if 'LDLCIGD' in param:\n self.LDLCIGD = param['LDLCIGD']\n self.LDLCIGDgiven = True\n elif 'LDLCIGD'.swapcase() in param:\n self.LDLCIGD = param['LDLCIGD'.swapcase()]\n self.LDLCIGDgiven = True\n else:\n if self.LDLCIGDgiven == False:\n self.LDLCIGD = 0.0\n if 'WDLCIGD' in param:\n self.WDLCIGD = param['WDLCIGD']\n self.WDLCIGDgiven = True\n elif 'WDLCIGD'.swapcase() in param:\n self.WDLCIGD = param['WDLCIGD'.swapcase()]\n self.WDLCIGDgiven = True\n else:\n if self.WDLCIGDgiven == False:\n self.WDLCIGD = 0.0\n if 'PDLCIGD' in param:\n self.PDLCIGD = param['PDLCIGD']\n self.PDLCIGDgiven = True\n elif 'PDLCIGD'.swapcase() in param:\n self.PDLCIGD = param['PDLCIGD'.swapcase()]\n self.PDLCIGDgiven = True\n else:\n if self.PDLCIGDgiven == False:\n self.PDLCIGD = 0.0\n if 'LNTOX' in param:\n self.LNTOX = param['LNTOX']\n self.LNTOXgiven = True\n elif 'LNTOX'.swapcase() in param:\n self.LNTOX = param['LNTOX'.swapcase()]\n self.LNTOXgiven = True\n else:\n if self.LNTOXgiven == False:\n self.LNTOX = 0.0\n if 'WNTOX' in param:\n self.WNTOX = param['WNTOX']\n self.WNTOXgiven = True\n elif 'WNTOX'.swapcase() in param:\n self.WNTOX = param['WNTOX'.swapcase()]\n self.WNTOXgiven = True\n else:\n if self.WNTOXgiven == False:\n self.WNTOX = 0.0\n if 'PNTOX' in param:\n self.PNTOX = param['PNTOX']\n self.PNTOXgiven = True\n elif 'PNTOX'.swapcase() in param:\n self.PNTOX = param['PNTOX'.swapcase()]\n self.PNTOXgiven = True\n else:\n if self.PNTOXgiven == False:\n self.PNTOX = 0.0\n if 'AGIDL' in param:\n self.AGIDL = param['AGIDL']\n self.AGIDLgiven = True\n elif 'AGIDL'.swapcase() in param:\n self.AGIDL = param['AGIDL'.swapcase()]\n self.AGIDLgiven = True\n else:\n if self.AGIDLgiven == False:\n self.AGIDL = 0.0\n if 'AGIDLL' in param:\n self.AGIDLL = param['AGIDLL']\n self.AGIDLLgiven = True\n elif 'AGIDLL'.swapcase() in param:\n self.AGIDLL = param['AGIDLL'.swapcase()]\n self.AGIDLLgiven = True\n else:\n if self.AGIDLLgiven == False:\n self.AGIDLL = 0.0\n if 'AGIDLW' in param:\n self.AGIDLW = param['AGIDLW']\n self.AGIDLWgiven = True\n elif 'AGIDLW'.swapcase() in param:\n self.AGIDLW = param['AGIDLW'.swapcase()]\n self.AGIDLWgiven = True\n else:\n if self.AGIDLWgiven == False:\n self.AGIDLW = 0.0\n if 'LAGIDL' in param:\n self.LAGIDL = param['LAGIDL']\n self.LAGIDLgiven = True\n elif 'LAGIDL'.swapcase() in param:\n self.LAGIDL = param['LAGIDL'.swapcase()]\n self.LAGIDLgiven = True\n else:\n if self.LAGIDLgiven == False:\n self.LAGIDL = 0.0\n if 'WAGIDL' in param:\n self.WAGIDL = param['WAGIDL']\n self.WAGIDLgiven = True\n elif 'WAGIDL'.swapcase() in param:\n self.WAGIDL = param['WAGIDL'.swapcase()]\n self.WAGIDLgiven = True\n else:\n if self.WAGIDLgiven == False:\n self.WAGIDL = 0.0\n if 'PAGIDL' in param:\n self.PAGIDL = param['PAGIDL']\n self.PAGIDLgiven = True\n elif 'PAGIDL'.swapcase() in param:\n self.PAGIDL = param['PAGIDL'.swapcase()]\n self.PAGIDLgiven = True\n else:\n if self.PAGIDLgiven == False:\n self.PAGIDL = 0.0\n if 'BGIDL' in param:\n self.BGIDL = param['BGIDL']\n self.BGIDLgiven = True\n elif 'BGIDL'.swapcase() in param:\n self.BGIDL = param['BGIDL'.swapcase()]\n self.BGIDLgiven = True\n else:\n if self.BGIDLgiven == False:\n self.BGIDL = 2300000000.0\n if 'LBGIDL' in param:\n self.LBGIDL = param['LBGIDL']\n self.LBGIDLgiven = True\n elif 'LBGIDL'.swapcase() in param:\n self.LBGIDL = param['LBGIDL'.swapcase()]\n self.LBGIDLgiven = True\n else:\n if self.LBGIDLgiven == False:\n self.LBGIDL = 0.0\n if 'WBGIDL' in param:\n self.WBGIDL = param['WBGIDL']\n self.WBGIDLgiven = True\n elif 'WBGIDL'.swapcase() in param:\n self.WBGIDL = param['WBGIDL'.swapcase()]\n self.WBGIDLgiven = True\n else:\n if self.WBGIDLgiven == False:\n self.WBGIDL = 0.0\n if 'PBGIDL' in param:\n self.PBGIDL = param['PBGIDL']\n self.PBGIDLgiven = True\n elif 'PBGIDL'.swapcase() in param:\n self.PBGIDL = param['PBGIDL'.swapcase()]\n self.PBGIDLgiven = True\n else:\n if self.PBGIDLgiven == False:\n self.PBGIDL = 0.0\n if 'CGIDL' in param:\n self.CGIDL = param['CGIDL']\n self.CGIDLgiven = True\n elif 'CGIDL'.swapcase() in param:\n self.CGIDL = param['CGIDL'.swapcase()]\n self.CGIDLgiven = True\n else:\n if self.CGIDLgiven == False:\n self.CGIDL = 0.5\n if 'LCGIDL' in param:\n self.LCGIDL = param['LCGIDL']\n self.LCGIDLgiven = True\n elif 'LCGIDL'.swapcase() in param:\n self.LCGIDL = param['LCGIDL'.swapcase()]\n self.LCGIDLgiven = True\n else:\n if self.LCGIDLgiven == False:\n self.LCGIDL = 0.0\n if 'WCGIDL' in param:\n self.WCGIDL = param['WCGIDL']\n self.WCGIDLgiven = True\n elif 'WCGIDL'.swapcase() in param:\n self.WCGIDL = param['WCGIDL'.swapcase()]\n self.WCGIDLgiven = True\n else:\n if self.WCGIDLgiven == False:\n self.WCGIDL = 0.0\n if 'PCGIDL' in param:\n self.PCGIDL = param['PCGIDL']\n self.PCGIDLgiven = True\n elif 'PCGIDL'.swapcase() in param:\n self.PCGIDL = param['PCGIDL'.swapcase()]\n self.PCGIDLgiven = True\n else:\n if self.PCGIDLgiven == False:\n self.PCGIDL = 0.0\n if 'EGIDL' in param:\n self.EGIDL = param['EGIDL']\n self.EGIDLgiven = True\n elif 'EGIDL'.swapcase() in param:\n self.EGIDL = param['EGIDL'.swapcase()]\n self.EGIDLgiven = True\n else:\n if self.EGIDLgiven == False:\n self.EGIDL = 0.8\n if 'LEGIDL' in param:\n self.LEGIDL = param['LEGIDL']\n self.LEGIDLgiven = True\n elif 'LEGIDL'.swapcase() in param:\n self.LEGIDL = param['LEGIDL'.swapcase()]\n self.LEGIDLgiven = True\n else:\n if self.LEGIDLgiven == False:\n self.LEGIDL = 0.0\n if 'WEGIDL' in param:\n self.WEGIDL = param['WEGIDL']\n self.WEGIDLgiven = True\n elif 'WEGIDL'.swapcase() in param:\n self.WEGIDL = param['WEGIDL'.swapcase()]\n self.WEGIDLgiven = True\n else:\n if self.WEGIDLgiven == False:\n self.WEGIDL = 0.0\n if 'PEGIDL' in param:\n self.PEGIDL = param['PEGIDL']\n self.PEGIDLgiven = True\n elif 'PEGIDL'.swapcase() in param:\n self.PEGIDL = param['PEGIDL'.swapcase()]\n self.PEGIDLgiven = True\n else:\n if self.PEGIDLgiven == False:\n self.PEGIDL = 0.0\n if 'AGISL' in param:\n self.AGISL = param['AGISL']\n self.AGISLgiven = True\n elif 'AGISL'.swapcase() in param:\n self.AGISL = param['AGISL'.swapcase()]\n self.AGISLgiven = True\n else:\n if self.AGISLgiven == False:\n self.AGISL = self.AGIDL\n if 'AGISLL' in param:\n self.AGISLL = param['AGISLL']\n self.AGISLLgiven = True\n elif 'AGISLL'.swapcase() in param:\n self.AGISLL = param['AGISLL'.swapcase()]\n self.AGISLLgiven = True\n else:\n if self.AGISLLgiven == False:\n self.AGISLL = self.AGIDLL\n if 'AGISLW' in param:\n self.AGISLW = param['AGISLW']\n self.AGISLWgiven = True\n elif 'AGISLW'.swapcase() in param:\n self.AGISLW = param['AGISLW'.swapcase()]\n self.AGISLWgiven = True\n else:\n if self.AGISLWgiven == False:\n self.AGISLW = self.AGIDLW\n if 'LAGISL' in param:\n self.LAGISL = param['LAGISL']\n self.LAGISLgiven = True\n elif 'LAGISL'.swapcase() in param:\n self.LAGISL = param['LAGISL'.swapcase()]\n self.LAGISLgiven = True\n else:\n if self.LAGISLgiven == False:\n self.LAGISL = self.LAGIDL\n if 'WAGISL' in param:\n self.WAGISL = param['WAGISL']\n self.WAGISLgiven = True\n elif 'WAGISL'.swapcase() in param:\n self.WAGISL = param['WAGISL'.swapcase()]\n self.WAGISLgiven = True\n else:\n if self.WAGISLgiven == False:\n self.WAGISL = self.WAGIDL\n if 'PAGISL' in param:\n self.PAGISL = param['PAGISL']\n self.PAGISLgiven = True\n elif 'PAGISL'.swapcase() in param:\n self.PAGISL = param['PAGISL'.swapcase()]\n self.PAGISLgiven = True\n else:\n if self.PAGISLgiven == False:\n self.PAGISL = self.PAGIDL\n if 'BGISL' in param:\n self.BGISL = param['BGISL']\n self.BGISLgiven = True\n elif 'BGISL'.swapcase() in param:\n self.BGISL = param['BGISL'.swapcase()]\n self.BGISLgiven = True\n else:\n if self.BGISLgiven == False:\n self.BGISL = self.BGIDL\n if 'LBGISL' in param:\n self.LBGISL = param['LBGISL']\n self.LBGISLgiven = True\n elif 'LBGISL'.swapcase() in param:\n self.LBGISL = param['LBGISL'.swapcase()]\n self.LBGISLgiven = True\n else:\n if self.LBGISLgiven == False:\n self.LBGISL = self.LBGIDL\n if 'WBGISL' in param:\n self.WBGISL = param['WBGISL']\n self.WBGISLgiven = True\n elif 'WBGISL'.swapcase() in param:\n self.WBGISL = param['WBGISL'.swapcase()]\n self.WBGISLgiven = True\n else:\n if self.WBGISLgiven == False:\n self.WBGISL = self.WBGIDL\n if 'PBGISL' in param:\n self.PBGISL = param['PBGISL']\n self.PBGISLgiven = True\n elif 'PBGISL'.swapcase() in param:\n self.PBGISL = param['PBGISL'.swapcase()]\n self.PBGISLgiven = True\n else:\n if self.PBGISLgiven == False:\n self.PBGISL = self.PBGIDL\n if 'CGISL' in param:\n self.CGISL = param['CGISL']\n self.CGISLgiven = True\n elif 'CGISL'.swapcase() in param:\n self.CGISL = param['CGISL'.swapcase()]\n self.CGISLgiven = True\n else:\n if self.CGISLgiven == False:\n self.CGISL = self.CGIDL\n if 'LCGISL' in param:\n self.LCGISL = param['LCGISL']\n self.LCGISLgiven = True\n elif 'LCGISL'.swapcase() in param:\n self.LCGISL = param['LCGISL'.swapcase()]\n self.LCGISLgiven = True\n else:\n if self.LCGISLgiven == False:\n self.LCGISL = self.LCGIDL\n if 'WCGISL' in param:\n self.WCGISL = param['WCGISL']\n self.WCGISLgiven = True\n elif 'WCGISL'.swapcase() in param:\n self.WCGISL = param['WCGISL'.swapcase()]\n self.WCGISLgiven = True\n else:\n if self.WCGISLgiven == False:\n self.WCGISL = self.WCGIDL\n if 'PCGISL' in param:\n self.PCGISL = param['PCGISL']\n self.PCGISLgiven = True\n elif 'PCGISL'.swapcase() in param:\n self.PCGISL = param['PCGISL'.swapcase()]\n self.PCGISLgiven = True\n else:\n if self.PCGISLgiven == False:\n self.PCGISL = self.PCGIDL\n if 'EGISL' in param:\n self.EGISL = param['EGISL']\n self.EGISLgiven = True\n elif 'EGISL'.swapcase() in param:\n self.EGISL = param['EGISL'.swapcase()]\n self.EGISLgiven = True\n else:\n if self.EGISLgiven == False:\n self.EGISL = self.EGIDL\n if 'LEGISL' in param:\n self.LEGISL = param['LEGISL']\n self.LEGISLgiven = True\n elif 'LEGISL'.swapcase() in param:\n self.LEGISL = param['LEGISL'.swapcase()]\n self.LEGISLgiven = True\n else:\n if self.LEGISLgiven == False:\n self.LEGISL = self.LEGIDL\n if 'WEGISL' in param:\n self.WEGISL = param['WEGISL']\n self.WEGISLgiven = True\n elif 'WEGISL'.swapcase() in param:\n self.WEGISL = param['WEGISL'.swapcase()]\n self.WEGISLgiven = True\n else:\n if self.WEGISLgiven == False:\n self.WEGISL = self.WEGIDL\n if 'PEGISL' in param:\n self.PEGISL = param['PEGISL']\n self.PEGISLgiven = True\n elif 'PEGISL'.swapcase() in param:\n self.PEGISL = param['PEGISL'.swapcase()]\n self.PEGISLgiven = True\n else:\n if self.PEGISLgiven == False:\n self.PEGISL = self.PEGIDL\n if 'CF' in param:\n self.CF = param['CF']\n self.CFgiven = True\n elif 'CF'.swapcase() in param:\n self.CF = param['CF'.swapcase()]\n self.CFgiven = True\n else:\n if self.CFgiven == False:\n self.CF = 0.0\n if 'LCF' in param:\n self.LCF = param['LCF']\n self.LCFgiven = True\n elif 'LCF'.swapcase() in param:\n self.LCF = param['LCF'.swapcase()]\n self.LCFgiven = True\n else:\n if self.LCFgiven == False:\n self.LCF = 0.0\n if 'WCF' in param:\n self.WCF = param['WCF']\n self.WCFgiven = True\n elif 'WCF'.swapcase() in param:\n self.WCF = param['WCF'.swapcase()]\n self.WCFgiven = True\n else:\n if self.WCFgiven == False:\n self.WCF = 0.0\n if 'PCF' in param:\n self.PCF = param['PCF']\n self.PCFgiven = True\n elif 'PCF'.swapcase() in param:\n self.PCF = param['PCF'.swapcase()]\n self.PCFgiven = True\n else:\n if self.PCFgiven == False:\n self.PCF = 0.0\n if 'CFRCOEFF' in param:\n self.CFRCOEFF = param['CFRCOEFF']\n self.CFRCOEFFgiven = True\n elif 'CFRCOEFF'.swapcase() in param:\n self.CFRCOEFF = param['CFRCOEFF'.swapcase()]\n self.CFRCOEFFgiven = True\n else:\n if self.CFRCOEFFgiven == False:\n self.CFRCOEFF = 1.0\n if 'CGSO' in param:\n self.CGSO = param['CGSO']\n self.CGSOgiven = True\n elif 'CGSO'.swapcase() in param:\n self.CGSO = param['CGSO'.swapcase()]\n self.CGSOgiven = True\n else:\n if self.CGSOgiven == False:\n self.CGSO = 0.0\n if 'CGDO' in param:\n self.CGDO = param['CGDO']\n self.CGDOgiven = True\n elif 'CGDO'.swapcase() in param:\n self.CGDO = param['CGDO'.swapcase()]\n self.CGDOgiven = True\n else:\n if self.CGDOgiven == False:\n self.CGDO = 0.0\n if 'CGBO' in param:\n self.CGBO = param['CGBO']\n self.CGBOgiven = True\n elif 'CGBO'.swapcase() in param:\n self.CGBO = param['CGBO'.swapcase()]\n self.CGBOgiven = True\n else:\n if self.CGBOgiven == False:\n self.CGBO = 0.0\n if 'CGSL' in param:\n self.CGSL = param['CGSL']\n self.CGSLgiven = True\n elif 'CGSL'.swapcase() in param:\n self.CGSL = param['CGSL'.swapcase()]\n self.CGSLgiven = True\n else:\n if self.CGSLgiven == False:\n self.CGSL = 0.0\n if 'LCGSL' in param:\n self.LCGSL = param['LCGSL']\n self.LCGSLgiven = True\n elif 'LCGSL'.swapcase() in param:\n self.LCGSL = param['LCGSL'.swapcase()]\n self.LCGSLgiven = True\n else:\n if self.LCGSLgiven == False:\n self.LCGSL = 0.0\n if 'WCGSL' in param:\n self.WCGSL = param['WCGSL']\n self.WCGSLgiven = True\n elif 'WCGSL'.swapcase() in param:\n self.WCGSL = param['WCGSL'.swapcase()]\n self.WCGSLgiven = True\n else:\n if self.WCGSLgiven == False:\n self.WCGSL = 0.0\n if 'PCGSL' in param:\n self.PCGSL = param['PCGSL']\n self.PCGSLgiven = True\n elif 'PCGSL'.swapcase() in param:\n self.PCGSL = param['PCGSL'.swapcase()]\n self.PCGSLgiven = True\n else:\n if self.PCGSLgiven == False:\n self.PCGSL = 0.0\n if 'CGDL' in param:\n self.CGDL = param['CGDL']\n self.CGDLgiven = True\n elif 'CGDL'.swapcase() in param:\n self.CGDL = param['CGDL'.swapcase()]\n self.CGDLgiven = True\n else:\n if self.CGDLgiven == False:\n self.CGDL = 0.0\n if 'LCGDL' in param:\n self.LCGDL = param['LCGDL']\n self.LCGDLgiven = True\n elif 'LCGDL'.swapcase() in param:\n self.LCGDL = param['LCGDL'.swapcase()]\n self.LCGDLgiven = True\n else:\n if self.LCGDLgiven == False:\n self.LCGDL = 0.0\n if 'WCGDL' in param:\n self.WCGDL = param['WCGDL']\n self.WCGDLgiven = True\n elif 'WCGDL'.swapcase() in param:\n self.WCGDL = param['WCGDL'.swapcase()]\n self.WCGDLgiven = True\n else:\n if self.WCGDLgiven == False:\n self.WCGDL = 0.0\n if 'PCGDL' in param:\n self.PCGDL = param['PCGDL']\n self.PCGDLgiven = True\n elif 'PCGDL'.swapcase() in param:\n self.PCGDL = param['PCGDL'.swapcase()]\n self.PCGDLgiven = True\n else:\n if self.PCGDLgiven == False:\n self.PCGDL = 0.0\n if 'CKAPPAS' in param:\n self.CKAPPAS = param['CKAPPAS']\n self.CKAPPASgiven = True\n elif 'CKAPPAS'.swapcase() in param:\n self.CKAPPAS = param['CKAPPAS'.swapcase()]\n self.CKAPPASgiven = True\n else:\n if self.CKAPPASgiven == False:\n self.CKAPPAS = 0.6\n if 'LCKAPPAS' in param:\n self.LCKAPPAS = param['LCKAPPAS']\n self.LCKAPPASgiven = True\n elif 'LCKAPPAS'.swapcase() in param:\n self.LCKAPPAS = param['LCKAPPAS'.swapcase()]\n self.LCKAPPASgiven = True\n else:\n if self.LCKAPPASgiven == False:\n self.LCKAPPAS = 0.0\n if 'WCKAPPAS' in param:\n self.WCKAPPAS = param['WCKAPPAS']\n self.WCKAPPASgiven = True\n elif 'WCKAPPAS'.swapcase() in param:\n self.WCKAPPAS = param['WCKAPPAS'.swapcase()]\n self.WCKAPPASgiven = True\n else:\n if self.WCKAPPASgiven == False:\n self.WCKAPPAS = 0.0\n if 'PCKAPPAS' in param:\n self.PCKAPPAS = param['PCKAPPAS']\n self.PCKAPPASgiven = True\n elif 'PCKAPPAS'.swapcase() in param:\n self.PCKAPPAS = param['PCKAPPAS'.swapcase()]\n self.PCKAPPASgiven = True\n else:\n if self.PCKAPPASgiven == False:\n self.PCKAPPAS = 0.0\n if 'CKAPPAD' in param:\n self.CKAPPAD = param['CKAPPAD']\n self.CKAPPADgiven = True\n elif 'CKAPPAD'.swapcase() in param:\n self.CKAPPAD = param['CKAPPAD'.swapcase()]\n self.CKAPPADgiven = True\n else:\n if self.CKAPPADgiven == False:\n self.CKAPPAD = 0.6\n if 'LCKAPPAD' in param:\n self.LCKAPPAD = param['LCKAPPAD']\n self.LCKAPPADgiven = True\n elif 'LCKAPPAD'.swapcase() in param:\n self.LCKAPPAD = param['LCKAPPAD'.swapcase()]\n self.LCKAPPADgiven = True\n else:\n if self.LCKAPPADgiven == False:\n self.LCKAPPAD = 0.0\n if 'WCKAPPAD' in param:\n self.WCKAPPAD = param['WCKAPPAD']\n self.WCKAPPADgiven = True\n elif 'WCKAPPAD'.swapcase() in param:\n self.WCKAPPAD = param['WCKAPPAD'.swapcase()]\n self.WCKAPPADgiven = True\n else:\n if self.WCKAPPADgiven == False:\n self.WCKAPPAD = 0.0\n if 'PCKAPPAD' in param:\n self.PCKAPPAD = param['PCKAPPAD']\n self.PCKAPPADgiven = True\n elif 'PCKAPPAD'.swapcase() in param:\n self.PCKAPPAD = param['PCKAPPAD'.swapcase()]\n self.PCKAPPADgiven = True\n else:\n if self.PCKAPPADgiven == False:\n self.PCKAPPAD = 0.0\n if 'DMCG' in param:\n self.DMCG = param['DMCG']\n self.DMCGgiven = True\n elif 'DMCG'.swapcase() in param:\n self.DMCG = param['DMCG'.swapcase()]\n self.DMCGgiven = True\n else:\n if self.DMCGgiven == False:\n self.DMCG = 0.0\n if 'DMCI' in param:\n self.DMCI = param['DMCI']\n self.DMCIgiven = True\n elif 'DMCI'.swapcase() in param:\n self.DMCI = param['DMCI'.swapcase()]\n self.DMCIgiven = True\n else:\n if self.DMCIgiven == False:\n self.DMCI = self.DMCG\n if 'DMDG' in param:\n self.DMDG = param['DMDG']\n self.DMDGgiven = True\n elif 'DMDG'.swapcase() in param:\n self.DMDG = param['DMDG'.swapcase()]\n self.DMDGgiven = True\n else:\n if self.DMDGgiven == False:\n self.DMDG = 0.0\n if 'DMCGT' in param:\n self.DMCGT = param['DMCGT']\n self.DMCGTgiven = True\n elif 'DMCGT'.swapcase() in param:\n self.DMCGT = param['DMCGT'.swapcase()]\n self.DMCGTgiven = True\n else:\n if self.DMCGTgiven == False:\n self.DMCGT = 0.0\n if 'XGL' in param:\n self.XGL = param['XGL']\n self.XGLgiven = True\n elif 'XGL'.swapcase() in param:\n self.XGL = param['XGL'.swapcase()]\n self.XGLgiven = True\n else:\n if self.XGLgiven == False:\n self.XGL = 0.0\n if 'RSHG' in param:\n self.RSHG = param['RSHG']\n self.RSHGgiven = True\n elif 'RSHG'.swapcase() in param:\n self.RSHG = param['RSHG'.swapcase()]\n self.RSHGgiven = True\n else:\n if self.RSHGgiven == False:\n self.RSHG = 0.1\n if 'CJS' in param:\n self.CJS = param['CJS']\n self.CJSgiven = True\n elif 'CJS'.swapcase() in param:\n self.CJS = param['CJS'.swapcase()]\n self.CJSgiven = True\n else:\n if self.CJSgiven == False:\n self.CJS = 0.0005\n if 'CJD' in param:\n self.CJD = param['CJD']\n self.CJDgiven = True\n elif 'CJD'.swapcase() in param:\n self.CJD = param['CJD'.swapcase()]\n self.CJDgiven = True\n else:\n if self.CJDgiven == False:\n self.CJD = self.CJS\n if 'CJSWS' in param:\n self.CJSWS = param['CJSWS']\n self.CJSWSgiven = True\n elif 'CJSWS'.swapcase() in param:\n self.CJSWS = param['CJSWS'.swapcase()]\n self.CJSWSgiven = True\n else:\n if self.CJSWSgiven == False:\n self.CJSWS = 5e-10\n if 'CJSWD' in param:\n self.CJSWD = param['CJSWD']\n self.CJSWDgiven = True\n elif 'CJSWD'.swapcase() in param:\n self.CJSWD = param['CJSWD'.swapcase()]\n self.CJSWDgiven = True\n else:\n if self.CJSWDgiven == False:\n self.CJSWD = self.CJSWS\n if 'CJSWGS' in param:\n self.CJSWGS = param['CJSWGS']\n self.CJSWGSgiven = True\n elif 'CJSWGS'.swapcase() in param:\n self.CJSWGS = param['CJSWGS'.swapcase()]\n self.CJSWGSgiven = True\n else:\n if self.CJSWGSgiven == False:\n self.CJSWGS = 0.0\n if 'CJSWGD' in param:\n self.CJSWGD = param['CJSWGD']\n self.CJSWGDgiven = True\n elif 'CJSWGD'.swapcase() in param:\n self.CJSWGD = param['CJSWGD'.swapcase()]\n self.CJSWGDgiven = True\n else:\n if self.CJSWGDgiven == False:\n self.CJSWGD = self.CJSWGS\n if 'PBS' in param:\n self.PBS = param['PBS']\n self.PBSgiven = True\n elif 'PBS'.swapcase() in param:\n self.PBS = param['PBS'.swapcase()]\n self.PBSgiven = True\n else:\n if self.PBSgiven == False:\n self.PBS = 1.0\n if 'PBD' in param:\n self.PBD = param['PBD']\n self.PBDgiven = True\n elif 'PBD'.swapcase() in param:\n self.PBD = param['PBD'.swapcase()]\n self.PBDgiven = True\n else:\n if self.PBDgiven == False:\n self.PBD = self.PBS\n if 'PBSWS' in param:\n self.PBSWS = param['PBSWS']\n self.PBSWSgiven = True\n elif 'PBSWS'.swapcase() in param:\n self.PBSWS = param['PBSWS'.swapcase()]\n self.PBSWSgiven = True\n else:\n if self.PBSWSgiven == False:\n self.PBSWS = 1.0\n if 'PBSWD' in param:\n self.PBSWD = param['PBSWD']\n self.PBSWDgiven = True\n elif 'PBSWD'.swapcase() in param:\n self.PBSWD = param['PBSWD'.swapcase()]\n self.PBSWDgiven = True\n else:\n if self.PBSWDgiven == False:\n self.PBSWD = self.PBSWS\n if 'PBSWGS' in param:\n self.PBSWGS = param['PBSWGS']\n self.PBSWGSgiven = True\n elif 'PBSWGS'.swapcase() in param:\n self.PBSWGS = param['PBSWGS'.swapcase()]\n self.PBSWGSgiven = True\n else:\n if self.PBSWGSgiven == False:\n self.PBSWGS = self.PBSWS\n if 'PBSWGD' in param:\n self.PBSWGD = param['PBSWGD']\n self.PBSWGDgiven = True\n elif 'PBSWGD'.swapcase() in param:\n self.PBSWGD = param['PBSWGD'.swapcase()]\n self.PBSWGDgiven = True\n else:\n if self.PBSWGDgiven == False:\n self.PBSWGD = self.PBSWGS\n if 'MJS' in param:\n self.MJS = param['MJS']\n self.MJSgiven = True\n elif 'MJS'.swapcase() in param:\n self.MJS = param['MJS'.swapcase()]\n self.MJSgiven = True\n else:\n if self.MJSgiven == False:\n self.MJS = 0.5\n if 'MJD' in param:\n self.MJD = param['MJD']\n self.MJDgiven = True\n elif 'MJD'.swapcase() in param:\n self.MJD = param['MJD'.swapcase()]\n self.MJDgiven = True\n else:\n if self.MJDgiven == False:\n self.MJD = self.MJS\n if 'MJSWS' in param:\n self.MJSWS = param['MJSWS']\n self.MJSWSgiven = True\n elif 'MJSWS'.swapcase() in param:\n self.MJSWS = param['MJSWS'.swapcase()]\n self.MJSWSgiven = True\n else:\n if self.MJSWSgiven == False:\n self.MJSWS = 0.33\n if 'MJSWD' in param:\n self.MJSWD = param['MJSWD']\n self.MJSWDgiven = True\n elif 'MJSWD'.swapcase() in param:\n self.MJSWD = param['MJSWD'.swapcase()]\n self.MJSWDgiven = True\n else:\n if self.MJSWDgiven == False:\n self.MJSWD = self.MJSWS\n if 'MJSWGS' in param:\n self.MJSWGS = param['MJSWGS']\n self.MJSWGSgiven = True\n elif 'MJSWGS'.swapcase() in param:\n self.MJSWGS = param['MJSWGS'.swapcase()]\n self.MJSWGSgiven = True\n else:\n if self.MJSWGSgiven == False:\n self.MJSWGS = self.MJSWS\n if 'MJSWGD' in param:\n self.MJSWGD = param['MJSWGD']\n self.MJSWGDgiven = True\n elif 'MJSWGD'.swapcase() in param:\n self.MJSWGD = param['MJSWGD'.swapcase()]\n self.MJSWGDgiven = True\n else:\n if self.MJSWGDgiven == False:\n self.MJSWGD = self.MJSWGS\n if 'JSS' in param:\n self.JSS = param['JSS']\n self.JSSgiven = True\n elif 'JSS'.swapcase() in param:\n self.JSS = param['JSS'.swapcase()]\n self.JSSgiven = True\n else:\n if self.JSSgiven == False:\n self.JSS = 0.0001\n if 'JSD' in param:\n self.JSD = param['JSD']\n self.JSDgiven = True\n elif 'JSD'.swapcase() in param:\n self.JSD = param['JSD'.swapcase()]\n self.JSDgiven = True\n else:\n if self.JSDgiven == False:\n self.JSD = self.JSS\n if 'JSWS' in param:\n self.JSWS = param['JSWS']\n self.JSWSgiven = True\n elif 'JSWS'.swapcase() in param:\n self.JSWS = param['JSWS'.swapcase()]\n self.JSWSgiven = True\n else:\n if self.JSWSgiven == False:\n self.JSWS = 0.0\n if 'JSWD' in param:\n self.JSWD = param['JSWD']\n self.JSWDgiven = True\n elif 'JSWD'.swapcase() in param:\n self.JSWD = param['JSWD'.swapcase()]\n self.JSWDgiven = True\n else:\n if self.JSWDgiven == False:\n self.JSWD = self.JSWS\n if 'JSWGS' in param:\n self.JSWGS = param['JSWGS']\n self.JSWGSgiven = True\n elif 'JSWGS'.swapcase() in param:\n self.JSWGS = param['JSWGS'.swapcase()]\n self.JSWGSgiven = True\n else:\n if self.JSWGSgiven == False:\n self.JSWGS = 0.0\n if 'JSWGD' in param:\n self.JSWGD = param['JSWGD']\n self.JSWGDgiven = True\n elif 'JSWGD'.swapcase() in param:\n self.JSWGD = param['JSWGD'.swapcase()]\n self.JSWGDgiven = True\n else:\n if self.JSWGDgiven == False:\n self.JSWGD = self.JSWGS\n if 'NJS' in param:\n self.NJS = param['NJS']\n self.NJSgiven = True\n elif 'NJS'.swapcase() in param:\n self.NJS = param['NJS'.swapcase()]\n self.NJSgiven = True\n else:\n if self.NJSgiven == False:\n self.NJS = 1.0\n if 'NJD' in param:\n self.NJD = param['NJD']\n self.NJDgiven = True\n elif 'NJD'.swapcase() in param:\n self.NJD = param['NJD'.swapcase()]\n self.NJDgiven = True\n else:\n if self.NJDgiven == False:\n self.NJD = self.NJS\n if 'IJTHSFWD' in param:\n self.IJTHSFWD = param['IJTHSFWD']\n self.IJTHSFWDgiven = True\n elif 'IJTHSFWD'.swapcase() in param:\n self.IJTHSFWD = param['IJTHSFWD'.swapcase()]\n self.IJTHSFWDgiven = True\n else:\n if self.IJTHSFWDgiven == False:\n self.IJTHSFWD = 0.1\n if 'IJTHDFWD' in param:\n self.IJTHDFWD = param['IJTHDFWD']\n self.IJTHDFWDgiven = True\n elif 'IJTHDFWD'.swapcase() in param:\n self.IJTHDFWD = param['IJTHDFWD'.swapcase()]\n self.IJTHDFWDgiven = True\n else:\n if self.IJTHDFWDgiven == False:\n self.IJTHDFWD = self.IJTHSFWD\n if 'IJTHSREV' in param:\n self.IJTHSREV = param['IJTHSREV']\n self.IJTHSREVgiven = True\n elif 'IJTHSREV'.swapcase() in param:\n self.IJTHSREV = param['IJTHSREV'.swapcase()]\n self.IJTHSREVgiven = True\n else:\n if self.IJTHSREVgiven == False:\n self.IJTHSREV = 0.1\n if 'IJTHDREV' in param:\n self.IJTHDREV = param['IJTHDREV']\n self.IJTHDREVgiven = True\n elif 'IJTHDREV'.swapcase() in param:\n self.IJTHDREV = param['IJTHDREV'.swapcase()]\n self.IJTHDREVgiven = True\n else:\n if self.IJTHDREVgiven == False:\n self.IJTHDREV = self.IJTHSREV\n if 'BVS' in param:\n self.BVS = param['BVS']\n self.BVSgiven = True\n elif 'BVS'.swapcase() in param:\n self.BVS = param['BVS'.swapcase()]\n self.BVSgiven = True\n else:\n if self.BVSgiven == False:\n self.BVS = 10.0\n if 'BVD' in param:\n self.BVD = param['BVD']\n self.BVDgiven = True\n elif 'BVD'.swapcase() in param:\n self.BVD = param['BVD'.swapcase()]\n self.BVDgiven = True\n else:\n if self.BVDgiven == False:\n self.BVD = self.BVS\n if 'XJBVS' in param:\n self.XJBVS = param['XJBVS']\n self.XJBVSgiven = True\n elif 'XJBVS'.swapcase() in param:\n self.XJBVS = param['XJBVS'.swapcase()]\n self.XJBVSgiven = True\n else:\n if self.XJBVSgiven == False:\n self.XJBVS = 1.0\n if 'XJBVD' in param:\n self.XJBVD = param['XJBVD']\n self.XJBVDgiven = True\n elif 'XJBVD'.swapcase() in param:\n self.XJBVD = param['XJBVD'.swapcase()]\n self.XJBVDgiven = True\n else:\n if self.XJBVDgiven == False:\n self.XJBVD = self.XJBVS\n if 'JTSS' in param:\n self.JTSS = param['JTSS']\n self.JTSSgiven = True\n elif 'JTSS'.swapcase() in param:\n self.JTSS = param['JTSS'.swapcase()]\n self.JTSSgiven = True\n else:\n if self.JTSSgiven == False:\n self.JTSS = 0.0\n if 'JTSD' in param:\n self.JTSD = param['JTSD']\n self.JTSDgiven = True\n elif 'JTSD'.swapcase() in param:\n self.JTSD = param['JTSD'.swapcase()]\n self.JTSDgiven = True\n else:\n if self.JTSDgiven == False:\n self.JTSD = self.JTSS\n if 'JTSSWS' in param:\n self.JTSSWS = param['JTSSWS']\n self.JTSSWSgiven = True\n elif 'JTSSWS'.swapcase() in param:\n self.JTSSWS = param['JTSSWS'.swapcase()]\n self.JTSSWSgiven = True\n else:\n if self.JTSSWSgiven == False:\n self.JTSSWS = 0.0\n if 'JTSSWD' in param:\n self.JTSSWD = param['JTSSWD']\n self.JTSSWDgiven = True\n elif 'JTSSWD'.swapcase() in param:\n self.JTSSWD = param['JTSSWD'.swapcase()]\n self.JTSSWDgiven = True\n else:\n if self.JTSSWDgiven == False:\n self.JTSSWD = self.JTSSWS\n if 'JTSSWGS' in param:\n self.JTSSWGS = param['JTSSWGS']\n self.JTSSWGSgiven = True\n elif 'JTSSWGS'.swapcase() in param:\n self.JTSSWGS = param['JTSSWGS'.swapcase()]\n self.JTSSWGSgiven = True\n else:\n if self.JTSSWGSgiven == False:\n self.JTSSWGS = 0.0\n if 'JTSSWGD' in param:\n self.JTSSWGD = param['JTSSWGD']\n self.JTSSWGDgiven = True\n elif 'JTSSWGD'.swapcase() in param:\n self.JTSSWGD = param['JTSSWGD'.swapcase()]\n self.JTSSWGDgiven = True\n else:\n if self.JTSSWGDgiven == False:\n self.JTSSWGD = self.JTSSWGS\n if 'JTWEFF' in param:\n self.JTWEFF = param['JTWEFF']\n self.JTWEFFgiven = True\n elif 'JTWEFF'.swapcase() in param:\n self.JTWEFF = param['JTWEFF'.swapcase()]\n self.JTWEFFgiven = True\n else:\n if self.JTWEFFgiven == False:\n self.JTWEFF = 0.0\n if 'NJTS' in param:\n self.NJTS = param['NJTS']\n self.NJTSgiven = True\n elif 'NJTS'.swapcase() in param:\n self.NJTS = param['NJTS'.swapcase()]\n self.NJTSgiven = True\n else:\n if self.NJTSgiven == False:\n self.NJTS = 20.0\n if 'NJTSD' in param:\n self.NJTSD = param['NJTSD']\n self.NJTSDgiven = True\n elif 'NJTSD'.swapcase() in param:\n self.NJTSD = param['NJTSD'.swapcase()]\n self.NJTSDgiven = True\n else:\n if self.NJTSDgiven == False:\n self.NJTSD = self.NJTS\n if 'NJTSSW' in param:\n self.NJTSSW = param['NJTSSW']\n self.NJTSSWgiven = True\n elif 'NJTSSW'.swapcase() in param:\n self.NJTSSW = param['NJTSSW'.swapcase()]\n self.NJTSSWgiven = True\n else:\n if self.NJTSSWgiven == False:\n self.NJTSSW = 20.0\n if 'NJTSSWD' in param:\n self.NJTSSWD = param['NJTSSWD']\n self.NJTSSWDgiven = True\n elif 'NJTSSWD'.swapcase() in param:\n self.NJTSSWD = param['NJTSSWD'.swapcase()]\n self.NJTSSWDgiven = True\n else:\n if self.NJTSSWDgiven == False:\n self.NJTSSWD = self.NJTSSW\n if 'NJTSSWG' in param:\n self.NJTSSWG = param['NJTSSWG']\n self.NJTSSWGgiven = True\n elif 'NJTSSWG'.swapcase() in param:\n self.NJTSSWG = param['NJTSSWG'.swapcase()]\n self.NJTSSWGgiven = True\n else:\n if self.NJTSSWGgiven == False:\n self.NJTSSWG = 20.0\n if 'NJTSSWGD' in param:\n self.NJTSSWGD = param['NJTSSWGD']\n self.NJTSSWGDgiven = True\n elif 'NJTSSWGD'.swapcase() in param:\n self.NJTSSWGD = param['NJTSSWGD'.swapcase()]\n self.NJTSSWGDgiven = True\n else:\n if self.NJTSSWGDgiven == False:\n self.NJTSSWGD = self.NJTSSWG\n if 'VTSS' in param:\n self.VTSS = param['VTSS']\n self.VTSSgiven = True\n elif 'VTSS'.swapcase() in param:\n self.VTSS = param['VTSS'.swapcase()]\n self.VTSSgiven = True\n else:\n if self.VTSSgiven == False:\n self.VTSS = 10.0\n if 'VTSD' in param:\n self.VTSD = param['VTSD']\n self.VTSDgiven = True\n elif 'VTSD'.swapcase() in param:\n self.VTSD = param['VTSD'.swapcase()]\n self.VTSDgiven = True\n else:\n if self.VTSDgiven == False:\n self.VTSD = self.VTSS\n if 'VTSSWS' in param:\n self.VTSSWS = param['VTSSWS']\n self.VTSSWSgiven = True\n elif 'VTSSWS'.swapcase() in param:\n self.VTSSWS = param['VTSSWS'.swapcase()]\n self.VTSSWSgiven = True\n else:\n if self.VTSSWSgiven == False:\n self.VTSSWS = 10.0\n if 'VTSSWD' in param:\n self.VTSSWD = param['VTSSWD']\n self.VTSSWDgiven = True\n elif 'VTSSWD'.swapcase() in param:\n self.VTSSWD = param['VTSSWD'.swapcase()]\n self.VTSSWDgiven = True\n else:\n if self.VTSSWDgiven == False:\n self.VTSSWD = self.VTSSWS\n if 'VTSSWGS' in param:\n self.VTSSWGS = param['VTSSWGS']\n self.VTSSWGSgiven = True\n elif 'VTSSWGS'.swapcase() in param:\n self.VTSSWGS = param['VTSSWGS'.swapcase()]\n self.VTSSWGSgiven = True\n else:\n if self.VTSSWGSgiven == False:\n self.VTSSWGS = 10.0\n if 'VTSSWGD' in param:\n self.VTSSWGD = param['VTSSWGD']\n self.VTSSWGDgiven = True\n elif 'VTSSWGD'.swapcase() in param:\n self.VTSSWGD = param['VTSSWGD'.swapcase()]\n self.VTSSWGDgiven = True\n else:\n if self.VTSSWGDgiven == False:\n self.VTSSWGD = self.VTSSWGS\n if 'XRCRG1' in param:\n self.XRCRG1 = param['XRCRG1']\n self.XRCRG1given = True\n elif 'XRCRG1'.swapcase() in param:\n self.XRCRG1 = param['XRCRG1'.swapcase()]\n self.XRCRG1given = True\n else:\n if self.XRCRG1given == False:\n self.XRCRG1 = 12.0\n if 'XRCRG2' in param:\n self.XRCRG2 = param['XRCRG2']\n self.XRCRG2given = True\n elif 'XRCRG2'.swapcase() in param:\n self.XRCRG2 = param['XRCRG2'.swapcase()]\n self.XRCRG2given = True\n else:\n if self.XRCRG2given == False:\n self.XRCRG2 = 1.0\n if 'GBMIN' in param:\n self.GBMIN = param['GBMIN']\n self.GBMINgiven = True\n elif 'GBMIN'.swapcase() in param:\n self.GBMIN = param['GBMIN'.swapcase()]\n self.GBMINgiven = True\n else:\n if self.GBMINgiven == False:\n self.GBMIN = 1e-12\n if 'RBPS0' in param:\n self.RBPS0 = param['RBPS0']\n self.RBPS0given = True\n elif 'RBPS0'.swapcase() in param:\n self.RBPS0 = param['RBPS0'.swapcase()]\n self.RBPS0given = True\n else:\n if self.RBPS0given == False:\n self.RBPS0 = 50.0\n if 'RBPSL' in param:\n self.RBPSL = param['RBPSL']\n self.RBPSLgiven = True\n elif 'RBPSL'.swapcase() in param:\n self.RBPSL = param['RBPSL'.swapcase()]\n self.RBPSLgiven = True\n else:\n if self.RBPSLgiven == False:\n self.RBPSL = 0.0\n if 'RBPSW' in param:\n self.RBPSW = param['RBPSW']\n self.RBPSWgiven = True\n elif 'RBPSW'.swapcase() in param:\n self.RBPSW = param['RBPSW'.swapcase()]\n self.RBPSWgiven = True\n else:\n if self.RBPSWgiven == False:\n self.RBPSW = 0.0\n if 'RBPSNF' in param:\n self.RBPSNF = param['RBPSNF']\n self.RBPSNFgiven = True\n elif 'RBPSNF'.swapcase() in param:\n self.RBPSNF = param['RBPSNF'.swapcase()]\n self.RBPSNFgiven = True\n else:\n if self.RBPSNFgiven == False:\n self.RBPSNF = 0.0\n if 'RBPD0' in param:\n self.RBPD0 = param['RBPD0']\n self.RBPD0given = True\n elif 'RBPD0'.swapcase() in param:\n self.RBPD0 = param['RBPD0'.swapcase()]\n self.RBPD0given = True\n else:\n if self.RBPD0given == False:\n self.RBPD0 = 50.0\n if 'RBPDL' in param:\n self.RBPDL = param['RBPDL']\n self.RBPDLgiven = True\n elif 'RBPDL'.swapcase() in param:\n self.RBPDL = param['RBPDL'.swapcase()]\n self.RBPDLgiven = True\n else:\n if self.RBPDLgiven == False:\n self.RBPDL = 0.0\n if 'RBPDW' in param:\n self.RBPDW = param['RBPDW']\n self.RBPDWgiven = True\n elif 'RBPDW'.swapcase() in param:\n self.RBPDW = param['RBPDW'.swapcase()]\n self.RBPDWgiven = True\n else:\n if self.RBPDWgiven == False:\n self.RBPDW = 0.0\n if 'RBPDNF' in param:\n self.RBPDNF = param['RBPDNF']\n self.RBPDNFgiven = True\n elif 'RBPDNF'.swapcase() in param:\n self.RBPDNF = param['RBPDNF'.swapcase()]\n self.RBPDNFgiven = True\n else:\n if self.RBPDNFgiven == False:\n self.RBPDNF = 0.0\n if 'RBPBX0' in param:\n self.RBPBX0 = param['RBPBX0']\n self.RBPBX0given = True\n elif 'RBPBX0'.swapcase() in param:\n self.RBPBX0 = param['RBPBX0'.swapcase()]\n self.RBPBX0given = True\n else:\n if self.RBPBX0given == False:\n self.RBPBX0 = 100.0\n if 'RBPBXL' in param:\n self.RBPBXL = param['RBPBXL']\n self.RBPBXLgiven = True\n elif 'RBPBXL'.swapcase() in param:\n self.RBPBXL = param['RBPBXL'.swapcase()]\n self.RBPBXLgiven = True\n else:\n if self.RBPBXLgiven == False:\n self.RBPBXL = 0.0\n if 'RBPBXW' in param:\n self.RBPBXW = param['RBPBXW']\n self.RBPBXWgiven = True\n elif 'RBPBXW'.swapcase() in param:\n self.RBPBXW = param['RBPBXW'.swapcase()]\n self.RBPBXWgiven = True\n else:\n if self.RBPBXWgiven == False:\n self.RBPBXW = 0.0\n if 'RBPBXNF' in param:\n self.RBPBXNF = param['RBPBXNF']\n self.RBPBXNFgiven = True\n elif 'RBPBXNF'.swapcase() in param:\n self.RBPBXNF = param['RBPBXNF'.swapcase()]\n self.RBPBXNFgiven = True\n else:\n if self.RBPBXNFgiven == False:\n self.RBPBXNF = 0.0\n if 'RBPBY0' in param:\n self.RBPBY0 = param['RBPBY0']\n self.RBPBY0given = True\n elif 'RBPBY0'.swapcase() in param:\n self.RBPBY0 = param['RBPBY0'.swapcase()]\n self.RBPBY0given = True\n else:\n if self.RBPBY0given == False:\n self.RBPBY0 = 100.0\n if 'RBPBYL' in param:\n self.RBPBYL = param['RBPBYL']\n self.RBPBYLgiven = True\n elif 'RBPBYL'.swapcase() in param:\n self.RBPBYL = param['RBPBYL'.swapcase()]\n self.RBPBYLgiven = True\n else:\n if self.RBPBYLgiven == False:\n self.RBPBYL = 0.0\n if 'RBPBYW' in param:\n self.RBPBYW = param['RBPBYW']\n self.RBPBYWgiven = True\n elif 'RBPBYW'.swapcase() in param:\n self.RBPBYW = param['RBPBYW'.swapcase()]\n self.RBPBYWgiven = True\n else:\n if self.RBPBYWgiven == False:\n self.RBPBYW = 0.0\n if 'RBPBYNF' in param:\n self.RBPBYNF = param['RBPBYNF']\n self.RBPBYNFgiven = True\n elif 'RBPBYNF'.swapcase() in param:\n self.RBPBYNF = param['RBPBYNF'.swapcase()]\n self.RBPBYNFgiven = True\n else:\n if self.RBPBYNFgiven == False:\n self.RBPBYNF = 0.0\n if 'RBSBX0' in param:\n self.RBSBX0 = param['RBSBX0']\n self.RBSBX0given = True\n elif 'RBSBX0'.swapcase() in param:\n self.RBSBX0 = param['RBSBX0'.swapcase()]\n self.RBSBX0given = True\n else:\n if self.RBSBX0given == False:\n self.RBSBX0 = 100.0\n if 'RBSBY0' in param:\n self.RBSBY0 = param['RBSBY0']\n self.RBSBY0given = True\n elif 'RBSBY0'.swapcase() in param:\n self.RBSBY0 = param['RBSBY0'.swapcase()]\n self.RBSBY0given = True\n else:\n if self.RBSBY0given == False:\n self.RBSBY0 = 100.0\n if 'RBDBX0' in param:\n self.RBDBX0 = param['RBDBX0']\n self.RBDBX0given = True\n elif 'RBDBX0'.swapcase() in param:\n self.RBDBX0 = param['RBDBX0'.swapcase()]\n self.RBDBX0given = True\n else:\n if self.RBDBX0given == False:\n self.RBDBX0 = 100.0\n if 'RBDBY0' in param:\n self.RBDBY0 = param['RBDBY0']\n self.RBDBY0given = True\n elif 'RBDBY0'.swapcase() in param:\n self.RBDBY0 = param['RBDBY0'.swapcase()]\n self.RBDBY0given = True\n else:\n if self.RBDBY0given == False:\n self.RBDBY0 = 100.0\n if 'RBSDBXL' in param:\n self.RBSDBXL = param['RBSDBXL']\n self.RBSDBXLgiven = True\n elif 'RBSDBXL'.swapcase() in param:\n self.RBSDBXL = param['RBSDBXL'.swapcase()]\n self.RBSDBXLgiven = True\n else:\n if self.RBSDBXLgiven == False:\n self.RBSDBXL = 0.0\n if 'RBSDBXW' in param:\n self.RBSDBXW = param['RBSDBXW']\n self.RBSDBXWgiven = True\n elif 'RBSDBXW'.swapcase() in param:\n self.RBSDBXW = param['RBSDBXW'.swapcase()]\n self.RBSDBXWgiven = True\n else:\n if self.RBSDBXWgiven == False:\n self.RBSDBXW = 0.0\n if 'RBSDBXNF' in param:\n self.RBSDBXNF = param['RBSDBXNF']\n self.RBSDBXNFgiven = True\n elif 'RBSDBXNF'.swapcase() in param:\n self.RBSDBXNF = param['RBSDBXNF'.swapcase()]\n self.RBSDBXNFgiven = True\n else:\n if self.RBSDBXNFgiven == False:\n self.RBSDBXNF = 0.0\n if 'RBSDBYL' in param:\n self.RBSDBYL = param['RBSDBYL']\n self.RBSDBYLgiven = True\n elif 'RBSDBYL'.swapcase() in param:\n self.RBSDBYL = param['RBSDBYL'.swapcase()]\n self.RBSDBYLgiven = True\n else:\n if self.RBSDBYLgiven == False:\n self.RBSDBYL = 0.0\n if 'RBSDBYW' in param:\n self.RBSDBYW = param['RBSDBYW']\n self.RBSDBYWgiven = True\n elif 'RBSDBYW'.swapcase() in param:\n self.RBSDBYW = param['RBSDBYW'.swapcase()]\n self.RBSDBYWgiven = True\n else:\n if self.RBSDBYWgiven == False:\n self.RBSDBYW = 0.0\n if 'RBSDBYNF' in param:\n self.RBSDBYNF = param['RBSDBYNF']\n self.RBSDBYNFgiven = True\n elif 'RBSDBYNF'.swapcase() in param:\n self.RBSDBYNF = param['RBSDBYNF'.swapcase()]\n self.RBSDBYNFgiven = True\n else:\n if self.RBSDBYNFgiven == False:\n self.RBSDBYNF = 0.0\n if 'EF' in param:\n self.EF = param['EF']\n self.EFgiven = True\n elif 'EF'.swapcase() in param:\n self.EF = param['EF'.swapcase()]\n self.EFgiven = True\n else:\n if self.EFgiven == False:\n self.EF = 1.0\n if 'EM' in param:\n self.EM = param['EM']\n self.EMgiven = True\n elif 'EM'.swapcase() in param:\n self.EM = param['EM'.swapcase()]\n self.EMgiven = True\n else:\n if self.EMgiven == False:\n self.EM = 41000000.0\n if 'NOIA' in param:\n self.NOIA = param['NOIA']\n self.NOIAgiven = True\n elif 'NOIA'.swapcase() in param:\n self.NOIA = param['NOIA'.swapcase()]\n self.NOIAgiven = True\n else:\n if self.NOIAgiven == False:\n self.NOIA = 6.25e+40\n if 'NOIB' in param:\n self.NOIB = param['NOIB']\n self.NOIBgiven = True\n elif 'NOIB'.swapcase() in param:\n self.NOIB = param['NOIB'.swapcase()]\n self.NOIBgiven = True\n else:\n if self.NOIBgiven == False:\n self.NOIB = 3.125e+25\n if 'NOIC' in param:\n self.NOIC = param['NOIC']\n self.NOICgiven = True\n elif 'NOIC'.swapcase() in param:\n self.NOIC = param['NOIC'.swapcase()]\n self.NOICgiven = True\n else:\n if self.NOICgiven == False:\n self.NOIC = 875000000.0\n if 'LINTNOI' in param:\n self.LINTNOI = param['LINTNOI']\n self.LINTNOIgiven = True\n elif 'LINTNOI'.swapcase() in param:\n self.LINTNOI = param['LINTNOI'.swapcase()]\n self.LINTNOIgiven = True\n else:\n if self.LINTNOIgiven == False:\n self.LINTNOI = 0.0\n if 'NOIA1' in param:\n self.NOIA1 = param['NOIA1']\n self.NOIA1given = True\n elif 'NOIA1'.swapcase() in param:\n self.NOIA1 = param['NOIA1'.swapcase()]\n self.NOIA1given = True\n else:\n if self.NOIA1given == False:\n self.NOIA1 = 0.0\n if 'NOIAX' in param:\n self.NOIAX = param['NOIAX']\n self.NOIAXgiven = True\n elif 'NOIAX'.swapcase() in param:\n self.NOIAX = param['NOIAX'.swapcase()]\n self.NOIAXgiven = True\n else:\n if self.NOIAXgiven == False:\n self.NOIAX = 1.0\n if 'NTNOI' in param:\n self.NTNOI = param['NTNOI']\n self.NTNOIgiven = True\n elif 'NTNOI'.swapcase() in param:\n self.NTNOI = param['NTNOI'.swapcase()]\n self.NTNOIgiven = True\n else:\n if self.NTNOIgiven == False:\n self.NTNOI = 1.0\n if 'RNOIA' in param:\n self.RNOIA = param['RNOIA']\n self.RNOIAgiven = True\n elif 'RNOIA'.swapcase() in param:\n self.RNOIA = param['RNOIA'.swapcase()]\n self.RNOIAgiven = True\n else:\n if self.RNOIAgiven == False:\n self.RNOIA = 0.577\n if 'RNOIB' in param:\n self.RNOIB = param['RNOIB']\n self.RNOIBgiven = True\n elif 'RNOIB'.swapcase() in param:\n self.RNOIB = param['RNOIB'.swapcase()]\n self.RNOIBgiven = True\n else:\n if self.RNOIBgiven == False:\n self.RNOIB = 0.5164\n if 'RNOIC' in param:\n self.RNOIC = param['RNOIC']\n self.RNOICgiven = True\n elif 'RNOIC'.swapcase() in param:\n self.RNOIC = param['RNOIC'.swapcase()]\n self.RNOICgiven = True\n else:\n if self.RNOICgiven == False:\n self.RNOIC = 0.395\n if 'TNOIA' in param:\n self.TNOIA = param['TNOIA']\n self.TNOIAgiven = True\n elif 'TNOIA'.swapcase() in param:\n self.TNOIA = param['TNOIA'.swapcase()]\n self.TNOIAgiven = True\n else:\n if self.TNOIAgiven == False:\n self.TNOIA = 1.5\n if 'TNOIB' in param:\n self.TNOIB = param['TNOIB']\n self.TNOIBgiven = True\n elif 'TNOIB'.swapcase() in param:\n self.TNOIB = param['TNOIB'.swapcase()]\n self.TNOIBgiven = True\n else:\n if self.TNOIBgiven == False:\n self.TNOIB = 3.5\n if 'TNOIC' in param:\n self.TNOIC = param['TNOIC']\n self.TNOICgiven = True\n elif 'TNOIC'.swapcase() in param:\n self.TNOIC = param['TNOIC'.swapcase()]\n self.TNOICgiven = True\n else:\n if self.TNOICgiven == False:\n self.TNOIC = 0.0\n if 'BINUNIT' in param:\n self.BINUNIT = param['BINUNIT']\n self.BINUNITgiven = True\n elif 'BINUNIT'.swapcase() in param:\n self.BINUNIT = param['BINUNIT'.swapcase()]\n self.BINUNITgiven = True\n else:\n if self.BINUNITgiven == False:\n self.BINUNIT = 1.0\n if 'DLBIN' in param:\n self.DLBIN = param['DLBIN']\n self.DLBINgiven = True\n elif 'DLBIN'.swapcase() in param:\n self.DLBIN = param['DLBIN'.swapcase()]\n self.DLBINgiven = True\n else:\n if self.DLBINgiven == False:\n self.DLBIN = 0.0\n if 'DWBIN' in param:\n self.DWBIN = param['DWBIN']\n self.DWBINgiven = True\n elif 'DWBIN'.swapcase() in param:\n self.DWBIN = param['DWBIN'.swapcase()]\n self.DWBINgiven = True\n else:\n if self.DWBINgiven == False:\n self.DWBIN = 0.0\n if 'TNOM' in param:\n self.TNOM = param['TNOM']\n self.TNOMgiven = True\n elif 'TNOM'.swapcase() in param:\n self.TNOM = param['TNOM'.swapcase()]\n self.TNOMgiven = True\n else:\n if self.TNOMgiven == False:\n self.TNOM = 27.0\n if 'TBGASUB' in param:\n self.TBGASUB = param['TBGASUB']\n self.TBGASUBgiven = True\n elif 'TBGASUB'.swapcase() in param:\n self.TBGASUB = param['TBGASUB'.swapcase()]\n self.TBGASUBgiven = True\n else:\n if self.TBGASUBgiven == False:\n self.TBGASUB = 0.000473\n if 'TBGBSUB' in param:\n self.TBGBSUB = param['TBGBSUB']\n self.TBGBSUBgiven = True\n elif 'TBGBSUB'.swapcase() in param:\n self.TBGBSUB = param['TBGBSUB'.swapcase()]\n self.TBGBSUBgiven = True\n else:\n if self.TBGBSUBgiven == False:\n self.TBGBSUB = 636.0\n if 'TNFACTOR' in param:\n self.TNFACTOR = param['TNFACTOR']\n self.TNFACTORgiven = True\n elif 'TNFACTOR'.swapcase() in param:\n self.TNFACTOR = param['TNFACTOR'.swapcase()]\n self.TNFACTORgiven = True\n else:\n if self.TNFACTORgiven == False:\n self.TNFACTOR = 0.0\n if 'UTE' in param:\n self.UTE = param['UTE']\n self.UTEgiven = True\n elif 'UTE'.swapcase() in param:\n self.UTE = param['UTE'.swapcase()]\n self.UTEgiven = True\n else:\n if self.UTEgiven == False:\n self.UTE = -1.5\n if 'LUTE' in param:\n self.LUTE = param['LUTE']\n self.LUTEgiven = True\n elif 'LUTE'.swapcase() in param:\n self.LUTE = param['LUTE'.swapcase()]\n self.LUTEgiven = True\n else:\n if self.LUTEgiven == False:\n self.LUTE = 0.0\n if 'WUTE' in param:\n self.WUTE = param['WUTE']\n self.WUTEgiven = True\n elif 'WUTE'.swapcase() in param:\n self.WUTE = param['WUTE'.swapcase()]\n self.WUTEgiven = True\n else:\n if self.WUTEgiven == False:\n self.WUTE = 0.0\n if 'PUTE' in param:\n self.PUTE = param['PUTE']\n self.PUTEgiven = True\n elif 'PUTE'.swapcase() in param:\n self.PUTE = param['PUTE'.swapcase()]\n self.PUTEgiven = True\n else:\n if self.PUTEgiven == False:\n self.PUTE = 0.0\n if 'UTEL' in param:\n self.UTEL = param['UTEL']\n self.UTELgiven = True\n elif 'UTEL'.swapcase() in param:\n self.UTEL = param['UTEL'.swapcase()]\n self.UTELgiven = True\n else:\n if self.UTELgiven == False:\n self.UTEL = 0.0\n if 'UA1' in param:\n self.UA1 = param['UA1']\n self.UA1given = True\n elif 'UA1'.swapcase() in param:\n self.UA1 = param['UA1'.swapcase()]\n self.UA1given = True\n else:\n if self.UA1given == False:\n self.UA1 = 0.001\n if 'LUA1' in param:\n self.LUA1 = param['LUA1']\n self.LUA1given = True\n elif 'LUA1'.swapcase() in param:\n self.LUA1 = param['LUA1'.swapcase()]\n self.LUA1given = True\n else:\n if self.LUA1given == False:\n self.LUA1 = 0.0\n if 'WUA1' in param:\n self.WUA1 = param['WUA1']\n self.WUA1given = True\n elif 'WUA1'.swapcase() in param:\n self.WUA1 = param['WUA1'.swapcase()]\n self.WUA1given = True\n else:\n if self.WUA1given == False:\n self.WUA1 = 0.0\n if 'PUA1' in param:\n self.PUA1 = param['PUA1']\n self.PUA1given = True\n elif 'PUA1'.swapcase() in param:\n self.PUA1 = param['PUA1'.swapcase()]\n self.PUA1given = True\n else:\n if self.PUA1given == False:\n self.PUA1 = 0.0\n if 'UA1L' in param:\n self.UA1L = param['UA1L']\n self.UA1Lgiven = True\n elif 'UA1L'.swapcase() in param:\n self.UA1L = param['UA1L'.swapcase()]\n self.UA1Lgiven = True\n else:\n if self.UA1Lgiven == False:\n self.UA1L = 0.0\n if 'UC1' in param:\n self.UC1 = param['UC1']\n self.UC1given = True\n elif 'UC1'.swapcase() in param:\n self.UC1 = param['UC1'.swapcase()]\n self.UC1given = True\n else:\n if self.UC1given == False:\n self.UC1 = 5.6e-11\n if 'LUC1' in param:\n self.LUC1 = param['LUC1']\n self.LUC1given = True\n elif 'LUC1'.swapcase() in param:\n self.LUC1 = param['LUC1'.swapcase()]\n self.LUC1given = True\n else:\n if self.LUC1given == False:\n self.LUC1 = 0.0\n if 'WUC1' in param:\n self.WUC1 = param['WUC1']\n self.WUC1given = True\n elif 'WUC1'.swapcase() in param:\n self.WUC1 = param['WUC1'.swapcase()]\n self.WUC1given = True\n else:\n if self.WUC1given == False:\n self.WUC1 = 0.0\n if 'PUC1' in param:\n self.PUC1 = param['PUC1']\n self.PUC1given = True\n elif 'PUC1'.swapcase() in param:\n self.PUC1 = param['PUC1'.swapcase()]\n self.PUC1given = True\n else:\n if self.PUC1given == False:\n self.PUC1 = 0.0\n if 'UD1' in param:\n self.UD1 = param['UD1']\n self.UD1given = True\n elif 'UD1'.swapcase() in param:\n self.UD1 = param['UD1'.swapcase()]\n self.UD1given = True\n else:\n if self.UD1given == False:\n self.UD1 = 0.0\n if 'LUD1' in param:\n self.LUD1 = param['LUD1']\n self.LUD1given = True\n elif 'LUD1'.swapcase() in param:\n self.LUD1 = param['LUD1'.swapcase()]\n self.LUD1given = True\n else:\n if self.LUD1given == False:\n self.LUD1 = 0.0\n if 'WUD1' in param:\n self.WUD1 = param['WUD1']\n self.WUD1given = True\n elif 'WUD1'.swapcase() in param:\n self.WUD1 = param['WUD1'.swapcase()]\n self.WUD1given = True\n else:\n if self.WUD1given == False:\n self.WUD1 = 0.0\n if 'PUD1' in param:\n self.PUD1 = param['PUD1']\n self.PUD1given = True\n elif 'PUD1'.swapcase() in param:\n self.PUD1 = param['PUD1'.swapcase()]\n self.PUD1given = True\n else:\n if self.PUD1given == False:\n self.PUD1 = 0.0\n if 'UD1L' in param:\n self.UD1L = param['UD1L']\n self.UD1Lgiven = True\n elif 'UD1L'.swapcase() in param:\n self.UD1L = param['UD1L'.swapcase()]\n self.UD1Lgiven = True\n else:\n if self.UD1Lgiven == False:\n self.UD1L = 0.0\n if 'EU1' in param:\n self.EU1 = param['EU1']\n self.EU1given = True\n elif 'EU1'.swapcase() in param:\n self.EU1 = param['EU1'.swapcase()]\n self.EU1given = True\n else:\n if self.EU1given == False:\n self.EU1 = 0.0\n if 'LEU1' in param:\n self.LEU1 = param['LEU1']\n self.LEU1given = True\n elif 'LEU1'.swapcase() in param:\n self.LEU1 = param['LEU1'.swapcase()]\n self.LEU1given = True\n else:\n if self.LEU1given == False:\n self.LEU1 = 0.0\n if 'WEU1' in param:\n self.WEU1 = param['WEU1']\n self.WEU1given = True\n elif 'WEU1'.swapcase() in param:\n self.WEU1 = param['WEU1'.swapcase()]\n self.WEU1given = True\n else:\n if self.WEU1given == False:\n self.WEU1 = 0.0\n if 'PEU1' in param:\n self.PEU1 = param['PEU1']\n self.PEU1given = True\n elif 'PEU1'.swapcase() in param:\n self.PEU1 = param['PEU1'.swapcase()]\n self.PEU1given = True\n else:\n if self.PEU1given == False:\n self.PEU1 = 0.0\n if 'UCSTE' in param:\n self.UCSTE = param['UCSTE']\n self.UCSTEgiven = True\n elif 'UCSTE'.swapcase() in param:\n self.UCSTE = param['UCSTE'.swapcase()]\n self.UCSTEgiven = True\n else:\n if self.UCSTEgiven == False:\n self.UCSTE = -0.004775\n if 'LUCSTE' in param:\n self.LUCSTE = param['LUCSTE']\n self.LUCSTEgiven = True\n elif 'LUCSTE'.swapcase() in param:\n self.LUCSTE = param['LUCSTE'.swapcase()]\n self.LUCSTEgiven = True\n else:\n if self.LUCSTEgiven == False:\n self.LUCSTE = 0.0\n if 'WUCSTE' in param:\n self.WUCSTE = param['WUCSTE']\n self.WUCSTEgiven = True\n elif 'WUCSTE'.swapcase() in param:\n self.WUCSTE = param['WUCSTE'.swapcase()]\n self.WUCSTEgiven = True\n else:\n if self.WUCSTEgiven == False:\n self.WUCSTE = 0.0\n if 'PUCSTE' in param:\n self.PUCSTE = param['PUCSTE']\n self.PUCSTEgiven = True\n elif 'PUCSTE'.swapcase() in param:\n self.PUCSTE = param['PUCSTE'.swapcase()]\n self.PUCSTEgiven = True\n else:\n if self.PUCSTEgiven == False:\n self.PUCSTE = 0.0\n if 'TETA0' in param:\n self.TETA0 = param['TETA0']\n self.TETA0given = True\n elif 'TETA0'.swapcase() in param:\n self.TETA0 = param['TETA0'.swapcase()]\n self.TETA0given = True\n else:\n if self.TETA0given == False:\n self.TETA0 = 0.0\n if 'PRT' in param:\n self.PRT = param['PRT']\n self.PRTgiven = True\n elif 'PRT'.swapcase() in param:\n self.PRT = param['PRT'.swapcase()]\n self.PRTgiven = True\n else:\n if self.PRTgiven == False:\n self.PRT = 0.0\n if 'LPRT' in param:\n self.LPRT = param['LPRT']\n self.LPRTgiven = True\n elif 'LPRT'.swapcase() in param:\n self.LPRT = param['LPRT'.swapcase()]\n self.LPRTgiven = True\n else:\n if self.LPRTgiven == False:\n self.LPRT = 0.0\n if 'WPRT' in param:\n self.WPRT = param['WPRT']\n self.WPRTgiven = True\n elif 'WPRT'.swapcase() in param:\n self.WPRT = param['WPRT'.swapcase()]\n self.WPRTgiven = True\n else:\n if self.WPRTgiven == False:\n self.WPRT = 0.0\n if 'PPRT' in param:\n self.PPRT = param['PPRT']\n self.PPRTgiven = True\n elif 'PPRT'.swapcase() in param:\n self.PPRT = param['PPRT'.swapcase()]\n self.PPRTgiven = True\n else:\n if self.PPRTgiven == False:\n self.PPRT = 0.0\n if 'AT' in param:\n self.AT = param['AT']\n self.ATgiven = True\n elif 'AT'.swapcase() in param:\n self.AT = param['AT'.swapcase()]\n self.ATgiven = True\n else:\n if self.ATgiven == False:\n self.AT = -0.00156\n if 'LAT' in param:\n self.LAT = param['LAT']\n self.LATgiven = True\n elif 'LAT'.swapcase() in param:\n self.LAT = param['LAT'.swapcase()]\n self.LATgiven = True\n else:\n if self.LATgiven == False:\n self.LAT = 0.0\n if 'WAT' in param:\n self.WAT = param['WAT']\n self.WATgiven = True\n elif 'WAT'.swapcase() in param:\n self.WAT = param['WAT'.swapcase()]\n self.WATgiven = True\n else:\n if self.WATgiven == False:\n self.WAT = 0.0\n if 'PAT' in param:\n self.PAT = param['PAT']\n self.PATgiven = True\n elif 'PAT'.swapcase() in param:\n self.PAT = param['PAT'.swapcase()]\n self.PATgiven = True\n else:\n if self.PATgiven == False:\n self.PAT = 0.0\n if 'ATL' in param:\n self.ATL = param['ATL']\n self.ATLgiven = True\n elif 'ATL'.swapcase() in param:\n self.ATL = param['ATL'.swapcase()]\n self.ATLgiven = True\n else:\n if self.ATLgiven == False:\n self.ATL = 0.0\n if 'TDELTA' in param:\n self.TDELTA = param['TDELTA']\n self.TDELTAgiven = True\n elif 'TDELTA'.swapcase() in param:\n self.TDELTA = param['TDELTA'.swapcase()]\n self.TDELTAgiven = True\n else:\n if self.TDELTAgiven == False:\n self.TDELTA = 0.0\n if 'PTWGT' in param:\n self.PTWGT = param['PTWGT']\n self.PTWGTgiven = True\n elif 'PTWGT'.swapcase() in param:\n self.PTWGT = param['PTWGT'.swapcase()]\n self.PTWGTgiven = True\n else:\n if self.PTWGTgiven == False:\n self.PTWGT = 0.0\n if 'LPTWGT' in param:\n self.LPTWGT = param['LPTWGT']\n self.LPTWGTgiven = True\n elif 'LPTWGT'.swapcase() in param:\n self.LPTWGT = param['LPTWGT'.swapcase()]\n self.LPTWGTgiven = True\n else:\n if self.LPTWGTgiven == False:\n self.LPTWGT = 0.0\n if 'WPTWGT' in param:\n self.WPTWGT = param['WPTWGT']\n self.WPTWGTgiven = True\n elif 'WPTWGT'.swapcase() in param:\n self.WPTWGT = param['WPTWGT'.swapcase()]\n self.WPTWGTgiven = True\n else:\n if self.WPTWGTgiven == False:\n self.WPTWGT = 0.0\n if 'PPTWGT' in param:\n self.PPTWGT = param['PPTWGT']\n self.PPTWGTgiven = True\n elif 'PPTWGT'.swapcase() in param:\n self.PPTWGT = param['PPTWGT'.swapcase()]\n self.PPTWGTgiven = True\n else:\n if self.PPTWGTgiven == False:\n self.PPTWGT = 0.0\n if 'PTWGTL' in param:\n self.PTWGTL = param['PTWGTL']\n self.PTWGTLgiven = True\n elif 'PTWGTL'.swapcase() in param:\n self.PTWGTL = param['PTWGTL'.swapcase()]\n self.PTWGTLgiven = True\n else:\n if self.PTWGTLgiven == False:\n self.PTWGTL = 0.0\n if 'KT1' in param:\n self.KT1 = param['KT1']\n self.KT1given = True\n elif 'KT1'.swapcase() in param:\n self.KT1 = param['KT1'.swapcase()]\n self.KT1given = True\n else:\n if self.KT1given == False:\n self.KT1 = -0.11\n if 'KT1EXP' in param:\n self.KT1EXP = param['KT1EXP']\n self.KT1EXPgiven = True\n elif 'KT1EXP'.swapcase() in param:\n self.KT1EXP = param['KT1EXP'.swapcase()]\n self.KT1EXPgiven = True\n else:\n if self.KT1EXPgiven == False:\n self.KT1EXP = 1.0\n if 'KT1L' in param:\n self.KT1L = param['KT1L']\n self.KT1Lgiven = True\n elif 'KT1L'.swapcase() in param:\n self.KT1L = param['KT1L'.swapcase()]\n self.KT1Lgiven = True\n else:\n if self.KT1Lgiven == False:\n self.KT1L = 0.0\n if 'LKT1' in param:\n self.LKT1 = param['LKT1']\n self.LKT1given = True\n elif 'LKT1'.swapcase() in param:\n self.LKT1 = param['LKT1'.swapcase()]\n self.LKT1given = True\n else:\n if self.LKT1given == False:\n self.LKT1 = 0.0\n if 'WKT1' in param:\n self.WKT1 = param['WKT1']\n self.WKT1given = True\n elif 'WKT1'.swapcase() in param:\n self.WKT1 = param['WKT1'.swapcase()]\n self.WKT1given = True\n else:\n if self.WKT1given == False:\n self.WKT1 = 0.0\n if 'PKT1' in param:\n self.PKT1 = param['PKT1']\n self.PKT1given = True\n elif 'PKT1'.swapcase() in param:\n self.PKT1 = param['PKT1'.swapcase()]\n self.PKT1given = True\n else:\n if self.PKT1given == False:\n self.PKT1 = 0.0\n if 'KT2' in param:\n self.KT2 = param['KT2']\n self.KT2given = True\n elif 'KT2'.swapcase() in param:\n self.KT2 = param['KT2'.swapcase()]\n self.KT2given = True\n else:\n if self.KT2given == False:\n self.KT2 = 0.022\n if 'LKT2' in param:\n self.LKT2 = param['LKT2']\n self.LKT2given = True\n elif 'LKT2'.swapcase() in param:\n self.LKT2 = param['LKT2'.swapcase()]\n self.LKT2given = True\n else:\n if self.LKT2given == False:\n self.LKT2 = 0.0\n if 'WKT2' in param:\n self.WKT2 = param['WKT2']\n self.WKT2given = True\n elif 'WKT2'.swapcase() in param:\n self.WKT2 = param['WKT2'.swapcase()]\n self.WKT2given = True\n else:\n if self.WKT2given == False:\n self.WKT2 = 0.0\n if 'PKT2' in param:\n self.PKT2 = param['PKT2']\n self.PKT2given = True\n elif 'PKT2'.swapcase() in param:\n self.PKT2 = param['PKT2'.swapcase()]\n self.PKT2given = True\n else:\n if self.PKT2given == False:\n self.PKT2 = 0.0\n if 'IIT' in param:\n self.IIT = param['IIT']\n self.IITgiven = True\n elif 'IIT'.swapcase() in param:\n self.IIT = param['IIT'.swapcase()]\n self.IITgiven = True\n else:\n if self.IITgiven == False:\n self.IIT = 0.0\n if 'LIIT' in param:\n self.LIIT = param['LIIT']\n self.LIITgiven = True\n elif 'LIIT'.swapcase() in param:\n self.LIIT = param['LIIT'.swapcase()]\n self.LIITgiven = True\n else:\n if self.LIITgiven == False:\n self.LIIT = 0.0\n if 'WIIT' in param:\n self.WIIT = param['WIIT']\n self.WIITgiven = True\n elif 'WIIT'.swapcase() in param:\n self.WIIT = param['WIIT'.swapcase()]\n self.WIITgiven = True\n else:\n if self.WIITgiven == False:\n self.WIIT = 0.0\n if 'PIIT' in param:\n self.PIIT = param['PIIT']\n self.PIITgiven = True\n elif 'PIIT'.swapcase() in param:\n self.PIIT = param['PIIT'.swapcase()]\n self.PIITgiven = True\n else:\n if self.PIITgiven == False:\n self.PIIT = 0.0\n if 'IGT' in param:\n self.IGT = param['IGT']\n self.IGTgiven = True\n elif 'IGT'.swapcase() in param:\n self.IGT = param['IGT'.swapcase()]\n self.IGTgiven = True\n else:\n if self.IGTgiven == False:\n self.IGT = 2.5\n if 'LIGT' in param:\n self.LIGT = param['LIGT']\n self.LIGTgiven = True\n elif 'LIGT'.swapcase() in param:\n self.LIGT = param['LIGT'.swapcase()]\n self.LIGTgiven = True\n else:\n if self.LIGTgiven == False:\n self.LIGT = 0.0\n if 'WIGT' in param:\n self.WIGT = param['WIGT']\n self.WIGTgiven = True\n elif 'WIGT'.swapcase() in param:\n self.WIGT = param['WIGT'.swapcase()]\n self.WIGTgiven = True\n else:\n if self.WIGTgiven == False:\n self.WIGT = 0.0\n if 'PIGT' in param:\n self.PIGT = param['PIGT']\n self.PIGTgiven = True\n elif 'PIGT'.swapcase() in param:\n self.PIGT = param['PIGT'.swapcase()]\n self.PIGTgiven = True\n else:\n if self.PIGTgiven == False:\n self.PIGT = 0.0\n if 'TGIDL' in param:\n self.TGIDL = param['TGIDL']\n self.TGIDLgiven = True\n elif 'TGIDL'.swapcase() in param:\n self.TGIDL = param['TGIDL'.swapcase()]\n self.TGIDLgiven = True\n else:\n if self.TGIDLgiven == False:\n self.TGIDL = 0.0\n if 'LTGIDL' in param:\n self.LTGIDL = param['LTGIDL']\n self.LTGIDLgiven = True\n elif 'LTGIDL'.swapcase() in param:\n self.LTGIDL = param['LTGIDL'.swapcase()]\n self.LTGIDLgiven = True\n else:\n if self.LTGIDLgiven == False:\n self.LTGIDL = 0.0\n if 'WTGIDL' in param:\n self.WTGIDL = param['WTGIDL']\n self.WTGIDLgiven = True\n elif 'WTGIDL'.swapcase() in param:\n self.WTGIDL = param['WTGIDL'.swapcase()]\n self.WTGIDLgiven = True\n else:\n if self.WTGIDLgiven == False:\n self.WTGIDL = 0.0\n if 'PTGIDL' in param:\n self.PTGIDL = param['PTGIDL']\n self.PTGIDLgiven = True\n elif 'PTGIDL'.swapcase() in param:\n self.PTGIDL = param['PTGIDL'.swapcase()]\n self.PTGIDLgiven = True\n else:\n if self.PTGIDLgiven == False:\n self.PTGIDL = 0.0\n if 'TCJ' in param:\n self.TCJ = param['TCJ']\n self.TCJgiven = True\n elif 'TCJ'.swapcase() in param:\n self.TCJ = param['TCJ'.swapcase()]\n self.TCJgiven = True\n else:\n if self.TCJgiven == False:\n self.TCJ = 0.0\n if 'TCJSW' in param:\n self.TCJSW = param['TCJSW']\n self.TCJSWgiven = True\n elif 'TCJSW'.swapcase() in param:\n self.TCJSW = param['TCJSW'.swapcase()]\n self.TCJSWgiven = True\n else:\n if self.TCJSWgiven == False:\n self.TCJSW = 0.0\n if 'TCJSWG' in param:\n self.TCJSWG = param['TCJSWG']\n self.TCJSWGgiven = True\n elif 'TCJSWG'.swapcase() in param:\n self.TCJSWG = param['TCJSWG'.swapcase()]\n self.TCJSWGgiven = True\n else:\n if self.TCJSWGgiven == False:\n self.TCJSWG = 0.0\n if 'TPB' in param:\n self.TPB = param['TPB']\n self.TPBgiven = True\n elif 'TPB'.swapcase() in param:\n self.TPB = param['TPB'.swapcase()]\n self.TPBgiven = True\n else:\n if self.TPBgiven == False:\n self.TPB = 0.0\n if 'TPBSW' in param:\n self.TPBSW = param['TPBSW']\n self.TPBSWgiven = True\n elif 'TPBSW'.swapcase() in param:\n self.TPBSW = param['TPBSW'.swapcase()]\n self.TPBSWgiven = True\n else:\n if self.TPBSWgiven == False:\n self.TPBSW = 0.0\n if 'TPBSWG' in param:\n self.TPBSWG = param['TPBSWG']\n self.TPBSWGgiven = True\n elif 'TPBSWG'.swapcase() in param:\n self.TPBSWG = param['TPBSWG'.swapcase()]\n self.TPBSWGgiven = True\n else:\n if self.TPBSWGgiven == False:\n self.TPBSWG = 0.0\n if 'XTIS' in param:\n self.XTIS = param['XTIS']\n self.XTISgiven = True\n elif 'XTIS'.swapcase() in param:\n self.XTIS = param['XTIS'.swapcase()]\n self.XTISgiven = True\n else:\n if self.XTISgiven == False:\n self.XTIS = 3.0\n if 'XTID' in param:\n self.XTID = param['XTID']\n self.XTIDgiven = True\n elif 'XTID'.swapcase() in param:\n self.XTID = param['XTID'.swapcase()]\n self.XTIDgiven = True\n else:\n if self.XTIDgiven == False:\n self.XTID = self.XTIS\n if 'XTSS' in param:\n self.XTSS = param['XTSS']\n self.XTSSgiven = True\n elif 'XTSS'.swapcase() in param:\n self.XTSS = param['XTSS'.swapcase()]\n self.XTSSgiven = True\n else:\n if self.XTSSgiven == False:\n self.XTSS = 0.02\n if 'XTSD' in param:\n self.XTSD = param['XTSD']\n self.XTSDgiven = True\n elif 'XTSD'.swapcase() in param:\n self.XTSD = param['XTSD'.swapcase()]\n self.XTSDgiven = True\n else:\n if self.XTSDgiven == False:\n self.XTSD = self.XTSS\n if 'XTSSWS' in param:\n self.XTSSWS = param['XTSSWS']\n self.XTSSWSgiven = True\n elif 'XTSSWS'.swapcase() in param:\n self.XTSSWS = param['XTSSWS'.swapcase()]\n self.XTSSWSgiven = True\n else:\n if self.XTSSWSgiven == False:\n self.XTSSWS = 0.02\n if 'XTSSWD' in param:\n self.XTSSWD = param['XTSSWD']\n self.XTSSWDgiven = True\n elif 'XTSSWD'.swapcase() in param:\n self.XTSSWD = param['XTSSWD'.swapcase()]\n self.XTSSWDgiven = True\n else:\n if self.XTSSWDgiven == False:\n self.XTSSWD = self.XTSSWS\n if 'XTSSWGS' in param:\n self.XTSSWGS = param['XTSSWGS']\n self.XTSSWGSgiven = True\n elif 'XTSSWGS'.swapcase() in param:\n self.XTSSWGS = param['XTSSWGS'.swapcase()]\n self.XTSSWGSgiven = True\n else:\n if self.XTSSWGSgiven == False:\n self.XTSSWGS = 0.02\n if 'XTSSWGD' in param:\n self.XTSSWGD = param['XTSSWGD']\n self.XTSSWGDgiven = True\n elif 'XTSSWGD'.swapcase() in param:\n self.XTSSWGD = param['XTSSWGD'.swapcase()]\n self.XTSSWGDgiven = True\n else:\n if self.XTSSWGDgiven == False:\n self.XTSSWGD = self.XTSSWGS\n if 'TNJTS' in param:\n self.TNJTS = param['TNJTS']\n self.TNJTSgiven = True\n elif 'TNJTS'.swapcase() in param:\n self.TNJTS = param['TNJTS'.swapcase()]\n self.TNJTSgiven = True\n else:\n if self.TNJTSgiven == False:\n self.TNJTS = 0.0\n if 'TNJTSD' in param:\n self.TNJTSD = param['TNJTSD']\n self.TNJTSDgiven = True\n elif 'TNJTSD'.swapcase() in param:\n self.TNJTSD = param['TNJTSD'.swapcase()]\n self.TNJTSDgiven = True\n else:\n if self.TNJTSDgiven == False:\n self.TNJTSD = self.TNJTS\n if 'TNJTSSW' in param:\n self.TNJTSSW = param['TNJTSSW']\n self.TNJTSSWgiven = True\n elif 'TNJTSSW'.swapcase() in param:\n self.TNJTSSW = param['TNJTSSW'.swapcase()]\n self.TNJTSSWgiven = True\n else:\n if self.TNJTSSWgiven == False:\n self.TNJTSSW = 0.0\n if 'TNJTSSWD' in param:\n self.TNJTSSWD = param['TNJTSSWD']\n self.TNJTSSWDgiven = True\n elif 'TNJTSSWD'.swapcase() in param:\n self.TNJTSSWD = param['TNJTSSWD'.swapcase()]\n self.TNJTSSWDgiven = True\n else:\n if self.TNJTSSWDgiven == False:\n self.TNJTSSWD = self.TNJTSSW\n if 'TNJTSSWG' in param:\n self.TNJTSSWG = param['TNJTSSWG']\n self.TNJTSSWGgiven = True\n elif 'TNJTSSWG'.swapcase() in param:\n self.TNJTSSWG = param['TNJTSSWG'.swapcase()]\n self.TNJTSSWGgiven = True\n else:\n if self.TNJTSSWGgiven == False:\n self.TNJTSSWG = 0.0\n if 'TNJTSSWGD' in param:\n self.TNJTSSWGD = param['TNJTSSWGD']\n self.TNJTSSWGDgiven = True\n elif 'TNJTSSWGD'.swapcase() in param:\n self.TNJTSSWGD = param['TNJTSSWGD'.swapcase()]\n self.TNJTSSWGDgiven = True\n else:\n if self.TNJTSSWGDgiven == False:\n self.TNJTSSWGD = self.TNJTSSWG\n if 'RTH0' in param:\n self.RTH0 = param['RTH0']\n self.RTH0given = True\n elif 'RTH0'.swapcase() in param:\n self.RTH0 = param['RTH0'.swapcase()]\n self.RTH0given = True\n else:\n if self.RTH0given == False:\n self.RTH0 = 0.0\n if 'CTH0' in param:\n self.CTH0 = param['CTH0']\n self.CTH0given = True\n elif 'CTH0'.swapcase() in param:\n self.CTH0 = param['CTH0'.swapcase()]\n self.CTH0given = True\n else:\n if self.CTH0given == False:\n self.CTH0 = 1e-05\n if 'WTH0' in param:\n self.WTH0 = param['WTH0']\n self.WTH0given = True\n elif 'WTH0'.swapcase() in param:\n self.WTH0 = param['WTH0'.swapcase()]\n self.WTH0given = True\n else:\n if self.WTH0given == False:\n self.WTH0 = 0.0\n if 'SAREF' in param:\n self.SAREF = param['SAREF']\n self.SAREFgiven = True\n elif 'SAREF'.swapcase() in param:\n self.SAREF = param['SAREF'.swapcase()]\n self.SAREFgiven = True\n else:\n if self.SAREFgiven == False:\n self.SAREF = 1e-06\n if 'SBREF' in param:\n self.SBREF = param['SBREF']\n self.SBREFgiven = True\n elif 'SBREF'.swapcase() in param:\n self.SBREF = param['SBREF'.swapcase()]\n self.SBREFgiven = True\n else:\n if self.SBREFgiven == False:\n self.SBREF = 1e-06\n if 'WLOD' in param:\n self.WLOD = param['WLOD']\n self.WLODgiven = True\n elif 'WLOD'.swapcase() in param:\n self.WLOD = param['WLOD'.swapcase()]\n self.WLODgiven = True\n else:\n if self.WLODgiven == False:\n self.WLOD = 0.0\n if 'KU0' in param:\n self.KU0 = param['KU0']\n self.KU0given = True\n elif 'KU0'.swapcase() in param:\n self.KU0 = param['KU0'.swapcase()]\n self.KU0given = True\n else:\n if self.KU0given == False:\n self.KU0 = 0.0\n if 'KVSAT' in param:\n self.KVSAT = param['KVSAT']\n self.KVSATgiven = True\n elif 'KVSAT'.swapcase() in param:\n self.KVSAT = param['KVSAT'.swapcase()]\n self.KVSATgiven = True\n else:\n if self.KVSATgiven == False:\n self.KVSAT = 0.0\n if 'TKU0' in param:\n self.TKU0 = param['TKU0']\n self.TKU0given = True\n elif 'TKU0'.swapcase() in param:\n self.TKU0 = param['TKU0'.swapcase()]\n self.TKU0given = True\n else:\n if self.TKU0given == False:\n self.TKU0 = 0.0\n if 'LKU0' in param:\n self.LKU0 = param['LKU0']\n self.LKU0given = True\n elif 'LKU0'.swapcase() in param:\n self.LKU0 = param['LKU0'.swapcase()]\n self.LKU0given = True\n else:\n if self.LKU0given == False:\n self.LKU0 = 0.0\n if 'WKU0' in param:\n self.WKU0 = param['WKU0']\n self.WKU0given = True\n elif 'WKU0'.swapcase() in param:\n self.WKU0 = param['WKU0'.swapcase()]\n self.WKU0given = True\n else:\n if self.WKU0given == False:\n self.WKU0 = 0.0\n if 'PKU0' in param:\n self.PKU0 = param['PKU0']\n self.PKU0given = True\n elif 'PKU0'.swapcase() in param:\n self.PKU0 = param['PKU0'.swapcase()]\n self.PKU0given = True\n else:\n if self.PKU0given == False:\n self.PKU0 = 0.0\n if 'LLODKU0' in param:\n self.LLODKU0 = param['LLODKU0']\n self.LLODKU0given = True\n elif 'LLODKU0'.swapcase() in param:\n self.LLODKU0 = param['LLODKU0'.swapcase()]\n self.LLODKU0given = True\n else:\n if self.LLODKU0given == False:\n self.LLODKU0 = 0.0\n if 'WLODKU0' in param:\n self.WLODKU0 = param['WLODKU0']\n self.WLODKU0given = True\n elif 'WLODKU0'.swapcase() in param:\n self.WLODKU0 = param['WLODKU0'.swapcase()]\n self.WLODKU0given = True\n else:\n if self.WLODKU0given == False:\n self.WLODKU0 = 0.0\n if 'KVTH0' in param:\n self.KVTH0 = param['KVTH0']\n self.KVTH0given = True\n elif 'KVTH0'.swapcase() in param:\n self.KVTH0 = param['KVTH0'.swapcase()]\n self.KVTH0given = True\n else:\n if self.KVTH0given == False:\n self.KVTH0 = 0.0\n if 'LKVTH0' in param:\n self.LKVTH0 = param['LKVTH0']\n self.LKVTH0given = True\n elif 'LKVTH0'.swapcase() in param:\n self.LKVTH0 = param['LKVTH0'.swapcase()]\n self.LKVTH0given = True\n else:\n if self.LKVTH0given == False:\n self.LKVTH0 = 0.0\n if 'WKVTH0' in param:\n self.WKVTH0 = param['WKVTH0']\n self.WKVTH0given = True\n elif 'WKVTH0'.swapcase() in param:\n self.WKVTH0 = param['WKVTH0'.swapcase()]\n self.WKVTH0given = True\n else:\n if self.WKVTH0given == False:\n self.WKVTH0 = 0.0\n if 'PKVTH0' in param:\n self.PKVTH0 = param['PKVTH0']\n self.PKVTH0given = True\n elif 'PKVTH0'.swapcase() in param:\n self.PKVTH0 = param['PKVTH0'.swapcase()]\n self.PKVTH0given = True\n else:\n if self.PKVTH0given == False:\n self.PKVTH0 = 0.0\n if 'LLODVTH' in param:\n self.LLODVTH = param['LLODVTH']\n self.LLODVTHgiven = True\n elif 'LLODVTH'.swapcase() in param:\n self.LLODVTH = param['LLODVTH'.swapcase()]\n self.LLODVTHgiven = True\n else:\n if self.LLODVTHgiven == False:\n self.LLODVTH = 0.0\n if 'WLODVTH' in param:\n self.WLODVTH = param['WLODVTH']\n self.WLODVTHgiven = True\n elif 'WLODVTH'.swapcase() in param:\n self.WLODVTH = param['WLODVTH'.swapcase()]\n self.WLODVTHgiven = True\n else:\n if self.WLODVTHgiven == False:\n self.WLODVTH = 0.0\n if 'STK2' in param:\n self.STK2 = param['STK2']\n self.STK2given = True\n elif 'STK2'.swapcase() in param:\n self.STK2 = param['STK2'.swapcase()]\n self.STK2given = True\n else:\n if self.STK2given == False:\n self.STK2 = 0.0\n if 'LODK2' in param:\n self.LODK2 = param['LODK2']\n self.LODK2given = True\n elif 'LODK2'.swapcase() in param:\n self.LODK2 = param['LODK2'.swapcase()]\n self.LODK2given = True\n else:\n if self.LODK2given == False:\n self.LODK2 = 0.0\n if 'STETA0' in param:\n self.STETA0 = param['STETA0']\n self.STETA0given = True\n elif 'STETA0'.swapcase() in param:\n self.STETA0 = param['STETA0'.swapcase()]\n self.STETA0given = True\n else:\n if self.STETA0given == False:\n self.STETA0 = 0.0\n if 'LODETA0' in param:\n self.LODETA0 = param['LODETA0']\n self.LODETA0given = True\n elif 'LODETA0'.swapcase() in param:\n self.LODETA0 = param['LODETA0'.swapcase()]\n self.LODETA0given = True\n else:\n if self.LODETA0given == False:\n self.LODETA0 = 0.0\n if 'WEB' in param:\n self.WEB = param['WEB']\n self.WEBgiven = True\n elif 'WEB'.swapcase() in param:\n self.WEB = param['WEB'.swapcase()]\n self.WEBgiven = True\n else:\n if self.WEBgiven == False:\n self.WEB = 0.0\n if 'WEC' in param:\n self.WEC = param['WEC']\n self.WECgiven = True\n elif 'WEC'.swapcase() in param:\n self.WEC = param['WEC'.swapcase()]\n self.WECgiven = True\n else:\n if self.WECgiven == False:\n self.WEC = 0.0\n if 'KVTH0WE' in param:\n self.KVTH0WE = param['KVTH0WE']\n self.KVTH0WEgiven = True\n elif 'KVTH0WE'.swapcase() in param:\n self.KVTH0WE = param['KVTH0WE'.swapcase()]\n self.KVTH0WEgiven = True\n else:\n if self.KVTH0WEgiven == False:\n self.KVTH0WE = 0.0\n if 'LKVTH0WE' in param:\n self.LKVTH0WE = param['LKVTH0WE']\n self.LKVTH0WEgiven = True\n elif 'LKVTH0WE'.swapcase() in param:\n self.LKVTH0WE = param['LKVTH0WE'.swapcase()]\n self.LKVTH0WEgiven = True\n else:\n if self.LKVTH0WEgiven == False:\n self.LKVTH0WE = 0.0\n if 'WKVTH0WE' in param:\n self.WKVTH0WE = param['WKVTH0WE']\n self.WKVTH0WEgiven = True\n elif 'WKVTH0WE'.swapcase() in param:\n self.WKVTH0WE = param['WKVTH0WE'.swapcase()]\n self.WKVTH0WEgiven = True\n else:\n if self.WKVTH0WEgiven == False:\n self.WKVTH0WE = 0.0\n if 'PKVTH0WE' in param:\n self.PKVTH0WE = param['PKVTH0WE']\n self.PKVTH0WEgiven = True\n elif 'PKVTH0WE'.swapcase() in param:\n self.PKVTH0WE = param['PKVTH0WE'.swapcase()]\n self.PKVTH0WEgiven = True\n else:\n if self.PKVTH0WEgiven == False:\n self.PKVTH0WE = 0.0\n if 'K2WE' in param:\n self.K2WE = param['K2WE']\n self.K2WEgiven = True\n elif 'K2WE'.swapcase() in param:\n self.K2WE = param['K2WE'.swapcase()]\n self.K2WEgiven = True\n else:\n if self.K2WEgiven == False:\n self.K2WE = 0.0\n if 'LK2WE' in param:\n self.LK2WE = param['LK2WE']\n self.LK2WEgiven = True\n elif 'LK2WE'.swapcase() in param:\n self.LK2WE = param['LK2WE'.swapcase()]\n self.LK2WEgiven = True\n else:\n if self.LK2WEgiven == False:\n self.LK2WE = 0.0\n if 'WK2WE' in param:\n self.WK2WE = param['WK2WE']\n self.WK2WEgiven = True\n elif 'WK2WE'.swapcase() in param:\n self.WK2WE = param['WK2WE'.swapcase()]\n self.WK2WEgiven = True\n else:\n if self.WK2WEgiven == False:\n self.WK2WE = 0.0\n if 'PK2WE' in param:\n self.PK2WE = param['PK2WE']\n self.PK2WEgiven = True\n elif 'PK2WE'.swapcase() in param:\n self.PK2WE = param['PK2WE'.swapcase()]\n self.PK2WEgiven = True\n else:\n if self.PK2WEgiven == False:\n self.PK2WE = 0.0\n if 'KU0WE' in param:\n self.KU0WE = param['KU0WE']\n self.KU0WEgiven = True\n elif 'KU0WE'.swapcase() in param:\n self.KU0WE = param['KU0WE'.swapcase()]\n self.KU0WEgiven = True\n else:\n if self.KU0WEgiven == False:\n self.KU0WE = 0.0\n if 'LKU0WE' in param:\n self.LKU0WE = param['LKU0WE']\n self.LKU0WEgiven = True\n elif 'LKU0WE'.swapcase() in param:\n self.LKU0WE = param['LKU0WE'.swapcase()]\n self.LKU0WEgiven = True\n else:\n if self.LKU0WEgiven == False:\n self.LKU0WE = 0.0\n if 'WKU0WE' in param:\n self.WKU0WE = param['WKU0WE']\n self.WKU0WEgiven = True\n elif 'WKU0WE'.swapcase() in param:\n self.WKU0WE = param['WKU0WE'.swapcase()]\n self.WKU0WEgiven = True\n else:\n if self.WKU0WEgiven == False:\n self.WKU0WE = 0.0\n if 'PKU0WE' in param:\n self.PKU0WE = param['PKU0WE']\n self.PKU0WEgiven = True\n elif 'PKU0WE'.swapcase() in param:\n self.PKU0WE = param['PKU0WE'.swapcase()]\n self.PKU0WEgiven = True\n else:\n if self.PKU0WEgiven == False:\n self.PKU0WE = 0.0\n if 'SCREF' in param:\n self.SCREF = param['SCREF']\n self.SCREFgiven = True\n elif 'SCREF'.swapcase() in param:\n self.SCREF = param['SCREF'.swapcase()]\n self.SCREFgiven = True\n else:\n if self.SCREFgiven == False:\n self.SCREF = 1e-06\n if 'SSL0' in param:\n self.SSL0 = param['SSL0']\n self.SSL0given = True\n elif 'SSL0'.swapcase() in param:\n self.SSL0 = param['SSL0'.swapcase()]\n self.SSL0given = True\n else:\n if self.SSL0given == False:\n self.SSL0 = 400.0\n if 'SSL1' in param:\n self.SSL1 = param['SSL1']\n self.SSL1given = True\n elif 'SSL1'.swapcase() in param:\n self.SSL1 = param['SSL1'.swapcase()]\n self.SSL1given = True\n else:\n if self.SSL1given == False:\n self.SSL1 = 336000000.0\n if 'SSL2' in param:\n self.SSL2 = param['SSL2']\n self.SSL2given = True\n elif 'SSL2'.swapcase() in param:\n self.SSL2 = param['SSL2'.swapcase()]\n self.SSL2given = True\n else:\n if self.SSL2given == False:\n self.SSL2 = 0.185\n if 'SSL3' in param:\n self.SSL3 = param['SSL3']\n self.SSL3given = True\n elif 'SSL3'.swapcase() in param:\n self.SSL3 = param['SSL3'.swapcase()]\n self.SSL3given = True\n else:\n if self.SSL3given == False:\n self.SSL3 = 0.3\n if 'SSL4' in param:\n self.SSL4 = param['SSL4']\n self.SSL4given = True\n elif 'SSL4'.swapcase() in param:\n self.SSL4 = param['SSL4'.swapcase()]\n self.SSL4given = True\n else:\n if self.SSL4given == False:\n self.SSL4 = 1.4\n if 'SSL5' in param:\n self.SSL5 = param['SSL5']\n self.SSL5given = True\n elif 'SSL5'.swapcase() in param:\n self.SSL5 = param['SSL5'.swapcase()]\n self.SSL5given = True\n else:\n if self.SSL5given == False:\n self.SSL5 = 0.0\n if 'SSLEXP1' in param:\n self.SSLEXP1 = param['SSLEXP1']\n self.SSLEXP1given = True\n elif 'SSLEXP1'.swapcase() in param:\n self.SSLEXP1 = param['SSLEXP1'.swapcase()]\n self.SSLEXP1given = True\n else:\n if self.SSLEXP1given == False:\n self.SSLEXP1 = 0.49\n if 'SSLEXP2' in param:\n self.SSLEXP2 = param['SSLEXP2']\n self.SSLEXP2given = True\n elif 'SSLEXP2'.swapcase() in param:\n self.SSLEXP2 = param['SSLEXP2'.swapcase()]\n self.SSLEXP2given = True\n else:\n if self.SSLEXP2given == False:\n self.SSLEXP2 = 1.42\n if 'AVDSX' in param:\n self.AVDSX = param['AVDSX']\n self.AVDSXgiven = True\n elif 'AVDSX'.swapcase() in param:\n self.AVDSX = param['AVDSX'.swapcase()]\n self.AVDSXgiven = True\n else:\n if self.AVDSXgiven == False:\n self.AVDSX = 20.0\n if 'WEDGE' in param:\n self.WEDGE = param['WEDGE']\n self.WEDGEgiven = True\n elif 'WEDGE'.swapcase() in param:\n self.WEDGE = param['WEDGE'.swapcase()]\n self.WEDGEgiven = True\n else:\n if self.WEDGEgiven == False:\n self.WEDGE = 1e-08\n if 'DGAMMAEDGE' in param:\n self.DGAMMAEDGE = param['DGAMMAEDGE']\n self.DGAMMAEDGEgiven = True\n elif 'DGAMMAEDGE'.swapcase() in param:\n self.DGAMMAEDGE = param['DGAMMAEDGE'.swapcase()]\n self.DGAMMAEDGEgiven = True\n else:\n if self.DGAMMAEDGEgiven == False:\n self.DGAMMAEDGE = 0.0\n if 'DGAMMAEDGEL' in param:\n self.DGAMMAEDGEL = param['DGAMMAEDGEL']\n self.DGAMMAEDGELgiven = True\n elif 'DGAMMAEDGEL'.swapcase() in param:\n self.DGAMMAEDGEL = param['DGAMMAEDGEL'.swapcase()]\n self.DGAMMAEDGELgiven = True\n else:\n if self.DGAMMAEDGELgiven == False:\n self.DGAMMAEDGEL = 0.0\n if 'DGAMMAEDGELEXP' in param:\n self.DGAMMAEDGELEXP = param['DGAMMAEDGELEXP']\n self.DGAMMAEDGELEXPgiven = True\n elif 'DGAMMAEDGELEXP'.swapcase() in param:\n self.DGAMMAEDGELEXP = param['DGAMMAEDGELEXP'.swapcase()]\n self.DGAMMAEDGELEXPgiven = True\n else:\n if self.DGAMMAEDGELEXPgiven == False:\n self.DGAMMAEDGELEXP = 1.0\n if 'DVTEDGE' in param:\n self.DVTEDGE = param['DVTEDGE']\n self.DVTEDGEgiven = True\n elif 'DVTEDGE'.swapcase() in param:\n self.DVTEDGE = param['DVTEDGE'.swapcase()]\n self.DVTEDGEgiven = True\n else:\n if self.DVTEDGEgiven == False:\n self.DVTEDGE = 0.0\n if 'NDEPEDGE' in param:\n self.NDEPEDGE = param['NDEPEDGE']\n self.NDEPEDGEgiven = True\n elif 'NDEPEDGE'.swapcase() in param:\n self.NDEPEDGE = param['NDEPEDGE'.swapcase()]\n self.NDEPEDGEgiven = True\n else:\n if self.NDEPEDGEgiven == False:\n self.NDEPEDGE = 1e+24\n if 'LNDEPEDGE' in param:\n self.LNDEPEDGE = param['LNDEPEDGE']\n self.LNDEPEDGEgiven = True\n elif 'LNDEPEDGE'.swapcase() in param:\n self.LNDEPEDGE = param['LNDEPEDGE'.swapcase()]\n self.LNDEPEDGEgiven = True\n else:\n if self.LNDEPEDGEgiven == False:\n self.LNDEPEDGE = 0.0\n if 'WNDEPEDGE' in param:\n self.WNDEPEDGE = param['WNDEPEDGE']\n self.WNDEPEDGEgiven = True\n elif 'WNDEPEDGE'.swapcase() in param:\n self.WNDEPEDGE = param['WNDEPEDGE'.swapcase()]\n self.WNDEPEDGEgiven = True\n else:\n if self.WNDEPEDGEgiven == False:\n self.WNDEPEDGE = 0.0\n if 'PNDEPEDGE' in param:\n self.PNDEPEDGE = param['PNDEPEDGE']\n self.PNDEPEDGEgiven = True\n elif 'PNDEPEDGE'.swapcase() in param:\n self.PNDEPEDGE = param['PNDEPEDGE'.swapcase()]\n self.PNDEPEDGEgiven = True\n else:\n if self.PNDEPEDGEgiven == False:\n self.PNDEPEDGE = 0.0\n if 'NFACTOREDGE' in param:\n self.NFACTOREDGE = param['NFACTOREDGE']\n self.NFACTOREDGEgiven = True\n elif 'NFACTOREDGE'.swapcase() in param:\n self.NFACTOREDGE = param['NFACTOREDGE'.swapcase()]\n self.NFACTOREDGEgiven = True\n else:\n if self.NFACTOREDGEgiven == False:\n self.NFACTOREDGE = 0.0\n if 'LNFACTOREDGE' in param:\n self.LNFACTOREDGE = param['LNFACTOREDGE']\n self.LNFACTOREDGEgiven = True\n elif 'LNFACTOREDGE'.swapcase() in param:\n self.LNFACTOREDGE = param['LNFACTOREDGE'.swapcase()]\n self.LNFACTOREDGEgiven = True\n else:\n if self.LNFACTOREDGEgiven == False:\n self.LNFACTOREDGE = 0.0\n if 'WNFACTOREDGE' in param:\n self.WNFACTOREDGE = param['WNFACTOREDGE']\n self.WNFACTOREDGEgiven = True\n elif 'WNFACTOREDGE'.swapcase() in param:\n self.WNFACTOREDGE = param['WNFACTOREDGE'.swapcase()]\n self.WNFACTOREDGEgiven = True\n else:\n if self.WNFACTOREDGEgiven == False:\n self.WNFACTOREDGE = 0.0\n if 'PNFACTOREDGE' in param:\n self.PNFACTOREDGE = param['PNFACTOREDGE']\n self.PNFACTOREDGEgiven = True\n elif 'PNFACTOREDGE'.swapcase() in param:\n self.PNFACTOREDGE = param['PNFACTOREDGE'.swapcase()]\n self.PNFACTOREDGEgiven = True\n else:\n if self.PNFACTOREDGEgiven == False:\n self.PNFACTOREDGE = 0.0\n if 'CITEDGE' in param:\n self.CITEDGE = param['CITEDGE']\n self.CITEDGEgiven = True\n elif 'CITEDGE'.swapcase() in param:\n self.CITEDGE = param['CITEDGE'.swapcase()]\n self.CITEDGEgiven = True\n else:\n if self.CITEDGEgiven == False:\n self.CITEDGE = 0.0\n if 'LCITEDGE' in param:\n self.LCITEDGE = param['LCITEDGE']\n self.LCITEDGEgiven = True\n elif 'LCITEDGE'.swapcase() in param:\n self.LCITEDGE = param['LCITEDGE'.swapcase()]\n self.LCITEDGEgiven = True\n else:\n if self.LCITEDGEgiven == False:\n self.LCITEDGE = 0.0\n if 'WCITEDGE' in param:\n self.WCITEDGE = param['WCITEDGE']\n self.WCITEDGEgiven = True\n elif 'WCITEDGE'.swapcase() in param:\n self.WCITEDGE = param['WCITEDGE'.swapcase()]\n self.WCITEDGEgiven = True\n else:\n if self.WCITEDGEgiven == False:\n self.WCITEDGE = 0.0\n if 'PCITEDGE' in param:\n self.PCITEDGE = param['PCITEDGE']\n self.PCITEDGEgiven = True\n elif 'PCITEDGE'.swapcase() in param:\n self.PCITEDGE = param['PCITEDGE'.swapcase()]\n self.PCITEDGEgiven = True\n else:\n if self.PCITEDGEgiven == False:\n self.PCITEDGE = 0.0\n if 'CDSCDEDGE' in param:\n self.CDSCDEDGE = param['CDSCDEDGE']\n self.CDSCDEDGEgiven = True\n elif 'CDSCDEDGE'.swapcase() in param:\n self.CDSCDEDGE = param['CDSCDEDGE'.swapcase()]\n self.CDSCDEDGEgiven = True\n else:\n if self.CDSCDEDGEgiven == False:\n self.CDSCDEDGE = 1e-09\n if 'LCDSCDEDGE' in param:\n self.LCDSCDEDGE = param['LCDSCDEDGE']\n self.LCDSCDEDGEgiven = True\n elif 'LCDSCDEDGE'.swapcase() in param:\n self.LCDSCDEDGE = param['LCDSCDEDGE'.swapcase()]\n self.LCDSCDEDGEgiven = True\n else:\n if self.LCDSCDEDGEgiven == False:\n self.LCDSCDEDGE = 0.0\n if 'WCDSCDEDGE' in param:\n self.WCDSCDEDGE = param['WCDSCDEDGE']\n self.WCDSCDEDGEgiven = True\n elif 'WCDSCDEDGE'.swapcase() in param:\n self.WCDSCDEDGE = param['WCDSCDEDGE'.swapcase()]\n self.WCDSCDEDGEgiven = True\n else:\n if self.WCDSCDEDGEgiven == False:\n self.WCDSCDEDGE = 0.0\n if 'PCDSCDEDGE' in param:\n self.PCDSCDEDGE = param['PCDSCDEDGE']\n self.PCDSCDEDGEgiven = True\n elif 'PCDSCDEDGE'.swapcase() in param:\n self.PCDSCDEDGE = param['PCDSCDEDGE'.swapcase()]\n self.PCDSCDEDGEgiven = True\n else:\n if self.PCDSCDEDGEgiven == False:\n self.PCDSCDEDGE = 0.0\n if 'CDSCBEDGE' in param:\n self.CDSCBEDGE = param['CDSCBEDGE']\n self.CDSCBEDGEgiven = True\n elif 'CDSCBEDGE'.swapcase() in param:\n self.CDSCBEDGE = param['CDSCBEDGE'.swapcase()]\n self.CDSCBEDGEgiven = True\n else:\n if self.CDSCBEDGEgiven == False:\n self.CDSCBEDGE = 0.0\n if 'LCDSCBEDGE' in param:\n self.LCDSCBEDGE = param['LCDSCBEDGE']\n self.LCDSCBEDGEgiven = True\n elif 'LCDSCBEDGE'.swapcase() in param:\n self.LCDSCBEDGE = param['LCDSCBEDGE'.swapcase()]\n self.LCDSCBEDGEgiven = True\n else:\n if self.LCDSCBEDGEgiven == False:\n self.LCDSCBEDGE = 0.0\n if 'WCDSCBEDGE' in param:\n self.WCDSCBEDGE = param['WCDSCBEDGE']\n self.WCDSCBEDGEgiven = True\n elif 'WCDSCBEDGE'.swapcase() in param:\n self.WCDSCBEDGE = param['WCDSCBEDGE'.swapcase()]\n self.WCDSCBEDGEgiven = True\n else:\n if self.WCDSCBEDGEgiven == False:\n self.WCDSCBEDGE = 0.0\n if 'PCDSCBEDGE' in param:\n self.PCDSCBEDGE = param['PCDSCBEDGE']\n self.PCDSCBEDGEgiven = True\n elif 'PCDSCBEDGE'.swapcase() in param:\n self.PCDSCBEDGE = param['PCDSCBEDGE'.swapcase()]\n self.PCDSCBEDGEgiven = True\n else:\n if self.PCDSCBEDGEgiven == False:\n self.PCDSCBEDGE = 0.0\n if 'ETA0EDGE' in param:\n self.ETA0EDGE = param['ETA0EDGE']\n self.ETA0EDGEgiven = True\n elif 'ETA0EDGE'.swapcase() in param:\n self.ETA0EDGE = param['ETA0EDGE'.swapcase()]\n self.ETA0EDGEgiven = True\n else:\n if self.ETA0EDGEgiven == False:\n self.ETA0EDGE = 0.08\n if 'LETA0EDGE' in param:\n self.LETA0EDGE = param['LETA0EDGE']\n self.LETA0EDGEgiven = True\n elif 'LETA0EDGE'.swapcase() in param:\n self.LETA0EDGE = param['LETA0EDGE'.swapcase()]\n self.LETA0EDGEgiven = True\n else:\n if self.LETA0EDGEgiven == False:\n self.LETA0EDGE = 0.0\n if 'WETA0EDGE' in param:\n self.WETA0EDGE = param['WETA0EDGE']\n self.WETA0EDGEgiven = True\n elif 'WETA0EDGE'.swapcase() in param:\n self.WETA0EDGE = param['WETA0EDGE'.swapcase()]\n self.WETA0EDGEgiven = True\n else:\n if self.WETA0EDGEgiven == False:\n self.WETA0EDGE = 0.0\n if 'PETA0EDGE' in param:\n self.PETA0EDGE = param['PETA0EDGE']\n self.PETA0EDGEgiven = True\n elif 'PETA0EDGE'.swapcase() in param:\n self.PETA0EDGE = param['PETA0EDGE'.swapcase()]\n self.PETA0EDGEgiven = True\n else:\n if self.PETA0EDGEgiven == False:\n self.PETA0EDGE = 0.0\n if 'ETABEDGE' in param:\n self.ETABEDGE = param['ETABEDGE']\n self.ETABEDGEgiven = True\n elif 'ETABEDGE'.swapcase() in param:\n self.ETABEDGE = param['ETABEDGE'.swapcase()]\n self.ETABEDGEgiven = True\n else:\n if self.ETABEDGEgiven == False:\n self.ETABEDGE = -0.07\n if 'LETABEDGE' in param:\n self.LETABEDGE = param['LETABEDGE']\n self.LETABEDGEgiven = True\n elif 'LETABEDGE'.swapcase() in param:\n self.LETABEDGE = param['LETABEDGE'.swapcase()]\n self.LETABEDGEgiven = True\n else:\n if self.LETABEDGEgiven == False:\n self.LETABEDGE = 0.0\n if 'WETABEDGE' in param:\n self.WETABEDGE = param['WETABEDGE']\n self.WETABEDGEgiven = True\n elif 'WETABEDGE'.swapcase() in param:\n self.WETABEDGE = param['WETABEDGE'.swapcase()]\n self.WETABEDGEgiven = True\n else:\n if self.WETABEDGEgiven == False:\n self.WETABEDGE = 0.0\n if 'PETABEDGE' in param:\n self.PETABEDGE = param['PETABEDGE']\n self.PETABEDGEgiven = True\n elif 'PETABEDGE'.swapcase() in param:\n self.PETABEDGE = param['PETABEDGE'.swapcase()]\n self.PETABEDGEgiven = True\n else:\n if self.PETABEDGEgiven == False:\n self.PETABEDGE = 0.0\n if 'KT1EDGE' in param:\n self.KT1EDGE = param['KT1EDGE']\n self.KT1EDGEgiven = True\n elif 'KT1EDGE'.swapcase() in param:\n self.KT1EDGE = param['KT1EDGE'.swapcase()]\n self.KT1EDGEgiven = True\n else:\n if self.KT1EDGEgiven == False:\n self.KT1EDGE = -0.11\n if 'LKT1EDGE' in param:\n self.LKT1EDGE = param['LKT1EDGE']\n self.LKT1EDGEgiven = True\n elif 'LKT1EDGE'.swapcase() in param:\n self.LKT1EDGE = param['LKT1EDGE'.swapcase()]\n self.LKT1EDGEgiven = True\n else:\n if self.LKT1EDGEgiven == False:\n self.LKT1EDGE = 0.0\n if 'WKT1EDGE' in param:\n self.WKT1EDGE = param['WKT1EDGE']\n self.WKT1EDGEgiven = True\n elif 'WKT1EDGE'.swapcase() in param:\n self.WKT1EDGE = param['WKT1EDGE'.swapcase()]\n self.WKT1EDGEgiven = True\n else:\n if self.WKT1EDGEgiven == False:\n self.WKT1EDGE = 0.0\n if 'PKT1EDGE' in param:\n self.PKT1EDGE = param['PKT1EDGE']\n self.PKT1EDGEgiven = True\n elif 'PKT1EDGE'.swapcase() in param:\n self.PKT1EDGE = param['PKT1EDGE'.swapcase()]\n self.PKT1EDGEgiven = True\n else:\n if self.PKT1EDGEgiven == False:\n self.PKT1EDGE = 0.0\n if 'KT1LEDGE' in param:\n self.KT1LEDGE = param['KT1LEDGE']\n self.KT1LEDGEgiven = True\n elif 'KT1LEDGE'.swapcase() in param:\n self.KT1LEDGE = param['KT1LEDGE'.swapcase()]\n self.KT1LEDGEgiven = True\n else:\n if self.KT1LEDGEgiven == False:\n self.KT1LEDGE = 0.0\n if 'LKT1LEDGE' in param:\n self.LKT1LEDGE = param['LKT1LEDGE']\n self.LKT1LEDGEgiven = True\n elif 'LKT1LEDGE'.swapcase() in param:\n self.LKT1LEDGE = param['LKT1LEDGE'.swapcase()]\n self.LKT1LEDGEgiven = True\n else:\n if self.LKT1LEDGEgiven == False:\n self.LKT1LEDGE = 0.0\n if 'WKT1LEDGE' in param:\n self.WKT1LEDGE = param['WKT1LEDGE']\n self.WKT1LEDGEgiven = True\n elif 'WKT1LEDGE'.swapcase() in param:\n self.WKT1LEDGE = param['WKT1LEDGE'.swapcase()]\n self.WKT1LEDGEgiven = True\n else:\n if self.WKT1LEDGEgiven == False:\n self.WKT1LEDGE = 0.0\n if 'PKT1LEDGE' in param:\n self.PKT1LEDGE = param['PKT1LEDGE']\n self.PKT1LEDGEgiven = True\n elif 'PKT1LEDGE'.swapcase() in param:\n self.PKT1LEDGE = param['PKT1LEDGE'.swapcase()]\n self.PKT1LEDGEgiven = True\n else:\n if self.PKT1LEDGEgiven == False:\n self.PKT1LEDGE = 0.0\n if 'KT2EDGE' in param:\n self.KT2EDGE = param['KT2EDGE']\n self.KT2EDGEgiven = True\n elif 'KT2EDGE'.swapcase() in param:\n self.KT2EDGE = param['KT2EDGE'.swapcase()]\n self.KT2EDGEgiven = True\n else:\n if self.KT2EDGEgiven == False:\n self.KT2EDGE = 0.022\n if 'LKT2EDGE' in param:\n self.LKT2EDGE = param['LKT2EDGE']\n self.LKT2EDGEgiven = True\n elif 'LKT2EDGE'.swapcase() in param:\n self.LKT2EDGE = param['LKT2EDGE'.swapcase()]\n self.LKT2EDGEgiven = True\n else:\n if self.LKT2EDGEgiven == False:\n self.LKT2EDGE = 0.0\n if 'WKT2EDGE' in param:\n self.WKT2EDGE = param['WKT2EDGE']\n self.WKT2EDGEgiven = True\n elif 'WKT2EDGE'.swapcase() in param:\n self.WKT2EDGE = param['WKT2EDGE'.swapcase()]\n self.WKT2EDGEgiven = True\n else:\n if self.WKT2EDGEgiven == False:\n self.WKT2EDGE = 0.0\n if 'PKT2EDGE' in param:\n self.PKT2EDGE = param['PKT2EDGE']\n self.PKT2EDGEgiven = True\n elif 'PKT2EDGE'.swapcase() in param:\n self.PKT2EDGE = param['PKT2EDGE'.swapcase()]\n self.PKT2EDGEgiven = True\n else:\n if self.PKT2EDGEgiven == False:\n self.PKT2EDGE = 0.0\n if 'KT1EXPEDGE' in param:\n self.KT1EXPEDGE = param['KT1EXPEDGE']\n self.KT1EXPEDGEgiven = True\n elif 'KT1EXPEDGE'.swapcase() in param:\n self.KT1EXPEDGE = param['KT1EXPEDGE'.swapcase()]\n self.KT1EXPEDGEgiven = True\n else:\n if self.KT1EXPEDGEgiven == False:\n self.KT1EXPEDGE = 1.0\n if 'LKT1EXPEDGE' in param:\n self.LKT1EXPEDGE = param['LKT1EXPEDGE']\n self.LKT1EXPEDGEgiven = True\n elif 'LKT1EXPEDGE'.swapcase() in param:\n self.LKT1EXPEDGE = param['LKT1EXPEDGE'.swapcase()]\n self.LKT1EXPEDGEgiven = True\n else:\n if self.LKT1EXPEDGEgiven == False:\n self.LKT1EXPEDGE = 0.0\n if 'WKT1EXPEDGE' in param:\n self.WKT1EXPEDGE = param['WKT1EXPEDGE']\n self.WKT1EXPEDGEgiven = True\n elif 'WKT1EXPEDGE'.swapcase() in param:\n self.WKT1EXPEDGE = param['WKT1EXPEDGE'.swapcase()]\n self.WKT1EXPEDGEgiven = True\n else:\n if self.WKT1EXPEDGEgiven == False:\n self.WKT1EXPEDGE = 0.0\n if 'PKT1EXPEDGE' in param:\n self.PKT1EXPEDGE = param['PKT1EXPEDGE']\n self.PKT1EXPEDGEgiven = True\n elif 'PKT1EXPEDGE'.swapcase() in param:\n self.PKT1EXPEDGE = param['PKT1EXPEDGE'.swapcase()]\n self.PKT1EXPEDGEgiven = True\n else:\n if self.PKT1EXPEDGEgiven == False:\n self.PKT1EXPEDGE = 0.0\n if 'TNFACTOREDGE' in param:\n self.TNFACTOREDGE = param['TNFACTOREDGE']\n self.TNFACTOREDGEgiven = True\n elif 'TNFACTOREDGE'.swapcase() in param:\n self.TNFACTOREDGE = param['TNFACTOREDGE'.swapcase()]\n self.TNFACTOREDGEgiven = True\n else:\n if self.TNFACTOREDGEgiven == False:\n self.TNFACTOREDGE = 0.0\n if 'LTNFACTOREDGE' in param:\n self.LTNFACTOREDGE = param['LTNFACTOREDGE']\n self.LTNFACTOREDGEgiven = True\n elif 'LTNFACTOREDGE'.swapcase() in param:\n self.LTNFACTOREDGE = param['LTNFACTOREDGE'.swapcase()]\n self.LTNFACTOREDGEgiven = True\n else:\n if self.LTNFACTOREDGEgiven == False:\n self.LTNFACTOREDGE = 0.0\n if 'WTNFACTOREDGE' in param:\n self.WTNFACTOREDGE = param['WTNFACTOREDGE']\n self.WTNFACTOREDGEgiven = True\n elif 'WTNFACTOREDGE'.swapcase() in param:\n self.WTNFACTOREDGE = param['WTNFACTOREDGE'.swapcase()]\n self.WTNFACTOREDGEgiven = True\n else:\n if self.WTNFACTOREDGEgiven == False:\n self.WTNFACTOREDGE = 0.0\n if 'PTNFACTOREDGE' in param:\n self.PTNFACTOREDGE = param['PTNFACTOREDGE']\n self.PTNFACTOREDGEgiven = True\n elif 'PTNFACTOREDGE'.swapcase() in param:\n self.PTNFACTOREDGE = param['PTNFACTOREDGE'.swapcase()]\n self.PTNFACTOREDGEgiven = True\n else:\n if self.PTNFACTOREDGEgiven == False:\n self.PTNFACTOREDGE = 0.0\n if 'TETA0EDGE' in param:\n self.TETA0EDGE = param['TETA0EDGE']\n self.TETA0EDGEgiven = True\n elif 'TETA0EDGE'.swapcase() in param:\n self.TETA0EDGE = param['TETA0EDGE'.swapcase()]\n self.TETA0EDGEgiven = True\n else:\n if self.TETA0EDGEgiven == False:\n self.TETA0EDGE = 0.0\n if 'LTETA0EDGE' in param:\n self.LTETA0EDGE = param['LTETA0EDGE']\n self.LTETA0EDGEgiven = True\n elif 'LTETA0EDGE'.swapcase() in param:\n self.LTETA0EDGE = param['LTETA0EDGE'.swapcase()]\n self.LTETA0EDGEgiven = True\n else:\n if self.LTETA0EDGEgiven == False:\n self.LTETA0EDGE = 0.0\n if 'WTETA0EDGE' in param:\n self.WTETA0EDGE = param['WTETA0EDGE']\n self.WTETA0EDGEgiven = True\n elif 'WTETA0EDGE'.swapcase() in param:\n self.WTETA0EDGE = param['WTETA0EDGE'.swapcase()]\n self.WTETA0EDGEgiven = True\n else:\n if self.WTETA0EDGEgiven == False:\n self.WTETA0EDGE = 0.0\n if 'PTETA0EDGE' in param:\n self.PTETA0EDGE = param['PTETA0EDGE']\n self.PTETA0EDGEgiven = True\n elif 'PTETA0EDGE'.swapcase() in param:\n self.PTETA0EDGE = param['PTETA0EDGE'.swapcase()]\n self.PTETA0EDGEgiven = True\n else:\n if self.PTETA0EDGEgiven == False:\n self.PTETA0EDGE = 0.0\n if 'DVT0EDGE' in param:\n self.DVT0EDGE = param['DVT0EDGE']\n self.DVT0EDGEgiven = True\n elif 'DVT0EDGE'.swapcase() in param:\n self.DVT0EDGE = param['DVT0EDGE'.swapcase()]\n self.DVT0EDGEgiven = True\n else:\n if self.DVT0EDGEgiven == False:\n self.DVT0EDGE = 2.2\n if 'DVT1EDGE' in param:\n self.DVT1EDGE = param['DVT1EDGE']\n self.DVT1EDGEgiven = True\n elif 'DVT1EDGE'.swapcase() in param:\n self.DVT1EDGE = param['DVT1EDGE'.swapcase()]\n self.DVT1EDGEgiven = True\n else:\n if self.DVT1EDGEgiven == False:\n self.DVT1EDGE = 0.53\n if 'DVT2EDGE' in param:\n self.DVT2EDGE = param['DVT2EDGE']\n self.DVT2EDGEgiven = True\n elif 'DVT2EDGE'.swapcase() in param:\n self.DVT2EDGE = param['DVT2EDGE'.swapcase()]\n self.DVT2EDGEgiven = True\n else:\n if self.DVT2EDGEgiven == False:\n self.DVT2EDGE = 0.0\n if 'K2EDGE' in param:\n self.K2EDGE = param['K2EDGE']\n self.K2EDGEgiven = True\n elif 'K2EDGE'.swapcase() in param:\n self.K2EDGE = param['K2EDGE'.swapcase()]\n self.K2EDGEgiven = True\n else:\n if self.K2EDGEgiven == False:\n self.K2EDGE = 0.0\n if 'LK2EDGE' in param:\n self.LK2EDGE = param['LK2EDGE']\n self.LK2EDGEgiven = True\n elif 'LK2EDGE'.swapcase() in param:\n self.LK2EDGE = param['LK2EDGE'.swapcase()]\n self.LK2EDGEgiven = True\n else:\n if self.LK2EDGEgiven == False:\n self.LK2EDGE = 0.0\n if 'WK2EDGE' in param:\n self.WK2EDGE = param['WK2EDGE']\n self.WK2EDGEgiven = True\n elif 'WK2EDGE'.swapcase() in param:\n self.WK2EDGE = param['WK2EDGE'.swapcase()]\n self.WK2EDGEgiven = True\n else:\n if self.WK2EDGEgiven == False:\n self.WK2EDGE = 0.0\n if 'PK2EDGE' in param:\n self.PK2EDGE = param['PK2EDGE']\n self.PK2EDGEgiven = True\n elif 'PK2EDGE'.swapcase() in param:\n self.PK2EDGE = param['PK2EDGE'.swapcase()]\n self.PK2EDGEgiven = True\n else:\n if self.PK2EDGEgiven == False:\n self.PK2EDGE = 0.0\n if 'KVTH0EDGE' in param:\n self.KVTH0EDGE = param['KVTH0EDGE']\n self.KVTH0EDGEgiven = True\n elif 'KVTH0EDGE'.swapcase() in param:\n self.KVTH0EDGE = param['KVTH0EDGE'.swapcase()]\n self.KVTH0EDGEgiven = True\n else:\n if self.KVTH0EDGEgiven == False:\n self.KVTH0EDGE = 0.0\n if 'LKVTH0EDGE' in param:\n self.LKVTH0EDGE = param['LKVTH0EDGE']\n self.LKVTH0EDGEgiven = True\n elif 'LKVTH0EDGE'.swapcase() in param:\n self.LKVTH0EDGE = param['LKVTH0EDGE'.swapcase()]\n self.LKVTH0EDGEgiven = True\n else:\n if self.LKVTH0EDGEgiven == False:\n self.LKVTH0EDGE = 0.0\n if 'WKVTH0EDGE' in param:\n self.WKVTH0EDGE = param['WKVTH0EDGE']\n self.WKVTH0EDGEgiven = True\n elif 'WKVTH0EDGE'.swapcase() in param:\n self.WKVTH0EDGE = param['WKVTH0EDGE'.swapcase()]\n self.WKVTH0EDGEgiven = True\n else:\n if self.WKVTH0EDGEgiven == False:\n self.WKVTH0EDGE = 0.0\n if 'PKVTH0EDGE' in param:\n self.PKVTH0EDGE = param['PKVTH0EDGE']\n self.PKVTH0EDGEgiven = True\n elif 'PKVTH0EDGE'.swapcase() in param:\n self.PKVTH0EDGE = param['PKVTH0EDGE'.swapcase()]\n self.PKVTH0EDGEgiven = True\n else:\n if self.PKVTH0EDGEgiven == False:\n self.PKVTH0EDGE = 0.0\n if 'STK2EDGE' in param:\n self.STK2EDGE = param['STK2EDGE']\n self.STK2EDGEgiven = True\n elif 'STK2EDGE'.swapcase() in param:\n self.STK2EDGE = param['STK2EDGE'.swapcase()]\n self.STK2EDGEgiven = True\n else:\n if self.STK2EDGEgiven == False:\n self.STK2EDGE = 0.0\n if 'LSTK2EDGE' in param:\n self.LSTK2EDGE = param['LSTK2EDGE']\n self.LSTK2EDGEgiven = True\n elif 'LSTK2EDGE'.swapcase() in param:\n self.LSTK2EDGE = param['LSTK2EDGE'.swapcase()]\n self.LSTK2EDGEgiven = True\n else:\n if self.LSTK2EDGEgiven == False:\n self.LSTK2EDGE = 0.0\n if 'WSTK2EDGE' in param:\n self.WSTK2EDGE = param['WSTK2EDGE']\n self.WSTK2EDGEgiven = True\n elif 'WSTK2EDGE'.swapcase() in param:\n self.WSTK2EDGE = param['WSTK2EDGE'.swapcase()]\n self.WSTK2EDGEgiven = True\n else:\n if self.WSTK2EDGEgiven == False:\n self.WSTK2EDGE = 0.0\n if 'PSTK2EDGE' in param:\n self.PSTK2EDGE = param['PSTK2EDGE']\n self.PSTK2EDGEgiven = True\n elif 'PSTK2EDGE'.swapcase() in param:\n self.PSTK2EDGE = param['PSTK2EDGE'.swapcase()]\n self.PSTK2EDGEgiven = True\n else:\n if self.PSTK2EDGEgiven == False:\n self.PSTK2EDGE = 0.0\n if 'STETA0EDGE' in param:\n self.STETA0EDGE = param['STETA0EDGE']\n self.STETA0EDGEgiven = True\n elif 'STETA0EDGE'.swapcase() in param:\n self.STETA0EDGE = param['STETA0EDGE'.swapcase()]\n self.STETA0EDGEgiven = True\n else:\n if self.STETA0EDGEgiven == False:\n self.STETA0EDGE = 0.0\n if 'LSTETA0EDGE' in param:\n self.LSTETA0EDGE = param['LSTETA0EDGE']\n self.LSTETA0EDGEgiven = True\n elif 'LSTETA0EDGE'.swapcase() in param:\n self.LSTETA0EDGE = param['LSTETA0EDGE'.swapcase()]\n self.LSTETA0EDGEgiven = True\n else:\n if self.LSTETA0EDGEgiven == False:\n self.LSTETA0EDGE = 0.0\n if 'WSTETA0EDGE' in param:\n self.WSTETA0EDGE = param['WSTETA0EDGE']\n self.WSTETA0EDGEgiven = True\n elif 'WSTETA0EDGE'.swapcase() in param:\n self.WSTETA0EDGE = param['WSTETA0EDGE'.swapcase()]\n self.WSTETA0EDGEgiven = True\n else:\n if self.WSTETA0EDGEgiven == False:\n self.WSTETA0EDGE = 0.0\n if 'PSTETA0EDGE' in param:\n self.PSTETA0EDGE = param['PSTETA0EDGE']\n self.PSTETA0EDGEgiven = True\n elif 'PSTETA0EDGE'.swapcase() in param:\n self.PSTETA0EDGE = param['PSTETA0EDGE'.swapcase()]\n self.PSTETA0EDGEgiven = True\n else:\n if self.PSTETA0EDGEgiven == False:\n self.PSTETA0EDGE = 0.0\n if 'IGCLAMP' in param:\n self.IGCLAMP = param['IGCLAMP']\n self.IGCLAMPgiven = True\n elif 'IGCLAMP'.swapcase() in param:\n self.IGCLAMP = param['IGCLAMP'.swapcase()]\n self.IGCLAMPgiven = True\n else:\n if self.IGCLAMPgiven == False:\n self.IGCLAMP = 1.0\n if 'LP' in param:\n self.LP = param['LP']\n self.LPgiven = True\n elif 'LP'.swapcase() in param:\n self.LP = param['LP'.swapcase()]\n self.LPgiven = True\n else:\n if self.LPgiven == False:\n self.LP = 1e-05\n if 'RNOIK' in param:\n self.RNOIK = param['RNOIK']\n self.RNOIKgiven = True\n elif 'RNOIK'.swapcase() in param:\n self.RNOIK = param['RNOIK'.swapcase()]\n self.RNOIKgiven = True\n else:\n if self.RNOIKgiven == False:\n self.RNOIK = 0.0\n if 'TNOIK' in param:\n self.TNOIK = param['TNOIK']\n self.TNOIKgiven = True\n elif 'TNOIK'.swapcase() in param:\n self.TNOIK = param['TNOIK'.swapcase()]\n self.TNOIKgiven = True\n else:\n if self.TNOIKgiven == False:\n self.TNOIK = 0.0\n if 'TNOIK2' in param:\n self.TNOIK2 = param['TNOIK2']\n self.TNOIK2given = True\n elif 'TNOIK2'.swapcase() in param:\n self.TNOIK2 = param['TNOIK2'.swapcase()]\n self.TNOIK2given = True\n else:\n if self.TNOIK2given == False:\n self.TNOIK2 = 0.1\n if 'K0' in param:\n self.K0 = param['K0']\n self.K0given = True\n elif 'K0'.swapcase() in param:\n self.K0 = param['K0'.swapcase()]\n self.K0given = True\n else:\n if self.K0given == False:\n self.K0 = 0.0\n if 'LK0' in param:\n self.LK0 = param['LK0']\n self.LK0given = True\n elif 'LK0'.swapcase() in param:\n self.LK0 = param['LK0'.swapcase()]\n self.LK0given = True\n else:\n if self.LK0given == False:\n self.LK0 = 0.0\n if 'WK0' in param:\n self.WK0 = param['WK0']\n self.WK0given = True\n elif 'WK0'.swapcase() in param:\n self.WK0 = param['WK0'.swapcase()]\n self.WK0given = True\n else:\n if self.WK0given == False:\n self.WK0 = 0.0\n if 'PK0' in param:\n self.PK0 = param['PK0']\n self.PK0given = True\n elif 'PK0'.swapcase() in param:\n self.PK0 = param['PK0'.swapcase()]\n self.PK0given = True\n else:\n if self.PK0given == False:\n self.PK0 = 0.0\n if 'K01' in param:\n self.K01 = param['K01']\n self.K01given = True\n elif 'K01'.swapcase() in param:\n self.K01 = param['K01'.swapcase()]\n self.K01given = True\n else:\n if self.K01given == False:\n self.K01 = 0.0\n if 'LK01' in param:\n self.LK01 = param['LK01']\n self.LK01given = True\n elif 'LK01'.swapcase() in param:\n self.LK01 = param['LK01'.swapcase()]\n self.LK01given = True\n else:\n if self.LK01given == False:\n self.LK01 = 0.0\n if 'WK01' in param:\n self.WK01 = param['WK01']\n self.WK01given = True\n elif 'WK01'.swapcase() in param:\n self.WK01 = param['WK01'.swapcase()]\n self.WK01given = True\n else:\n if self.WK01given == False:\n self.WK01 = 0.0\n if 'PK01' in param:\n self.PK01 = param['PK01']\n self.PK01given = True\n elif 'PK01'.swapcase() in param:\n self.PK01 = param['PK01'.swapcase()]\n self.PK01given = True\n else:\n if self.PK01given == False:\n self.PK01 = 0.0\n if 'M0' in param:\n self.M0 = param['M0']\n self.M0given = True\n elif 'M0'.swapcase() in param:\n self.M0 = param['M0'.swapcase()]\n self.M0given = True\n else:\n if self.M0given == False:\n self.M0 = 1.0\n if 'LM0' in param:\n self.LM0 = param['LM0']\n self.LM0given = True\n elif 'LM0'.swapcase() in param:\n self.LM0 = param['LM0'.swapcase()]\n self.LM0given = True\n else:\n if self.LM0given == False:\n self.LM0 = 0.0\n if 'WM0' in param:\n self.WM0 = param['WM0']\n self.WM0given = True\n elif 'WM0'.swapcase() in param:\n self.WM0 = param['WM0'.swapcase()]\n self.WM0given = True\n else:\n if self.WM0given == False:\n self.WM0 = 0.0\n if 'PM0' in param:\n self.PM0 = param['PM0']\n self.PM0given = True\n elif 'PM0'.swapcase() in param:\n self.PM0 = param['PM0'.swapcase()]\n self.PM0given = True\n else:\n if self.PM0given == False:\n self.PM0 = 0.0\n if 'M01' in param:\n self.M01 = param['M01']\n self.M01given = True\n elif 'M01'.swapcase() in param:\n self.M01 = param['M01'.swapcase()]\n self.M01given = True\n else:\n if self.M01given == False:\n self.M01 = 0.0\n if 'LM01' in param:\n self.LM01 = param['LM01']\n self.LM01given = True\n elif 'LM01'.swapcase() in param:\n self.LM01 = param['LM01'.swapcase()]\n self.LM01given = True\n else:\n if self.LM01given == False:\n self.LM01 = 0.0\n if 'WM01' in param:\n self.WM01 = param['WM01']\n self.WM01given = True\n elif 'WM01'.swapcase() in param:\n self.WM01 = param['WM01'.swapcase()]\n self.WM01given = True\n else:\n if self.WM01given == False:\n self.WM01 = 0.0\n if 'PM01' in param:\n self.PM01 = param['PM01']\n self.PM01given = True\n elif 'PM01'.swapcase() in param:\n self.PM01 = param['PM01'.swapcase()]\n self.PM01given = True\n else:\n if self.PM01given == False:\n self.PM01 = 0.0\n if 'NEDGE' in param:\n self.NEDGE = param['NEDGE']\n self.NEDGEgiven = True\n elif 'NEDGE'.swapcase() in param:\n self.NEDGE = param['NEDGE'.swapcase()]\n self.NEDGEgiven = True\n else:\n if self.NEDGEgiven == False:\n self.NEDGE = 1.0\n if 'NOIA1_EDGE' in param:\n self.NOIA1_EDGE = param['NOIA1_EDGE']\n self.NOIA1_EDGEgiven = True\n elif 'NOIA1_EDGE'.swapcase() in param:\n self.NOIA1_EDGE = param['NOIA1_EDGE'.swapcase()]\n self.NOIA1_EDGEgiven = True\n else:\n if self.NOIA1_EDGEgiven == False:\n self.NOIA1_EDGE = 0.0\n if 'NOIAX_EDGE' in param:\n self.NOIAX_EDGE = param['NOIAX_EDGE']\n self.NOIAX_EDGEgiven = True\n elif 'NOIAX_EDGE'.swapcase() in param:\n self.NOIAX_EDGE = param['NOIAX_EDGE'.swapcase()]\n self.NOIAX_EDGEgiven = True\n else:\n if self.NOIAX_EDGEgiven == False:\n self.NOIAX_EDGE = 1.0\n if 'FNOIMOD' in param:\n self.FNOIMOD = param['FNOIMOD']\n self.FNOIMODgiven = True\n elif 'FNOIMOD'.swapcase() in param:\n self.FNOIMOD = param['FNOIMOD'.swapcase()]\n self.FNOIMODgiven = True\n else:\n if self.FNOIMODgiven == False:\n self.FNOIMOD = 0.0\n if 'LH' in param:\n self.LH = param['LH']\n self.LHgiven = True\n elif 'LH'.swapcase() in param:\n self.LH = param['LH'.swapcase()]\n self.LHgiven = True\n else:\n if self.LHgiven == False:\n self.LH = 1e-08\n if 'NOIA2' in param:\n self.NOIA2 = param['NOIA2']\n self.NOIA2given = True\n elif 'NOIA2'.swapcase() in param:\n self.NOIA2 = param['NOIA2'.swapcase()]\n self.NOIA2given = True\n else:\n if self.NOIA2given == False:\n self.NOIA2 = self.NOIA\n if 'HNDEP' in param:\n self.HNDEP = param['HNDEP']\n self.HNDEPgiven = True\n elif 'HNDEP'.swapcase() in param:\n self.HNDEP = param['HNDEP'.swapcase()]\n self.HNDEPgiven = True\n else:\n if self.HNDEPgiven == False:\n self.HNDEP = self.NDEP\n if 'ABULK' in param:\n self.ABULK = param['ABULK']\n self.ABULKgiven = True\n elif 'ABULK'.swapcase() in param:\n self.ABULK = param['ABULK'.swapcase()]\n self.ABULKgiven = True\n else:\n if self.ABULKgiven == False:\n self.ABULK = 1.0\n if 'C0' in param:\n self.C0 = param['C0']\n self.C0given = True\n elif 'C0'.swapcase() in param:\n self.C0 = param['C0'.swapcase()]\n self.C0given = True\n else:\n if self.C0given == False:\n self.C0 = 0.0\n if 'LC0' in param:\n self.LC0 = param['LC0']\n self.LC0given = True\n elif 'LC0'.swapcase() in param:\n self.LC0 = param['LC0'.swapcase()]\n self.LC0given = True\n else:\n if self.LC0given == False:\n self.LC0 = 0.0\n if 'WC0' in param:\n self.WC0 = param['WC0']\n self.WC0given = True\n elif 'WC0'.swapcase() in param:\n self.WC0 = param['WC0'.swapcase()]\n self.WC0given = True\n else:\n if self.WC0given == False:\n self.WC0 = 0.0\n if 'PC0' in param:\n self.PC0 = param['PC0']\n self.PC0given = True\n elif 'PC0'.swapcase() in param:\n self.PC0 = param['PC0'.swapcase()]\n self.PC0given = True\n else:\n if self.PC0given == False:\n self.PC0 = 0.0\n if 'C01' in param:\n self.C01 = param['C01']\n self.C01given = True\n elif 'C01'.swapcase() in param:\n self.C01 = param['C01'.swapcase()]\n self.C01given = True\n else:\n if self.C01given == False:\n self.C01 = 0.0\n if 'LC01' in param:\n self.LC01 = param['LC01']\n self.LC01given = True\n elif 'LC01'.swapcase() in param:\n self.LC01 = param['LC01'.swapcase()]\n self.LC01given = True\n else:\n if self.LC01given == False:\n self.LC01 = 0.0\n if 'WC01' in param:\n self.WC01 = param['WC01']\n self.WC01given = True\n elif 'WC01'.swapcase() in param:\n self.WC01 = param['WC01'.swapcase()]\n self.WC01given = True\n else:\n if self.WC01given == False:\n self.WC01 = 0.0\n if 'PC01' in param:\n self.PC01 = param['PC01']\n self.PC01given = True\n elif 'PC01'.swapcase() in param:\n self.PC01 = param['PC01'.swapcase()]\n self.PC01given = True\n else:\n if self.PC01given == False:\n self.PC01 = 0.0\n if 'C0SI' in param:\n self.C0SI = param['C0SI']\n self.C0SIgiven = True\n elif 'C0SI'.swapcase() in param:\n self.C0SI = param['C0SI'.swapcase()]\n self.C0SIgiven = True\n else:\n if self.C0SIgiven == False:\n self.C0SI = 1.0\n if 'LC0SI' in param:\n self.LC0SI = param['LC0SI']\n self.LC0SIgiven = True\n elif 'LC0SI'.swapcase() in param:\n self.LC0SI = param['LC0SI'.swapcase()]\n self.LC0SIgiven = True\n else:\n if self.LC0SIgiven == False:\n self.LC0SI = 0.0\n if 'WC0SI' in param:\n self.WC0SI = param['WC0SI']\n self.WC0SIgiven = True\n elif 'WC0SI'.swapcase() in param:\n self.WC0SI = param['WC0SI'.swapcase()]\n self.WC0SIgiven = True\n else:\n if self.WC0SIgiven == False:\n self.WC0SI = 0.0\n if 'PC0SI' in param:\n self.PC0SI = param['PC0SI']\n self.PC0SIgiven = True\n elif 'PC0SI'.swapcase() in param:\n self.PC0SI = param['PC0SI'.swapcase()]\n self.PC0SIgiven = True\n else:\n if self.PC0SIgiven == False:\n self.PC0SI = 0.0\n if 'C0SI1' in param:\n self.C0SI1 = param['C0SI1']\n self.C0SI1given = True\n elif 'C0SI1'.swapcase() in param:\n self.C0SI1 = param['C0SI1'.swapcase()]\n self.C0SI1given = True\n else:\n if self.C0SI1given == False:\n self.C0SI1 = 0.0\n if 'LC0SI1' in param:\n self.LC0SI1 = param['LC0SI1']\n self.LC0SI1given = True\n elif 'LC0SI1'.swapcase() in param:\n self.LC0SI1 = param['LC0SI1'.swapcase()]\n self.LC0SI1given = True\n else:\n if self.LC0SI1given == False:\n self.LC0SI1 = 0.0\n if 'WC0SI1' in param:\n self.WC0SI1 = param['WC0SI1']\n self.WC0SI1given = True\n elif 'WC0SI1'.swapcase() in param:\n self.WC0SI1 = param['WC0SI1'.swapcase()]\n self.WC0SI1given = True\n else:\n if self.WC0SI1given == False:\n self.WC0SI1 = 0.0\n if 'PC0SI1' in param:\n self.PC0SI1 = param['PC0SI1']\n self.PC0SI1given = True\n elif 'PC0SI1'.swapcase() in param:\n self.PC0SI1 = param['PC0SI1'.swapcase()]\n self.PC0SI1given = True\n else:\n if self.PC0SI1given == False:\n self.PC0SI1 = 0.0\n if 'C0SISAT' in param:\n self.C0SISAT = param['C0SISAT']\n self.C0SISATgiven = True\n elif 'C0SISAT'.swapcase() in param:\n self.C0SISAT = param['C0SISAT'.swapcase()]\n self.C0SISATgiven = True\n else:\n if self.C0SISATgiven == False:\n self.C0SISAT = 0.0\n if 'LC0SISAT' in param:\n self.LC0SISAT = param['LC0SISAT']\n self.LC0SISATgiven = True\n elif 'LC0SISAT'.swapcase() in param:\n self.LC0SISAT = param['LC0SISAT'.swapcase()]\n self.LC0SISATgiven = True\n else:\n if self.LC0SISATgiven == False:\n self.LC0SISAT = 0.0\n if 'WC0SISAT' in param:\n self.WC0SISAT = param['WC0SISAT']\n self.WC0SISATgiven = True\n elif 'WC0SISAT'.swapcase() in param:\n self.WC0SISAT = param['WC0SISAT'.swapcase()]\n self.WC0SISATgiven = True\n else:\n if self.WC0SISATgiven == False:\n self.WC0SISAT = 0.0\n if 'PC0SISAT' in param:\n self.PC0SISAT = param['PC0SISAT']\n self.PC0SISATgiven = True\n elif 'PC0SISAT'.swapcase() in param:\n self.PC0SISAT = param['PC0SISAT'.swapcase()]\n self.PC0SISATgiven = True\n else:\n if self.PC0SISATgiven == False:\n self.PC0SISAT = 0.0\n if 'C0SISAT1' in param:\n self.C0SISAT1 = param['C0SISAT1']\n self.C0SISAT1given = True\n elif 'C0SISAT1'.swapcase() in param:\n self.C0SISAT1 = param['C0SISAT1'.swapcase()]\n self.C0SISAT1given = True\n else:\n if self.C0SISAT1given == False:\n self.C0SISAT1 = 0.0\n if 'LC0SISAT1' in param:\n self.LC0SISAT1 = param['LC0SISAT1']\n self.LC0SISAT1given = True\n elif 'LC0SISAT1'.swapcase() in param:\n self.LC0SISAT1 = param['LC0SISAT1'.swapcase()]\n self.LC0SISAT1given = True\n else:\n if self.LC0SISAT1given == False:\n self.LC0SISAT1 = 0.0\n if 'WC0SISAT1' in param:\n self.WC0SISAT1 = param['WC0SISAT1']\n self.WC0SISAT1given = True\n elif 'WC0SISAT1'.swapcase() in param:\n self.WC0SISAT1 = param['WC0SISAT1'.swapcase()]\n self.WC0SISAT1given = True\n else:\n if self.WC0SISAT1given == False:\n self.WC0SISAT1 = 0.0\n if 'PC0SISAT1' in param:\n self.PC0SISAT1 = param['PC0SISAT1']\n self.PC0SISAT1given = True\n elif 'PC0SISAT1'.swapcase() in param:\n self.PC0SISAT1 = param['PC0SISAT1'.swapcase()]\n self.PC0SISAT1given = True\n else:\n if self.PC0SISAT1given == False:\n self.PC0SISAT1 = 0.0\n if 'minr' in param:\n self.minr = param['minr']\n self.minrgiven = True\n elif 'minr'.swapcase() in param:\n self.minr = param['minr'.swapcase()]\n self.minrgiven = True\n else:\n if self.minrgiven == False:\n self.minr = 0.001\n if 'HVMOD' in param:\n self.HVMOD = param['HVMOD']\n self.HVMODgiven = True\n elif 'HVMOD'.swapcase() in param:\n self.HVMOD = param['HVMOD'.swapcase()]\n self.HVMODgiven = True\n else:\n if self.HVMODgiven == False:\n self.HVMOD = 0.0\n if 'HVCAP' in param:\n self.HVCAP = param['HVCAP']\n self.HVCAPgiven = True\n elif 'HVCAP'.swapcase() in param:\n self.HVCAP = param['HVCAP'.swapcase()]\n self.HVCAPgiven = True\n else:\n if self.HVCAPgiven == False:\n self.HVCAP = 0.0\n if 'HVCAPS' in param:\n self.HVCAPS = param['HVCAPS']\n self.HVCAPSgiven = True\n elif 'HVCAPS'.swapcase() in param:\n self.HVCAPS = param['HVCAPS'.swapcase()]\n self.HVCAPSgiven = True\n else:\n if self.HVCAPSgiven == False:\n self.HVCAPS = 0.0\n if 'IIMOD' in param:\n self.IIMOD = param['IIMOD']\n self.IIMODgiven = True\n elif 'IIMOD'.swapcase() in param:\n self.IIMOD = param['IIMOD'.swapcase()]\n self.IIMODgiven = True\n else:\n if self.IIMODgiven == False:\n self.IIMOD = 0.0\n if 'NDRIFTD' in param:\n self.NDRIFTD = param['NDRIFTD']\n self.NDRIFTDgiven = True\n elif 'NDRIFTD'.swapcase() in param:\n self.NDRIFTD = param['NDRIFTD'.swapcase()]\n self.NDRIFTDgiven = True\n else:\n if self.NDRIFTDgiven == False:\n self.NDRIFTD = 5e+16\n if 'VDRIFT' in param:\n self.VDRIFT = param['VDRIFT']\n self.VDRIFTgiven = True\n elif 'VDRIFT'.swapcase() in param:\n self.VDRIFT = param['VDRIFT'.swapcase()]\n self.VDRIFTgiven = True\n else:\n if self.VDRIFTgiven == False:\n self.VDRIFT = 100000.0\n if 'MDRIFT' in param:\n self.MDRIFT = param['MDRIFT']\n self.MDRIFTgiven = True\n elif 'MDRIFT'.swapcase() in param:\n self.MDRIFT = param['MDRIFT'.swapcase()]\n self.MDRIFTgiven = True\n else:\n if self.MDRIFTgiven == False:\n self.MDRIFT = 1.0\n if 'NDRIFTS' in param:\n self.NDRIFTS = param['NDRIFTS']\n self.NDRIFTSgiven = True\n elif 'NDRIFTS'.swapcase() in param:\n self.NDRIFTS = param['NDRIFTS'.swapcase()]\n self.NDRIFTSgiven = True\n else:\n if self.NDRIFTSgiven == False:\n self.NDRIFTS = self.NDRIFTD\n if 'RDLCW' in param:\n self.RDLCW = param['RDLCW']\n self.RDLCWgiven = True\n elif 'RDLCW'.swapcase() in param:\n self.RDLCW = param['RDLCW'.swapcase()]\n self.RDLCWgiven = True\n else:\n if self.RDLCWgiven == False:\n self.RDLCW = 100.0\n if 'RSLCW' in param:\n self.RSLCW = param['RSLCW']\n self.RSLCWgiven = True\n elif 'RSLCW'.swapcase() in param:\n self.RSLCW = param['RSLCW'.swapcase()]\n self.RSLCWgiven = True\n else:\n if self.RSLCWgiven == False:\n self.RSLCW = 0.0\n if 'PDRWB' in param:\n self.PDRWB = param['PDRWB']\n self.PDRWBgiven = True\n elif 'PDRWB'.swapcase() in param:\n self.PDRWB = param['PDRWB'.swapcase()]\n self.PDRWBgiven = True\n else:\n if self.PDRWBgiven == False:\n self.PDRWB = 0.0\n if 'VFBDRIFT' in param:\n self.VFBDRIFT = param['VFBDRIFT']\n self.VFBDRIFTgiven = True\n elif 'VFBDRIFT'.swapcase() in param:\n self.VFBDRIFT = param['VFBDRIFT'.swapcase()]\n self.VFBDRIFTgiven = True\n else:\n if self.VFBDRIFTgiven == False:\n self.VFBDRIFT = -1.0\n if 'VFBOV' in param:\n self.VFBOV = param['VFBOV']\n self.VFBOVgiven = True\n elif 'VFBOV'.swapcase() in param:\n self.VFBOV = param['VFBOV'.swapcase()]\n self.VFBOVgiven = True\n else:\n if self.VFBOVgiven == False:\n self.VFBOV = -1.0\n if 'LOVER' in param:\n self.LOVER = param['LOVER']\n self.LOVERgiven = True\n elif 'LOVER'.swapcase() in param:\n self.LOVER = param['LOVER'.swapcase()]\n self.LOVERgiven = True\n else:\n if self.LOVERgiven == False:\n self.LOVER = 5e-07\n if 'LOVERACC' in param:\n self.LOVERACC = param['LOVERACC']\n self.LOVERACCgiven = True\n elif 'LOVERACC'.swapcase() in param:\n self.LOVERACC = param['LOVERACC'.swapcase()]\n self.LOVERACCgiven = True\n else:\n if self.LOVERACCgiven == False:\n self.LOVERACC = self.LOVER\n if 'NDR' in param:\n self.NDR = param['NDR']\n self.NDRgiven = True\n elif 'NDR'.swapcase() in param:\n self.NDR = param['NDR'.swapcase()]\n self.NDRgiven = True\n else:\n if self.NDRgiven == False:\n self.NDR = self.NDEP\n if 'SLHV' in param:\n self.SLHV = param['SLHV']\n self.SLHVgiven = True\n elif 'SLHV'.swapcase() in param:\n self.SLHV = param['SLHV'.swapcase()]\n self.SLHVgiven = True\n else:\n if self.SLHVgiven == False:\n self.SLHV = 0.0\n if 'SLHV1' in param:\n self.SLHV1 = param['SLHV1']\n self.SLHV1given = True\n elif 'SLHV1'.swapcase() in param:\n self.SLHV1 = param['SLHV1'.swapcase()]\n self.SLHV1given = True\n else:\n if self.SLHV1given == False:\n self.SLHV1 = 1.0\n if 'ALPHADR' in param:\n self.ALPHADR = param['ALPHADR']\n self.ALPHADRgiven = True\n elif 'ALPHADR'.swapcase() in param:\n self.ALPHADR = param['ALPHADR'.swapcase()]\n self.ALPHADRgiven = True\n else:\n if self.ALPHADRgiven == False:\n self.ALPHADR = self.ALPHA0\n if 'BETADR' in param:\n self.BETADR = param['BETADR']\n self.BETADRgiven = True\n elif 'BETADR'.swapcase() in param:\n self.BETADR = param['BETADR'.swapcase()]\n self.BETADRgiven = True\n else:\n if self.BETADRgiven == False:\n self.BETADR = self.BETA0\n if 'PRTHV' in param:\n self.PRTHV = param['PRTHV']\n self.PRTHVgiven = True\n elif 'PRTHV'.swapcase() in param:\n self.PRTHV = param['PRTHV'.swapcase()]\n self.PRTHVgiven = True\n else:\n if self.PRTHVgiven == False:\n self.PRTHV = 0.0\n if 'ATHV' in param:\n self.ATHV = param['ATHV']\n self.ATHVgiven = True\n elif 'ATHV'.swapcase() in param:\n self.ATHV = param['ATHV'.swapcase()]\n self.ATHVgiven = True\n else:\n if self.ATHVgiven == False:\n self.ATHV = 0.0\n if 'HVFACTOR' in param:\n self.HVFACTOR = param['HVFACTOR']\n self.HVFACTORgiven = True\n elif 'HVFACTOR'.swapcase() in param:\n self.HVFACTOR = param['HVFACTOR'.swapcase()]\n self.HVFACTORgiven = True\n else:\n if self.HVFACTORgiven == False:\n self.HVFACTOR = 0.001\n if 'DRII1' in param:\n self.DRII1 = param['DRII1']\n self.DRII1given = True\n elif 'DRII1'.swapcase() in param:\n self.DRII1 = param['DRII1'.swapcase()]\n self.DRII1given = True\n else:\n if self.DRII1given == False:\n self.DRII1 = 1.0\n if 'DRII2' in param:\n self.DRII2 = param['DRII2']\n self.DRII2given = True\n elif 'DRII2'.swapcase() in param:\n self.DRII2 = param['DRII2'.swapcase()]\n self.DRII2given = True\n else:\n if self.DRII2given == False:\n self.DRII2 = 5.0\n if 'DELTAII' in param:\n self.DELTAII = param['DELTAII']\n self.DELTAIIgiven = True\n elif 'DELTAII'.swapcase() in param:\n self.DELTAII = param['DELTAII'.swapcase()]\n self.DELTAIIgiven = True\n else:\n if self.DELTAIIgiven == False:\n self.DELTAII = 0.5\n\n def _rdsmod(self, z):\n x, y = z\n f = np.zeros(2)\n f[0] = self.VD - x - self._calc(**{\"VD\":x, \"VS\":y}) * self.Rdrain\n f[1] = y - self.VS - self._calc(**{\"VD\":x, \"VS\":y}) * self.Rsource\n return f\n\n def get_id(self, **param): \n self.VDI, self.VSI = fsolve(self._rdsmod, [self.VD, self.VS])\n return self._calc(**{\"VD\":self.VDI, \"VS\":self.VSI})\n\n def _calc(self, **param):\n self.par_update(**param)\n # Bias-independent calculations\n if (self.TYPE == self.ntype):\n self.devsign = 1\n else:\n self.devsign = -1\n\n # Constants\n self.epssi = self.EPSRSUB * self.EPS0\n self.epsox = self.EPSROX * self.EPS0\n self.Cox = self.EPSROX * self.EPS0 / self.TOXE\n self.epsratio = self.EPSRSUB / self.EPSROX\n\n # Physical oxide thickness\n if self.TOXPgiven == False:\n self.BSIMBULKTOXP = (self.TOXE * self.EPSROX / 3.9) - self.DTOX\n else:\n self.BSIMBULKTOXP = self.TOXP\n self.L_mult = self.L * self.LMLT\n self.W_mult = self.W * self.WMLT\n self.Lnew = self.L_mult + self.XL\n if (self.Lnew <= 0.0):\n print(\"Fatal: Ldrawn * LMLT + XL = %e for %M is non-positive\", Lnew)\n self.W_by_NF = self.W_mult / self.NF\n self.Wnew = self.W_by_NF + self.XW\n if (self.Wnew <= 0.0):\n print(\"Fatal: W / NF * WMLT + XW = %e for %M is non-positive\", Wnew)\n\n # Leff and Weff for I-V\n self.L_LLN = self.Lnew**-self.LLN\n self.W_LWN = self.Wnew**-self.LWN\n self.LW_LLN_LWN = self.L_LLN * self.W_LWN\n self.dLIV = self.LINT + self.LL * self.L_LLN + self.LW * self.W_LWN + self.LWL * self.LW_LLN_LWN\n self.L_WLN = self.Lnew**-self.WLN\n self.W_WWN = self.Wnew**-self.WWN\n self.LW_WLN_WWN = self.L_WLN * self.W_WWN\n self.dWIV = self.WINT + self.WL * self.L_WLN + self.WW * self.W_WWN + self.WWL * self.LW_WLN_WWN\n self.Leff = self.Lnew - 2.0 * self.dLIV\n if (self.Leff <= 0.0):\n print(\"Fatal: Effective channel length = %e for %M is non-positive\", Leff)\n elif (self.Leff <= 1.0e-9):\n print(\"Warning: Effective channel length = %e for %M is <= 1.0e-9. Recommended Leff >= 1e-8\", Leff)\n self.Weff = self.Wnew - 2.0 * self.dWIV\n if (self.Weff <= 0.0):\n print(\"Fatal: Effective channel Width = %e for %M is non-positive\", Weff)\n elif (self.Weff <= 1.0e-9):\n print(\"Warning: Effective channel width = %e for %M is <= 1.0e-9. Recommended Weff >= 1e-8\", Weff)\n\n # Leff and Weff for C-V\n self.dLCV = self.DLC + self.LLC * self.L_LLN + self.LWC * self.W_LWN + self.LWLC * self.LW_LLN_LWN\n self.dWCV = self.DWC + self.WLC * self.L_WLN + self.WWC * self.W_WWN + self.WWLC * self.LW_WLN_WWN\n self.Lact = self.Lnew - 2.0 * self.dLCV\n if (self.Lact <= 0.0):\n print(\"Fatal: Effective channel length for C-V = %e for %M is non-positive\", Lact)\n elif (self.Lact <= 1.0e-9):\n print(\"Warning: Effective channel length for C-V = %e for %M is <= 1.0e-9. Recommended Lact >= 1e-8\", Lact)\n self.Wact = self.Wnew - 2.0 * self.dWCV\n if (self.Wact <= 0.0):\n print(\"Fatal: Effective channel width for C-V = %e for %M is non-positive\", Wact)\n elif (self.Wact <= 1.0e-9):\n print(\"Warning: Effective channel width for C-V = %e for %M is <= 1.0e-9. Recommended Wact >= 1e-8\", Wact)\n\n # Weffcj for diode, GIDL etc.\n self.dWJ = self.DWJ + self.WLC / self.Lnew**self.WLN + self.WWC / self.Wnew**self.WWN + self.WWLC / self.Lnew**self.WLN / self.Wnew**self.WWN\n self.Weffcj = self.Wnew - 2.0 * self.dWJ\n if (self.Weffcj <= 0.0):\n print(\"Fatal: Effective channel width for S/D junctions = %e for %M is non-positive\", Weffcj)\n self.Inv_L = 1.0e-6 / self.Leff\n self.Inv_W = 1.0e-6 / self.Weff\n self.Inv_Lact = 1.0e-6 / self.Lact\n self.Inv_Wact = 1.0e-6 / self.Wact\n self.Inv_Llong = 1.0e-6 / self.LLONG\n self.Inv_Wwide = 1.0e-6 / self.WWIDE\n self.Inv_WL = self.Inv_L * self.Inv_W\n\n # Effective length and width for binning\n self.L_LLN1 = self.L_LLN\n self.L_WLN1 = self.L_WLN\n if (self.DLBIN != 0.0):\n if (self.DLBIN <= -self.Lnew):\n print(\"Fatal: DLBIN for %M = %e is <= -Ldrawn * LMLT\", DLBIN)\n else:\n self.L_LLN1 = (self.Lnew + self.DLBIN)**-self.LLN\n self.L_WLN1 = (self.Lnew + self.DLBIN)**-self.WLN\n self.W_LWN1 = self.W_LWN\n self.W_WWN1 = self.W_WWN\n if (self.DWBIN != 0.0):\n if (self.DWBIN <= -self.Wnew):\n print(\"Fatal: DWBIN for %M = %e is <= -Wdrawn * WMLT\", DWBIN)\n else:\n self.W_LWN1 = (self.Wnew + self.DWBIN)**-self.LWN\n self.W_WWN1 = (self.Wnew + self.DWBIN)**-self.WWN\n self.LW_LLN_LWN1 = self.L_LLN1 * self.W_LWN1\n self.dLB = self.LINT + self.LL * self.L_LLN1 + self.LW * self.W_LWN1 + self.LWL * self.LW_LLN_LWN1\n self.LW_WLN_WWN1 = self.L_WLN1 * self.W_WWN1\n self.dWB = self.WINT + self.WL * self.L_WLN1 + self.WW * self.W_WWN1 + self.WWL * self.LW_WLN_WWN1\n self.Leff1 = self.Lnew - 2.0 * self.dLB + self.DLBIN\n if (self.Leff1 <= 0.0):\n print(\"Fatal: Effective channel length for binning = %e for %M is non-positive\", Leff1)\n self.Weff1 = self.Wnew - 2.0 * self.dWB + self.DWBIN\n if (self.Weff1 <= 0.0):\n print(\"Fatal: Effective channel width for binning = %e for %M is non-positive\", Weff1)\n if (self.BINUNIT == 1):\n self.BIN_L = 1.0e-6 / self.Leff1\n self.BIN_W = 1.0e-6 / self.Weff1\n else:\n self.BIN_L = 1.0 / self.Leff1\n self.BIN_W = 1.0 / self.Weff1\n self.BIN_WL = self.BIN_L * self.BIN_W\n self.VFB_i = self.VFB + self.BIN_L * self.LVFB + self.BIN_W * self.WVFB + self.BIN_WL * self.PVFB\n self.VFBCV_i = self.VFBCV + self.BIN_L * self.LVFBCV + self.BIN_W * self.WVFBCV + self.BIN_WL * self.PVFBCV\n self.NSD_i = self.NSD + self.BIN_L * self.LNSD + self.BIN_W * self.WNSD + self.BIN_WL * self.PNSD\n self.NDEP_i = self.NDEP + self.BIN_L * self.LNDEP + self.BIN_W * self.WNDEP + self.BIN_WL * self.PNDEP\n self.NDEPCV_i = self.NDEPCV + self.BIN_L * self.LNDEPCV + self.BIN_W * self.WNDEPCV + self.BIN_WL * self.PNDEPCV\n self.NGATE_i = self.NGATE + self.BIN_L * self.LNGATE + self.BIN_W * self.WNGATE + self.BIN_WL * self.PNGATE\n self.CIT_i = self.CIT + self.BIN_L * self.LCIT + self.BIN_W * self.WCIT + self.BIN_WL * self.PCIT\n self.NFACTOR_i = self.NFACTOR + self.BIN_L * self.LNFACTOR + self.BIN_W * self.WNFACTOR + self.BIN_WL * self.PNFACTOR\n self.CDSCD_i = self.CDSCD + self.BIN_L * self.LCDSCD + self.BIN_W * self.WCDSCD + self.BIN_WL * self.PCDSCD\n self.CDSCB_i = self.CDSCB + self.BIN_L * self.LCDSCB + self.BIN_W * self.WCDSCB + self.BIN_WL * self.PCDSCB\n self.DVTP0_i = self.DVTP0 + self.BIN_L * self.LDVTP0 + self.BIN_W * self.WDVTP0 + self.BIN_WL * self.PDVTP0\n self.DVTP1_i = self.DVTP1 + self.BIN_L * self.LDVTP1 + self.BIN_W * self.WDVTP1 + self.BIN_WL * self.PDVTP1\n self.DVTP2_i = self.DVTP2 + self.BIN_L * self.LDVTP2 + self.BIN_W * self.WDVTP2 + self.BIN_WL * self.PDVTP2\n self.DVTP3_i = self.DVTP3 + self.BIN_L * self.LDVTP3 + self.BIN_W * self.WDVTP3 + self.BIN_WL * self.PDVTP3\n self.DVTP4_i = self.DVTP4 + self.BIN_L * self.LDVTP4 + self.BIN_W * self.WDVTP4 + self.BIN_WL * self.PDVTP4\n self.DVTP5_i = self.DVTP5 + self.BIN_L * self.LDVTP5 + self.BIN_W * self.WDVTP5 + self.BIN_WL * self.PDVTP5\n self.K2_i = self.K2 + self.BIN_L * self.LK2 + self.BIN_W * self.WK2 + self.BIN_WL * self.PK2\n self.K1_i = self.K1 + self.BIN_L * self.LK1 + self.BIN_W * self.WK1 + self.BIN_WL * self.PK1\n self.XJ_i = self.XJ + self.BIN_L * self.LXJ + self.BIN_W * self.WXJ + self.BIN_WL * self.PXJ\n self.PHIN_i = self.PHIN + self.BIN_L * self.LPHIN + self.BIN_W * self.WPHIN + self.BIN_WL * self.PPHIN\n self.ETA0_i = self.ETA0 + self.BIN_L * self.LETA0 + self.BIN_W * self.WETA0 + self.BIN_WL * self.PETA0\n self.ETAB_i = self.ETAB + self.BIN_L * self.LETAB + self.BIN_W * self.WETAB + self.BIN_WL * self.PETAB\n self.DELTA_i = self.DELTA + self.BIN_L * self.LDELTA + self.BIN_W * self.WDELTA + self.BIN_WL * self.PDELTA\n self.U0_i = self.U0 + self.BIN_L * self.LU0 + self.BIN_W * self.WU0 + self.BIN_WL * self.PU0\n self.UA_i = self.UA + self.BIN_L * self.LUA + self.BIN_W * self.WUA + self.BIN_WL * self.PUA\n self.UD_i = self.UD + self.BIN_L * self.LUD + self.BIN_W * self.WUD + self.BIN_WL * self.PUD\n self.EU_i = self.EU + self.BIN_L * self.LEU + self.BIN_W * self.WEU + self.BIN_WL * self.PEU\n self.UCS_i = self.UCS + self.BIN_L * self.LUCS + self.BIN_W * self.WUCS + self.BIN_WL * self.PUCS\n self.UC_i = self.UC + self.BIN_L * self.LUC + self.BIN_W * self.WUC + self.BIN_WL * self.PUC\n self.PCLM_i = self.PCLM + self.BIN_L * self.LPCLM + self.BIN_W * self.WPCLM + self.BIN_WL * self.PPCLM\n self.PCLMCV_i = self.PCLMCV + self.BIN_L * self.LPCLMCV + self.BIN_W * self.WPCLMCV + self.BIN_WL * self.PPCLMCV\n self.RSW_i = self.RSW + self.BIN_L * self.LRSW + self.BIN_W * self.WRSW + self.BIN_WL * self.PRSW\n self.RDW_i = self.RDW + self.BIN_L * self.LRDW + self.BIN_W * self.WRDW + self.BIN_WL * self.PRDW\n self.PRWG_i = self.PRWG + self.BIN_L * self.LPRWG + self.BIN_W * self.WPRWG + self.BIN_WL * self.PPRWG\n self.PRWB_i = self.PRWB + self.BIN_L * self.LPRWB + self.BIN_W * self.WPRWB + self.BIN_WL * self.PPRWB\n self.WR_i = self.WR + self.BIN_L * self.LWR + self.BIN_W * self.WWR + self.BIN_WL * self.PWR\n self.RSWMIN_i = self.RSWMIN + self.BIN_L * self.LRSWMIN + self.BIN_W * self.WRSWMIN + self.BIN_WL * self.PRSWMIN\n self.RDWMIN_i = self.RDWMIN + self.BIN_L * self.LRDWMIN + self.BIN_W * self.WRDWMIN + self.BIN_WL * self.PRDWMIN\n self.RDSW_i = self.RDSW + self.BIN_L * self.LRDSW + self.BIN_W * self.WRDSW + self.BIN_WL * self.PRDSW\n self.RDSWMIN_i = self.RDSWMIN + self.BIN_L * self.LRDSWMIN + self.BIN_W * self.WRDSWMIN + self.BIN_WL * self.PRDSWMIN\n self.PTWG_i = self.PTWG + self.BIN_L * self.LPTWG + self.BIN_W * self.WPTWG + self.BIN_WL * self.PPTWG\n self.PDIBLC_i = self.PDIBLC + self.BIN_L * self.LPDIBLC + self.BIN_W * self.WPDIBLC + self.BIN_WL * self.PPDIBLC\n self.PDIBLCB_i = self.PDIBLCB + self.BIN_L * self.LPDIBLCB + self.BIN_W * self.WPDIBLCB + self.BIN_WL * self.PPDIBLCB\n self.PSCBE1_i = self.PSCBE1 + self.BIN_L * self.LPSCBE1 + self.BIN_W * self.WPSCBE1 + self.BIN_WL * self.PPSCBE1\n self.PSCBE2_i = self.PSCBE2 + self.BIN_L * self.LPSCBE2 + self.BIN_W * self.WPSCBE2 + self.BIN_WL * self.PPSCBE2\n self.PDITS_i = self.PDITS + self.BIN_L * self.LPDITS + self.BIN_W * self.WPDITS + self.BIN_WL * self.PPDITS\n self.PDITSD_i = self.PDITSD + self.BIN_L * self.LPDITSD + self.BIN_W * self.WPDITSD + self.BIN_WL * self.PPDITSD\n self.FPROUT_i = self.FPROUT + self.BIN_L * self.LFPROUT + self.BIN_W * self.WFPROUT + self.BIN_WL * self.PFPROUT\n self.PVAG_i = self.PVAG + self.BIN_L * self.LPVAG + self.BIN_W * self.WPVAG + self.BIN_WL * self.PPVAG\n self.VSAT_i = self.VSAT + self.BIN_L * self.LVSAT + self.BIN_W * self.WVSAT + self.BIN_WL * self.PVSAT\n self.PSAT_i = self.PSAT + self.BIN_L * self.LPSAT + self.BIN_W * self.WPSAT + self.BIN_WL * self.PPSAT\n self.VSATCV_i = self.VSATCV + self.BIN_L * self.LVSATCV + self.BIN_W * self.WVSATCV + self.BIN_WL * self.PVSATCV\n self.CF_i = self.CF + self.BIN_L * self.LCF + self.BIN_W * self.WCF + self.BIN_WL * self.PCF\n self.CGSL_i = self.CGSL + self.BIN_L * self.LCGSL + self.BIN_W * self.WCGSL + self.BIN_WL * self.PCGSL\n self.CGDL_i = self.CGDL + self.BIN_L * self.LCGDL + self.BIN_W * self.WCGDL + self.BIN_WL * self.PCGDL\n self.CKAPPAS_i = self.CKAPPAS + self.BIN_L * self.LCKAPPAS + self.BIN_W * self.WCKAPPAS + self.BIN_WL * self.PCKAPPAS\n self.CKAPPAD_i = self.CKAPPAD + self.BIN_L * self.LCKAPPAD + self.BIN_W * self.WCKAPPAD + self.BIN_WL * self.PCKAPPAD\n self.ALPHA0_i = self.ALPHA0 + self.BIN_L * self.LALPHA0 + self.BIN_W * self.WALPHA0 + self.BIN_WL * self.PALPHA0\n self.BETA0_i = self.BETA0 + self.BIN_L * self.LBETA0 + self.BIN_W * self.WBETA0 + self.BIN_WL * self.PBETA0\n self.KVTH0WE_i = self.KVTH0WE + self.BIN_L * self.LKVTH0WE + self.BIN_W * self.WKVTH0WE + self.BIN_WL * self.PKVTH0WE\n self.K2WE_i = self.K2WE + self.BIN_L * self.LK2WE + self.BIN_W * self.WK2WE + self.BIN_WL * self.PK2WE\n self.KU0WE_i = self.KU0WE + self.BIN_L * self.LKU0WE + self.BIN_W * self.WKU0WE + self.BIN_WL * self.PKU0WE\n self.AGIDL_i = self.AGIDL + self.BIN_L * self.LAGIDL + self.BIN_W * self.WAGIDL + self.BIN_WL * self.PAGIDL\n self.BGIDL_i = self.BGIDL + self.BIN_L * self.LBGIDL + self.BIN_W * self.WBGIDL + self.BIN_WL * self.PBGIDL\n self.CGIDL_i = self.CGIDL + self.BIN_L * self.LCGIDL + self.BIN_W * self.WCGIDL + self.BIN_WL * self.PCGIDL\n self.EGIDL_i = self.EGIDL + self.BIN_L * self.LEGIDL + self.BIN_W * self.WEGIDL + self.BIN_WL * self.PEGIDL\n self.AGISL_i = self.AGISL + self.BIN_L * self.LAGISL + self.BIN_W * self.WAGISL + self.BIN_WL * self.PAGISL\n self.BGISL_i = self.BGISL + self.BIN_L * self.LBGISL + self.BIN_W * self.WBGISL + self.BIN_WL * self.PBGISL\n self.CGISL_i = self.CGISL + self.BIN_L * self.LCGISL + self.BIN_W * self.WCGISL + self.BIN_WL * self.PCGISL\n self.EGISL_i = self.EGISL + self.BIN_L * self.LEGISL + self.BIN_W * self.WEGISL + self.BIN_WL * self.PEGISL\n self.UTE_i = self.UTE + self.BIN_L * self.LUTE + self.BIN_W * self.WUTE + self.BIN_WL * self.PUTE\n self.UA1_i = self.UA1 + self.BIN_L * self.LUA1 + self.BIN_W * self.WUA1 + self.BIN_WL * self.PUA1\n self.UC1_i = self.UC1 + self.BIN_L * self.LUC1 + self.BIN_W * self.WUC1 + self.BIN_WL * self.PUC1\n self.UD1_i = self.UD1 + self.BIN_L * self.LUD1 + self.BIN_W * self.WUD1 + self.BIN_WL * self.PUD1\n self.EU1_i = self.EU1 + self.BIN_L * self.LEU1 + self.BIN_W * self.WEU1 + self.BIN_WL * self.PEU1\n self.UCSTE_i = self.UCSTE + self.BIN_L * self.LUCSTE + self.BIN_W * self.WUCSTE + self.BIN_WL * self.PUCSTE\n self.PRT_i = self.PRT + self.BIN_L * self.LPRT + self.BIN_W * self.WPRT + self.BIN_WL * self.PPRT\n self.AT_i = self.AT + self.BIN_L * self.LAT + self.BIN_W * self.WAT + self.BIN_WL * self.PAT\n self.PTWGT_i = self.PTWGT + self.BIN_L * self.LPTWGT + self.BIN_W * self.WPTWGT + self.BIN_WL * self.PPTWGT\n self.IIT_i = self.IIT + self.BIN_L * self.LIIT + self.BIN_W * self.WIIT + self.BIN_WL * self.PIIT\n self.TGIDL_i = self.TGIDL + self.BIN_L * self.LTGIDL + self.BIN_W * self.WTGIDL + self.BIN_WL * self.PTGIDL\n self.IGT_i = self.IGT + self.BIN_L * self.LIGT + self.BIN_W * self.WIGT + self.BIN_WL * self.PIGT\n self.AIGBINV_i = self.AIGBINV + self.BIN_L * self.LAIGBINV + self.BIN_W * self.WAIGBINV + self.BIN_WL * self.PAIGBINV\n self.BIGBINV_i = self.BIGBINV + self.BIN_L * self.LBIGBINV + self.BIN_W * self.WBIGBINV + self.BIN_WL * self.PBIGBINV\n self.CIGBINV_i = self.CIGBINV + self.BIN_L * self.LCIGBINV + self.BIN_W * self.WCIGBINV + self.BIN_WL * self.PCIGBINV\n self.EIGBINV_i = self.EIGBINV + self.BIN_L * self.LEIGBINV + self.BIN_W * self.WEIGBINV + self.BIN_WL * self.PEIGBINV\n self.NIGBINV_i = self.NIGBINV + self.BIN_L * self.LNIGBINV + self.BIN_W * self.WNIGBINV + self.BIN_WL * self.PNIGBINV\n self.AIGBACC_i = self.AIGBACC + self.BIN_L * self.LAIGBACC + self.BIN_W * self.WAIGBACC + self.BIN_WL * self.PAIGBACC\n self.BIGBACC_i = self.BIGBACC + self.BIN_L * self.LBIGBACC + self.BIN_W * self.WBIGBACC + self.BIN_WL * self.PBIGBACC\n self.CIGBACC_i = self.CIGBACC + self.BIN_L * self.LCIGBACC + self.BIN_W * self.WCIGBACC + self.BIN_WL * self.PCIGBACC\n self.NIGBACC_i = self.NIGBACC + self.BIN_L * self.LNIGBACC + self.BIN_W * self.WNIGBACC + self.BIN_WL * self.PNIGBACC\n self.AIGC_i = self.AIGC + self.BIN_L * self.LAIGC + self.BIN_W * self.WAIGC + self.BIN_WL * self.PAIGC\n self.BIGC_i = self.BIGC + self.BIN_L * self.LBIGC + self.BIN_W * self.WBIGC + self.BIN_WL * self.PBIGC\n self.CIGC_i = self.CIGC + self.BIN_L * self.LCIGC + self.BIN_W * self.WCIGC + self.BIN_WL * self.PCIGC\n self.AIGS_i = self.AIGS + self.BIN_L * self.LAIGS + self.BIN_W * self.WAIGS + self.BIN_WL * self.PAIGS\n self.BIGS_i = self.BIGS + self.BIN_L * self.LBIGS + self.BIN_W * self.WBIGS + self.BIN_WL * self.PBIGS\n self.CIGS_i = self.CIGS + self.BIN_L * self.LCIGS + self.BIN_W * self.WCIGS + self.BIN_WL * self.PCIGS\n self.AIGD_i = self.AIGD + self.BIN_L * self.LAIGD + self.BIN_W * self.WAIGD + self.BIN_WL * self.PAIGD\n self.BIGD_i = self.BIGD + self.BIN_L * self.LBIGD + self.BIN_W * self.WBIGD + self.BIN_WL * self.PBIGD\n self.CIGD_i = self.CIGD + self.BIN_L * self.LCIGD + self.BIN_W * self.WCIGD + self.BIN_WL * self.PCIGD\n self.POXEDGE_i = self.POXEDGE + self.BIN_L * self.LPOXEDGE + self.BIN_W * self.WPOXEDGE + self.BIN_WL * self.PPOXEDGE\n self.DLCIG_i = self.DLCIG + self.BIN_L * self.LDLCIG + self.BIN_W * self.WDLCIG + self.BIN_WL * self.PDLCIG\n self.DLCIGD_i = self.DLCIGD + self.BIN_L * self.LDLCIGD + self.BIN_W * self.WDLCIGD + self.BIN_WL * self.PDLCIGD\n self.NTOX_i = self.NTOX + self.BIN_L * self.LNTOX + self.BIN_W * self.WNTOX + self.BIN_WL * self.PNTOX\n self.KT1_i = self.KT1 + self.BIN_L * self.LKT1 + self.BIN_W * self.WKT1 + self.BIN_WL * self.PKT1\n self.KT2_i = self.KT2 + self.BIN_L * self.LKT2 + self.BIN_W * self.WKT2 + self.BIN_WL * self.PKT2\n self.PSATB_i = self.PSATB + self.BIN_L * self.LPSATB + self.BIN_W * self.WPSATB + self.BIN_WL * self.PPSATB\n self.A1_i = self.A1 + self.BIN_L * self.LA1 + self.BIN_W * self.WA1 + self.BIN_WL * self.PA1\n self.A11_i = self.A11 + self.BIN_L * self.LA11 + self.BIN_W * self.WA11 + self.BIN_WL * self.PA11\n self.A2_i = self.A2 + self.BIN_L * self.LA2 + self.BIN_W * self.WA2 + self.BIN_WL * self.PA2\n self.A21_i = self.A21 + self.BIN_L * self.LA21 + self.BIN_W * self.WA21 + self.BIN_WL * self.PA21\n self.K0_i = self.K0 + self.BIN_L * self.LK0 + self.BIN_W * self.WK0 + self.BIN_WL * self.PK0\n self.M0_i = self.M0 + self.BIN_L * self.LM0 + self.BIN_W * self.WM0 + self.BIN_WL * self.PM0\n self.K01_i = self.K01 + self.BIN_L * self.LK01 + self.BIN_W * self.WK01 + self.BIN_WL * self.PK01\n self.M01_i = self.M01 + self.BIN_L * self.LM01 + self.BIN_W * self.WM01 + self.BIN_WL * self.PM01\n self.NFACTOREDGE_i = self.NFACTOREDGE + self.BIN_L * self.LNFACTOREDGE + self.BIN_W * self.WNFACTOREDGE + self.BIN_WL * self.PNFACTOREDGE\n self.NDEPEDGE_i = self.NDEPEDGE + self.BIN_L * self.LNDEPEDGE + self.BIN_W * self.WNDEPEDGE + self.BIN_WL * self.PNDEPEDGE\n self.CITEDGE_i = self.CITEDGE + self.BIN_L * self.LCITEDGE + self.BIN_W * self.WCITEDGE + self.BIN_WL * self.PCITEDGE\n self.CDSCDEDGE_i = self.CDSCDEDGE + self.BIN_L * self.LCDSCDEDGE + self.BIN_W * self.WCDSCDEDGE + self.BIN_WL * self.PCDSCDEDGE\n self.CDSCBEDGE_i = self.CDSCBEDGE + self.BIN_L * self.LCDSCBEDGE + self.BIN_W * self.WCDSCBEDGE + self.BIN_WL * self.PCDSCBEDGE\n self.ETA0EDGE_i = self.ETA0EDGE + self.BIN_L * self.LETA0EDGE + self.BIN_W * self.WETA0EDGE + self.BIN_WL * self.PETA0EDGE\n self.ETABEDGE_i = self.ETABEDGE + self.BIN_L * self.LETABEDGE + self.BIN_W * self.WETABEDGE + self.BIN_WL * self.PETABEDGE\n self.KT1EDGE_i = self.KT1EDGE + self.BIN_L * self.LKT1EDGE + self.BIN_W * self.WKT1EDGE + self.BIN_WL * self.PKT1EDGE\n self.KT1LEDGE_i = self.KT1LEDGE + self.BIN_L * self.LKT1LEDGE + self.BIN_W * self.WKT1LEDGE + self.BIN_WL * self.PKT1LEDGE\n self.KT2EDGE_i = self.KT2EDGE + self.BIN_L * self.LKT2EDGE + self.BIN_W * self.WKT2EDGE + self.BIN_WL * self.PKT2EDGE\n self.KT1EXPEDGE_i = self.KT1EXPEDGE + self.BIN_L * self.LKT1EXPEDGE + self.BIN_W * self.WKT1EXPEDGE + self.BIN_WL * self.PKT1EXPEDGE\n self.TNFACTOREDGE_i = self.TNFACTOREDGE + self.BIN_L * self.LTNFACTOREDGE + self.BIN_W * self.WTNFACTOREDGE + self.BIN_WL * self.PTNFACTOREDGE\n self.TETA0EDGE_i = self.TETA0EDGE + self.BIN_L * self.LTETA0EDGE + self.BIN_W * self.WTETA0EDGE + self.BIN_WL * self.PTETA0EDGE\n self.K2EDGE_i = self.K2EDGE + self.BIN_L * self.LK2EDGE + self.BIN_W * self.WK2EDGE + self.BIN_WL * self.PK2EDGE\n self.KVTH0EDGE_i = self.KVTH0EDGE + self.BIN_L * self.LKVTH0EDGE + self.BIN_W * self.WKVTH0EDGE + self.BIN_WL * self.PKVTH0EDGE\n self.STK2EDGE_i = self.STK2EDGE + self.BIN_L * self.LSTK2EDGE + self.BIN_W * self.WSTK2EDGE + self.BIN_WL * self.PSTK2EDGE\n self.STETA0EDGE_i = self.STETA0EDGE + self.BIN_L * self.LSTETA0EDGE + self.BIN_W * self.WSTETA0EDGE + self.BIN_WL * self.PSTETA0EDGE\n self.C0_i = self.C0 + self.BIN_L * self.LC0 + self.BIN_W * self.WC0 + self.BIN_WL * self.PC0\n self.C01_i = self.C01 + self.BIN_L * self.LC01 + self.BIN_W * self.WC01 + self.BIN_WL * self.PC01\n self.C0SI_i = self.C0SI + self.BIN_L * self.LC0SI + self.BIN_W * self.WC0SI + self.BIN_WL * self.PC0SI\n self.C0SI1_i = self.C0SI1 + self.BIN_L * self.LC0SI1 + self.BIN_W * self.WC0SI1 + self.BIN_WL * self.PC0SI1\n self.C0SISAT_i = self.C0SISAT + self.BIN_L * self.LC0SISAT + self.BIN_W * self.WC0SISAT + self.BIN_WL * self.PC0SISAT\n self.C0SISAT1_i = self.C0SISAT1 + self.BIN_L * self.LC0SISAT1 + self.BIN_W * self.WC0SISAT1 + self.BIN_WL * self.PC0SISAT1\n\n if (self.ASYMMOD != 0):\n self.CDSCDR_i = self.CDSCDR + self.BIN_L * self.LCDSCDR + self.BIN_W * self.WCDSCDR + self.BIN_WL * self.PCDSCDR\n self.ETA0R_i = self.ETA0R + self.BIN_L * self.LETA0R + self.BIN_W * self.WETA0R + self.BIN_WL * self.PETA0R\n self.U0R_i = self.U0R + self.BIN_L * self.LU0R + self.BIN_W * self.WU0R + self.BIN_WL * self.PU0R\n self.UAR_i = self.UAR + self.BIN_L * self.LUAR + self.BIN_W * self.WUAR + self.BIN_WL * self.PUAR\n self.UDR_i = self.UDR + self.BIN_L * self.LUDR + self.BIN_W * self.WUDR + self.BIN_WL * self.PUDR\n self.UCSR_i = self.UCSR + self.BIN_L * self.LUCSR + self.BIN_W * self.WUCSR + self.BIN_WL * self.PUCSR\n self.UCR_i = self.UCR + self.BIN_L * self.LUCR + self.BIN_W * self.WUCR + self.BIN_WL * self.PUCR\n self.PCLMR_i = self.PCLMR + self.BIN_L * self.LPCLMR + self.BIN_W * self.WPCLMR + self.BIN_WL * self.PPCLMR\n self.PDIBLCR_i = self.PDIBLCR + self.BIN_L * self.LPDIBLCR + self.BIN_W * self.WPDIBLCR + self.BIN_WL * self.PPDIBLCR\n self.VSATR_i = self.VSATR + self.BIN_L * self.LVSATR + self.BIN_W * self.WVSATR + self.BIN_WL * self.PVSATR\n self.PSATR_i = self.PSATR + self.BIN_L * self.LPSATR + self.BIN_W * self.WPSATR + self.BIN_WL * self.PPSATR\n self.PTWGR_i = self.PTWGR + self.BIN_L * self.LPTWGR + self.BIN_W * self.WPTWGR + self.BIN_WL * self.PPTWGR\n else:\n self.CDSCDR_i = 0.0\n self.ETA0R_i = 0.0\n self.U0R_i = 0.0\n self.UAR_i = 0.0\n self.UDR_i = 0.0\n self.UCSR_i = 0.0\n self.UCR_i = 0.0\n self.PCLMR_i = 0.0\n self.PDIBLCR_i = 0.0\n self.VSATR_i = 0.0\n self.PSATR_i = 0.0\n self.PTWGR_i = 0.0\n\n # Geometrical scaling\n self.T0 = self.NDEPL1 * max(self.Inv_L**self.NDEPLEXP1 - self.Inv_Llong**self.NDEPLEXP1, 0.0) + self.NDEPL2 * max(self.Inv_L**self.NDEPLEXP2 - self.Inv_Llong**self.NDEPLEXP2, 0.0)\n self.T1 = self.NDEPW * max(self.Inv_W**self.NDEPWEXP - self.Inv_Wwide**self.NDEPWEXP, 0.0) + self.NDEPWL * (self.Inv_W * self.Inv_L)**self.NDEPWLEXP\n self.NDEP_i = self.NDEP_i * (1.0 + self.T0 + self.T1)\n self.T0 = self.NFACTORL * max(self.Inv_L**self.NFACTORLEXP - self.Inv_Llong**self.NFACTORLEXP, 0.0)\n self.T1 = self.NFACTORW * max(self.Inv_W**self.NFACTORWEXP - self.Inv_Wwide**self.NFACTORWEXP, 0.0) + self.NFACTORWL * self.Inv_WL**self.NFACTORWLEXP\n self.NFACTOR_i = self.NFACTOR_i * (1.0 + self.T0 + self.T1)\n self.T0 = (1.0 + self.CDSCDL * max(self.Inv_L**self.CDSCDLEXP - self.Inv_Llong**self.CDSCDLEXP, 0.0))\n self.CDSCD_i = self.CDSCD_i * self.T0\n if (self.ASYMMOD != 0):\n self.CDSCDR_i = self.CDSCDR_i * self.T0\n self.CDSCB_i = self.CDSCB_i * (1.0 + self.CDSCBL * max(self.Inv_L**self.CDSCBLEXP - self.Inv_Llong**self.CDSCBLEXP, 0.0))\n self.U0_i = self.MULU0 * self.U0_i\n if (self.MOBSCALE != 1):\n if (self.U0LEXP > 0.0):\n self.U0_i = self.U0_i * (1.0 - self.U0L * max(self.Inv_L**self.U0LEXP - self.Inv_Llong**self.U0LEXP, 0.0))\n if (self.ASYMMOD != 0):\n self.U0R_i = self.U0R_i * (1.0 - self.U0L * max(self.Inv_L**self.U0LEXP - self.Inv_Llong**self.U0LEXP, 0.0))\n else:\n self.U0_i = self.U0_i * (1.0 - self.U0L)\n if (self.ASYMMOD != 0):\n self.U0R_i = self.U0R_i * (1.0 - self.U0L)\n else:\n self.U0_i = self.U0_i * (1.0 - (self.UP1 * self.lexp(-self.Leff / self.LP1)) - (self.UP2 * self.lexp(-self.Leff / self.LP2)))\n if (self.ASYMMOD != 0):\n self.U0R_i = self.U0R_i * (1.0 - (self.UP1 * self.lexp(-self.Leff / self.LP1)) - (self.UP2 * self.lexp(-self.Leff / self.LP2)))\n self.T0 = self.UAL * max(self.Inv_L**self.UALEXP - self.Inv_Llong**self.UALEXP, 0.0)\n self.T1 = self.UAW * max(self.Inv_W**self.UAWEXP - self.Inv_Wwide**self.UAWEXP, 0.0) + self.UAWL * self.Inv_WL**self.UAWLEXP\n self.UA_i = self.UA_i * (1.0 + self.T0 + self.T1)\n if (self.ASYMMOD != 0):\n self.UAR_i = self.UAR_i * (1.0 + self.T0 + self.T1)\n self.T0 = self.EUL * max(self.Inv_L**self.EULEXP - self.Inv_Llong**self.EULEXP, 0.0)\n self.T1 = self.EUW * max(self.Inv_W**self.EUWEXP - self.Inv_Wwide**self.EUWEXP, 0.0) + self.EUWL * self.Inv_WL**self.EUWLEXP\n self.EU_i = self.EU_i * (1.0 + self.T0 + self.T1)\n self.T0 = 1.0 + self.UDL * max(self.Inv_L**self.UDLEXP - self.Inv_Llong**self.UDLEXP, 0.0)\n self.UD_i = self.UD_i * self.T0\n if (self.ASYMMOD != 0):\n self.UDR_i = self.UDR_i * self.T0\n self.T0 = self.UCL * max(self.Inv_L**self.UCLEXP - self.Inv_Llong**self.UCLEXP, 0.0)\n self.T1 = self.UCW * max(self.Inv_W**self.UCWEXP - self.Inv_Wwide**self.UCWEXP, 0.0) + self.UCWL * self.Inv_WL**self.UCWLEXP\n self.UC_i = self.UC_i * (1.0 + self.T0 + self.T1)\n if (self.ASYMMOD != 0):\n self.UCR_i = self.UCR_i * (1.0 + self.T0 + self.T1)\n self.T0 = max(self.Inv_L**self.DSUB - self.Inv_Llong**self.DSUB, 0.0)\n self.ETA0_i = self.ETA0_i * self.T0\n if (self.ASYMMOD != 0):\n self.ETA0R_i = self.ETA0R_i * self.T0\n self.ETAB_i = self.ETAB_i * max(self.Inv_L**self.ETABEXP - self.Inv_Llong**self.ETABEXP, 0.0)\n self.T0 = 1.0 + self.PDIBLCL * max(self.Inv_L**self.PDIBLCLEXP - self.Inv_Llong**self.PDIBLCLEXP, 0.0)\n self.PDIBLC_i = self.PDIBLC_i * self.T0\n if (self.ASYMMOD != 0):\n self.PDIBLCR_i = self.PDIBLCR_i * self.T0\n self.T0 = self.DELTA_i * (1.0 + self.DELTAL * max(self.Inv_L**self.DELTALEXP - self.Inv_Llong**self.DELTALEXP, 0.0))\n self.DELTA_i = min(self.T0, 0.5)\n self.FPROUT_i = self.FPROUT_i * (1.0 + self.FPROUTL * max(self.Inv_L**self.FPROUTLEXP - self.Inv_Llong**self.FPROUTLEXP, 0.0))\n self.T0 = (1.0 + self.PCLML * max(self.Inv_L**self.PCLMLEXP - self.Inv_Llong**self.PCLMLEXP, 0.0))\n self.PCLM_i = self.PCLM_i * self.T0\n self.PCLM_i = max(self.PCLM_i, 0.0)\n if (self.ASYMMOD != 0):\n self.PCLMR_i = self.PCLMR_i * self.T0\n self.PCLMR_i = max(self.PCLMR_i, 0.0)\n self.T0 = self.VSATL * max(self.Inv_L**self.VSATLEXP - self.Inv_Llong**self.VSATLEXP, 0.0)\n self.T1 = self.VSATW * max(self.Inv_W**self.VSATWEXP - self.Inv_Wwide**self.VSATWEXP, 0.0) + self.VSATWL * self.Inv_WL**self.VSATWLEXP\n self.VSAT_i = self.VSAT_i * (1.0 + self.T0 + self.T1)\n if (self.ASYMMOD != 0):\n self.VSATR_i = self.VSATR_i * (1.0 + self.T0 + self.T1)\n self.PSAT_i = max(self.PSAT_i * (1.0 + self.PSATL * max(self.Inv_L**self.PSATLEXP - self.Inv_Llong**self.PSATLEXP, 0.0)), 0.25)\n if (self.ASYMMOD != 0):\n self.PSATR_i = max(self.PSATR_i * (1.0 + self.PSATL * max(self.Inv_L**self.PSATLEXP - self.Inv_Llong**self.PSATLEXP, 0.0)), 0.25)\n self.T0 = (1.0 + self.PTWGL * max(self.Inv_L**self.PTWGLEXP - self.Inv_Llong**self.PTWGLEXP, 0.0))\n self.PTWG_i = self.PTWG_i * self.T0\n if (self.ASYMMOD != 0):\n self.PTWGR_i = self.PTWGR_i * self.T0\n self.ALPHA0_i = self.ALPHA0_i * (1.0 + self.ALPHA0L * max(self.Inv_L**self.ALPHA0LEXP - self.Inv_Llong**self.ALPHA0LEXP, 0.0))\n self.AGIDL_i = self.AGIDL_i * (1.0 + self.AGIDLL * self.Inv_L + self.AGIDLW * self.Inv_W)\n self.AGISL_i = self.AGISL_i * (1.0 + self.AGISLL * self.Inv_L + self.AGISLW * self.Inv_W)\n self.AIGC_i = self.AIGC_i * (1.0 + self.AIGCL * self.Inv_L + self.AIGCW * self.Inv_W)\n self.AIGS_i = self.AIGS_i * (1.0 + self.AIGSL * self.Inv_L + self.AIGSW * self.Inv_W)\n self.AIGD_i = self.AIGD_i * (1.0 + self.AIGDL * self.Inv_L + self.AIGDW * self.Inv_W)\n self.PIGCD_i = self.PIGCD * (1.0 + self.PIGCDL * self.Inv_L)\n self.T0 = self.NDEPCVL1 * max(self.Inv_Lact**self.NDEPCVLEXP1 - self.Inv_Llong**self.NDEPCVLEXP1, 0.0) + self.NDEPCVL2 * max(self.Inv_Lact**self.NDEPCVLEXP2 - self.Inv_Llong**self.NDEPCVLEXP2, 0.0)\n self.T1 = self.NDEPCVW * max(self.Inv_Wact**self.NDEPCVWEXP - self.Inv_Wwide**self.NDEPCVWEXP, 0.0) + self.NDEPCVWL * (self.Inv_Wact * self.Inv_Lact)**self.NDEPCVWLEXP\n self.NDEPCV_i = self.NDEPCV_i * (1.0 + self.T0 + self.T1)\n self.T0 = self.VFBCVL * max(self.Inv_Lact**self.VFBCVLEXP - self.Inv_Llong**self.VFBCVLEXP, 0.0)\n self.T1 = self.VFBCVW * max(self.Inv_Wact**self.VFBCVWEXP - self.Inv_Wwide**self.VFBCVWEXP, 0.0) + self.VFBCVWL * self.Inv_WL**self.VFBCVWLEXP\n self.VFBCV_i = self.VFBCV_i * (1.0 + self.T0 + self.T1)\n self.T0 = self.VSATCVL * max(self.Inv_Lact**self.VSATCVLEXP - self.Inv_Llong**self.VSATCVLEXP, 0.0)\n self.T1 = self.VSATCVW * max(self.Inv_W**self.VSATCVWEXP - self.Inv_Wwide**self.VSATCVWEXP, 0.0) + self.VSATCVWL * self.Inv_WL**self.VSATCVWLEXP\n self.VSATCV_i = self.VSATCV_i * (1.0 + self.T0 + self.T1)\n self.PCLMCV_i = self.PCLMCV_i * (1.0 + self.PCLMCVL * max(self.Inv_Lact**self.PCLMCVLEXP - self.Inv_Llong**self.PCLMCVLEXP, 0.0))\n self.PCLMCV_i = max(self.PCLMCV_i, 0.0)\n self.T0 = self.K1L * max(self.Inv_L**self.K1LEXP - self.Inv_Llong**self.K1LEXP, 0.0)\n self.T1 = self.K1W * max(self.Inv_W**self.K1WEXP - self.Inv_Wwide**self.K1WEXP, 0.0) + self.K1WL * self.Inv_WL**self.K1WLEXP\n self.K1_i = self.K1_i * (1.0 + self.T0 + self.T1)\n self.T0 = self.K2L * max(self.Inv_L**self.K2LEXP - self.Inv_Llong**self.K2LEXP, 0.0)\n self.T1 = self.K2W * max(self.Inv_W**self.K2WEXP - self.Inv_Wwide**self.K2WEXP, 0.0) + self.K2WL * self.Inv_WL**self.K2WLEXP\n self.K2_i = self.K2_i * (1.0 + self.T0 + self.T1)\n self.PRWB_i = self.PRWB_i * (1.0 + self.PRWBL * max(self.Inv_L**self.PRWBLEXP - self.Inv_Llong**self.PRWBLEXP, 0.0))\n\n # Global scaling parameters for temperature\n self.UTE_i = self.UTE_i * (1.0 + self.Inv_L * self.UTEL)\n self.UA1_i = self.UA1_i * (1.0 + self.Inv_L * self.UA1L)\n self.UD1_i = self.UD1_i * (1.0 + self.Inv_L * self.UD1L)\n self.AT_i = self.AT_i * (1.0 + self.Inv_L * self.ATL)\n self.PTWGT_i = self.PTWGT_i * (1.0 + self.Inv_L * self.PTWGTL)\n\n if (self.RDSMOD == 1):\n self.RSW_i = self.RSW_i * (1.0 + self.RSWL * max(self.Inv_L**self.RSWLEXP - self.Inv_Llong**self.RSWLEXP, 0.0))\n self.RDW_i = self.RDW_i * (1.0 + self.RDWL * max(self.Inv_L**self.RDWLEXP - self.Inv_Llong**self.RDWLEXP, 0.0))\n else:\n self.RDSW_i = self.RDSW_i * (1.0 + self.RDSWL * max(self.Inv_L**self.RDSWLEXP - self.Inv_Llong**self.RDSWLEXP, 0.0))\n\n # Parameter checking\n if (self.UCS_i < 1.0):\n self.UCS_i = 1.0\n elif (self.UCS_i > 2.0):\n self.UCS_i = 2.0\n if (self.ASYMMOD != 0):\n if (self.UCSR_i < 1.0):\n self.UCSR_i = 1.0\n elif (self.UCSR_i > 2.0):\n self.UCSR_i = 2.0\n if (self.CGIDL_i < 0.0):\n print(\"Fatal: CGIDL_i = %e is negative.\", CGIDL_i)\n if (self.CGISL_i < 0.0):\n print(\"Fatal: CGISL_i = %e is negative.\", CGISL_i)\n if (self.CKAPPAD_i <= 0.0):\n print(\"Fatal: CKAPPAD_i = %e is non-positive.\", CKAPPAD_i)\n if (self.CKAPPAS_i <= 0.0):\n print(\"Fatal: CKAPPAS_i = %e is non-positive.\", CKAPPAS_i)\n if (self.PDITS_i < 0.0):\n print(\"Fatal: PDITS_i = %e is negative.\", PDITS_i)\n if (self.CIT_i < 0.0):\n print(\"Fatal: CIT_i = %e is negative.\", CIT_i)\n if (self.NFACTOR_i < 0.0):\n print(\"Fatal: NFACTOR_i = %e is negative.\", NFACTOR_i)\n if (self.K1_i < 0.0):\n print(\"Fatal: K1_i = %e is negative.\", K1_i)\n if (self.NSD_i <= 0.0):\n print(\"Fatal: NSD_i = %e is non-positive.\", NSD_i)\n if (self.NDEP_i <= 0.0):\n print(\"Fatal: NDEP_i = %e is non-positive.\", NDEP_i)\n if (self.NDEPCV_i <= 0.0):\n print(\"Fatal: NDEPCV_i = %e is non-positive.\", NDEPCV_i)\n if (self.IGBMOD != 0):\n if (self.NIGBINV_i <= 0.0):\n print(\"Fatal: NIGBINV_i = %e is non-positive.\", NIGBINV_i)\n if (self.NIGBACC_i <= 0.0):\n print(\"Fatal: NIGBACC_i = %e is non-positive.\", NIGBACC_i)\n if (self.IGCMOD != 0):\n if (self.POXEDGE_i <= 0.0):\n print(\"Fatal: POXEDGE_i = %e is non-positive.\", POXEDGE_i)\n if (self.CDSCD_i < 0.0):\n print(\"Fatal: CDSCD_i = %e is negative.\", CDSCD_i)\n if (self.ASYMMOD != 0):\n if (self.CDSCDR_i < 0.0):\n print(\"Fatal: CDSCDR_i = %e is negative.\", CDSCDR_i)\n if (self.DLCIG_i < 0.0):\n print(\"Warning: DLCIG = %e is negative, setting it to 0.\", DLCIG_i)\n self.DLCIG_i = 0.0\n if (self.DLCIGD_i < 0.0):\n print(\"Warning: DLCIGD = %e is negative, setting it to 0.\", DLCIGD_i)\n self.DLCIGD_i = 0.0\n if (self.M0_i < 0.0):\n print(\"Warning: M0_i = %e is negative, setting it to 0.\", M0_i)\n self.M0_i = 0.0\n if (self.U0_i <= 0.0):\n print(\"Warning: U0_i = %e is non-positive, setting it to the default value.\", U0_i)\n self.U0_i = 0.067\n if (self.UA_i < 0.0):\n print(\"Warning: UA_i = %e is negative, setting it to 0.\", UA_i)\n self.UA_i = 0.0\n if (self.EU_i < 0.0):\n print(\"Warning: EU_i = %e is negative, setting it to 0.\", EU_i)\n self.EU_i = 0.0\n if (self.UD_i < 0.0):\n print(\"Warning: UD_i = %e is negative, setting it to 0.\", UD_i)\n self.UD_i = 0.0\n if (self.UCS_i < 0.0):\n print(\"Warning: UCS_i = %e is negative, setting it to 0.\", UCS_i)\n self.UCS_i = 0.0\n\n # Process drain series resistance\n self.DMCGeff = self.DMCG - self.DMCGT\n self.DMCIeff = self.DMCI\n self.DMDGeff = self.DMDG - self.DMCGT\n\n # Processing S/D resistances and conductances\n if self.NRSgiven == True:\n self.RSourceGeo = self.RSH * self.NRS\n elif (self.RGEOMOD > 0 and self.RSH > 0.0):\n self.RSourceGeo = self.BSIMBULKRdseffGeo(self.NF, self.GEOMOD, self.RGEOMOD, self.MINZ, self.Weff, self.RSH, self.DMCGeff, self.DMCIeff, self.DMDGeff, 1)\n else:\n self.RSourceGeo = 0.0\n\n if self.NRDgiven == True:\n self.RDrainGeo = self.RSH * self.NRD\n elif (self.RGEOMOD > 0 and self.RSH > 0.0):\n self.RDrainGeo = self.BSIMBULKRdseffGeo(self.NF, self.GEOMOD, self.RGEOMOD, self.MINZ, self.Weff, self.RSH, self.DMCGeff, self.DMCIeff, self.DMDGeff, 0)\n else:\n self.RDrainGeo = 0.0\n\n # Clamping of S/D resistances\n if (self.RDSMOD == 0):\n if (self.RSourceGeo < self.minr):\n self.RSourceGeo = 0.0\n if (self.RDrainGeo < self.minr):\n self.RDrainGeo = 0.0\n else:\n if (self.RSourceGeo <= self.minr):\n self.RSourceGeo = self.minr\n if (self.RDrainGeo <= self.minr):\n self.RDrainGeo = self.minr\n if (self.RDSMOD == 1):\n if (self.RSWMIN_i <= 0.0):\n self.RSWMIN_i = 0.0\n if (self.RDWMIN_i <= 0.0):\n self.RDWMIN_i = 0.0\n if (self.RSW_i <= 0.0):\n self.RSW_i = 0.0\n if (self.RDW_i <= 0.0):\n self.RDW_i = 0.0\n else:\n if (self.RDSWMIN_i <= 0.0):\n self.RDSWMIN_i = 0.0\n if (self.RDSW_i <= 0.0):\n self.RDSW_i = 0.0\n\n # Body resistance network\n if (self.RBODYMOD != 0):\n self.Lnl = self.lln(self.Leff * 1.0e6)\n self.Lnw = self.lln(self.Weff * 1.0e6)\n self.Lnnf = self.lln(self.NF)\n self.Bodymode = 5\n self.Rbpb = self.RBPB\n self.Rbpd = self.RBPD\n self.Rbps = self.RBPS\n self.Rbdb = self.RBDB\n self.Rbsb = self.RBSB\n if self.RBPS0given == False or self.RBPD0given == False:\n self.Bodymode = 1\n elif self.RBSBX0given == False and self.RBSBY0given == False or self.RBDBX0given == False and self.RBDBY0given == False:\n self.Bodymode = 3\n if (self.RBODYMOD == 2):\n if (self.Bodymode == 5):\n self.Rbsbx = self.RBSBX0 * self.lexp(self.RBSDBXL * self.Lnl + self.RBSDBXW * self.Lnw + self.RBSDBXNF * self.Lnnf)\n self.Rbsby = self.RBSBY0 * self.lexp(self.RBSDBYL * self.Lnl + self.RBSDBYW * self.Lnw + self.RBSDBYNF * self.Lnnf)\n self.Rbsb = self.Rbsbx * self.Rbsby / (self.Rbsbx + self.Rbsby)\n self.Rbdbx = self.RBDBX0 * self.lexp(self.RBSDBXL * self.Lnl + self.RBSDBXW * self.Lnw + self.RBSDBXNF * self.Lnnf)\n self.Rbdby = self.RBDBY0 * self.lexp(self.RBSDBYL * self.Lnl + self.RBSDBYW * self.Lnw + self.RBSDBYNF * self.Lnnf)\n self.Rbdb = self.Rbdbx * self.Rbdby / (self.Rbdbx + self.Rbdby)\n if (self.Bodymode == 3 or self.Bodymode == 5):\n self.Rbps = self.RBPS0 * self.lexp(self.RBPSL * self.Lnl + self.RBPSW * self.Lnw + self.RBPSNF * self.Lnnf)\n self.Rbpd = self.RBPD0 * self.lexp(self.RBPDL * self.Lnl + self.RBPDW * self.Lnw + self.RBPDNF * self.Lnnf)\n self.Rbpbx = self.RBPBX0 * self.lexp(self.RBPBXL * self.Lnl + self.RBPBXW * self.Lnw + self.RBPBXNF * self.Lnnf)\n self.Rbpby = self.RBPBY0 * self.lexp(self.RBPBYL * self.Lnl + self.RBPBYW * self.Lnw + self.RBPBYNF * self.Lnnf)\n self.Rbpb = self.Rbpbx * self.Rbpby / (self.Rbpbx + self.Rbpby)\n if (self.RBODYMOD == 1 or (self.RBODYMOD == 2 and self.Bodymode == 5)):\n if (self.Rbdb < 1.0e-3):\n Grbdb = 1.0e3 # in mho\n else:\n self.Grbdb = self.GBMIN + 1.0 / self.Rbdb\n if (self.Rbpb < 1.0e-3):\n self.Grbpb = 1.0e3\n else:\n self.Grbpb = self.GBMIN + 1.0 / self.Rbpb\n if (self.Rbps < 1.0e-3):\n self.Grbps = 1.0e3\n else:\n self.Grbps = self.GBMIN + 1.0 / self.Rbps\n if (self.Rbsb < 1.0e-3):\n self.Grbsb = 1.0e3\n else:\n self.Grbsb = self.GBMIN + 1.0 / self.Rbsb\n if (self.Rbpd < 1.0e-3):\n self.Grbpd = 1.0e3\n else:\n self.Grbpd = self.GBMIN + 1.0 / self.Rbpd\n elif (self.RBODYMOD == 2 and self.Bodymode == 3):\n self.Grbdb = self.GBMIN\n self.Grbsb = self.GBMIN\n if (self.Rbpb < 1.0e-3):\n self.Grbpb = 1.0e3\n else:\n self.Grbpb = self.GBMIN + 1.0 / self.Rbpb\n if (self.Rbps < 1.0e-3):\n self.Grbps = 1.0e3\n else:\n self.Grbps = self.GBMIN + 1.0 / self.Rbps\n if (self.Rbpd < 1.0e-3):\n self.Grbpd = 1.0e3\n else:\n self.Grbpd = self.GBMIN + 1.0 / self.Rbpd\n elif (self.RBODYMOD == 2 and self.Bodymode == 1):\n self.Grbdb = self.GBMIN\n self.Grbsb = self.GBMIN\n self.Grbps = 1.0e3\n self.Grbpd = 1.0e3\n if (self.Rbpb < 1.0e-3):\n self.Grbpb = 1.0e3\n else:\n self.Grbpb = self.GBMIN + 1.0 / self.Rbpb\n\n # Gate process resistance\n self.Grgeltd = self.RSHG * (self.XGW + self.Weffcj / 3.0 / self.NGCON) / (self.NGCON * self.NF * (self.Lnew - self.XGL))\n if (self.Grgeltd > 0.0):\n self.Grgeltd = 1.0 / self.Grgeltd\n else:\n self.Grgeltd = 1.0e3\n if (self.RGATEMOD != 0):\n print(\"Warning: (instance %M) The gate conductance reset to 1.0e3 mho.\")\n\n self.T0 = self.TOXE * self.TOXE\n self.T1 = self.TOXE * self.POXEDGE_i\n self.T2 = self.T1 * self.T1\n self.ToxRatio = self.lexp(self.NTOX_i * self.lln(self.TOXREF / self.TOXE)) / self.T0\n self.ToxRatioEdge = self.lexp(self.NTOX_i * self.lln(self.TOXREF / self.T1)) / self.T2\n self.Aechvb = 4.97232e-7 if (self.TYPE == self.ntype) else 3.42537e-7\n self.Bechvb = 7.45669e11 if (self.TYPE == self.ntype) else 1.16645e12\n self.AechvbEdge = self.Aechvb * self.Weff * self.ToxRatioEdge\n self.BechvbEdge = -self.Bechvb * self.TOXE * self.POXEDGE_i\n self.Aechvb = self.Aechvb * (self.Weff * self.Leff * self.ToxRatio)\n self.Bechvb = -self.Bechvb * self.TOXE\n self.Weff_SH = self.WTH0 + self.Weff\n\n # Parameters for self-heating effects\n if (self.SHMOD != 0) and (self.RTH0 > 0.0) and (self.Weff_SH > 0.0):\n self.gth = self.Weff_SH * self.NF / self.RTH0\n self.cth = self.CTH0 * self.Weff_SH * self.NF\n else:\n # Set gth to some value to prevent a singular G matrix\n self.gth = 1.0\n self.cth = 0.0\n\n # Temperature-dependent calculations\n if (self.TNOM <= -self.P_CELSIUS0):\n self.T0 = self.REFTEMP - self.P_CELSIUS0\n print(\"Warning: TNOM = %e C <= %e C. Setting TNOM to %e C.\", TNOM, -P_CELSIUS0, T0)\n self.Tnom = self.REFTEMP\n else:\n self.Tnom = self.TNOM + self.P_CELSIUS0\n self.DevTemp = self.TEMP + self.P_CELSIUS0 + self.DTEMP\n\n self.Vt = self.KboQ * self.DevTemp\n self.inv_Vt = 1.0 / self.Vt\n self.TRatio = self.DevTemp / self.Tnom\n self.delTemp = self.DevTemp - self.Tnom\n self.Vtm = self.KboQ * self.DevTemp\n self.Vtm0 = self.KboQ * self.Tnom\n self.Eg = self.BG0SUB - self.TBGASUB * self.DevTemp * self.DevTemp / (self.DevTemp + self.TBGBSUB)\n self.Eg0 = self.BG0SUB - self.TBGASUB * self.Tnom * self.Tnom / (self.Tnom + self.TBGBSUB)\n self.T1 = (self.DevTemp / self.Tnom) * sqrt(self.DevTemp / self.Tnom)\n self.ni = self.NI0SUB * self.T1 * self.lexp(self.Eg / (2.0 * self.Vtm0) - self.Eg / (2.0 * self.Vtm))\n if ((self.SHMOD != 0) and (self.RTH0 > 0.0) and (self.Weff_SH > 0.0)):\n self.T0 = self.lln(self.NDEP_i / self.ni)\n self.phib = sqrt(self.T0 * self.T0 + 1.0e-6)\n else:\n self.phib = self.lln(self.NDEP_i / self.ni)\n if ((self.SHMOD != 0) and (self.RTH0 > 0.0) and (self.Weff_SH > 0.0)):\n self.T0 = self.lln(self.NDEPEDGE_i * self.NSD_i / (self.ni * self.ni))\n self.Vbi_edge = sqrt(self.T0 * self.T0 + 1.0e-6)\n else:\n self.Vbi_edge = self.lln(self.NDEPEDGE_i * self.NSD_i / (self.ni * self.ni))\n if (self.NGATE_i > 0.0):\n self.Vfbsdr = -self.devsign * self.Vt * self.lln(self.NGATE_i / self.NSD_i) + self.VFBSDOFF\n else:\n self.Vfbsdr = 0.0\n\n # Short channel effects\n self.Phist = max(0.4 + self.Vt * self.phib + self.PHIN_i, 0.4)\n self.sqrtPhist = sqrt(self.Phist)\n self.T1DEP = sqrt(2.0 * self.epssi / (self.q * self.NDEP_i))\n self.litl = sqrt((self.epssi / self.epsox) * self.TOXE * self.XJ_i)\n self.NFACTOR_t = self.NFACTOR_i * self.hypsmooth((1.0 + self.TNFACTOR * (self.TRatio - 1.0)), 1e-3)\n self.ETA0_t = self.ETA0_i * (1.0 + self.TETA0 * (self.TRatio - 1.0))\n if (self.ASYMMOD != 0):\n self.ETA0R_t = self.ETA0R_i * (1.0 + self.TETA0 * (self.TRatio - 1.0))\n\n # Mobility degradation\n self.eta_mu = (self.Oneby3 * self.ETAMOB) if (self.TYPE != self.ntype) else (0.5 * self.ETAMOB)\n self.U0_t = self.U0_i * self.TRatio**self.UTE_i\n self.UA_t = self.UA_i * self.hypsmooth(1.0 + self.UA1_i * self.delTemp - 1.0e-6, 1.0e-3)\n self.UC_t = self.UC_i * self.hypsmooth(1.0 + self.UC1_i * self.delTemp - 1.0e-6, 1.0e-3)\n self.UD_t = self.UD_i * self.TRatio**self.UD1_i\n self.UCS_t = self.UCS_i * self.TRatio**self.UCSTE_i\n self.EU_t = self.EU_i * self.hypsmooth((1.0 + self.EU1_i * (self.TRatio - 1.0)), 1e-3)\n if (self.ASYMMOD != 0):\n self.U0R_t = self.U0R_i * self.TRatio**self.UTE_i\n self.UAR_t = self.UAR_i * self.hypsmooth(1.0 + self.UA1_i * self.delTemp - 1.0e-6, 1.0e-3)\n self.UCR_t = self.UCR_i * self.hypsmooth(1.0 + self.UC1_i * self.delTemp - 1.0e-6, 1.0e-3)\n self.UDR_t = self.UDR_i * self.TRatio**self.UD1_i\n self.UCSR_t = self.UCSR_i * self.TRatio**self.UCSTE_i\n else:\n self.U0R_t = 0.0\n self.UAR_t = 0.0\n self.UCR_t = 0.0\n self.UDR_t = 0.0\n self.UCSR_t = 0.0\n self.rdstemp = self.TRatio**self.PRT_i\n self.VSAT_t = self.VSAT_i * self.TRatio**-self.AT_i\n if (self.VSAT_t < 100.0):\n print(\"Warning: VSAT(%f) = %e is less than 100, setting it to 100.\", DevTemp, VSAT_t)\n self.VSAT_t = 100.0\n if (self.HVMOD == 1):\n self.rdstemphv = self.TRatio**self.PRTHV\n self.VDRIFT_t = self.VDRIFT * self.TRatio**-self.ATHV\n if (self.ASYMMOD != 0):\n self.VSATR_t = self.VSATR_i * self.TRatio**-self.AT_i\n if(self.VSATR_t < 100.0):\n print(\"Warning: VSATR(%f) = %e is less than 100, setting it to 100.\", DevTemp, VSATR_t)\n self.VSATR_t = 100.0\n\n self.VSATCV_t = self.VSATCV_i * self.TRatio**-self.AT_i\n if (self.VSATCV_t < 100.0):\n print(\"Warning: VSATCV(%f) = %e is less than 100, setting it to 100.\", DevTemp, VSATCV_t)\n self.VSATCV_t = 100.0\n self.DELTA_t = 1.0 / ( self.hypsmooth((1.0 / self.DELTA_i) * (1.0 + self.TDELTA * self.delTemp) - 2.0 , 1.0e-3) + 2.0)\n self.PTWG_t = self.PTWG_i * self.hypsmooth(1.0 - self.PTWGT_i * self.delTemp - 1.0e-6, 1.0e-3)\n if (self.ASYMMOD != 0):\n self.PTWGR_t = self.PTWGR_i * self.hypsmooth(1.0 - self.PTWGT_i * self.delTemp - 1.0e-6, 1.0e-3)\n self.A1_t = self.A1_i * self.hypsmooth(1.0 + self.A11_i * self.delTemp - 1.0e-6, 1.0e-3)\n self.A2_t = self.A2_i * self.hypsmooth(1.0 + self.A21_i * self.delTemp - 1.0e-6, 1.0e-3)\n self.BETA0_t = self.BETA0_i * self.TRatio**self.IIT_i\n self.BGIDL_t = self.BGIDL_i * self.hypsmooth(1.0 + self.TGIDL_i * self.delTemp - 1.0e-6, 1.0e-3)\n self.BGISL_t = self.BGISL_i * self.hypsmooth(1.0 + self.TGIDL_i * self.delTemp - 1.0e-6, 1.0e-3)\n self.igtemp = self.lexp(self.IGT_i * self.lln(self.TRatio))\n self.K0_t = self.K0_i * self.hypsmooth(1.0 + self.K01_i * self.delTemp - 1.0e-6, 1.0e-3)\n self.M0_t = self.M0_i * self.hypsmooth(1.0 + self.M01_i * self.delTemp - 1.0e-6, 1.0e-3)\n self.C0_t = self.C0_i * self.hypsmooth(1.0 + self.C01_i * self.delTemp - 1.0e-6, 1.0e-3)\n self.C0SI_t = self.C0SI_i * self.hypsmooth(1.0 + self.C0SI1_i * self.delTemp - 1.0e-6, 1.0e-3)\n self.C0SISAT_t = self.C0SISAT_i * self.hypsmooth(1.0 + self.C0SISAT1_i * self.delTemp - 1.0e-6, 1.0e-3)\n\n # Diode model temperature effects\n self.CJS_t = self.CJS * self.hypsmooth(1.0 + self.TCJ * self.delTemp - 1.0e-6, 1.0e-3)\n self.CJD_t = self.CJD * self.hypsmooth(1.0 + self.TCJ * self.delTemp - 1.0e-6, 1.0e-3)\n self.CJSWS_t = self.CJSWS * self.hypsmooth(1.0 + self.TCJSW * self.delTemp - 1.0e-6, 1.0e-3)\n self.CJSWD_t = self.CJSWD * self.hypsmooth(1.0 + self.TCJSW * self.delTemp - 1.0e-6, 1.0e-3)\n self.CJSWGS_t = self.CJSWGS * self.hypsmooth(1.0 + self.TCJSWG * self.delTemp - 1.0e-6, 1.0e-3)\n self.CJSWGD_t = self.CJSWGD * self.hypsmooth(1.0 + self.TCJSWG * self.delTemp - 1.0e-6, 1.0e-3)\n self.PBS_t = self.hypsmooth(self.PBS - self.TPB * self.delTemp - 0.01, 1.0e-3) + 0.01\n self.PBD_t = self.hypsmooth(self.PBD - self.TPB * self.delTemp - 0.01, 1.0e-3) + 0.01\n self.PBSWS_t = self.hypsmooth(self.PBSWS - self.TPBSW * self.delTemp - 0.01, 1.0e-3) + 0.01\n self.PBSWD_t = self.hypsmooth(self.PBSWD - self.TPBSW * self.delTemp - 0.01, 1.0e-3) + 0.01\n self.PBSWGS_t = self.hypsmooth(self.PBSWGS - self.TPBSWG * self.delTemp - 0.01, 1.0e-3) + 0.01\n self.PBSWGD_t = self.hypsmooth(self.PBSWGD - self.TPBSWG * self.delTemp - 0.01, 1.0e-3) + 0.01\n self.T0 = self.Eg0 / self.Vtm0 - self.Eg / self.Vtm\n self.T1 = self.lln(self.TRatio)\n self.T3 = self.lexp((self.T0 + self.XTIS * self.T1) / self.NJS)\n self.JSS_t = self.JSS * self.T3\n self.JSWS_t = self.JSWS * self.T3\n self.JSWGS_t = self.JSWGS * self.T3\n self.T3 = self.lexp((self.T0 + self.XTID * self.T1) / self.NJD)\n self.JSD_t = self.JSD * self.T3\n self.JSWD_t = self.JSWD * self.T3\n self.JSWGD_t = self.JSWGD * self.T3\n self.JTSS_t = self.JTSS * self.lexp(self.Eg0 * self.XTSS * (self.TRatio - 1.0) / self.Vtm)\n self.JTSSWS_t = self.JTSSWS * self.lexp(self.Eg0 * self.XTSSWS * (self.TRatio - 1.0) / self.Vtm)\n self.JTSSWGS_t = self.JTSSWGS * (sqrt(self.JTWEFF / self.Weffcj) + 1.0) * self.lexp(self.Eg0 * self.XTSSWGS * (self.TRatio - 1) / self.Vtm)\n self.JTSD_t = self.JTSD * self.lexp(self.Eg0 * self.XTSD * (self.TRatio - 1.0) / self.Vtm)\n self.JTSSWD_t = self.JTSSWD * self.lexp(self.Eg0 * self.XTSSWD * (self.TRatio - 1.0) / self.Vtm)\n self.JTSSWGD_t = self.JTSSWGD * (sqrt(self.JTWEFF / self.Weffcj) + 1.0) * self.lexp(self.Eg0 * self.XTSSWGD * (self.TRatio - 1) / self.Vtm)\n\n # All NJT*'s smoothed to 0.01 to prevent divide by zero/negative values\n self.NJTS_t = self.hypsmooth(self.NJTS * (1.0 + self.TNJTS * (self.TRatio - 1.0)) - 0.01, 1.0e-3) + 0.01\n self.NJTSSW_t = self.hypsmooth(self.NJTSSW * (1.0 + self.TNJTSSW * (self.TRatio - 1.0)) - 0.01, 1.0e-3) + 0.01\n self.NJTSSWG_t = self.hypsmooth(self.NJTSSWG * (1.0 + self.TNJTSSWG * (self.TRatio - 1.0)) - 0.01, 1.0e-3) + 0.01\n self.NJTSD_t = self.hypsmooth(self.NJTSD * (1.0 + self.TNJTSD * (self.TRatio - 1.0)) - 0.01, 1.0e-3) + 0.01\n self.NJTSSWD_t = self.hypsmooth(self.NJTSSWD * (1.0 + self.TNJTSSWD * (self.TRatio - 1.0)) - 0.01, 1.0e-3) + 0.01\n self.NJTSSWGD_t = self.hypsmooth(self.NJTSSWGD * (1.0 + self.TNJTSSWGD * (self.TRatio - 1.0)) - 0.01, 1.0e-3) + 0.01\n\n # Effective S/D junction area and perimeters\n self.temp_PSeff, self.temp_PDeff, self.temp_ASeff, self.temp_ADeff = self.BSIMBULKPAeffGeo(self.NF, self.GEOMOD, self.MINZ, self.Weffcj, self.DMCGeff, self.DMCIeff, self.DMDGeff)\n if self.ASgiven == True:\n self.ASeff = self.AS * self.WMLT * self.LMLT\n else:\n self.ASeff = self.temp_ASeff\n if (self.ASeff < 0.0):\n print(\"Warning: (instance %M) ASeff = %e is negative. Set to 0.0.\", ASeff)\n self.ASeff = 0.0\n if self.ADgiven == True:\n self.ADeff = self.AD * self.WMLT * self.LMLT\n else:\n self.ADeff = self.temp_ADeff\n if (self.ADeff < 0.0):\n print(\"Warning: (instance %M) ADeff = %e is negative. Set to 0.0.\", ADeff)\n self.ADeff = 0.0\n if self.PSgiven == True:\n if (self.PERMOD == 0):\n # PS does not include gate-edge perimeters\n self.PSeff = self.PS * self.WMLT\n else:\n # PS includes gate-edge perimeters\n self.PSeff = max(self.PS * self.WMLT - self.Weffcj * self.NF, 0.0)\n else:\n self.PSeff = self.temp_PSeff\n if (self.PSeff < 0.0):\n print(\"Warning: (instance %M) PSeff = %e is negative. Set to 0.0.\", PSeff)\n self.PSeff = 0.0\n if self.PDgiven == True:\n if (self.PERMOD == 0):\n # PD does not include gate-edge perimeters\n self.PDeff = self.PD * self.WMLT\n else:\n # PD includes gate-edge perimeters\n self.PDeff = max(self.PD * self.WMLT - self.Weffcj * self.NF, 0.0)\n else:\n self.PDeff = self.temp_PDeff\n if (self.PDeff < 0.0):\n print(\"Warning: (instance %M) PDeff = %e is negative. Set to 0.0.\", PDeff)\n self.PDeff = 0.0\n\n self.Isbs = self.ASeff * self.JSS_t + self.PSeff * self.JSWS_t + self.Weffcj * self.NF * self.JSWGS_t\n if (self.Isbs > 0.0):\n self.Nvtms = self.Vtm * self.NJS\n self.XExpBVS = self.lexp(-self.BVS / self.Nvtms) * self.XJBVS\n self.T2 = max(self.IJTHSFWD / self.Isbs, 10.0)\n self.Tb = 1.0 + self.T2 - self.XExpBVS\n self.VjsmFwd = self.Nvtms * self.lln(0.5 * (self.Tb + sqrt(self.Tb * self.Tb + 4.0 * self.XExpBVS)))\n self.T0 = self.lexp(self.VjsmFwd / self.Nvtms)\n self.IVjsmFwd = self.Isbs * (self.T0 - self.XExpBVS / self.T0 + self.XExpBVS - 1.0)\n self.SslpFwd = self.Isbs * (self.T0 + self.XExpBVS / self.T0) / self.Nvtms\n self.T2 = self.hypsmooth(self.IJTHSREV / self.Isbs - 10.0, 1.0e-3) + 10.0\n self.VjsmRev = -self.BVS - self.Nvtms * self.lln((self.T2 - 1.0) / self.XJBVS)\n self.T1 = self.XJBVS * self.lexp(-(self.BVS + self.VjsmRev) / self.Nvtms)\n self.IVjsmRev = self.Isbs * (1.0 + self.T1)\n self.SslpRev = -self.Isbs * self.T1 / self.Nvtms\n else:\n self.Nvtms = 0.0\n self.XExpBVS = 0.0\n self.VjsmFwd = 0.0\n self.IVjsmFwd = 0.0\n self.SslpFwd = 0.0\n self.VjsmRev = 0.0\n self.IVjsmRev = 0.0\n self.SslpRev = 0.0\n\n # Drain-side junction currents\n self.Isbd = self.ADeff * self.JSD_t + self.PDeff * self.JSWD_t + self.Weffcj * self.NF * self.JSWGD_t\n if (self.Isbd > 0.0):\n self.Nvtmd = self.Vtm * self.NJD\n self.XExpBVD = self.lexp(-self.BVD / self.Nvtmd) * self.XJBVD\n self.T2 = max(self.IJTHDFWD / self.Isbd, 10.0)\n self.Tb = 1.0 + self.T2 - self.XExpBVD\n self.VjdmFwd = self.Nvtmd * self.lln(0.5 * (self.Tb + sqrt(self.Tb * self.Tb + 4.0 * self.XExpBVD)))\n self.T0 = self.lexp(self.VjdmFwd / self.Nvtmd)\n self.IVjdmFwd = self.Isbd * (self.T0 - self.XExpBVD / self.T0 + self.XExpBVD - 1.0)\n self.DslpFwd = self.Isbd * (self.T0 + self.XExpBVD / self.T0) / self.Nvtmd\n self.T2 = self.hypsmooth(self.IJTHDREV / self.Isbd - 10.0, 1.0e-3) + 10.0\n self.VjdmRev = -self.BVD - self.Nvtmd * self.lln((self.T2 - 1.0) / self.XJBVD)\n self.T1 = self.XJBVD * self.lexp(-(self.BVD + self.VjdmRev) / self.Nvtmd)\n self.IVjdmRev = self.Isbd * (1.0 + self.T1)\n self.DslpRev = -self.Isbd * self.T1 / self.Nvtmd\n else:\n self.Nvtmd = 0.0\n self.XExpBVD = 0.0\n self.VjdmFwd = 0.0\n self.IVjdmFwd = 0.0\n self.DslpFwd = 0.0\n self.VjdmRev = 0.0\n self.IVjdmRev = 0.0\n self.DslpRev = 0.0\n\n # STI stress equations\n if ((self.SA > 0.0) and (self.SB > 0.0) and ((self.NF == 1.0) or ((self.NF > 1.0) and (self.SD > 0.0)))):\n self.T0 = self.Lnew**self.LLODKU0\n self.W_tmp_stress = self.Wnew + self.WLOD\n self.T1 = self.W_tmp_stress**self.WLODKU0\n self.tmp1_stress = self.LKU0 / self.T0 + self.WKU0 / self.T1 + self.PKU0 / (self.T0 * self.T1)\n self.kstress_u0 = 1.0 + self.tmp1_stress\n self.T0 = self.Lnew**self.LLODVTH\n self.T1 = self.W_tmp_stress**self.WLODVTH\n self.tmp1_stress_vth = self.LKVTH0 / self.T0 + self.WKVTH0 / self.T1 + self.PKVTH0 / (self.T0 * self.T1)\n self.kstress_vth0 = 1.0 + self.tmp1_stress_vth\n self.T0 = self.TRatio - 1.0\n self.ku0_temp = self.kstress_u0 * (1.0 + self.TKU0 * self.T0) + 1.0e-9\n for i in range(self.NF):\n self.T0 = 1.0 / self.NF / (self.SA + 0.5 * self.L_mult + i * (self.SD + self.L_mult))\n self.T1 = 1.0 / self.NF / (self.SB + 0.5 * self.L_mult + i * (self.SD + self.L_mult))\n self.Inv_sa = self.Inv_sa + self.T0\n self.Inv_sb = self.Inv_sb + self.T1\n self.Inv_saref = 1.0 / (self.SAREF + 0.5 * self.L_mult)\n self.Inv_sbref = 1.0 / (self.SBREF + 0.5 * self.L_mult)\n self.Inv_odref = self.Inv_saref + self.Inv_sbref\n self.rho_ref = (self.KU0 / self.ku0_temp) * self.Inv_odref\n self.Inv_od = self.Inv_sa + self.Inv_sb\n self.rho = (self.KU0 / self.ku0_temp) * self.Inv_od\n self.mu0_mult = (1.0 + self.rho) / (1.0 + self.rho_ref)\n self.vsat_mult = (1.0 + self.rho * self.KVSAT) / (1.0 + self.rho_ref * self.KVSAT)\n self.vth0_stress = (self.KVTH0 / self.kstress_vth0) * (self.Inv_od - self.Inv_odref)\n self.k2_stress = (self.STK2 / self.kstress_vth0**self.LODK2) * (self.Inv_od - self.Inv_odref)\n self.eta_stress = (self.STETA0 / self.kstress_vth0**self.LODETA0) * (self.Inv_od - self.Inv_odref)\n self.U0_t = self.U0_t * self.mu0_mult\n self.VSAT_t = self.VSAT_t * self.vsat_mult\n self.K2_i = self.K2_i + self.k2_stress\n self.ETA0_t = self.ETA0_t + self.eta_stress\n if (self.EDGEFET == 1):\n self.vth0_stress_EDGE = (self.KVTH0EDGE_i / self.kstress_vth0) * (self.Inv_od - self.Inv_odref)\n self.k2_stress_EDGE = (self.STK2EDGE_i / self.kstress_vth0**self.LODK2) * (self.Inv_od - self.Inv_odref)\n self.eta_stress_EDGE = (self.STETA0EDGE_i / self.kstress_vth0**self.LODETA0) * (self.Inv_od - self.Inv_odref)\n self.K2EDGE_i = self.K2EDGE_i + self.k2_stress_EDGE\n self.ETA0EDGE_i = self.ETA0EDGE_i + self.eta_stress_EDGE\n else:\n self.vth0_stress = 0.0\n self.vth0_stress_EDGE = 0.0\n\n # Well proximity effect\n if (self.WPEMOD == 1):\n self.Wdrn = self.W / self.NF\n self.local_sca = self.SCA\n self.local_scb = self.SCB\n self.local_scc = self.SCC\n if self.SCAgiven == False and self.SCBgiven == False and self.SCCgiven == False:\n if self.SCgiven == True and self.SC > 0.0:\n self.T1 = self.SC + self.Wdrn\n self.T2 = 1.0 / self.SCREF\n self.local_sca = self.SCREF * self.SCREF / (self.SC * self.T1)\n self.local_scb = ((0.1 * self.SC + 0.01 * self.SCREF) * self.lexp(-10.0 * self.SC * self.T2) - (0.1 * self.T1 + 0.01 * self.SCREF) * self.lexp(-10.0 * self.T1 * self.T2)) / self.Wdrn\n self.local_scc = ((0.05 * self.SC + 0.0025 * self.SCREF) * self.lexp(-20.0 * self.SC * self.T2) - (0.05 * self.T1 + 0.0025 * self.SCREF) * self.lexp(-20.0 * self.T1 * self.T2)) / self.Wdrn\n else:\n print(\"Warning: (Instance %M) No WPE as none of SCA, SCB, SCC, SC is given and/or SC not positive.\")\n else:\n self.local_sca = 0.0\n self.local_scb = 0.0\n self.local_scc = 0.0\n\n self.vth0_well = self.KVTH0WE_i * (self.local_sca + self.WEB * self.local_scb + self.WEC * self.local_scc)\n self.k2_well = self.K2WE_i * (self.local_sca + self.WEB * self.local_scb + self.WEC * self.local_scc)\n self.mu_well = 1.0 + self.KU0WE_i * (self.local_sca + self.WEB * self.local_scb + self.WEC * self.local_scc)\n self.U0_t = self.U0_t * self.mu_well\n self.K2_i = self.K2_i + self.k2_well\n\n # Load terminal voltages\n self.Vg = self.devsign * (self.VG - self.VB)\n self.Vd = self.devsign * (self.VD - self.VB)\n self.Vs = self.devsign * (self.VS - self.VB)\n self.Vds = self.Vd - self.Vs\n self.Vds_noswap = self.Vds\n self.Vsb_noswap = self.Vs\n self.Vdb_noswap = self.Vd\n self.Vbs_jct = self.devsign * (self.VB - self.VS)\n self.Vbd_jct = self.devsign * (self.VB - self.VD)\n self.Vgd_noswap = self.Vg - self.Vd\n self.Vgs_noswap = self.Vg - self.Vs\n self.Vgd_ov_noswap = self.devsign * (self.VG - self.VD)\n self.Vgs_ov_noswap = self.devsign * (self.VG - self.VS)\n\n # Terminal voltage conditioning\n # Source-drain interchange\n self.sigvds = 1.0\n if (self.Vds < 0.0):\n self.sigvds = -1.0\n self.Vd = self.devsign * (self.VS - self.VB)\n self.Vs = self.devsign * (self.VD - self.VB)\n self.Vds = self.Vd - self.Vs\n self.T0 = self.AVDSX * self.Vds\n if (self.T0 > self.EXPL_THRESHOLD):\n self.T1 = self.T0\n else:\n self.T1 = log(1.0 + exp(self.T0))\n self.Vdsx = ((2.0 / self.AVDSX) * self.T1) - self.Vds - ((2.0 / self.AVDSX) * log(2.0))\n self.Vbsx = -(self.Vs + 0.5 * (self.Vds - self.Vdsx))\n\n # Asymmetry model\n self.T0 = tanh(0.6 * self.Vds_noswap / self.Vtm)\n self.wf = 0.5 + 0.5 * self.T0\n self.wr = 1.0 - self.wf\n if (self.ASYMMOD != 0):\n self.CDSCD_a = self.CDSCDR_i * self.wr + self.CDSCD_i * self.wf\n self.ETA0_a = self.ETA0R_t * self.wr + self.ETA0_t * self.wf\n self.PDIBLC_a = self.PDIBLCR_i * self.wr + self.PDIBLC_i * self.wf\n self.PCLM_a = self.PCLMR_i * self.wr + self.PCLM_i * self.wf\n self.PSAT_a = self.PSATR_i * self.wr + self.PSAT_i * self.wf\n self.VSAT_a = self.VSATR_t * self.wr + self.VSAT_t * self.wf\n self.PTWG_a = self.PTWGR_t * self.wr + self.PTWG_t * self.wf\n self.U0_a = self.U0R_t * self.wr + self.U0_t * self.wf\n self.UA_a = self.UAR_t * self.wr + self.UA_t * self.wf\n self.UC_a = self.UCR_t * self.wr + self.UC_t * self.wf\n self.UD_a = self.UDR_t * self.wr + self.UD_t * self.wf\n self.UCS_a = self.UCSR_t * self.wr + self.UCS_t * self.wf\n else:\n self.CDSCD_a = self.CDSCD_i\n self.ETA0_a = self.ETA0_t\n self.PDIBLC_a = self.PDIBLC_i\n self.PCLM_a = self.PCLM_i\n self.PSAT_a = self.PSAT_i\n self.VSAT_a = self.VSAT_t\n self.PTWG_a = self.PTWG_t\n self.U0_a = self.U0_t\n self.UA_a = self.UA_t\n self.UC_a = self.UC_t\n self.UD_a = self.UD_t\n self.UCS_a = self.UCS_t\n\n # SCE, DIBL, SS degradation effects, Ref: BSIM4\n self.PhistVbs = self.Smooth(self.Phist - self.Vbsx, 0.05, 0.1)\n self.sqrtPhistVbs = sqrt(self.PhistVbs)\n self.Xdep = self.T1DEP * self.sqrtPhistVbs\n self.Cdep = self.epssi / self.Xdep\n self.cdsc = self.CIT_i + self.NFACTOR_t + self.CDSCD_a * self.Vdsx - self.CDSCB_i * self.Vbsx\n self.T1 = 1.0 + self.cdsc/self.Cox\n self.n = self.Smooth(self.T1, 1.0, 0.05)\n self.nVt = self.n * self.Vt\n self.inv_nVt = 1.0 / self.nVt\n\n # Vth shift for DIBL\n self.dVth_dibl = -(self.ETA0_a + self.ETAB_i * self.Vbsx) * self.Vdsx\n self.dVth_dibl = self.Smooth2(self.dVth_dibl, 0.0, 5.0e-5)\n\n # Vth shift with temperature\n self.dvth_temp = (self.KT1_i + self.KT1L / self.Leff + self.KT2_i * self.Vbsx) * (self.TRatio**self.KT1EXP - 1.0)\n\n # Vth correction for pocket implants\n if (self.DVTP0_i > 0.0):\n self.T0 = -self.DVTP1_i * self.Vdsx\n if (self.T0 < -self.EXPL_THRESHOLD):\n self.T2 = self.MIN_EXPL\n else:\n self.T2 = self.lexp(self.T0)\n self.T3 = self.Leff + self.DVTP0_i * (1.0 + self.T2)\n self.dVth_ldop = -self.nVt * self.lln(self.Leff / self.T3)\n else:\n self.dVth_ldop = 0.0\n self.T4 = self.DVTP5_i + self.DVTP2_i / self.Leff**self.DVTP3_i\n self.dVth_ldop = self.dVth_ldop - self.T4 * tanh(self.DVTP4_i * self.Vdsx)\n\n # Normalization of terminal and flatband voltage by nVt\n self.VFB_i = self.VFB_i + self.DELVTO\n self.vg = self.Vg * self.inv_nVt\n self.vs = self.Vs * self.inv_nVt\n self.vfb = self.VFB_i * self.inv_nVt\n\n # Compute dVth_VNUD with \"first-order\" and \"second-order\" body-bias effect\n self.dVth_VNUD = self.K1_i * (self.sqrtPhistVbs - self.sqrtPhist) - self.K2_i * self.Vbsx\n self.Vth_shift = self.dVth_dibl + self.dVth_ldop + self.dVth_VNUD - self.dvth_temp + self.vth0_stress + self.vth0_well\n self.vgfb = self.vg - self.vfb - self.Vth_shift * self.inv_nVt\n\n # Threshold voltage for operating point information\n self.gam = sqrt(2.0 * self.q * self.epssi * self.NDEP_i * self.inv_Vt) / self.Cox\n self.q_vth = 0.5\n self.T0 = self.hypsmooth((2.0 * self.phib + self.Vs * self.inv_Vt), 1.0e-3)\n self.nq = 1.0 + self.gam / (2.0 * sqrt(self.T0))\n self.psip_th = self.hypsmooth((self.Vs * self.inv_Vt + 2.0 * self.phib + self.lln(self.q_vth) + 2.0 * self.q_vth + self.lln(2.0 * self.nq / self.gam * (2.0 * self.q_vth * self.nq / self.gam + 2.0 * sqrt(self.T0)))), 1.0e-3)\n self.VTH = self.devsign * (self.VFB_i + (self.psip_th - self.Vs * self.inv_Vt) * self.Vt + self.Vt * self.gam * sqrt(self.psip_th) + self.Vth_shift)\n\n # Normalized body factor\n self.gam = sqrt(2.0 * self.q * self.epssi * self.NDEP_i * self.inv_nVt) / self.Cox\n self.inv_gam = 1.0 / self.gam\n\n # psip: pinch-off voltage\n self.phib_n = self.phib / self.n\n self.psip = self.PO_psip(self.vgfb, self.gam, 0.0)\n\n # Normalized inversion charge at source end of channel\n self.qs = self.BSIM_q(self.psip, self.phib_n, self.vs, self.gam)\n\n # Average charge-surface potential slope, Ref: Charge-based MOS Transistor Modeling by C. Enz & E. Vittoz\n self.psipclamp = self.Smooth(self.psip, 1.0, 2.0)\n self.sqrtpsip = sqrt(self.psipclamp)\n\n # Source side surface potential\n self.psiavg = self.psip - 2.0 * self.qs\n self.T0 = self.Smooth(self.psiavg, 1.0, 2.0)\n self.nq = 1.0 + self.gam / (self.sqrtpsip + sqrt(self.T0))\n\n # Drain saturation voltage\n self.EeffFactor = 1.0e-8 / (self.epsratio * self.TOXE)\n self.T0 = self.nVt * (self.vgfb - self.psip - 2.0 * self.qs * (self.nq - 1.0))\n self.qbs = self.Smooth(self.T0, 0.0, 0.1)\n\n # Source side qi and qb for Vdsat- normalized to Cox\n self.qis = 2.0 * self.nq * self.nVt * self.qs\n self.Eeffs = self.EeffFactor * (self.qbs + self.eta_mu * self.qis)\n\n # Ref: BSIM4 mobility model\n self.T2 = (0.5 * (1.0 + (self.qis / self.qbs)))**self.UCS_a\n self.T3 = (self.UA_a + self.UC_a * self.Vbsx) * self.Eeffs**self.EU_t + self.UD_a / self.T2\n self.T4 = 1.0 + self.T3\n self.Dmobs = self.Smooth(self.T4, 1.0, 0.0015)\n self.WeffWRFactor = 1.0 / ((self.Weff * 1.0e6)**self.WR_i * self.NF)\n\n if (self.RDSMOD == 1):\n self.Rdss = 0.0\n else:\n self.T0 = 1.0 + self.PRWG_i * self.qis\n self.T1 = self.PRWB_i * (self.sqrtPhistVbs - self.sqrtPhist)\n self.T2 = 1.0 / self.T0 + self.T1\n self.T3 = self.T2 + sqrt(self.T2 * self.T2 + 0.01)\n self.Rdss = (self.RDSWMIN_i + self.RDSW_i * self.T3) * self.WeffWRFactor * self.NF * self.rdstemp\n if (self.RDSMOD == 2):\n self.Rdss = (self.RSourceGeo + (self.RDSWMIN_i + self.RDSW_i * self.T3) * self.WeffWRFactor * self.NF + self.RDrainGeo) * self.rdstemp\n\n self.T0 = self.Dmobs**(1.0 / self.PSAT_a)\n self.T11 = self.PSATB_i * self.Vbsx\n self.T12 = sqrt(0.1 + self.T11 * self.T11)\n self.T1 = 0.5*(1 - self.T11 + sqrt((1 - self.T11) * (1 - self.T11) + self.T12))\n self.T2 = 10.0 * self.PSATX * self.qs * self.T1 / (10.0 * self.PSATX + self.qs * self.T1)\n if (self.PTWG_a < 0.0):\n self.LambdaC = 2.0 * ((self.U0_a / self.T0) * self.nVt / (self.VSAT_a * self.Leff)) * (1.0 / (1.0 - self.PTWG_a * self.T2))\n else:\n self.LambdaC = 2.0 * ((self.U0_a / self.T0) * self.nVt / (self.VSAT_a * self.Leff)) * (1.0 + self.PTWG_a * self.T2)\n\n # qdsat for external Rds\n if (self.Rdss == 0):\n # Accurate qdsat derived from consistent I-V\n self.T0 = 0.5 * self.LambdaC * (self.qs * self.qs + self.qs) / (1.0 + 0.5 * self.LambdaC * (1.0 + self.qs))\n self.T1 = 2.0 * self.LambdaC * (self.qs - self.T0)\n self.T2 = sqrt(1.0 + self.T1 * self.T1)\n self.ln_T1_T2 = asinh(self.T1)\n if (self.T1 != 0.0):\n self.T3 = self.T2 + (1.0 / self.T1) * self.ln_T1_T2\n else:\n self.T3 = self.T2 + (1.0 / self.T2)\n self.T4 = self.T0 * self.T3 - self.LambdaC * ((self.qs * self.qs + self.qs) - (self.T0 * self.T0 + self.T0))\n if (self.T1 != 0.0):\n self.T5 = -2.0 * self.LambdaC * (self.T1 * self.T2 - self.ln_T1_T2) / (self.T1 * self.T1)\n else:\n self.T5 = -2.0 * self.LambdaC * (self.T1/self.T2) * (self.T1/self.T2) *(self.T1/self.T2)\n\n self.T6 = self.T0 * self.T5 + self.T3 + self.LambdaC * (2.0 * self.T0 + 1.0)\n self.T0 = self.T0 - (self.T4 / self.T6)\n self.T1 = 2.0 * self.LambdaC * (self.qs - self.T0)\n self.T2 = sqrt(1.0 + self.T1 * self.T1)\n self.ln_T1_T2 = asinh(self.T1)\n if (self.T1 != 0.0):\n self.T3 = self.T2 + (1.0 / self.T1) * self.ln_T1_T2\n else:\n self.T3 = self.T2 + (1.0 / self.T2)\n self.T4 = self.T0 * self.T3 - self.LambdaC * ((self.qs * self.qs + self.qs) - (self.T0 * self.T0 + self.T0))\n if (self.T1 != 0.0):\n self.T5 = -2.0 * self.LambdaC * (self.T1 * self.T2 - self.ln_T1_T2) / (self.T1 * self.T1)\n else:\n self.T5 = (self.T1 / self.T2) * (self.T1 / self.T2) * (self.T1 / self.T2)\n\n self.T6 = self.T0 * self.T5 + self.T3 + self.LambdaC * (2.0 * self.T0 + 1.0)\n self.qdsat = self.T0 - (self.T4/self.T6)\n # qdsat for internal Rds, Ref: BSIM4\n else:\n # Accurate qdsat derived from consistent I-V\n self.T11 = self.Weff * 2.0 * self.nq * self.Cox * self.nVt * self.VSAT_a\n self.T12 = self.T11 * self.LambdaC * self.Rdss / (2.0 * self.nVt)\n self.T0 = 0.5 * self.LambdaC * (self.qs * self.qs + self.qs) / (1.0 + 0.5 * self.LambdaC * (1.0 + self.qs))\n self.T1 = 2.0 * self.LambdaC * (self.qs - self.T0)\n self.T2 = sqrt(1.0 + self.T1 * self.T1)\n self.ln_T1_T2 = asinh(self.T1)\n if (self.T1 != 0.0):\n self.T3 = self.T2 + (1.0 / self.T1) * self.ln_T1_T2\n else:\n self.T3 = self.T2 + (1.0 / self.T2)\n self.T4 = self.T0 * self.T3 + self.T12 * self.T0 * (self.qs + self.T0 + 1.0) - self.LambdaC * ((self.qs * self.qs + self.qs) - (self.T0 * self.T0 + self.T0))\n if (self.T1 != 0.0):\n self.T5 = -2.0 * self.LambdaC * (self.T1 * self.T2 - self.ln_T1_T2) / (self.T1 * self.T1)\n else:\n self.T5 = -2.0 * self.LambdaC * (self.T1 / self.T2) * (self.T1 / self.T2) * (self.T1 / self.T2)\n self.T6 = self.T0 * self.T5 + self.T3 + self.T12 * (self.qs + 2.0 * self.T0 + 1.0) + self.LambdaC * (2.0 * self.T0 + 1.0)\n self.T0 = self.T0 - self.T4 / self.T6\n self.T1 = 2.0 * self.LambdaC * (self.qs - self.T0)\n self.T2 = sqrt(1.0 + self.T1 * self.T1)\n self.ln_T1_T2 = asinh(self.T1)\n if (self.T1 != 0):\n self.T3 = self.T2 + (1.0 / self.T1) * self.ln_T1_T2\n else:\n self.T3 = self.T2 + (1.0 / self.T2)\n self.T4 = self.T0 * self.T3 + self.T12 * self.T0 * (self.qs + self.T0 + 1.0) - self.LambdaC * ((self.qs * self.qs + self.qs) - (self.T0 * self.T0 + self.T0))\n if (self.T1 != 0.0):\n self.T5 = -2.0 * self.LambdaC * (self.T1 * self.T2 - self.ln_T1_T2) / (self.T1 * self.T1)\n else:\n self.T5 = -2.0 * self.LambdaC * (self.T1 / self.T2) * (self.T1 / self.T2) * (self.T1 / self.T2)\n self.T6 = self.T0 * self.T5 + self.T3 + self.T12 * (self.qs + 2.0 * self.T0 + 1.0) + self.LambdaC * (2.0 * self.T0 + 1.0)\n self.qdsat = self.T0 - self.T4 / self.T6\n self.vdsat = self.psip - 2.0 * self.phib_n - (2.0 * self.qdsat + self.lln((self.qdsat * 2.0 * self.nq * self.inv_gam) * ((self.qdsat * 2.0 * self.nq * self.inv_gam) + (self.gam / (self.nq - 1.0)))))\n self.Vdsat = self.vdsat * self.nVt\n\n # Normalized charge qdeff at drain end of channel\n # Vdssat clamped to avoid negative values during transient simulation\n self.Vdssat = self.Smooth(self.Vdsat - self.Vs, 0.0, 1.0e-3)\n self.T7 = (self.Vds / self.Vdssat)**(1.0 / self.DELTA_t)\n self.T8 = (1.0 + self.T7)**-self.DELTA_t\n self.Vdseff = self.Vds * self.T8\n self.vdeff = (self.Vdseff + self.Vs) * self.inv_nVt\n self.qdeff = self.BSIM_q(self.psip, self.phib_n, self.vdeff, self.gam)\n\n # Reevaluation of nq to include qdeff\n self.psiavg = self.psip - self.qs - self.qdeff -1.0\n self.T0 = self.Smooth(self.psiavg, 1.0, 2.0)\n self.T2 = sqrt(self.T0)\n self.nq = 1.0 + self.gam / (self.sqrtpsip + self.T2)\n\n # Inversion and bulk charge\n self.DQSD2 = (self.qs - self.qdeff) * (self.qs - self.qdeff)\n self.T0 = 1.0 / (1.0 + self.qs + self.qdeff)\n self.T1 = self.DQSD2 * self.T0\n self.Qb = self.vgfb - self.psip - (self.nq - 1.0) * (self.qs + self.qdeff + self.Oneby3 * self.T1)\n self.T2 = self.Oneby3 * self.nq\n self.T3 = self.T1 * self.T0\n self.Qs = self.T2 * (2.0 * self.qs + self.qdeff + 0.5 * (1.0 + 0.8 * self.qs + 1.2 * self.qdeff) * self.T3)\n self.Qd = self.T2 * (self.qs + 2.0 * self.qdeff + 0.5 * (1.0 + 1.2 * self.qs + 0.8 * self.qdeff) * self.T3)\n\n # Mobility degradation, Ref: BSIM4\n # Average charges (qba and qia) - normalized to Cox\n self.qba = self.Smooth(self.nVt * self.Qb, 0.0, 0.1)\n self.qia = self.nVt * (self.Qs + self.Qd)\n\n self.Eeffm = self.EeffFactor * (self.qba + self.eta_mu * self.qia)\n self.T2 = (0.5 * (1.0 + (self.qia / self.qba)))**self.UCS_a\n self.T3 = (self.UA_a + self.UC_a * self.Vbsx) * self.Eeffm**self.EU_t + self.UD_a / self.T2\n self.T4 = 1.0 + self.T3\n self.Dmob = self.Smooth(self.T4, 1.0, 0.0015)\n\n # Output conductance\n self.Esat = 2.0 * self.VSAT_a / (self.U0_a / self.Dmob)\n self.EsatL = self.Esat * self.Leff\n if (self.PVAG_i > 0.0):\n self.PVAGfactor = 1.0 + self.PVAG_i * self.qia / self.EsatL\n else:\n self.PVAGfactor = 1.0 / (1.0 - self.PVAG_i * self.qia / self.EsatL)\n\n # Output conductance due to DIBL, Ref: BSIM4\n self.DIBLfactor = self.PDIBLC_a\n self.diffVds = self.Vds - self.Vdseff\n self.Vgst2Vtm = self.qia + 2.0 * self.nVt\n if (self.DIBLfactor > 0.0):\n self.T3 = self.Vgst2Vtm / (self.Vdssat + self.Vgst2Vtm)\n self.T4 = self.hypsmooth((1.0 + self.PDIBLCB_i * self.Vbsx), 1.0e-3)\n self.T5 = 1.0 / self.T4\n self.VaDIBL = self.Vgst2Vtm / self.DIBLfactor * self.T3 * self.PVAGfactor * self.T5\n self.Moc = 1.0 + self.diffVds / self.VaDIBL\n else:\n self.Moc = 1.0\n\n # Degradation factor due to pocket implants, Ref: BSIM4\n if (self.FPROUT_i <= 0.0):\n self.Fp = 1.0\n else:\n self.T9 = self.FPROUT_i * sqrt(self.Leff) / self.Vgst2Vtm\n self.Fp = 1.0 / (1.0 + self.T9)\n\n # Channel length modulation, Ref: BSIM4\n self.Vasat = self.Vdssat + self.EsatL\n if (self.PCLM_a != 0.0):\n if (self.PCLMG < 0.0):\n self.T1 = self.PCLM_a / (1.0 - self.PCLMG * self.qia / self.EsatL) / self.Fp\n else:\n self.T1 = self.PCLM_a * (1.0 + self.PCLMG * self.qia / self.EsatL) / self.Fp\n\n self.MdL = 1.0 + self.T1 * self.lln(1.0 + self.diffVds / self.T1 / self.Vasat)\n else:\n self.MdL = 1.0\n self.Moc = self.Moc * self.MdL\n\n # Calculate Va_DITS, Ref: BSIM4\n self.T1 = self.lexp(self.PDITSD_i * self.Vds)\n if (self.PDITS_i > 0.0):\n self.T2 = 1.0 + self.PDITSL * self.Leff\n self.VaDITS = (1.0 + self.T2 * self.T1) / self.PDITS_i\n self.VaDITS = self.VaDITS * self.Fp\n else:\n self.VaDITS = self.MAX_EXPL\n self.T4 = self.diffVds / self.VaDITS\n self.T0 = 1.0 + self.T4\n self.Moc = self.Moc * self.T0\n\n # Calculate Va_SCBE, Ref: BSIM4\n if (self.PSCBE2_i > 0.0):\n if (self.diffVds > self.PSCBE1_i * self.litl / self.EXPL_THRESHOLD):\n self.T0 = self.PSCBE1_i * self.litl / self.diffVds\n self.VaSCBE = self.Leff * self.lexp(self.T0) / self.PSCBE2_i\n else:\n self.VaSCBE = self.MAX_EXPL * self.Leff/self.PSCBE2_i\n else:\n self.VaSCBE = self.MAX_EXPL\n self.Mscbe = 1.0 + (self.diffVds / self.VaSCBE)\n self.Moc = self.Moc * self.Mscbe\n\n # Velocity saturation\n self.T0 = self.Dmob**(1.0 / self.PSAT_a)\n self.T11 = self.PSATB_i * self.Vbsx\n self.T12 = sqrt(0.1+self.T11*self.T11)\n self.T1 = 0.5*(1-self.T11+sqrt((1-self.T11)*(1-self.T11)+self.T12))\n self.T2 = 10.0 * self.PSATX * self.qia * self.T1 / (10.0 * self.PSATX + self.qia * self.T1)\n if (self.PTWG_a < 0.0):\n self.LambdaC = 2.0 * ((self.U0_a / self.T0) * self.nVt / (self.VSAT_a * self.Leff)) * (1.0 / (1.0 - self.PTWG_a * self.T2))\n else:\n self.LambdaC = 2.0 * ((self.U0_a / self.T0) * self.nVt / (self.VSAT_a * self.Leff)) * (1.0 + self.PTWG_a * self.T2)\n self.T1 = 2.0 * self.LambdaC * (self.qs - self.qdeff)\n self.T2 = sqrt(1.0 + self.T1 * self.T1)\n if (self.T1 != 0.0):\n self.Dvsat = 0.5 * (self.T2 + (1.0 / self.T1) * asinh(self.T1))\n else:\n self.Dvsat = 0.5 * (self.T2 + (1.0 / self.T2))\n self.Dptwg = self.Dvsat\n\n self.Rsource = 0.0\n self.Rdrain = 0.0\n # S/D series resistances, Ref: BSIM4\n if (self.RDSMOD == 1):\n self.Rdsi = 0.0\n self.Dr = 1.0\n # Rs (Source side resistance for all fingers)\n self.T2 = self.Vgs_noswap - self.Vfbsdr\n self.T3 = sqrt(self.T2 * self.T2 + 0.01)\n self.Vgs_eff = 0.5 * (self.T2 + self.T3)\n self.T5 = 1.0 + self.PRWG_i * self.Vgs_eff\n self.T6 = (1.0 / self.T5) + self.PRWB_i * self.Vsb_noswap\n self.T4 = 0.5 * (self.T6 + sqrt(self.T6 * self.T6 + 0.01))\n self.Rsource = self.rdstemp * (self.RSourceGeo + (self.RSWMIN_i + self.RSW_i * self.T4) * self.WeffWRFactor)\n # Rd (Drain side resistance for all fingers)\n self.T2 = self.Vgd_noswap - self.Vfbsdr\n self.T3 = sqrt(self.T2 * self.T2 + 0.01)\n self.Vgd_eff = 0.5 * (self.T2 + self.T3)\n self.T5 = 1.0 + self.PRWG_i * self.Vgd_eff\n self.T6 = (1.0 / self.T5) + self.PRWB_i * self.Vdb_noswap\n self.T4 = 0.5 * (self.T6 + sqrt(self.T6 * self.T6 + 0.01))\n self.Rdrain = self.rdstemp * (self.RDrainGeo + (self.RDWMIN_i + self.RDW_i * self.T4) * self.WeffWRFactor)\n else:\n # Ref: (1) BSIM4 (2) \"Operation and Modeling of the MOS Transistor\" by Yannis Tsividis\n self.T0 = 1.0 + self.PRWG_i * self.qia\n self.T1 = self.PRWB_i * (self.sqrtPhistVbs - self.sqrtPhist)\n self.T2 = 1.0 / self.T0 + self.T1\n self.T3 = 0.5 * (self.T2 + sqrt(self.T2 * self.T2 + 0.01))\n self.Rdsi = self.rdstemp * (self.RDSWMIN_i + self.RDSW_i * self.T3) * self.WeffWRFactor * self.NF\n self.Rdrain = self.RDrainGeo\n self.Rsource = self.RSourceGeo\n self.Dr = 1.0 + self.U0_a /(self.Dvsat * self.Dmob) * self.Cox * self.Weff / self.Leff * self.qia * self.Rdsi\n if (self.RDSMOD == 2):\n self.Rdsi = self.rdstemp * (self.RSourceGeo + (self.RDSWMIN_i + self.RDSW_i * self.T3) * self.WeffWRFactor * self.NF + self.RDrainGeo)\n self.Rdrain = 0.0\n self.Rsource = 0.0\n self.Dr = 1.0 + self.U0_a /(self.Dvsat * self.Dmob) * self.Cox * self.Weff / self.Leff * self.qia * self.Rdsi\n\n # Non-saturation effect\n self.T0 = self.A1_t + self.A2_t / (self.qia + 2.0 * self.n * self.Vtm)\n self.DQSD = self.qs - self.qdeff\n self.T1 = self.T0 * self.DQSD * self.DQSD\n self.T2 = self.T1 + 1.0 - 0.001\n self.T3 = -1.0 + 0.5 * (self.T2 + sqrt(self.T2 * self.T2 + 0.004))\n self.Nsat = 0.5 * (1.0 + sqrt(1.0 + self.T3))\n\n # MNUD model to enhance Id-Vd fitting flexibility\n self.T0 = (self.qs + self.qdeff)\n self.T1 = (self.qs - self.qdeff)\n self.T2 = self.T1 / (self.T0 + self.M0_t)\n self.T3 = self.K0_t * self.T2 * self.T2\n self.Mnud = 1.0 + self.T3\n\n # MNUD1 to enhance the fitting flexiblity for the gm/Id - similar approach used in BSIM-CMG\n self.T9 = self.C0_t / (max(0, self.C0SI_t + self.C0SISAT_t * self.T1 * self.T1) * self.T0 + 2.0 * self.n * self.Vtm)\n self.Mnud1 = self.lexp(-self.T9)\n self.Dtot = self.Dmob * self.Dvsat * self.Dr\n\n # Effective mobility including mobility degradation\n self.ueff = self.U0_a / self.Dtot\n\n # I-V\n self.ids = 2.0 * self.NF * self.nq * self.ueff * self.Weff / self.Leff * self.Cox * self.nVt * self.nVt * ((self.qs - self.qdeff) * (1.0 + self.qs + self.qdeff)) * self.Moc / self.Nsat * self.Mnud * self.Mnud1\n self.ids = self.ids * self.IDS0MULT\n\n # High-voltage model s: Ref. - Harshit Agarwal et.al., IEEE TED vol. 66, issue 10, pp. 4258, 2019\n if (self.RDSMOD == 1 and self.HVMOD == 1):\n self.T4 = 1 + self.PDRWB * self.Vbsx\n self.T0 = self.ids\n self.T11 = self.NF * self.Weff * self.q * self.VDRIFT_t\n if (self.RDLCW != 0):\n self.idrift_sat_d = self.T11 * self.NDRIFTD\n self.delta_hv = self.ids**(4 - self.MDRIFT) / (self.ids**(4 - self.MDRIFT) + self.HVFACTOR * self.idrift_sat_d**(4 - self.MDRIFT))\n self.T5 = self.T0/self.idrift_sat_d\n if (self.T5 >= 0.99):\n self.T5 = 0.5 * ((self.T5 + 0.99) - sqrt( (self.T5 - 0.99) * (self.T5 - 0.99) + 1.0e-6) + 0.001)\n self.T0D = self.delta_hv * self.T5**self.MDRIFT\n self.T1D = 1.0 - self.T0D\n self.T2D = self.T1D**(1.0 / self.MDRIFT)\n self.rdrift_d = self.rdstemphv * self.RDLCW * self.WeffWRFactor/self.T2D * self.T4\n self.IDRIFTSATD = self.idrift_sat_d\n if (self.rdrift_d < 0):\n self.rdrift_d = 0\n if (self.RSLCW != 0):\n self.idrift_sat_s = self.T11 * self.NDRIFTS\n self.delta_hv = self.ids**(4 - self.MDRIFT) / (self.ids**(4 - self.MDRIFT) + self.HVFACTOR * self.idrift_sat_s**(4 - self.MDRIFT))\n self.T5 = self.T0/self.idrift_sat_s\n if (self.T5 >= 0.99):\n self.T5 = 0.5 * ((self.T5 + 0.99) - sqrt( (self.T5 - 0.99) * (self.T5 - 0.99) + 1.0e-6) + 0.001 )\n self.T0S = self.delta_hv * self.T5**self.MDRIFT\n self.T1S = 1.0 - self.T0S\n self.T2S = self.T1S**(1.0 / self.MDRIFT)\n self.rdrift_s = self.rdstemphv * self.RSLCW * self.WeffWRFactor/self.T2S * self.T4\n if (self.rdrift_s < 0.0):\n self.rdrift_s = 0.0\n self.Rdrain = self.Rdrain + self.rdrift_d\n self.Rsource = self.Rsource + self.rdrift_s\n\n # CV calculations for HVMOD\n if (self.RDSMOD == 1 and self.HVCAP == 1 and self.HVMOD == 1):\n self.vgfbdrift = -self.devsign * (self.VG - self.VD) - self.VFBOV\n self.vgfbdrift = self.vgfbdrift/self.Vt\n self.gamhv = sqrt(2.0 * self.q * self.epssi * self.NDR * self.inv_Vt) / self.Cox\n self.phibHV = self.lln(self.NDR / self.ni)\n self.psip_k = self.PO_psip(self.vgfbdrift, self.gamhv, 0.0)\n self.q_k = self.BSIM_q(self.psip_k, self.phibHV, self.devsign * (self.VD - self.VB) / self.Vt, self.gamhv)\n\n # calculate nq for the drift region\n self.psipclamp_hv = self.Smooth(self.psip_k, 1.0, 2.0)\n self.sqrtpsip_k = sqrt(self.psipclamp_hv)\n self.psiavg_hv = self.psip_k - 2.0 * self.q_k\n self.T0 = self.Smooth(self.psiavg_hv, 1.0, 2.0)\n self.nq_hv = 1.0 + self.gamhv / (self.sqrtpsip_k + sqrt(self.T0))\n self.psi_k = self.psip_k - 2 * self.q_k\n\n # contribution due to accumulation of the overlap region\n self.QBOV = self.NF * self.Wact * self.LOVER * self.EPS0 * self.EPSROX / self.BSIMBULKTOXP * self.Vt * (self.vgfbdrift - self.psi_k - 2 * self.nq_hv * self.q_k)\n\n # contribution due to inversion of the overlap region\n if (self.SLHV > 0):\n self.T1 = 1 + self.q_k / self.SLHV1\n self.T2 = self.SLHV * 1.9e-9 / self.T1\n self.T0 = 3.9 * self.EPS0 / (self.BSIMBULKTOXP * 3.9 / self.EPSROX + self.T2 / self.epsratio)\n else:\n self.T0 = self.EPS0 * self.EPSROX / self.BSIMBULKTOXP\n\n self.QIOV = self.NF * self.Wact * self.LOVERACC * 2 * self.nq_hv * self.Vt * self.T0 * self.q_k\n\n # For symmetric device, adding contribution of the source side drift region\n if (self.HVCAPS == 1):\n self.vgfbdrift = -self.devsign * (self.VG - self.VS) - self.VFBOV\n self.vgfbdrift = self.vgfbdrift/self.Vt\n self.psip_k = self.PO_psip(self.vgfbdrift, self.gamhv, 0.0)\n self.q_k = self.BSIM_q(self.psip_k, self.phibHV, self.devsign * (self.VS - self.VB) / self.Vt, self.gamhv)\n self.psipclamp_hv = self.Smooth(self.psip_k, 1.0, 2.0)\n self.sqrtpsip_k = sqrt(self.psipclamp_hv)\n self.psiavg_hv = self.psip_k - 2.0 * self.q_k\n self.T0 = self.Smooth(self.psiavg_hv, 1.0, 2.0)\n self.nq_hv = 1.0 + self.gamhv / (self.sqrtpsip_k + sqrt(self.T0))\n self.psi_k = self.psip_k - 2 * self.q_k\n self.QBOVS = self.NF * self.Wact * self.LOVER * self.EPS0 * self.EPSROX / self.BSIMBULKTOXP * self.Vt * (self.vgfbdrift - self.psi_k - 2 * self.nq_hv * self.q_k)\n if (self.SLHV > 0):\n self.T1 = 1 + self.q_k / self.SLHV1\n self.T2 = self.SLHV * 1.9e-9 / self.T1\n self.T0 = 3.9 * self.EPS0 / (self.BSIMBULKTOXP * 3.9 / self.EPSROX + self.T2 / self.epsratio)\n else:\n self.T0 = self.EPS0 * self.EPSROX / self.BSIMBULKTOXP\n self.QIOVS = self.NF * self.Wact * self.LOVERACC * 2 * self.nq_hv * self.Vt * self.T0 * self.q_k\n if (self.RGATEMOD > 1):\n self.idsovvds = self.ueff * self.Weff / self.Leff * self.Cox * self.qia\n self.T9 = self.XRCRG2 * self.Vt\n self.T0 = self.T9 * self.ueff * self.Weff / self.Leff * self.Cox\n self.Gcrg = self.XRCRG1 * self.NF * (self.T0 + self.idsovvds)\n if (self.RGATEMOD == 2):\n self.T11 = self.Grgeltd + self.Gcrg\n self.Gcrg = self.Grgeltd * self.Gcrg / self.T11\n\n # Impact ionization currents, Ref: BSIM4\n if ((self.ALPHA0_i <= 0.0) or (self.BETA0_t <= 0.0)):\n self.Iii = 0.0\n elif (self.diffVds > self.BETA0_t / self.EXPL_THRESHOLD):\n self.T1 = -self.BETA0_t / self.diffVds\n self.Iii = self.ALPHA0_i * self.diffVds * self.ids * self.lexp(self.T1) / self.Mscbe\n else:\n self.Iii = self.ALPHA0_i * self.diffVds * self.ids * self.MIN_EXPL / self.Mscbe\n\n # Secondary impact ionization in the drift region\n if (self.HVMOD == 1 and self.IIMOD == 1):\n self.Ntot = self.DRII1 * self.ids/(self.NF * self.Weff * self.q * self.VDRIFT_t )\n self.Nextra = self.Ntot/self.NDRIFTD - 1\n self.Nextra = self.Smooth(self.Nextra, 0, self.DELTAII)\n self.Nextra = self.NDRIFTD * self.Nextra\n self.T2 = self.Smooth(self.devsign * (self.VD - self.VB) - self.Vdseff - self.DRII2, 0, 0.05)\n self.T3 = 2.0 * self.q /(self.EPSRSUB * self.EPS0) * self.Nextra\n self.T3 = self.T3 * self.T2\n if (self.T3 > self.BETADR / self.EXPL_THRESHOLD):\n self.T1 = -self.BETADR/self.T3\n self.IsubDR = self.ALPHADR * self.T2 * self.ids * self.lexp(self.T1)\n else:\n self.IsubDR = self.ALPHADR * self.T2 * self.ids * self.MIN_EXPL\n self.Iii = self.Iii + self.IsubDR\n\n # Gate currents, Ref: BSIM4\n if ((self.IGCMOD != 0) or (self.IGBMOD != 0)):\n self.Voxm = self.nVt * (self.vgfb - self.psip + self.qs + self.qdeff)\n self.T1 = sqrt(self.Voxm * self.Voxm + 1.0e-4)\n self.Voxmacc = 0.5 * (-self.Voxm + self.T1)\n self.Voxminv = 0.5 * (self.Voxm + self.T1)\n # Igbinv\n if (self.IGBMOD != 0):\n self.T1 = self.Voxm / self.NIGBACC_i / self.Vt\n self.Vaux_Igbacc = self.NIGBACC_i * self.Vt * self.lln(1.0 + self.lexp(-self.T1))\n self.T2 = self.AIGBACC_i - self.BIGBACC_i * self.Voxmacc\n self.T3 = 1.0 + self.CIGBACC_i * self.Voxmacc\n self.T4 = -7.45669e11 * self.TOXE * self.T2 * self.T3\n self.T5 = self.lexp(self.T4)\n self.T6 = 4.97232e-7\n self.igbacc = self.NF * self.Weff * self.Leff * self.T6 * self.ToxRatio * self.Vg * self.Vaux_Igbacc * self.T5\n self.igbacc = self.igbacc * self.igtemp\n self.T1 = (self.Voxm - self.EIGBINV_i) / self.NIGBINV_i / self.Vt\n self.Vaux_Igbinv = self.NIGBINV_i * self.Vt * self.lln(1.0 + self.lexp(self.T1))\n self.T2 = self.AIGBINV_i - self.BIGBINV_i * self.Voxminv\n self.T3 = 1.0 + self.CIGBINV_i * self.Voxminv\n self.T4 = -9.82222e11 * self.TOXE * self.T2 * self.T3\n self.T5 = self.lexp(self.T4)\n self.T6 = 3.75956e-7\n self.igbinv = self.NF * self.Weff * self.Leff * self.T6 * self.ToxRatio * self.Vg * self.Vaux_Igbinv * self.T5\n self.igbinv = self.igbinv * self.igtemp\n self.igb = self.igbacc + self.igbinv\n if (self.IGCMOD != 0):\n # Igcinv\n self.T1 = self.AIGC_i - self.BIGC_i * self.Voxminv\n self.T2 = 1.0 + self.CIGC_i * self.Voxminv\n self.T3 = self.Bechvb * self.T1 * self.T2\n self.T4 = self.nq * self.nVt * (self.qs + self.qdeff) * self.lexp(self.T3)\n self.igc0 = self.NF * self.Aechvb * self.T4 * (self.Vg + 0.5 * self.Vdsx - 0.5 * (self.Vs + self.Vd)) * self.igtemp\n # Gate-current partitioning\n self.Vdseffx = sqrt(self.Vdseff * self.Vdseff + 0.01) - 0.1\n self.T1 = self.PIGCD_i * self.Vdseffx\n self.T1_exp = self.lexp(-self.T1)\n self.T3 = self.T1 + self.T1_exp -1.0 + 1.0e-4\n self.T4 = 1.0 - (self.T1 + 1.0) * self.T1_exp + 1.0e-4\n self.T5 = self.T1 * self.T1 + 2.0e-4\n if (self.sigvds > 0):\n self.igcd = self.igc0 * self.T4 / self.T5\n self.igcs = self.igc0 * self.T3 / self.T5\n else:\n self.igcs = self.igc0 * self.T4 / self.T5\n self.igcd = self.igc0 * self.T3 / self.T5\n # Igs\n self.T2 = self.Vgs_noswap - self.Vfbsdr\n self.Vgs_eff = sqrt(self.T2 * self.T2 + 1.0e-4)\n if (self.IGCLAMP == 1):\n self.T1 = self.hypsmooth((self.AIGS_i - self.BIGS_i * self.Vgs_eff), 1.0e-6)\n if (self.CIGS_i < 0.01):\n self.CIGS_i = 0.01\n else:\n self.T1 = self.AIGS_i - self.BIGS_i * self.Vgs_eff\n\n self.T2 = 1.0 + self.CIGS_i * self.Vgs_eff\n self.T3 = self.BechvbEdge * self.T1 * self.T2\n self.T4 = self.lexp(self.T3)\n self.igs_mult = self.igtemp * self.NF * self.AechvbEdge * self.DLCIG_i\n self.igs = self.igs_mult * self.Vgs_noswap * self.Vgs_eff * self.T4\n # Igd\n self.T2 = self.Vgd_noswap - self.Vfbsdr\n self.Vgd_eff = sqrt(self.T2 * self.T2 + 1.0e-4)\n if (self.IGCLAMP == 1):\n self.T1 = self.hypsmooth((self.AIGD_i - self.BIGD_i * self.Vgd_eff), 1.0e-6)\n if (self.CIGD_i < 0.01):\n self.CIGD_i = 0.01\n else:\n self.T1 = self.AIGD_i - self.BIGD_i * self.Vgd_eff\n self.T2 = 1.0 + self.CIGD_i * self.Vgd_eff\n self.T3 = self.BechvbEdge * self.T1 * self.T2\n self.T4 = self.lexp(self.T3)\n self.igd_mult = self.igtemp * self.NF * self.AechvbEdge * self.DLCIGD_i\n self.igd = self.igd_mult * self.Vgd_noswap * self.Vgd_eff * self.T4\n\n # GIDL and GISL currents, Ref: BSIM4\n if (self.GIDLMOD != 0):\n self.T0 = self.epsratio * self.TOXE\n # GIDL\n if ((self.AGIDL_i <= 0.0) or (self.BGIDL_t <= 0.0) or (self.CGIDL_i < 0.0)):\n self.T6 = 0.0\n else:\n self.T1 = (-self.Vgd_noswap - self.EGIDL_i + self.Vfbsdr) / self.T0\n self.T1 = self.hypsmooth(self.T1, 1.0e-2)\n self.T2 = self.BGIDL_t / (self.T1 + 1.0e-3)\n if (self.CGIDL_i != 0.0):\n self.T3 = self.Vdb_noswap * self.Vdb_noswap * self.Vdb_noswap\n self.T4 = self.CGIDL_i + abs(self.T3) + 1.0e-4\n self.T5 = self.hypsmooth(self.T3 / self.T4, 1.0e-6) - 1.0e-6\n else:\n self.T5 = 1.0\n self.T6 = self.AGIDL_i * self.Weff * self.T1 * self.lexp(-self.T2) * self.T5\n\n self.igidl = self.T6\n # GISL\n if ((self.AGISL_i <= 0.0) or (self.BGISL_t <= 0.0) or (self.CGISL_i < 0.0)):\n self.T6 = 0.0\n else:\n self.T1 = (-self.Vgs_noswap - self.EGISL_i + self.Vfbsdr) / self.T0\n self.T1 = self.hypsmooth(self.T1, 1.0e-2)\n self.T2 = self.BGISL_t / (self.T1 + 1.0e-3)\n if (self.CGISL_i != 0.0):\n self.T3 = self.Vsb_noswap * self.Vsb_noswap * self.Vsb_noswap\n self.T4 = self.CGISL_i + abs(self.T3) + 1.0e-4\n self.T5 = self.hypsmooth(self.T3 / self.T4, 1.0e-6) - 1.0e-6\n else:\n self.T5 = 1.0\n self.T6 = self.AGISL_i * self.Weff * self.T1 * self.lexp(-self.T2) * self.T5\n self.igisl = self.T6\n\n # Junction currents and capacitances\n # Source-side junction currents\n if (self.Isbs > 0.0):\n if (self.Vbs_jct < self.VjsmRev):\n self.T0 = self.Vbs_jct / self.Nvtms\n self.T1 = self.lexp(self.T0) - 1.0\n self.T2 = self.IVjsmRev + self.SslpRev * (self.Vbs_jct - self.VjsmRev)\n self.Ibs = self.T1 * self.T2\n elif (self.Vbs_jct <= self.VjsmFwd):\n self.T0 = self.Vbs_jct / self.Nvtms\n self.T1 = (self.BVS + self.Vbs_jct) / self.Nvtms\n self.T2 = self.lexp(-self.T1)\n self.Ibs = self.Isbs * (self.lexp(self.T0) + self.XExpBVS - 1.0 - self.XJBVS * self.T2)\n else:\n self.Ibs = self.IVjsmFwd + self.SslpFwd * (self.Vbs_jct - self.VjsmFwd)\n else:\n self.Ibs = 0.0\n\n # Source-side junction tunneling currents\n if (self.JTSS_t > 0.0):\n if ((self.VTSS - self.Vbs_jct) < (self.VTSS * 1.0e-3)):\n self.T0 = -self.Vbs_jct / self.Vtm0 / self.NJTS_t\n self.T1 = self.lexp(self.T0 * 1.0e3) - 1.0\n self.Ibs = self.Ibs - self.ASeff * self.JTSS_t * self.T1\n else:\n self.T0 = -self.Vbs_jct / self.Vtm0 / self.NJTS_t\n self.T1 = self.lexp(self.T0 * self.VTSS / (self.VTSS - self.Vbs_jct)) - 1.0\n self.Ibs = self.Ibs - self.ASeff * self.JTSS_t * self.T1\n if (self.JTSSWS_t > 0.0):\n if ((self.VTSSWS - self.Vbs_jct) < (self.VTSSWS * 1.0e-3)):\n self.T0 = -self.Vbs_jct / self.Vtm0 / self.NJTSSW_t\n self.T1 = self.lexp(self.T0 * 1.0e3) - 1.0\n self.Ibs = self.Ibs - self.PSeff * self.JTSSWS_t * self.T1\n else:\n self.T0 = -self.Vbs_jct / self.Vtm0 / self.NJTSSW_t\n self.T1 = self.lexp(self.T0 * self.VTSSWS / (self.VTSSWS - self.Vbs_jct)) - 1.0\n self.Ibs = self.Ibs - self.PSeff * self.JTSSWS_t * self.T1\n if (self.JTSSWGS_t > 0.0):\n if ((self.VTSSWGS - self.Vbs_jct) < (self.VTSSWGS * 1.0e-3)):\n self.T0 = -self.Vbs_jct / self.Vtm0 / self.NJTSSWG_t\n self.T1 = self.lexp(self.T0 * 1.0e3) - 1.0\n self.Ibs = self.Ibs - self.Weffcj * self.NF * self.JTSSWGS_t * self.T1\n else:\n self.T0 = -self.Vbs_jct / self.Vtm0 / self.NJTSSWG_t\n self.T1 = self.lexp(self.T0 * self.VTSSWGS / (self.VTSSWGS - self.Vbs_jct)) - 1.0\n self.Ibs = self.Ibs - self.Weffcj * self.NF * self.JTSSWGS_t * self.T1\n\n # Drain-side junction currents\n if (self.Isbd > 0.0):\n if (self.Vbd_jct < self.VjdmRev):\n self.T0 = self.Vbd_jct / self.Nvtmd\n self.T1 = self.lexp(self.T0) - 1.0\n self.T2 = self.IVjdmRev + self.DslpRev * (self.Vbd_jct - self.VjdmRev)\n self.Ibd = self.T1 * self.T2\n elif (self.Vbd_jct <= self.VjdmFwd):\n self.T0 = self.Vbd_jct / self.Nvtmd\n self.T1 = (self.BVD + self.Vbd_jct) / self.Nvtmd\n self.T2 = self.lexp(-self.T1)\n self.Ibd = self.Isbd * (self.lexp(self.T0) + self.XExpBVD - 1.0 - self.XJBVD * self.T2)\n else:\n self.Ibd = self.IVjdmFwd + self.DslpFwd * (self.Vbd_jct - self.VjdmFwd)\n else:\n self.Ibd = 0.0\n\n # Drain-side junction tunneling currents\n if (self.JTSD_t > 0.0):\n if ((self.VTSD - self.Vbd_jct) < (self.VTSD * 1.0e-3)):\n self.T0 = -self.Vbd_jct / self.Vtm0 / self.NJTSD_t\n self.T1 = self.lexp(self.T0 * 1.0e3) - 1.0\n self.Ibd = self.Ibd - self.ADeff * self.JTSD_t * self.T1\n else:\n self.T0 = -self.Vbd_jct / self.Vtm0 / self.NJTSD_t\n self.T1 = self.lexp(self.T0 * self.VTSD/ (self.VTSD - self.Vbd_jct)) - 1.0\n self.Ibd = self.Ibd - self.ADeff * self.JTSD_t * self.T1\n if (self.JTSSWD_t > 0.0):\n if ((self.VTSSWD - self.Vbd_jct) < (self.VTSSWD * 1.0e-3)):\n self.T0 = -self.Vbd_jct / self.Vtm0 / self.NJTSSWD_t\n self.T1 = self.lexp(self.T0 * 1.0e3) - 1.0\n self.Ibd = self.Ibd - self.PDeff * self.JTSSWD_t * self.T1\n else:\n self.T0 = -self.Vbd_jct / self.Vtm0 / self.NJTSSWD_t\n self.T1 = self.lexp(self.T0 * self.VTSSWD / (self.VTSSWD - self.Vbd_jct)) - 1.0\n self.Ibd = self.Ibd - self.PDeff * self.JTSSWD_t * self.T1\n if (self.JTSSWGD_t > 0.0):\n if ((self.VTSSWGD - self.Vbd_jct) < (self.VTSSWGD * 1.0e-3)):\n self.T0 = -self.Vbd_jct / self.Vtm0 / self.NJTSSWGD_t\n self.T1 = self.lexp(self.T0 * 1.0e3) - 1.0\n self.Ibd = self.Ibd - self.Weffcj * self.NF * self.JTSSWGD_t * self.T1\n else:\n self.T0 = -self.Vbd_jct / self.Vtm0 / self.NJTSSWGD_t\n self.T1 = self.lexp(self.T0 * self.VTSSWGD / (self.VTSSWGD - self.Vbd_jct)) - 1.0\n self.Ibd = self.Ibd - self.Weffcj * self.NF * self.JTSSWGD_t * self.T1\n\n\n # Junction capacitances (no swapping)\n # Source-to-bulk junction\n self.Czbs = self.CJS_t * self.ASeff\n self.Czbssw = self.CJSWS_t * self.PSeff\n self.Czbsswg = self.CJSWGS_t * self.Weffcj * self.NF\n self.czbs_p1 = 0.1**-self.MJS\n self.czbs_p2 = 1.0 / (1.0 - self.MJS) * (1.0 - 0.05 * self.MJS * (1.0 + self.MJS) * self.czbs_p1)\n self.czbssw_p1 = 0.1**-self.MJSWS\n self.czbssw_p2 = 1.0 / (1.0 - self.MJSWS) * (1.0 - 0.05 * self.MJSWS * (1.0 + self.MJSWS) * self.czbssw_p1)\n self.czbsswg_p1 = 0.1**-self.MJSWGS\n self.czbsswg_p2 = 1.0 / (1.0 - self.MJSWGS) * (1.0 - 0.05 * self.MJSWGS * (1.0 + self.MJSWGS) * self.czbsswg_p1)\n self.Qbsj1 = self.JunCap(self.Czbs, self.Vbs_jct, self.PBS_t, self.MJS, self.czbs_p1, self.czbs_p2)\n self.Qbsj2 = self.JunCap(self.Czbssw, self.Vbs_jct, self.PBSWS_t, self.MJSWS, self.czbssw_p1, self.czbssw_p2)\n self.Qbsj3 = self.JunCap(self.Czbsswg, self.Vbs_jct, self.PBSWGS_t, self.MJSWGS, self.czbsswg_p1, self.czbsswg_p2)\n self.Qbsj = self.Qbsj1 + self.Qbsj2 + self.Qbsj3\n\n # Drain-to-bulk junction\n self.Czbd = self.CJD_t * self.ADeff\n self.Czbdsw = self.CJSWD_t * self.PDeff\n self.Czbdswg = self.CJSWGD_t * self.Weffcj * self.NF\n self.czbd_p1 = 0.1**-self.MJD\n self.czbd_p2 = 1.0 / (1.0 - self.MJD) * (1.0 - 0.05 * self.MJD * (1.0 + self.MJD) * self.czbd_p1)\n self.czbdsw_p1 = 0.1**-self.MJSWD\n self.czbdsw_p2 = 1.0 / (1.0 - self.MJSWD) * (1.0 - 0.05 * self.MJSWD * (1.0 + self.MJSWD) * self.czbdsw_p1)\n self.czbdswg_p1 = 0.1**-self.MJSWGD\n self.czbdswg_p2 = 1.0 / (1.0 - self.MJSWGD) * (1.0 - 0.05 * self.MJSWGD * (1.0 + self.MJSWGD) * self.czbdswg_p1)\n self.Qbdj1 = self.JunCap(self.Czbd, self.Vbd_jct, self.PBD_t, self.MJD, self.czbd_p1, self.czbd_p2)\n self.Qbdj2 = self.JunCap(self.Czbdsw, self.Vbd_jct, self.PBSWD_t, self.MJSWD, self.czbdsw_p1, self.czbdsw_p2)\n self.Qbdj3 = self.JunCap(self.Czbdswg, self.Vbd_jct, self.PBSWGD_t, self.MJSWGD, self.czbdswg_p1, self.czbdswg_p2)\n self.Qbdj = self.Qbdj1 + self.Qbdj2 + self.Qbdj3\n\n # Sub-surface leakage drain current\n if (self.SSLMOD != 0):\n self.T1 = (self.NDEP_i / 1.0e23)**self.SSLEXP1\n self.T2 = (300.0 / self.DevTemp)**self.SSLEXP2\n self.T3 = (self.devsign * self.SSL5 * (self.VB - self.VS)) / self.Vt\n self.SSL0_NT = self.SSL0 * self.lexp(-self.T1 * self.T2)\n self.SSL1_NT = self.SSL1 * self.T2 * self.T1\n self.PHIB_SSL = self.SSL3 * tanh(self.lexp(self.devsign * self.SSL4 * ((self.VG - self.VB) - self.VTH - (self.VS - self.VB))))\n self.Issl = self.sigvds * self.NF * self.Weff * self.SSL0_NT * self.lexp(self.T3) * self.lexp(-self.SSL1_NT * self.Leff) * self.lexp(self.PHIB_SSL / self.Vt) * (self.lexp(self.SSL2 * self.Vdsx / self.Vt) - 1.0)\n\n # Harshit's new flicker noise model. Ref: H. Agarwal et. al., IEEE J-EDS, vol. 3, no. 4, April 2015.\n self.Nt = 4.0 * self.Vt * self.q\n self.Esatnoi = 2.0 * self.VSAT_a / self.ueff\n if (self.EM <= 0.0):\n self.DelClm = 0.0\n else:\n self.T0 = (self.diffVds / self.litl + self.EM) / self.Esatnoi\n self.DelClm = self.litl * self.lln(self.T0)\n if (self.DelClm < 0.0):\n self.DelClm = 0.0\n\n self.Nstar = self.Vt / self.q * (self.Cox + self.Cdep + self.CIT_i)\n self.Nl = 2.0 * self.nq * self.Cox * self.Vt * self.qdeff * self.Mnud1 * self.Mnud / self.q\n self.T0a = self.q * self.q * self.q * self.Vt * abs(self.ids) * self.ueff\n self.T0b = self.q * self.Vt * self.ids * self.ids\n self.T0c = self.NOIA + self.NOIB * self.Nl + self.NOIC * self.Nl * self.Nl\n self.T0d = (self.Nl + self.Nstar) * (self.Nl + self.Nstar)\n self.T0e = self.NOIA * self.q * self.Vt\n if (self.FNOIMOD == 1):\n self.LH1 = self.LH\n if (self.Leff > self.LH1):\n self.T0 = (self.Leff - self.LH1)\n else:\n self.LH1 = self.Leff\n self.T0 = self.LH1\n if (self.LINTNOI >= self.T0 / 2.0):\n print(\"Warning: LINTNOI = %e is too large - Leff for noise is negative. Re-setting LINTNOI = 0.\", LINTNOI)\n self.LINTNOI_i = 0.0\n else:\n self.LINTNOI_i = self.LINTNOI\n\n self.LeffnoiH = self.Leff\n self.vgfbh = (self.Vg - self.VFB_i) / self.Vt\n self.gam_h = sqrt(2.0 * self.q * self.epssi * self.HNDEP / self.Vt) / self.Cox\n self.phib_h = log(self.HNDEP / self.ni)\n\n # Pinch-Off potential for halo region\n self.psiph = self.PO_psip(self.vgfbh, self.gam_h, 0.0)\n\n # Normalized inversion charge at source end of halo MOSFET\n self.qsh = self.BSIM_q(self.psiph, self.phib_h, self.vs, self.gam_h)\n self.nq_h = 1.0 + self.gam_h / (2.0 * sqrt(self.psiph))\n\n # Setting mobility of halo region equal to the mobility of the channel. In general, U0H < ueff\n self.U0_i_h = self.ueff\n self.beta_h = self.U0_i_h * self.Cox * self.Weff\n self.beta_ch = self.ueff * self.Cox * self.Weff\n\n # Normalized drain current for halo transistor. Eq. (14) of the paper\n self.i1 = self.ids * self.LH1 / (2.0 * self.nq_h * self.beta_h * self.Vt * self.Vt)\n\n # Normalized drain current for channel transistor. Eq. (15) of the paper\n self.i2 = self.ids * (self.LeffnoiH - self.LH1) / (2.0 * self.nq * self.beta_ch * self.nVt * self.nVt)\n self.T0 = (1.0 + 4.0 * (self.qsh * self.qsh + self.qsh - self.i1))\n if (self.T0 < 1.0):\n self.qdh = 0.0\n else:\n # Drain charge of halo transistor. Eq. (16) of the paper\n self.qdh = -0.5 + 0.5 * sqrt(self.T0)\n\n # Source charge of channel transistor. Eq. (17) of the paper\n self.qsch = -0.5 + 0.5 * sqrt(1.0 + 4.0 * (self.qdeff * self.qdeff + self.qdeff + self.i2))\n self.gds_h = 2.0 * self.nq_h * self.beta_h * self.Vt * self.qdh\n self.gds_ch = 2.0 * self.nq * self.beta_ch * self.Vt * self.qdeff\n self.gm_ch = 2.0 * self.beta_ch * self.Vt * (self.qsch - self.qdeff)\n self.R_ch = self.gds_h * (self.LeffnoiH - self.LH1)\n self.R_h = self.gm_ch * self.LH1 + self.gds_ch * self.LH1\n self.t_tot = 1.0 / (self.R_ch + self.R_h) / (self.R_ch + self.R_h)\n self.CF_ch = self.R_ch * self.R_ch * self.t_tot\n self.CF_h = self.R_h * self.R_h * self.t_tot\n\n # Local noise source\n if (self.Leff != self.LH1):\n self.Np2 = 2.0 * self.nq * self.Cox * self.Vt * self.qsch / self.q\n self.Leffnoi = self.LeffnoiH - 2.0 * self.LINTNOI_i-self.LH1\n self.Leffnoisq = self.Leffnoi * self.Leffnoi\n # Channel transistor LNS\n self.T1 = 1.0e10 * self.Cox * self.Leffnoisq\n self.T2 = self.NOIA * self.lln((self.Np2 + self.Nstar) / (self.Nl + self.Nstar))\n self.T3 = self.NOIB * (self.Np2 - self.Nl)\n self.T4 = 0.5 * self.NOIC * (self.Np2 * self.Np2 - self.Nl * self.Nl)\n self.T5 = 1.0e10 * self.Leffnoisq * self.Weff * self.NF\n self.Ssi_ch = self.T0a / self.T1 * (self.T2 + self.T3 + self.T4) + self.T0b / self.T5 * self.DelClm * self.T0c / self.T0d\n self.T6 = self.Weff * self.NF * self.Leffnoi * 1.0e10 * self.Nstar * self.Nstar\n self.Swi_ch = self.T0e / self.T6 * self.ids * self.ids\n self.T7 = self.Swi_ch + self.Ssi_ch\n if (self.T7 > 0.0):\n self.FNPowerAt1Hz_ch = (self.Ssi_ch * self.Swi_ch) / self.T7\n else:\n self.FNPowerAt1Hz_ch = 0.0\n else:\n self.FNPowerAt1Hz_ch = 0.0\n # Halo transistor LNS\n self.T8 = self.NOIA2 * self.q * self.Vt\n self.T9 = self.Weff * self.NF * self.LH1 * 1.0e10 * self.Nstar * self.Nstar\n self.Swi_h = self.T8 / self.T9 * self.ids * self.ids\n self.T10 = self.Swi_h\n if (self.T10 > 0.0):\n self.FNPowerAt1Hz_h = self.Swi_h\n else:\n self.FNPowerAt1Hz_h = 0.0\n # Overall noise\n self.FNPowerAt1Hz = self.FNPowerAt1Hz_ch * self.CF_ch + self.FNPowerAt1Hz_h * self.CF_h\n else:\n # Parameter checking\n if (self.LINTNOI >= self.Leff/2.0):\n print(\"Warning: LINTNOI = %e is too large - Leff for noise is negative. Re-setting LINTNOI = 0.\", LINTNOI)\n self.LINTNOI_i = 0.0\n else:\n self.LINTNOI_i = self.LINTNOI\n\n if (self.NOIA > 0.0 or self.NOIB > 0.0 or self.NOIC > 0.0):\n self.Leffnoi = self.Leff - 2.0 * self.LINTNOI_i\n self.Leffnoisq = self.Leffnoi * self.Leffnoi\n self.T0 = 1.0e10 * self.Cox * self.Leffnoisq\n self.N0 = 2.0 * self.nq * self.Cox * self.Vt * self.qs * self.Mnud1 * self.Mnud / self.q\n self.T1 = self.NOIA * self.lln((self.N0 + self.Nstar) / (self.Nl + self.Nstar))\n self.T2 = self.NOIB * (self.N0 - self.Nl)\n self.T3 = 0.5 * self.NOIC * (self.N0 * self.N0 - self.Nl * self.Nl)\n self.T4 = 1.0e10 * self.Leffnoisq * self.Weff * self.NF\n self.Ssi = self.T0a / self.T0 * (self.T1 + self.T2 + self.T3) + self.T0b / self.T4 * self.DelClm * self.T0c / self.T0d\n self.T5 = self.Weff * self.NF * self.Leffnoi * 1.0e10 * self.Nstar * self.Nstar\n self.Swi = self.T0e / self.T5 * self.ids * self.ids\n self.T6 = self.Swi + self.Ssi\n if (self.T6 > 0.0):\n self.FNPowerAt1Hz = (self.Ssi * self.Swi) / self.T6 / (1 + self.NOIA1 * (self.qs-self.qdeff)**self.NOIAX)\n else:\n self.FNPowerAt1Hz = 0.0\n else:\n self.FNPowerAt1Hz = 0.0\n self.T0 = self.qia / self.Esatnoi / self.Leff\n self.T1 = self.T0 * self.T0\n self.T3 = self.RNOIA * (1.0 + self.TNOIA * self.Leff * self.T1)\n self.T4 = self.RNOIB * (1.0 + self.TNOIB * self.Leff * self.T1)\n self.T5 = self.RNOIK * (1.0 + self.TNOIK * self.Leff * self.T1)\n self.ctnoi = self.RNOIC * (1.0 + self.TNOIC * self.Leff * self.T1)\n self.betanoisq = 3.0 * self.T3 * self.T3\n self.betanoisq = (self.betanoisq - 1.0) * exp(-self.Leff / self.LP) + 1.0\n self.betaLowId = self.T5 * self.T5\n self.thetanoisq = self.T4 * self.T4\n self.cm_igid = 0.0\n\n # C-V model\n self.vgfbCV = self.vgfb\n self.gamg2 = (2.0 * self.q * self.epssi * self.NGATE_i) / (self.Cox * self.Cox * self.Vt)\n self.invgamg2 = 0.0\n if (self.CVMOD == 1):\n self.VFBCV_i = self.VFBCV_i + self.DELVTO\n self.vg = self.Vg * self.inv_Vt\n self.vs = self.Vs * self.inv_Vt\n self.vfb = self.VFBCV_i * self.inv_Vt\n self.vgfbCV = self.vg - self.vfb\n self.phibCV = self.lln(self.NDEPCV_i / self.ni)\n # Normalized body factor\n self.gamCV = sqrt(2.0 * self.q * self.epssi * self.NDEPCV_i * self.inv_Vt) / self.Cox\n self.inv_gam = 1.0 / self.gamCV\n self.gamg2 = (2.0 * self.q * self.epssi * self.NGATE_i) / (self.Cox * self.Cox * self.Vt)\n self.invgamg2 = (1.0 / self.gamg2) if (self.NGATE_i > 0.0) else 0.0\n self.DPD = (self.NDEPCV_i / self.NGATE_i) if (self.NGATE_i > 0.0) else 0.0\n\n # psip: pinch-off voltage\n self.psip = self.PO_psip(self.vgfbCV, self.gamCV, self.DPD)\n\n # Normalized inversion charge at source end of channel\n self.qs = self.BSIM_q(self.psip, self.phibCV, self.vs, self.gamCV)\n self.psipclamp = self.Smooth(self.psip, 1.0, 2.0)\n self.sqrtpsip = sqrt(self.psipclamp)\n\n # Source side surface potential\n self.psiavg = self.psip - 2.0 * self.qs\n self.T0 = self.Smooth(self.psiavg, 1.0, 2.0)\n self.nq = 1.0 + self.gamCV / (self.sqrtpsip + sqrt(self.T0))\n\n # Drain saturation voltage\n self.T0 = self.Vt * (self.vgfbCV - self.psip - 2.0 * self.qs * (self.nq - 1.0))\n self.qbs = self.Smooth(self.T0, 0.0, 0.1)\n\n # Source side qi and qb for Vdsat (normalized to Cox)\n self.qis = 2.0 * self.nq * self.Vt * self.qs\n self.Eeffs = self.EeffFactor * (self.qbs + self.eta_mu * self.qis)\n\n # Ref: BSIM4 mobility model\n self.T3 = (self.UA_a + self.UC_a * self.Vbsx) * self.Eeffs**self.EU_t\n self.T4 = 1.0 + self.T3\n self.Dmobs = self.Smooth(self.T4, 1.0, 0.0015)\n self.LambdaC_by2 = (self.U0_a / self.Dmobs) * self.Vt / (self.VSATCV_t * self.Lact)\n self.qdsat = self.LambdaC_by2 * (self.qs * self.qs + self.qs) / (1.0 + self.LambdaC_by2 * (1.0 + self.qs))\n self.vdsatcv = self.psip - 2.0 * self.phibCV - (2.0 * self.qdsat + self.lln((self.qdsat * 2.0 * self.nq * self.inv_gam) * ((self.qdsat * 2.0 * self.nq * self.inv_gam) + (self.gam / (self.nq - 1.0)))))\n self.VdsatCV = self.vdsatcv * self.Vt\n\n # Normalized charge qdeff at drain end of channel\n self.VdssatCV = self.Smooth(self.VdsatCV - self.Vs, 0.0, 1e-3)\n self.VdssatCV = self.VdssatCV / self.ABULK\n self.T7 = (self.Vds / self.VdssatCV)**(1.0 / self.DELTA_t)\n self.T8 = (1.0 + self.T7)**-self.DELTA_t\n self.Vdseff = self.Vds * self.T8\n self.vdeff = (self.Vdseff + self.Vs) * self.inv_Vt\n self.qdeff = self.BSIM_q(self.psip, self.phibCV, self.vdeff, self.gamCV)\n\n # Reevaluation of nq to include qdeff needed for gummel symmetry\n self.psiavg = self.psip - self.qs - self.qdeff - 1.0\n self.T0 = self.Smooth(self.psiavg, 1.0, 2.0)\n self.T2 = sqrt(self.T0)\n self.T3 = 1.0 + self.DPD + self.gamCV / (self.sqrtpsip + self.T2)\n self.T4 = 0.5 + self.DPD * self.T2 * self.inv_gam\n self.T5 = sqrt(self.T4 * self.T4 + self.T3 * (self.qs + self.qdeff) * self.invgamg2)\n self.nq = self.T3 / (self.T4 + self.T5)\n\n # C-V expressions including velocity saturation and CLM\n # Velocity saturation for C-V\n self.T0 = self.Vt * (self.vgfbCV - self.psip - 2.0 * self.qs * (self.nq - 1.0))\n self.qbs = self.Smooth(self.T0, 0.0, 0.1)\n self.T1 = self.Vt * (self.vgfbCV - self.psip - 2.0 * self.qdeff * (self.nq - 1.0))\n self.qbd = self.Smooth(self.T1, 0.0, 0.1)\n self.qb = 0.5 * (self.qbs + self.qbd)\n self.qia = self.nq * self.Vt * (self.qs + self.qdeff)\n self.Eeffm = self.EeffFactor * (self.qb + self.eta_mu * self.qia)\n self.psip = self.PO_psip((self.vgfbCV + self.DELVFBACC * self.inv_Vt), self.gamCV, self.DPD)\n self.T3 = (self.UA_a + self.UC_a * self.Vbsx) * self.Eeffm**self.EU_t\n self.T4 = 1.0 + self.T3\n self.Dmob = self.Smooth(self.T4, 1.0, 0.0015)\n self.LambdaC = 2.0 * (self.U0_a / self.Dmob) * self.Vt / (self.VSATCV_t * self.Lact)\n self.dps = self.qs - self.qdeff\n self.T1 = 2.0 * (self.LambdaC * self.dps) * (self.LambdaC * self.dps)\n self.zsat = sqrt(1.0 + self.T1)\n self.Dvsat = 0.5 * (1.0 + self.zsat)\n # CLM for C-V\n self.Esat = 2.0 * self.VSATCV_t / (self.U0_a / self.Dmob)\n self.EsatL = self.Esat * self.Lact\n self.Vasat = self.VdssatCV + self.EsatL\n self.diffVds = self.Vds - self.Vdseff\n if (self.PCLMCV_i != 0.0):\n self.MdL = 1.0 + self.PCLMCV_i * self.lln(1.0 + self.diffVds / self.PCLMCV_i / self.Vasat)\n else:\n self.MdL = 1.0\n self.MdL_2 = self.MdL * self.MdL\n self.inv_MdL = 1.0 / self.MdL\n self.inv_MdL_2 = 1.0 / self.MdL_2\n self.MdL_less_1 = self.MdL - 1.0\n self.vgpqm = self.vgfbCV - self.psip\n self.DQSD = (self.qs - self.qdeff)\n self.DQSD2 = (self.qs - self.qdeff) * (self.qs - self.qdeff)\n self.sis = self.vgpqm + 2.0 * self.qs\n self.sid = self.vgpqm + 2.0 * self.qdeff\n self.T1 = self.Smooth(self.sis, 0.0, 0.5)\n self.T2 = self.Smooth(self.sid, 0.0, 0.5)\n self.Temps = sqrt(0.25 + self.T1 * self.invgamg2)\n self.Tempd = sqrt(0.25 + self.T2 * self.invgamg2)\n self.T1 = self.sis / (1.0 + 2.0 * self.Temps)\n self.T2 = self.sid / (1.0 + 2.0 * self.Tempd)\n self.T3 = self.Temps + self.Tempd\n self.T4 = self.Oneby3 * (self.DQSD2 / (self.T3 * self.T3 * self.T3))\n self.T5 = (self.ABULK*self.Dvsat * self.inv_MdL) / (1.0 + self.qs + self.qdeff)\n self.T6 = 0.8 * (self.T3 * self.T3 + self.Temps * self.Tempd) * self.T5\n self.T7 = self.T6 + (2.0 * self.invgamg2)\n self.T8 = self.Oneby3 * self.DQSD2 * self.T5\n self.dqgeff = self.sid * (2.0 * self.Tempd - 1.0) / (2.0 * self.Tempd + 1.0)\n self.qbeff = self.vgpqm - 2.0 * (self.nq - 1.0) * self.qdeff + self.dqgeff\n self.Qb = self.inv_MdL * (self.T1 + self.T2 + (self.T4 * self.T7 - self.nq * (self.qs + self.qdeff + self.T8))) + self.MdL_less_1 * self.qbeff\n self.T9 = self.qs + self.qdeff\n self.T10 = self.DQSD2 * self.T5 * self.T5\n self.Qi = self.nq * self.inv_MdL * (self.T9 + self.Oneby3 * self.DQSD2 * self.T5) + 2.0 * self.nq * self.MdL_less_1 * self.qdeff\n self.Qd1 = self.nq * self.inv_MdL_2 * (0.5 * self.T9 - (self.DQSD / 6.0) * (1.0 - self.DQSD * self.T5 - 0.2 * self.T10))\n self.Qd2 = self.nq * (self.MdL - self.inv_MdL) * self.qdeff\n self.Qd = self.Qd1 + self.Qd2\n self.Qs = self.Qi - self.Qd\n\n # Quantum mechanical effects\n self.qbaCV = self.Smooth(self.Vt * self.Qb, 0.0, 0.1)\n self.qiaCV = self.Vt * (self.Qs + self.Qd)\n self.T0 = (self.qiaCV + self.ETAQM * self.qbaCV) / self.QM0\n self.T1 = 1.0 + self.T0**(0.7 * self.BDOS)\n self.XDCinv = self.ADOS * 1.9e-9 / self.T1\n self.Coxeffinv = 3.9 * self.EPS0 / (self.BSIMBULKTOXP * 3.9 / self.EPSROX + self.XDCinv / self.epsratio)\n self.QBi = -self.NF * self.Wact * self.Lact * (self.EPS0 * self.EPSROX / self.BSIMBULKTOXP) * self.Vt * self.Qb\n self.WLCOXVtinv = self.NF * self.Wact * self.Lact * self.Coxeffinv * self.Vt\n self.QSi = -self.WLCOXVtinv * self.Qs\n self.QDi = -self.WLCOXVtinv * self.Qd\n self.QGi = -(self.QBi + self.QSi + self.QDi)\n\n # Outer fringing capacitances\n if self.CFgiven == False:\n self.CF_i = 2.0 * self.EPSROX * self.EPS0 / self.M_PI * self.lln(self.CFRCOEFF * (1.0 + 0.4e-6 / self.TOXE))\n self.Cgsof = self.CGSO + self.CF_i\n self.Cgdof = self.CGDO + self.CF_i\n\n # Overlap capacitances\n if (self.COVMOD == 0):\n self.Qovs = -self.Wact * self.NF * self.Cgsof * self.Vgs_ov_noswap\n self.Qovd = -self.Wact * self.NF * self.Cgdof * self.Vgd_ov_noswap\n else:\n self.T0 = sqrt((self.Vgs_ov_noswap - self.Vfbsdr + self.DELTA_1) * (self.Vgs_ov_noswap - self.Vfbsdr + self.DELTA_1) + 4.0 * self.DELTA_1)\n self.Vgsov = 0.5 * (self.Vgs_ov_noswap - self.Vfbsdr + self.DELTA_1 - self.T0)\n self.T1 = sqrt(1.0 - 4.0 * self.Vgsov / self.CKAPPAS_i)\n self.Qovs = -self.Wact * self.NF * (self.Cgsof * self.Vgs_ov_noswap + self.CGSL_i * (self.Vgs_ov_noswap - self.Vfbsdr - self.Vgsov - 0.5 * self.CKAPPAS_i * (-1.0 + self.T1)))\n self.T0 = sqrt((self.Vgd_ov_noswap - self.Vfbsdr + self.DELTA_1) * (self.Vgd_ov_noswap - self.Vfbsdr + self.DELTA_1) + 4.0 * self.DELTA_1)\n self.Vgdov = 0.5 * (self.Vgd_ov_noswap - self.Vfbsdr + self.DELTA_1 - self.T0)\n self.T2 = sqrt(1.0 - 4.0 * self.Vgdov / self.CKAPPAD_i)\n self.Qovd = -self.Wact * self.NF * (self.Cgdof * self.Vgd_ov_noswap + self.CGDL_i * (self.Vgd_ov_noswap - self.Vfbsdr - self.Vgdov - 0.5 * self.CKAPPAD_i * (-1.0 + self.T2)))\n self.Qovb = -self.devsign * self.NF * self.Lact * self.CGBO * (self.VG - self.VB)\n self.Qovg = -(self.Qovs + self.Qovd + self.Qovb)\n\n # Edge FET model\n if (self.EDGEFET == 1):\n self.phib_edge = self.lln(self.NDEPEDGE_i / self.ni)\n self.Phist = max(0.4 + self.Vt * self.phib_edge + self.PHIN_i, 0.4)\n self.sqrtPhist = sqrt(self.Phist)\n self.T1DEP = sqrt(2.0 * self.epssi / (self.q * self.NDEPEDGE_i))\n self.NFACTOREDGE_t = self.NFACTOREDGE_i * self.hypsmooth((1.0 + self.TNFACTOREDGE_i * (self.TRatio - 1.0)), 1e-3)\n self.ETA0EDGE_t = self.ETA0EDGE_i * (1.0 + self.TETA0EDGE_i * (self.TRatio - 1.0))\n self.PhistVbs = self.Smooth(self.Phist - self.Vbsx, 0.05, 0.1)\n self.sqrtPhistVbs = sqrt(self.PhistVbs)\n self.Xdep = self.T1DEP * self.sqrtPhistVbs\n self.Cdep = self.epssi / self.Xdep\n self.cdsc = self.CITEDGE_i + self.NFACTOREDGE_t + self.CDSCDEDGE_i * self.Vdsx - self.CDSCBEDGE_i * self.Vbsx\n self.T1 = 1.0 + self.cdsc/self.Cox\n self.n = self.Smooth(self.T1, 1.0, 0.05)\n self.nVt = self.n * self.Vt\n self.inv_nVt = 1.0 / self.nVt\n self.vg = self.Vg * self.inv_nVt\n self.vs = self.Vs * self.inv_nVt\n self.vfb = self.VFB_i * self.inv_nVt\n self.dvth_dibl = -(self.ETA0EDGE_t + self.ETABEDGE_i * self.Vbsx) * self.Vdsx\n self.dvth_temp = (self.KT1EDGE_i + self.KT1LEDGE_i / self.Leff + self.KT2EDGE_i * self.Vbsx) * (self.TRatio**self.KT1EXPEDGE_i - 1.0)\n self.litl_edge = self.litl * (1.0 + self.DVT2EDGE * self.Vbsx)\n self.T0 = self.DVT1EDGE * self.Leff / self.litl_edge\n if (self.T0 < 40.0):\n self.theta_sce_edge = 0.5 * self.DVT0EDGE / (cosh(self.T0) - 1.0)\n else:\n self.theta_sce_edge = self.DVT0EDGE * self.lexp(-self.T0)\n self.dvth_sce = self.theta_sce_edge * (self.Vbi_edge - self.Phist)\n self.Vth_shift = self.dvth_dibl - self.dvth_temp + self.dvth_sce + self.DVTEDGE + self.vth0_stress_EDGE - self.K2EDGE_i * self.Vbsx\n self.vgfb = self.vg - self.vfb - self.Vth_shift * self.inv_nVt\n\n # Normalized body factor\n self.DGAMMAEDGE_i = self.DGAMMAEDGE * (1.0 + self.DGAMMAEDGEL * self.Leff**-self.DGAMMAEDGELEXP)\n self.gam_edge = sqrt(2.0 * self.q * self.epssi * self.NDEPEDGE_i * self.inv_nVt) / self.Cox\n self.gam_edge = self.gam_edge * (1.0 + self.DGAMMAEDGE_i)\n self.inv_gam = 1.0 / self.gam_edge\n\n # psip: pinch-off voltage\n self.phib_n_edge = self.phib_edge / self.n\n self.psip = self.PO_psip(self.vgfb, self.gam_edge, 0.0)\n self.qs_edge = self.BSIM_q(self.psip, self.phib_n_edge, self.vs, self.gam_edge)\n\n # Approximate pinch-off voltage\n self.vdsatedge = 2.0 * self.nVt * self.qs_edge + 2.0 * self.nVt\n self.Vdsatedge = self.vdsatedge\n self.Vdsatedge = self.Vdsatedge + self.Vs\n\n # Vdssat clamped to avoid negative values during transient simulation\n self.Vdssate = self.Smooth(self.Vdsatedge - self.Vs, 0.0, 1.0e-3)\n self.T7 = (self.Vds / self.Vdssate)**(1.0 / self.DELTA_t)\n self.T8 = (1.0 + self.T7)**-self.DELTA_t\n self.Vdseff = self.Vds * self.T8\n self.vdeff = (self.Vdseff + self.Vs) * self.inv_nVt\n self.qdeff_edge = self.BSIM_q(self.psip, self.phib_n_edge, self.vdeff, self.gam_edge)\n\n # Nq calculation for Edge FET\n self.psipclamp = self.Smooth(self.psip, 1.0, 2.0)\n self.sqrtpsip = sqrt(self.psipclamp)\n self.psiavg = self.psip - self.qs_edge - self.qdeff_edge -1.0\n self.T0 = self.Smooth(self.psiavg, 1.0, 2.0)\n self.T2 = sqrt(self.T0)\n self.nq_edge = 1.0 + self.gam_edge / (self.sqrtpsip + self.T2)\n self.ids_edge = 2.0 * self.NF * self.nq_edge * self.ueff * self.WEDGE / self.Leff * self.Cox * self.nVt * self.nVt * ((self.qs_edge - self.qdeff_edge) * (1.0 + self.qs_edge + self.qdeff_edge)) * self.Moc\n self.ids = self.ids_edge + self.ids\n return self.ids\n\n","sub_path":"bsimbulk.py","file_name":"bsimbulk.py","file_ext":"py","file_size_in_byte":523531,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"284118628","text":"def my_map(function, iterable):\n\tfor i in iterable:\n\t\tyield function(i)\n\ndef my_enumerate(iterable, start = 0):\n\tfor i in iterable:\n\t\tyield start, i\n\t\tstart += 1\n\ndef my_zip(*iterables):\n\titerlen = list(map(len, iterables))\n\tminlen = min(iterlen)\n\tfor i in range(minlen):\n\t\tyield tuple(j[i] for j in iterables)\n\na = (1, 2, 3)\nb = (4, 5, 6)\nz = my_zip(a, b)\nprint(list(z))\n","sub_path":"w8/3.py","file_name":"3.py","file_ext":"py","file_size_in_byte":372,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"556946209","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue May 8 12:09:13 2018\n\n@author: jbt\n\"\"\"\n\nimport warnings\n \ndef fn(a):\n s=0;\n if a>100:\n warnings.warn('Long Wait...')\n for i in range(a):\n s+=i\n return s\n\n\nwarnings.filterwarnings('error','.*') \nprint(\"Start...\")\nprint(fn(1000))\nprint (\"Ending...\")","sub_path":"w1.py","file_name":"w1.py","file_ext":"py","file_size_in_byte":316,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"602966160","text":"\n\ndef log_pet_views(view):\n log_file1 = open(\"/app/pet_view_log.txt\", \"a+\")\n log_file1.write(assemble_log_entry(view))\n log_file1.close()\n log_file2 = open(\"/home/whiskey/pet_view_log.txt\", \"a+\")\n log_file2.write(assemble_log_entry(view))\n log_file2.close()\n \n \n\ndef assemble_log_entry(view):\n return \"{}:{}\\n\".format(\n view[\"username\"],\n view[\"pet_id\"]\n )\n\ndef parse_pet_log():\n result = {}\n with open(\"/app/pet_view_log.txt\") as log:\n lines = log.readlines()\n for line in lines:\n result[line.split(\":\")[1].rstrip()] = result.get(line.split(\":\")[1].rstrip(), 0) + 1\n return result\n\n\n\n'''\nview = {\n \"username\": hao,\n \"pet_id\": 1\n}\n'''\n","sub_path":"batch/search_indexer/search_indexer/services/logging_service.py","file_name":"logging_service.py","file_ext":"py","file_size_in_byte":711,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"196124264","text":"from __future__ import with_statement\n\nfrom contextlib import contextmanager\nfrom mock import patch\nfrom sqlalchemy import create_engine\nimport sys\n\nfrom proccer import database\n\n__all__ = ['assert_raises', 'assert_eq', 'setup_module', 'setup_hooks']\n\n\n@contextmanager\ndef assert_raises(expected_exception):\n '''Context manager for use in tests, where an exception is expected.\n\n Use like this::\n\n with assert_raises(Exception):\n raise Exception('I should fail')\n\n If an instance of :param:`expected_exception` is not raised this will\n raise AssertionError.'''\n\n try:\n yield\n except expected_exception:\n pass\n else:\n raise AssertionError('%s was not raised'\n % expected_exception.__name__)\n\n\ndef assert_eq(actual, expected):\n 'Assert that two values compare equal.'\n assert actual == expected, '%r not == expected %r' % (actual, expected)\n\n\ndef setup_hooks(module_name):\n '''Setup per-test setup/teardown hooks for all tests in module.\n\n This is equivalent to decorating each test-function in the module with\n ``@with_setup(setup_function, teardown_function)``.'''\n\n module = sys.modules[module_name]\n local_setup = getattr(module, 'setup_function', lambda: None)\n local_teardown = getattr(module, 'teardown_function', lambda: None)\n\n orig_Session = database.Session\n\n def setup_function():\n engine = create_engine('sqlite://')\n database.Base.metadata.create_all(bind=engine)\n module.session = orig_Session(bind=engine)\n database.populate_database(module.session)\n # Replace database.Session with a MockSession while in testing, to\n # prevent session_manager from dropping our in-memory database too\n # soon.\n database.Session = MockSession(module.session)\n\n local_setup()\n\n def teardown_function():\n local_teardown()\n\n orig_Session.remove()\n database.Session = orig_Session\n module.session = None\n\n for name, value in module.__dict__.items():\n if name.startswith('test_') and callable(value):\n value.setup = setup_function\n value.teardown = teardown_function\n\n\ndef setup_module(m):\n setup_hooks(m.__name__)\n\n\nclass MockSession(object):\n 'I mock the SQLAlchemy Session for tests.'\n\n def __init__(self, session):\n self.session = session\n\n def __call__(self):\n return self.session\n\n def object_session(self, object):\n return self.session.object_session(object)\n\n def remove(self):\n # No dropping the in-memory database!\n pass\n","sub_path":"src/proccer/t/testing.py","file_name":"testing.py","file_ext":"py","file_size_in_byte":2621,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"610181610","text":"from Zombie import Zombie\n\nclass ZombieManager:\n\n zombies = []\n round = 0\n ZOMBIE_HEALTH = [150 + i * 100 for i in range(10)]\n spawnpoints = [[-200, -100, 150, 1.0], [-200, 100, 150, 1.0], [200, -100, 150, 1.0], [200, 100, 150, 1.0]]\n ZOMBIES_PER_HORDE = 24\n zombiesToSpawn = 0\n\n def spawn(self, x, y, health, speed):\n self.zombies.append(Zombie(x, y, health, speed))\n\n def tick(self, win, playerX, playerY, playerGun, shotVect):\n for zombie in self.zombies:\n zombie.updatePos(playerX, playerY)\n zombie.checkShot(shotVect, playerGun)\n zombie.draw(win, playerX, playerY)\n if not zombie.checkAlive():\n self.zombies.remove(zombie)\n if not self.zombies:\n self.incRound()\n self.spawnZombiesAtSpawnpoints()\n\n def incRound(self):\n self.round += 1\n self.zombiesToSpawn = self.getZombiesInWave(self.round)\n\n def spawnZombiesAtSpawnpoints(self):\n for spawnpoint in self.spawnpoints:\n if self.zombiesToSpawn > 0 and not self.spawnpointNearbyZombie(spawnpoint):\n self.spawn(spawnpoint[0], spawnpoint[1], ZombieManager.getZombieHealth(self.round), 1.0)\n self.zombiesToSpawn -= 1\n\n def spawnpointNearbyZombie(self, spawnpoint):\n for zombie in self.zombies:\n if abs(zombie.x - spawnpoint[0]) < 50 and abs(zombie.y - spawnpoint[1]) < 50:\n return True\n return False\n\n def getRound(self):\n return self.round\n\n @staticmethod\n def getZombiesInWave(roundNum):\n return roundNum * 0.15 * ZombieManager.ZOMBIES_PER_HORDE\n\n @staticmethod\n def getZombieHealth(roundNum):\n if roundNum < 11:\n return ZombieManager.ZOMBIE_HEALTH[roundNum - 1]\n else:\n return ZombieManager.ZOMBIE_HEALTH[len(ZombieManager.ZOMBIE_HEALTH) - 1] * pow(1.1, roundNum - len(ZombieManager.ZOMBIE_HEALTH))","sub_path":"ZombieManager.py","file_name":"ZombieManager.py","file_ext":"py","file_size_in_byte":1948,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"300676296","text":"import zmq\nfrom random import randint\n\nfrom sharkgrid.tasks.example import example_task as task\n\nLRU_READY = \"\\x01\"\n\ndef worker(context):\n \"\"\" Simple Pirate Worker example in ZMQ The Guide\"\"\"\n worker = context.socket(zmq.REQ)\n identity = \"%04X-%04X\" % (randint(0, 0x10000), randint(0, 0x10000))\n worker.setsockopt(zmq.IDENTITY, identity)\n worker.connect(\"inproc://workers\")\n\n worker.send(LRU_READY)\n\n while True:\n msg = worker.recv_multipart()\n if not msg:\n break\n data = msg[2]\n result = task(data)\n worker.send_multipart(result)\n\ndef broker(context):\n \"\"\" Simple Pirate Queue example in ZMQ The Guide\"\"\"\n frontend = context.socket(zmq.ROUTER)\n backend = context.socket(zmq.ROUTER)\n frontend.bind(\"inproc://client\")\n backend.bind(\"inproc://workers\")\n\n poll_workers = zmq.Poller()\n poll_workers.register(backend, zmq.POLLIN)\n\n poll_both = zmq.Poller()\n poll_both.register(frontend, zmq.POLLIN)\n poll_both.register(backend, zmq.POLLIN)\n\n workers = []\n\n while True:\n if workers:\n socks = dict(poll_both.poll())\n else:\n socks = dict(poll_workers.poll())\n\n if socks.get(backend) == zmq.POLLIN:\n msg = backend.recv_multipart()\n if not msg:\n break\n address = msg[0]\n workers.append(address)\n \n reply = msg[2:]\n\n # Forward message to client if it's not a READY\n if reply[0] != LRU_READY:\n frontend.send_multipart(reply)\n\n if socks.get(frontend) == zmq.POLLIN:\n # Get client request, route to first available worker\n msg = frontend.recv_multipart()\n request = [workers.pop(0), ''] + msg\n backend.send_multipart(request)\n","sub_path":"src/sharkgrid/zmq_zguide/simplepirate.py","file_name":"simplepirate.py","file_ext":"py","file_size_in_byte":1828,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"254483641","text":"\"\"\"\nproblem 121. Best Time to Buy and Sell Stock\nhttps://leetcode.com/problems/best-time-to-buy-and-sell-stock/\n\nsolution:\n\n\"\"\" \nclass Solution(object):\n def maxProfit(self, prices):\n \"\"\"\n :type prices: List[int]\n :rtype: int\n \"\"\"\n pre_min = float('inf')\n maximum = 0\n for price in prices:\n if price < pre_min:\n pre_min = price\n elif price > pre_min:\n if price - pre_min > maximum:\n maximum = price - pre_min\n return maximum","sub_path":"P0121.py","file_name":"P0121.py","file_ext":"py","file_size_in_byte":554,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"473295431","text":"import os\n\nfrom get_ztgz import gen_big_table, gen_get_value, focus_words\nbig_table = gen_big_table()\nget_value = gen_get_value(big_table)\n\nlines = open('data.txt').read().split('\\n')\nlines2 = open('data2.txt').read().split('\\n')\nlines.extend(lines2)\ndatas = list(map(lambda x:x.split('==>'), lines))\nfor data in datas:\n if len(data) != 2:\n print(data, len(data))\n\ntable_file = open(\"table.txt\", \"w\")\nlines = []\nfor key in big_table:\n line = key + \"==>\" + big_table[key] + \"\\n\"\n lines.append(line)\ntable_file.writelines(lines)\n\ntotal = len(datas)\ncount_o = 0\ncount_f = 0\ncount_v = 0\nfor rec,gt in datas:\n # if rec == '' or gt == '':\n # continue\n rec_f = focus_words(rec)\n gt_f = focus_words(gt)\n rec_v = get_value(rec_f)\n gt_v = get_value(gt_f)\n if rec == gt:\n count_o += 1\n if rec_f == gt_f:\n count_f += 1\n if rec_v == gt_v:\n count_v += 1\n else:\n print(rec, '>>', rec_v, \"=\\=\", gt_v)\n pass\nprint('==================================')\nprint(round(count_o / total * 100, 2), '%')\nprint(round(count_f / total * 100, 2), '%')\nprint(round(count_v / total * 100, 2), '%')","sub_path":"calamari-regression/regression_test/get_ztgz/preview.py","file_name":"preview.py","file_ext":"py","file_size_in_byte":1151,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"320015879","text":"# -*- coding: utf-8 -*-\n#!/usr/bin/env python\n\n# Import from the future for Python 2 and 3 compatability!\nfrom __future__ import print_function, absolute_import, unicode_literals\n\nimport re\n\n# local imports\nfrom qtpy import QtGui, QtCore\nfrom tools.mfixproject import KeyWord, Equation\nfrom tools.general import to_text_string\n\n\nclass CommonBase(QtCore.QObject):\n value_updated = QtCore.Signal(object, object, object)\n\n def __init__(self):\n self.key = None\n self.defualtValue = None\n\n def emitUpdatedValue(self):\n self.value_updated.emit(self, {self.key: self.value}, None)\n\n def validator(self):\n return False\n\n def updateValue(self, key, newValue, args=None):\n pass\n\n @property\n def value(self):\n return None\n\n def setdtype(self, dtype=None):\n dtype = to_text_string(dtype).lower().strip()\n if dtype == to_text_string('i'):\n self.dtype = int\n elif dtype == to_text_string('dp'):\n self.dtype = float\n elif dtype == to_text_string('bool'):\n self.dtype = bool\n else:\n self.dtype = str\n\n def setValInfo(self, _max=None, _min=None, req=False):\n self._max = _max\n self._min = _min\n self.required = req\n\n def default(self, val=None):\n if val is not None:\n self.defualtValue = val\n\n if self.defualtValue is not None:\n self.updateValue(self.key, self.defualtValue, args=None)\n\n\nclass LineEdit(QtGui.QLineEdit, CommonBase):\n value_updated = QtCore.Signal(object, object, object)\n\n def __init__(self, parent=None):\n QtGui.QLineEdit.__init__(self, parent)\n CommonBase.__init__(self)\n\n self.timer = QtCore.QTimer()\n self.timer.timeout.connect(self.emitUpdatedValue)\n self.timer.setSingleShot(True)\n\n self.textEdited.connect(self.textEditedEvent)\n\n self.dtype = str\n\n self.regX_expression = re.compile('@\\(([0-9.eEpiPI\\+\\-/*\\(\\))]+)\\)')\n self.regX_mathOp = re.compile('([eEpiPI\\+\\-/*\\^\\(\\)]+)')\n\n @property\n def value(self):\n if len(str(self.text())) == 0:\n return ''\n if self.dtype == str:\n return str(self.text())\n elif self.dtype == float:\n if self.regX_mathOp.findall(str(self.text())):\n return Equation(self.text())\n else:\n return float(str(self.text()))\n elif self.dtype == int:\n return int(float(str(self.text())))\n\n def updateValue(self, key, newValue, args=None):\n\n if newValue:\n if self.regX_expression.findall(str(newValue)):\n self.setText(self.regX_expression.findall(str(newValue))[0])\n else:\n self.setText(str(newValue).replace(\"'\", '').replace('\"', ''))\n else:\n self.setText('')\n\n def textEditedEvent(self, event):\n self.timer.stop()\n self.timer.start(100)\n\n def default(self, val=None):\n if val is not None:\n self.defualtValue = val\n\n if self.defualtValue is not None:\n self.updateValue(self.key, self.defualtValue, args=None)\n else:\n self.clear()\n\n\nclass CheckBox(QtGui.QCheckBox, CommonBase):\n value_updated = QtCore.Signal(object, object, object)\n\n def __init__(self, parent=None):\n QtGui.QCheckBox.__init__(self, parent)\n CommonBase.__init__(self)\n self.released.connect(self.emitUpdatedValue)\n\n @property\n def value(self):\n return bool(self.isChecked())\n\n def updateValue(self, key, newValue, args=None):\n if isinstance(newValue, KeyWord):\n newValue = newValue.value\n\n if newValue and isinstance(newValue, bool):\n self.setChecked(newValue)\n else:\n self.setChecked(False)\n\n\nclass ComboBox(QtGui.QComboBox, CommonBase):\n value_updated = QtCore.Signal(object, object, object)\n\n def __init__(self, parent=None):\n QtGui.QComboBox.__init__(self, parent)\n CommonBase.__init__(self)\n self.activated.connect(self.emitUpdatedValue)\n\n self.dtype = str\n\n @property\n def value(self):\n if self.dtype == int:\n return int(str(self.currentText()).split('-')[0].strip())\n elif self.dtype == bool:\n if str(self.currentText()).lower() == 'true':\n return True\n else:\n return False\n else:\n return str(self.currentText())\n\n def updateValue(self, key, newValue, args=None):\n if isinstance(newValue, KeyWord):\n newValue = newValue.value\n\n self.setCurrentText(newValue)\n\n def setCurrentText(self, newValue):\n for itm in range(self.count()):\n if self.dtype == str and str(newValue).lower() == str(self.itemText(itm)).lower():\n self.setCurrentIndex(itm)\n break\n elif self.dtype == int and int(newValue) == int(str(self.itemText(itm)).split('-')[0].strip()):\n self.setCurrentIndex(itm)\n break\n\n\nclass SpinBox(QtGui.QSpinBox, CommonBase):\n value_updated = QtCore.Signal(object, object, object)\n\n def __init__(self, parent=None):\n QtGui.QDoubleSpinBox.__init__(self, parent)\n CommonBase.__init__(self)\n\n self.valueChanged.connect(self.emitUpdatedValue)\n\n self.dtype = int\n\n def emitUpdatedValue(self):\n self.value_updated.emit(self, {self.key: self.value()}, None)\n\n def updateValue(self, key, newValue, args=None):\n if isinstance(newValue, KeyWord):\n newValue = newValue.value\n\n self.setValue(int(newValue))\n\n def setValInfo(self, _max=None, _min=None, req=False):\n if _max:\n self.setMaximum(int(_max))\n if _min:\n self.setMinimum(int(_min))\n\n\nclass DoubleSpinBox(QtGui.QDoubleSpinBox, CommonBase):\n value_updated = QtCore.Signal(object, object, object)\n\n def __init__(self, parent=None):\n QtGui.QDoubleSpinBox.__init__(self, parent)\n CommonBase.__init__(self)\n\n self.valueChanged.connect(self.emitUpdatedValue)\n\n self.dtype = float\n\n def emitUpdatedValue(self):\n self.value_updated.emit(self, {self.key: self.value()}, None)\n\n def updateValue(self, key, newValue, args=None):\n if isinstance(newValue, KeyWord):\n newValue = newValue.value\n\n self.setValue(float(newValue))\n\n def setValInfo(self, _max=None, _min=None, req=False):\n if _max:\n self.setMaximum(float(_max))\n if _min:\n self.setMinimum(float(_min))\n","sub_path":"gui/widgets/base.py","file_name":"base.py","file_ext":"py","file_size_in_byte":6611,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"315904814","text":"#EID:ta8779\n\nimport socket\nimport sys\nimport os\nimport ipaddress\n\n\n\nhost=''\nserverPort=int(sys.argv[1])\n\nserverSocket=socket.socket(socket.AF_INET,socket.SOCK_STREAM)\n\nroutingTable=[]\nroutingTable.append(\"A 0.0.0.0/0 100\")\n\n\ntry:\n\tserverSocket.bind((host,serverPort))\nexcept socket.error as e:\n\tprint(str(e))\nprint ('The server is runnning in port:' , serverPort)\nserverSocket.listen(1)\n\n\n#loop to accept the connection from any client and keep it open\nwhile 1:\n\tconnection, addr=serverSocket.accept()\n\n\trequest = connection.recv(1024)\n\tclientRequest=request.decode()\n\tprint (clientRequest)\n\tresponse = clientRequest\n\n\t#split the client request by \\r\\n to get individual part\t\n\teachLines = clientRequest.split('\\r\\n')\n\tlines=len(eachLines)\n\n\t#check to see if first line is UPDATE\n\tif (eachLines[0]=='UPDATE'):\n\t\t# print ('ACK')\n\t\tcounter=1\n\t\twhile (counter < (lines-2)):\n\t\t\teachUpdate=eachLines[counter].split(\" \")\n\t\t\trouter=eachUpdate[0] #A\n\t\t\teachIPmask=eachUpdate[1] #111.1.1.1/1\n\t\t\tpathCost=eachUpdate[2] #100\n\t\t\troutingTableLen=len(routingTable)\n\t\t\trCounter=0\n\t\t\t\n\t\t\t# loop to compare given CDIR with existing CIDR in the routing table\n\t\t\twhile(rCounterip2_prefix):\n\t\t\t \t\tif(int(routes[2])<=int(pathCost)):\n\t\t\t \t\t\troutingTable.append(eachLines[counter])\n\t\t\t \t\t\troutingTableLen=len(routingTable)\n\t\t\t \t\telse:\n\t\t\t \t\t\troutingTable[rCounter]=eachLines[counter]\n\t\t\t \telif(ip1_prefix=int(pathCost)):\n\t\t\t \t\t\troutingTable.append(eachLines[counter])\n\t\t\t \t\t\troutingTableLen=len(routingTable)\n\t\t\t \t\telse:\n\t\t\t \t\t\t#loop to remove all existing path that has higher cost and then break based on ip prefix\n\t\t\t \t\t\twhile True:\n\t\t\t \t\t\t\ttry:\n\t\t\t \t\t\t\t\troutingTable.remove(eachLines[counter])\n\t\t\t \t\t\t\texcept ValueError:\n\t\t\t \t\t\t\t\tbreak;\n\t\t\t \t\t\troutingTableLen=len(routingTable)\n\t\t\t \t\t\tbreak;\n\t\t\t \telif(ip1_prefix==ip2_prefix):\n\t\t\t \t\tif(int(routes[2])>int(pathCost)):\n\t\t\t \t\t\troutingTable[rCounter]=eachLines[counter]\n\t\t\t else:\n\t\t\t \troutingTable.append(eachLines[counter])\n\t\t\t \troutingTableLen=len(routingTable)\n\t\t\t \n\t\t\t rCounter+=1\n\n\t\t\troutingTable=list(set(routingTable))\n\t\t\tcounter+=1 \n\n\t\tack='ACK\\r\\n'\n\t\tack+='END\\r\\n'\n\t\t\n\t\tconnection.sendall(ack.encode())\n\t\t\t\n\t\t#print the whole routing table\n\t\t# print (\"Routing table entries:\")\n\t\t# routingTableLen=len(routingTable)\n\t\t# for i in range(0,routingTableLen):\n\t\t# \tprint (routingTable[i])\n\n\t#check to see if first line is QUERY\n\tif (eachLines[0]=='QUERY'):\n\t\tcounter=0\n\t\tindex=0\n\t\trouterTableLength=len(routingTable)\n\t\tminCost=9999999999999\n\t\tlongestPrefix=-1\n\t\tclosestRoutingIPs=[]\n\n\t\t#loop to check the best path based on ip prefix and path cost\n\t\twhile(counterlongestPrefix):\n\t\t\t\t\t\tminCost=cost\n\t\t\t\t\t\tlongestPrefix=ip_prefix\n\t\t\t\t\t\t# print(\"min:******\")\n\t\t\t\t\t\t# print(minCost)\n\t\t\t\t\t\tindex=counter\n\t\t\tcounter+=1\n\n\t\t#best path\n\t\tresultPath=routingTable[index].split(\" \")\n\t\tresult=\"RESULT\\r\\n\"\n\t\tresult+=eachLines[1]+\" \"+resultPath[0]+\" \"+resultPath[2]+'\\r\\n'\n\t\tresult+='END\\r\\n'\n\n\t\tconnection.sendall(result.encode())\n\t\n\t","sub_path":"server-ta8779.py","file_name":"server-ta8779.py","file_ext":"py","file_size_in_byte":3952,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"644318538","text":"import cv2\nimport numpy as np\nfrom matplotlib import pyplot as plt\n\n\n\n# capture frames from a camera\ncap = cv2.VideoCapture(0)\n#cv2.waitKey(500)\n# loop runs if capturing has been initialized\nwhile (1):\n ret, frame = cap.read()\n edges = cv2.Canny(frame,100,200)\n kernel = np.ones((5,5),np.uint8)\n closing = cv2.morphologyEx(edges, cv2.MORPH_CLOSE, kernel)\n\n contours, hierarchy = cv2.findContours(edges, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE);\n img = cv2.drawContours(frame, contours, -1, (0,0,255), 3)\n \n cv2.imshow(\"hellboy\",edges)\n cv2.imshow(\"hello\",closing)\n\n #cv2.imshow(\"hellboy\",img)\n # Wait for Esc key to stop\n k = cv2.waitKey(5) & 0xFF\n if k == 27:\n break\n \n# Close the window\ncap.release()\n# De-allocate any associated memory usage\ncv2.destroyAllWindows()","sub_path":"santosh hero.py","file_name":"santosh hero.py","file_ext":"py","file_size_in_byte":816,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"356829820","text":"#!/usr/bin/python\n\nimport subprocess\nimport globalVars\n\n\ndef stopMusic(sendTelegram):\n command = \"/usr/local/bin/mpc stop -h 127.0.0.1 -p 6601\"\n subprocess.Popen(command, shell=True)\n if (sendTelegram):\n globalVars.toFile(globalVars.sendFile, \"mpc STOP\")\n return True\n\nif __name__ == \"__main__\":\n stopMusic(True)\n","sub_path":"raspiWeb/backoffice/tgScripts/mpcoff.py","file_name":"mpcoff.py","file_ext":"py","file_size_in_byte":335,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"288328736","text":"#-*- coding:utf-8 -*-\nfrom django.shortcuts import render,get_object_or_404\nfrom django.http import HttpResponseRedirect\nfrom django.utils import timezone\nfrom .models import *\nfrom .form import *\nimport time\nfrom django.contrib.auth.models import User\nfrom django.views.decorators.csrf import csrf_exempt\nfrom django.db.models import F\n#import logging\n\n\n# Create your views here.\n#logger = logging.getLogger('loggers')\n\ndef post_list(request):\n return render(request,'blog/post_list.html')\n\ndef base_title(request):\n return render(request,'blog/base_title.html')\n\ndef post_data(request,style_id,page):\n #The following is page_funtion\n page_num = Post.objects.filter(style_id=style_id).count()\n page_num1 = [i for i in range(1,int(page_num/7)+1)]\n page = int(page)\n posts = Post.objects.filter(style_id=style_id).order_by('-id')[(page-1)*7:(page*7)]\n\n\t#The following is comment_leaderboard\n lst_post = Post.objects.filter(title__isnull=False)\n lst_comm_num = []\n lst_article_count = []\n for i in lst_post:\n post_id = i.id\n post_title = i.title\n post_id_1 = Post.objects.get(id=post_id)\n comm_num = post_id_1.comment_set.all().count()\n lst_comm_num.append({'num':comm_num,'title':post_title,'id':post_id})\n\n post_article_count = i.article_count\n lst_article_count.append({'article_count':post_article_count,'title':post_title,'id':post_id})\n\n lst_comm_num = sorted(lst_comm_num,key=lambda x:x['num'],reverse=True)\n lst_article_count = sorted(lst_article_count,key=lambda x:x['article_count'],reverse=True)\n\n dic = {\n 'style_id':style_id,\n 'posts':posts,\n 'page_num':page_num1,\n 'end':page_num1[-1], #the last page\n 'page':page,\n 'lst_comm_num':lst_comm_num[0:5],\n 'lst_article_count':lst_article_count[0:5],\n }\n\t\n return render(request,'blog/post_data.html',dic)\n\ndef post_detail(request,ids):\n #The following is article_count leaderboard\n Post.objects.filter(id=ids).update(article_count=F('article_count')+1)\n\n a = Post.objects.get(id=ids)\n\t\n if request.method == 'POST':\n form = Comment_form(request.POST)\n if form.is_valid():\n cleaned_data = form.cleaned_data\n cleaned_data['post'] = a\n Comment.objects.create(**cleaned_data)\n return HttpResponseRedirect('')\n else:\n form = Comment_form()\t#if data is false,create a space form\n\n dic = {\n 'a':a,\n 'form':form,\n 'ties':a.comment_set.all() #screened artical,find corresponding all comments\n }\n\n return render(request,'blog/post_detail.html',dic)\n\n@csrf_exempt\ndef post_add(request):\n author = User.objects.get(username='admin')\n lst_style_id = set(Post.objects.values_list('style_id'))\n lst_style_id_1 = map(lambda x:x[0],lst_style_id)\n\n if request.method == 'POST':\n add_form = Add(request.POST)\n if add_form.is_valid():\n title = add_form.cleaned_data['title']\n text = add_form.cleaned_data['text']\n style_id = add_form.cleaned_data['style_id']\n Post.objects.create(author=author,title=title,describe=text[0:50],\n text=text,published_date=timezone.now(),style_id=style_id)\n\n return HttpResponseRedirect('/post_add/')\n else:\n add_form = Add()\n\n dic = {\n 'lst_style_id_1':lst_style_id_1,\n }\n return render(request,'blog/post_add.html',dic)\n","sub_path":"blog/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3469,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"470447943","text":"import os\nimport pathlib\nfrom shutil import copyfile\nimport yaml\nfrom pkg_resources import get_distribution, DistributionNotFound\n\nclass DotDict(dict):\n \"\"\"dot.notation access to dictionary attributes\"\"\"\"\"\n __getattr__ = dict.get\n __setattr__ = dict.__setitem__\n __delattr__ = dict.__delitem__\n\n def __str__(self):\n return yaml.dump(dict(self))\n\nhome_path = os.path.expanduser('~')\nconfig_dir = pathlib.Path(os.path.join(home_path, '.ale'))\nconfig_file_path = pathlib.Path(os.path.join(home_path, '.ale', 'config.yml'))\n\nconfig_dir.mkdir(parents=True, exist_ok=True)\n\nif not config_file_path.is_file():\n copyfile(os.path.join(os.path.dirname(__file__), 'config.yml'), config_file_path)\n\nconfig = DotDict(yaml.load(open(config_file_path), Loader=yaml.FullLoader))\n\ntry:\n _dist = get_distribution('ale')\n # Normalize case for Windows systems\n dist_loc = os.path.normcase(_dist.location)\n here = os.path.normcase(__file__)\n if not here.startswith(os.path.join(dist_loc, 'ale')):\n # not installed, but there is another version that *is*\n raise DistributionNotFound\nexcept DistributionNotFound:\n __version__ = 'Please install this project with setup.py'\nelse:\n __version__ = _dist.version\n\n# bring ale stuff into main ale module\nfrom . import drivers\nfrom . import formatters\nfrom . drivers import load, loads\n","sub_path":"ale/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":1363,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"165934064","text":"import WRCCUtils, WRCCData, DJANGOUtils, AcisWS, WRCCClasses\nimport my_acis_settings as settings\n\nimport unittest\nimport os, sys\nimport copy\nimport json\n#Testing feedback form\nfrom django.core.mail import send_mail\n\nimport logging\n\n###########\n#STATICS\n###########\nlog_dir = '/tmp/'\nlog_file = 'UnitTestSCENIC.log'\n\n\n###########\n#ClASSES\n###########\nclass LoggerWriter:\n '''\n Writes stderr and stdout to log file\n '''\n def __init__(self, level):\n # self.level is really like using log.debug(message)\n # at least in my case\n self.level = level\n\n def write(self, message):\n # if statement reduces the amount of newlines that are\n # printed to the logger\n if message != '\\n':\n self.level(message)\n\n def flush(self):\n # create a flush method so things can be flushed when\n # the system wants to. Not sure if simply 'printing'\n # sys.stderr is the correct way to do it, but it seemed\n # to work properly for me.\n self.level(sys.stderr)\n\nclass TestIDNameFind(unittest.TestCase):\n def setUp(self):\n self.test_areas = copy.deepcopy(WRCCData.TEST_AREAS)\n\n def test_find_id_and_name(self):\n for area_type, area_val in self.test_areas.iteritems():\n if area_type in ['station_id','basin','county','county_warning_area','climate_division']:\n json_file_path = '/www/apps/csc/dj-projects/my_acis/media/json/US_' + area_type + '.json'\n ID, name = WRCCUtils.find_id_and_name(area_val, json_file_path)\n try:\n self.assertNotEqual('ID','')\n except AssertionError as err:\n logger.error('AssertionError' + str(err))\n def test_find_ids_and_names(self):\n area_type = 'station_ids'\n area_val = self.test_areas[area_type]\n json_file_path = '/www/apps/csc/dj-projects/my_acis/media/json/US_station_id.json'\n IDs, names = WRCCUtils.find_ids_and_names(area_val, json_file_path)\n try:\n self.assertIsInstance(IDs, str)\n except AssertionError as err:\n logger.error('AssertionError' + str(err))\n try:\n self.assertNotEqual(IDs.split(','),[])\n except AssertionError as err:\n logger.error('AssertionError' + str(err))\n\nclass TestGetElAndBaseTemp(unittest.TestCase):\n def setUp(self):\n self.variables = WRCCData.ACIS_ELEMENTS_DICT.keys()\n self.variables+=['gdd67','hdd34','cdd65']\n self.units = ['english','metric']\n\n def test_get_el_and_base_temp(self):\n for unit in self.units:\n for el in self.variables:\n el, base_temp = WRCCUtils.get_el_and_base_temp(el,units=unit)\n self.assertIsInstance(el, basestring)\n self.assertIn(el,WRCCData.ACIS_ELEMENTS_DICT.keys())\n try:\n int(base_temp)\n except:\n self.assertEqual(base_temp,None)\n\nclass TestElementsToTableHeaders(unittest.TestCase):\n def setUp(self):\n self.variables = WRCCData.ACIS_ELEMENTS_DICT.keys()\n self.units = ['english','metric']\n\n def test_variables_to_headers(self):\n for unit in self.units:\n el_list_header = WRCCUtils.variables_to_table_headers(self.variables,unit)\n self.assertIsInstance(el_list_header, list)\n self.assertNotEqual(el_list_header,[])\n\nclass TestFormToDisplay(unittest.TestCase):\n def setUp(self):\n self.test_params = copy.deepcopy(WRCCData.SCENIC_DATA_PARAMS)\n\n def test_defaults(self):\n #Test most general case:\n #convert all form aprameters to display\n key_order_list = None\n for app_name, params in self.test_params.iteritems():\n display_params = WRCCUtils.form_to_display_list(key_order_list, params)\n try:\n self.assertIsInstance(display_params, list)\n except AssertionError as err:\n logger.error('AssertionError' + str(err))\n try:\n self.assertNotEqual(display_params,[])\n except AssertionError as err:\n logger.error('AssertionError' + str(err))\n logger.info(display_params)\n for dp in display_params:\n try:\n self.assertEqual(len(dp),2)\n except AssertionError as err:\n logger.error('AssertionError' + str(err))\n\nclass TestFindArea(unittest.TestCase):\n\n def setUp(self):\n self.area_dict = WRCCData.TEST_AREAS\n\n def test_find_area(self):\n msg = 'Testing Area finder for Multi Lister'\n logger.info(msg)\n for area_type, area in self.area_dict.iteritems():\n if area_type in ['station_id','station_ids','shape','location','state']:\n continue\n msg = 'Area: ' + area_type\n logger.info(msg)\n station_json = '/www/apps/csc/dj-projects/my_acis/media/json/US_'+area_type+'.json'\n ID, name = WRCCUtils.find_id_and_name(area,station_json)\n try:\n self.assertIsInstance(name, str)\n except AssertionError as err:\n logger.error('AssertionError' + str(err))\n try:\n self.assertIsInstance(ID, str)\n except AssertionError as err:\n logger.error('AssertionError' + str(err))\n try:\n self.assertNotEqual(ID,'')\n except AssertionError as err:\n logger.error('AssertionError' + str(err))\n\n\n'''\nclass TestFeedback(unittest.TestCase):\n def setUp(self):\n self.subject = 'TestFeedback'\n self.message = 'SUCCESS'\n self.from_email = 'scenic@dri.edu'\n self.to_email = 'scenic@dri.edu'\n def test_mailing(self):\n try:\n send_mail(\n self.subject,\n self.message,\n self.from_email,\n [self.to_email],\n )\n except:\n raise AssertionError\n'''\n############\n# RUN TESTS\n###########\nif __name__ == '__main__':\n log_file_path = log_dir + log_file\n if os.path.isfile(log_file_path):\n os.remove(log_file_path)\n Logger = WRCCClasses.Logger(log_dir,log_file,log_file.split('.')[0])\n logger = Logger.start_logger()\n sys.stdout = LoggerWriter(logger.info)\n sys.stderr = LoggerWriter(logger.error)\n unittest.main()\n","sub_path":"UnitTestSCENIC.py","file_name":"UnitTestSCENIC.py","file_ext":"py","file_size_in_byte":6435,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"483997719","text":"from flask import Flask\r\nfrom flask import render_template\r\nfrom flask import request, send_from_directory, redirect, jsonify\r\nimport requests\r\nimport jwt\r\nimport datetime\r\nimport json\r\n\r\nimport time\r\nimport threading\r\nimport math\r\nimport random\r\n\r\nfrom connections import DBConnection, RabbitConnection\r\nfrom admin import Admin\r\nfrom users import Users\r\nfrom bots import Bots\r\n\r\ndb = DBConnection.db\r\nconnection = RabbitConnection.rabbit\r\n\r\n\r\ndef keep_alive():\r\n while True:\r\n time.sleep(45)\r\n with RabbitConnection.p_lock:\r\n connection.sleep(0.01)\r\n\r\n\r\ndef initialize():\r\n channel = connection.channel()\r\n buildings = db.buildings.find({})\r\n for b in buildings:\r\n channel.exchange_declare(exchange= b['id'], exchange_type='fanout')\r\n channel.close()\r\n\r\n t = threading.Thread(target=keep_alive)\r\n t.daemon = True # thread dies when main thread (only non-daemon thread) exits.\r\n t.start()\r\n\r\n\r\ndef get_payload(request):\r\n token = request.headers['Authorization']\r\n try:\r\n payload = jwt.decode(token, 'SECRET', algorithms=['HS256'])\r\n except:\r\n return None\r\n return payload\r\n\r\n\r\napp = Flask(__name__)\r\n\r\n\r\n###Website###\r\n\r\n@app.route('/')\r\ndef root():\r\n return app.send_static_file('app/index.html')\r\n\r\n\r\n@app.route('/')\r\ndef static_proxy(path):\r\n return app.send_static_file('app/'+path)\r\n\r\n\r\n@app.route('/api/getBuildings')\r\ndef get_Buildings():\r\n db_buildings = db.buildings.find({})\r\n\r\n buildings = []\r\n\r\n for building in db_buildings:\r\n buildings.append({'id':building['id'], 'name':building['name']})\r\n\r\n res = {'buildings':buildings, 'error':0}\r\n return jsonify(res)\r\n\r\n\r\n###Admin###\r\n\r\n@app.route('/api/admin/login', methods=['POST'])\r\ndef login_admin():\r\n data = json.loads(request.data)\r\n user = data['user']\r\n pw = data['pw']\r\n if user == 'admin' and pw == '123':\r\n token = jwt.encode({'user':user, 'exp':datetime.datetime.utcnow() + datetime.timedelta(seconds = 3600)}, 'SECRET', algorithm = 'HS256')\r\n res = {'token':token, 'error':0}\r\n return jsonify(res)\r\n else:\r\n res = {'token': '', 'error':1}\r\n return jsonify(res)\r\n\r\n\r\n@app.route('/api/admin/updateBuildings', methods=['POST'])\r\ndef update_buildings():\r\n data = json.loads(request.data)\r\n buildings = data['buildings']\r\n\r\n payload = get_payload(request)\r\n if payload == None:\r\n res = {'error':1, 'data':'Invalid token!'}\r\n return jsonify(res)\r\n\r\n Admin.update_buildings(buildings)\r\n res = {'error': 0}\r\n return jsonify(res)\r\n\r\n\r\n@app.route('/api/admin/getAllUsers')\r\ndef get_all_users():\r\n payload = get_payload(request)\r\n if payload == None:\r\n res = {'error':1, 'data':'Invalid token!'}\r\n return jsonify(res)\r\n\r\n all_users = Admin.get_all_users()\r\n res = {'all_users':all_users, 'error':0}\r\n return jsonify(res)\r\n\r\n\r\n@app.route('/api/admin/getUsers/')\r\ndef get_users(building):\r\n payload = get_payload(request)\r\n if payload == None:\r\n res = {'error':1, 'data':'Invalid token!'}\r\n return jsonify(res)\r\n\r\n all_users = Admin.get_users(building)\r\n res = {'all_users': all_users, 'error':0}\r\n return jsonify(res)\r\n\r\n\r\n@app.route('/api/admin/getLogs/userMessages///')\r\ndef logs_user_messages(istid, mode, days):\r\n payload = get_payload(request)\r\n if payload == None:\r\n res = {'error':1, 'data':'Invalid token!'}\r\n return jsonify(res)\r\n\r\n msgs = Admin.logs_user_messages(istid, mode, days)\r\n res = {'msgs': msgs, 'error': 0}\r\n return jsonify(res)\r\n\r\n\r\n@app.route('/api/admin/getLogs/userLocations//')\r\ndef logs_user_locations(istid, days):\r\n payload = get_payload(request)\r\n if payload == None:\r\n res = {'error':1, 'data':'Invalid token!'}\r\n return jsonify(res)\r\n\r\n locations = Admin.logs_user_locations(istid, days)\r\n res = {'locations': locations, 'error': 0}\r\n return jsonify(res)\r\n\r\n\r\n@app.route('/api/admin/getLogs/building//')\r\ndef logs_buildings(b_id, days):\r\n payload = get_payload(request)\r\n if payload == None:\r\n res = {'error':1, 'data':'Invalid token!'}\r\n return jsonify(res)\r\n\r\n msgs = Admin.logs_buildings(b_id, days)\r\n res = {'msgs': msgs, 'error': 0}\r\n return jsonify(res)\r\n\r\n\r\n###Users###\r\n\r\n@app.route('/api/users/login')\r\ndef users_login():\r\n #receive code\r\n code = request.args.get('code')\r\n if code != None:\r\n if code != 't1' and code != 't2': ## PARA TESTES\r\n #Fenix app configs\r\n client_id = \"sec\"\r\n client_secret = \"sec\"\r\n redirect_uri = \"http://localhost:5000\"\r\n grant_type = \"authorization_code\"\r\n data = {'client_id':client_id, 'client_secret':client_secret, 'redirect_uri':redirect_uri, 'code':code, 'grant_type':grant_type}\r\n #send code and receive access_token\r\n r = requests.post('https://fenix.tecnico.ulisboa.pt/oauth/access_token', data = data)\r\n access_token = r.json()['access_token']\r\n #get istid\r\n r = requests.get('https://fenix.tecnico.ulisboa.pt/api/fenix/v1/person', params = {'access_token':access_token})\r\n istid = r.json()['username']\r\n else: ## PARA TESTES\r\n if code == 't1':\r\n istid = \"ist_test1\"\r\n elif code == 't2':\r\n istid = \"ist_test2\"\r\n #generate jwt token\r\n token = jwt.encode({'istid':istid, 'exp':datetime.datetime.utcnow() + datetime.timedelta(seconds = 3600)}, 'SECRET', algorithm = 'HS256')\r\n distance = Users.users_login(istid)\r\n\r\n #send jwt token\r\n res = {'token':token, 'distance':distance, 'error':0}\r\n return jsonify(res)\r\n\r\n\r\n@app.route('/api/users/sendLocation', methods=['POST'])\r\ndef send_location():\r\n payload = get_payload(request)\r\n if payload == None:\r\n res = {'error':1, 'data':'Invalid token!'}\r\n return jsonify(res)\r\n\r\n data = json.loads(request.data)\r\n latitude = data['latitude']\r\n longitude = data['longitude']\r\n\r\n istid = payload['istid']\r\n\r\n building = Users.send_location(istid, latitude, longitude)\r\n res = {'data':'OK', 'building':building, 'error':0}\r\n return jsonify(res)\r\n\r\n\r\n@app.route('/api/users/sendMessage', methods=['POST'])\r\ndef send_message():\r\n payload = get_payload(request)\r\n if payload == None:\r\n res = {'error':1, 'data':'Invalid token!'}\r\n return jsonify(res)\r\n\r\n istid = payload['istid']\r\n\r\n data = json.loads(request.data)\r\n\r\n Users.send_message(istid, data)\r\n res = {'data':'OK', 'error':0}\r\n return jsonify(res)\r\n\r\n\r\n@app.route('/api/users/getMessages')\r\ndef get_messages():\r\n payload = get_payload(request)\r\n if payload == None:\r\n res = {'error':1, 'data':'Invalid token!'}\r\n return jsonify(res)\r\n istid = payload['istid']\r\n\r\n messages = Users.get_messages(istid)\r\n res = {'messages':messages, 'error':0}\r\n return jsonify(res)\r\n\r\n\r\n@app.route('/api/users/setDistance', methods=['POST'])\r\ndef set_distance():\r\n payload = get_payload(request)\r\n if payload == None:\r\n res = {'error':1, 'data':'Invalid token!'}\r\n return jsonify(res)\r\n\r\n data = json.loads(request.data)\r\n distance = data['distance']\r\n\r\n istid = payload['istid']\r\n\r\n Users.set_distance(istid, distance)\r\n res = {'data':'OK', 'error':0}\r\n return jsonify(res)\r\n\r\n\r\n@app.route('/api/users/getNearbyUsers')\r\ndef get_nearby_users():\r\n payload = get_payload(request)\r\n if payload == None:\r\n res = {'error':1, 'data':'Invalid token!'}\r\n return jsonify(res)\r\n\r\n istid = payload['istid']\r\n\r\n location, building = Users.get_nearby_users(istid)\r\n res = {'users':{'location':location, 'building':building}, 'error':0}\r\n return jsonify(res)\r\n\r\n\r\n### BOTS\r\n\r\n@app.route('/api/bots/login', methods=['POST'])\r\ndef bots_login():\r\n data = json.loads(request.data)\r\n building = data['building']\r\n bot_id = random.randrange(100000, 999999, 1) # 6 number id\r\n bot_id = \"bot\" + str(bot_id)\r\n token = jwt.encode({'bot_id':bot_id, 'building': building}, 'SECRET', algorithm = 'HS256')\r\n res = {'bot_id': bot_id, 'token':token, 'error':0}\r\n return jsonify(res)\r\n\r\n\r\n@app.route('/api/bots/message', methods=['POST'])\r\ndef bots_msg():\r\n payload = get_payload(request)\r\n if payload == None:\r\n res = {'error':1, 'data':'Invalid token!'}\r\n return jsonify(res)\r\n\r\n data = json.loads(request.data)\r\n building = payload['building']\r\n bot_id = payload['bot_id']\r\n\r\n Bots.bots_msg(data, bot_id, building)\r\n res = {'error':0}\r\n return jsonify(res)\r\n\r\n\r\ndef main():\r\n initialize()\r\n app.run()\r\n\r\n\r\nif __name__ == '__main__':\r\n main()\r\n","sub_path":"server/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":8811,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"263233172","text":"def bala(s1,s2):\n s = set(s2)\n for l in range(len(s2), len(s1) + 1):\n for i in range(len(s1) - l + 1):\n if set(s1[i:i + l]) & s == s:\n return s1[i:i+l]\n else:\n return -1\n\nt = int(input())\nfor j in range(t):\n k = int(input())\n s1=input()\n s2=input()\n print(bala(s1,s2))","sub_path":"Code/CodeRecords/2210/61132/298324.py","file_name":"298324.py","file_ext":"py","file_size_in_byte":329,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"43507467","text":"from __future__ import unicode_literals\n\nfrom django.contrib import admin\nfrom django.core.urlresolvers import reverse\nfrom myhpom.tasks import CloudFactoryAbortDocumentRun, CloudFactoryUpdateDocumentRun\nfrom django.utils.safestring import mark_safe\n\nfrom myhpom.models import (\n AdvanceDirective, CloudFactoryDocumentRun, DocumentUrl, State, StateRequirement,\n StateRequirementLink)\n\n\nclass StateRequirementLinkAdmin(admin.TabularInline):\n model = StateRequirementLink\n\n\nclass StateRequirementAdmin(admin.ModelAdmin):\n model = StateRequirement\n inlines = [StateRequirementLinkAdmin]\n\n\nclass StateRequirementInlineAdmin(admin.TabularInline):\n model = StateRequirement\n fields = ('text', 'admin_link')\n readonly_fields = ('admin_link',)\n\n\nclass StateAdmin(admin.ModelAdmin):\n model = State\n inlines = [StateRequirementInlineAdmin]\n\n\nclass DocumentUrlInlineAdmin(admin.StackedInline):\n model = DocumentUrl\n fields = ('url_as_link', 'expiration', 'cloud_factory_runs')\n readonly_fields = ('url_as_link', 'cloud_factory_runs')\n extra = 0\n\n def url_as_link(self, obj):\n return mark_safe(\n '%s' % (obj.url, obj.url)\n )\n\n def cloud_factory_runs(self, obj):\n return mark_safe(\n '

      '\n + ''.join(\n # Is there a better way to get a URL in the mmh-admin? I don't find a resolver.\n '
    • %s
    • '\n % (reverse(\"admin:myhpom_cloudfactorydocumentrun_change\", args=[cf_run.id]), cf_run)\n for cf_run in obj.cloudfactorydocumentrun_set.all()\n )\n + '
    '\n )\n\n\nclass AdvanceDirectiveAdmin(admin.ModelAdmin):\n model = AdvanceDirective\n inlines = [DocumentUrlInlineAdmin]\n\n\nclass CloudFactoryDocumentRunAdmin(admin.ModelAdmin):\n model = CloudFactoryDocumentRun\n fields = (\n ('status', 'run_id'),\n ('document_url', 'document_host', 'advance_directive'),\n ('inserted_at', 'updated_at'),\n ('created_at', 'processed_at'),\n 'post_data',\n 'response_content',\n )\n readonly_fields = [\n 'document_url',\n 'inserted_at',\n 'updated_at',\n 'document_host',\n 'advance_directive',\n 'run_id',\n 'created_at',\n 'processed_at',\n 'post_data',\n ]\n list_display = [\n 'document_url',\n 'document_host',\n 'run_id',\n 'status',\n 'latest_timestamp',\n 'advance_directive',\n ]\n actions = ['abort_runs', 'update_runs']\n\n def latest_timestamp(self, obj):\n return obj.processed_at or obj.created_at or obj.updated_at\n\n def advance_directive(self, obj):\n if obj.document_url and obj.document_url.advancedirective:\n return mark_safe(\n '%s'\n % (\n reverse(\n \"admin:myhpom_advancedirective_change\",\n args=[obj.document_url.advancedirective.id],\n ),\n obj.document_url.advancedirective,\n )\n )\n\n def delete_selected(self, request, queryset):\n self.abort_runs(request, queryset)\n super(CloudFactoryDocumentRunAdmin, self).delete_selected(request, queryset)\n\n def abort_runs(self, request, queryset):\n for cf_run in queryset:\n CloudFactoryAbortDocumentRun(cf_run.id)\n\n abort_runs.short_description = \"Abort the selected document runs at CloudFactory.\"\n\n def update_runs(self, request, queryset):\n for cf_run in queryset:\n CloudFactoryUpdateDocumentRun(cf_run.id)\n\n update_runs.short_description = \"Update the selected document runs by querying CloudFactory.\"\n\n\nadmin.site.register(State, StateAdmin)\nadmin.site.register(StateRequirement, StateRequirementAdmin)\nadmin.site.register(AdvanceDirective, AdvanceDirectiveAdmin)\nadmin.site.register(CloudFactoryDocumentRun, CloudFactoryDocumentRunAdmin)\n","sub_path":"myhpom/admin.py","file_name":"admin.py","file_ext":"py","file_size_in_byte":4049,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"171644515","text":"nucleotides = ['A', 'C', 'G', 'T']\n\ndef hammingDistance(s1, s2):\n dist = 0\n for i in range(len(s1)):\n if s1[i] != s2[i]:\n dist += 1\n return dist\n\ndef numToSymbol(num):\n if num == 0:\n return 'A'\n elif num == 1:\n return 'C'\n elif num == 2:\n return 'G'\n elif num == 3:\n return 'T'\n\n\ndef symbolToNum(sym):\n if sym == 'A':\n return 0\n elif sym == 'C':\n return 1\n elif sym == 'G':\n return 2\n elif sym == 'T':\n return 3\n\n\ndef patternToNum(pattern):\n if len(pattern) == 0:\n return 0\n if len(pattern) == 1:\n return symbolToNum(pattern)\n\n return 4 * patternToNum(pattern[:-1]) + symbolToNum(pattern[-1])\n\n\ndef numToPattern(i, k):\n if k == 1:\n return numToSymbol(i)\n prefixInd = i // 4\n rem = i % 4\n sym = numToSymbol(rem)\n prefix = numToPattern(prefixInd, k - 1)\n\n return prefix + sym\n\n\ndef neighbors(pattern, d):\n if d == 0:\n return [pattern]\n if len(pattern) == 1:\n return nucleotides\n neighborhood = []\n suffixNeighbors = neighbors(pattern[1:], d)\n for neighbor in suffixNeighbors:\n if hammingDistance(neighbor, pattern[1:]) < d:\n for nucleotide in nucleotides:\n neighborhood.append(nucleotide + neighbor)\n else:\n neighborhood.append(pattern[0] + neighbor)\n return neighborhood\n\n\n\ndef frequentWordsWithMismatches(text, k, d):\n freqArr = [0] * (4 ** k)\n maxCount = 0\n freqPatterns = []\n for i in range(len(text) - k):\n currText = text[i: i + k]\n neighborhood = neighbors(currText, d)\n\n\n for neighbor in neighborhood:\n index = patternToNum(neighbor)\n freqArr[index] += 1\n if freqArr[index] > maxCount:\n maxCount = freqArr[index]\n\n for i, elem in enumerate(freqArr):\n if elem == maxCount:\n pattern = numToPattern(i, k)\n freqPatterns.append(pattern)\n\n return freqPatterns\n\nif __name__ == '__main__':\n with open('/Users/KedarRudrawar/Desktop/Winter Quarter 2019/BENG 181/HW/test.txt', 'r+') as f:\n text = f.readline().rstrip()\n values = f.readline().rstrip().split(' ')\n k = int(values[0])\n d = int(values[1])\n freqPatterns = frequentWordsWithMismatches(text, k, d)\n print(' '.join(freqPatterns))","sub_path":"FrequentWordsWithMismatches.py","file_name":"FrequentWordsWithMismatches.py","file_ext":"py","file_size_in_byte":2382,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"447468301","text":"from random import randint\n\n# P1 input based off of the given text file... append number of marbles taken to temporary list used to access each game sequence\ndef P1_turn(marbles, sub_value, temp_sequence):\n\tif marbles <= int(sub_value):\n\t\tsub_value = marbles\n\t\tmarbles -= marbles\n\telse:\n\t\tmarbles = marbles - int(sub_value)\n\ttemp_sequence.append(sub_value)\n\treturn marbles\n\n# P2 input based off of random integer... append number of marbles taken to a temporary list used to access each game sequence\ndef P2_turn(marbles, temp_sequence):\t\n\tif marbles <= 3:\n\t\tmarbles_taken = 1\n\telse:\n\t\tmarbles_taken = randint(1,3)\n\tmarbles -= marbles_taken\n\ttemp_sequence.append(marbles_taken)\n\treturn marbles\n\t\n# read in input from text file and get into a list of list format\ndef read_file():\n\twith open(\"seventeen_input.txt\") as f_in:\n\t\tf_in_list = []\n\t\tf_in = f_in.read().split(\"\\n\")\n\t\t[f_in_list.append(line.split(\",\")) for line in f_in]\n\t\treturn f_in_list\n\ndef play_game():\n\tf_in_list = read_file()\n\n\t# create empty variables for use in future\n\tfinal_dict = {}\n\twinner = []\n\tP1_win = 0\n\tP2_win = 0\n\n\t# loop through top list in order to access inner lists\n\tfor index, value in enumerate(f_in_list):\n\n\t\t# reset marbles to 17 and temp_sequence to empty list\n\t\tmarbles = 17\n\t\ttemp_sequence = []\n\n\t\t# loop through inner list in order to pull out values within each list\n\t\tfor sub_index, sub_value in enumerate(value):\n\n\t\t\t# Call for Player 1 input-- if marbles = 0, then break and account for winner and number of wins\n\t\t\tmarbles = P1_turn(marbles,sub_value, temp_sequence)\n\t\t\tif marbles == 0:\n\t\t\t\twinner.append(\"P2\")\n\t\t\t\tP2_win += 1\n\t\t\t\tbreak\n\t\t\t# Call for Player 2 input-- if marbles = 0, then break and account for winner and number of wins\n\t\t\tmarbles = P2_turn(marbles, temp_sequence)\n\t\t\tif marbles == 0:\n\t\t\t\twinner.append(\"P1\")\n\t\t\t\tP1_win += 1\n\t\t\t\tbreak\n\n\t\t# after loop through inner list has finished, add the game sequence to final_dict at the appropriate key\n\t\tfinal_dict[index] = temp_sequence\n\n\t# once both for loops have finished, return a tuple-- 1) P1 win count 2) P2 win count 3) list of each game winner 4) dictionary of each game sequence\n\treturn P1_win, P2_win, winner, final_dict\n\n\n#############################################################################\n##################### call functions below through main(): ###################\n##############################################################################\ndef main():\n\t# access tuple (of four items) returned by play_game to use to write final outcome\n\tfactors = play_game()\n\tP1_win = factors[0]\n\tP2_win = factors[1]\n\twinner = factors[2]\n\tfinal_dict = factors[3]\n\n\twith open(\"seventeen_output.txt\", \"w\") as f_out:\n\t\t# write each game sequence using for loop, then write the total number of times P1 and P2 won\n\t\tfor key, value in final_dict.items():\n\t\t\tf_out.write((\"Game #\" + str(key+1) + \". Play Sequence: \" + (\"-\".join(str(s) for s in value)) + \". \" + winner[key] + \" wins.\\n\"))\n\t\tf_out.write(\"\\nPlayer 1 won \" + str(P1_win) + \" times; Player 2 won \" + str(P2_win) + \" times.\")\n\nif __name__ == '__main__':\n main()\n","sub_path":"seventeen2.py","file_name":"seventeen2.py","file_ext":"py","file_size_in_byte":3086,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"478669377","text":"__author__ = 'Cohen'\t\t\n# 函数:程序中可以重复使用的程序段\t\t\n# 用关键字def来定义,identifier(参数)\t\t\n\t\t\n# 没有参数和返回的函数\t\t\n\t\t\n\t\t\ndef say_hi():\t\t\n print(\"hi!\")\t\t\nsay_hi()\t\t\n\t\t# 有参数无返回值\t\t\n\t\t\n\t\t\ndef print_sum_two(a, b):\t\t\n c = a+b\t\t\n print(c)\t\t\nprint_sum_two(3, 5)\t\t\n\t\t\n\t\t\ndef hello_some(str):\t\t\n print(\"Hello \"+str+\"!\")\t\t\nhello_some(\"China\")\t\t\nhello_some(\"python\")\t\t\n\t\t\n# 有参数有返回值\t\t\n\t\t\n# times = 1设定默认参数,Happy Birthday重复一次\t\t\ndef repeat_str(str, times = 1):\t\t\n repeated_strs = str * times\t\t\n return repeated_strs\t\t\n# repeat_str后面times没有赋值则使用默认参数\t\t\nrepeated_strings = repeat_str(\"Happy Birthday! \",)\t\t\nprint(repeated_strings)\t\t\n\t\t\n# 全局变量和局部变量\t\t\nx = 60\t\t\n\t\t\ndef foo(x):\t\t\n print(\"x is \"+str(x))\t\t\n x = 3\t\t\n print(\"change local x to \" + str(x))\t\t\nfoo(x)\t\t\nprint('x is still',str(x))\t\t\n\t\n\t\t\n\t\t\nx = 50\t\t\ndef foo1():\t\t\n global x\t\t\n print(\"x is \" + str(x))\t\t\n x = 3\t\t\n print(\"change local x to \" + str(x))\t\t\nfoo1()\t\t\nprint('value of x is ',str(x))","sub_path":"practice/Function.py","file_name":"Function.py","file_ext":"py","file_size_in_byte":1114,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"553071458","text":"def _intensity_grids_for_frame(frame_and_events, delta=4):\n frame = frame_and_events[0]\n puff_events = frame_and_events[1]\n puff_intensities = []\n side = 2*delta + 1\n for f_num, xloc, yloc, idx in tqdm(np.array(puff_events)):\n if (f_num < 0) | (f_num >= np.shape(f)[0]):\n block = np.zeros((9,9))\n else:\n y_len, x_len = np.shape(frame)\n xloc = int(xloc)\n yloc = int(yloc)\n\n # literal edge case detection\n y_start = (yloc - delta) if (yloc - delta) >= 0 else 0\n y_end = (yloc + delta + 1) if (yloc + delta) <= y_len else (y_len + 1)\n x_start = (xloc - delta) if (xloc - delta) >= 0 else 0\n x_end = (xloc + delta + 1) if (xloc + delta) <= x_len else (x_len + 1)\n block = frame[y_start:y_end, x_start:x_end]\n\n if x_start == 0:\n block = np.pad(block, ((0,0), ((delta-xloc)+1,0)), mode=\"reflect\")\n elif x_end == (x_len + 1):\n block = np.pad(block, ((0,0), (0,delta-(x_len-xloc)+1)), mode=\"reflect\")\n\n if y_start == 0:\n block = np.pad(block, (((delta-yloc)+1,0), (0,0)), mode=\"reflect\")\n elif y_end == (y_len + 1):\n block = np.pad(block, ((0,delta-(y_len-yloc)+1), (0,0)), mode=\"reflect\")\n\n for r,c in product(range(side), repeat=2):\n puff_intensities.append([f_num, c - delta, r - delta, idx, block[r,c]])\n\n puff_intensities = pd.DataFrame(puff_intensities, columns=['frame', 'x', 'y', 'particle', 'intensity'])\n return puff_intensities\n\ndef intensity_grid(f, puff_events, delta=4):\n frames = np.unique(puff_events['frame'])\n frame_generator = (n for n in frames)\n frame_events_generator = (puff_events[puff_events['frame'] == n]\n for n in frames)\n n_cores = multiprocessing.cpu_count()\n f_with_options = partial(_intensity_grids_for_frame,\n delta=delta)\n with multiprocessing.Pool(3) as pool:\n grids_out = pool.map(f_with_options,\n zip(frame_generator, frame_events_generator),\n chunksize=100)\n\n puff_intensities = pd.concat(grids_out, ignore_index=True)\n return puff_intensities\n","sub_path":"misc/parallel_intensity_grid.py","file_name":"parallel_intensity_grid.py","file_ext":"py","file_size_in_byte":2286,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"459774291","text":"# %%\nfrom logging import getLogger, Formatter, INFO, StreamHandler, Logger, DEBUG\nfrom os import environ\n\nclass LoggerConfig:\n \"\"\"\n Configure and return logger object.\n \"\"\"\n\n @classmethod\n def logger(cls, cls_name) -> Logger:\n \"\"\"\n :param cls_name: Class name to be further used in logger output\n :return: logger object\n \"\"\"\n logger = getLogger(cls_name)\n logger.setLevel(environ.get('logger_lvl', INFO))\n formatter = Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')\n ch = StreamHandler()\n ch.setFormatter(formatter)\n if logger.hasHandlers():\n logger.handlers.clear()\n logger.addHandler(ch)\n\n return logger\n","sub_path":"MgmtModules/LoggerConfig.py","file_name":"LoggerConfig.py","file_ext":"py","file_size_in_byte":734,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"80699221","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\nfrom django.shortcuts import render, redirect\nfrom django.http import HttpResponse\nfrom django.contrib.auth.decorators import login_required\nfrom opDataInt.models import hostInfo\nfrom django.db.models import Q\nimport json\nfrom configCenter.models import groupManage\nfrom hostInfo.views import paginatorProcess\n\n@login_required\ndef groupManageIndex(request):\n group_info = groupManage.objects.all().order_by('groupId')\n page = request.GET.get('page')\n group_page = paginatorProcess(group_info, page)\n return render(request, 'groupManageIndex.html', {'business_info': group_page})\n\n\n@login_required\ndef groupManageAdd(request):\n if request.method == \"POST\":\n return render(request, \"addGroupInfo.html\")\n\n@login_required\ndef groupManageDB(request):\n if request.method == \"POST\":\n groupName = request.POST.get('groupName')\n hostList = request.POST.get('selectAll').split(',')\n truehostList = list(set(hostList))\n remarkInfo = request.POST.get('note')\n if groupManage.objects.filter(groupName__iexact=groupName):\n return HttpResponse(\"组已存在\")\n else:\n for hostNote in truehostList:\n ip = hostInfo.objects.filter(info__icontains=hostNote).values('internet_ip')[0]['internet_ip']\n datadict = {'groupName': groupName,\n 'internetIP': ip,\n 'remarkInfo': remarkInfo}\n groupManage.objects.create(**datadict)\n return redirect('/configCenter/groupManage/')\n\n@login_required\ndef groupManageDel(request):\n if request.method == 'POST':\n group_id = request.POST.get('g-del').strip()\n group_del_info = groupManage.objects.filter(Q(groupId__icontains=group_id))\n group_del_info.delete()\n return redirect('/configCenter/groupManage/')\n\n@login_required\ndef groupInfoSearch(request):\n res = None\n if request.method == 'POST':\n res = request.POST.get('keyword').strip()\n elif request.method == 'GET':\n res = request.GET.get('keyword').strip()\n all(request)\n business_info_search = groupManage.objects.filter(\n Q(groupName__icontains=res) | Q(internetIP__icontains=res)).order_by('groupId')\n page = request.GET.get('page')\n group_info_page = paginatorProcess(business_info_search, page)\n return render(request, 'groupManageIndex.html', {'business_info': group_info_page, 'search_argv': res})\n\n@login_required\ndef groupDetail(request):\n if request.method == 'POST':\n group_id = request.POST.get('g-detail')\n groupInfo = groupManage.objects.filter(groupId=group_id)\n print(groupInfo.values('internetIP'))\n return render(request, \"groupDetail.html\", {'business_info': groupInfo})\n\n@login_required\ndef groupModify(request):\n if request.method == 'POST':\n group_name = request.POST.get('change')\n group_Info = groupManage.objects.filter(groupName=group_name).values('groupName', 'remarkInfo').distinct()\n return render(request, 'groupModify.html', {'business_info': group_Info})\n\n@login_required\ndef modifyGroupToDB(request):\n try:\n if request.method == 'POST':\n group_name = request.POST.get('groupName')\n hostList = request.POST.get('selectAll').split(',')\n remarkInfo = request.POST.get('note')\n truehostlist = list(set(hostList))\n group_info = groupManage.objects.filter(groupName=group_name)\n group_info.delete()\n for hostNote in truehostlist:\n print(hostNote)\n ip = hostInfo.objects.filter(info__icontains=hostNote).values('internet_ip')[0]['internet_ip']\n print(ip)\n datadict = {'groupName': group_name,\n 'internetIP': ip,\n 'remarkInfo': remarkInfo}\n groupManage.objects.create(**datadict)\n return redirect('/configCenter/groupManage/')\n except:\n return HttpResponse('更新失败')\n\n@login_required\ndef selectAllGroup(request):\n if request.method == 'POST':\n group_name = request.body\n print(group_name)\n groupIp = groupManage.objects.filter(groupName=group_name).values('internetIP').distinct()\n infoList = list()\n for i in groupIp:\n ip = i['internetIP']\n info = hostInfo.objects.filter(internet_ip=ip).values(\"info\").distinct()\n for key in info:\n if key not in infoList:\n infoList.append(key)\n data = json.dumps({\"data\": infoList})\n return HttpResponse(data, content_type='application/json')\n","sub_path":".idea/HMbroadviewCoss/configCenter/views/groupManager.py","file_name":"groupManager.py","file_ext":"py","file_size_in_byte":4713,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"278061875","text":"#!/usr/bin/env python3\n\n\nimport time\nimport pygame\n\nfrom pygame.math import Vector2\n\n\n# ordinary pygame init\npygame.init()\nsize_x, size_y = (800, 600)\n\nscreen = pygame.display.set_mode(\n (size_x, size_y))\n\ntitle = \"Isometric coordinate systems visual test\"\n\npygame.display.set_caption(title)\n\n\n# configuration constants\n\n# size in pixels of an isometric 1x1 tile in cartesian coords, remember actual\n# pixel size of an individual tile image resource should be width equal to \n# ``tile_size`` and height equal to ``tile_size / 2``\ntile_size = 64\n \niso_scaling = 8 # scale factor for the isometric coords display\n\niso_size_x = 13 # total width of map in isometric system\niso_size_y = 13 # total height of map in isometric system\n\nred_color = (255, 0, 0)\ngreen_color = (0, 255, 0)\nblue_color = (0, 0, 255)\nyellow_color = (255, 255, 0)\n\n# when drawing the cartesian space add this delta to center \"camera\"\ncartesian_delta = Vector2(20, size_y / 2)\n\n# when drawing the isometric space add this delta to offset from window corner\niso_delta = Vector2(40)\n\ndef draw_point(pos: Vector2, color, width: int = 3):\n \"\"\"Helper function to draw a point\n \"\"\"\n pygame.draw.circle(\n screen,\n color,\n pos,\n width\n )\n\n\"\"\"Transformations\n\"\"\"\n\ndef iso_to_cartesian(pos: Vector2) -> Vector2:\n return Vector2(\n (pos.y + pos.x) / 2,\n (pos.y - pos.x) / 4 \n ) * tile_size\n\n\ndef cartesian_to_iso(pos: Vector2) -> Vector2:\n return Vector2(\n pos.x - (2 * pos.y),\n pos.x + (2 * pos.y)\n ) / tile_size\n\n\nif __name__ == '__main__':\n\n # create isometric position list\n positions = []\n for y in range(iso_size_y):\n for x in range(iso_size_x):\n positions.append(Vector2(x, y))\n\n # transform those positions to cartesian space\n cartesian_positions = []\n for pos in positions:\n cartesian_positions.append(iso_to_cartesian(pos))\n\n # transform back to isometric and compare to original coords\n checks = True\n for pos, cpos in zip(positions, cartesian_positions):\n checks = checks and (pos == cartesian_to_iso(cpos))\n\n if checks:\n pygame.display.set_caption(title + \" - [PASSED]\")\n else:\n pygame.display.set_caption(title + \" - [NOT PASSED]\")\n \n # begin main loop\n stop = False\n while not stop:\n\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n stop = True\n\n screen.fill((0, 0, 0))\n\n mouse_pos_x, mouse_pos_y = pygame.mouse.get_pos()\n mouse_pos = Vector2(mouse_pos_x, mouse_pos_y) - cartesian_delta\n\n # isometric drawing\n for pos in positions:\n draw_point((pos * iso_scaling) + iso_delta, red_color, width=1)\n\n iso_pos = cartesian_to_iso(mouse_pos)\n\n # mouse inside map?\n if (iso_pos.x >= 0 and iso_pos.y >= 0 and\n iso_pos.x < iso_size_x and iso_pos.y < iso_size_y):\n\n # pointer\n draw_point((iso_pos * iso_scaling) + iso_delta, yellow_color)\n\n # horizontal line\n pygame.draw.line(\n screen,\n yellow_color,\n (Vector2(0, iso_pos.y) * iso_scaling) + iso_delta,\n (Vector2(iso_size_x, iso_pos.y) * iso_scaling) + iso_delta\n )\n\n # vertical line\n pygame.draw.line(\n screen,\n yellow_color,\n (Vector2(iso_pos.x, 0) * iso_scaling) + iso_delta,\n (Vector2(iso_pos.x, iso_size_y) * iso_scaling) + iso_delta\n )\n\n\n\n # cartesian drawing\n for pos in cartesian_positions:\n draw_point(pos + cartesian_delta, blue_color)\n \n # mouse inside map?\n if (iso_pos.x >= 0 and iso_pos.y >= 0 and\n iso_pos.x < iso_size_x and iso_pos.y < iso_size_y):\n\n # pointer\n draw_point(mouse_pos + cartesian_delta, green_color)\n\n # horizontal line\n pygame.draw.line(\n screen,\n green_color,\n iso_to_cartesian(Vector2(0, iso_pos.y)) + cartesian_delta,\n iso_to_cartesian(Vector2(iso_size_x, iso_pos.y)) + cartesian_delta\n )\n\n # vertical line\n pygame.draw.line(\n screen,\n green_color,\n iso_to_cartesian(Vector2(iso_pos.x, 0)) + cartesian_delta,\n iso_to_cartesian(Vector2(iso_pos.x, iso_size_y)) + cartesian_delta\n )\n\n pygame.display.flip()\n\n pygame.quit()\n","sub_path":"tests/visual/coords_test.py","file_name":"coords_test.py","file_ext":"py","file_size_in_byte":4552,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"13751905","text":"import math\nimport matplotlib.pyplot as plt\n\ndef f(x):\n return math.pow(math.e,x)+x+7\ndef secant(xk,xkm1,f,number):\n for i in range(number):\n if(f(xk)-f(xkm1) == 0):\n break\n xkp1 = xk-((xk-xkm1)/(f(xk)-f(xkm1)))*f(xk)\n xkm1 = xk\n xk = xkp1\n print(\"xk: \",xk)\n return xkp1\ndef foo(x):\n return math.pow(math.e,math.pow(math.sin(x),3))+math.pow(x,6)-2*math.pow(x,4)-math.pow(x,3)-1\ndef dxfoo(x):\n return math.pow(math.e,math.pow(math.sin(x),3))*3*math.pow(math.sin(x),2)*math.cos(x)+6*math.pow(x,5)-8*math.pow(x,3)-3*math.pow(x,2)\ndef newton(f,df,x0,number,tol):\n n=0\n dx=f(x0)/df(x0)\n while ((dx>tol) and (f(x0)>tol) or (n 1:\n acc_user_request_read[1:].assign(request_read[1:])\n \n acc_user_request_read[0].assign(request_read[0] | conf_control_req_rd_data)\n\n genInstFor1 = m.GenerateFor(genv(0), genv < num_pe_io_in, genv.inc(), 'inst_fecth_data')\n genInstFor2 = m.GenerateFor(genv(0), genv < num_pe_io_out, genv.inc(), 'inst_dispath_data')\n\n params = [('INPUT_DATA_WIDTH', 512), ('OUTPUT_DATA_WIDTH', data_width)]\n con = [\n ('clk', clk), ('rst', rst), ('en', en_fecth_data[genv]), ('available_read', acc_user_available_read[genv]),\n ('request_read', request_read[genv]), ('data_valid', acc_user_read_data_valid[genv]),\n ('read_data', acc_user_read_data[Mul(genv, 512):Mul(genv + 1, 512)]), ('pop_data', fifo_in_re[genv]),\n ('available_pop', available_pop[genv]),\n ('data_out', fifo_in_data[Mul(genv, data_width):Mul(genv + 1, data_width)])\n ]\n genInstFor1.Instance(fd, 'fecth_data', params, con)\n\n params = [('INPUT_DATA_WIDTH', data_width), ('OUTPUT_DATA_WIDTH', 512)]\n con = [('clk', clk), ('rst', rst),\n ('available_write', acc_user_available_write[genv]),\n ('request_write', acc_user_request_write[genv]),\n ('write_data', acc_user_write_data[Mul(genv, 512):Mul(genv + 1, 512)]), ('push_data', fifo_out_we[genv]),\n ('available_push', available_push[genv]),\n ('data_in', fifo_out_data[Mul(genv, data_width):Mul(genv + 1, data_width)])\n ]\n genInstFor2.Instance(dd, 'dispath_data', params, con)\n\n params = []\n con = [\n ('clk', clk), ('rst', rst), ('start', start), ('available_read', acc_user_available_read[0]),\n ('req_rd_data', conf_control_req_rd_data), ('rd_data', acc_user_read_data[0:512]),\n ('rd_data_valid', acc_user_read_data_valid[0]), ('conf_out_bus', conf_out_bus),\n ('read_fifo_mask', read_fifo_mask),\n ('write_fifo_mask', write_fifo_mask), ('done', conf_done)\n ]\n m.Instance(control_conf, 'control_conf', params, con)\n\n params = []\n con = [('clk', clk), ('rst', rst), ('start', conf_done), ('read_fifo_mask', read_fifo_mask),\n ('write_fifo_mask', write_fifo_mask), ('available_read', acc_user_available_read),\n ('available_write', acc_user_available_write),\n ('available_pop', available_pop), ('available_push', available_push),\n ('read_fifo_done', acc_user_done_rd_data),\n ('write_fifo_done', acc_user_done_wr_data), ('en', en),\n ('en_fecth_data', en_fecth_data), ('done', acc_user_done)\n ]\n m.Instance(control_exec, 'control_exec', params, con)\n\n params = []\n con = [\n ('clk', clk), ('rst', rst), ('en', en),\n ('conf_bus_in', conf_out_bus), ('fifo_in_re', fifo_in_re), ('fifo_in_data', fifo_in_data),\n ('fifo_out_we', fifo_out_we), ('fifo_out_data', fifo_out_data)\n ]\n m.Instance(cgra, 'cgra', params, con)\n\n return m\n","sub_path":"hw/src/make_cgra_accelerator.py","file_name":"make_cgra_accelerator.py","file_ext":"py","file_size_in_byte":5660,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"451926105","text":"import sys\nimport numpy as np\nimport matplotlib\nimport matplotlib.pyplot as plt\n\nout_ind = '1s50auv_2e6.tab'\nout_ind1 = '1s50auv_2e6.tab'\nIter = 100\n\n############################################################################\nname = 'init_neutral_mass'\n# find the name of the plotting\nf = open(out_ind,'r')\nmark = True\nwhile(mark):\n line = f.readline()\n data = line.split()\n if data[0]==name:\n mark = False\n numx = int(data[1])\n px = np.linspace(0,0,numx)\n py = np.linspace(0,0,numx)\n py0 = np.linspace(0,0,numx)\n neu = np.linspace(0,0,numx)\n for i in range(0,numx):\n line = f.readline()\n data = line.split()\n px[i] = float(data[0])\n neu[i] = float(data[1])\n py[i] = 1.0\n py0[i] = 0.0\n break\n\nf1 = open(out_ind1,'r')\nwhile(1>0):\n line1 = f1.readline()\n data1 = line1.split()\n if data1[0]==name:\n numx1 = int(data1[1])\n px1 = np.linspace(0,0,numx1)\n py1 = np.linspace(0,0,numx1)\n py2 = np.linspace(0,0,numx1)\n neu1 = np.linspace(0,0,numx1)\n for i in range(0,numx1):\n line = f1.readline()\n data = line.split()\n px1[i] = float(data[0])\n neu1[i] = float(data[1])\n py1[i] = 1.0\n py2[i] = 0.0\n break\n#print 'numx1=',numx1\n\nname = 'dust_vert_distribution'\nf = open(out_ind,'r')\nmark = True\nwhile(mark):\n line = f.readline()\n data = line.split()\n if data[0]==name:\n mark = False\n numy = int(data[2])\n break\nf.close()\n\nf = open(out_ind1,'r')\nmark = True\nwhile(mark):\n line = f.readline()\n data = line.split()\n if data[0]==name:\n mark = False\n numy1 = int(data[2])\n break\nf.close()\n\n#print 'num',numx,numy,numx1,numy1\n######################\nplt.plot(px,py,'k-',linewidth=1.5,label=r'$\\rm gas $')\nplt.plot(px,py0,'b-',linewidth=1.5,label=r'$\\rm mantle$')\nplt.plot(px,py,'k--',linewidth=1.5)\nplt.plot(px,py0,'b--',linewidth=1.5)\nfont = {'family' : 'sans-serif',\n 'sans-serif' : 'Helvetica',\n 'weight' : 'light',\n 'size' : 20}\nmatplotlib.rc('font', **font)\n\nn = 0\nplt.axis([0,5,0,2.0])\nplt.xlabel(r'$\\rm Z/H$')\nplt.ylabel(r'$\\rm n/n_{initial}$')\ntxt = r'$\\rm Time: $'+str(int(10*n))+r'$ \\rm kyr$'\nplt.text(1.0,1.3,txt, fontsize=18)\nplt.legend(loc=1)\nfig = plt.gcf()\n#plt.savefig('fig/'+out_ind+str(\"%03d\" %(n))+'.eps',format='eps',dpi=500,bbox_inches='tight')\nplt.show()\nplt.close()\n\nf.close()\nf1.close()\n\n\n#####################################\nname = 'timestep'\nf = open(out_ind,'r')\nf1 = open(out_ind1,'r')\nwhile(1>0):\n line = f.readline()\n data = line.split()\n if data[0]==name:\n break\nwhile(1>0):\n line = f1.readline()\n data = line.split()\n if data[0]==name:\n break\n\nfor n in range(1,Iter):\n #print 'n=',n\n sum0 = np.linspace(0,0,numx) \n sum1 = np.linspace(0,0,numx1) \n ############################\n for i in range(0,numx):\n fi = f.readline()\n data = fi.split()\n px[i] = float(data[0])\n py[i] = float(data[1])/neu[i]\n for j in range(2,numy+1):\n sum0[i] += float(data[j])\n py0[i]= sum0[i]/neu[i]\n #print px[i],py[i],py0[i]\n #############################\n for i in range(0,numx1):\n fi1 = f1.readline()\n data1 = fi1.split()\n px1[i] = float(data1[0])\n py1[i] = float(data1[1])/neu1[i]\n for j in range(2,numy1+1):\n sum1[i] += float(data1[j])\n py2[i]= sum1[i]/neu1[i]\n #print px1[i],py1[i],py2[i]\n\n if n Dict[str, Any]:\n function, filename, lineno = stack_frame\n\n name = (\n # Use the source file line.\n linecache.getline(filename, lineno)\n # Or just describe where it is from\n or f\"{function} at {filename}:{lineno}\"\n )\n return {\n \"name\": name,\n \"location\": [html.escape(function), html.escape(filename), lineno],\n \"value\": 0,\n \"children\": [],\n \"n_allocations\": 0,\n \"interesting\": (\n is_frame_interesting(stack_frame)\n and not is_frame_from_import_system(stack_frame)\n ),\n **kwargs,\n }\n\n\nclass StringRegistry:\n def __init__(self) -> None:\n self.strings: List[str] = []\n self._index_by_string: Dict[str, int] = {}\n\n def register(self, string: str) -> int:\n idx = self._index_by_string.setdefault(string, len(self.strings))\n if idx == len(self.strings):\n self.strings.append(string)\n return idx\n\n\nclass FlameGraphReporter:\n def __init__(\n self,\n data: Dict[str, Any],\n *,\n memory_records: Iterable[MemorySnapshot],\n ) -> None:\n super().__init__()\n self.data = data\n self.memory_records = memory_records\n\n @classmethod\n def _from_any_snapshot(\n cls,\n allocations: Iterable[Union[AllocationRecord, TemporalAllocationRecord]],\n *,\n memory_records: Iterable[MemorySnapshot],\n native_traces: bool,\n temporal: bool,\n ) -> \"FlameGraphReporter\":\n root: Dict[str, Any] = {\n \"name\": \"\",\n \"location\": [html.escape(\"\"), \"memray\", 0],\n \"value\": 0,\n \"children\": [],\n \"n_allocations\": 0,\n \"thread_id\": \"0x0\",\n \"interesting\": True,\n \"import_system\": False,\n }\n\n frames = [root]\n interval_list: List[Tuple[int, Optional[int], int, int, int]] = []\n\n node_index_by_key: Dict[Tuple[int, StackFrame, str], int] = {}\n\n unique_threads = set()\n for record in allocations:\n thread_id = record.thread_name\n\n unique_threads.add(thread_id)\n\n if temporal:\n assert isinstance(record, TemporalAllocationRecord)\n intervals = record.intervals\n size = None\n n_allocations = None\n else:\n assert not isinstance(record, TemporalAllocationRecord)\n intervals = None\n size = record.size\n n_allocations = record.n_allocations\n\n if size is not None:\n root[\"value\"] += size\n if n_allocations is not None:\n root[\"n_allocations\"] += n_allocations\n\n current_frame_id = 0\n current_frame = root\n\n stack = (\n tuple(record.hybrid_stack_trace())\n if native_traces\n else record.stack_trace()\n )\n num_skipped_frames = 0\n is_import_system = False\n for index, stack_frame in enumerate(reversed(stack)):\n node_key = (current_frame_id, stack_frame, thread_id)\n if node_key not in node_index_by_key:\n if is_cpython_internal(stack_frame):\n num_skipped_frames += 1\n continue\n\n if not is_import_system:\n is_import_system = is_frame_from_import_system(stack_frame)\n\n new_node_id = len(frames)\n node_index_by_key[node_key] = new_node_id\n current_frame[\"children\"].append(new_node_id)\n frames.append(\n create_framegraph_node_from_stack_frame(\n stack_frame,\n import_system=is_import_system,\n thread_id=thread_id,\n )\n )\n\n current_frame_id = node_index_by_key[node_key]\n current_frame = frames[current_frame_id]\n is_import_system = current_frame[\"import_system\"]\n if size is not None:\n current_frame[\"value\"] += size\n if n_allocations is not None:\n current_frame[\"n_allocations\"] += n_allocations\n\n if index - num_skipped_frames > MAX_STACKS:\n current_frame[\"name\"] = \"\"\n current_frame[\"location\"] = [\"...\", \"...\", 0]\n break\n\n if intervals is not None:\n interval_list.extend(\n (\n interval.allocated_before_snapshot,\n interval.deallocated_before_snapshot,\n current_frame_id,\n interval.n_allocations,\n interval.n_bytes,\n )\n for interval in intervals\n )\n\n all_strings = StringRegistry()\n nodes = collections.defaultdict(list)\n for frame in frames:\n nodes[\"name\"].append(all_strings.register(frame[\"name\"]))\n nodes[\"function\"].append(all_strings.register(frame[\"location\"][0]))\n nodes[\"filename\"].append(all_strings.register(frame[\"location\"][1]))\n nodes[\"lineno\"].append(frame[\"location\"][2])\n nodes[\"children\"].append(frame[\"children\"])\n if not interval_list:\n nodes[\"value\"].append(frame[\"value\"])\n nodes[\"n_allocations\"].append(frame[\"n_allocations\"])\n nodes[\"thread_id\"].append(all_strings.register(frame[\"thread_id\"]))\n nodes[\"interesting\"].append(int(frame[\"interesting\"]))\n nodes[\"import_system\"].append(int(frame[\"import_system\"]))\n\n data = {\n \"unique_threads\": tuple(\n all_strings.register(t) for t in sorted(unique_threads)\n ),\n \"nodes\": nodes,\n \"strings\": all_strings.strings,\n }\n\n if interval_list:\n data[\"intervals\"] = interval_list\n\n return cls(data, memory_records=memory_records)\n\n @classmethod\n def from_snapshot(\n cls,\n allocations: Iterable[AllocationRecord],\n *,\n memory_records: Iterable[MemorySnapshot],\n native_traces: bool,\n ) -> \"FlameGraphReporter\":\n return cls._from_any_snapshot(\n allocations,\n memory_records=memory_records,\n native_traces=native_traces,\n temporal=False,\n )\n\n @classmethod\n def from_temporal_snapshot(\n cls,\n allocations: Iterable[TemporalAllocationRecord],\n *,\n memory_records: Iterable[MemorySnapshot],\n native_traces: bool,\n high_water_mark_by_snapshot: Optional[List[int]],\n ) -> \"FlameGraphReporter\":\n ret = cls._from_any_snapshot(\n allocations,\n memory_records=memory_records,\n native_traces=native_traces,\n temporal=True,\n )\n ret.data[\"high_water_mark_by_snapshot\"] = high_water_mark_by_snapshot\n return ret\n\n def render(\n self,\n outfile: TextIO,\n metadata: Metadata,\n show_memory_leaks: bool,\n merge_threads: bool,\n ) -> None:\n kind = \"temporal_flamegraph\" if \"intervals\" in self.data else \"flamegraph\"\n html_code = render_report(\n kind=kind,\n data=self.data,\n metadata=metadata,\n memory_records=self.memory_records,\n show_memory_leaks=show_memory_leaks,\n merge_threads=merge_threads,\n )\n print(html_code, file=outfile)\n","sub_path":"src/memray/reporters/flamegraph.py","file_name":"flamegraph.py","file_ext":"py","file_size_in_byte":8655,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"391817204","text":"#!/bin/env python\n# coding: utf-8\n\nimport os\nfrom flask import Flask, render_template, request\n\napp = Flask(__name__)\napp.debug = True\n\n\n@app.route('/')\ndef index():\n return render_template('index.html')\n\n\n@app.route('/hello',methods=['GET','POST'])\ndef hello():\n\tname = ''\n\tif request.method == 'POST':\n\t\tif (request.form['name'] != ''):\n\t\t\tname = request.form['name'] + u'さん'\n\t\telse:\n\t\t\tname = u'名無しさん'\n\telse:\n\t\tname = u'名無しさん'\n\n\treturn render_template('hello.html', name = name)\n\n\nif __name__ == '__main__':\n port = int(os.environ.get('PORT', 5000))\n app.run(port=port)","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":605,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"66280885","text":"from flask import Flask, jsonify\nimport subprocess\napp = Flask(__name__)\nfrom CarDetection import *\n\nimage_name = \"cam_s2.jpg\"\n\n@app.route(\"/\")\ndef exec():\n # subprocess capture image if we have multiple pi & cameras\n isVacant = detect(image_name)\n return jsonify(isVacant=isVacant)\n\nif __name__ == \"__main__\":\n app.run(host='0.0.0.0', port=8091, debug=True)\n\n","sub_path":"slave2.py","file_name":"slave2.py","file_ext":"py","file_size_in_byte":372,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"567033336","text":"#!/usr/bin/env python2\nimport rospy\nfrom sensor_msgs.msg import LaserScan\nfrom geometry_msgs.msg import Pose, PoseStamped, Point, PointStamped, Quaternion\nfrom irob_assignment_1.srv import GetSetpoint, GetSetpointRequest, GetSetpointResponse\nfrom orm import ORM\nfrom polar_histogram import PolarHistogram\nimport tf2_ros\nimport tf2_geometry_msgs\nfrom math import atan2, hypot\nimport numpy as np\n\ntf_buffer = None\nlistener = None\n\nlatest_scan = None\n\nserver = None\n\nrobot_frame_id = \"\"\nlook_ahead_distance = 2\ndistance_converged = 0.3\nradius = 0.105\n\norm = None\n\npub = None\n\n\ndef scan_callback(msg):\n global latest_scan\n latest_scan = msg\n\n\ndef get_obstacles():\n global latest_scan\n scan = latest_scan\n\n # FIXME: What should last argument be?\n obstacles = PolarHistogram(len(scan.ranges), float(\"inf\"))\n\n angle = scan.angle_min\n for r in scan.ranges:\n obstacles.set_range(angle, r)\n angle += scan.angle_increment\n\n return obstacles\n\n\ndef get_next_setpoint(path):\n global tf_buffer, robot_frame_id, look_ahead_distance, distance_converged\n distance_left = look_ahead_distance\n\n transform = tf_buffer.lookup_transform(\n robot_frame_id, path.header.frame_id, rospy.Time(0), rospy.Duration(1))\n transform_inverse = tf_buffer.lookup_transform(\n path.header.frame_id, robot_frame_id, rospy.Time(0), rospy.Duration(1))\n\n point = tf2_geometry_msgs.do_transform_point(\n PointStamped(path.header, path.poses[0].pose.position), transform)\n\n distance = np.linalg.norm(np.array([[point.point.x, point.point.y]]))\n\n last_point = PointStamped()\n\n # print(len(path.poses))\n\n if 1 == len(path.poses):\n point.header = path.header\n point.point = path.poses[0].pose.position\n if distance < distance_converged:\n del path.poses[0]\n return point\n elif distance <= (look_ahead_distance / 2.0):\n del path.poses[0]\n last_point = point\n distance_left -= distance\n elif distance > look_ahead_distance:\n point.header = path.header\n point.point = path.poses[0].pose.position\n return point\n\n last_position = np.array([[last_point.point.x, last_point.point.y]])\n for pose in path.poses:\n # FIXME: We assume that it is the same transform...\n point = tf2_geometry_msgs.do_transform_point(\n PointStamped(path.header, pose.pose.position), transform)\n position = np.array([[point.point.x, point.point.y]])\n distance = np.linalg.norm(position - last_position)\n if distance > distance_left:\n last_point.header = path.header\n # Return interpolated between point and last_point\n last_point.point = interpolate(\n last_point.point, point.point, distance_left / distance)\n return tf2_geometry_msgs.do_transform_point(last_point, transform_inverse)\n\n distance_left -= distance\n last_point = point\n last_position = position\n\n point.header = path.header\n point.point = path.poses[-1].pose.position\n return point # Return last element\n\n\ndef interpolate(start, end, t):\n return lerp(start, end, t)\n\n\ndef lerp(start, end, t):\n result = Point()\n result.x = (1.0 - t) * start.x + t * end.x\n result.y = (1.0 - t) * start.y + t * end.y\n result.z = (1.0 - t) * start.z + t * end.z\n return result\n\n\ndef avoid_collision(setpoint):\n global radius\n transform = tf_buffer.lookup_transform(\n robot_frame_id, setpoint.header.frame_id, rospy.Time(0), rospy.Duration(1))\n transform_inverse = tf_buffer.lookup_transform(\n setpoint.header.frame_id, robot_frame_id, rospy.Time(0), rospy.Duration(1))\n\n point = tf2_geometry_msgs.do_transform_point(setpoint, transform)\n\n goal = [point.point.x, point.point.y]\n obstacles = get_obstacles()\n\n control = orm.avoid_collision(goal, obstacles)\n\n point.point.x = control[0]\n point.point.y = control[1]\n\n return tf2_geometry_msgs.do_transform_point(point, transform_inverse)\n\n\ndef get_setpoint_callback(req):\n res = GetSetpointResponse()\n\n if 0 == len(req.path.poses):\n res.setpoint.header = req.path.header\n return res\n\n res.setpoint = get_next_setpoint(req.path)\n res.setpoint = avoid_collision(res.setpoint)\n pub.publish(res.setpoint)\n res.new_path = req.path\n return res\n\n\nif __name__ == \"__main__\":\n rospy.init_node(\"collision_avoidance\")\n\n # Temp for testing\n pub = rospy.Publisher(\"collision_free_control_point\", PointStamped, queue_size=10)\n\n # Read parameters\n robot_frame_id = rospy.get_param(\"~robot_frame_id\", \"base_link\")\n look_ahead_distance = rospy.get_param(\"~look_ahead_distance\", 2.0)\n radius = rospy.get_param(\"~radius\", 0.105)\n security_distance = rospy.get_param(\"~security_distance\", 0.1)\n epsilon = rospy.get_param(\"~epsilon\", 0.1)\n\n # Create TF buffer\n tf_buffer = tf2_ros.Buffer()\n listener = tf2_ros.TransformListener(tf_buffer)\n\n # Subscribers\n rospy.Subscriber(\"scan\", LaserScan, scan_callback)\n\n # Server\n server = rospy.Service(\"get_setpoint\", GetSetpoint, get_setpoint_callback)\n\n # Init ORM\n orm = ORM(radius, security_distance, epsilon)\n\n rospy.spin()\n","sub_path":"scripts/collision_avoidance.py","file_name":"collision_avoidance.py","file_ext":"py","file_size_in_byte":5228,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"195099274","text":"#dashGUI.py\n#Description: DASH python html gui\n#Engineer: T Looby\n#Date: 20200615 (ish)\n\"\"\"\nThis is the python - html interface, and the launch point for the HEAT code.\nRunning this script launches a web interface that can be used to run HEAT\nThe web interface is html and can be accessed via any web browser.\n\nDASH is the python library that creates the html - python binding\nUnder the hood, DASH is running a flask server with associated proxy mapping,\n html, javascipt, etc. We use decorators (@) to serve as javascript callbacks\n\nThere are css files that go with this program. They are located in the\n ./assets directory\n\nIf you want to use this in a production environment serving multiple sessions\nsimultaneously, you will need to run a gunicorn server or something to isolate\ndifferent users' class variables from each other.\n\ndashGUI.py should be called with no arguments to run on 127.0.0.1:8050 (default)\nto run on address:port, use command line:\ndashGUI.py
    \n\nYou will need to set a few variables below, based upon your system paths\nrootDir, PVPath\n\"\"\"\n#========= VARIABLES THAT ARE SYSTEM DEPENDENT =================================\nimport os\nimport sys\nimport subprocess\n#If this code is being run inside an appImage, then we set our paths up accordingly\ntry:\n AppImage = os.environ[\"APPIMAGE\"]\n inAppImage = True\nexcept:\n inAppImage = False\n\n#default HEAT output directory\nhomeDir = os.environ[\"HOME\"]\ndataPath = homeDir + '/HEAT/data'\n\nif inAppImage == True:\n print(\"Running in appImage mode\\n\")\n AppDir = os.environ[\"APPDIR\"]\n #Include the location of the paraview binaries\n #Specifically we need the python libs and pvpython\n PVPath = os.environ[\"PVPath\"]\n pvpythonCMD = os.environ[\"pvpythonCMD\"]\n #Root HEAT source code directory\n rootDir = AppDir + '/usr/src'\n #openFOAM bashrc location\n OFbashrc = AppDir + '/usr/opt/openfoam/openfoam1912/etc/bashrc'\n OFdir = AppDir+'/usr/opt/openfoam/openfoam1912'\n #default freecad path\n #FreeCADPath = AppDir + '/opt/freecad/squashfs-root/usr/lib'\n FreeCADPath = AppDir + '/usr/lib/freecad-python3/lib'\n #default source code location (EFIT class should be here)\n EFITPath = AppDir + '/usr/src'\n #python site packages where PyFoam resides\n pyFoamPath = AppDir + '/lib/python3.8/site-packages'\n\nelse:\n ### If developing you will need to edit these manually!\n print(\"Running in dev mode\\n\")\n #Include the location of the paraview binaries.\n #Specifically we need the python libs and pvpython\n PVPath = '/opt/paraview/ParaView-5.9.0-RC2-MPI-Linux-Python3.8-64bit/lib/python3.8/site-packages'\n pvpythonCMD = '/opt/paraview/ParaView-5.9.0-RC2-MPI-Linux-Python3.8-64bit/bin/pvpython'\n #Root HEAT source code directory\n rootDir = '/home/tom/source/HEAT/github/source'\n #default freecad path\n# FreeCADPath = '/opt/freecad/squashfs-root/usr/lib'\n #FreeCADPath = '/usr/lib/freecad/lib'\n FreeCADPath = '/usr/lib/freecad-python3/lib'\n #default source code location (EFIT class should be here)\n EFITPath = '/home/tom/source'\n #default openFOAM source path\n OFbashrc = '/opt/openfoam/openfoam-OpenFOAM-v1912/etc/bashrc'\n# OFbashrc = '/opt/OpenFOAM/OpenFOAM-v1912/etc/bashrc'\n #python site packages where PyFoam resides\n pyFoamPath = '/home/tom/.local/lib/python3.8/site-packages'\n #pyFoam python scripts\n pyFoamPath = '/'\n #default AppDir for when running in dev mode\n AppDir = 'not in appImage mode'\n #create necessary environment variables when outside appImage\n os.environ[\"PVPath\"] = PVPath\n os.environ[\"pvpythonCMD\"] = pvpythonCMD\n\n#default logfile location\nlogFile = dataPath + '/HEATlog.txt'\n#list of tokamak flags that are options in HEAT (if adding new tokamak add flag to list)\nmachineList = ['d3d','nstx','st40','step','sparc']\n\n#===============================================================================\n\n\n#=======UPDATE PATHS============================================================\n#orca installation location (for saving EQ plots)\n#pio.orca.config.executable='/usr/bin/orca'\n#append EFIT to python path\nsys.path.append(EFITPath)\n#append FreeCAD to python path\nsys.path.append(FreeCADPath)\n#append paraview to python path\nsys.path.append(PVPath)\n#append pyFoam site-packages location to python path\nsys.path.append(pyFoamPath)\n#append pvpython to binary path\noldEnv = os.environ[\"PATH\"]\n#os.environ[\"PATH\"] = oldEnv + ':' + pvpythonCMD\n#===============================================================================\n\nimport shutil\nimport base64\nimport io\nimport json\nimport numpy as np\nimport pandas as pd\nimport parser\nimport time\nimport copy\nimport dash\nimport dash_html_components as html\nimport dash_core_components as dcc\nfrom dash.dependencies import Input, Output, State\nfrom dash.exceptions import PreventUpdate\nimport visdcc\nfrom flask import Flask, send_from_directory\nimport plotly.io as pio\nimport dash_table\nimport EFIT.equilParams_class as EP\nimport toolsClass\ntools = toolsClass.tools()\nfrom dash_extensions import Download\nfrom dash_extensions.snippets import send_file\nimport ipaddress\n\n#Create log files that will be displayed in the HTML GUI\nfrom pathlib import Path\nif not os.path.exists(dataPath):\n os.makedirs(dataPath)\nPath(logFile).touch()\nimport logging\nlogFlask = logging.getLogger('werkzeug')\nlogFlask.disabled = True\nlogging.basicConfig(filename=logFile, filemode=\"w\", level=logging.INFO, format='%(message)s')\nlog = logging.getLogger(__name__)\n\n#Make sure all our python scripts are in the path\nfrom GUIclass import GUIobj\n#app = dash.Dash(__name__, meta_tags=[{\"name\": \"viewport\", \"content\": \"width=device-width\"}])\n#Create our own server for downloading files\nserver = Flask(__name__)\napp = dash.Dash(server=server, meta_tags=[{\"name\": \"viewport\", \"content\": \"width=device-width\"}],\n prevent_initial_callbacks=False)\n\n#Eventually need to fix this so that we are not using a global variable\n#dash can acces Flask Cache so we should cache data by userID or something\n#for R&D this works\ngui = GUIobj(logFile, rootDir, dataPath, OFbashrc)\n\n\"\"\"\n==============================================================================\nBanner and Tabs\n\"\"\"\n\ndef build_banner():\n return html.Div(\n id=\"banner\",\n className=\"banner\",\n children=[\n html.Div(\n id=\"banner-text\",\n children=[\n html.H4(\"Heat flux Engineering Analysis Toolkit (HEAT)\"),\n ],\n ),\n ],\n )\n\n# Dash doesnt let CSS overwrite tab settings so do it here\ntabs_style = {\n# 'width': '15%'\n}\ntab_style = {\n 'fontWeight': 'bold',\n 'color': '#ffffff',\n 'backgroundColor': '#252626',\n 'border': 'none',\n\n}\ntab_selected_style = {\n 'backgroundColor': '#119DFF',\n 'color': 'blue',\n 'border': 'none',\n}\n\ndef build_tabs():\n \"\"\"\n returns tab bar\n \"\"\"\n return html.Div(\n id=\"tabs\",\n# className=\"tab-container\",\n className=\"tabcontent\",\n children=[\n dcc.Tabs(\n id=\"app-tabs\",\n value=\"tab1\",\n vertical=True,\n style=tabs_style,\n children=[\n dcc.Tab(\n id=\"input-tab\",\n label=\"Inputs\",\n value=\"tab1\",\n style=tab_style,\n selected_style=tab_selected_style,\n children=[\n html.Div(\n# className='tabcontent',\n className=\"innerTabContent\",\n children=[\n buildDefaultPaths(),\n buildButtonRibbon(),\n buildMHDbox(),\n buildCADbox(),\n buildPFCbox(),\n buildHFbox(),\n buildOFbox(),\n ]\n )\n ]\n ),\n dcc.Tab(\n id=\"run-tab\",\n label=\"Run HEAT\",\n value=\"tab2\",\n style=tab_style,\n selected_style=tab_selected_style,\n children=[\n html.Div(\n# className='tabcontent',\n className=\"innerTabContent\",\n children=[\n buildRunTab()\n ]\n )\n ]\n ),\n dcc.Tab(\n id=\"gfileCleaner-tab\",\n label=\"gFile Tools\",\n value=\"tab3\",\n style=tab_style,\n selected_style=tab_selected_style,\n children=[\n html.Div(\n# className='tabcontent',\n className=\"innerTabContent\",\n children=[\n buildGfileCleanerTab()\n ]\n )\n ]\n ),\n\n dcc.Tab(\n id=\"output-tab\",\n label=\"Output\",\n value=\"tab4\",\n style=tab_style,\n selected_style=tab_selected_style,\n children=[\n html.Div(\n# className='tabcontent',\n className=\"innerTabContentColumn\",\n children=[\n buildOutputTab()\n ]\n )\n ],\n ),\n dcc.Tab(\n id=\"log-tab\",\n label=\"LogFile\",\n value=\"tab5\",\n style=tab_style,\n selected_style=tab_selected_style,\n children=[\n html.Div(\n# className='tabcontent',\n className=\"logTabContent\",\n children=[\n buildLogTab()\n ]\n )\n ],\n ),\n\n\n ],\n )\n ],\n )\n\n\"\"\"\n==============================================================================\nTab Contents: inputs tab\n\"\"\"\ndef buildButtonRibbon():\n \"\"\"\n returns machine selector and load default buttons\n \"\"\"\n return html.Div(\n id=\"buttonRib\",\n className=\"buttonRibbon\",\n children=[\n html.H5(\"Machine Selection and Input Files\"),\n html.Div(\n children=[\n buildMachineSelector(),\n buildInputButtons(),\n ],\n className=\"rowBox\"\n )\n ],\n )\n\ndef buildDefaultPaths():\n \"\"\"\n contains text boxes for HEAT relevent paths\n PVPath is path for paraview binaries and pvpython\n FreeCAD is location of freecad installation\n dataDir is location where HEAT output will be saved\n\n rootDir is location of HEAT source code and is not included in GUI\n because it would be impossible to run GUI if this was not already set.\n rootDir (and some other defaults) are hardcoded at the top of this file\n\n if className is Hidden, then the input exists in html but is hidden from user\n \"\"\"\n return html.Div(\n id=\"defaultPaths\",\n children=[\n html.Label(\"ParaVIEW Path\", className=\"textInputHidden\"),\n dcc.Input(id=\"PVPath\", className=\"textInputHidden\", value=PVPath),\n html.Label(\"FreeCAD Path\", className=\"textInputHidden\"),\n dcc.Input(id=\"FreeCADPath\", className=\"textInputHidden\", value=FreeCADPath),\n html.Label(\"Data Directory\"),\n dcc.Input(id=\"dataPath\", className=\"textInput\", value=dataPath),\n html.Label(\"OpenFOAM bashrc file\", className=\"textInputHidden\"),\n dcc.Input(id=\"OFbashrc\", className=\"textInputHidden\", value=OFbashrc),\n html.Label(\"AppImage Mount Directory: \"+AppDir)\n ],\n className=\"colBox\"\n )\n\ndef buildMachineSelector():\n \"\"\"\n returns machine selector dropdown\n \"\"\"\n return html.Div(\n className=\"machineSelectBox\",\n children=[\n html.Label(id=\"machLabel\", children=\"Select a Tokamak\"),\n dcc.Dropdown(\n id='MachFlag',\n className=\"machineSelect\",\n style={'backgroundColor': 'transparent', 'color':'transparent',\n 'align-items':'center'},\n #style=dropdown_style,\n options=[\n {'label': 'NSTX-U', 'value': 'nstx'},\n {'label': 'DIII-D', 'value': 'd3d'},\n {'label': 'ST40', 'value': 'st40'},\n {'label': 'STEP', 'value': 'step'},\n {'label': 'SPARC', 'value': 'sparc'}\n ],\n value=None\n ),\n html.Div(id=\"hiddenDivMachFlag\"),\n dcc.Upload(\n className=\"inputUpload\",\n id='input-upload',\n children=html.Div([\n 'Drag and Drop or ',\n html.A('Select input file')\n ]),\n style={\n 'width': '100%', 'height': '60px', 'lineHeight': '60px',\n 'borderWidth': '1px', 'borderStyle': 'dashed',\n 'borderRadius': '5px', 'textAlign': 'center', 'margin': '10px',\n 'align-items':'center'\n },\n multiple=True,\n ),\n ],\n )\n\ndef buildInputButtons():\n \"\"\"\n returns Load Defaults drag and drop and Upload Input buttons\n \"\"\"\n return html.Div(\n id=\"buttonInputs\",\n className=\"defaultButtonBox\",\n children=[\n html.Div(id=\"hiddenDivInput\"),\n html.Button(\"Load Defaults (optional)\", id=\"loadDefaults\", n_clicks=0, className=\"defaultButtons\"),\n html.Button(\"Save Settings\\nInto Input File\", id=\"saveInputs\",\n n_clicks=0, className=\"defaultButtons\"),\n Download(id=\"downloadInputs\"),\n html.Div(id=\"hiddenDivSaveInput\"),\n ],\n )\n\n@app.callback(Output('hiddenDivMachFlag', 'children'),\n [Input('MachFlag', 'value')])\ndef machineSelector(MachFlag):\n \"\"\"\n callback to handle machine selector drop down\n \"\"\"\n if MachFlag == None:\n machFlagChosen = \"Select a machine\"\n return [html.Label(machFlagChosen, style={'color':'#fc0313'})]\n gui.machineSelect(MachFlag)\n machFlagChosen = \"Selected \"+MachFlag\n return [html.Label(machFlagChosen, style={'color':'#f5d142'})]\n\n\n@app.callback([Output('hiddenDivInput', 'children'),\n Output('userInputFileData', 'data')],\n [Input('input-upload','filename')],\n [State('input-upload','contents'),\n State('MachFlag','value'),])\ndef inputDragDrop(file, contents, MachFlag):\n \"\"\"\n callback to handle user input file drag and drop\n \"\"\"\n if MachFlag is None:\n print(\"Select a machine before uploading input file\")\n log.info(\"Select a machine before uploading input file\")\n if file is None:\n raise PreventUpdate\n else:\n outputDiv = html.Label(\"Loaded Input File\", style={'color':'#f5d142'})\n newFile = gui.tmpDir + file[0]\n decoded = base64.b64decode(contents[0].split(',')[1])\n #Save user loaded file into tmp directory\n with open(newFile, \"w\") as f:\n f.write(decoded.decode('utf-8'))\n data = gui.loadDefaults(inFile=newFile)\n\n return [outputDiv, data]\n\n@app.callback([Output('hiddenDivSaveInput','children'),\n Output('downloadInputs', 'data')],\n [Input('saveInputs','n_clicks')],\n [State('shot', 'value'),\n State('tmin', 'value'),\n State('tmax', 'value'),\n State('nTrace', 'value'),\n State('ionDir', 'value'),\n State('ROIGridRes', 'value'),\n State('gridRes', 'value'),\n State('lqEich', 'value'),\n State('S', 'value'),\n State('lqCN', 'value'),\n State('lqCF', 'value'),\n State('lqPN', 'value'),\n State('lqPF', 'value'),\n State('fracCN', 'value'),\n State('fracCF', 'value'),\n State('fracPN', 'value'),\n State('fracPF', 'value'),\n State('Psol', 'value'),\n State('fracUI', 'value'),\n State('fracUO', 'value'),\n State('fracLI', 'value'),\n State('fracLO', 'value'),\n State('qBG', 'value'),\n State('OFstartTime', 'value'),\n State('OFstopTime', 'value'),\n State('OFminMeshLev', 'value'),\n State('OFmaxMeshLev', 'value'),\n State('OFSTLscale', 'value'),\n State('OFdeltaT', 'value'),\n State('PVPath', 'value'),\n State('FreeCADPath', 'value'),\n State('dataPath', 'value'),\n State('OFbashrc', 'value')\n ]\n )\ndef saveGUIinputs( n_clicks,\n shot,\n tmin,\n tmax,\n nTrace,\n ionDir,\n ROIGridRes,\n gridRes,\n lqEich,\n S,\n lqCN,\n lqCF,\n lqPN,\n lqPF,\n fracCN,\n fracCF,\n fracPN,\n fracPF,\n Psol,\n fracUI,\n fracUO,\n fracLI,\n fracLO,\n qBG,\n OFstartTime,\n OFstopTime,\n OFminMeshLev,\n OFmaxMeshLev,\n OFSTLscale,\n OFdeltaT,\n PVLoc,\n FreeCADLoc,\n dataLoc,\n OFbashrcLoc\n ):\n \"\"\"\n Saves GUI text boxes into an input file in the HEAT format\n first file is saved to the gui.tmpDir, then to client machine\n \"\"\"\n if n_clicks < 1:\n raise PreventUpdate\n\n data = {}\n data['shot'] = shot\n data['tmin'] = tmin\n data['tmax'] = tmax\n data['nTrace'] = nTrace\n data['ionDir'] = ionDir\n data['ROIGridRes'] = ROIGridRes\n data['gridRes'] = gridRes\n data['lqEich'] = lqEich\n data['S'] = S\n data['lqCN'] = lqCN\n data['lqCF'] = lqCF\n data['lqPN'] = lqPN\n data['lqPF'] = lqPF\n data['fracCN'] = fracCN\n data['fracCF'] = fracCF\n data['fracPN'] = fracPN\n data['fracPF'] = fracPF\n data['Psol'] = Psol\n data['fracUI'] = fracUI\n data['fracUO'] = fracUO\n data['fracLI'] = fracLI\n data['fracLO'] = fracLO\n data['qBG'] = qBG\n data['OFstartTime'] = OFstartTime\n data['OFstopTime'] = OFstopTime\n data['OFminMeshLev'] = OFminMeshLev\n data['OFmaxMeshLev'] = OFmaxMeshLev\n data['OFSTLscale'] = OFSTLscale\n data['OFdeltaT'] = OFdeltaT\n data['FreeCADPath'] = FreeCADLoc\n data['PVPath'] = PVLoc\n data['dataPath'] = dataLoc\n data['OFbashrc'] = OFbashrcLoc\n\n tools.saveInputFile(data, gui.tmpDir, gui.rootDir, gui.dataPath)\n\n outputDiv = html.Label(\"Saved File\", style={'color':'#f5d142'})\n return [outputDiv, send_file(gui.tmpDir + \"HEATinput.csv\")]\n\n\n#==========MHD==========\ndef buildMHDbox():\n \"\"\"\n MHD input parameters\n \"\"\"\n return html.Div(\n id=\"MHDbox\",\n children=[\n html.H6(\"MHD Settings\"),\n html.Label(id=\"shotLabel\", children=\"Shot Number \"),\n dcc.Input(id=\"shot\", className=\"textInput\"),\n html.Label(id=\"tMinLabel\", children=\"Minimum Timestep [ms]\"),\n dcc.Input(id=\"tmin\", className=\"textInput\"),\n html.Label(id=\"tMaxLabel\", children=\"Maximum Timestep [ms]\"),\n dcc.Input(id=\"tmax\", className=\"textInput\"),\n html.Label(id=\"nTraceLabel\", children=\"Number of Trace Steps (degrees)\"),\n dcc.Input(id=\"nTrace\", className=\"textInput\"),\n# html.Label(id=\"ionDirLabel\", children=\"Ion Direction\"),\n# dcc.Input(id=\"ionDir\", className=\"textInput\"),\n# html.Label(id=\"gfileLabel\", children=\"Path to gFile\"),\n# dcc.Input(id=\"gfilePath\", type='text', className=\"textInput\"),\n dcc.Upload(\n className=\"PFCupload\",\n id='gfiletable-upload',\n children=html.Div([\n 'Drag and Drop or ',\n html.A('Select gFiles')\n ]),\n style={\n 'width': '60%', 'height': '60px', 'lineHeight': '60px',\n 'borderWidth': '1px', 'borderStyle': 'dashed',\n 'borderRadius': '5px', 'textAlign': 'center', 'margin': '10px',\n },\n multiple=True,\n ),\n html.Div(id=\"hiddenDivGfileUpload\"),\n html.Br(),\n dcc.RadioItems(\n id=\"plasma3Dmask\",\n options=[\n {'label': '2D Plasmas', 'value': 'plasma2D'},\n {'label': '3D Plasmas', 'value': 'plasma3D'},\n ],\n value='plasma2D'\n ),\n html.Button(\"Load MHD\", id=\"loadMHD\", n_clicks=0, style={'margin':'10px 10px 10px 10px'}),\n html.Br(),\n #save EQ plots as png buttons / forms\n html.Div(\n children=[\n html.Div(\n children=[\n html.Label(\"Width (px)\"),\n dcc.Input(id=\"EQpixelX\", className=\"textInput\"),\n ],\n className=\"colBox\"\n ),\n html.Div(\n children=[\n html.Label(\"Height (px)\"),\n dcc.Input(id=\"EQpixelY\", className=\"textInput\"),\n ],\n className=\"colBox\"\n ),\n html.Button(\"Save EQs to .png\", id=\"saveEQbutton\", n_clicks=0, style={'margin':'30px 10px 10px 10px'}),\n ],\n className=\"rowBox\"\n ),\n Download(id=\"downloadEQplots\"),\n html.Div(id=\"hiddenDivSaveEQ\")\n\n ],\n className=\"box\",\n )\n\n\n#==========MHD Callbacks\n\n@app.callback([Output('timeSlider', 'min'),\n Output('timeSlider', 'max'),\n Output('timeSlider', 'marks'),\n Output('timeSlider', 'value'),\n Output('gFileTable2', 'data')],\n [Input('loadMHD', 'n_clicks')],\n [State('shot', 'value'),\n State('tmin', 'value'),\n State('tmax', 'value'),\n State('nTrace', 'value'),\n #State('ionDir', 'value'),\n #State('gfilePath', 'value'),\n State('gfiletable-upload', 'filename'),\n State('gfiletable-upload', 'contents'),\n State('plasma3Dmask', 'value'),\n State('dataPath', 'value')]\n )\ndef loadMHD(n_clicks,shot,tmin,tmax,nTrace,gFileList,gFileData,plasma3Dmask,dataPath):\n \"\"\"\n Load MHD\n \"\"\"\n try: MachFlag = gui.MachFlag\n except:\n print(\"You didn't select a machine\")\n log.info(\"You didn't select a machine\")\n raise PreventUpdate\n\n\n #if data directory doesn't exist, create it\n try:\n os.mkdir(dataPath)\n except:\n print(\"Did not make new data directory: \"+dataPath)\n log.info(\"Did not make new data directory: \"+dataPath)\n pass\n\n if plasma3Dmask == 'plasma3D': plasma3Dmask=1\n else: plasma3Dmask=0\n\n if (shot is None) and (gFileList is None):\n raise PreventUpdate\n\n if shot is not None: shot = int(shot)\n if tmin is not None: tmin = int(tmin)\n if tmax is not None: tmax = int(tmax)\n if nTrace is not None: nTrace = int(nTrace)\n# if ionDir is not None: ionDir = int(ionDir)\n if gFileList is not None:\n if type(gFileList) is not list:\n gFileList = [gFileList]\n if gFileData is not None:\n if type(gFileData) is not list:\n gFileData = [gFileData]\n\n gui.getMHDInputs(shot=shot,\n tmin=tmin,\n tmax=tmax,\n nTrace=nTrace,\n gFileList=gFileList,\n gFileData=gFileData,\n plasma3Dmask=plasma3Dmask\n )\n\n ts = gui.MHD.timesteps\n tminMHD = ts.min()\n tmaxMHD = ts.max()\n if gFileList is None:\n tAll = np.linspace(int(tmin), int(tmax), (int(tmax)-int(tmin)+1))\n data = [dict([{'filename':'', 'timestep':''}][0])]\n else:\n tAll = ts\n keys=[\"filename\"]\n interpData = pd.DataFrame(gFileList, columns=keys)\n interpData[\"timestep[ms]\"] = \"\"\n data = interpData.to_dict('records')\n #interpData = [dict([{'filename':g, 'timestep':''} for g in gFileList])]\n marks = {}\n for t in ts:\n if t in tAll:\n marks.update({int(t):'{}'.format(t)})\n\n value = ts[0]\n return tminMHD, tmaxMHD, marks, value, data\n\n\n@app.callback([Output('hiddenDivSaveEQ', 'children'),\n Output('downloadEQplots', 'data')],\n [Input('saveEQbutton', 'n_clicks')],\n [State('EQpixelX', 'value'),\n State('EQpixelY', 'value')])\ndef saveEQplots(n_clicks, x, y):\n if n_clicks < 1:\n raise PreventUpdate\n try: MachFlag = gui.MachFlag\n except:\n print(\"You didn't select a machine\")\n raise PreventUpdate\n try: ts = gui.MHD.timesteps\n except:\n print('Please load MHD before saving EQ plots')\n return [html.Label(\"Load MHD First\", style={'color':'#f51b60'})]\n\n #get png resolution\n if x == None or y == None:\n #default PV window size on toms computer,\n #more or less preserving NSTX aspect ratio\n x = 526\n y = 760\n else:\n x = float(x)\n y = float(y)\n\n shot = gui.MHD.shot\n #this import needs to be here (not at top of file) to prevent FreeCAD qt5\n #shared object conflict\n import GUIscripts.plot2DEQ as eqPlot\n allFiles = []\n for t in ts:\n print(\"Saving timestep {:5d}ms to PNG\".format(t))\n log.info(\"Saving timestep {:5d}ms to PNG\".format(t))\n fileName = gui.MHD.tmpDir + 'EQplot_{:05d}.png'.format(t)\n allFiles.append(fileName)\n idx = np.where(t==ts)[0][0]\n ep = gui.MHD.ep[idx]\n #write EQ plot using matplotlib\n plt = eqPlot.EQ2Dplot(ep,shot,t,MachFlag,height=y)\n plt.savefig(fileName, facecolor=\"#1b1f22\")\n\n #Write Equilibrium plot using plotly\n #plot = plotly2DEQ.makePlotlyEQDiv(shot, t, MachFlag, ep)\n #plot.update_layout(\n # title=\"{:05d}ms\".format(t),\n # xaxis_title=\"R [m]\",\n # yaxis_title=\"Z [m]\",\n # autosize=True,\n # paper_bgcolor='#1b1f22',\n # plot_bgcolor='#1b1f22',\n # showlegend=False,\n # font=dict(\n # # family=\"Courier New\",\n # size=22,\n # color=\"#dcdce3\"\n # )\n # )\n #plot.write_image(fileName, width=x, height=y)\n\n #now zip all these plots into a single file that the user may\n #download from GUI\n from zipfile import ZipFile\n from os.path import basename\n zipFile = gui.tmpDir + 'EQplots.zip'\n zipObj = ZipFile(zipFile, 'w')\n for f in allFiles:\n zipObj.write(f, basename(f))\n zipObj.close()\n\n\n return [html.Label(\"Saved EQs to file\", style={'color':'#f5d142'}),\n send_file(zipFile)]\n\n#Load CAD button connect\n@app.callback([Output('hiddenDivGfileUpload', 'children')],\n [Input('gfiletable-upload', 'filename')],\n [State('MachFlag', 'value')])\ndef gfileUpload(gFile, MachFlag):\n if MachFlag is None:\n raise PreventUpdate\n else:\n return [html.Label(\"Loaded gFile: \"+gFile[0], style={'color':'#f5d142'})]\n\n#==========CAD==========\ndef buildCADbox():\n \"\"\"\n CAD input parameters\n \"\"\"\n return html.Div(\n id=\"CADbox\",\n draggable='yes',\n children=[\n html.H6(\"CAD Settings\"),\n html.Label(id=\"ROIgridResLabel\", children=\"Heat Flux Resolution [mm] \"),\n dcc.Input(id=\"ROIGridRes\", className=\"textInput\"),\n html.Label(id=\"gridResLabel\", children=\"Intersect Resolution [mm]\"),\n dcc.Input(id=\"gridRes\", className=\"textInput\"),\n html.Button(\"Load Res Settings\", id=\"loadRes\", style={'margin':'10px 10px 10px 10px'}),\n html.Div(id=\"hiddenDivCAD1\"),\n html.Label(id=\"STPdropLabel\", children=\"STP File Direct Upload:\"),\n dcc.Upload(\n className=\"PFCupload\",\n id='CAD-upload',\n children=html.Div([\n 'Drag and Drop or ',\n html.A('Select STP file')\n ]),\n style={\n 'width': '60%', 'height': '60px', 'lineHeight': '60px',\n 'borderWidth': '1px', 'borderStyle': 'dashed',\n 'borderRadius': '5px', 'textAlign': 'center', 'margin': '10px',\n },\n multiple=True,\n ),\n html.Div(id=\"hiddenDivCAD2\"),\n ],\n className=\"box\",\n )\n\n#Load res button connect\n@app.callback([Output('hiddenDivCAD1', 'children')],\n [Input('loadRes', 'n_clicks')],\n [State('ROIGridRes', 'value'),\n State('gridRes', 'value'),\n State('MachFlag', 'value')])\ndef loadRes(n_clicks, ROIGridRes, gridRes, MachFlag):\n if n_clicks is None:\n raise PreventUpdate\n if MachFlag is None:\n return [html.Label(\"Select a machine\", style={'color':'#fc0313'})]\n gui.getCADResInputs(ROIGridRes,gridRes)\n return [html.Label(\"Loaded Resolution Settings\", style={'color':'#f5d142'})]\n\n#Load CAD button connect\n@app.callback([Output('hiddenDivCAD2', 'children')],\n [Input('CAD-upload', 'filename')],\n [State('CAD-upload', 'contents'),\n State('MachFlag', 'value')])\ndef loadCAD(STPfile, STPcontents, MachFlag):\n if MachFlag is None:\n return [html.Label(\"Select a machine first\", style={'color':'#fc0313'})]\n else:\n contents = STPcontents[0]\n content_type, content_string = contents.split(',')\n STPdata= base64.b64decode(content_string)\n gui.getCAD(STPfile=STPfile[0],STPdata=STPdata)\n return [html.Label(\"Loaded CAD: \"+STPfile[0], style={'color':'#f5d142'})]\n\n#==========HF==========\ndef buildHFbox():\n \"\"\"\n Heat Flux input parameters\n \"\"\"\n return html.Div(\n id=\"HFbox\",\n children=[\n html.H6(\"HF Settings\"),\n html.Label(id=\"hfModeLabel\", children=\"Select a Heat Flux Profile\"),\n dcc.Dropdown(\n id='hfMode',\n className=\"hfSelect\",\n style={'backgroundColor': 'transparent', 'color':'transparent'},\n #style=dropdown_style,\n options=[\n {'label': 'Gaussian Spreading', 'value': 'eich'},\n {'label': 'Multi-Exponential', 'value': 'multiExp'},\n {'label': 'Limiter', 'value': 'limiter'}\n ],\n ),\n html.Div(id='hfParameters',\n children=[\n loadHFSettings(mode=None,hidden=True),\n ],\n ),\n html.Label(\"Long Range Intersection Checking?\"),\n dcc.RadioItems(\n id=\"LRmask\",\n options=[\n {'label': 'Yes', 'value': 'yes'},\n {'label': 'No', 'value': 'no'},\n ],\n value='no'\n ),\n\n html.Div(id=\"LRthreshDiv\",\n children=[ loadLRsettings(mask='no', hidden=True), ]\n ),\n html.Br(),\n html.Button(\"Load HF\", id=\"loadHF\", style={'margin':'10px 10px 10px 10px'}),\n html.Div(id=\"hiddenDivHF\"),\n\n ],\n className=\"HFbox\",\n )\n\n\n#Heat Flux Callbacks and Conditionals\n@app.callback(Output('LRthreshDiv', 'children'),\n [Input('LRmask', 'value')])\ndef LRselector(mask):\n return [ loadLRsettings(mask, hidden=False) ]\n\n\ndef loadLRsettings(mask, hidden=False):\n if hidden==True or mask=='no':\n style={\"display\":\"none\"}\n else:\n style={}\n return html.Div(\n children=\n [\n html.Label(\"Long Range Checking Power Threshold [MW]\", style=style),\n dcc.Input(id=\"LRthresh\", className=\"textInput\", style=style),\n ],\n )\n\n@app.callback([Output('hfParameters', 'children')],\n [Input('hfMode', 'value')])\ndef hfParameters(mode):\n div = [loadHFSettings(mode=mode, hidden=False)]\n return [div]\n\ndef PsolInput(hidden=False):\n #do this hidden business so that we can always load defaults into these id's\n if hidden==True:\n className=\"hiddenBox\"\n else:\n className=\"hfInput\"\n\n\n row2 = html.Div(\n children=[\n html.Div(\n children=[\n html.Label(\"Upper Inner Power Fraction\", className=\"hfLabel\"),\n dcc.Input(id=\"fracUI\", className=\"hfInput2\"),\n ],\n className=\"colBox\"\n ),\n html.Div(\n children=[\n html.Label(\"Upper Outer Power Fraction\", className=\"hfLabel\"),\n dcc.Input(id=\"fracUO\", className=\"hfInput2\"),\n ],\n className=\"colBox\"\n ),\n ],\n className=\"rowBox\",\n )\n\n row3 = html.Div(\n children=[\n html.Div(\n children=[\n html.Label(\"Lower Inner Power Fraction\", className=\"hfLabel\"),\n dcc.Input(id=\"fracLI\", className=\"hfInput2\"),\n ],\n className=\"colBox\"\n ),\n html.Div(\n children=[\n html.Label(\"Lower Outer Power Fraction\", className=\"hfLabel\"),\n dcc.Input(id=\"fracLO\", className=\"hfInput2\"),\n ],\n className=\"colBox\"\n ),\n ],\n className=\"rowBox\",\n )\n\n\n return html.Div(\n className=className,\n children=[\n html.Label(\"Power Crossing Separatrix [MW]\"),\n dcc.Input(id=\"Psol\", className=\"textInput\"),\n row2,\n row3\n ],\n )\n\ndef loadHFSettings(mode=None, hidden=False):\n #do this hidden business so that we can always load defaults into these id's\n #hideMask corresponds to the following parameters:\n #[eichProfile, commonRegion, privateRegion]\n hideMask = ['hiddenBox','hiddenBox','hiddenBox']\n if mode=='eich':\n hideMask = ['hfInput','hiddenBox','hiddenBox']\n elif mode=='limiter':\n hideMask = ['hiddenBox','hiddenBox','hfInput'] #common flux region\n elif mode=='multiExp':\n hideMask = ['hiddenBox','hfInput','hiddenBox'] #common + private flux region\n if hidden==True or mode==None:\n hideMask=['hiddenBox','hiddenBox','hiddenBox']\n\n return html.Div(\n children=[\n #gaussian spreading / eich\n html.Div(\n #className=hideMask[0],\n children=[\n eichParameters(hideMask[0]),\n ]\n ),\n #multiple exponentials\n html.Div(\n #className=hideMask[1],\n children=[\n multiExpParameters(hideMask[1]),\n ]\n ),\n #limiters\n html.Div(\n #className=hideMask[2],\n children=[\n limiterParameters(hideMask[2]),\n ]\n ),\n PsolInput(hidden),\n ],\n )\n\n\ndef eichParameters(className):\n row1 = html.Div(\n className='rowBox',\n children=[\n html.Div(\n className=\"colBox\",\n children=[\n html.Label(\"Select Heat Flux Width source:\", className=\"hfLabel\"),\n dcc.Dropdown(\n id='eichlqCNMode',\n className=\"SelectorBoxInput\",\n style={'backgroundColor': 'transparent', 'color':'transparent'},\n options=[\n {'label': 'From Eich Scaling', 'value': 'eich'},\n {'label': 'User Defined', 'value': 'user'}\n ],\n value=None,\n ),\n ],\n ),\n html.Div(\n className=\"colBox\",\n children=[\n html.Label(\"Select Gaussian Spreading source:\", className=\"hfLabel\"),\n dcc.Dropdown(\n id='eichSMode',\n className=\"SelectorBoxInput\",\n style={'backgroundColor': 'transparent', 'color':'transparent'},\n #style=dropdown_style,\n options=[\n {'label': 'From Makowski Scaling', 'value': 'makowski'},\n {'label': 'User Defined', 'value': 'user'}\n ],\n value=None,\n ),\n ],\n ),\n ])\n\n row2 = html.Div(\n className='rowBox',\n children=[\n html.Div(\n className=\"colBox\",\n children=[\n html.Label(\"User Defined Heat Flux Width [mm]:\", className=\"hfLabel\"),\n dcc.Input(id=\"lqEich\", className=\"hfInput2\"),\n\n ],\n ),\n html.Div(\n className=\"colBox\",\n children=[\n html.Label(\"User Defined Gaussian Spreading [mm]:\", className=\"hfLabel\"),\n dcc.Input(id=\"S\", className=\"hfInput2\"),\n ],\n ),\n ])\n\n row3 = html.Div(\n className=\"rowBox\",\n children=[\n html.Div(\n className=\"colBox\",\n children=[\n html.Label(\"Background Heat Flux [MW/m^2]\", className=\"hfLabel\"),\n dcc.Input(id=\"qBG\", className=\"hfInput2\"),\n ]),\n html.Div(\n className=\"colBox\",\n children=[\n html.Label(\"Greenwald Density Fraction\", className=\"hfLabel\"),\n dcc.Input(id=\"fG\", className=\"hfInput2\", value=0.6),\n ]),\n ])\n\n\n div = html.Div(\n className=className,\n children=[\n row1,\n row2,\n row3\n ]\n )\n\n return div\n\n\ndef multiExpParameters(className):\n row1 = html.Div(\n className=\"rowBox\",\n children = [\n html.Div(\n className=\"colBox\",\n children=[\n html.Label(\"Select Common Near Heat Flux Width source:\"),\n dcc.Dropdown(\n id='multiExplqCNMode',\n className=\"SelectorBoxInput\",\n style={'backgroundColor': 'transparent', 'color':'transparent'},\n options=[\n #{'label': 'From Brunner Scaling', 'value': 'brunner'},\n {'label': 'User Defined', 'value': 'user'}\n ],\n value=None,\n )\n ]),\n ]\n )\n row2 = html.Div(\n className=\"rowBox\",\n children=[\n html.Div(\n className=\"colBox\",\n children=[\n html.Label(\"Common Near Heat Flux Width [mm]\"),\n dcc.Input(id=\"lqCN\", className=\"hfInput2\"),\n ]),\n html.Div(\n className=\"colBox\",\n children=[\n html.Label(\"Common Near Power Fraction\"),\n dcc.Input(id=\"fracCN\", className=\"hfInput2\"),\n ]),\n ])\n\n row3 = html.Div(\n className=\"rowBox\",\n children=[\n html.Div(\n className=\"colBox\",\n children=[\n html.Label(\"Common Far Heat Flux Width [mm]\"),\n dcc.Input(id=\"lqCF\", className=\"hfInput2\"),\n ]),\n html.Div(\n className=\"colBox\",\n children=[\n html.Label(\"Common Far Power Fraction\"),\n dcc.Input(id=\"fracCF\", className=\"hfInput2\"),\n ]),\n ])\n\n row4 = html.Div(\n className=\"rowBox\",\n children=[\n html.Div(\n className=\"colBox\",\n children=[\n html.Label(\"Private Near Heat Flux Width [mm]\"),\n dcc.Input(id=\"lqPN\", className=\"hfInput2\"),\n ]),\n html.Div(\n className=\"colBox\",\n children=[\n html.Label(\"Private Near Power Fraction\"),\n dcc.Input(id=\"fracPN\", className=\"hfInput2\"),\n ]),\n ])\n\n row5 = html.Div(\n className=\"rowBox\",\n children=[\n html.Div(\n className=\"colBox\",\n children=[\n html.Label(\"Private Far Heat Flux Width [mm]\"),\n dcc.Input(id=\"lqPF\", className=\"hfInput2\"),\n ]),\n html.Div(\n className=\"colBox\",\n children=[\n html.Label(\"Private Far Power Fraction\"),\n dcc.Input(id=\"fracPF\", className=\"hfInput2\"),\n ]),\n ])\n\n\n\n div = html.Div(\n className=className,\n children=[\n #row1, #commented for now because only user defined is allowed (no regression)\n row2,\n row3,\n row4,\n row5\n ]\n )\n\n return div\n\n\ndef limiterParameters(className):\n #return if this div is supposed to be hidden to prevent duplicate IDs\n #if className== 'hiddenBox':\n # return\n\n row1 = html.Div(\n className=\"rowBox\",\n children = [\n html.Div(\n className=\"colBox\",\n children=[\n html.Label(\"Select Common Near Heat Flux Width source:\"),\n dcc.Dropdown(\n id='limiterlqCNMode',\n className=\"SelectorBoxInput\",\n style={'backgroundColor': 'transparent', 'color':'transparent'},\n options=[\n {'label': 'From Eich Scaling', 'value': 'eich'},\n {'label': 'User Defined', 'value': 'user'}\n ],\n value=None,\n )\n ]),\n html.Div(\n className=\"colBox\",\n children=[\n html.Label(\"Select Common Far Heat Flux Width source:\"),\n dcc.Dropdown(\n id='limiterlqCFMode',\n className=\"SelectorBoxInput\",\n style={'backgroundColor': 'transparent', 'color':'transparent'},\n options=[\n #{'label': 'From Horaceck Scaling', 'value': 'horaceck'},\n {'label': 'User Defined', 'value': 'user'}\n ],\n value=None,\n )\n ]),\n\n ]\n )\n\n row2 = html.Div(\n className=\"rowBox\",\n children=[\n html.Div(\n className=\"colBox\",\n children=[\n html.Label(\"Common Near Heat Flux Width [mm]\"),\n dcc.Input(id=\"limlqCN\", className=\"hfInput2\"),\n ]),\n html.Div(\n className=\"colBox\",\n children=[\n html.Label(\"Common Far Heat Flux Width [mm]\"),\n dcc.Input(id=\"limlqCF\", className=\"hfInput2\"),\n ]),\n ])\n\n row3 = html.Div(\n className=\"rowBox\",\n children=[\n html.Div(\n className=\"colBox\",\n children=[\n html.Label(\"Common Near Power Fraction\"),\n dcc.Input(id=\"limfracCN\", className=\"hfInput2\"),\n ]),\n\n html.Div(\n className=\"colBox\",\n children=[\n html.Label(\"Common Far Power Fraction\"),\n dcc.Input(id=\"limfracCF\", className=\"hfInput2\"),\n ]),\n ])\n\n div = html.Div(\n className=className,\n children=[\n row1,\n row2,\n row3\n ]\n )\n return div\n\n\n\n\n\n\ndef commonRegionParameters():\n \"\"\"\n near and far heat flux widths and power sharing fractions\n \"\"\"\n row1 = html.Div(\n className=\"rowBox\",\n children=[\n html.Div(\n className=\"colBox\",\n children=[\n html.Label(\"Common Near Heat Flux Width [mm]\"),\n dcc.Input(id=\"lqCN\", className=\"hfInput2\"),\n ]),\n html.Div(\n className=\"colBox\",\n children=[\n html.Label(\"Common Near Power Fraction\"),\n dcc.Input(id=\"fracCN\", className=\"hfInput2\"),\n ]),\n ])\n\n row2 = html.Div(\n className=\"rowBox\",\n children=[\n html.Div(\n className=\"colBox\",\n children=[\n html.Label(\"Common Far Heat Flux Width [mm]\"),\n dcc.Input(id=\"lqCF\", className=\"hfInput2\"),\n ]),\n html.Div(\n className=\"colBox\",\n children=[\n html.Label(\"Common Far Power Fraction\"),\n dcc.Input(id=\"fracCF\", className=\"hfInput2\"),\n ]),\n ])\n\n return row1,row2\n\n\n#Load HF button connect\n@app.callback([Output('hiddenDivHF', 'children'),\n Output('hfTable', 'data')],\n [Input('loadHF', 'n_clicks')],\n [State('hfMode', 'value'),\n State('lqEich', 'value'),\n State('S', 'value'),\n State('qBG', 'value'),\n State('lqCN', 'value'),\n State('lqCF', 'value'),\n State('lqPN', 'value'),\n State('lqPF', 'value'),\n State('fracCN', 'value'),\n State('fracCF', 'value'),\n State('fracPN', 'value'),\n State('fracPF', 'value'),\n State('Psol', 'value'),\n State('fracUI', 'value'),\n State('fracUO', 'value'),\n State('fracLI', 'value'),\n State('fracLO', 'value'),\n State('LRmask', 'value'),\n State('LRthresh', 'value'),\n State('MachFlag', 'value'),\n State('eichlqCNMode', 'value'),\n #State('multiExplqCNMode', 'value'),\n State('limiterlqCNMode', 'value'),\n State('limiterlqCFMode', 'value'),\n State('eichSMode', 'value'),\n State('fG', 'value'),\n State('limlqCN', 'value'),\n State('limlqCF', 'value'),\n State('limfracCN', 'value'),\n State('limfracCF', 'value'),\n ])\ndef loadHF(n_clicks,hfMode,lqEich,S,qBG,lqCN,lqCF,lqPN,lqPF,\n fracCN,fracCF,fracPN,fracPF,\n Psol,fracUI,fracUO,fracLI,fracLO,\n LRmask,LRthresh,MachFlag,\n eichlqCNMode,limiterlqCNMode,limiterlqCFMode,SMode,fG,\n limlqCN,limlqCF,limfracCN,limfracCF):\n if MachFlag is None:\n raise PreventUpdate\n else:\n #set up the heat flux configuration (which scalings to use)\n if hfMode == 'limiter':\n lqCNmode = limiterlqCNMode\n lqCFmode = limiterlqCFMode\n lqCN = limlqCN\n lqCF = limlqCF\n fracCN = limfracCN\n fracCF = limfracCF\n elif hfMode == 'multiExp':\n #add this back in after brunner scaling is in HEAT:\n # lqCNmode = multiExplqCNMode\n lqCNmode = 'user'\n lqCFmode = 'user'\n lqPNmode = 'user'\n lqPFmode = 'user'\n else: #eich mode is default\n lqCNmode = eichlqCNMode\n lqCFmode = None\n SMode = SMode\n #could add private flux scalings here if they ever exist\n\n #set up HF object in HEAT\n gui.getHFInputs(lqEich,S,Psol,qBG,lqPN,lqPF,lqCN,lqCF,\n fracPN,fracPF,fracCN,fracCF,\n fracUI,fracUO,fracLI,fracLO,\n hfMode,LRmask,LRthresh,\n lqCNmode,lqCFmode,SMode,fG)\n\n #Update output tab table\n dataDict = gui.HF.HFdataDict\n hfDict = [{'Parameter':i, 'Value':dataDict[i]} for i in dataDict]\n\n return [html.Label(\"Loaded HF Settings\", style={'color':'#f5d142'}), hfDict]\n\n\n\n\n\n#==========PFC==========\ndef buildPFCbox():\n return html.Div(\n id=\"PFCbox\",\n children=[\n html.H6(\"PFC Settings\"),\n html.Div(id=\"pfcUploadDiv\"),\n dcc.Upload(\n className=\"PFCupload\",\n id='pfctable-upload',\n children=html.Div([\n 'Drag and Drop or ',\n html.A('Select Files')\n ]),\n style={\n 'width': '60%', 'height': '60px', 'lineHeight': '60px',\n 'borderWidth': '1px', 'borderStyle': 'dashed',\n 'borderRadius': '5px', 'textAlign': 'center', 'margin': '10px',\n },\n ),\n html.Div(children=loadPFCtable(), className=\"PFCtable\"),\n html.Br(),\n html.Button(\"Load PFC Settings\", id=\"loadPFC\", n_clicks=0, style={'margin':'0 10px 10px 0'}),\n# html.Button('Add Row', id='add-rows-button', n_clicks=0, style={'margin':'0 10px 10px 0'}),\n html.Button(\"Download Default PFC file\", id=\"downloadPFCbtn\", n_clicks=0, style={'margin':'0 10px 10px 0'}),\n Download(id=\"downloadPFC\"),\n html.Div(id=\"hiddenDivDownloadPFC\", style={\"display\": \"none\"}),\n html.Div(id=\"hiddenDivPFC\", style={\"display\": \"none\"}),\n dcc.Input(id=\"hiddenDivPFC2\", style={\"display\": \"none\"}),\n html.Div(id=\"hiddenDivPFC3\")\n\n ],\n className=\"PFCbox\",\n )\n\ndef loadPFCtable():\n params = ['timesteps','PFCname','MapDirection','DivCode','intersectName']\n cols = [{'id': p, 'name': p} for p in params]\n data = [{}]\n return dash_table.DataTable(\n id='pfcTable',\n columns = cols,\n data = data,\n style_header={'backgroundColor': 'rgb(30, 30, 30)'},\n style_cell={\n 'textAlign': 'left',\n 'backgroundColor': 'rgb(50, 50, 50)',\n 'color': 'white'\n },\n editable=True,\n export_format='csv',\n row_deletable=True,\n )\n\n#upload file area\ndef parse_contents(contents, filename):\n content_type, content_string = contents.split(',')\n decoded = base64.b64decode(content_string)\n if 'csv' in filename:\n # Assume that the user uploaded a CSV file\n return pd.read_csv(io.StringIO(decoded.decode('utf-8')), comment='#')\n elif 'xls' in filename:\n # Assume that the user uploaded an excel file\n return pd.read_excel(io.BytesIO(decoded))\n\n\n#Uploading files and button presses update table and HTML storage object\n@app.callback([Output('PFCdataStorage', 'data'),\n Output('pfcTable', 'data'),\n Output('pfcTable', 'columns'),\n Output('hiddenDivPFC3', 'children')],\n [Input('loadPFC', 'n_clicks'),\n Input('pfctable-upload', 'filename')],\n [State('PFCdataStorage', 'data'),\n State('PFCdataStorage', 'modified_timestamp'),\n State('pfctable-upload', 'contents'),\n State('pfcTable', 'data'),\n State('pfcTable', 'columns'),\n State('MachFlag', 'value')])\ndef PFCtable(n_clicks, filename, dataStore, ts, uploadContents,\n tableData, tableColumns, MachFlag):\n if dataStore==None:\n print('Initializing HTML PFC data storage object')\n dataStore = {}\n dataStore.update({'PFC_n_clicks':0})\n dataStore.update({'PFCfilename':''})\n\n #user has to load MHD and CAD for a specific machine before PFCs\n if MachFlag == None:\n hiddenDiv = [html.Label(\"Select a Tokamak and Load MHD/CAD First\", style={'color':'#db362a'})]\n\n #Button Clicks\n elif n_clicks > 0 and n_clicks>dataStore.get('PFC_n_clicks'):\n dataStore['PFC_n_clicks'] = n_clicks\n #read default machine PFC file\n if (tableData == [{}]) and (uploadContents is None):\n gui.getPFCinputs(defaultMask=True)\n tableData = gui.timestepMap.to_dict('records')\n tableColumns = [{\"name\": i, \"id\": i} for i in gui.timestepMap.columns]\n #load PFC data from page and send it to HEAT\n else:\n gui.getPFCdataFromGUI(tableData)\n gui.getPFCinputs(defaultMask=False)\n\n hiddenDiv = [html.Label(\"Loaded PFC Data into HEAT\", style={'color':'#f5d142'})]\n\n #file dropper\n elif filename != dataStore['PFCfilename']:\n df = parse_contents(uploadContents, filename)\n tableData = df.to_dict('records')\n tableColumns = [{\"name\": i, \"id\": i} for i in df.columns]\n hiddenDiv = [html.Label(\"Loaded file: \"+filename, style={'color':'#34b3ed'})]\n else:\n hiddenDiv = []\n\n\n return dataStore, tableData, tableColumns, hiddenDiv\n\n#Download PFC Default file button connect\n@app.callback([Output('downloadPFC', 'data'),\n Output('hiddenDivDownloadPFC', 'children')],\n [Input('downloadPFCbtn', 'n_clicks')])\ndef downloadPFCfile(n_clicks):\n if n_clicks < 1:\n raise PreventUpdate\n gui.savePFCfile()\n return [send_file(gui.tmpDir + \"PFCinput.csv\"),\n html.Label(\"Saved PFC Default File\", style={'color':'#f5d142'})]\n\n\n\n\n\n#==========openFOAM==========\ndef buildOFbox():\n return html.Div(\n id=\"OFbox\",\n children=[\n html.H6(\"openFOAM Settings\"),\n OFinputBoxes(),\n html.Br(),\n html.Button(\"Load OF Settings\", id=\"loadOF\", n_clicks=0, style={'margin':'0 10px 10px 0'}),\n html.Div(id=\"hiddenDivOF\")\n ],\n className=\"HFbox\",\n )\n\ndef OFinputBoxes():\n return html.Div(\n children=[\n html.Div(\n children=[\n html.Label(\"Start Time [ms]\"),\n dcc.Input(id=\"OFstartTime\", className=\"textInput\"),\n ],\n className=\"OFInput\",\n ),\n html.Div(\n children=[\n html.Label(\"Stop Time [ms]\"),\n dcc.Input(id=\"OFstopTime\", className=\"textInput\"),\n ],\n className=\"OFInput\"\n ),\n html.Div(\n children=[\n html.Label(\"Minimum Resh Refinement Level\"),\n dcc.Input(id=\"OFminMeshLev\", className=\"textInput\"),\n ],\n className=\"OFInput\",\n ),\n html.Div(\n children=[\n html.Label(\"Maximum Resh Refinement Level\"),\n dcc.Input(id=\"OFmaxMeshLev\", className=\"textInput\"),\n ],\n className=\"OFInput\",\n ),\n html.Div(\n children=[\n html.Label(\"STL scaling\"),\n dcc.Input(id=\"OFSTLscale\", className=\"textInput\"),\n ],\n className=\"OFInput\",\n ),\n html.Div(\n children=[\n html.Label(\"deltaT [s]\"),\n dcc.Input(id=\"OFdeltaT\", className=\"textInput\"),\n ],\n className=\"OFInput\",\n ),\n ],\n className=\"wideBoxNoColor\",\n )\n\n#Load OF button connect\n@app.callback([Output('hiddenDivOF', 'children')],\n [Input('loadOF', 'n_clicks')],\n [State('OFstartTime', 'value'),\n State('OFstopTime', 'value'),\n State('OFminMeshLev', 'value'),\n State('OFmaxMeshLev', 'value'),\n State('OFSTLscale', 'value'),\n State('OFdeltaT', 'value'),\n State('OFbashrc', 'value')\n ])\ndef loadOF(n_clicks,OFstartTime,OFstopTime,\n OFminMeshLev,OFmaxMeshLev,OFSTLscale,OFdeltaT,OFbashrcLoc):\n \"\"\"\n sets up openFOAM for an analysis\n \"\"\"\n if n_clicks == 0:\n raise PreventUpdate\n gui.loadOF(OFstartTime,OFstopTime,\n OFminMeshLev,OFmaxMeshLev,\n OFSTLscale,OFbashrcLoc,OFdeltaT)\n return [html.Label(\"Loaded OF Data into HEAT\", style={'color':'#f5d142'})]\n\n\n\"\"\"\n==============================================================================\nTab Contents: run tab\n\"\"\"\ndef buildRunTab():\n return html.Div(\n id=\"runTab\",\n children=[runChildren()],\n className=\"runContentBox\",\n )\n\ndef runChildren():\n return html.Div(\n children = [\n html.H4(\"HEAT Run Settings\", className=\"buttonRibbon\"),\n html.Br(),\n html.H6(\"Point Clouds at Tile Surface:\"),\n runTabChecklist(),\n html.H6(\"Traces from Points:\"),\n runTabTraces(),\n html.Button(\"Run HEAT\", id=\"runHEAT\", n_clicks=0, style={'margin':'0 10px 10px 0'}),\n html.Div(id=\"hiddenDivRun\")\n ],\n className=\"wideBoxDark\",\n )\n\n\ndef runTabChecklist():\n return html.Div(\n id=\"runTabChecklist\",\n children=[\n dcc.Checklist(\n options=[\n {'label': 'B-field point cloud ', 'value': 'Bpc'},\n {'label': 'Normal vector point cloud', 'value': 'NormPC'},\n {'label': 'ShadowMask point cloud', 'value': 'shadowPC'},\n {'label': 'psiN point cloud', 'value': 'psiPC'},\n {'label': 'bdotn point cloud', 'value': 'bdotnPC'},\n {'label': 'Heat flux point cloud', 'value': 'HFpc'},\n {'label': 'openFOAM thermal analysis', 'value': 'OFpc'}\n ],\n value=['HFpc'],\n id='checklistPC',\n ),\n ],\n className=\"PCbox\",\n )\ndef runTabTraces():\n return html.Div(\n id=\"runTabTraces\",\n children=[\n dcc.Checklist(\n options=[{'label': 'B-field Trace ', 'value': 'Btrace'}],\n value=[''],\n id=\"Btrace\",\n ),\n html.Div(id=\"bFieldTracePoints\", children=[loadBfieldTrace(hidden=True)]),\n dcc.Checklist(\n options=[{'label': 'OpenFOAM Temp Probe ', 'value': 'OFtrace'}],\n value=[''],\n id=\"OFtrace\",\n ),\n html.Div(id=\"OFTracePoints\", children=[loadOFTrace(hidden=True)]),\n\n ],\n className=\"PCbox\",\n )\n\n@app.callback(Output('bFieldTracePoints', 'children'),\n [Input('Btrace', 'value')],)\ndef bfieldTracePoint(value):\n return [loadBfieldTrace(Btrace=value)]\n\n#this function enables the inputs to be rendered on page load but hidden\ndef loadBfieldTrace(Btrace=None, hidden=False):\n if (Btrace == 'Btrace') or (hidden == True):\n style={}\n else:\n style={\"display\":\"hidden\"}\n return html.Div(\n children=[\n html.Div(\n children=[\n html.Label(\"x [mm]\"),\n dcc.Input(id=\"xBtrace\", className=\"xyzBoxInput\"),\n html.Label(\"y [mm]\"),\n dcc.Input(id=\"yBtrace\", className=\"xyzBoxInput\"),\n html.Label(\"z [mm]\"),\n dcc.Input(id=\"zBtrace\", className=\"xyzBoxInput\"),\n ],\n className=\"xyzBox\"\n ),\n html.Div(\n children=[\n html.Label(\"ionDirection\"),\n dcc.Input(id=\"ionDir\", className=\"xyzBoxInput\"),\n html.Label(\"Degrees\"),\n dcc.Input(id=\"traceDeg\", className=\"xyzBoxInput\"),\n ],\n className=\"xyzBox\"\n )\n ],\n style=style,\n className=\"xyzBoxVert\",\n )\n\n@app.callback(Output('OFTracePoints', 'children'),\n [Input('OFtrace', 'value')])\ndef OFTracePoint(value):\n return [loadOFTrace(OFtrace=value)]\n\n#this function enables the inputs to be rendered on page load but hidden\ndef loadOFTrace(OFtrace=None, hidden=False):\n if (OFtrace == 'OFtrace') or (hidden == True):\n style={}\n else:\n style={\"display\":\"hidden\"}\n return html.Div(\n children=[\n html.Label(\"x [mm]\"),\n dcc.Input(id=\"xOFtrace\", className=\"xyzBoxInput\"),\n html.Label(\"y [mm]\"),\n dcc.Input(id=\"yOFtrace\", className=\"xyzBoxInput\"),\n html.Label(\"z [mm]\"),\n dcc.Input(id=\"zOFtrace\", className=\"xyzBoxInput\"),\n #html.Label(\"t [ms]\"),\n #dcc.Input(id=\"tOFtrace\", className=\"xyzBoxInput\"),\n ],\n style=style,\n className=\"xyzBox\",\n )\n\n\n@app.callback([Output('hiddenDivRun', 'children'),\n Output('qDivDist', 'children'),\n Output('OFmaxTplot', 'children'),\n Output('OFTprobePlot', 'children')],\n [Input('runHEAT', 'n_clicks')],\n [State('checklistPC','value'),\n State('Btrace','value'),\n State('OFtrace','value'),\n State('xBtrace','value'),\n State('yBtrace','value'),\n State('zBtrace','value'),\n State('xOFtrace','value'),\n State('yOFtrace','value'),\n State('zOFtrace','value'),\n State('timeSlider', 'value'),\n State('ionDir', 'value'),\n State('traceDeg', 'value')\n ])\ndef runHEAT(n_clicks,runList,Btrace,OFtrace,\n xBtrace,yBtrace,zBtrace,\n xOFtrace,yOFtrace,zOFtrace,t,ionDir,traceDeg):\n if n_clicks == 0:\n raise PreventUpdate\n\n if 'Btrace' in Btrace:\n gui.Btrace(xBtrace,yBtrace,zBtrace,t,ionDir,traceDeg)\n\n gui.runHEAT(runList)\n\n if 'HFpc' in runList:\n #load HF distribution plots on output page\n qDistFig = hfDistPlots(update=True)\n else:\n qDistFig = hfDistPlots(update=False)\n\n if 'OFpc' in runList:\n gui.runOpenFOAM()\n OFminmaxFig = OFmaxTPlots(update=True)\n else:\n OFminmaxFig = OFmaxTPlots(update=False)\n\n if 'OFtrace' in OFtrace:\n OFTprobeFig = OFTprobePlots(update=True,x=xOFtrace,y=yOFtrace,z=zOFtrace)\n #do these again here so that the plots on output tab dont go blank\n #if the HFpc and OFpc boxes arent checked\n OFminmaxFig = OFmaxTPlots(update=True)\n qDistFig = hfDistPlots(update=True)\n else:\n OFTprobeFig = OFTprobePlots(update=False)\n\n return ([html.Label(\"HEAT Run Complete\", style={'color':'#f5d142'})],\n qDistFig,\n OFminmaxFig,\n OFTprobeFig)\n\n\n\n\"\"\"\n==============================================================================\nTab Contents: gfile cleaner tab\n\"\"\"\ndef buildGfileCleanerTab():\n return html.Div(\n id=\"gfileCleanerTab\",\n children=[gfileChildren()],\n className=\"runContentBox\",\n )\n\ndef gfileChildren():\n return html.Div(\n children = [\n html.H4(\"gFile Tools\", style={\"text-align\":\"center\", \"width\":\"100%\"}),\n html.H6(\"Loaded gFile Parameters:\"),\n html.Div( children=buildGfileTable(), className=\"gfileTable\" ),\n html.Div( children=buildGfilePlots(), className=\"gfileTable\" ),\n html.H6(\"gFile Multipliers:\"),\n gFileMultipiers(),\n html.H6(\"Re-define LCFS:\"),\n gFileNewSep(),\n html.H6(\"Save New gFile:\"),\n saveNewGfile(),\n html.H6(\"Interpolate gFile:\"),\n interpolateGfile(),\n ],\n className=\"wideBoxDark\",\n )\n\ndef buildGfilePlots():\n \"\"\"\n gFile plot for Fpol, psi, etc\n \"\"\"\n return html.Div(\n id=\"gFilePlots\",\n children=[dcc.Graph(id=\"gFilePlot1\", className=\"\"),],\n className=\"gfileBox\"\n )\n\ndef buildGfileTable():\n cols = getGfileColumns()\n data = [{}]\n return dash_table.DataTable(\n id='gFileTable',\n columns = cols,\n data = data,\n style_header={'backgroundColor': 'rgb(30, 30, 30)'},\n style_cell={\n 'textAlign': 'left',\n 'backgroundColor': 'rgb(50, 50, 50)',\n 'color': 'white'\n },\n editable=False,\n row_deletable=False,\n )\n\n\n#generic row data\ndef getGfileColumns():\n params = ['Parameter','Value']\n return [{'id': p, 'name': p} for p in params]\n\n#load data\ndef getGfileData(t=None):\n if t is None:\n return [{}]\n idx = np.where(t==gui.MHD.timesteps)[0][0]\n g = gui.MHD.ep[idx].g\n #parameters from gfile we want to display in table\n keepValues = ('psiSep',\n 'psiAxis',\n 'shot',\n 'time',\n 'NR',\n 'NZ',\n 'RmAxis',\n 'ZmAxis',\n 'Ip')\n dict ={k: g[k] for k in keepValues}\n psiMax = g['psiRZ'].max()\n psiMin = g['psiRZ'].min()\n FpolMax = g['Fpol'].max()\n FpolMin = g['Fpol'].min()\n dict.update({'psiRZmin':psiMin})\n dict.update({'psiRZmax':psiMax})\n dict.update({'FpolMin':FpolMin})\n dict.update({'FpolMax':FpolMax})\n dict = [{'Parameter':i, 'Value':dict[i]} for i in dict]\n return dict\n\ndef gFileMultipiers():\n return html.Div(\n id=\"gfileMult\",\n children=[\n html.Label(\"psiRZ Multiplier\", style={'margin':'0 10px 0 10px'}),\n dcc.Input(id=\"psiRZMult\", className=\"gfileBoxInput\", value=\"1.0\"),\n html.Label(\"psiRZ Addition\", style={'margin':'0 10px 0 10px'}),\n dcc.Input(id=\"psiRZAdd\", className=\"gfileBoxInput\", value=\"0.0\"),\n html.Label(\"psiSep Multiplier\", style={'margin':'0 10px 0 10px'}),\n dcc.Input(id=\"psiSepMult\", className=\"gfileBoxInput\", value=\"1.0\"),\n html.Label(\"psiSep Addition\", style={'margin':'0 10px 0 10px'}),\n dcc.Input(id=\"psiSepAdd\", className=\"gfileBoxInput\", value=\"0.0\"),\n html.Label(\"psiAxis Multiplier\", style={'margin':'0 10px 0 10px'}),\n dcc.Input(id=\"psiAxisMult\", className=\"gfileBoxInput\", value=\"1.0\"),\n html.Label(\"psiAxis Addition\", style={'margin':'0 10px 0 10px'}),\n dcc.Input(id=\"psiAxisAdd\", className=\"gfileBoxInput\", value=\"0.0\"),\n html.Label(\"Fpol Multiplier\", style={'margin':'0 10px 0 10px'}),\n dcc.Input(id=\"FpolMult\", className=\"gfileBoxInput\", value=\"1.0\"),\n html.Label(\"Fpol Addition\", style={'margin':'0 10px 0 10px'}),\n dcc.Input(id=\"FpolAdd\", className=\"gfileBoxInput\", value=\"0.0\"),\n html.Button(\"Apply Corrections\", id=\"applyMult\", n_clicks=0, style={'margin':'0 10px 10px 0'}),\n html.Div(id=\"hiddenDivMult\")\n ],\n className=\"gfileBox\",\n )\n\ndef gFileNewSep():\n return html.Div(\n id=\"gfileNewSep\",\n children=[\n html.Label(\"New LCFS R Value [m]\", style={'margin':'0 10px 0 10px'}),\n dcc.Input(id=\"newLCFSr\", className=\"gfileBoxInput\", value=\"NA\"),\n html.Label(\"New LCFS Z Value [m]\", style={'margin':'0 10px 0 10px'}),\n dcc.Input(id=\"newLCFSz\", className=\"gfileBoxInput\", value=\"NA\"),\n html.Label(\"(Value of NA in Z will choose minimum psi)\"),\n html.Br(),\n dcc.RadioItems(\n id=\"newLCFSradio\",\n options=[\n {'label': 'Apply to All Timesteps', 'value': 'all'},\n {'label': 'Apply to Currently Selected Timestep', 'value': 'single'},\n ],\n value='all'\n ),\n html.Button(\"Re-Define LCFS\", id=\"newLCFSbutton\", n_clicks=0, style={'margin':'10px 10px 10px 10px'}),\n html.Div(id=\"hiddenDivSep\"),\n html.Button(\"Find LCFS From PFCs\", id=\"findLCFSbutton\", n_clicks=0, style={'margin':'10px 10px 10px 10px'}),\n html.Div(id=\"hiddenDivSep2\")\n ],\n className=\"gfileBox\",\n )\n\ndef saveNewGfile():\n return html.Div(\n id=\"saveGfile\",\n children=[\n html.Label(\"New gFile Name\", style={'margin':'0 10px 0 10px'}),\n dcc.Input(id=\"newGfileName\", className=\"gfileBoxInput\"),\n html.Button(\"Save New gFile\", id=\"saveGfileButton\", n_clicks=0, style={'margin':'10px 10px 10px 10px'}),\n Download(id=\"downloadNewGfile\"),\n html.Div(id=\"hiddenDivSaveGfile\")\n ],\n className=\"gfileBox\",\n )\n\ndef interpolateGfile():\n params = ['filename', 'timestep[ms]']\n data = [dict([{'filename':'', 'timestep':''}][0])]\n return html.Div(\n id=\"interpGfile\",\n children=[\n html.Label(\"Interpolation by Timestep\", style={'margin':'0 10px 0 10px'}),\n dcc.Input(id=\"interpTime\", className=\"gfileBoxInput\"),\n html.Button(\"Interpolate this Timestep\", id=\"interpButton\", n_clicks=0, style={'margin':'0 10px 10px 0'}),\n html.Div(id=\"hiddenDivInterp1\"),\n html.Br(),\n dash_table.DataTable(\n id='gFileTable2',\n columns = ([{'id': p, 'name': p} for p in params]),\n data = data,\n style_header={'backgroundColor': 'rgb(30, 30, 30)'},\n style_cell={\n 'textAlign': 'left',\n 'backgroundColor': 'rgb(50, 50, 50)',\n 'color': 'white'\n },\n editable=True,\n row_deletable=False,\n\n ),\n html.Br(),\n\n html.Label(\"Interpolate N steps between gFiles\", style={'margin':'0 10px 0 10px'}),\n html.Div(id='interpTable', className=\"gfileTable\"), #updated from MHD button callback\n dcc.Input(id=\"interpN\", className=\"gfileBoxInput\", placeholder='Enter N steps'),\n html.Button(\"Interpolate these Timesteps\", id=\"interpButton2\", n_clicks=0, style={'margin':'0 10px 10px 0'}),\n Download(id=\"download1InterpGfile\"),\n Download(id=\"downloadInterpGfiles\"),\n html.Div(id=\"hiddenDivInterp2\")\n ],\n className=\"gfileBox\",\n )\n\n\n@app.callback([Output('hiddenDivInterp1', 'children'),\n Output('download1InterpGfile', 'data')],\n [Input('interpButton', 'n_clicks')],\n [State('interpTime','value'),\n ])\ndef interpolate(n_clicks, t):\n \"\"\"\n interpolate gfile at user defined timestep\n \"\"\"\n if n_clicks < 1:\n raise PreventUpdate\n name = gui.interpolateGfile(t)\n return [html.Label(\"Gfile Interpolated\", style={'color':'#f5d142'}),\n send_file(name)]\n\n\n@app.callback([Output('hiddenDivInterp2', 'children'),\n Output('downloadInterpGfiles', 'data')],\n [Input('interpButton2', 'n_clicks')],\n [State('interpN','value'),\n State('gFileTable2','data'),\n ])\ndef interpolateNsteps(n_clicks, N, data):\n \"\"\"\n interpolate gfile at user defined steps between two gfiles\n \"\"\"\n if n_clicks < 1:\n raise PreventUpdate\n #load interpolation table data\n df = pd.DataFrame(data)\n df = df.sort_values('timestep[ms]')\n print(df)\n print(df['timestep[ms]'].values)\n #interpolate N steps between each point\n gui.interpolateNsteps(df['filename'].values, pd.to_numeric(df['timestep[ms]']).values,int(N))\n zipFile = gui.tmpDir + 'InterpolatedGfiles.zip'\n return [html.Label(\"gFiles Interpolated\", style={'color':'#f5d142'}),\n send_file(zipFile)]\n\n\n\n\n\n@app.callback(Output('hiddenDivMult', 'children'),\n [Input('applyMult', 'n_clicks')],\n [State('psiRZMult','value'),\n State('psiSepMult','value'),\n State('psiAxisMult','value'),\n State('FpolMult','value'),\n State('psiRZAdd','value'),\n State('psiSepAdd','value'),\n State('psiAxisAdd','value'),\n State('FpolAdd','value'),\n State('timeSlider', 'value')])\ndef applyMult(n_clicks, psiRZMult, psiSepMult, psiAxisMult, FpolMult,\n psiRZAdd,psiSepAdd,psiAxisAdd,FpolAdd,t):\n \"\"\"\n apply multiplier to psiRZ, psiSep, psiAxis, Fpol for currently\n selected equilibrium timestep\n \"\"\"\n if n_clicks < 1:\n raise PreventUpdate\n #parse user formulas and convert then to number via python compiler\n pi = np.pi\n #NEED TO ADAPT THIS TO HANDLE ADDITION\n psiRZMult = eval(parser.expr(psiRZMult).compile())\n psiSepMult = eval(parser.expr(psiSepMult).compile())\n psiAxisMult = eval(parser.expr(psiAxisMult).compile())\n FpolMult = eval(parser.expr(FpolMult).compile())\n\n psiRZAdd = eval(parser.expr(psiRZAdd).compile())\n psiSepAdd = eval(parser.expr(psiSepAdd).compile())\n psiAxisAdd = eval(parser.expr(psiAxisAdd).compile())\n FpolAdd = eval(parser.expr(FpolAdd).compile())\n\n\n gui.gfileClean(psiRZMult,psiSepMult,psiAxisMult,FpolMult,\n psiRZAdd,psiSepAdd,psiAxisAdd,FpolAdd,t)\n return [html.Label(\"Corrections Applied\", style={'color':'#f5d142'})]\n\n@app.callback(Output('hiddenDivSep', 'children'),\n [Input('newLCFSbutton', 'n_clicks')],\n [State('newLCFSr','value'),\n State('newLCFSz','value'),\n State('timeSlider', 'value'),\n State('newLCFSradio', 'value')])\ndef newLCFSbutton(n_clicks, rNew, zNew, t, radio):\n if n_clicks < 1:\n raise PreventUpdate\n if radio=='all':\n gui.newLCFSallTimesteps(rNew, zNew)\n else:\n gui.newLCFS(t, rNew, zNew)\n return [html.Label(\"Redefined LCFS\", style={'color':'#f5d142'})]\n\n@app.callback(Output('hiddenDivSep2', 'children'),\n [Input('findLCFSbutton', 'n_clicks')],\n [State('timeSlider', 'value'),\n State('loadPFC', 'n_clicks'),\n State('newLCFSr','value')])\ndef findLCFSbutton(n_clicks, t, PFC_n_clicks, r):\n if n_clicks < 1:\n raise PreventUpdate\n if PFC_n_clicks < 1:\n print(\"You must load a PFC before running this function\")\n raise PreventUpdate\n gui.findPsiSepfromPFCs(t, r)\n# gui.findPsiSepfromEQ(t)\n return [html.Label(\"Iteratively Found LCFS\", style={'color':'#f5d142'})]\n\n\n\n@app.callback([Output('hiddenDivSaveGfile', 'children'),\n Output('downloadNewGfile', 'data')],\n [Input('saveGfileButton', 'n_clicks')],\n [State('newGfileName','value'),\n State('timeSlider', 'value'),\n State('shot', 'value')])\ndef saveG(n_clicks, filename, t, shot):\n if n_clicks < 1:\n raise PreventUpdate\n gui.writeGfile(filename, shot, t)\n return [html.Label(\"Saved gFile\", style={'color':'#f5d142'}),\n send_file(gui.tmpDir + filename)]\n\n\"\"\"\n==============================================================================\nTab Contents: Output Tab\n\"\"\"\ndef buildOutputTab():\n return html.Div(\n id=\"outputTab\",\n children=[outputChildren()],\n )\n\ndef outputChildren():\n return html.Div(\n children = [\n html.H4(\"HEAT outputs\", style={\"text-align\":\"center\", \"width\":\"100%\"}),\n html.Button(\"Download HEAT Results\", id=\"downloadResults\", n_clicks=0, style={'margin':'0 10px 10px 0', \"width\":\"95%\" }),\n html.Br(),\n html.Div(id=\"hiddenDivDownloadResults\", style={\"width\":\"100%\"}),\n Download(id=\"downloadResultsDir\"),\n html.H6(\"Heat Flux Parameters:\"),\n html.Div( children=buildHFtable(), className=\"gfileTable\" ),\n #qDiv plot\n html.Div(\n children=[\n html.H6(\"HEAT qDiv Distributions (run HEAT for plot):\"),\n html.Div(children=hfDistPlots(update=False), id=\"qDivDist\"),\n ],\n className=\"wideBoxDarkColumn\",\n ),\n #Temp(t) plot for max(T) in OF run\n html.Div(\n children=[\n html.H6(\"openFOAM max(T) Evolutions (run openFOAM for plot):\"),\n html.Div(children=OFmaxTPlots(update=False), id=\"OFmaxTplot\"),\n ],\n className=\"wideBoxDarkColumn\",\n ),\n #Temp(t) for probes from GUI\n html.Div(\n children=[\n html.H6(\"openFOAM Tprobe Evolution (run openFOAM Tprobe for plot):\"),\n html.Div(children=OFTprobePlots(update=False), id=\"OFTprobePlot\"),\n ],\n className=\"wideBoxDarkColumn\",\n )\n ],\n className=\"wideBoxDark\",\n )\n\n@app.callback([Output('hiddenDivDownloadResults', 'children'),\n Output('downloadResultsDir', 'data')],\n [Input('downloadResults', 'n_clicks')],\n [State('MachFlag','value'),\n State('shot', 'value')])\ndef saveResults(n_clicks, MachFlag, shot):\n if n_clicks is None:\n raise PreventUpdate\n if MachFlag is None:\n raise PreventUpdate\n #create zip archive of data folder for this shot #\n file = gui.tmpDir + 'HEATresults'\n print(\"Creating HEAT results zip. This may take a while for large OF runs\")\n log.info(\"Creating HEAT results zip. This may take a while for large OF runs\")\n shutil.make_archive(file, 'zip', gui.MHD.shotPath)\n print(\"Zipped results\")\n log.info(\"Zipped results\")\n return [html.Label(\"Saved HEAT output\", style={'color':'#f5d142'}),\n send_file(file+'.zip')]\n\n\n\ndef buildHFtable(data=None):\n cols = getOutputColumns()\n if data==None:\n data = [{}]\n return dash_table.DataTable(\n id='hfTable',\n columns = cols,\n data = data,\n style_header={'backgroundColor': 'rgb(30, 30, 30)'},\n style_cell={\n 'textAlign': 'left',\n 'backgroundColor': 'rgb(50, 50, 50)',\n 'color': 'white'\n },\n editable=False,\n row_deletable=False,\n )\n\n\n#generic row data (table data is created in loadHF button connect)\ndef getOutputColumns():\n params = ['Parameter','Value']\n return [{'id': p, 'name': p} for p in params]\n\n\n\n\ndef hfDistPlots(update=False):\n \"\"\"\n div for heat flux distribution plots\n\n if update is False, just return an empty div, so that nothing happens on\n page load. If update=True, get qDivs and update the plot.\n\n This is called at the end of a HEAT run (runHEAT callback) button click\n \"\"\"\n if update==True:\n fig = gui.getHFdistPlots()\n\n return html.Div(\n className=\"plotBox\",\n children=[\n dcc.Graph(id=\"\", figure=fig),\n ],\n )\n else:\n\n return html.Div(\n children=[\n html.Label(\"Run HEAT to get qDiv plot\", style={'color':'#52caeb'})\n ],\n className=\"gfileBox\"\n )\n\n\ndef OFmaxTPlots(update=False):\n \"\"\"\n div for maximum openFOAM temperature plots\n\n if update is False, just return an empty div, so that nothing happens on\n page load. If update=True, get qDivs and update the plot.\n\n This is called at the end of a HEAT run (runHEAT callback) button click\n \"\"\"\n if update==True:\n fig = gui.getOFMinMaxPlots()\n\n return html.Div(\n className=\"plotBox\",\n children=[\n dcc.Graph(id=\"\", figure=fig),\n ],\n )\n else:\n\n return html.Div(\n children=[\n html.Label(\"Run OpenFOAM to get max(T) plot\", style={'color':'#52caeb'})\n ],\n className=\"gfileBox\"\n )\n\n\ndef OFTprobePlots(update=False,x=None,y=None,z=None):\n \"\"\"\n div for openFOAM probe plots\n\n if update is False, just return an empty div, so that nothing happens on\n page load. If update=True, get qDivs and update the plot.\n\n x,y,z are coordinate locations [mm] of T probe\n\n This is called at the end of a HEAT run (runHEAT callback) button click\n \"\"\"\n if update==True:\n fig = gui.TprobeOF(float(x),float(y),float(z))\n\n return html.Div(\n className=\"plotBox\",\n children=[\n dcc.Graph(id=\"\", figure=fig),\n ],\n )\n else:\n\n return html.Div(\n children=[\n html.Label(\"Run OpenFOAM Temp Probe to get plot\", style={'color':'#52caeb'})\n ],\n className=\"gfileBox\"\n )\n\n\n\n\n\n\n\n\"\"\"\n==============================================================================\nTab Contents: logfile tab\n\"\"\"\ndef buildLogTab():\n return html.Div(\n id=\"logTab\",\n children=[\n html.H4(\"HEAT Log File Updated Every 5 Seconds\"),\n dcc.Textarea(id=\"logData\", value='TEST', className=\"logBox\",\n readOnly=True),\n ],\n\n className=\"wideBoxDark\"\n )\n\n@app.callback([Output('logData', 'value'),\n Output('javascriptLog', 'run')],\n [Input('intervalLog', 'n_intervals')])\ndef updateLogFile(n):\n if n < 1:\n raise PreventUpdate\n with open(logFile, \"r\") as f:\n content = f.read()\n logCMD = '''\n var textarea = document.getElementById('logData');\n textarea.scrollTop = textarea.scrollHeight;\n\n '''\n return content, logCMD\n\n\n\"\"\"\n==============================================================================\nGraphs, plots, etc.\n\"\"\"\ndef build_graphs():\n return html.Div(\n id=\"graph-container\",\n children=[\n MHDplot(),\n ],\n )\n\ndef MHDplot():\n\n return html.Div(\n className=\"MHDplotBox\",\n children=[\n dcc.Graph(id=\"2DEQ\", className=\"EQplot\"),\n html.Br(),\n dcc.Slider(\n id='timeSlider',\n min=0,\n max=100,\n step=None,\n value=10,\n marks={50: 'Load MHD to see timesteps'},\n ),\n ],\n )\n\n#this callback is fired any time user moves time slider under EQ plot,\n#or when user loads mhd (which changes time slider value)\n@app.callback([Output('2DEQ', 'figure'),\n Output('gFileTable', 'data'),\n Output('gFilePlot1', 'figure')],\n [Input('timeSlider', 'value'),\n Input('hiddenDivMult', 'children'),\n Input('hiddenDivSep', 'children'),])\ndef slideEQplot(value, dummy1, tom):\n try: MachFlag = gui.MachFlag\n except:\n print(\"You didn't select a machine\")\n raise PreventUpdate\n try: ts = gui.MHD.timesteps\n except:\n print('Please load MHD')\n raise PreventUpdate\n idx = np.where(value==gui.MHD.timesteps)[0][0]\n ep = gui.MHD.ep[idx]\n shot = gui.MHD.shot\n t = gui.MHD.timesteps[idx]\n #Update Equilibrium plot\n #this import needs to be here (not at top of file) to prevent FreeCAD qt5\n #shared object conflict\n import GUIscripts.plotly2DEQ as plotly2DEQ\n plot = plotly2DEQ.makePlotlyEQDiv(shot, t, MachFlag, ep)\n data = getGfileData(t)\n\n #update plot on gfile cleaner tab with Fpol, psi. etc\n plot2 = plotly2DEQ.makePlotlyGfilePlot(ep)\n\n return plot, data, plot2\n\n\n\n\n\n\n\n\n\"\"\"\n==============================================================================\nMain Layout\n\"\"\"\ndef build_simulator():\n return html.Div(\n id=\"simulator-container\",\n children=[\n build_tabs(),\n build_graphs(),\n ],\n )\n\nlogJScmd = \"\"\napp.layout = html.Div(\n id=\"big-app-container\",\n children=[\n #store the session data until browser tab is closed\n dcc.Store(id='session', storage_type='memory'),\n dcc.Store(id='userInputFileData', storage_type='memory'),\n dcc.Store(id='PFCdataStorage', storage_type='memory'),\n dcc.Store(id='gFileListStorage', storage_type='memory'),\n #interval for updating logFile every 5 seconds\n dcc.Interval(\n id='intervalLog',\n interval=5*1000, # in milliseconds\n n_intervals=0\n ),\n #visdcc to run js to scroll log box to bottom\n visdcc.Run_js(id = 'javascriptLog', run = \"\"),\n build_banner(),\n build_simulator(),\n html.Div(id=\"hiddenDiv\", style={'display': 'none'}),\n ],\n)\n\napp.title = 'HEAT'\n\n\n\n\"\"\"\n==============================================================================\nSession storage callbacks and functions\n\"\"\"\n# Load Default callback and input file drag and drop\n@app.callback([Output('shot', 'value'),\n Output('tmin', 'value'),\n Output('tmax', 'value'),\n Output('nTrace', 'value'),\n Output('ionDir', 'value'),\n Output('ROIGridRes', 'value'),\n Output('gridRes', 'value'),\n Output('lqEich', 'value'),\n Output('S', 'value'),\n Output('lqCN', 'value'),\n Output('lqCF', 'value'),\n Output('lqPN', 'value'),\n Output('lqPF', 'value'),\n Output('fracCN', 'value'),\n Output('fracCF', 'value'),\n Output('fracPN', 'value'),\n Output('fracPF', 'value'),\n Output('Psol', 'value'),\n Output('fracUI', 'value'),\n Output('fracUO', 'value'),\n Output('fracLI', 'value'),\n Output('fracLO', 'value'),\n Output('qBG', 'value'),\n Output('OFstartTime', 'value'),\n Output('OFstopTime', 'value'),\n Output('OFminMeshLev', 'value'),\n Output('OFmaxMeshLev', 'value'),\n Output('OFSTLscale', 'value'),\n Output('OFdeltaT', 'value'),\n Output('session', 'data'),\n# Output('hiddenDivMachFlag', 'children')\n ],\n [Input('loadDefaults', 'n_clicks'),\n Input('userInputFileData', 'modified_timestamp')],\n [State('session', 'modified_timestamp'),\n State('MachFlag', 'value'),\n State('session', 'data'),\n State('userInputFileData', 'data')])\ndef session_data(n_clicks, inputTs, ts, MachFlag, data, inputFileData):\n #default case\n if ts is None or MachFlag not in machineList:\n print('Initializing Data Store')\n if MachFlag not in machineList:\n print(\"Machine not in machine list\")\n log.info(\"Machine not in machine list\")\n data = gui.getDefaultDict()\n data.update({'default_n_clicks':n_clicks})\n\n #Let the user know if this worked or if we still need a MachFlag\n if MachFlag not in machineList:\n outputDiv = html.Label(\"Select Machine First\", style={'color':'#f51b60'})\n else:\n outputDiv = html.Label(\"Loaded Input File\", style={'color':'#f5d142'})\n\n #load defaults\n if n_clicks > 0 and n_clicks>data.get('default_n_clicks') and MachFlag is not None:\n print(\"Loading Default Input File\")\n log.info(\"Loading Default Input File\")\n data = gui.loadDefaults()\n data['default_n_clicks'] = n_clicks\n elif inputTs == None or inputTs == -1:\n pass\n #use data we saved into storage object that we got from user input file\n else:\n print(inputTs)\n print(\"Loading User Input File\")\n log.info(\"Loading User Input File\")\n inputFileData['default_n_clicks'] = n_clicks\n data = inputFileData\n\n print(\"Updating Session Store\")\n return [data.get('shot', ''),\n data.get('tmin', ''),\n data.get('tmax', ''),\n data.get('nTrace', ''),\n data.get('ionDirection', ''),\n data.get('ROIGridRes', ''),\n data.get('gridRes', ''),\n data.get('lqEich', ''),\n data.get('S', ''),\n data.get('lqCN', ''),\n data.get('lqCF', ''),\n data.get('lqPN', ''),\n data.get('lqPF', ''),\n data.get('fracCN', ''),\n data.get('fracCF', ''),\n data.get('fracPN', ''),\n data.get('fracPF', ''),\n data.get('Psol', ''),\n data.get('fracUI', ''),\n data.get('fracUO', ''),\n data.get('fracLI', ''),\n data.get('fracLO', ''),\n data.get('qBG', ''),\n data.get('tMin', ''),\n data.get('tMax', ''),\n data.get('meshMinLevel', ''),\n data.get('meshMaxLevel', ''),\n data.get('STLscale', ''),\n data.get('deltaT', ''),\n data,\n# outputDiv\n ]\n\n\n\nif __name__ == '__main__':\n# dashGUI.py should be called with no arguments to run on 127.0.0.1:8050 (default)\n# to run on address:port, use command line:\n# dashGUI.py
    \n\n try:\n ipaddress.ip_address(sys.argv[1]) #validate it is an ip address\n address = sys.argv[1]\n except:\n address = '127.0.0.1' #default\n try:\n port = int(sys.argv[2])\n except:\n port = 8050 # default\n\n\n app.run_server(\n debug=True,\n dev_tools_ui=True,\n port=port,\n host=address\n )\n","sub_path":"source/dashGUI.py","file_name":"dashGUI.py","file_ext":"py","file_size_in_byte":94148,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"96390420","text":"def multi_string(string):\n def multiply(number):\n return string*number\n \n return multiply\n\ndef make_division_by(divisor):\n def divide(number):\n assert type(number) == int, 'debe ser un numero'\n assert divisor > 0, 'no se puede dividir por cero'\n return number/divisor\n\n return divide\n\n\nif __name__ == '__main__':\n multiply_javier = multi_string('Javier')\n multiply_hola = multi_string('hola')\n multiply_mundo = multi_string('mundo')\n\n print(multiply_javier(3))\n print(multiply_hola(5))\n print(multiply_mundo(2))\n\n division_by_3 = make_division_by(3)\n division_by_5 = make_division_by(5)\n division_by_18 = make_division_by(18)\n\n print(division_by_3(18))\n print(division_by_5(100))\n print(division_by_18(54))","sub_path":"closure.py","file_name":"closure.py","file_ext":"py","file_size_in_byte":785,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"770451","text":"#!/usr/bin/env python3\nimport os\nimport subprocess\nimport struct\nimport pandas as pd\nimport numpy as np\nimport csv\nimport math\n\ndef FindAllDivisors(x):\n divList = []\n y = 1\n sqrt = math.sqrt(x)\n while y <= sqrt:\n if x % y == 0:\n divList.append(y)\n divList.append(int(x/y))\n y += 1\n return divList\n\nsrc_program = r'src.exe'\nmod_program = r'mod.exe'\n\nomp = True\nthread_count = 12\ncount = 5\nsum = 0\nresult = 0\n\nos.system(\"gcc -O3 -o src Heat-2d.c\")\nif omp:\n os.system(\"gcc -O3 -fopenmp -o mod Heat-2d-st+wf.c\")\nelse:\n os.system(\"gcc -O3 -o mod Heat-2d-st+wf.c\")\n thread_count = 0\n\n# Запуск исходной программы.\nprint(\">>> Running original program.\")\nfor i in range(count):\n process = subprocess.Popen(src_program, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=False)\n outs, errs = process.communicate()\n var = (float(outs))\n sum += var\nsrc_result = sum/count\nprint(src_result)\n# Структура таблицы\n# [N,M; time; %]\ndf = pd.DataFrame(np.array([[u'src', str(src_result).replace('.', ','), '']]),\n columns=['d1, d2, d3', 'time', 'seq/res'])\n\n# Запуск модифицированной программы.\nfor th_c in range(6, thread_count+1, 6):\n print(\">>> Running modified program. Thread count = \" + str(th_c))\n for d1 in [4, 8, 16, 32]:\n for dn in [4, 8, 16, 20, 25, 40, 50, 80, 100, 125, 200, 250, 400]:#sorted(FindAllDivisors(10000)): #list(range(2, 30 + 1, 1)): #(200,5000,50)\n print('>>> Running with variables: d1='+str(d1)+', dn='+str(dn))\n sum = 0\n for i in range(count):\n process = subprocess.Popen([mod_program, str(d1), str(dn), str(th_c)], stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=False)\n outs, errs = process.communicate()\n var = (float(outs))\n sum += var\n result = sum / count\n print(result)\n df1 = pd.DataFrame(np.array([[u'd1='+str(d1)+u', d2='+str(dn)+u', d3='+str(dn), str(result).replace('.', ','), str(src_result/result).replace('.',',')]]),\n columns=['d1, d2, d3', 'time', 'seq/res']) #(src_result - result)/src_result\n df = pd.concat([df, df1], ignore_index=True)\n\nprint(\">>> Preparing the report.\")\nfrom time import gmtime, strftime\ndf.to_csv(\"./time_result_\"+strftime(\"%Y-%m-%d_%H-%M-%S\", gmtime())+\".csv\", sep=';', index=False)\n\nprint(\">>> Finish.\")\n","sub_path":"Heat - test/2d/test_runner.py","file_name":"test_runner.py","file_ext":"py","file_size_in_byte":2490,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"134697913","text":"from django.contrib import messages\nfrom django.shortcuts import render, get_object_or_404, redirect\nfrom .forms import WorkbookForm\nfrom .models import Workbook\nfrom django.http import HttpResponseRedirect\nimport pandas as pd\nfrom .worksheet_csv import convert_worksheets\nimport inspect, os, csv\n\n# Create your views here.\ndef home(request):\n\n\tif not request.user.is_authenticated:\n\t\tmessages.success(request, \"I'm sorry, but you must login first.\")\n\t\treturn redirect(\"login\")\n\telse:\t\n\t\tform = WorkbookForm(request.POST or None, request.FILES or None)\n\n\t\tif form.is_valid():\n\t\t\tinstance = form.save(commit=False)\n\t\t\tinstance.save()\n\t\t\n\t\t\treturn HttpResponseRedirect(instance.get_absolute_url())\n\t\tcontext = {\n\t\t\t\"form\": form\n\t\t}\n\t\treturn render(request, \"xlsxtocsv.html\", context)\n\n\ndef download(request, slug):\n\tif not request.user.is_authenticated:\n\t\tmessages.success(request, \"I'm sorry, but you must login first.\")\n\t\treturn redirect(\"login\")\n\telse:\t\n\t\tinstance = get_object_or_404(Workbook, slug=slug)\n\t\t# print instance.workbook\n\t\t# print instance.workbook.name\n\t\tif os.path.exists('static/media/merged.csv'):\n\t\t\twith open('static/media/merged.csv', 'w'):\n\t\t\t\tpass\n\t\telse:\n\t\t\twith open('static/media/merged.csv', 'w') as fp:\n\t\t\t\ta = csv.writer(fp)\n\t\t\t\tdata = []\n\t\t\t\ta.writerows(data)\n\n\t\ttry:#convert the workbook to a single csv file\n\t\t\tconvert_worksheets(instance.workbook)\n\t\t\t# instance.delete()\n\t\t\tcontext = {\n\t\t\t\t\"name\": 'merged.csv'\n\t\t\t}\n\t\t\tmessages.success(request, 'FILE IS SUCCESSFULLY CONVERTED!')\n\t\t\treturn render(request, \"download_page_xlsx.html\", context)\n\t\texcept:\n\t\t\tmessages.error(request, 'INVALID FILE FORMAT!')\n\t\t\t# instance.delete()\n\t\t\treturn redirect(\"main_home:home\")\n\n\t","sub_path":"xlsx_app/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1698,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"215356806","text":"import json\nimport os\nfrom django.test import TestCase, Client\nfrom corehq.apps.domain.models import Domain\nfrom corehq.apps.app_manager.models import Application\nfrom corehq.apps.app_manager.tests.util import add_build\n\n\nclass BrokenBuildTest(TestCase):\n\n @classmethod\n def setUpClass(cls):\n domain = 'apptest'\n cls.domain = Domain.get_or_create_with_name(domain, is_active=True)\n cls.cc_2_build = add_build(version='2.7.0', build_number=20655)\n with open(os.path.join(os.path.dirname(__file__), 'data', 'yesno.json')) as f:\n source = json.load(f)\n cls.app = Application.wrap(source)\n cls.app.domain = domain\n cls.app.save()\n cls.build = cls.app.make_build()\n cls.build.save(increment_version=False)\n\n @classmethod\n def tearDownClass(cls):\n cls.app.delete()\n cls.build.delete()\n cls.cc_2_build.delete()\n cls.domain.delete()\n\n def test_broken_build(self):\n client = Client()\n url = '/a/{domain}/apps/download/{build_id}/suite.xml'.format(\n domain=self.build.domain,\n build_id=self.build.get_id,\n )\n self.build = Application.get(self.build.get_id)\n self.assertEqual(self.build.build_broken, False)\n\n # delete the file and do it again, and assert the build is broken\n self.assertIn('files/suite.xml', self.build.blobs)\n self.build.delete_attachment('files/suite.xml')\n self.assertNotIn('files/suite.xml', self.build.blobs)\n\n self.build = Application.get(self.build.get_id)\n response = client.get(url)\n self.assertEqual(response.status_code, 404)\n self.build = Application.get(self.build.get_id)\n self.assertEqual(self.build.build_broken, True)\n","sub_path":"corehq/apps/app_manager/tests/test_broken_build.py","file_name":"test_broken_build.py","file_ext":"py","file_size_in_byte":1779,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"504969450","text":"import os\n\nimport imageio\nimport numpy as np\nimport pandas as pd\nimport pytest\n\nimport brainio\nfrom brainio.stimuli import StimulusSet\n\n\nclass TestPreservation:\n def test_subselection(self):\n stimulus_set = StimulusSet([{'image_id': i} for i in range(100)])\n stimulus_set.image_paths = {i: f'/dummy/path/{i}' for i in range(100)}\n stimulus_set = stimulus_set[stimulus_set['image_id'].isin(stimulus_set['image_id'].values[:3])]\n assert stimulus_set.get_image(0) is not None\n\n def test_pd_concat(self):\n s1 = StimulusSet([{'image_id': i} for i in range(10)])\n s1.image_paths = {i: f'/dummy/path/{i}' for i in range(10)}\n s2 = StimulusSet([{'image_id': i} for i in range(10, 20)])\n s2.image_paths = {i: f'/dummy/path/{i}' for i in range(10, 20)}\n s = pd.concat((s1, s2))\n s.image_paths = {**s1.image_paths, **s2.image_paths}\n assert s.get_image(1) is not None\n assert s.get_image(11) is not None\n\n\ndef test_get_stimulus_set():\n stimulus_set = brainio.get_stimulus_set(\"dicarlo.hvm-public\")\n assert \"image_id\" in stimulus_set.columns\n assert set(stimulus_set.columns).issuperset({'image_id', 'object_name', 'variation', 'category_name',\n 'image_file_name', 'background_id', 'ty', 'tz',\n 'size', 'id', 's', 'rxz', 'ryz', 'ryz_semantic',\n 'rxy', 'rxy_semantic', 'rxz_semantic'})\n assert len(stimulus_set) == 3200\n assert stimulus_set.identifier == 'dicarlo.hvm-public'\n for image_id in stimulus_set['image_id']:\n image_path = stimulus_set.get_image(image_id)\n assert os.path.exists(image_path)\n extension = os.path.splitext(image_path)[1]\n assert extension in ['.png', '.PNG', '.jpg', '.jpeg', '.JPG', '.JPEG']\n\n\ndef test_loadname_dicarlo_hvm():\n assert brainio.get_stimulus_set(identifier=\"dicarlo.hvm-public\") is not None\n\n\nclass TestLoadImage:\n def test_dicarlohvm(self):\n stimulus_set = brainio.get_stimulus_set(identifier=\"dicarlo.hvm-public\")\n paths = stimulus_set.image_paths.values()\n for path in paths:\n image = imageio.imread(path)\n assert isinstance(image, np.ndarray)\n assert image.size > 0\n\n\n@pytest.mark.parametrize('stimulus_set', (\n 'dicarlo.hvm',\n 'dicarlo.hvm-public',\n 'dicarlo.hvm-private',\n 'gallant.David2004',\n 'tolias.Cadena2017',\n 'movshon.FreemanZiemba2013',\n 'movshon.FreemanZiemba2013-public',\n 'movshon.FreemanZiemba2013-private',\n 'dicarlo.objectome.public',\n 'dicarlo.objectome.private',\n 'dicarlo.Kar2018cocogray',\n 'klab.Zhang2018.search_obj_array',\n 'dicarlo.Rajalingham2020',\n 'dicarlo.Rust2012',\n 'dicarlo.BOLD5000',\n 'dicarlo.THINGS1',\n 'dicarlo.THINGS2',\n 'aru.Kuzovkin2018',\n 'dietterich.Hendrycks2019.noise',\n 'dietterich.Hendrycks2019.blur',\n 'dietterich.Hendrycks2019.weather',\n 'dietterich.Hendrycks2019.digital',\n 'fei-fei.Deng2009',\n 'aru.Cichy2019',\n 'dicarlo.BashivanKar2019.naturalistic',\n 'dicarlo.BashivanKar2019.synthetic'\n))\ndef test_list_stimulus_set(stimulus_set):\n l = brainio.list_stimulus_sets()\n assert stimulus_set in l\n\n\n@pytest.mark.private_access\ndef test_klab_Zhang2018search():\n stimulus_set = brainio.get_stimulus_set('klab.Zhang2018.search_obj_array')\n # There are 300 presentation images in the assembly but 606 in the StimulusSet (explanation from @shashikg follows).\n # For each of the visual search task out of total 300, you need two images (one - the target image,\n # second - the search space image) plus there are 6 different mask images to mask objects\n # present at 6 different locations in a specified search image.\n # Therefore, a total of 300 * 2 + 6 images are there in the stimulus set.\n assert len(stimulus_set) == 606\n assert len(set(stimulus_set['image_id'])) == 606\n\n\n@pytest.mark.private_access\n@pytest.mark.slow\nclass TestDietterichHendrycks2019:\n def test_noise(self):\n stimulus_set = brainio.get_stimulus_set('dietterich.Hendrycks2019.noise')\n assert len(stimulus_set) == 3 * 5 * 50000\n assert len(set(stimulus_set['synset'])) == 1000\n\n def test_blur(self):\n stimulus_set = brainio.get_stimulus_set('dietterich.Hendrycks2019.blur')\n assert len(stimulus_set) == 4 * 5 * 50000\n assert len(set(stimulus_set['synset'])) == 1000\n\n def test_weather(self):\n stimulus_set = brainio.get_stimulus_set('dietterich.Hendrycks2019.weather')\n assert len(stimulus_set) == 4 * 5 * 50000\n assert len(set(stimulus_set['synset'])) == 1000\n\n def test_digital(self):\n stimulus_set = brainio.get_stimulus_set('dietterich.Hendrycks2019.digital')\n assert len(stimulus_set) == 4 * 5 * 50000\n assert len(set(stimulus_set['synset'])) == 1000\n\n\n@pytest.mark.private_access\ndef test_feifei_Deng2009():\n stimulus_set = brainio.get_stimulus_set('fei-fei.Deng2009')\n assert len(stimulus_set) == 50_000\n assert len(set(stimulus_set['label'])) == 1_000\n","sub_path":"tests/test_stimuli.py","file_name":"test_stimuli.py","file_ext":"py","file_size_in_byte":5258,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"123360117","text":"from subscribers.note_subscriber import NotesSubscriber\n\nfrom requests_futures.sessions import FuturesSession\nfrom concurrent.futures import ThreadPoolExecutor\n\nfrom utils.classes import MidiNote, Param\n\nfrom time import time, sleep\n\nimport logging\n\nlogging.basicConfig(level=\"INFO\")\n\n\nUPLOAD_DEST_PARAM = Param('u', 'upload')\nPARAMS = [UPLOAD_DEST_PARAM]\n\nTO_SLEEP = 0.3\n\n\nsession = FuturesSession(executor=ThreadPoolExecutor(max_workers=3))\n\ndef upload_stuff(reads, upload_url):\n if len(reads) == 0:\n return\n \n logging.info(f\"Uploading {len(reads)} values to {upload_url}\")\n session.post(upload_url, json=reads)\n\n\ndef note_to_weird(note: MidiNote):\n return note.status, note.note, note.velocity, 0, note.delay, time()\n\n\nclass Uploader(NotesSubscriber):\n def __init__(self):\n super().__init__('Uploader', PARAMS)\n \n red_queue = []\n green_queue = []\n self.queues = [red_queue, green_queue]\n self.active_index = 0\n\n self.run_in_new_thread(\"uploader\", self._aggregator_upload)\n\n\n def taram(self, note: MidiNote):\n read = note_to_weird(note)\n to_upload = self.queues[self.active_index]\n to_upload.append(read)\n \n def _switch(self):\n prev = self.active_index\n self.active_index = 0 if self.active_index else 1\n return prev\n \n def _aggregator_upload(self):\n logging.info(\"Aggregation uploader starting...\")\n upload_url = self.get_parameter(UPLOAD_DEST_PARAM)\n\n while True:\n inactive = self._switch()\n upload_stuff(self.queues[inactive], upload_url)\n self.queues[inactive] = []\n\n sleep(TO_SLEEP)\n\n\n\n# Heroku endpoint: \"https://mighty-island-21925.herokuapp.com/postNotes\"\n# Local endpoint: \"http://192.168.0.151:8080/postNotes\"\n","sub_path":"listener/subscribers/uploader.py","file_name":"uploader.py","file_ext":"py","file_size_in_byte":1818,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"621730184","text":"from django.db import models\nfrom django.utils import timezone\n\n\nclass Apartment(models.Model):\n \"\"\"\n Модель квартиры\n \"\"\"\n object = models.ForeignKey('users.Object', verbose_name='Дом', related_name='apartments')\n controller = models.ForeignKey('devices.Controller', verbose_name='Контроллер', related_name='apartments')\n user = models.ForeignKey('users.User', verbose_name='Жилец', related_name='apartments', blank=True, null=True)\n number = models.PositiveSmallIntegerField(verbose_name='Номер квартиры')\n\n class Meta:\n verbose_name = 'Квартира'\n verbose_name_plural = 'Квартиры'\n\n def __str__(self):\n return 'Apartment №{}'.format(self.number)\n\n @property\n def is_connected(self):\n if self.controller.statistics.exists():\n return (timezone.now() - self.controller.statistics.last().time).days < 7\n return False\n","sub_path":"unios_control/hcs/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":957,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"551123981","text":"\"\"\" Utils module \"\"\"\nimport random\nimport re\nimport string\n\n\nclass Utils:\n \"\"\" Class for utils \"\"\"\n @staticmethod\n def random_string(length):\n \"\"\" Function that creates random string with specified length \"\"\"\n letters = string.ascii_lowercase\n return ''.join(random.choice(letters) for i in range(length))\n\n @staticmethod\n def is_email_valid(email):\n \"\"\" Function that validates email \"\"\"\n reg_expression = r\"[^@]+@[^@]+\\.[^@]+\"\n return re.match(reg_expression, email)\n","sub_path":"api_backend/myapp/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":526,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"416225855","text":"\n# coding: utf-8\n\n# #Method of reflections in python\n# The Method of Reflection (MOR) is a algorithm first coming out of Macroeconomics, that ranks nodes in a bi-partite network. This notebook should hopefully help you implement the _method of reflection_ in python. To be precise, it is the modified algorithm that is proposed by Caldarelli et al., which solves some problems with the original Hidalgo-Hausmann (HH) algorithm [doi:10.1073/pnas.0900943106](http://chidalgo.com/Papers/HidalgoHausmann_PNAS_2009_PaperAndSM.pdf). The main problem with (HH) is that all values converge to a single fixed point after sufficiently many iterations. The Caldarelli version solves this by adding a new term to the recursive equation - what they call a _biased random walker_ (function _G_). [doi: 10.1371/journal.pone.0047278](http://www.plosone.org/article/info%3Adoi%2F10.1371%2Fjournal.pone.0047278). I hadn't seen any open-source implementations of this algorithm, so I thought I'd share my naïve approach.\n\n# In[4]:\n\nimport datetime\nimport pandas as pd\nimport numpy as np\nfrom collections import defaultdict\nimport scipy.stats as ss\nfrom scipy.optimize import fmin as scipyfmin\nimport operator\nimport re\nimport json\n\n#if you are using ipython and want to see things inline. \nget_ipython().magic(u'pylab inline')\n\n\n# #Modelling the data\n# We want to model a bi-partite network. Since we are using `numpy` and want to operate on a matrix we will use a `numpy.matrix`, but we also may want to retain the Unique IDs associated with each node, so we'll need to keep `dicts` of those as they relate to the matrix indices. Therefore for each bi-partite network at least __three files__ are needed. In my case I analysed a network which was a Wikipedia Category, so my two node-types are _users_ and _articles_. In your case they may be different, but I've kept the nomenclature here for simplicity - my own simplicity 8^). You can borrow my sample data from https://github.com/notconfusing/wiki_econ_capability/tree/master/savedata\n# \n# + the `M.npy` - an numpy matrix _M_ - adjacently matrix of the network.\n# + `user_dict.json` - a mapping (json dictionary)between unique key (in my case Wikipedia user name) to _M_ row index.\n# + `article_dict` - a mapping (json dictionary) between unique key (in my case the name of the article) _M_ column index.\n# \n# ##Extra data\n# If you plan to calibrate your model against some exogenous metrics you will need to provide two more files - the rankings from the exogenous data.\n# \n# + `user_exogenous_ranks.json` - a mapping (json dictionary) between the same keys of the `user_dict` to their exogenous ranks (how well another metric ranks Wikipedia users).\n# + `article_exogenous_ranks.json` - - a mapping (json dictionary) between the same keys of the `article_dict` to their exogenous ranks (how well another metric ranks Wikipedia articles).\n# \n# ##Putting it all in a folder\n# I put everything belonging to one network into a single folder and then use this `load_files` method which unpacks all the object and gives you a dict of all the objects.\n\n# In[2]:\n\ndef load_files(folder):\n M = np.load(folder+'M.npy')\n user_dict = json.load(open(folder+'user_dict.json', 'r'))\n article_dict = json.load(open(folder+'article_dict.json', 'r')) \n user_exogenous_ranks = json.load(open(folder+'user_exogenous_ranks.json', 'r'))\n article_exogenous_ranks = json.load(open(folder+'article_exogenous_ranks.json', 'r'))\n return {'M':M,\n 'user_dict':user_dict,\n 'article_dict':article_dict,\n 'user_exogenous_ranks':user_exogenous_ranks, \n 'article_exogenous_ranks':article_exogenous_ranks}\n\n\n# For instance, let's create the `feminist_data` dict, which holds data from _Category:Feminist_writers_ . I am snapshotting data, so that's why below you see two dates: when the snapshot was taken, and the latest date to be considered in the snapshot. So we are getting the full data from February 18th 2014.\n\n# In[7]:\n\nfeminist_data = load_files('savedata/Category:Feminist_writers/2014-02-18/2014-02-18/')\n\n\n# Now we define two operations on _M_. The _HH_ technique and those coming after use a binary input matrix, I also got better results, with a binary matrix. So we can normalise all our non-zero data to `1`. Also we may want to take a look at it an see if it has a triangular shape, since (MOR) assumes a triangular matrix.\n\n# In[8]:\n\ndef make_bin_matrix(M):\n #this returns the a matrix with entry True where the original was nonzero, and zero otherwise.\n M[M>0] = 1.0\n return M\n\ndef M_test_triangular(M):\n user_edits_sum = M.sum(axis=1)\n article_edits_sum = M.sum(axis=0)\n \n user_edits_order = user_edits_sum.argsort()\n article_edits_order = article_edits_sum.argsort()\n \n M_sorted = M[user_edits_order,:]\n M_sorted_sorted = M_sorted[:,article_edits_order]\n \n M_bin = make_bin_matrix(M_sorted_sorted)\n \n plt.figure(figsize=(10,10))\n imshow(M_sorted_sorted, cmap=plt.cm.bone, interpolation='nearest')\n\n\n# In[10]:\n\nbin_M = make_bin_matrix(feminist_data['M'])\nM_test_triangular(bin_M)\n\n\n# Ok now let's move onto our third and fourth operations on _M_ - getting some numeric rankings out of the matrix. Let us refresh ourselves on the equations from the literature. (Note variables _c_ and _p_, countries and products, translate to editors and article respectively): \n# \n# ##Zeroth order scores\n# These are an $w_{c}$ editor-vector which is the sums of articles edited by each editor. Or the article-vector $w_{p}$, which is the sum of editors contributing to each article.\n# \n# \\begin{cases}\n# w_{c}^{(0)} = \\sum_{p=1}^{N_{p}} M \\equiv k_c\\\\[7pt]\n# w_{p}^{(0)} = \\sum_{c=1}^{N_{c}} M \\equiv k_p\n# \\end{cases}\n# \n# ## Higher orders\n# The first order $w^{1}_c$ is the sum of the articles touched, but weighted by the Zeroth order article-vector (and the $G$ term). So if you've edited better articles that counts. And $w^{1}_c$ is the sum of editors touching, but weighted by the Zeroth order editor-vector (and $G$). So if you're touched by better editors that's also being considered. \n# \n# Beyond the first order interpretation for the higher orders is difficult.\n# \n# \\begin{cases}\n# w^{(n+1)}_c (\\alpha,\\beta) = \\sum_{p=1}^{N_p} G_{cp}(\\beta) \\,w^{(n)}_p (\\alpha,\\beta)\\\\[7pt]\n# w^{(n+1)}_p (\\alpha,\\beta) = \\sum_{c=1}^{N_c} G_{pc}(\\alpha) \\, w^{(n)}_c (\\alpha,\\beta)\\\\\n# \\end{cases}\n# \n# ## G - transition probability function\n# Depending on $\\alpha$ and $\\beta$ we non-linearly weight based on the Zeroth order iterations. \n# \n# \\begin{cases}\n# G_{cp}(\\beta) = \\frac{M_{cp} k_{c}^{-\\beta}}{\\sum_{c' = 1}^{N_c} M_{c'p} k_{c'}^{-\\beta}}\\\\[10pt]\n# G_{pc}(\\alpha) = \\frac{M_{cp} k_{p}^{-\\alpha}}{\\sum_{p' = 1}^{N_p} M_{cp'} k_{p'}^{-\\alpha}}.\\\\\n# \\end{cases}\n# \n# ## Translating the mathematics into numpy\n# And now we implement the mathematics in python. Hopefully I got this right, it hasn't been independently verified. Additionally I implement $w$ as a `generator`, so you can go on for many generations without chewing up too much memory. There is also a stream function that allows you get a specific iteration. And lastly a `find_convergence` function, that checks to see if the rankings haven't shifted for two consecutive iterations.\n\n# In[71]:\n\ndef Gcp_denominateur(M, p, k_c, beta):\n M_p = M[:,p]\n k_c_beta = k_c ** (-1 * beta)\n return np.dot(M_p, k_c_beta)\n\ndef Gpc_denominateur(M, c, k_p, alpha):\n M_c = M[c,:]\n k_p_alpha = k_p ** (-1 * alpha)\n return np.dot(M_c, k_p_alpha)\n\n\ndef make_G_hat(M, alpha=1, beta=1):\n '''G hat is Markov chain of length 2\n Gcp is a matrix to go from contries to product and then \n Gpc is a matrix to go from products to ccountries'''\n \n k_c = M.sum(axis=1) #aka k_c summing over the rows\n k_p = M.sum(axis=0) #aka k_p summering over the columns\n \n G_cp = np.zeros(shape=M.shape)\n #Gcp_beta\n for [c, p], val in np.ndenumerate(M):\n numerateur = (M[c,p]) * (k_c[c] ** ((-1) * beta))\n denominateur = Gcp_denominateur(M, p, k_c, beta)\n G_cp[c,p] = numerateur / float(denominateur)\n \n \n G_pc = np.zeros(shape=M.T.shape)\n #Gpc_alpha\n for [p, c], val in np.ndenumerate(M.T):\n numerateur = (M.T[p,c]) * (k_p[p] ** ((-1) * alpha))\n denominateur = Gpc_denominateur(M, c, k_p, alpha)\n G_pc[p,c] = numerateur / float(denominateur)\n \n \n return {'G_cp': G_cp, \"G_pc\" : G_pc}\n\ndef w_generator(M, alpha, beta):\n #this cannot return the zeroeth iteration\n \n G_hat = make_G_hat(M, alpha, beta)\n G_cp = G_hat['G_cp']\n G_pc = G_hat['G_pc']\n #\n\n fitness_0 = np.sum(M,1)\n ubiquity_0 = np.sum(M,0)\n \n fitness_next = fitness_0\n ubiquity_next = ubiquity_0\n i = 0\n \n while True:\n \n fitness_prev = fitness_next\n ubiquity_prev = ubiquity_next\n i += 1\n \n fitness_next = np.sum( G_cp*ubiquity_prev, axis=1 )\n ubiquity_next = np.sum( G_pc* fitness_prev, axis=1 )\n \n yield {'iteration':i, 'fitness': fitness_next, 'ubiquity': ubiquity_next}\n \n\n\ndef w_stream(M, i, alpha, beta):\n \"\"\"gets the i'th iteration of reflections of M, \n but in a memory safe way so we can calculate many generations\"\"\"\n if i < 0:\n raise ValueError\n for j in w_generator(M, alpha, beta):\n if j[0] == i:\n return {'fitness': j[1], 'ubiquity': j[2]}\n break\n \ndef find_convergence(M, alpha, beta, fit_or_ubiq, do_plot=False,):\n '''finds the convergence point (or gives up after 1000 iterations)'''\n if fit_or_ubiq == 'fitness':\n Mshape = M.shape[0]\n elif fit_or_ubiq == 'ubiquity':\n Mshape = M.shape[1]\n \n rankings = list()\n scores = list()\n \n prev_rankdata = np.zeros(Mshape)\n iteration = 0\n\n for stream_data in w_generator(M, alpha, beta):\n iteration = stream_data['iteration']\n \n data = stream_data[fit_or_ubiq]\n rankdata = data.argsort().argsort()\n \n #test for convergence\n if np.equal(rankdata,prev_rankdata).all():\n break\n if iteration == 1000:\n break\n else:\n rankings.append(rankdata)\n scores.append(data)\n prev_rankdata = rankdata\n \n if do_plot:\n plt.figure(figsize=(iteration/10, Mshape / 20))\n plt.xlabel('Iteration')\n plt.ylabel('Rank, higher is better')\n plt.title('Rank Evolution')\n p = semilogx(range(1,iteration), rankings, '-,', alpha=0.5)\n return {fit_or_ubiq:scores[-1], 'iteration':iteration}\n\n\n# We also know from Caldarelli et al. that there is an analytic formulation to the recursive procedure. So if you want to save some (a lot) processing and just know the end result we can use:\n# \n# ## Analytic solution\n# \n# \\begin{cases}\n# w^{*}_e (\\alpha,\\beta) = (\\sum_{a=1}^{N_a} M_{ea}k_{a}^{-\\alpha})k_{e}^{-\\beta} \\\\\n# w^{*}_a (\\alpha,\\beta) = (\\sum_{e=1}^{N_e} M_{ea}k_{e}^{-\\beta})k_{a}^{-\\alpha}\\\\\n# \\end{cases}\n# \n# And again in python:\n\n# In[13]:\n\ndef w_star_analytic(M, alpha, beta, w_star_type):\n k_c = M.sum(axis=1) #aka k_c summing over the rows\n k_p = M.sum(axis=0) #aka k_p summering over the columns\n \n A = 1\n B = 1\n \n def Gcp_denominateur(M, p, k_c, beta):\n M_p = M[:,p]\n k_c_beta = k_c ** (-1 * beta)\n return np.dot(M_p, k_c_beta)\n \n def Gpc_denominateur(M, c, k_p, alpha):\n M_c = M[c,:]\n k_p_alpha = k_p ** (-1 * alpha)\n return np.dot(M_c, k_p_alpha)\n \n if w_star_type == 'w_star_c':\n w_star_c = np.zeros(shape=M.shape[0])\n\n for c in range(M.shape[0]):\n summand = Gpc_denominateur(M, c, k_p, alpha)\n k_beta = (k_c[c] ** (-1 * beta))\n w_star_c[c] = A * summand * k_beta\n\n return w_star_c\n \n elif w_star_type == 'w_star_p':\n w_star_p = np.zeros(shape=M.shape[1])\n \n for p in range(M.shape[1]):\n summand = Gcp_denominateur(M, p, k_c, beta)\n k_alpha = (k_p[p] ** (-1 * alpha))\n w_star_p[p] = B * summand * k_alpha\n \n return w_star_p\n\n\n# ## Running the iterative and analytic solutions on data.\n# We will run our algorithms on our data. The output of both the iterative and the analytic solutions are scores. So in order to know who was the best, we afterwards identify (this is why we need the ID-mapping) and sort the list. I use `pandas` here to simply life, but I've also done it in pure-python if you're not familiar with `pandas`. Also I arbitrarily use $(\\alpha, \\beta) = (0,0)$.\n# \n# ###First lets use the analytic solution.\n\n# In[25]:\n\n#purer python\n#score\nw_scores = w_star_analytic(M=feminist_data['M'], alpha=0.5, beta=0.5, w_star_type='w_star_c')\n#identify\nw_ranks = {name: w_scores[pos] for name, pos in feminist_data['user_dict'].iteritems() }\n#sort\nw_ranks_sorted = sorted(w_ranks.iteritems(), key=operator.itemgetter(1))\n\n#or use pandas\nw_scores_df = pd.DataFrame.from_dict(w_ranks, orient='index')\nw_scores_df.columns = ['w_score']\nw_scores_df.sort(columns=['w_score'], ascending=False).head()\n\n\n# Well done users _Dsp13_ and _Bearcat_. (Isn't there a Mogwai video called _Bearcat_? Oh, no it's [Batcat](https://www.youtube.com/watch?v=KMDCM5OAOaE) \\\\m/ never mind let's move on.) \n# \n# ##Verification with the iterative method.\n# Let's take the long way home, and check that the shortcut actually takes us to the right place. We use the iterative method with the same data, until we find convergence. Also I make a plot here that ranks the users after each iteration, so we can track them. So each line you will see if the history of users rise to Glory, or their slow decline to forgotten irrelevance (or none of those phenomenon). Actually if you see a user going up its because the value of the articles edited is increasing. And likewise if a user is losing standing, its because they edited a lot of articles, but were of poor quality.\n\n# In[ ]:\n\nconvergence = find_convergence(M=feminist_data['M'], alpha=0.5, beta=0.5, fit_or_ubiq='fitness', do_plot=True)\n\n\n# In[41]:\n\nconvergence['iteration']\n\n\n# It looks like it took 661 iterations for this particular network to converge with $(\\alpha, \\beta) = (0,0)$. Now, let's what the ranking produce. \n\n# In[47]:\n\nw_iter = convergence['fitness'] \n#rank\nw_iter_ranks = {name: w_iter[pos] for name, pos in feminist_data['user_dict'].iteritems() }\n#sort\nw_ranks_sorted = sorted(w_iter_ranks.iteritems(), key=operator.itemgetter(1))\n\n#or use pandas\nw_iter_scores_df = pd.DataFrame.from_dict(w_iter_ranks, orient='index')\nw_iter_scores_df.columns = ['w_score']\nw_iter_scores_df.sort(columns=['w_score'], ascending=False).head()\n\n\n# Verified. You can see the analytic and iterative methods produce the same ranking, but the scores are off by a normalisation constant.\n# \n# ## Calibration with exogenous variables.\n# \n# Lastly, we might want to know for what values of $alpha$ and $beta$ maximise our correlation between model and actual. Without resorting to any fancy optimisers, let's just perform a grid search. With a gridserch we can also get a picture of the landscape. We define a way to compare our list rankings using the Spearman method from `scipy.stats`. Then we'll make a landscape of $[-2,2] \\times [-2,2]$ with resolution $50 \\times 50$, and evaluate at all those points (using the analytic solution). Finally we will return the top correlation we found.\n\n# In[67]:\n\n'''I'm sure this can be done much more elegantly\nbut this was sort-of drink-a-lot-of-coffee-one-afternoon-and-get-it-done\ncleaning this up is an exercise for the reader'''\ndef rank_comparison(a_ranks_sorted, b_ranks_sorted, do_plot=False):\n a_list = list()\n b_list = list()\n for atup in a_ranks_sorted:\n aiden = atup[0]\n apos = atup[1]\n #find this in our other list\n for btup in b_ranks_sorted:\n biden = btup[0]\n bpos = btup[1]\n if aiden == biden:\n a_list.append(apos)\n b_list.append(bpos)\n if do_plot: \n plt.figure(figsize=(10,20))\n plot([1,2], [a_list, b_list], '-o')\n plt.show()\n \n return ss.spearmanr(a_list, b_list)\n\ndef calibrate_analytic(M, ua, exogenous_ranks_sorted, user_or_art_dict, index_function, title, do_plot=False):\n \n if ua == 'users':\n w_star_type = 'w_star_c'\n elif ua == 'articles':\n w_star_type = 'w_star_p'\n \n squarelen = range(0,50)\n \n alpha_range = map(index_function,squarelen)\n beta_range = map(index_function,squarelen)\n landscape = np.zeros(shape=(len(list(alpha_range)),len(list(beta_range))))\n\n top_spearman = {'spearman':None,'alpha':None, 'beta':None, 'ua':ua}\n\n for alpha_index, alpha in enumerate(alpha_range):\n for beta_index, beta in enumerate(beta_range):\n \n w_converged = w_star_analytic(M, alpha, beta, w_star_type)\n \n w_ranks = {name: w_converged[pos] for name, pos in user_or_art_dict.iteritems() }\n w_ranks_sorted = sorted(w_ranks.iteritems(), key=operator.itemgetter(1))\n \n spearman = rank_comparison(w_ranks_sorted, exogenous_ranks_sorted)\n\n if spearman[1] < 0.05:\n landscape[alpha_index][beta_index] = spearman[0]\n \n if (not top_spearman['spearman']) or (spearman[0] > top_spearman['spearman']):\n top_spearman['spearman'] = spearman[0]\n top_spearman['alpha'] = alpha\n top_spearman['beta'] = beta\n else:\n landscape[alpha_index][beta_index] = np.nan\n\n if do_plot:\n plt.figure(figsize=(10,10))\n heatmap = imshow(landscape, interpolation='nearest', vmin=-1, vmax=1)\n #heatmap = plt.pcolor(landscape)\n colorbar = plt.colorbar(heatmap)\n plt.xlabel(r'$ \\beta $')\n plt.xticks(squarelen, beta_range, rotation=90)\n plt.ylabel(r'$ \\alpha $')\n plt.yticks(squarelen, alpha_range)\n plt.title(title)\n \n landscape_file = open(title+'_landscape.npy', 'w')\n np.save(landscape_file, landscape)\n plt.savefig(title+'_landscape.eps')\n\n return top_spearman\n\n\n# Ok, now let's run the calibration and get our optimising variables.\n\n# In[ ]:\n\nuser_spearman = calibrate_analytic(M=make_bin_matrix(feminist_data['M']),\n ua='users',\n exogenous_ranks_sorted=feminist_data['user_exogenous_ranks'],\n user_or_art_dict=feminist_data['user_dict'],\n index_function=lambda x: (x-25)/12.5, \n title='Grid Search for User of Feminist Writers',\n do_plot=True)\n\n\n# Note that the white parts of the gridsearch are where the Spearman rho value was not significant using 0.05 as a threshold.\n\n# In[60]:\n\nprint('Optimizing points from gridsearch', \n 'rho:', user_spearman['spearman'], \n 'alpha', user_spearman['alpha'], \n 'beta', user_spearman['beta'] )\n\n\n# Well it looks like this optimising point occurs on the boundary. But we can see also that $\\alpha = 0, \\beta < 1$ seems to be an optimising solution set ripe for further investigation. \n# \n# #Conclusion\n# I hope this allows you to see how Method of Reflections works, and - importantly - how to translate it into different domains. Anywhere you have a bi-partite network you can start ranking nodes using this technique! And if you have some exogenous data, you can also calibrate your model. Please alert me if there are any mistakes in here.\n# \n# ##License\n# \n# The MIT License (MIT)\n# \n# Copyright © 2014 Max Klein aka notconfusing‽\n# \n# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:\n# \n# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.\n# \n# THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n# \n","sub_path":"Method of Reflections Explained and Exampled.py","file_name":"Method of Reflections Explained and Exampled.py","file_ext":"py","file_size_in_byte":20845,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"56527303","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# @Time : 2017/12/19 21:45\n# @Author : Evescn\n# @Site : \n# @File : sock_server1.py\n# @Software: PyCharm\n\nimport socketserver\n\nclass MyTCPHandler(socketserver.BaseRequestHandler):\n def handle(self):\n print(\"New Conn:\", self.client_address)\n while True:\n data = self.request.recv(1024)\n if not data: break\n print(\"Client Says:\", data.decode())\n self.request.send(data)\n\n\nif __name__ == '__main__':\n HOST, PORT = \"localhost\", 50007\n\n # 吧刚才写的类当作一个参数传给ThreadingTCPServer这个类,下面的代码就创建了一个多现场socket server\n server = socketserver.ThreadingTCPServer((HOST, PORT), MyTCPHandler)\n\n # 启动这个server,这个server会一直运行,除非按ctrl-C停止\n server.serve_forever()","sub_path":"day8/sock_server1.py","file_name":"sock_server1.py","file_ext":"py","file_size_in_byte":863,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"517969776","text":"\"\"\"\nClass Button comes here.\n\"\"\"\nfrom selenium.webdriver.support import expected_conditions as EC\nfrom selenium.webdriver.support.ui import WebDriverWait\n\nfrom elements.base import BasePageElement\n\n\n# pylint: disable=too-few-public-methods\nclass Button(BasePageElement):\n \"\"\"\n Button methods come here.\n \"\"\"\n\n def __init__(self, driver, locator):\n \"\"\"\n Add locator property\n\n :param driver: state of driver\n :param locator: tuple contains attribute available for By class and the same locator\n \"\"\"\n super().__init__(driver)\n self.locator = locator\n\n def click(self):\n \"\"\"\n Click on the button defined by the locator\n \"\"\"\n WebDriverWait(self.driver, 30).until(\n EC.element_to_be_clickable(self.locator))\n self.driver.find_element(*self.locator).click()\n","sub_path":"elements/button.py","file_name":"button.py","file_ext":"py","file_size_in_byte":860,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"574891530","text":"import tensorflow as tf\nimport tensorflow.contrib.slim as slim\nclass EDSR(object):\n def __init__(self,args,sess):\n self.sess = sess\n self.img_size = args.imgsize\n self.output_channels = args.output_channels\n self.scale = args.scale\n self.num_layers = args.resBlocks\n self.feature_size = args.featuresize\n self.batchsize = args.batchsize\n self.savedir = args.savedir\n self.model_name = args.model_name\n self.logs = args.logs\n self.epoch = args.epoch\n\n # 网络的输入\n with tf.name_scope('input'):\n self.input = tf.placeholder(tf.float32, [None, self.img_size, self.img_size, self.output_channels],\n name=\"images\")\n self.target = tf.placeholder(tf.float32, [None, self.img_size * self.scale, self.img_size * self.scale,\n self.output_channels], name=\"labels\")\n x = slim.conv2d(self.input, self.feature_size, [3, 3])\n x = slim.conv2d(x,self.feature_size,[1,1])\n x = slim.conv2d(x,self.feature_size,[5,5])\n self.out = x\n self.loss = tf.reduce_mean(tf.square(self.target - self.out))\n tf.summary.scalar(\"loss\", self.loss)\n\n mse = tf.reduce_mean(tf.squared_difference(self.target, self.out))\n mse = tf.sqrt(mse)\n PSNR = tf.constant(1, dtype=tf.float32) / mse\n PSNR = tf.constant(20, dtype=tf.float32) * self.log10(PSNR)\n tf.summary.scalar(\"PSNR\", PSNR)\n\n PSNR2 = tf.image.psnr(self.target, self.out, max_val=1.0)\n PSNR2 = tf.reduce_sum(PSNR2)\n PSNR2 = tf.div(PSNR2, self.batchsize)\n tf.summary.scalar('PSNR_tf', PSNR2)\n\n def resBlock(x, channels=64, kernel_size=[3, 3], scale=1):\n tmp = slim.conv2d(x, channels, kernel_size, activation_fn=None)\n tmp = tf.nn.relu(tmp)\n tmp = slim.conv2d(tmp, channels, kernel_size, activation_fn=None)\n tmp *= scale\n return x + tmp\n\n def upsample(x, scale=3, features=64, activation=tf.nn.relu):\n assert scale in [2, 3, 4]\n x = slim.conv2d(x, features, [3, 3], activation_fn=activation)\n if scale == 2:\n ps_features = 3 * (scale ** 2)\n x = slim.conv2d(x, ps_features, [3, 3], activation_fn=activation)\n # x = slim.conv2d_transpose(x,ps_features,6,stride=1,activation_fn=activation)\n x = PS(x, 2, color=True)\n elif scale == 3:\n ps_features = (scale ** 2)\n x = slim.conv2d(x, ps_features, [3, 3], activation_fn=activation)\n # x = slim.conv2d_transpose(x,ps_features,9,stride=1,activation_fn=activation)\n x = PS(x, 3, color=False)\n elif scale == 4:\n ps_features = 3 * (2 ** 2)\n for i in range(2):\n x = slim.conv2d(x, ps_features, [3, 3], activation_fn=activation)\n # x = slim.conv2d_transpose(x,ps_features,6,stride=1,activation_fn=activation)\n x = PS(x, 2, color=True)\n return x\n\n def _phase_shift(I, r):\n bsize, a, b, c = I.get_shape().as_list()\n print(I.get_shape)\n bsize = tf.shape(I)[0] # Handling Dimension(None) type for undefined batch dim\n X = tf.reshape(I, (bsize, a, b, r, r))\n X = tf.transpose(X, (0, 1, 2, 4, 3)) # bsize, a, b, 1, 1\n X = tf.split(X, a, 1) # a, [bsize, b, r, r]\n X = tf.concat([tf.squeeze(x, axis=1) for x in X], 2) # bsize, b, a*r, r\n X = tf.split(X, b, 1) # b, [bsize, a*r, r]\n X = tf.concat([tf.squeeze(x, axis=1) for x in X], 2) # bsize, a*r, b*r\n return tf.reshape(X, (bsize, a * r, b * r, 1))\n\n def PS(self,X, r, color=False):\n if color:\n Xc = tf.split(X, 3, 3)\n X = tf.concat([_phase_shift(x, r) for x in Xc], 3)\n else:\n X = _phase_shift(X, r)\n return X\n\n def log10(x):\n numerator = tf.log(x)\n denominator = tf.log(tf.constant(10, dtype=numerator.dtype))\n return numerator / denominator\n","sub_path":"CNNModel.py","file_name":"CNNModel.py","file_ext":"py","file_size_in_byte":4069,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"255184942","text":"#!/usr/bin/env python3\nimport numpy as np\nfrom scipy.sparse import diags\nfrom scipy.sparse.linalg import spsolve\nimport matplotlib.pyplot as plt\n\ndef u_exact(t, N = 1e4, dx = 0.01, L = 1):\n \"\"\"\n The analytical solution:\n \"\"\"\n N = int(N)\n\n x = np.linspace(0,1,int(1/dx), 'float')\n u_exact = x/L\n\n for n in np.arange(1, N+1):\n lmb = n*np.pi/L\n A_n = 2*(np.pi*n*np.cos(np.pi*n)-np.sin(np.pi*n))/(np.pi*n)**2\n u_exact += A_n * np.exp(-lmb**2*t)*np.sin(lmb*x)\n\n return u_exact\n\n\ndef solver(I ,dx, dt, T, theta = 1/2, save_solution = True, filename = 'u_aprox'):\n\n \"\"\"\n Numerically solves the 1D diffusion equation using finite difference method:\n u_t = u_xx\n\n With none-homegenus didrech boundary conditions:\n u(0,t) = 0 and u(1,t) = 1\n\n Initial condition:\n u(x,0) = I(x)\n\n The method for solving the PDE is determined by theta:\n Explicit forward euler: theta = 0\n Implicit backward euler: theta = 1\n Implicit Crank Nicolson scheme: theta = 1/2\n\n \"\"\"\n\n T = 1. # End time\n\n Nx = int(1/dx)\n Nt = int(T/dt)\n\n x = np.linspace(0,1,Nx)\n t = np.linspace(0,T,Nt)\n\n lmbd = dt/dx**2\n\n print('______________________________________________________________')\n if theta == 0: print('Explicit euler')\n elif theta == 1/2: print('Implicit Crank Nicolson scheme')\n elif theta == 1: print('Implicit backward euler')\n print( 'Lambda: ', round(lmbd,2) )\n print( 'dt = ' , dt)\n print( 'dx = ' , dx)\n print('______________________________________________________________')\n\n # setting up the linear system: Au = b\n # A (Tridiagonal matrix elements):\n\n upper = np.zeros(Nx-1)\n upper.fill(-lmbd*theta)\n\n lower = np.zeros(Nx-1)\n lower.fill(-lmbd*theta)\n\n diag = np.zeros(Nx)\n diag.fill(1+2*lmbd*theta)\n\n #modify the elements to fit the B.C.\n #diag[0] = 1\n diag[-1] = 1\n lower[-1] = 0\n\n A = diags(\n diagonals=[diag, lower, upper],\n offsets=[0, -1, 1], shape=(Nx, Nx),\n format='csr')\n\n print('A matrix: ')\n print (A.todense() ) # Check that A is correct\n print('')\n\n def calculate_b(u, theta, lmbd):\n size = len(u)\n\n b = np.zeros(len(u))\n b[0] = u[0]\n b[-1] = u[-1]\n\n for i in np.arange(1,size-1):\n b[i] = u[i] + lmbd*(1-theta)*(u[i+1]-2*u[i]+u[i-1])\n\n return b\n\n #b satisfying the initial condition:\n u = I(x)\n b = calculate_b(u, theta, lmbd)\n\n print('b matrix: ')\n print(b)\n\n # solve for each time step assert if numerical solution reaches a treshold\n u_aprox = np.zeros((Nt,Nx))\n\n u1 = np.zeros(Nx+1) # The next time step.\n\n for n in range(0,Nt):\n u = spsolve(A,b)\n\n u[0] = 0.0; u[-1] = 1.0 # updating boundary condtions\n\n u1 = u # reshuffle\n b = calculate_b(u, theta, lmbd)\n\n u_aprox[n] = u # store solutions to array.\n\n if save_solution == True:\n np.savetxt(filename +'.txt', u_aprox, delimiter = ' ') # save solution to file\n\n return u_aprox\n\n\nif __name__ == '__main__':\n\n def I(x):\n I = np.zeros(len(x))\n I[-1] = 1\n return I\n\n theta = 0\n dt = 0.001\n dx = 0.1\n\n u_aprox = solver(I ,dx = dx, dt = dt, T = 1, theta = theta)\n\n plt.figure()\n plt.plot(u_aprox[0])\n plt.plot(u_aprox[-1])\n plt.show()\n","sub_path":"Project5/main_code/python/universal_1D_solver.py","file_name":"universal_1D_solver.py","file_ext":"py","file_size_in_byte":3540,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"578296203","text":"#-------------------------------------------------------\n\nfrom linklist import linklist\nfrom choicelink import choicelink\nfrom fathermake import fathermake\nfrom xhtmlopen import xhtmlopen\nfrom washxhtml import washxhtml\nimport re\n\n#-------------------------------------------------------\n\nmother = 'http://www.aozora.gr.jp/'\nfatherfront = ''\nfatherrear = 'c'\nkeyinitial = 'index_pages/sakuhin'\nkeytitle = '../cards'\nkeyxhtml = '.files/'\nkeyxhtmlclass1 = 'div'\nkeyxhtmlclass2 = 'main_text'\n\ninitialfront = '\"'\ninitialrear = '\"'\ntitlefront = '/'\ntitlerear = '\"'\nxhtmlfront = '/'\nxhtmlrear = '\"'\n\nxhtml = None\n\n#-------------------------------------------------------\n\nlinklistinitial = linklist(mother, keyinitial)\nlinkinitial = choicelink(mother, linklistinitial, initialfront, initialrear)\n\nprint(linkinitial)\n\nlinklisttitle = linklist(linkinitial, keytitle)\nlinktitle = choicelink(mother, linklisttitle, titlefront, titlerear)\n\nprint(linktitle)\n\nfather = fathermake(linktitle, fatherfront, fatherrear)\n\nlinklistxhtml = linklist(linktitle, keyxhtml)\n\n\nwhile xhtml == None:\n linkxhtml = choicelink(father, linklistxhtml, xhtmlfront, xhtmlrear)\n print(linkxhtml)\n\n xhtml = xhtmlopen(linkxhtml, keyxhtmlclass1, keyxhtmlclass2)\n\nelse :\n print(xhtml)\n\n\nwashedxhtml = washxhtml(xhtml)\nprint(washedxhtml)\n\ntext = re.sub('\\([^\\)]*\\)', '', washedxhtml)\ncleantext = re.sub('[\\t\\n\\r\\f\\v]', 'kkk', text)\ncleantext = re.sub('\\u3000', ' ', text)\nText = re.findall('「([^」]*)」', cleantext)\n\nprint(text)\nprint(Text, len(Text))\n","sub_path":"lamourvole/linkxhtml.py","file_name":"linkxhtml.py","file_ext":"py","file_size_in_byte":1536,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"111343502","text":"import requests\r\nimport re\r\nfrom bs4 import BeautifulSoup\r\nfrom urllib.parse import urlencode\r\nimport json\r\nimport os\r\nimport csv\r\nfrom hashlib import md5\r\nfrom multiprocessing import Pool\r\nfrom json.decoder import JSONDecodeError\r\nfrom multiprocessing import Pool\r\n\r\n\r\nheaders = {\r\n 'Accept': '*/*',\r\n 'Accept-Encoding': 'gzip, deflate',\r\n 'Accept-Language': 'zh-CN,zh;q=0.9',\r\n 'Connection': 'keep-alive',\r\n 'Content-Length': '234',\r\n 'Content-Type': 'application/json',\r\n 'Cookie': 's_ViewType=10; _lxsdk_cuid=167a12e4c4cc8-0c6bd3ec1714d7-546f3a7b-13c680-167a12e4c4dc8; _lxsdk=167a12e4c4cc8-0c6bd3ec1714d7-546f3a7b-13c680-167a12e4c4dc8; _hc.v=7c0c148c-3496-0230-0e2b-c80fa9b780ca.1544597425; cityid=7; logan_custom_report=; pvhistory=6L+U5ZuePjo8L2Vycm9yL2Vycm9yX3BhZ2U+OjwxNTQ0NTk4MjA3NTE2XV9b; m_flash2=1; default_ab=shop%3AA%3A1%7Cindex%3AA%3A1%7CshopList%3AA%3A1; msource=default; logan_session_token=slcx73holc8vw6jy95gj; _lxsdk_s=167a17f2e94-3f3-3d6-7b5%7C%7C1116',\r\n 'Host': 'm.dianping.com',\r\n 'Origin': 'http://m.dianping.com',\r\n 'Referer': 'http://m.dianping.com/shenzhen/ch15',\r\n 'User-Agent': 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.102 Safari/537.36',\r\n # 'X-Requested-With': 'XMLHttpRequest',\r\n}\r\n\r\nheaders2 = {\r\n 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8',\r\n 'Accept-Encoding': 'gzip, deflate',\r\n 'Accept-Language': 'zh-CN,zh;q=0.9',\r\n 'Cache-Control': 'max-age=0',\r\n 'Connection': 'keep-alive',\r\n 'Cookie': 's_ViewType=10; _lxsdk_cuid=167a12e4c4cc8-0c6bd3ec1714d7-546f3a7b-13c680-167a12e4c4dc8; _lxsdk=167a12e4c4cc8-0c6bd3ec1714d7-546f3a7b-13c680-167a12e4c4dc8; _hc.v=7c0c148c-3496-0230-0e2b-c80fa9b780ca.1544597425; cityid=7; m_flash2=1; default_ab=shop%3AA%3A1%7Cindex%3AA%3A1%7CshopList%3AA%3A1; msource=default; logan_custom_report=; chwlsource=default; switchcityflashtoast=1; logan_session_token=vrfpm8u9ei59w1yizcb2; _lxsdk_s=167bffea304-84c-438-b1d%7C%7C197',\r\n 'Host': 'm.dianping.com',\r\n 'Referer': 'http://m.dianping.com/shenzhen/ch15/',\r\n 'Upgrade-Insecure-Requests': '1',\r\n 'User-Agent': 'Mozilla/5.0 (iPhone; CPU iPhone OS 11_0 like Mac OS X) AppleWebKit/604.1.38 (KHTML, like Gecko) Version/11.0 Mobile/15A372 Safari/604.1'\r\n\r\n}\r\n\r\ndef get_page_index(num):\r\n Payload = {\r\n 'moduleInfoList': [{'moduleName': 'mapiSearch',\r\n 'query':\r\n {'search':\r\n {\r\n 'categoryId': '15',\r\n 'cityId': '7',\r\n 'keyword': '',\r\n 'limit': '20',\r\n 'locateCityid': '0',\r\n 'maptype': '0',\r\n 'parentCategoryId': '15',\r\n 'regionId': '0',\r\n 'sortId': '0',\r\n 'start': str(num),\r\n }}\r\n }],\r\n 'pageEnName': 'shopList',\r\n }\r\n\r\n url = 'http://m.dianping.com/isoapi/module'\r\n resp = requests.post(url, data=json.dumps(Payload), headers=headers, allow_redirects=False)\r\n try:\r\n if resp.status_code == 200:\r\n return resp.text\r\n return None\r\n except ConnectionError:\r\n return None\r\n\r\ndef get_page_deatil(text):\r\n try:\r\n results = json.loads(text)\r\n print(results)\r\n\r\n if results and 'data' in results.keys():\r\n node_list = dict(results.get('data').get('moduleInfoList')[0]).get('moduleData').get('data').get(\r\n 'listData').get('list')\r\n # print(node_list)\r\n if node_list:\r\n for node in node_list:\r\n item = {}\r\n item['name'] = node['name']\r\n item['shopId'] = node['shopId']\r\n item['priceText'] = node['priceText']\r\n item['reviewCount'] = node['reviewCount']\r\n item['matchText'] = node['matchText']\r\n item['detail_url'] = 'http://m.dianping.com/shop/' + str(item['shopId'])\r\n yield item\r\n except JSONDecodeError:\r\n return None\r\n\r\ndef detail_parse(url):\r\n resp = requests.get(url, headers=headers2)\r\n try:\r\n if resp.status_code == 200:\r\n # print(resp.text)\r\n return resp.text\r\n return None\r\n except ConnectionError:\r\n return None\r\n\r\n\r\ndef detail_parse2(html, url, n, s, p, r, m):\r\n # pass\r\n item = []\r\n a = re.search(r'
    .*?.*?\"address\":\"(.*?)\"', html, re.S)\r\n if b and b is not None:\r\n b = b.group(1)\r\n\r\n item.append(a)\r\n item.append(b)\r\n item.append(url)\r\n item.append(n)\r\n item.append(s)\r\n item.append(p)\r\n item.append(r)\r\n item.append(m)\r\n\r\n print(item)\r\n\r\n\r\ndef main(num):\r\n text = get_page_index(num)\r\n if text:\r\n for item in get_page_deatil(text):\r\n if item['detail_url'] is not None:\r\n html = detail_parse(item['detail_url'])\r\n detail_parse2(html, item['detail_url'], item['name'], item['shopId'], item['priceText'], item['reviewCount'], item['matchText'])\r\n\r\n\r\nif __name__ == '__main__':\r\n pool = Pool()\r\n pool.map(main, [i*20 for i in range(1)])\r\n","sub_path":"Pscrapy/PycharmProjects/Reptile/ven/dzdp.py","file_name":"dzdp.py","file_ext":"py","file_size_in_byte":5761,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"} +{"seq_id":"370451059","text":"from django.contrib.contenttypes.models import ContentType\n\nfrom apps.annotations.models import Annotation\n\nfrom apps.annotations.graphql.types import mutation\n\n\n@mutation.field(\"addAnnotation\")\ndef resolve_add_annotation(_, info, app_name, model_name, object_id, contents):\n try:\n content_type = ContentType.objects.get(app_label=app_name, model=model_name)\n model = content_type.model_class()\n obj = model.objects.get(pk=object_id)\n except (ContentType.DoesNotExist, model.DoesNotExist):\n return None\n return obj.annotations.create(contents=contents)\n\n\n@mutation.field(\"updateAnnotation\")\ndef resolve_update_annotation(_, info, pk, contents, is_active):\n try:\n note = Annotation.objects.get(pk=pk)\n except Annotation.DoesNotExist:\n return None\n note.contents = contents\n note.is_active = is_active\n note.save()\n return note\n","sub_path":"apps/annotations/graphql/mutations.py","file_name":"mutations.py","file_ext":"py","file_size_in_byte":895,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"18"}