diff --git "a/5851.jsonl" "b/5851.jsonl" new file mode 100644--- /dev/null +++ "b/5851.jsonl" @@ -0,0 +1,229 @@ +{"seq_id":"382396493","text":"# -*- coding:utf-8 -*-\nfrom F2M_model import *\n\nfrom random import shuffle, random\nfrom collections import Counter\n\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport easydict\nimport os\n\nFLAGS = easydict.EasyDict({\"img_size\": 256, \n \n \"load_size\": 276,\n\n \"tar_size\": 256,\n\n \"tar_load_size\": 276,\n \n \"batch_size\": 1,\n \n \"epochs\": 200,\n\n \"epoch_decay\": 100,\n \n \"lr\": 0.0002,\n \n \"A_txt_path\": \"/yuwhan/yuwhan/Dataset/[2]Fourth_dataset/Generation/Morph/test_BM.txt\",\n \n \"A_img_path\": \"/yuwhan/yuwhan/Dataset/[1]Third_dataset/Morph/All/Crop_dlib/\",\n \n \"B_txt_path\": \"/yuwhan/yuwhan/Dataset/[2]Fourth_dataset/Generation/Morph/test_WM.txt\",\n \n \"B_img_path\": \"/yuwhan/yuwhan/Dataset/[1]Third_dataset/Morph/All/Crop_dlib/\",\n\n \"age_range\": [40, 64],\n\n \"n_classes\": 48,\n\n \"train\": True,\n \n \"pre_checkpoint\": False,\n \n \"pre_checkpoint_path\": \"/yuwhan/Edisk/yuwhan/Edisk/4th_paper/F2M_model_V19/checkpoint_final/75\",\n \n \"save_checkpoint\": \"/yuwhan/Edisk/yuwhan/Edisk/4th_paper/F2M_model_V19/checkpoint_final\",\n \n \"sample_images\": \"/yuwhan/Edisk/yuwhan/Edisk/4th_paper/F2M_model_V19/sample_images_final\",\n \n \"A_test_txt_path\": \"/yuwhan/yuwhan/Dataset/[2]Fourth_dataset/Generation/Morph/test_BM.txt\",\n \n \"A_test_img_path\": \"/yuwhan/yuwhan/Dataset/[1]Third_dataset/Morph/All/Crop_dlib/\",\n \n \"B_test_txt_path\": \"/yuwhan/yuwhan/Dataset/[2]Fourth_dataset/Generation/Morph/test_WM.txt\",\n \n \"B_test_img_path\": \"/yuwhan/yuwhan/Dataset/[1]Third_dataset/Morph/All/Crop_dlib/\",\n \n \"test_dir\": \"A2B\",\n \n \"fake_B_path\": \"/yuwhan/Edisk/yuwhan/Edisk/4th_paper/F2M_model_V19/fake_B_V23\",\n \n \"fake_A_path\": \"/yuwhan/Edisk/yuwhan/Edisk/4th_paper/F2M_model_V19/fake_A_V23\"})\n\nclass LinearDecay(tf.keras.optimizers.schedules.LearningRateSchedule):\n # if `step` < `step_decay`: use fixed learning rate\n # else: linearly decay the learning rate to zero\n\n def __init__(self, initial_learning_rate, total_steps, step_decay):\n super(LinearDecay, self).__init__()\n self._initial_learning_rate = initial_learning_rate\n self._steps = total_steps\n self._step_decay = step_decay\n self.current_learning_rate = tf.Variable(initial_value=initial_learning_rate, trainable=False, dtype=tf.float32)\n\n def __call__(self, step):\n self.current_learning_rate.assign(tf.cond(\n step >= self._step_decay,\n true_fn=lambda: self._initial_learning_rate * (1 - 1 / (self._steps - self._step_decay) * (step - self._step_decay)),\n false_fn=lambda: self._initial_learning_rate\n ))\n return self.current_learning_rate\nA_dataset = np.loadtxt(FLAGS.A_txt_path, dtype=np.int32, skiprows=0, usecols=1)\nB_dataset = np.loadtxt(FLAGS.B_txt_path, dtype=np.int32, skiprows=0, usecols=1)\nlen_dataset = min(len(A_dataset), len(B_dataset))\nG_lr_scheduler = LinearDecay(FLAGS.lr, FLAGS.epochs * len_dataset, FLAGS.epoch_decay * len_dataset)\nD_lr_scheduler = LinearDecay(FLAGS.lr, FLAGS.epochs * len_dataset, FLAGS.epoch_decay * len_dataset)\ng_optim = tf.keras.optimizers.Adam(G_lr_scheduler, beta_1=0.5)\nd_optim = tf.keras.optimizers.Adam(D_lr_scheduler, beta_1=0.5)\n\ndef input_func(A_data, B_data):\n\n A_img = tf.io.read_file(A_data[0])\n A_img = tf.image.decode_jpeg(A_img, 3)\n A_img = tf.image.resize(A_img, [FLAGS.load_size, FLAGS.load_size])\n A_img = tf.image.random_crop(A_img, [FLAGS.img_size, FLAGS.img_size, 3])\n A_img = A_img / 127.5 - 1.\n\n B_img = tf.io.read_file(B_data[0])\n B_img = tf.image.decode_jpeg(B_img, 3)\n B_img = tf.image.resize(B_img, [FLAGS.tar_load_size, FLAGS.tar_load_size])\n B_img = tf.image.random_crop(B_img, [FLAGS.tar_size, FLAGS.tar_size, 3])\n B_img = B_img / 127.5 - 1.\n\n if random() > 0.5:\n A_img = tf.image.flip_left_right(A_img)\n B_img = tf.image.flip_left_right(B_img)\n\n B_lab = int(B_data[1])\n A_lab = int(A_data[1])\n\n return A_img, A_lab, B_img, B_lab\n\ndef ref_input_map(input_list):\n img = tf.io.read_file(input_list)\n img = tf.image.decode_jpeg(img, 3)\n img = tf.image.resize(img, [FLAGS.load_size, FLAGS.load_size])\n img = tf.image.random_crop(img, [FLAGS.img_size, FLAGS.img_size, 3])\n img = tf.image.per_image_standardization(img)\n\n return img\n\ndef generate_ref_img(input):\n\n ref_generator = tf.data.Dataset.from_tensor_slices(input)\n ref_generator = ref_generator.map(ref_input_map)\n ref_generator = ref_generator.batch(1)\n ref_generator = ref_generator.prefetch(tf.data.experimental.AUTOTUNE)\n\n ref_it = iter(ref_generator)\n ref_img = 0.\n for i in range(len(input)):\n img = next(ref_it)\n ref_img += (img / tf.reduce_max(img, [0,1,2,3])) + tf.reduce_mean(img, [0,1,2,3]) + 0.2\n ref_img = ref_img / len(input)\n ref_img = tf.clip_by_value(ref_img, -1., 1.)\n\n return ref_img\n\ndef generated_attention_map(input):\n\n\n\n return map_img\n\n# @tf.function\ndef model_out(model, images, training=True):\n return model(images, training=training)\n\ndef increase_func(x):\n x = tf.cast(tf.maximum(1, x), tf.float32)\n return tf.math.log(x)\n\ndef cal_loss(A2B_model, B2A_model, DA_model, DB_model,\n A_batch_images, B_batch_images, B_batch_labels, A_batch_labels,\n A_ref, B_ref, A_N_buf, B_N_buf, fake_A_ref_img, fake_B_ref_img, count):\n \n with tf.GradientTape() as g_tape, tf.GradientTape() as d_tape:\n\n \n A_batch_label = A_batch_labels[0].numpy() - 16\n B_batch_label = B_batch_labels[0].numpy() - 16\n\n A_class_weights = A_N_buf[A_batch_label]\n B_class_weights = B_N_buf[B_batch_label]\n\n en_A_ref = tf.image.resize(A_ref, [64, 64])\n de_B_ref = tf.image.resize(B_ref, [64, 64])\n\n fake_B = model_out(A2B_model, [A_batch_images, B_ref, en_A_ref], True)\n fake_A_ = model_out(B2A_model, [fake_B, A_ref, de_B_ref], True)\n\n fake_A = model_out(B2A_model, [B_batch_images, A_ref, de_B_ref], True)\n fake_B_ = model_out(A2B_model, [fake_A, B_ref, en_A_ref], True)\n\n DB_real = model_out(DB_model, B_batch_images, True)\n DB_fake = model_out(DB_model, fake_B, True)\n DA_real = model_out(DA_model, A_batch_images, True)\n DA_fake = model_out(DA_model, fake_A, True)\n\n # DB_age_real = model_out(DB_age_model, B_batch_images, True)\n # DB_age_fake = model_out(DB_age_model, fake_B, True)\n # DA_age_real = model_out(DA_age_model, A_batch_images, True)\n # DA_age_fake = model_out(DA_age_model, fake_A, True)\n\n ################################################################################################\n # 나이에 대한 distance를 구하는곳\n age_loss = 0.\n for i in range(FLAGS.batch_size):\n energy_ft = (A_batch_images[i] - fake_B[i])**2\n energy_ft2 = (B_batch_images[i] - fake_A[i])**2\n\n realB_fakeB_loss = A_class_weights * tf.reduce_mean(energy_ft)\n realA_fakeA_loss = B_class_weights * tf.reduce_mean(energy_ft2)\n\n age_loss += realB_fakeB_loss + realA_fakeA_loss\n\n age_loss = age_loss / FLAGS.batch_size\n ################################################################################################\n # content loss 를 작성하자\n f_B = fake_B\n f_B_x, f_B_y = tf.image.image_gradients(f_B)\n f_B_m = tf.add(tf.abs(f_B_x), tf.abs(f_B_y))\n f_B = tf.abs(f_B - f_B_m)\n\n f_A = fake_A\n f_A_x, f_A_y = tf.image.image_gradients(f_A)\n f_A_m = tf.add(tf.abs(f_A_x), tf.abs(f_A_y))\n f_A = tf.abs(f_A - f_A_m)\n\n r_A = A_batch_images\n r_A_x, r_A_y = tf.image.image_gradients(r_A)\n r_A_m = tf.add(tf.abs(r_A_x), tf.abs(r_A_y))\n r_A = tf.abs(r_A - r_A_m)\n\n r_B = B_batch_images\n r_B_x, r_B_y = tf.image.image_gradients(r_B)\n r_B_m = tf.add(tf.abs(r_B_x), tf.abs(r_B_y))\n r_B = tf.abs(r_B - r_B_m)\n\n id_loss = B_class_weights * tf.reduce_mean(tf.abs(f_B - r_B)) * 5.0 \\\n + A_class_weights * tf.reduce_mean(tf.abs(f_A - r_A) * 5.0) # content loss # style이 아닌 skin 등등 이라고 가정\n # target될 영상을 만드는것이기에, 원본의 영상이 target으로 변할 때 배경 성분은 유지 되도록\n\n Cycle_loss = A_class_weights * (tf.reduce_mean(tf.abs(fake_A_ - A_batch_images))) \\\n * 10.0 + B_class_weights * (tf.reduce_mean(tf.abs(fake_B_ - B_batch_images))) * 10.0\n # Cycle을 하여 원본으로 갈때, Cycle된 이미지의 high freguency 성분이 원본 성분과 비슷해지도록\n\n G_gan_loss = A_class_weights * (tf.reduce_mean((DB_fake - tf.ones_like(DB_fake))**2) \\\n + B_class_weights * tf.reduce_mean((DA_fake - tf.ones_like(DA_fake))**2))\n\n Adver_loss = B_class_weights*(tf.reduce_mean((DB_real - tf.ones_like(DB_real))**2) + tf.reduce_mean((DB_fake - tf.zeros_like(DB_fake))**2)) / 2. \\\n + A_class_weights*(tf.reduce_mean((DA_real - tf.ones_like(DA_real))**2) + tf.reduce_mean((DA_fake - tf.zeros_like(DA_fake))**2)) / 2.\n\n if count % 10 == 0 and count != 0:\n distribution_loss = 10*tf.reduce_mean(tf.abs(fake_A_ref_img - A_ref)) + 10*tf.reduce_mean(tf.abs(fake_B_ref_img - B_ref))\n g_loss = Cycle_loss + G_gan_loss + id_loss + age_loss + distribution_loss\n else:\n g_loss = Cycle_loss + G_gan_loss + id_loss + age_loss\n\n d_loss = Adver_loss\n\n g_trainables_params = A2B_model.trainable_variables + B2A_model.trainable_variables\n d_trainables_params = DA_model.trainable_variables + DB_model.trainable_variables\n g_grads = g_tape.gradient(g_loss, g_trainables_params)\n d_grads = d_tape.gradient(d_loss, d_trainables_params)\n\n g_optim.apply_gradients(zip(g_grads, g_trainables_params))\n d_optim.apply_gradients(zip(d_grads, d_trainables_params))\n\n return g_loss, d_loss, age_loss\n\ndef match_age_images(a_images, a_labels, b_images, b_labels):\n\n #a = np.array([1,2,3,4,5])\n #for i in range(len(a)):\n # i = 0\n # a = np.delete(a, i)\n # print(a)\n # if len(a) == 1:\n # break\n\n a_images, a_labels, b_images, b_labels = np.array(a_images), np.array(a_labels), np.array(b_images), np.array(b_labels)\n\n A_images_buffer = []\n A_labels_buffer = []\n B_images_buffer = []\n B_labels_buffer = []\n \n for i in range(len(a_images)):\n i = 0\n for j in range(len(b_images)):\n if np.less_equal(tf.abs(a_labels[i] - b_labels[j]), 2):\n A_images_buffer.append(a_images[i])\n A_labels_buffer.append(a_labels[i])\n a_images = np.delete(a_images, i)\n a_labels = np.delete(a_labels, i)\n\n B_images_buffer.append(b_images[j])\n B_labels_buffer.append(b_labels[j])\n b_images = np.delete(b_images, j)\n b_labels = np.delete(b_labels, j)\n break\n\n\n A_images_buffer = np.array(A_images_buffer)\n A_labels_buffer = np.array(A_labels_buffer)\n B_images_buffer = np.array(B_images_buffer)\n B_labels_buffer = np.array(B_labels_buffer)\n print(len(A_images_buffer), len(A_labels_buffer), len(B_images_buffer), len(B_labels_buffer))\n\n return A_images_buffer, A_labels_buffer, B_images_buffer, B_labels_buffer\n\ndef main():\n pre_trained_encoder1 = tf.keras.applications.ResNet50V2(include_top=False, input_shape=(FLAGS.img_size, FLAGS.img_size, 3))\n pre_trained_encoder2 = tf.keras.applications.VGG16(include_top=False, input_shape=(FLAGS.img_size, FLAGS.img_size, 3))\n\n A2B_model = F2M_generator(input_shape=(FLAGS.img_size, FLAGS.img_size, 3),\n de_attention_shape=(FLAGS.img_size, FLAGS.img_size, 1))\n B2A_model = F2M_generator(input_shape=(FLAGS.img_size, FLAGS.img_size, 3),\n de_attention_shape=(FLAGS.img_size, FLAGS.img_size, 1))\n DA_model = F2M_discriminator(input_shape=(FLAGS.img_size, FLAGS.img_size, 3))\n DB_model = F2M_discriminator(input_shape=(FLAGS.img_size, FLAGS.img_size, 3))\n \n if FLAGS.pre_checkpoint:\n ckpt = tf.train.Checkpoint(A2B_model=A2B_model, B2A_model=B2A_model,\n DA_model=DA_model,\n DB_model=DB_model,\n g_optim=g_optim, d_optim=d_optim)\n ckpt_manager = tf.train.CheckpointManager(ckpt, FLAGS.pre_checkpoint_path, 5)\n if ckpt_manager.latest_checkpoint:\n ckpt.restore(ckpt_manager.latest_checkpoint)\n print(\"Restored!!\")\n else:\n A2B_model.get_layer(\"conv_en_1\").set_weights(pre_trained_encoder1.get_layer(\"conv1_conv\").get_weights())\n B2A_model.get_layer(\"conv_en_1\").set_weights(pre_trained_encoder1.get_layer(\"conv1_conv\").get_weights())\n \n A2B_model.get_layer(\"conv_en_3\").set_weights(pre_trained_encoder2.get_layer(\"block2_conv1\").get_weights())\n B2A_model.get_layer(\"conv_en_3\").set_weights(pre_trained_encoder2.get_layer(\"block2_conv1\").get_weights())\n\n A2B_model.get_layer(\"conv_en_5\").set_weights(pre_trained_encoder2.get_layer(\"block3_conv1\").get_weights())\n B2A_model.get_layer(\"conv_en_5\").set_weights(pre_trained_encoder2.get_layer(\"block3_conv1\").get_weights())\n\n A2B_model.summary()\n DA_model.summary()\n\n if FLAGS.train:\n count = 0\n\n A_images = np.loadtxt(FLAGS.A_txt_path, dtype=\" D vs B_images -> D ] , get near age\n\n else:\n B_images = np.loadtxt(FLAGS.B_test_txt_path, dtype=\"= 0) :\n if(timestamp in d) :\n return d[timestamp]\n timestamp = timestamp - 1\n return \"\" \n\n\n\n# Your TimeMap object will be instantiated and called as such:\n# obj = TimeMap()\n# obj.set(key,value,timestamp)\n# param_2 = obj.get(key,timestamp)","sub_path":"981.py","file_name":"981.py","file_ext":"py","file_size_in_byte":939,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"115352015","text":"from astropy.io import fits\nfrom astropy.table import Table\nimport matplotlib.pyplot as plt\nimport matplotlib.cbook as cbook\nimport numpy as np\nimport matplotlib.mlab as mlab\nimport math as m\nimport pdb\nimport scipy.stats as scs\n\n#test the effect of spectral index\n\n#read in data\ndata0=np.arange(2E5)*1./1E5+1.\nprint(data0)\n\n#data=np.random.choice(data0,size=20000,p=np.log(3)*1./data0)\n\ndata=scs.powerlaw.rvs(0.0001,size=2000)*1E4\n\nprint(data0)\nprint(data)\n\n#create poisson array\npo1=np.random.poisson(lam=1.,size=1E6)\npo2=np.random.poisson(lam=0.1,size=1E6)\npo3=np.random.poisson(lam=0.01,size=1E6)\npo4=np.random.poisson(lam=0.001,size=3E6)\n\npu1=np.zeros(1e6)\npu2=np.zeros(1e6)\npu3=np.zeros(1e6)\npu4=np.zeros(3e6)\nprint(np.min(po2))\n\n\nii=0\nj=0\nfor i in np.arange(np.size(po1)): \n# print('haha ',po1[i])\n k=0\n if po1[i] > 0 and j < np.size(data)-1:\n print('ca',po1[i])\n while (k < po1[i] and j+k < np.size(data)-1):\n pu1[ii]=pu1[ii]+data[j+k]\n print(ii,j,k)\n k=k+1\n print(k)\n j=j+k\n ii=ii+1\nprint(j)\nii=0\nj=0\nfor i in np.arange(np.size(po2)):\n k=0\n if po2[i] > 0 and j < np.size(data)-1:\n while (k < po2[i] and j+k < np.size(data)-1):\n pu2[ii]=pu2[ii]+data[j+k]\n k=k+1\n# print('yi?',j,po2[i])\n j=j+k\n ii=ii+1\nprint(j)\n\nprint(data[0:20])\nprint(po1[0:20])\nprint(pu1[0:20])\n\n\n\nii=0\nj=0\nfor i in np.arange(np.size(po3)):\n k=0\n if po3[i] > 0 and j < np.size(data)-1:\n while (k < po3[i] and j+k < np.size(data)-1):\n pu3[ii]=pu3[ii]+data[j+k]\n k=k+1\n j=j+k\n ii=ii+1\nprint(j)\n\nii=0\nj=0\nfor i in np.arange(np.size(po4)):\n k=0\n if po4[i] > 0 and j < np.size(data)-1:\n while (k < po4[i] and j+k < np.size(data)-1):\n pu4[ii]=pu4[ii]+data[j+k]\n #print('heihei ',ii,j,k,i)\n k=k+1\n j=j+k\n ii=ii+1\nprint(j)\n\n\nprint('heihei',np.where(pu1 > 0))\nprint(data)\n\npu1=pu1[np.where(pu1 > 0.)]\npu2=pu2[np.where(pu2 > 0.)]\npu3=pu3[np.where(pu3 > 0.)]\npu4=pu4[np.where(pu4 > 0.)]\nprint(po1)\nprint(np.min(po1))\n\n\n\n#plot spectrum\nplt.figure('histogram')\nee=data\nhiste,be = np.histogram(ee,bins=20)\nben=np.array(be[:20])+0.05\nnum_bins=20\nn = plt.hist(ee, num_bins)\n\nee=pu1\nhiste1,be = np.histogram(ee,bins=20)\nben1=np.array(be[:20])+0.05\nnum_bins=20\nprint(pu1)\n#pdb.set_trace()\nn = plt.hist(ee, num_bins)\n\nee=pu2\nhiste2,be = np.histogram(ee,bins=20)\nben2=np.array(be[:20])+0.05\nnum_bins=20\nn = plt.hist(ee, num_bins)\n\nee=pu3\nhiste3,be = np.histogram(ee,bins=20)\nben3=np.array(be[:20])+0.05\nnum_bins=20\nn = plt.hist(ee, num_bins)\n\nee=pu4\nhiste4,be = np.histogram(ee,bins=20)\nben4=np.array(be[:20])+0.05\nnum_bins=20\nn = plt.hist(ee, num_bins)\n\n\n#plot spectrum in log scale\nlbe=np.log(ben)\nlhiste=np.log(histe)\nplt.figure(\"flux-log-zoom\")\nplt.axis=([0.,1.2,0.,7.])\n#plt.axis.set_autoscale_on(False)\n\n\nline,=plt.plot(lbe,lhiste,marker='o',color='k',linestyle='-',linewidth=3,label='data',)\n\n#linear fit to the data in log scale \nindf=np.isfinite(lhiste)\nlhiste=lhiste[indf]\nlbe=lbe[indf]\nxiao=np.where(lbe < np.log(3.))\nlbe=lbe[xiao]\nlhiste=lhiste[xiao]\npp=np.polyfit(lbe,lhiste,1)\nline2,=plt.plot(lbe,lbe*pp[0]+pp[1],'-',color='r')\nplt.ylabel('flux')\nplt.xlabel('photon energy')\nplt.legend()\nprint('parameters: ',pp)\n\n\n#plot spectrum in log scale\nlbe=np.log(ben1)\nlhiste=np.log(histe1)\nline,=plt.plot(lbe,lhiste,marker='o',color='b',linestyle='-',linewidth=3,label='data_1us')\n#linear fit to the data in log scale \n\nindf=np.isfinite(lhiste)\nlhiste=lhiste[indf]\nlbe=lbe[indf]\nxiao=np.where(lbe < np.log(3.))\nlbe=lbe[xiao]\nlhiste=lhiste[xiao]\n\npp=np.polyfit(lbe,lhiste,1)\nline2,=plt.plot(lbe,lbe*pp[0]+pp[1],'-',color='r')\nplt.ylabel('flux')\nplt.xlabel('photon energy')\nplt.legend()\nprint('parameter2s: ',pp)\n\nlbe=np.log(ben2)\nlhiste=np.log(histe2)\nline,=plt.plot(lbe,lhiste,marker='o',color='c',linestyle='-',linewidth=3,label='data_10us')\n#linear fit to the data in log scale \nindf=np.isfinite(lhiste)\nlhiste=lhiste[indf]\nlbe=lbe[indf]\nxiao=np.where(lbe < np.log(3.))\nlbe=lbe[xiao]\nlhiste=lhiste[xiao]\n\npp=np.polyfit(lbe,lhiste,1)\nline2,=plt.plot(lbe,lbe*pp[0]+pp[1],'-',color='r')\nplt.ylabel('flux')\nplt.xlabel('photon energy')\nplt.legend(loc=0)\nprint('parameters: ',pp)\n#pp2, pp3=scs.linregress(lbe,lhiste)\n#line3,=plt.plot(lbe,lbe*pp2+pp3,'-',color='g',label='fit2')\n\nlbe=np.log(ben3)\nlhiste=np.log(histe3)\nline,=plt.plot(lbe,lhiste,marker='o',color='y',linestyle='-',linewidth=3,label='data_100us')\n#linear fit to the data in log scale \nindf=np.isfinite(lhiste)\nlhiste=lhiste[indf]\nlbe=lbe[indf]\nxiao=np.where(lbe < np.log(3.))\nlbe=lbe[xiao]\nlhiste=lhiste[xiao]\npp=np.polyfit(lbe,lhiste,1)\nline2,=plt.plot(lbe,lbe*pp[0]+pp[1],'-',color='r')\nplt.ylabel('flux')\nplt.xlabel('photon energy')\nplt.legend()\nprint('parameters: ',pp)\n#pp2, pp3=scs.linregress(lbe,lhiste)\n#line3,=plt.plot(lbe,lbe*pp2+pp3,'-',color='g',label='fit2')\n\n#plot spectrum in log scale\nlbe=np.log(ben4)\nlhiste=np.log(histe4)\nline,=plt.plot(lbe,lhiste,marker='o',color='g',linestyle='-',linewidth=3,label='data_1000us')\n#linear fit to the data in log scale \nindf=np.isfinite(lhiste)\nlhiste=lhiste[indf]\nlbe=lbe[indf]\nxiao=np.where(lbe < np.log(3.))\nlbe=lbe[xiao]\nlhiste=lhiste[xiao]\npp=np.polyfit(lbe,lhiste,1)\nline2,=plt.plot(lbe,lbe*pp[0]+pp[1],'-',color='r',label='fit')\nplt.ylabel('flux')\nplt.xlabel('photon energy')\nplt.legend()\nprint('parameters: ',pp)\n\n\n\n\n#plt.axis=([0.,1.2,0.,7.])\n\n\nplt.show()\n\n#test effect of spectral index\n\n\n\n\n","sub_path":"pileup4.py","file_name":"pileup4.py","file_ext":"py","file_size_in_byte":5518,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"396269282","text":"import numpy as np\n\ndef loss_func(h_x,y,theta,lam):\n a = -y*np.log(h_x)\n b = (1-y)*np.log(1-h_x)\n c = (lam/(2*len(h_x)))*np.sum(theta[1:]**2)\n return (np.sum(a-b)/len(h_x)) + c\n\nclass ScratchLogisticRegression():\n \"\"\"\n ロジスティック回帰のスクラッチ実装\n\n Parameters\n ----------\n num_iter : int\n イテレーション数\n lr : float\n 学習率\n no_bias : bool\n バイアス項を入れない場合はTrue\n verbose : bool\n 学習過程を出力する場合はTrue\n\n Attributes\n ----------\n self.coef_ : 次の形のndarray, shape (n_features,)\n パラメータ\n self.loss : 次の形のndarray, shape (self.iter,)\n 訓練データに対する損失の記録\n self.val_loss : 次の形のndarray, shape (self.iter,)\n 検証データに対する損失の記録\n\n \"\"\"\n def __init__(self,num_iter=1000,lam=1e-3,lr=1e-2,bias=True, verbose=False,name=\"empty\"):\n # ハイパーパラメータを属性として記録\n self.iter = num_iter\n self.lr = lr\n self.bias = bias\n self.verbose = verbose\n self.lam = lam\n #すでに使ったことのあるクラスだった場合にnameにクラス名をstr型で指定すると,\n #filesにあるバイナリファイ��からすでに計算済みのθを取ってくる.\n save_filename = \"files/\"+name+\".npz\"\n #バイナリファイルからndarray読み込み\n if name == \"empty\":\n self.theta = np.empty(1)\n else:\n self.theta = np.load(save_filename)[name]\n # 損失を記録する配列を用意\n self.loss = np.zeros(self.iter)\n self.val_loss = np.zeros(self.iter)\n def fit(self, X, y, X_val=np.empty(1), y_val=np.empty(1)):\n \"\"\"\n ロジスティック回帰を学習する。検証データが入力された場合はそれに対する損失と精度もイテレーションごとに計算する。\n\n Parameters\n ----------\n X : 次の形のndarray, shape (n_samples, n_features)\n 訓練データの特徴量\n y : 次の形のndarray, shape (n_samples, )\n 訓練データの正解値\n X_val : 次の形のndarray, shape (n_samples, n_features)\n 検証データの特徴量\n y_val : 次の形のndarray, shape (n_samples, )\n 検証データの正解値\n \"\"\"\n #訓練用データ、検証用データの形を整える\n if y.ndim == 1: #yが1次元のとき\n self.y = y[:,np.newaxis] #_linear_hypothesisの返り値(行列)にサイズを合わせるためreshapeする\n else:\n self.y = y\n self.y_val = y_val\n if self.bias == True: #バイアス項がある時\n if X.ndim == 1: #1次元の時(2次元であればここはスルー)\n X = X[:,np.newaxis] #バイアス項と結合できるようにXを2次元に変形\n self.X = np.concatenate([np.ones(X.shape[0])[:,np.newaxis],X],axis=1) #バイアス項を結合\n if(len(X_val) != 1) & (len(y_val) != 1): #検証データが入力された場合(入力されない場合は何もしない)\n if X_val.ndim == 1: #検証データが1次元の時\n X_val = X_val[:,np.newaxis] #バイアス項と結合できるようにXを2次元に変形\n self.X_val = np.concatenate([np.ones(X_val.shape[0])[:,np.newaxis],X_val],axis=1) #バイアス項を結合\n\n else: #バイアス項がない時\n if X.ndim ==1: #Xが1次元の時\n self.X = X[:,np.newaxis]\n self.X_val = X_val[:,np.newaxis]\n else: #Xが2次元の時\n self.X = X\n self.X_val = X_val\n\n #ここから計算\n if (len(X_val) != 1) & (len(y_val) != 1): #検証データが入力された場合\n error = self._gradient_descent(self.X)\n self.loss[0] = loss_func(self.predict(self.X),y,self.theta,self.lam)\n self.val_loss[0] = loss_func(self.predict(self.X_val),y_val,self.theta,self.lam)\n for i in range(self.iter-1): #iter-1回,_gradient_descentを実行する\n error = self._gradient_descent(self.X,error)\n self.loss[i+1] = loss_func(self.predict_proba(self.X),self.y,self.theta,self.lam)\n self.val_loss[i+1] = loss_func(self.predict_proba(self.X_val),self.y_val,self.theta,self.lam)\n if self.verbose:\n #verboseをTrueにした際は学習過程を出力\n print(\"{}回目\".format(i+1))\n print(\"theta:{}\".format(self.theta))\n print(\"損失:{}\".format(self.val_loss[i+1]))\n print(\"精度(平均2乗誤差):{}\\n\".format(MSE(self.predict(self.X_val),self.y_val)))\n else: #検証データが入力されない場合\n error = self._gradient_descent(self.X)\n self.loss[0] = loss_func(self.predict(self.X),y,self.theta,self.lam)\n self.val_loss[0] = loss_func(self.predict(self.X_val),y_val,self.theta,self.lam)\n for i in range(self.iter-1):\n error = self._gradient_descent(self.X,error)\n self.loss[i+1] = loss_func(self.predict_proba(self.X),self.y,self.theta,self.lam)\n self.val_loss[i+1] = loss_func(self.predict_proba(self.X_val),self.y_val,self.theta,self.lam)\n if self.verbose:\n #verboseをTrueにした際は学習過程を出力\n print(\"{}回目\".format(i+1))\n print(\"theta:\\n{}\".format(self.theta))\n\n def _gradient_descent(self, X,error=np.empty(1)):\n \"\"\"\n θとXを用いて次のθを計算する\n Parameters\n ----------\n X : 次の形のndarray, shape (n_samples, n_features)\n 訓練データの特徴量\n\n error:次の形のndarray,shape (n_samples,)\n 予測値と正解値の残差\n --------\n Returns\n --------\n 次の形のndarray,shape(n_samples,)\n 予測値と正解値の残差\n \"\"\"\n if error.shape == (1,): #errorが渡されていない���\n #θが与えられていない時だけ初期化する\n if self.theta.shape == (1,):\n self.theta = np.ones(X.shape[1]).reshape(1,-1) #θを1で初期化\n error = (self._linear_hypothesis(X) - self.y).reshape(1,-1)\n else: #errorが渡されている時\n error = (self.predict_proba(X) - self.y).flatten()\n if self.bias == True: #バイアス項がある場合\n self.theta[0,0] = self.theta[0,0]- (self.lr/X.shape[0])*error@self.X[:,0]\n self.theta[0,1:] = self.theta[0,1:] - (self.lr/X.shape[0])*error@self.X[:,1:]+ (self.lam/X.shape[0])*self.theta[0,1:]\n else: #バイアス項がない場合\n self.theta = self.theta - (self.lr/X.shape[0])*error@self.X+ (self.lam/X.shape[0])*self.theta\n return error\n\n def _linear_hypothesis(self, X):\n \"\"\"\n 線形の仮定関数を計算する\n Parameters\n ----------\n X : 次の形のndarray, shape (n_samples, n_features)\n 訓練データ\n Returns\n -------\n 次の形のndarray, shape (n_samples, 1)\n 線形の仮定関数による推定結果\n \"\"\"\n if X.ndim == 1: #Xが1次元の時\n X = X[:,np.newaxis] #2次元に変形\n if (X.shape[1] != self.theta.T.shape[0])&(self.bias==True):\n #x_0が含まれていない状態でXを受け取り(外部からのメソッド呼び出しを想定)、かつバイアス項を使う時\n X = np.concatenate([np.ones(X.shape[0])[:,np.newaxis],X],axis=1)\n return np.dot(X,self.theta.T)\n\n def predict(self, X):\n \"\"\"\n ロジスティック回帰を使いラベルを推定する。\n\n Parameters\n ----------\n X : 次の形のndarray, shape (n_samples, n_features)\n サンプル\n\n Returns\n -------\n 次の形のndarray, shape (n_samples, 1)\n ロジスティック回帰による推定結果\n \"\"\"\n #閾値を設定\n threshold = 0.5\n X_pred = self.predict_proba(X).flatten()\n X_pred[X_pred=threshold] = 1\n return X_pred\n def predict_proba(self, X):\n \"\"\"\n ロジスティック回帰を使い確率を推定する。\n\n Parameters\n ----------\n X : 次の形のndarray, shape (n_samples, n_features)\n サンプル\n\n Returns\n -------\n 次の形のndarray, shape (n_samples, 1)\n ロジスティック回帰による推定結果\n \"\"\"\n\n return 1/(1+np.exp(-self._linear_hypothesis(X)))\n","sub_path":"Logistic_Regression/scratch_logistic_regression.py","file_name":"scratch_logistic_regression.py","file_ext":"py","file_size_in_byte":8997,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"131431588","text":"from conftest import QL_URL\nimport pytest\nimport requests\nimport time\nimport urllib\nfrom .utils import send_notifications\n\n\ndef mk_entity(eid, entity_type, attr_name):\n return {\n 'id': eid,\n 'type': entity_type,\n attr_name: {\n 'type': 'Text',\n 'value': 'test'\n }\n }\n\n\ndef insert_entity(entity):\n notification_data = [{'data': [entity]}]\n send_notifications(notification_data)\n\n time.sleep(2)\n\n\ndef query_entity(entity_id, attr_name):\n escaped_attr_name = urllib.parse.quote(attr_name)\n url = \"{}/entities/{}/attrs/{}\".format(QL_URL, entity_id, escaped_attr_name)\n response = requests.get(url)\n assert response.status_code == 200\n return response.json().get('data', {})\n\n\ndef delete_entities(entity_type):\n delete_url = \"{}/types/{}\".format(QL_URL, entity_type)\n response = requests.delete(delete_url)\n assert response.ok\n\n\ndef run_test(entity_type, attr_name):\n entity = mk_entity('d1', entity_type, attr_name)\n\n insert_entity(entity)\n\n query_result = query_entity(entity['id'], attr_name)\n query_result.pop('index', None)\n assert query_result == {\n 'attrName': attr_name,\n 'entityId': entity['id'],\n 'values': [entity[attr_name]['value']]\n }\n\n delete_entities(entity['type'])\n\n\nodd_chars = ['-', '+', '@', ':']\n# Note that you can't use certain chars at all, even if quoted. Three\n# such chars are '.', '#' and ' '. So for example, CrateDB bombs out\n# on `create table \"x.y\" (...)` or `create table \"x y\" (...)`\n\n\n@pytest.mark.parametrize('char', odd_chars)\ndef test_odd_char_in_entity_type(char, clean_mongo, clean_crate):\n entity_type = 'test{}device'.format(char)\n attr_name = 'plain_name'\n run_test(entity_type, attr_name)\n\n\n@pytest.mark.parametrize('char', odd_chars)\ndef test_odd_char_in_attr_name(char, clean_mongo, clean_crate):\n entity_type = 'test_device'\n attr_name = 'weird{}name'.format(char)\n run_test(entity_type, attr_name)\n\n\n@pytest.mark.parametrize('char', odd_chars)\ndef test_odd_char_in_entity_type_and_attr_name(char, clean_mongo, clean_crate):\n entity_type = 'test{}device'.format(char)\n attr_name = 'weird{}name'.format(char)\n run_test(entity_type, attr_name)\n","sub_path":"src/reporter/tests/test_entities_with_odd_chars.py","file_name":"test_entities_with_odd_chars.py","file_ext":"py","file_size_in_byte":2243,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"240306491","text":"'''\r\nCreated on Nov 18, 2011\r\n\r\n@author: Arif\r\n'''\r\nfrom django.shortcuts import render_to_response\r\nfrom django.contrib.auth.decorators import login_required\r\nfrom django.template import RequestContext\r\nfrom django.http import HttpResponse\r\n\r\n@login_required\r\ndef test_plot(request):\r\n import matplotlib\r\n from mpl_toolkits.basemap import Basemap\r\n import numpy as np\r\n from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas\r\n from matplotlib.figure import Figure\r\n \r\n # llcrnrlat,llcrnrlon,urcrnrlat,urcrnrlon\r\n # are the lat/lon values of the lower left and upper right corners\r\n # of the map.\r\n # lat_ts is the latitude of true scale.\r\n # resolution = 'c' means use crude resolution coastlines.\r\n \r\n# #mercator\r\n# m = Basemap(projection='merc',llcrnrlat=-80,urcrnrlat=80,llcrnrlon=-180,urcrnrlon=180,lat_ts=20,resolution='c')\r\n \r\n\r\n m = Basemap(width=36000000,height=27000000,rsphere=(6378137.00,6356752.3142),\r\n resolution='l',area_thresh=1000.,projection='lcc',\r\n lat_1=30.,lat_0=0.,lon_0=0.)\r\n \r\n fig = Figure()\r\n canvas = FigureCanvas(fig)\r\n m.ax = fig.add_axes([0, 0, 1, 1])\r\n \r\n# m.bluemarble(scale=0.5)\r\n m.drawcoastlines()\r\n m.drawmapboundary(fill_color='aqua') \r\n m.fillcontinents(color='coral',lake_color='aqua')\r\n m.drawparallels(np.arange(-90.,91.,30.))\r\n m.drawmeridians(np.arange(-180.,181.,60.))\r\n \r\n response = HttpResponse(content_type='image/png')\r\n canvas.print_figure(response, dpi=100)\r\n return response\r\n\r\n@login_required\r\ndef mercator(request):\r\n import matplotlib\r\n from mpl_toolkits.basemap import Basemap\r\n import numpy as np\r\n from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas\r\n from matplotlib.figure import Figure\r\n \r\n upper_lat = float(request.GET.get('upper_lat', 20))\r\n upper_lon = float(request.GET.get('upper_lon', 145))\r\n lower_lat = float(request.GET.get('lower_lat',-20))\r\n lower_lon = float(request.GET.get('lower_lon',90))\r\n true_lat = float(request.GET.get('true_lat',5))\r\n \r\n draw_ref_point = False\r\n try:\r\n ref_lat = float(request.GET.get('ref_lat'))\r\n ref_lon = float(request.GET.get('ref_lon'))\r\n draw_ref_point = True\r\n except:\r\n pass\r\n \r\n m = Basemap(projection='merc',llcrnrlat=lower_lat,urcrnrlat=upper_lat,\r\n llcrnrlon=lower_lon,urcrnrlon=upper_lon,lat_ts=true_lat,\r\n resolution=None)\r\n \r\n fig = Figure()\r\n canvas = FigureCanvas(fig)\r\n m.ax = fig.add_axes([0, 0, 1, 1])\r\n \r\n# m.drawcoastlines()\r\n# m.drawmapboundary(fill_color='aqua') \r\n# m.fillcontinents(color='coral',lake_color='aqua')\r\n# m.etopo()\r\n m.drawlsmask(land_color='gray',ocean_color='white',lakes=True)\r\n m.drawparallels(np.arange(-90.,91.,30.), color='black')\r\n m.drawmeridians(np.arange(-180.,181.,60.), color='black')\r\n \r\n if draw_ref_point:\r\n x, y = m(ref_lon, ref_lat)\r\n m.plot(x, y, 'ro')\r\n \r\n response = HttpResponse(content_type='image/png')\r\n canvas.print_figure(response, dpi=100)\r\n return response\r\n\r\n@login_required\r\ndef lambert_conformal(request):\r\n import matplotlib\r\n from mpl_toolkits.basemap import Basemap\r\n import numpy as np\r\n from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas\r\n from matplotlib.figure import Figure\r\n \r\n width = float(request.GET.get('width', 6000000))\r\n height = float(request.GET.get('height', 4500000))\r\n lat = float(request.GET.get('lat',-7))\r\n lon = float(request.GET.get('lon',107))\r\n true_lat1 = float(request.GET.get('true_lat1',5))\r\n true_lat2 = float(request.GET.get('true_lat2',5))\r\n \r\n m = Basemap(width=width,height=height,\r\n rsphere=(6378137.00,6356752.3142),\\\r\n resolution=None,projection='lcc',\\\r\n lat_1=true_lat1,lat_2=true_lat2,lat_0=lat,lon_0=lon)\r\n \r\n fig = Figure()\r\n canvas = FigureCanvas(fig)\r\n m.ax = fig.add_axes([0, 0, 1, 1])\r\n \r\n m.drawlsmask(land_color='gray',ocean_color='white',lakes=True)\r\n m.drawparallels(np.arange(-90.,91.,30.), color='black')\r\n m.drawmeridians(np.arange(-180.,181.,60.), color='black')\r\n \r\n x, y = m(lon, lat)\r\n m.plot(x, y, 'ro')\r\n \r\n response = HttpResponse(content_type='image/png')\r\n canvas.print_figure(response, dpi=100)\r\n return response\r\n","sub_path":"aqm_web/views/plot.py","file_name":"plot.py","file_ext":"py","file_size_in_byte":4445,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"554095574","text":"# -*- coding: utf-8 -*-\n\n\"\"\"\nMIT License\n\nCopyright (c) 2019 mathsman5133\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\"\"\"\n\nfrom datetime import datetime\n\nfrom .enums import LabelType\nfrom .utils import from_timestamp\n\n\ndef try_enum(_class, data, default=None, **kwargs):\n if data is None:\n return default\n return _class(data=data, **kwargs)\n\n\nclass EqualityComparable:\n __slots__ = ()\n\n def __eq__(self, other):\n return isinstance(self, other.__class__) and self._data == other._data\n\n def __hash__(self):\n return hash(len(self._data))\n\n\nclass Achievement(EqualityComparable):\n \"\"\"Represents a Clash of Clans Achievement.\n\n\n Attributes\n -----------\n player:\n :class:`SearchPlayer` - The player this achievement is assosiated with\n name:\n :class:`str` - The name of the achievement\n stars:\n :class:`int` - The current stars achieved for the achievement\n value:\n :class:`int` - The number of X things attained for this achievement\n target:\n :class:`int` - The number of X things required to complete this achievement\n info:\n :class:`str` - Information regarding the achievement\n completion_info:\n :class:`str` - Information regarding completion of the achievement\n village:\n :class:`str` - Either `home` or `builderBase`\n \"\"\"\n\n __slots__ = ('player', 'name', 'stars', 'value', 'target',\n 'info', 'completion_info', 'village', '_data')\n\n def __str__(self):\n return self.name\n\n def __repr__(self):\n attrs = [\n ('player', repr(self.player)),\n ('name', self.name),\n ('stars', self.stars),\n ('value', self.value)\n ]\n return '<%s %s>' % (self.__class__.__name__, ' '.join('%s=%r' % t for t in attrs))\n\n def __init__(self, *, data, player):\n self._data = data\n\n self.player = player\n self.name = data['name']\n self.stars = data.get('stars')\n self.value = data['value']\n self.target = data['target']\n self.info = data['info']\n self.completion_info = data.get('completionInfo')\n self.village = data['village']\n\n @property\n def is_builder_base(self):\n \"\"\":class:`bool`: Helper property to tell you if the achievement belongs to the builder base\n \"\"\"\n return self.village == 'builderBase'\n\n @property\n def is_home_base(self):\n \"\"\":class:`bool`: Helper property to tell you if the achievement belongs to the home base\n \"\"\"\n return self.village == 'home'\n\n @property\n def is_completed(self):\n \"\"\":class:`bool`: Indicates whether the achievement is completed (3 stars achieved)\n i\"\"\"\n return self.stars == 3\n\n\nclass Troop(EqualityComparable):\n \"\"\"Represents a Clash of Clans Troop.\n\n Attributes\n -----------\n player:\n :class:`SearchPlayer` - player this troop is assosiated with\n name:\n :class:`str` - The name of the troop\n level:\n :class:`int` - The level of the troop\n max_level:\n :class:`int` - The overall max level of the troop, excluding townhall limitations\n village:\n :class:`str` - Either `home` or `builderBase`\n \"\"\"\n __slots__ = ('player', 'name', 'level',\n 'max_level', 'village', '_data')\n\n def __str__(self):\n return self.name\n\n def __repr__(self):\n attrs = [\n ('player', repr(self.player)),\n ('name', self.name),\n ('level', self.level)\n ]\n return '<%s %s>' % (self.__class__.__name__, ' '.join('%s=%r' % t for t in attrs))\n\n def __init__(self, *, data, player):\n self._data = data\n\n self.player = player\n self.name = data['name']\n self.level = data['level']\n self.max_level = data['maxLevel']\n self.village = data['village']\n\n @property\n def is_max(self):\n \"\"\":class:`bool`: Helper property to tell you if the troop is the max level\n \"\"\"\n return self.max_level == self.level\n\n @property\n def is_builder_base(self):\n \"\"\":class:`bool`: Helper property to tell you if the troop belongs to the builder base\n \"\"\"\n return self.village == 'builderBase'\n\n @property\n def is_home_base(self):\n \"\"\":class:`bool`: Helper property to tell you if the troop belongs to the home base\n \"\"\"\n return self.village == 'home'\n\n\nclass Hero(EqualityComparable):\n \"\"\"Represents a Clash of Clans Hero.\n\n Attributes\n -----------\n player:\n :class:`SearchPlayer` - The player this hero is assosiated with\n name:\n :class:`str` - The name of the hero\n level:\n :class:`int` - The level of the hero\n max_level:\n :class:`int` - The overall max level of the hero, excluding townhall limitations\n village:\n :class:`str` - Either `home` or `builderBase`\n \"\"\"\n __slots__ = ('player', 'name', 'level',\n 'max_level', 'village', '_data')\n\n def __str__(self):\n return self.name\n\n def __repr__(self):\n attrs = [\n ('player', repr(self.player)),\n ('name', self.name),\n ('level', self.level)\n ]\n return '<%s %s>' % (self.__class__.__name__, ' '.join('%s=%r' % t for t in attrs))\n\n def __init__(self, *, data, player):\n self._data = data\n\n self.player = player\n self.name = data['name']\n self.level = data['level']\n self.max_level = data['maxLevel']\n self.village = data['village']\n\n @property\n def is_max(self):\n \"\"\":class:`bool`: Helper property to tell you if the hero is the max level\n \"\"\"\n return self.level == self.max_level\n\n @property\n def is_builder_base(self):\n \"\"\":class:`bool`: Helper property to tell you if the hero belongs to the builder base\n \"\"\"\n return self.village == 'builderBase'\n\n @property\n def is_home_base(self):\n \"\"\":class:`bool`: Helper property to tell you if the hero belongs to the home base\n \"\"\"\n return self.village == 'home'\n\n\nclass Spell(EqualityComparable):\n \"\"\"Represents a Clash of Clans Spell.\n\n Attributes\n -----------\n player:\n :class:`SearchPlayer` - The player this spell is assosiated with\n name:\n :class:`str` - The name of the spell\n level:\n :class:`int` - The level of the spell\n max_level:\n :class:`int` - The overall max level of the spell, excluding townhall limitations\n village:\n :class:`str` - Either `home` or `builderBase`\n \"\"\"\n __slots__ = ('player', 'name', 'level',\n 'max_level', 'village', '_data')\n\n def __str__(self):\n return self.name\n\n def __repr__(self):\n attrs = [\n ('player', repr(self.player)),\n ('name', self.name),\n ('level', self.level)\n ]\n return '<%s %s>' % (self.__class__.__name__, ' '.join('%s=%r' % t for t in attrs))\n\n def __init__(self, *, data, player):\n self._data = data\n\n self.player = player\n self.name = data['name']\n self.level = data['level']\n self.max_level = data['maxLevel']\n self.village = data['village']\n\n @property\n def is_max(self):\n \"\"\":class:`bool`: Helper property to tell you if the spell is the max level\n \"\"\"\n return self.max_level == self.level\n\n @property\n def is_builder_base(self):\n \"\"\":class:`bool`: Helper property to tell you if the spell belongs to the builder base\n \"\"\"\n return self.village == 'builderBase'\n\n @property\n def is_home_base(self):\n \"\"\":class:`bool`: Helper property to tell you if the spell belongs to the home base\n \"\"\"\n return self.village == 'home'\n\n\nclass Location(EqualityComparable):\n \"\"\"Represents a Clash of Clans Location\n\n Attributes\n -----------\n id:\n :class:`str` - The location ID\n name:\n :class:`str` - The location name\n is_country:\n :class:`bool` - Indicates whether the location is a country\n country_code:\n :class:`str` - The shorthand country code, if the location is a country\n localised_name:\n :class:`str` - A localised name of the location. The extent of the use of this is unknown at present.\n \"\"\"\n __slots__ = ('id', 'name', 'is_country', 'country_code', 'localised_name', '_data')\n\n def __str__(self):\n return self.name\n\n def __repr__(self):\n attrs = [\n ('id', self.id),\n ('name', self.name),\n ]\n return '<%s %s>' % (self.__class__.__name__, ' '.join('%s=%r' % t for t in attrs))\n\n def __init__(self, *, data):\n self._data = data\n\n self.id = data.get('id')\n self.name = data.get('name')\n self.is_country = data.get('isCountry')\n self.country_code = data.get('countryCode')\n self.localised_name = data.get('localizedName')\n\n\nclass League(EqualityComparable):\n \"\"\"Represents a Clash of Clans League\n\n Attributes\n -----------\n id:\n :class:`str` - The league ID\n name:\n :class:`str` - The league name\n localised_name:\n :class:`str` - A localised name of the location. The extent of the use of this is unknown at present.\n localised_short_name:\n :class:`str` - A localised short name of the location. The extent of the use of this is unknown at present.\n \"\"\"\n __slots__ = ('id', 'name', 'localised_short_name', 'localised_name', '_data', '_http')\n\n def __str__(self):\n return self.name\n\n def __repr__(self):\n attrs = [\n ('id', self.id),\n ('name', self.name)\n ]\n return '<%s %s>' % (self.__class__.__name__, ' '.join('%s=%r' % t for t in attrs))\n\n def __init__(self, *, data, http):\n self._data = data\n self._http = http\n\n self.id = data.get('id')\n self.name = data.get('name')\n self.localised_name = data.get('localizedName')\n self.localised_short_name = data.get('localizedShortName')\n\n @property\n def badge(self):\n \"\"\":class:`Badge`: The league's badge\n \"\"\"\n return try_enum(Badge, data=self._data.get('iconUrls'), http=self._http)\n\n\nclass Season(EqualityComparable):\n \"\"\"Represents a Clash of Clans Player's Season.\n\n rank: \"\"\"\n __slots__ = ('rank', 'trophies', 'id')\n\n def __init__(self, *, data):\n self.rank = data.get('rank')\n self.trophies = data.get('trophies')\n self.id = data.get('id')\n\n\nclass LegendStatistics(EqualityComparable):\n \"\"\"Represents the Legend Statistics for a player.\n\n Attributes\n -----------\n player:\n :class:`Player` - The player\n legend_trophies:\n :class:`int` - The player's legend trophies\n \"\"\"\n __slots__ = ('player', 'legend_trophies', '_data')\n\n def __repr__(self):\n attrs = [\n ('player', repr(self.player)),\n ('legend_trophies', self.legend_trophies)\n ]\n return '<%s %s>' % (self.__class__.__name__, ' '.join('%s=%r' % t for t in attrs))\n\n def __init__(self, *, data, player):\n self._data = data\n\n self.player = player\n self.legend_trophies = data['legendTrophies']\n\n @property\n def current_season(self):\n \"\"\":class:`int`: Legend trophies for this season.\n \"\"\"\n return try_enum(Season, data=self._data.get('currentSeason'))\n\n @property\n def previous_season(self):\n \"\"\":class:`int`: Legend trophies for the previous season.\n \"\"\"\n return try_enum(Season, data=self._data.get('previousSeason'))\n\n @property\n def best_season(self):\n \"\"\":class:`int`: Legend trophies for the player's best season.\n \"\"\"\n return try_enum(Season, data=self._data.get('bestSeason'))\n\n\nclass Badge(EqualityComparable):\n \"\"\"Represents a Clash Of Clans Badge.\n\n Attributes\n -----------\n small:\n :class:`str` - URL for a small sized badge\n medium:\n :class:`str` - URL for a medium sized badge\n large:\n :class:`str` - URL for a large sized badge\n url:\n :class:`str` - Medium, the default URL badge size\n \"\"\"\n __slots__ = ('small', 'medium', 'large', 'url', '_data', '_http')\n\n def __repr__(self):\n attrs = [\n ('url', self.url),\n ]\n return '<%s %s>' % (self.__class__.__name__, ' '.join('%s=%r' % t for t in attrs))\n\n def __init__(self, *, data, http):\n self._http = http\n self._data = data\n\n self.small = data.get('small')\n self.medium = data.get('medium')\n self.large = data.get('large')\n\n self.url = self.medium\n\n async def save(self, fp, size=None):\n \"\"\"This function is a coroutine. Save this badge as a file-like object.\n\n :param fp: :class:`os.PathLike`\n The filename to save the badge to\n :param size: Optional[:class:`str`] Either `small`, `medium` or `large`.\n The default is `medium`\n\n :raise HTTPException: Saving the badge failed\n\n :raise NotFound: The url was not found\n\n :return: :class:`int` The number of bytes written\n \"\"\"\n sizes = {'small': self.small,\n 'medium': self.medium,\n 'large': self.large}\n\n if size and size in sizes.keys():\n url = sizes[size]\n else:\n url = self.medium\n\n data = self._http.get_data_from_url(url)\n\n with open(fp, 'wb') as f:\n return f.write(data)\n\n\nclass Timestamp(EqualityComparable):\n \"\"\"Represents a Clash of Clans Timestamp\n\n Attributes\n -----------\n raw_time: :class:`str`: The raw timestamp string (ISO8601) as given by the API.\n \"\"\"\n __slots__ = ('raw_time', '_data')\n\n def __repr__(self):\n attrs = [\n ('time', self.raw_time),\n ('seconds_until', self.seconds_until)\n ]\n return '<%s %s>' % (self.__class__.__name__, ' '.join('%s=%r' % t for t in attrs))\n\n def __init__(self, *, data):\n self._data = data\n self.raw_time = data\n\n @property\n def time(self):\n \"\"\":class:`datetime`: The timestamp as a UTC datetime object\n \"\"\"\n return from_timestamp(self.raw_time)\n\n @property\n def now(self):\n \"\"\":class:`datetime`: The time in UTC now as a datetime object\n \"\"\"\n return datetime.utcnow()\n\n @property\n def seconds_until(self):\n \"\"\":class:`int`: Number of seconds until the timestamp. This may be negative.\n \"\"\"\n delta = self.time - self.now\n return delta.total_seconds()\n\n\nclass Label(EqualityComparable):\n \"\"\"Represents a clan or player label.\n\n Attributes\n -----------\n id: :class:`int`: The label's unique ID as given by the API.\n name: :class:`str`: The label's name.\n \"\"\"\n __slots__ = ('_data', 'id', 'name', '_http', 'label_type')\n\n def __repr__(self):\n attrs = [\n ('id', self.id),\n ('name', self.name)\n ]\n return '<%s %s>' % (self.__class__.__name__, ' '.join('%s=%r' % t for t in attrs))\n\n def __init__(self, *, data, http, label_type: LabelType):\n self._http = http\n self._data = data\n\n self.id = data.get('id')\n self.name = data.get('name')\n self._data[\"iconUrls\"] = label_type.value[self.id]\n\n @property\n def badge(self):\n \"\"\":class:`Badge` - The label's badge.\"\"\"\n\n return try_enum(Badge, self._data.get('iconUrls'), http=self._http)\n","sub_path":"coc/miscmodels.py","file_name":"miscmodels.py","file_ext":"py","file_size_in_byte":16576,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"371499747","text":"import numpy as np\nimport netCDF4\nfrom netCDF4 import Dataset\nfrom numpy.random import uniform\n\nph_rate_n2 = np.zeros([20,50,1,1])\nplev = np.zeros([50])\ni = 0\nfor zenith in range(0,100,5):\n fname = netCDF4.Dataset('/Users/eecwk/work/sp_uv_chris/trop_1b_%sz_sg.ph_rate_6' %zenith, 'r', format='NETCDF4')\n ph_rate_n2[i,:,:,:] = fname.variables['ph_rate_6'][:]\n i += 1\nph_rate_n2 = ph_rate_n2[:,:,0,0]\nplevs = fname.variables['plev'][:]\nfname.close()\nszas = np.arange(0,100,5)\n\n# Create netCDF\ndataset = Dataset('/Users/eecwk/work/n2_ph_rate.nc', 'w', format='NETCDF4')\n\n# Define variable dimensions\nsza = dataset.createDimension('sza', 20)\nplev = dataset.createDimension('plev', 50)\n\n# Create the actual 2-d variable\nJ_N2 = dataset.createVariable('J_N2', np.float64, ('sza', 'plev'))\n\n# Create coordinate varialbes for 2-dimensions\nsza = dataset.createVariable('sza', np.float32, ('sza'))\nplev = dataset.createVariable('plev', np.float32, ('plev'))\n\n# Variable attributes\nJ_N2.title = 'N2 -> N2+'\nJ_N2.long_name = 'N2 -> N2+'\nJ_N2.units = ''\n\nsza.title = 'solar zenith angle'\nsza.long_name = 'solar zenith angle'\nsza.units = 'degree'\n\nplev.title = 'pressure'\nplev.long_name = 'pressure'\nplev.units = 'pa'\n\n# Writing data\nsza[:] = szas\nplev[:] = plevs\n\nnszas = len(dataset.dimensions['sza']) \nnplevs = len(dataset.dimensions['plev'])\n\nJ_N2[:,:] = uniform(size=(nszas,nplevs))\nJ_N2[:,:] = ph_rate_n2\n \n# Write the file\ndataset.close()","sub_path":"group_ph_rates.py","file_name":"group_ph_rates.py","file_ext":"py","file_size_in_byte":1443,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"127545234","text":"def limit(iterator, count):\n \"\"\"\n A filter that removes all elements behind the set limit.\n\n :param iterator: The iterator to be filtered.\n :param count: The iterator limit. All elements at positions bigger than\n this limit are trimmed off. Exclusion: 0 or numbers below\n does not limit at all, means the passed iterator is\n completely yielded.\n \"\"\"\n if count <= 0: # Performance branch\n for elem in iterator:\n yield elem\n else:\n for elem in iterator:\n yield elem\n count -= 1\n if count == 0:\n break\n\n\ndef trim_empty_matches(iterator, groups=(0,)):\n \"\"\"\n A filter that removes empty match strings. It can only operate on iterators\n whose elements are of type MatchObject.\n\n :param iterator: The iterator to be filtered.\n :param groups: An iteratable defining the groups to check for blankness.\n Only results are not yielded if all groups of the match\n are blank.\n You can not only pass numbers but also strings, if your\n MatchObject contains named groups.\n \"\"\"\n for elem in iterator:\n if any(len(elem.group(group)) > 0 for group in groups):\n yield elem\n","sub_path":"ve/Lib/site-packages/coala_utils/string_processing/Filters.py","file_name":"Filters.py","file_ext":"py","file_size_in_byte":1331,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"304909267","text":"\r\nimport random\r\nimport time\r\nimport math\r\nimport psutil\r\n\r\n\r\ndef Fitness(guess):\r\n fitness = 0\r\n for i in range(len(guess)):\r\n if guess[i] == proof[i]:\r\n fitness+=1\r\n return fitness\r\n\r\n\r\n\r\ndef acceptance_probability(temperature):\r\n return math.exp(temperature/(1+temperature))\r\n\r\n\r\n\r\ndef get_neighbor(parent):\r\n index = random.randrange(0, len(parent))\r\n # turn the parent characters into a list\r\n childChars = list(parent)\r\n # pick 2 random characters from the possible set of genes\r\n newChar, alternate = random.sample(gSet, 2)\r\n # print (gSet)\r\n # replace the index character with one of the randomly found genes\r\n childChars[index] = alternate if newChar == childChars[index] else newChar\r\n #chars = ''.join(childChars)\r\n # get the fitness of the newly generated character set\r\n #fitness = Fitness(childChars)\r\n #return Guess(chars, fitness)\r\n\r\n #print(childChars)\r\n return (childChars)\r\n\r\n\r\n\r\ndef anneal(parent, temperature, min_temp, alpha):\r\n geneTime = time.time()\r\n cc=0\r\n arcount=0\r\n # print (alpha)\r\n\r\n #make the random initial guess\r\n # bestGuess = generate_guess(targetLen, charSet, get_fitness)\r\n #display(bestGuess)\r\n best_fitness = Fitness(parent)\r\n #If best_fitn guess is already perfect then no need to go on with the search!\r\n if best_fitness >= optimalFitness:\r\n # print (\"AR Count: \", arcount)\r\n # print(\"AR Count: \", arcount)\r\n return cc, parent #best_fitness#Guess\r\n #Set the temperatures\r\n T = temperature\r\n T_min = min_temp\r\n #until the temperature reaches the minimum, search!\r\n while T > T_min:\r\n cc = cc+1\r\n if cc % 500 == 0:\r\n print('count', cc, Fitness(parent), (time.time()-totalstartTime))\r\n new_solution = get_neighbor(parent)\r\n new_fitness = Fitness(new_solution)\r\n # print (\"NNS: \", new_solution)\r\n # print (\"FFNS: \", new_fitness)\r\n # x=input()\r\n #If the generated neighbor is already good, return it.\r\n if new_fitness == optimalFitness:\r\n # print (\"AR Count: \",arcount)\r\n # print(\"AR Count: \", arcount)\r\n\r\n return cc, new_solution\r\n #If the generated neighbor is better, move on to it.\r\n if new_fitness > best_fitness:\r\n #bestGuess = new_solution #BCBCBCBC\r\n parent = new_solution #BCBCBCBC\r\n best_fitness = new_fitness\r\n # print(time.time() - geneTime, end=',')\r\n geneTime = time.time()\r\n\r\n else:\r\n ar = acceptance_probability(T)\r\n #let the acceptance rate recommend whether to switch to the worse or not.\r\n if ar > random.uniform(2.71825400004040,6.71825464604849): #bad one\r\n # if ar > random.uniform(2.71820060604849, 2.71825464604849):\r\n parent = new_solution\r\n best_fitness = new_fitness\r\n arcount = arcount + 1\r\n #the temperature decreases\r\n T = T*alpha\r\n # print(\"BG11:\", bestGuess)\r\n# #display(bestGuess)\r\n # print(\"BG:\", bestGuess)\r\n # print(\"BG:\", bestGuess)\r\n# print(\"AR Count: \", arcount)\r\n\r\n return cc, parent\r\n#pid = psutil.Process(os.getpgid())\r\n#print(pid.memory_info().rss)# str(os.getpgid())\r\n#status = os.system('cat /proc' +pid + 'status')\r\n#print(status)\r\n\r\n\r\nrandom.seed()\r\n#starttime = time.time()\r\nSTime = time.time()\r\ntimee = time.process_time()\r\nfits = []\r\nlastt = []\r\ncount=0\r\ntotalCount=0\r\nite = []\r\ntotalstartTime = time.time()\r\n\r\nwith open(\"Population.txt\", 'r') as f: #tokenize all the words in file guru99 into set 'a','b'\r\n p = f.read()\r\n gSet = p.split()\r\n #print(gSet)\r\n\r\nwith open(\"PD.txt\", 'r') as f:\r\n for line in f: #all the lines in f (proofs.txt)\r\n timee += timee\r\n timings = []\r\n for i in range(1):\r\n startTime = time.time()\r\n proof = line.split() #tokenize each word within a line\r\n length = len(proof)\r\n #length of that word in line\r\n optimalFitness = len(proof)\r\n # print(\"OS:\", proof)\r\n #print(\"OSL:\", len(proof))\r\n g1 = [] #to save first generation randomely from Parent generation\r\n #g2 = [] #to save second generation randomely from Parent generation\r\n\r\n while len(g1) < len(proof):\r\n sSize = min(length - len(g1), len(gSet))\r\n g1.extend(random.sample(gSet, sSize))\r\n #g2.extend(random.sample(gSet, sSize))\r\n randSample = list(g1)\r\n #i2 = list(g2)\r\n# print(\"RS:\", randSample)\r\n #print(\"OSL:\", len(i1))\r\n # print(Fitness(g1))\r\n randSampleFit= Fitness(randSample)\r\n\r\n #print('Random sequence:', len(randSample))\r\n # print(\"SRS:\", len(randSample))\r\n T_max = 100000.0\r\n T_min = 0.00001\r\n alpha = 0.99954001\r\n# alpha = 0.9992\r\n #count=0\r\n #Results(randSample, timings)\r\n count, randSample=anneal(randSample, T_max, T_min, alpha)\r\n print('Count', count)\r\n totalCount = totalCount+count\r\n #res = Results(randSample, timings)\r\n #mea = timings\r\n #lt = mea[-1]\r\n # print(\"LT:\", mea)\r\n # lastt.append(lt)\r\n # lasttt = numpy.array(lastt)\r\n #print(\"Time:\", mea)\r\n #print('TotalllllCount', totalCount)\r\n #if totalIterations % 500 == 0:\r\n # print(totalIterations, pBest)\r\n\r\n# print (count, end=',')\r\n\r\n # print(time.time() - startTime)\r\n\r\n# print(\"NS:\", randSample)\r\n #print(\"FNS:\", neighborSampleFit)\r\n\r\n #print(\"SNS:\", len(neighborSample))\r\n\r\n # best = anneal(g1, 100000.0, 0.00001, 0.09 )\r\n\r\n# child = mutate(bParent)\r\n# cFitness = Fitness(child)\r\n\r\nprint(\"Total TimeSA:\", time.time() - totalstartTime)\r\nprint(\"Total Count\", totalCount, Fitness(randSample))\r\nmem = psutil.virtual_memory() # .total / (1024.0 ** 2)\r\nprint(\"Memory Used in Mb:\", mem.used >> 20)","sub_path":"code/SA.py","file_name":"SA.py","file_ext":"py","file_size_in_byte":6184,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"631397541","text":"import numpy as np\nimport math\nimport scipy\n\n\ndef Optomech(params):\n wm=params['wm'] #frequenza oscillatore meccanico presa unitaria\n k=params['k']*wm #accoppiamento luce ambiente \n y=params['y']*wm #accoppiamento mech ambiente\n eta=params['eta'] #efficienza misura su bagno luce\n g=params['g']*wm #accoppiamento ML\n detuning=params['detuning']*wm#1,-1,0\n ne=params['ne'] #numero di fononi meccanici\n na=params['na'] #numero fononi ottici\n phi=params['phi'] #LO phase\n \n cos=np.around(math.cos(phi),15)\n sin=np.around(math.sin(phi),15)\n\n A=np.array([[-y/2,-wm,0,0],[wm,-y/2,g,0],[0,0,-k/2,detuning],[g,0,-detuning,-k/2]])#il detuning di hammerer è definito al contrario\n D=np.array([[(1+2*ne)*y,0,0,0],[0,(1+2*ne)*y,0,0],[0,0,(1+2*na)*k,0],[0,0,0,(1+2*na)*k]])\n eta=(eta/(1+2*na*eta))**0.5\n b=-(((k*eta)**0.5))\n B=b*np.array([[0,0,0,0],[0,0,0,0],[0,0,cos**2,cos*sin],[0,0,sin*cos,sin**2]])\n E=(1+2*na)*B\n\n return A,D,B,E\n\ndef Cavity(params): #questo è meno dettagliato dell'optomeccanica\n \n k=params['k'] #loss rate\n eta=params['eta'] #eta della misura\n X=params['X_kunit']*k #accoppiamento hamiltoniana del sistema \n a=-(X+k/2)\n b=X-k/2\n A=np.array([[a,0],[0,b]])\n D=k*np.identity(2)\n d=-(eta*k)**0.5\n B=d*np.array([[1,0],[0,0]])\n E=B\n\n return A,D,B,E\n\ndef Fisher(params): #questo è meno dettagliato dell'optomeccanica\n theta=params['theta']#parameter to estimate\n k=params['k'] #loss rate\n eta=params['eta'] #eta della misura\n X=params['X_kunit']*k #accoppiamento hamiltoniana del sistema \n a=-(X+k/2)\n b=X-k/2\n A=np.array([[a,0],[0,b]])\n A=A+theta*np.array([[0,1],[-1,0]])\n deA=np.array([[0,1],[-1,0]])\n D=k*np.identity(2)\n d=-(eta*k)**0.5\n B=d*np.array([[1,0],[0,0]])\n E=B\n\n return A,deA,D,B,E\n \n","sub_path":"Fisher_nocost/Matrices.py","file_name":"Matrices.py","file_ext":"py","file_size_in_byte":1841,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"415226083","text":"#!/usr/bin/env python\n# coding: utf-8\nfrom django.template import Template, Context\n\nfrom table.columns import Column\nfrom table.utils import Accessor\n\n\nclass BoolColumn(Column):\n def __init__(self, field=None, header=None, *args, **kwargs):\n kwargs[\"sortable\"] = False\n kwargs[\"searchable\"] = False\n super(BoolColumn, self).__init__(field, header, *args, **kwargs)\n\n def render(self, obj, user=None):\n text = Accessor(self.field).resolve(obj)\n html = '= 10:\n raise Exception('Page overflow')\n\n url = 'https://www.yoytec.com/lg-m-32.html?page={}'.format(page)\n response = session.get(url)\n soup = BeautifulSoup(response.text, 'html5lib')\n container = soup.find('div', {'id': 'tabs-2'})\n items = container.findAll('div', 'product_block')\n\n for item in items:\n product_url = item.find(\n 'a', 'product_img')['href'].split('?')[0]\n\n if product_url in product_urls:\n done = True\n break\n\n product_urls.append(product_url)\n\n page += 1\n\n return product_urls\n\n @classmethod\n def products_for_url(cls, url, category=None, extra_args=None):\n print(url)\n session = session_with_proxy(extra_args)\n response = session.get(url)\n\n if response.status_code == 404:\n return []\n\n soup = BeautifulSoup(response.text, 'html5lib')\n\n name = soup.find('h1', 'name').text.strip()\n sku = soup.find('div', 'listing').find('td', 'td_right').text.strip()\n stock_cells = soup.find('div', 'listing').findAll(\n 'table')[1].findAll('td', 'td_right')[1::2]\n\n stock = 0\n\n for stock_cell in stock_cells:\n if 'Agotado' in stock_cell.text:\n continue\n\n if stock_cell.text == '10+':\n stock = -1\n break\n\n stock += int(stock_cell.text.split()[0])\n\n price = Decimal(soup.find('span', 'productSpecialPrice').text\n .replace(',', '').replace('$', ''))\n description = html_to_markdown(str(soup.find('div', 'description')))\n\n image_containers = soup.findAll('li', 'wrapper_pic_div')\n picture_urls = []\n\n for image in image_containers:\n picture_url = image.find('a')['href'].replace(' ', '%20')\n picture_urls.append(picture_url)\n\n p = Product(\n name,\n cls.__name__,\n category,\n url,\n url,\n sku,\n stock,\n price,\n price,\n 'USD',\n sku=sku,\n description=description,\n picture_urls=picture_urls\n )\n\n return [p]\n","sub_path":"storescraper/stores/yoytec.py","file_name":"yoytec.py","file_ext":"py","file_size_in_byte":3003,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"606759674","text":"def NBAccuracy(features_train, labels_train, features_test, labels_test):\r\n \"\"\" compute the accuracy of your Naive Bayes classifier \"\"\"\r\n ### import the sklearn module for GaussianNB\r\n from sklearn.naive_bayes import GaussianNB\r\n\r\n \r\n clf = GaussianNB()\r\n clf.fit(features_train, labels_train)\r\n \r\n ### use the trained classifier to predict labels for the test features\r\n pred = clf.predict(features_test)\r\n \r\n correct = 0\r\n for i in range(0,len(pred)):\r\n if pred[i] == labels_test[i]:\r\n correct = correct+1\r\n accuracy = correct/len(pred)\r\n return accuracy","sub_path":"unordered/Classify.py","file_name":"Classify.py","file_ext":"py","file_size_in_byte":616,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"551722758","text":"import warnings\nimport numpy as np\n\n\ndef get_clp_mapping_from_tc_mapping(tc_mapping):\n \"\"\"\n Get a CHECLabPy mapping dataframe from a TargetCalib Mapping class,\n along with the metadata\n\n Parameters\n ----------\n tc_mapping : `target_calib.Mapping`\n\n Returns\n -------\n df : `pandas.DataFrame`\n\n \"\"\"\n df = tc_mapping.as_dataframe()\n with warnings.catch_warnings():\n warnings.simplefilter('ignore', UserWarning)\n df.metadata = dict(\n cfgfile=tc_mapping.GetCfgPath(),\n is_single_module=tc_mapping.IsSingleModule(),\n n_pixels=tc_mapping.GetNPixels(),\n n_modules=tc_mapping.GetNModules(),\n n_tmpix=tc_mapping.GetNTMPix(),\n n_superpixels=tc_mapping.GetNSuperPixels(),\n n_rows=tc_mapping.GetNRows(),\n n_columns=tc_mapping.GetNColumns(),\n size=tc_mapping.GetSize(),\n fOTUpRow_l=tc_mapping.fOTUpRow_l,\n fOTUpRow_u=tc_mapping.fOTUpRow_u,\n fOTUpCol_l=tc_mapping.fOTUpCol_l,\n fOTUpCol_u=tc_mapping.fOTUpCol_u,\n fOTUpX_l=tc_mapping.fOTUpX_l,\n fOTUpX_u=tc_mapping.fOTUpX_u,\n fOTUpY_l=tc_mapping.fOTUpY_l,\n fOTUpY_u=tc_mapping.fOTUpY_u\n )\n return df\n\n\ndef get_clp_mapping_from_version(version, single_module=False):\n from target_calib import CameraConfiguration\n tc_mapping = CameraConfiguration(version).GetMapping(\n singleModule=single_module\n )\n return get_clp_mapping_from_tc_mapping(tc_mapping)\n\n\ndef get_ref_path_from_version(version):\n from target_calib import CameraConfiguration\n ref_path = CameraConfiguration(version).GetReferencePulsePath()\n return ref_path\n\n\ndef get_tc_mapping_from_clp_mapping(mapping):\n \"\"\"\n Get a TargetCalib Mapping class from a CHECLabPy mapping dataframe\n\n Parameters\n ----------\n mapping : `pandas.DataFrame`\n The CHECLabPy dataframe representation of the mapping\n\n Returns\n -------\n tc_mapping : `target_calib.Mapping`\n\n \"\"\"\n from target_calib import Mapping\n cfgfile = mapping.metadata.cfgfile\n is_single_module = mapping.metadata.is_single_module\n return Mapping(cfgfile, is_single_module)\n\n\ndef get_superpixel_mapping(mapping):\n \"\"\"\n Reorganise a CHECLabPy mapping dataframe to represent the positions of the\n superpixels on the camera\n\n Parameters\n ----------\n mapping : `pandas.DataFrame`\n The CHECLabPy dataframe representation of the mapping\n\n Returns\n -------\n `pandas.DataFrame`\n\n \"\"\"\n df = mapping[['superpixel', 'slot', 'asic', 'row', 'col', 'xpix', 'ypix']]\n f_rowcol = lambda v: v.values[0] // 2\n f = dict(slot='first', asic='first', row=f_rowcol, col=f_rowcol,\n xpix='mean', ypix='mean')\n df = df.groupby('superpixel').agg(f).reset_index()\n with warnings.catch_warnings():\n warnings.simplefilter('ignore', UserWarning)\n df.metadata = mapping.metadata.copy()\n df.metadata['n_rows'] = df['row'].max() + 1\n df.metadata['n_columns'] = df['col'].max() + 1\n df.metadata['size'] *= 2\n return df\n\n\ndef get_tm_mapping(mapping):\n \"\"\"\n Reorganise a CHECLabPy mapping dataframe to represent the positions of the\n TMs on the camera\n\n Parameters\n ----------\n mapping : `pandas.DataFrame`\n The CHECLabPy dataframe representation of the mapping\n\n Returns\n -------\n `pandas.DataFrame`\n\n \"\"\"\n df = mapping[['slot', 'row', 'col', 'xpix', 'ypix']]\n f_rowcol = lambda v: v.values[0] // 8\n f = dict(row=f_rowcol, col=f_rowcol, xpix='mean', ypix='mean')\n df = df.groupby('slot').agg(f, as_index=False).reset_index()\n with warnings.catch_warnings():\n warnings.simplefilter('ignore', UserWarning)\n df.metadata = mapping.metadata.copy()\n df.metadata['n_rows'] = df['row'].max() + 1\n df.metadata['n_columns'] = df['col'].max() + 1\n df.metadata['size'] *= 8\n return df\n\n\ndef get_ctapipe_camera_geometry(mapping, plate_scale=None):\n \"\"\"\n Obtain a ctapipe CameraGeometry object from the CHECLabPy Mapping object.\n\n Pixel coordinates are converted into degrees using the plate scale.\n\n Parameters\n ----------\n mapping : `pandas.DataFrame`\n The mapping for the pixels stored in a pandas DataFrame. Can be\n obtained from either of these options:\n\n CHECLabPy.io.TIOReader.mapping\n CHECLabPy.io.ReaderR0.mapping\n CHECLabPy.io.ReaderR1.mapping\n CHECLabPy.io.DL1Reader.mapping\n CHECLabPy.utils.mapping.get_clp_mapping_from_tc_mapping\n\n Returns\n -------\n geom : `ctapipe.instrument.camera.CameraGeometry`\n \"\"\"\n from ctapipe.instrument import CameraGeometry\n from astropy import units as u\n\n if plate_scale:\n mapping['xpix'] /= plate_scale\n mapping['ypix'] /= plate_scale\n mapping.metadata['size'] /= plate_scale\n\n camera = CameraGeometry(\n \"CHEC\",\n pix_id=np.arange(mapping.metadata['n_pixels']),\n pix_x=mapping['xpix'].values * u.m,\n pix_y=mapping['ypix'].values * u.m,\n pix_area=None,\n pix_type='rectangular',\n )\n return camera\n","sub_path":"CHECLabPy/utils/mapping.py","file_name":"mapping.py","file_ext":"py","file_size_in_byte":5176,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"276868236","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# @Time : 2020/06/03\n# @Company : INVINCIBLE STUDIO\n# @Author : Sun Jing\n# @Email : jing.sun4@ubisoft.com\n# @File : alignObjectController.py\n\n\nfrom Core.MayaGUI.LitFrame.controller import Controller\n\n\nclass AlignObjectController(Controller):\n @property\n def _viewInstance(self):\n import alignObjectView\n reload(alignObjectView)\n return alignObjectView.AlignObjectView()\n\n @property\n def _modelInstance(self):\n import alignObjectModel\n reload(alignObjectModel)\n return alignObjectModel.AlignObjectModel()\n\n @property\n def _view2ModelMsg(self):\n return {\"select_objects\": \"select_objects\",\n \"bake_objects\": \"bake_objects\",\n \"add_to_list\":\"add_to_list\",\n \"get_selected_list\":\"get_selected_list\",\n \"bake_animations\":\"bake_animations\",\n \"export_locators\":\"export_locators\",\n \"create_locators\":\"create_locators\",\n \"get_time_range\":\"get_time_range\"}\n\n @property\n def _model2ViewMsg(self):\n return {}\n\n def run(self, **kwargs):\n self._view = self._viewInstance\n self._view.setController(self)\n self._view.lateInit()\n\n self._model = self._modelInstance\n self._model.setController(self)\n self._model.lateInit()\n\n self._view.show()\n","sub_path":"Projects/Maya/Tools/AlignObject/Package/Scripts/alignObjectController.py","file_name":"alignObjectController.py","file_ext":"py","file_size_in_byte":1413,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"52640400","text":"#!/usr/bin/env python3\n\"\"\"根据文件MD5值去除相同文件\"\"\"\n\n# 日常收集的某些文件可能因为其来源不同而产生不同的文件名,在文件夹内容较多时不方便直接逐个比较,可利用文件MD5值不同直接比较删除相同文件\n# 脚本目前只比较文件二进制内容的MD5值,对于类Unix系统下文件权限及其他文件属性未进行比较,此为局限,后期可能考虑进一步改进\n\nimport os\nimport hashlib\n\n# 使用时直接替换rootPath值即可运行\nrootPath = \"D:/Files/tests/\"\nfilesMD5 = []\n\nfor fileNamesTuple in os.walk(rootPath):\n for fileName in fileNamesTuple[-1]:\n fullPath = rootPath + fileName\n rb_file = open(fullPath, 'rb')\n# 实际使用时可比较文件MD5、sha1、sha256、sha512等\n rb_fileMD5 = hashlib.md5()\n rb_fileMD5.update(rb_file.read())\n fileMD5 = rb_fileMD5.hexdigest()\n rb_file.close()\n if fileMD5 in filesMD5:\n print(fullPath)\n os.remove(fullPath)\n filesMD5.append(rb_fileMD5.hexdigest())\n","sub_path":"python/md5Hash.py","file_name":"md5Hash.py","file_ext":"py","file_size_in_byte":1069,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"195737694","text":"from collections import deque\n\n\ndef bfs():\n global result, cnt\n while q:\n x, y = q.popleft()\n\n for i in range(4):\n nx = x + dx[i]\n ny = y + dy[i]\n\n if nx >= n or nx < 0 or ny >= m or ny < 0: continue\n\n if check[nx][ny] == -1 and a[nx][ny] == 0:\n check[nx][ny] = check[x][y] + 1\n result = max(result, check[nx][ny])\n cnt -= 1\n q.append((nx, ny))\n\n\nm, n = map(int, input().split())\na = []\ncheck = [[-1 for _ in range(m)] for _ in range(n)]\ncnt = 0\nq = deque()\ndx = [0, 0, 1, -1]\ndy = [-1, 1, 0, 0]\nresult = 0\n\nfor i in range(n):\n arr = list(map(int, input().split()))\n a.append(arr)\n\n for j in range(m):\n if a[i][j] == 0:\n cnt += 1\n elif a[i][j] == 1:\n check[i][j] = 0\n q.append((i, j))\n\nbfs()\nif cnt != 0:\n result = -1\n\nprint(result)\n","sub_path":"algorithm.py","file_name":"algorithm.py","file_ext":"py","file_size_in_byte":916,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"20547298","text":"import tensorflow as tf\n\ndef conv(x, w, b, stride, name, padding='SAME'):\n with tf.variable_scope('conv'):\n return tf.nn.conv2d(x,\n filter=w,\n strides=[1, stride, stride, 1],\n padding=padding,\n name=name) + b\n\n\ndef deconv(x, w, b, shape, stride, name):\n with tf.variable_scope('deconv'):\n return tf.nn.conv2d_transpose(x,\n filter=w,\n output_shape=shape,\n strides=[1, stride, stride, 1],\n padding='SAME',\n name=name) + b\n\ndef lrelu(x, alpha=0.2):\n with tf.variable_scope('leakyReLU'):\n return tf.maximum(x, alpha * x)\n\n\ndef discriminator(X, keep_prob, is_train=True, reuse=False):\n with tf.variable_scope('discriminator'):\n if reuse:\n tf.get_variable_scope().reuse_variables()\n\n\n batch_size = tf.shape(X)[0]\n K = 96\n M = 192\n N = 384\n\n W1 = tf.get_variable('D_W1', [5, 5, 3, K], \n initializer=tf.contrib.layers.xavier_initializer())\n B1 = tf.get_variable('D_B1', [K], \n initializer=tf.constant_initializer())\n\n W2 = tf.get_variable('D_W2', [5, 5, K, M], \n initializer=tf.contrib.layers.xavier_initializer())\n B2 = tf.get_variable('D_B2', [M], \n initializer=tf.constant_initializer())\n\n W3 = tf.get_variable('D_W3', [5, 5, M, N], \n initializer=tf.contrib.layers.xavier_initializer())\n B3 = tf.get_variable('D_B3', [N], \n initializer=tf.constant_initializer())\n\n W4 = tf.get_variable('D_W4', [3, 3, N, N], \n initializer=tf.contrib.layers.xavier_initializer())\n B4 = tf.get_variable('D_B4', [N], \n initializer=tf.constant_initializer())\n\n W5 = tf.get_variable('D_W5', [4, 4, N, N], \n initializer=tf.contrib.layers.xavier_initializer())\n B5 = tf.get_variable('D_B5', [N], \n initializer=tf.constant_initializer())\n\n W6 = tf.get_variable('D_W6', [N, 10+1], \n initializer=tf.contrib.layers.xavier_initializer())\n \n\n conv1 = conv(X, W1, B1, stride=2, name='conv1')\n bn1 = tf.contrib.layers.batch_norm(conv1,\n is_training=is_train,center=True,decay=0.9,updates_collections=None)\n\n conv2 = conv(tf.nn.dropout(lrelu(bn1), keep_prob),\n W2, B2, stride=2, name='conv2')\n bn2 = tf.contrib.layers.batch_norm(conv2,\n is_training=is_train,center=True,decay=0.9,updates_collections=None)\n\n conv3 = conv(tf.nn.dropout(lrelu(bn2),keep_prob),\n W3, B3, stride=2, name='conv3')\n bn3 = tf.contrib.layers.batch_norm(conv3,\n is_training=is_train,center=True,decay=0.9,updates_collections=None)\n\n conv4 = conv(tf.nn.dropout(lrelu(bn3),keep_prob),\n W4, B4, stride=1, name='conv4')\n bn4 = tf.contrib.layers.batch_norm(conv4,\n is_training=is_train,center=True,decay=0.9,updates_collections=None)\n\n conv5 = conv(lrelu(bn4), W5, B5, stride=1, name='conv5', padding='VALID')\n bn5 = tf.contrib.layers.batch_norm(conv5,\n is_training=is_train,center=True,decay=0.9,updates_collections=None)\n\n flat = tf.reshape(lrelu(bn5),[batch_size,N])\n output = tf.matmul(flat, W6)\n\n return tf.nn.softmax(output), output, flat\n \ndef generator(Z, keep_prob, is_train=True):\n with tf.variable_scope('generator'):\n\n batch_size = tf.shape(Z)[0]\n K = 512\n L = 256\n M = 128\n N = 64\n\n W1 = tf.get_variable('G_W1', [100, 4*4*K],\n initializer=tf.contrib.layers.xavier_initializer())\n B1 = tf.get_variable('G_B1', [4*4*K], initializer=tf.constant_initializer())\n\n W2 = tf.get_variable('G_W2', [4, 4, L, K], \n initializer=tf.contrib.layers.xavier_initializer())\n B2 = tf.get_variable('G_B2', [L], \n initializer=tf.constant_initializer())\n\n W3 = tf.get_variable('G_W3', [6, 6, M, L], \n initializer=tf.contrib.layers.xavier_initializer())\n B3 = tf.get_variable('G_B3', [M], \n initializer=tf.constant_initializer())\n\n W4 = tf.get_variable('G_W4', [6, 6, N, M], \n initializer=tf.contrib.layers.xavier_initializer())\n B4 = tf.get_variable('G_B4', [N], \n initializer=tf.constant_initializer())\n\n W5 = tf.get_variable('G_W5', [3, 3, N, 3], \n initializer=tf.contrib.layers.xavier_initializer())\n B5 = tf.get_variable('G_B5', [3], \n initializer=tf.constant_initializer())\n\n Z = lrelu(tf.matmul(Z, W1) + B1)\n Z = tf.reshape(Z, [batch_size, 4, 4, K])\n Z = tf.contrib.layers.batch_norm(Z,\n is_training=is_train,center=True,decay=0.9,updates_collections=None)\n\n deconv1 = deconv(Z, \n W2, B2, shape=[batch_size, 8, 8, L], stride=2, name='deconv1')\n bn1 = tf.contrib.layers.batch_norm(deconv1,\n is_training=is_train,center=True,decay=0.9,updates_collections=None)\n\n deconv2 = deconv(lrelu(bn1), \n W3, B3, shape=[batch_size, 16, 16, M], stride=2, name='deconv2')\n bn2 = tf.contrib.layers.batch_norm(deconv2,\n is_training=is_train,center=True,decay=0.9,updates_collections=None)\n\n deconv3 = deconv(lrelu(bn2), \n W4, B4, shape=[batch_size, 32, 32, N], stride=2, name='deconv3')\n bn3 = tf.contrib.layers.batch_norm(deconv3,\n is_training=is_train,center=True,decay=0.9,updates_collections=None)\n\n conv4 = conv(lrelu(bn3), W5, B5, stride=1, name='conv4')\n output = tf.nn.tanh(conv4)\n\n return output\n","sub_path":"CNN_GAN/model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":5843,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"395585455","text":"#! /usr/bin/python3\n\nimport functions\n\nfile=functions.clean('USA.csv')\n\na=functions.create_goaldiff(file)\nfile['goaldiff']=a\n\nb=functions.create_results(file)\nfile['result']=b\n\nfile.to_csv('usa_worked.csv')\n","sub_path":"usa_test/usa.py","file_name":"usa.py","file_ext":"py","file_size_in_byte":207,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"252773126","text":"#!/usr/bin/env python3\nimport tkinter as tk\n\n\ndef main():\n root = tk.Tk() # Defines the root window\n root.geometry(\"500x75+400-200\") # Define the size of the window\n root.maxsize(width=600, height=200) # restrict window's maximum size\n root.minsize(width=350, height=60) # restrict window's minimum size\n root.title(\"A Very Basic GUI\") # Define a title for the window\n tk.Label(root, text=\"Hello,World!\", # Add and configure a label\n fg=\"red\", font=(\"Times\", 48)).pack() # and pack it\n root.mainloop() # Start event loop that then waits for user interaction\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"python/pythonlabs/examples/guis/hello.py","file_name":"hello.py","file_ext":"py","file_size_in_byte":705,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"397581859","text":"# title: remove-duplicates-from-sorted-list\n# detail: https://leetcode.com/submissions/detail/190663810/\n# datetime: Tue Nov 20 14:30:49 2018\n# runtime: 36 ms\n# memory: N/A\n\n# Definition for singly-linked list.\n# class ListNode(object):\n# def __init__(self, x):\n# self.val = x\n# self.next = None\n\nclass Solution(object):\n def deleteDuplicates(self, head):\n \"\"\"\n :type head: ListNode\n :rtype: ListNode\n \"\"\"\n if head is None:\n return\n prev = head\n node = head.next\n while node:\n if node.val == prev.val:\n prev.next = node.next\n else:\n prev = node\n node = node.next \n return head","sub_path":"leetcode/remove-duplicates-from-sorted-list/190663810.py","file_name":"190663810.py","file_ext":"py","file_size_in_byte":736,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"244782139","text":"import math as m\n\npi = m.pi\n\n\ndef doubleSilnia(n):\n if n == 0 or n == 1:\n return 1\n return n * doubleSilnia(n-2)\n\n\ndef Silnia(n):\n if n == 1 or n == 0:\n return 1\n return n * Silnia(n-1)\n\n\ndef tStudent(k, t):\n licznik = 1\n mianownik = 1\n if k % 2 == 1:\n licznik = Silnia((k+1)/2 - 1)\n mianownik = pow(k*pi*pi, 1/2) * doubleSilnia(k-2) / pow(2, (k-1)/2)\n else:\n licznik = doubleSilnia(k - 1)/pow(2, k/2)\n mianownik *= pow(k, 1/2)*Silnia(k/2 - 1)\n\n ulamek = licznik / mianownik\n\n def f(x):\n return ulamek * pow(1 + x**2/k, -(k+1)/2)\n\n def trapezy(n):\n result = 0\n h = abs(t) / n\n for i in range(n):\n x = i * h\n result += h * (f(x) + f(x + h))/2\n if t < 0:\n return 0.5 - result\n return result + 0.5\n\n def romberg(n):\n h = [0]*(n+1)\n r = [[0]*(n+1) for i in range(n+1)]\n for i in range(1, n + 1):\n h[i] = abs(t) / pow(2, i-1)\n\n r[1][1] = h[1] / 2 * (f(0) + f(t))\n\n for i in range(2, n + 1):\n wsp = 0\n for j in range(1, pow(2, i-2) + 1):\n wsp += f((2*j - 1) * h[i])\n r[i][1] = 0.5 * (r[i-1][1] + h[i-1] * wsp)\n\n for i in range(2, n+1):\n for j in range(2, i+1):\n r[i][j] = r[i][j-1] + (r[i][j-1]-r[i-1][j-1]) / (pow(4, j-1)-1)\n\n if t < 0:\n return 0.5 - r[n][n]\n return r[n][n] + 0.5\n\n for i in range(4, 12):\n n = pow(2, i)\n\n print(f\"Wynik dla trapezów: {trapezy(n)} przy {n} punktach.\")\n\n print(f\"Wynik dla romberga: {romberg(i)} przy {n} punktach.\")\n\n print(\"------------------------------------------------------\")\n\n\nprint(\"Dla k = 3 i t = 0.25:\")\ntStudent(3, 0.25)\n","sub_path":"RPiS/egzaminacyjne/e1 - 315373/e1.py","file_name":"e1.py","file_ext":"py","file_size_in_byte":1798,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"145263946","text":"\"\"\"\n_mask.py\n\nmodule that performs missing values masking\nand geographical area eslection\n\"\"\"\n\nfrom __future__ import print_function\n\nimport logging\nimport os\n\nimport cartopy.io.shapereader as shpreader\nimport iris\nimport numpy as np\nimport shapely.vectorized as shp_vect\nfrom iris.analysis import Aggregator\nfrom iris.util import rolling_window\n\nlogger = logging.getLogger(__name__)\n\n\ndef _check_dims(cube, mask_cube):\n \"\"\"Check for same dims for mask and data\"\"\"\n x_dim = cube.coord('longitude').points.ndim\n y_dim = cube.coord('latitude').points.ndim\n mx_dim = mask_cube.coord('longitude').points.ndim\n my_dim = mask_cube.coord('latitude').points.ndim\n len_x = len(cube.coord('longitude').points)\n len_y = len(cube.coord('latitude').points)\n len_mx = len(mask_cube.coord('longitude').points)\n len_my = len(mask_cube.coord('latitude').points)\n if (x_dim == mx_dim and y_dim == my_dim and len_x == len_mx\n and len_y == len_my):\n logger.debug('Data cube and fx mask have same dims')\n return True\n\n logger.debug(\n 'Data cube and fx mask differ in dims: '\n 'cube: ((%i, %i), grid=(%i, %i)), mask: ((%i, %i), grid=(%i, %i))',\n x_dim, y_dim, len_x, len_y, mx_dim, my_dim, len_mx, len_my)\n return False\n\n\ndef _get_fx_mask(fx_data, fx_option, mask_type):\n \"\"\"Build a 50 percent land or sea mask\"\"\"\n inmask = np.zeros_like(fx_data, bool)\n if mask_type == 'sftlf':\n if fx_option == 'land':\n # Mask land out\n inmask[fx_data > 50.] = True\n elif fx_option == 'sea':\n # Mask sea out\n inmask[fx_data <= 50.] = True\n elif mask_type == 'sftof':\n if fx_option == 'land':\n # Mask land out\n inmask[fx_data < 50.] = True\n elif fx_option == 'sea':\n # Mask sea out\n inmask[fx_data >= 50.] = True\n elif mask_type == 'sftgif':\n if fx_option == 'ice':\n # Mask ice out\n inmask[fx_data > 50.] = True\n elif fx_option == 'landsea':\n # Mask landsea out\n inmask[fx_data <= 50.] = True\n\n return inmask\n\n\ndef _apply_fx_mask(fx_mask, var_data):\n \"\"\"Apply the fx mask\"\"\"\n # Broadcast mask\n var_mask = np.zeros_like(var_data, bool)\n var_mask = np.broadcast_to(fx_mask, var_mask.shape).copy()\n\n # Aplly mask accross\n if np.ma.is_masked(var_data):\n var_mask |= var_data.mask\n\n # Build the new masked data\n var_data = np.ma.array(var_data, mask=var_mask, fill_value=1e+20)\n\n return var_data\n\n\ndef mask_landsea(cube, fx_files, mask_out):\n \"\"\"\n Mask out either land or sea\n\n Function that masks out either land mass or seas (oceans, seas and lakes)\n\n It uses dedicated fx files (sftlf or sftof) or, in their absence, it\n applies a Natural Earth mask (land or ocean contours). Not that the\n Natural Earth masks have different resolutions: 10m for land, and 50m\n for seas; these are more than enough for ESMValTool puprpose.\n\n Parameters\n ----------\n\n * cube (iris.Cube.cube instance):\n data cube to be masked.\n\n * fx_files (list):\n list holding the full paths to fx files.\n\n * mask_out (string):\n either \"land\" to mask out land mass or \"sea\" to mask out seas.\n\n Returns\n -------\n masked iris cube\n\n \"\"\"\n # Dict to store the Natural Earth masks\n cwd = os.path.dirname(__file__)\n # ne_10m_land is fast; ne_10m_ocean is very slow\n shapefiles = {\n 'land': os.path.join(cwd, 'ne_masks/ne_10m_land.shp'),\n 'sea': os.path.join(cwd, 'ne_masks/ne_50m_ocean.shp')\n }\n\n if fx_files:\n fx_cubes = {}\n for fx_file in fx_files:\n fx_root = os.path.basename(fx_file).split('_')[0]\n fx_cubes[fx_root] = iris.load_cube(fx_file)\n\n # preserve importance order: try stflf first then sftof\n if ('sftlf' in fx_cubes.keys()\n and _check_dims(cube, fx_cubes['sftlf'])):\n landsea_mask = _get_fx_mask(fx_cubes['sftlf'].data, mask_out,\n 'sftlf')\n cube.data = _apply_fx_mask(landsea_mask, cube.data)\n logger.debug(\"Applying land-sea mask: sftlf\")\n elif ('sftof' in fx_cubes.keys()\n and _check_dims(cube, fx_cubes['sftof'])):\n landsea_mask = _get_fx_mask(fx_cubes['sftof'].data, mask_out,\n 'sftof')\n cube.data = _apply_fx_mask(landsea_mask, cube.data)\n logger.debug(\"Applying land-sea mask: sftof\")\n else:\n if cube.coord('longitude').points.ndim < 2:\n cube = _mask_with_shp(cube, shapefiles[mask_out])\n logger.debug(\n \"Applying land-sea mask from Natural Earth\"\n \" shapefile: \\n%s\", shapefiles[mask_out])\n else:\n logger.error(\"Use of shapefiles with irregular grids not \"\n \"yet implemented, land-sea mask not applied\")\n else:\n if cube.coord('longitude').points.ndim < 2:\n cube = _mask_with_shp(cube, shapefiles[mask_out])\n logger.debug(\n \"Applying land-sea mask from Natural Earth\"\n \" shapefile: \\n%s\", shapefiles[mask_out])\n else:\n logger.error(\"Use of shapefiles with irregular grids not \"\n \"yet implemented, land-sea mask not applied\")\n\n return cube\n\n\ndef mask_landseaice(cube, fx_files, mask_out):\n \"\"\"\n Mask out either landsea (combined) or ice\n\n Function that masks out either landsea (land and seas) or ice (Antarctica\n and Greenland and some wee glaciers). It uses dedicated fx files (sftgif).\n\n Parameters\n ----------\n\n * cube (iris.Cube.cube instance):\n data cube to be masked.\n\n * fx_files (list):\n list holding the full paths to fx files.\n\n * mask_out (string):\n either \"landsea\" to mask out landsea or \"ice\" to mask out ice.\n\n Returns\n -------\n masked iris cube\n\n \"\"\"\n # sftgif is the only one so far\n if fx_files:\n for fx_file in fx_files:\n fx_cube = iris.load_cube(fx_file)\n\n if _check_dims(cube, fx_cube):\n landice_mask = _get_fx_mask(fx_cube.data, mask_out,\n 'sftgif')\n cube.data = _apply_fx_mask(landice_mask, cube.data)\n logger.debug(\"Applying landsea-ice mask: sftgif\")\n else:\n logger.warning(\"Landsea-ice mask could not be found \")\n\n return cube\n\n\ndef _get_geometry_from_shp(shapefilename):\n \"\"\"Get the mask geometry out from a shapefile\"\"\"\n reader = shpreader.Reader(shapefilename)\n # Index 0 grabs the lowest resolution mask (no zoom)\n main_geom = [contour for contour in reader.geometries()][0]\n return main_geom\n\n\ndef _mask_with_shp(cube, shapefilename):\n \"\"\"Apply a Natural Earth land/sea mask\"\"\"\n # Create the region\n region = _get_geometry_from_shp(shapefilename)\n\n # Create a mask for the data\n mask = np.zeros(cube.shape, dtype=bool)\n\n # Create a set of x,y points from the cube\n # 1D regular grids\n if cube.coord('longitude').points.ndim < 2:\n x_p, y_p = np.meshgrid(\n cube.coord(axis='X').points, cube.coord(axis='Y').points)\n # 2D irregular grids; spit an error for now\n else:\n logger.error('No fx-files found (sftlf or sftof)!\\n \\\n 2D grids are suboptimally masked with\\n \\\n Natural Earth masks. Exiting.')\n\n # Wrap around longitude coordinate to match data\n x_p_180 = np.where(x_p >= 180., x_p - 360., x_p)\n # the NE mask has no points at x = -180 and y = +/-90\n # so we will fool it and apply the mask at (-179, -89, 89) instead\n x_p_180 = np.where(x_p_180 == -180., x_p_180 + 1., x_p_180)\n y_p_0 = np.where(y_p == -90., y_p + 1., y_p)\n y_p_90 = np.where(y_p_0 == 90., y_p_0 - 1., y_p_0)\n\n # Build mask with vectorization\n if len(cube.data.shape) == 3:\n mask[:] = shp_vect.contains(region, x_p_180, y_p_90)\n elif len(cube.data.shape) == 4:\n mask[:, :] = shp_vect.contains(region, x_p_180, y_p_90)\n\n # Then apply the mask\n if isinstance(cube.data, np.ma.MaskedArray):\n cube.data.mask |= mask\n else:\n cube.data = np.ma.masked_array(cube.data, mask)\n\n return cube\n\n\n# Define a function to perform the custom statistical operation.\n# Note: in order to meet the requirements of iris.analysis.Aggregator, it must\n# do the calculation over an arbitrary (given) data axis.\ndef count_spells(data, threshold, axis, spell_length):\n \"\"\"\n Count data occurences\n\n Function to calculate the number of points in a sequence where the value\n has exceeded a threshold value for at least a certain number of timepoints.\n\n Generalised to operate on multiple time sequences arranged on a specific\n axis of a multidimensional array.\n\n Args:\n\n * data (array):\n raw data to be compared with value threshold.\n\n * threshold (float):\n threshold point for 'significant' datapoints.\n\n * axis (int):\n number of the array dimension mapping the time sequences.\n (Can also be negative, e.g. '-1' means last dimension)\n\n * spell_length (int):\n number of consecutive times at which value > threshold to \"count\".\n\n \"\"\"\n if axis < 0:\n # just cope with negative axis numbers\n axis += data.ndim\n # Threshold the data to find the 'significant' points.\n data_hits = data > threshold\n # Make an array with data values \"windowed\" along the time axis.\n ###############################################################\n # WARNING: default step is = window size i.e. no overlapping\n # if you want overlapping windows set the step to be m*spell_length\n # where m is a float\n ###############################################################\n hit_windows = rolling_window(\n data_hits, window=spell_length, step=spell_length, axis=axis)\n # Find the windows \"full of True-s\" (along the added 'window axis').\n full_windows = np.all(hit_windows, axis=axis + 1)\n # Count points fulfilling the condition (along the time axis).\n spell_point_counts = np.sum(full_windows, axis=axis, dtype=int)\n return spell_point_counts\n\n\ndef window_counts(mycube, value_threshold, window_size, pctile):\n \"\"\"\n Find data counts in a time window\n\n Function that returns a flat array containing\n the number of data points within a time window `window_size'\n per grid point that satify a condition\n value > value_threshold.\n It also returns statistical measures for the flat array\n window_counts[0] = array\n window_counts[1] = mean(array)\n window_counts[2] = std(array)\n window_counts[3] = percentile(array, pctile)\n \"\"\"\n # Make an aggregator from the user function.\n spell_count = Aggregator(\n 'spell_count', count_spells, units_func=lambda units: 1)\n\n # Calculate the statistic.\n counts_windowed_cube = mycube.collapsed(\n 'time',\n spell_count,\n threshold=value_threshold,\n spell_length=window_size)\n\n # if one wants to print the whole array\n # np.set_printoptions(threshold=np.nan)\n r_p = counts_windowed_cube.data.flatten()\n meanr = np.mean(r_p)\n stdr = np.std(r_p)\n prcr = np.percentile(r_p, pctile)\n return r_p, meanr, stdr, prcr\n\n\ndef mask_cube_counts(mycube, value_threshold, counts_threshold, window_size):\n \"\"\"Build the counts mask\"\"\"\n # Make an aggregator from the user function.\n spell_count = Aggregator(\n 'spell_count', count_spells, units_func=lambda units: 1)\n\n # Calculate the statistic.\n counts_windowed_cube = mycube.collapsed(\n 'time',\n spell_count,\n threshold=value_threshold,\n spell_length=window_size)\n\n mask = counts_windowed_cube.data >= counts_threshold\n mask.astype(np.int)\n # preserving the original cube metadata\n dummyar = np.ones(mycube.data.shape, dtype=mycube.data.dtype)\n newmask = dummyar * mask\n newmask[newmask == 0] = 1e+20 # np.nan\n masked_cube = mycube.copy()\n # masked_cube.data = masked_cube.data * newmask\n masked_cube.data = newmask\n return counts_windowed_cube, newmask, masked_cube\n\n\ndef mask_above_threshold(cube, threshold):\n \"\"\"\n Mask above a specific threshold value.\n\n Takes a value 'threshold' and masks off anything that is above\n it in the cube data. Values equal to the threshold are not masked.\n \"\"\"\n cube.data = np.ma.masked_where(cube.data > threshold, cube.data)\n return cube\n\n\ndef mask_below_threshold(cube, threshold):\n \"\"\"\n Mask below a specific threshold value.\n\n Takes a value 'threshold' and masks off anything that is below\n it in the cube data. Values equal to the threshold are not masked.\n \"\"\"\n cube.data = np.ma.masked_where(cube.data < threshold, cube.data)\n return cube\n\n\ndef mask_inside_range(cube, minimum, maximum):\n \"\"\"\n Mask inside a specific threshold range.\n\n Takes a MINIMUM and a MAXIMUM value for the range, and masks off anything\n that's between the two in the cube data.\n \"\"\"\n cube.data = np.ma.masked_inside(cube.data, minimum, maximum)\n return cube\n\n\ndef mask_outside_range(cube, minimum, maximum):\n \"\"\"\n Mask outside a specific threshold range.\n\n Takes a MINIMUM and a MAXIMUM value for the range, and masks off anything\n that's outside the two in the cube data.\n \"\"\"\n cube.data = np.ma.masked_outside(cube.data, minimum, maximum)\n return cube\n\n\ndef mask_fillvalues(products,\n threshold_fraction,\n min_value=-1.e10,\n time_window=1):\n \"\"\"Compute and apply a multi-dataset fillvalues mask\"\"\"\n combined_mask = None\n\n logger.debug(\"Creating fillvalues mask\")\n used = set()\n for product in products:\n for cube in product.cubes:\n cube.data = np.ma.fix_invalid(cube.data, copy=False)\n mask = _get_fillvalues_mask(cube, threshold_fraction, min_value,\n time_window)\n if combined_mask is None:\n combined_mask = np.zeros_like(mask)\n # Select only valid (not all masked) pressure levels\n n_dims = len(mask.shape)\n if n_dims == 2:\n valid = ~np.all(mask)\n if valid:\n combined_mask |= mask\n used.add(product)\n elif n_dims == 3:\n valid = ~np.all(mask, axis=(1, 2))\n combined_mask[valid] |= mask[valid]\n if np.any(valid):\n used.add(product)\n else:\n raise NotImplementedError(\n \"Unable to handle {} dimensional data\".format(n_dims))\n\n if np.any(combined_mask):\n logger.debug(\"Applying fillvalues mask\")\n used = {p.copy_provenance() for p in used}\n for product in products:\n for cube in product.cubes:\n cube.data.mask |= combined_mask\n for other in used:\n if other.filename != product.filename:\n product.wasderivedfrom(other)\n\n return products\n\n\ndef _get_fillvalues_mask(cube, threshold_fraction, min_value, time_window):\n\n # basic checks\n if threshold_fraction < 0 or threshold_fraction > 1.0:\n raise ValueError(\n \"Fraction of missing values {} should be between 0 and 1.0\"\n .format(threshold_fraction))\n nr_time_points = len(cube.coord('time').points)\n if time_window > nr_time_points:\n logger.warning(\"Time window (in time units) larger \"\n \"than total time span\")\n\n max_counts_per_time_window = nr_time_points / time_window\n # round to lower integer\n counts_threshold = int(max_counts_per_time_window * threshold_fraction)\n\n # Make an aggregator\n spell_count = Aggregator(\n 'spell_count', count_spells, units_func=lambda units: 1)\n\n # Calculate the statistic.\n counts_windowed_cube = cube.collapsed(\n 'time', spell_count, threshold=min_value, spell_length=time_window)\n\n # Create mask\n mask = counts_windowed_cube.data < counts_threshold\n if np.ma.isMaskedArray(mask):\n mask = mask.data | mask.mask\n\n return mask\n","sub_path":"esmvaltool/preprocessor/_mask.py","file_name":"_mask.py","file_ext":"py","file_size_in_byte":16342,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"290267848","text":"from django.conf import settings\nfrom django.contrib.auth import get_user_model\nfrom django.core.mail import EmailMultiAlternatives\nfrom django.template.loader import render_to_string\n\n\ndef send_email_notification(notification):\n single_template_html = \"issue-drip.html\"\n multiple_template_html = \"multiple-issues-drip.html\"\n\n subject = \"GlitchTip\"\n issue_count = notification.issues.count()\n first_issue = notification.issues.all().first()\n if issue_count == 1:\n subject = f\"Error in {first_issue.project}: {first_issue.title}\"\n elif issue_count > 1:\n subject = f\"{issue_count} errors reported in {first_issue.project}\"\n\n base_url = settings.GLITCHTIP_DOMAIN.geturl()\n org_slug = first_issue.project.organization.slug\n\n text_content = f\"Errors reported in {first_issue.project}:\\n\\n\"\n for issue in notification.issues.all():\n text_content += f\"{issue.title}\\n\"\n text_content += f\"{base_url}/organizations/{org_slug}/issues/{issue.id}\\n\\n\"\n\n settings_link = (\n f\"{base_url}/settings/{org_slug}/projects/{first_issue.project.slug}\"\n )\n\n if issue_count == 1:\n issue_link = f\"{base_url}/organizations/{org_slug}/issues/{first_issue.id}\"\n html_content = render_to_string(\n single_template_html,\n {\n \"issue_title\": first_issue.title,\n \"project_name\": first_issue.project,\n \"base_url\": base_url,\n \"issue_link\": issue_link,\n \"project_notification_settings_link\": settings_link,\n },\n )\n elif issue_count > 1:\n project_link = f\"{base_url}/organizations/{org_slug}/issues?project={first_issue.project.id}\"\n html_content = render_to_string(\n multiple_template_html,\n {\n \"org_slug\": org_slug,\n \"project_notification_settings_link\": settings_link,\n \"issues\": notification.issues.all(),\n \"project_name\": first_issue.project,\n \"project_link\": project_link,\n },\n )\n\n User = get_user_model()\n users = User.objects.filter(\n organizations_ext_organization__projects__notification=notification\n )\n to = users.values_list(\"email\", flat=True)\n msg = EmailMultiAlternatives(subject, text_content, to=to)\n msg.attach_alternative(html_content, \"text/html\")\n msg.send()\n","sub_path":"alerts/email.py","file_name":"email.py","file_ext":"py","file_size_in_byte":2410,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"414689236","text":"from models.concessionaria import Concessionaria\nfrom models.venda import Venda\nfrom views.venda_view import VendaView\n\n\nclass VendaController():\n def __init__(self, concessionaria: Concessionaria):\n self.__concessionaria = concessionaria\n self.__view = VendaView()\n\n def nova_venda(self):\n info = self.__view.tela_de_vendas()\n #info[0] -> ID_Vendedor\n #info[1] -> ID_Cliente\n #info[2] -> ID_Carro\n #info[3] -> Garantia\n #info[4] -> Data\n vendedor_existe = False\n cliente_existe = False\n carro_existe = False\n\n for vendedor in self.__concessionaria.vendedores:\n if vendedor.num_id == info[0]:\n vendedor_existe = True\n for cliente in self.__concessionaria.vendedores:\n if cliente.num_id == info[1]:\n cliente_existe = True\n for carro in self.__concessionaria.vendedores:\n if carro.num_id == info[2]:\n carro_existe = True\n\n if vendedor_existe and cliente_existe and carro_existe:\n self.__concessionaria.nova_venda(Venda(info[0], info[1], info[2], info[3], info[4]))\n \n def relatorio(self):\n self.__view.relatorio(self.__concessionaria.vendas)\n","sub_path":"controllers/venda_controller.py","file_name":"venda_controller.py","file_ext":"py","file_size_in_byte":1277,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"147512925","text":"from instruments.model import buildModel\n\n############# RESIDUAL ##############\n\ndef residual(params, x, good_x, y_meas, good_y_meas, good_y_err, goodIndexes, componentslist, psfFunction, fitConvolvedModel, psfwing_02pxscale_datatab, psfwing_logscale_datatab, Settings, sampling, gaussianSmoothing):\n\t\n\ty_model, good_y_model = buildModel(params, componentslist, x, goodIndexes, psfFunction, fitConvolvedModel, psfwing_02pxscale_datatab, psfwing_logscale_datatab, Settings, sampling, gaussianSmoothing)\n\t\n\tif Settings.useErrorsInFit:\n\t\t#res = abs(good_y_meas-good_y_model)/good_y_err\n\t\tres = (good_y_meas-good_y_model)**2/good_y_err**2\n\telse:\n\t\t#res = abs(good_y_meas-good_y_model)\n\t\tres = (good_y_meas-good_y_model)**2\n\n\treturn res\t\n\t\n\t\n","sub_path":"python_codes/decomposition/ProFitErole1.0.1/instruments/residual.py","file_name":"residual.py","file_ext":"py","file_size_in_byte":737,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"69515566","text":"from scrapers import mlb_scraper,fantasylabs_lineups, sbr_scraper\nfrom datetime import datetime, timedelta\nimport pandas as pd\nimport os\n\nyear = 2018\nyesterday = (datetime.now() - timedelta(1)).strftime('%Y-%m-%d')\ntoday = datetime.now().strftime('%Y-%m-%d')\n\ndef update_games():\n print(\"getting games\")\n mlb_path = os.path.join('data','games','games_{}.csv'.format(year))\n games_df = pd.read_csv(mlb_path)\n yesterday_games = pd.DataFrame(mlb_scraper.get_day_of_games(yesterday))\n updated_games_df = pd.concat([games_df,yesterday_games]).set_index('key')\n updated_games_df.drop_duplicates().to_csv(mlb_path)\n\ndef update_lineups():\n print(\"getting lineups\")\n lineups_path = os.path.join('data','lineups','lineups_{}.csv'.format(year))\n lineups_df = pd.read_csv(lineups_path)\n yesterday_lineups = pd.DataFrame(fantasylabs_lineups.scrape_day_lineups(yesterday))\n updated_lineups_df = pd.concat([lineups_df,yesterday_lineups]).set_index('key')\n updated_lineups_df.drop_duplicates().to_csv(lineups_path)\n\n today_lineups = pd.DataFrame(fantasylabs_lineups.scrape_day_lineups(today)).set_index('key')\n today_lineups.to_csv(os.path.join('data','lineups','today.csv'))\n\ndef update_lines():\n print(\"getting lines\")\n lines_path = os.path.join('data','lines','lines_{}.csv'.format(year))\n lines_df = pd.read_csv(lines_path)\n yesterday_lines = pd.DataFrame(list(sbr_scraper.scrape_sbr_day(yesterday).values()))\n updated_lines_df = pd.concat([lines_df,yesterday_lines]).set_index('key')\n updated_lines_df.drop_duplicates().to_csv(lines_path)\n\n today_lines = pd.DataFrame(list(sbr_scraper.scrape_sbr_day(today).values())).set_index('key')\n today_lines.to_csv(os.path.join('data','lines','today.csv'))\n\ndef update_all():\n update_games()\n update_lineups()\n update_lines()\n","sub_path":"scrapers/update.py","file_name":"update.py","file_ext":"py","file_size_in_byte":1830,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"569417302","text":"users = [\n {'id': 0, 'name': 'Hero'},\n {'id': 1, 'name': 'Dunn'},\n {'id': 2, 'name': 'Sue'},\n {'id': 3, 'name': 'Chi'},\n {'id': 4, 'name': 'Thor'},\n {'id': 5, 'name': 'Clive'},\n {'id': 6, 'name': 'Hicks'},\n {'id': 7, 'name': 'Devin'},\n {'id': 8, 'name': 'Kate'},\n {'id': 9, 'name': 'Klein'}\n]\n\nfriendship_pairs = [(0,1),(0,2),(1,2),(1,3),(2,3),(3,4),(4,5),(5,6),(5,7),(6,8),(7,8),(8,9)]\n\n# Initialize the dict with an empmty list for each user id:\nfriendships = {user['id']: [] for user in users}\n\n# And loop over the friendship pairs to populate it:\nfor i, j in friendship_pairs:\n friendships[i].append(j)\n friendships[j].append(i)\n\nprint(friendships)\n\ndef number_of_friends(user):\n \"\"\"\n How many friends does _user_ have?\n :param user:\n :return:\n \"\"\"\n user_id = user['id']\n friend_ids = friendships[user_id]\n return len(friend_ids)\n\ntotal_connections = sum(number_of_friends(user)\n for user in users)\nprint(total_connections)\n\nnum_users = len(users)\navg_connection = total_connections / num_users\nprint(avg_connection)\n\n# Create a list (user_id, number_of_friends).\nnum_friends_by_id = [(user['id'], number_of_friends(user))\n for user in users]\nnum_friends_by_id.sort(\n key=lambda id_and_friends: id_and_friends[1],\n reverse=True)\nprint(num_friends_by_id)","sub_path":"Data-Science-From-Scratch/Intro/key-connectors.py","file_name":"key-connectors.py","file_ext":"py","file_size_in_byte":1366,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"405665828","text":"'''\ndocker exec -it mongo mongo\n\nuse chapter07\ndb.artists.find({\"name\": \"Queen\"})\n'''\n\ndef main():\n from knock64 import MusicDb\n\n db = MusicDb()\n name = input(\"input artist name: \").strip()\n for ret in db.collection.find({\"name\": name}):\n print(ret)\n\nif __name__ == '__main__':\n main()\n # import cProfile\n # cProfile.run('main()')","sub_path":"tosho/chapter07/knock65.py","file_name":"knock65.py","file_ext":"py","file_size_in_byte":358,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"289031701","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sat Mar 11 19:33:51 2017\n\n@author: Avokald\n\"\"\"\n\n\ndef convert_to_mandarin(us_num):\n '''\n us_num, a string representing a US number 0 to 99\n returns the string mandarin representation of us_num\n '''\n trans = {\n '0': 'ling', '1': 'yi', '2': 'er',\n '3': 'san', '4': 'si', '5': 'wu',\n '6': 'liu', '7': 'qi', '8': 'ba',\n '9': 'jiu', '10': 'shi'\n }\n us_num = str(us_num)\n copyNum = int(us_num)\n\n tens = str(copyNum // 10)\n ones = str(copyNum % 10)\n\n assert copyNum >= 0 and copyNum < 100\n\n if copyNum < 10:\n return trans[us_num]\n elif copyNum >= 10 and copyNum < 20:\n return trans['10'] + (\" \" \\\n + trans[ones] if copyNum % 10 != 0 else \"\")\n else:\n return trans[tens] \\\n + \" \" + trans['10'] \\\n + (\" \" + trans[ones] if copyNum % 10 != 0 else \"\")\n","sub_path":"6.00.1x/final/problem3.py","file_name":"problem3.py","file_ext":"py","file_size_in_byte":875,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"574256437","text":"## Script (Python) \"setPath\"\n##bind container=container\n##bind context=context\n##bind namespace=\n##bind script=script\n##bind subpath=traverse_subpath\n##parameters=\n##title=Pfad zum temporären repository\n##\nfrom Products.PythonScripts.standard import html_quote\nrequest = container.REQUEST\nRESPONSE = request.RESPONSE\ntry:\n\tpath = request.pfad\nexcept:\n\tpath = container.portal_properties.repository\nreturn path\n","sub_path":"Products/DiPP/skins/dipp_workflow/setPath.py","file_name":"setPath.py","file_ext":"py","file_size_in_byte":412,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"40145697","text":"#professor jucimar junior\n#Bruno de Oliveira freire - 1615310030\n#Felipe Henrique Bastos Costa -1615310032\n#Caio de OLiveira Martins-1615310031\n#Samuel Silva de França- 1615310049\n#Eduardo Maia Freire-1615310003\n#lista de Repetição\nnum = int(input(\"Informe o numero que deseja fatorar:\\n\"))\ncont = 1\nfat = 1\nx = \"\" #string vazia\nmult = \"\" #string vazia\n\nwhile(cont <= num):\n fat *= cont\n x = str(cont) + mult + x\n mult = \".\" # a partir daqui o mult é uma string que recebe \".\"(ponto) nas \n # demais repetições até o programa finalizar\n cont += 1\n \nprint(\"%d! = %s = %d\"%(num,x,fat))\n","sub_path":"Lista de Estrutura de Repetição (3)/ipc_lista3.32.py","file_name":"ipc_lista3.32.py","file_ext":"py","file_size_in_byte":620,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"4908657","text":"#!/home/sean/virtualenvs/numerai/bin/python\n\nimport logging\nimport os\nimport random\nimport sys\nsys.path.append('../..')\n\nfrom dotenv import load_dotenv, find_dotenv\nfrom numerapi import numerapi\n\nfrom src.tools import numerai_api, utils\nfrom src.tools.manage_model_files import *\nfrom src.models import train_RFC\n\ndef predict_with_noise(df, model, features, noise=0.0):\n df = df.loc[(df['data_type'] != 'train'),:]\n drop_columns = ['era','data_type', 'target']\n df = df.drop(drop_columns, axis=1).iloc[:,features]\n df['probability'] = model.predict_proba(df)[:,1]\n df['probability'] = df['probability'] + random.uniform(-noise,noise)\n return df\n\ndef create_submission_file(df, filename):\n df['id'] = df.index\n df = df.loc[:, ['id','probability']]\n df.to_csv(filename, index=False)\n\n\ndef get_napi(user='NUMERAI'):\n dotenv_path = find_dotenv()\n load_dotenv(dotenv_path)\n public_id = os.environ.get('{}_SUBMIT_ID'.format(user))\n secret_key = os.environ.get('{}_SUBMIT_KEY'.format(user))\n return numerapi.NumerAPI(public_id, secret_key, verbosity='info')\n\ndef main(noise=0.0):\n logger.info('Get data')\n df = utils.load_data()\n\n X_train = df.loc[df['data_type']=='train','feature1':'feature50']\n y_train = df.loc[df['data_type']=='train', 'target']\n\n logger.info('Train model')\n try:\n model, features = load_model('rfc_filtered')\n except FileNotFoundError:\n model, features = train_RFC.train_rfc_filtered(X_train, y_train)\n save_model((model, features),'rfc_filtered')\n\n logger.info('Predict')\n df_predict = predict_with_noise(df, model, features, float(noise))\n\n round_number = numerai_api.get_current_round()\n filename = 'predictions_RFC_{}.csv'.format(round_number)\n logger.info('Create submission')\n create_submission_file(df_predict, filename)\n\n napi = get_napi()\n\n logger.info('Submit')\n napi.upload_predictions(filename)\n\n\nif __name__ == '__main__':\n # setup logger\n log_fmt = '%(asctime)s - %(levelname)s - %(message)s'\n logging.basicConfig(level=logging.INFO, format=log_fmt)\n logger = logging.getLogger()\n try:\n main(sys.argv[1])\n except IndexError:\n main()\n\n","sub_path":"src/models/predict_model.py","file_name":"predict_model.py","file_ext":"py","file_size_in_byte":2211,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"426963392","text":"#!/usr/bin/env python\n# -*- coding:utf-8 -*-#\n\n\n\n#写代码,有如下元组,按照要求实现每一个功能\ntu = ('alex','eric','rain')\n\n#a.计算元组长度并输出\n# print(len(tu))\n\n#b.获取元组的第2个元素,并输出\n# print(tu[1])\n\n#c.获取元组的第1-2个元素,并输出\n# print(tu[0:2])\n\n#d.请使用for输出元组的元素\n# for i in tu:\n # print(i)\n\n#e.请使用for、len、range输出元组的索引\n# i = 0\n#\n# for c in tu:\n#\n# print(i)\n# i += 1\n#\n#\n# j = 0\n# while j < len(tu):\n# print(j)\n# j += 1\n#\n#\n# for m in range(0,len(tu)):\n# print(m)\n\n\n#f.请使用enumerate输出元组元素和序号(序号从10开始)\nfor index,value in enumerate(tu):\n print(10 + index,value)\n\n\n#6、有如下变量,请实现要求的功能\ntu = (\"alex\",[11,22,{\"k1\":\"v1\",\"k2\":[\"age\",\"name\"],\"k3\":(11,22,33)},44])\n\n#讲述元组的特性\n\n#请问tu变量中的第一个元素是否可被修改?\n#不能被修改\n\n#请问tu标量中\"k2\"对应的值是什么类型?是否可以被修改?如果可以,请在其中添加一个元素\"Seven\"\n#列表,可以修改\n# tu[1][2]['k2'].append(\"Seven\")\n# print(tu)\n\n#请问tu标量中\"k3\"对应的值是什么类型?是否可以被修改?如果可以,请在其中添加一个元素\"Seven\"\n#元组,不能修改\n\n","sub_path":"waldens/list_tuple_dict_funtions/tuple_excesice.py","file_name":"tuple_excesice.py","file_ext":"py","file_size_in_byte":1310,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"260218005","text":"\"\"\"empty message\n\nRevision ID: 96bbd021cbe4\nRevises: 40d75dcca6f8\nCreate Date: 2019-09-24 11:00:37.431481\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\n\n\n# revision identifiers, used by Alembic.\nrevision = '96bbd021cbe4'\ndown_revision = '40d75dcca6f8'\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.create_table('annotations',\n sa.Column('id', sa.Integer(), autoincrement=True, nullable=False),\n sa.Column('created_at', sa.TIMESTAMP(), nullable=True),\n sa.Column('updated_at', sa.TIMESTAMP(), nullable=True),\n sa.Column('deviceID', sa.String(length=50), nullable=True),\n sa.Column('file_path', sa.String(length=255), nullable=False),\n sa.Column('file_location', sa.String(length=255), nullable=False),\n sa.PrimaryKeyConstraint('id'),\n sa.UniqueConstraint('id')\n )\n op.create_index(op.f('ix_annotations_deviceID'), 'annotations', ['deviceID'], unique=False)\n op.create_unique_constraint(None, 'users', ['phone'])\n # ### end Alembic commands ###\n\n\ndef downgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.drop_constraint(None, 'users', type_='unique')\n op.drop_index(op.f('ix_annotations_deviceID'), table_name='annotations')\n op.drop_table('annotations')\n # ### end Alembic commands ###\n","sub_path":"migrations/versions/96bbd021cbe4_.py","file_name":"96bbd021cbe4_.py","file_ext":"py","file_size_in_byte":1352,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"6847106","text":"class Queue:\n def __init__(self):\n self.item = []\n\n def push(self,item):\n self.item.append(item)\n\n def deQueue(self):\n if self.size() > 0:\n return self.item.pop(0)\n\n def size(self):\n return len(self.item)\n\n def __str__(self):\n return str(self.item)\n\n def isEmpty(self):\n return len(self.item) == 0\n\nInp = input('Enter people and time : ').split()\nChashier1 = Queue()\nChashier2 = Queue()\nCustomers = Queue()\n\nminute = int(Inp[1])\n\nfor i in Inp[0]:\n Customers.push(i)\n\nfor y in range(1,minute+1,1): \n if (y % 2) == 0:\n Chashier2.deQueue() \n temp = Customers.deQueue()\n if Chashier1.size() == 5:\n if temp is not None:\n Chashier2.push(temp)\n print(y,Customers,Chashier1,Chashier2)\n if Chashier1.size() < 5:\n if temp is not None:\n Chashier1.push(temp)\n print(y,Customers,Chashier1,Chashier2)\n if (y % 3) == 0:\n Chashier1.deQueue()\n\n \n","sub_path":"Grader_3_Queue/Grader3_Queue2.py","file_name":"Grader3_Queue2.py","file_ext":"py","file_size_in_byte":995,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"24"} +{"seq_id":"336334130","text":"from __future__ import division\n\nimport glob\nimport numpy as np\nimport warnings\nfrom netCDF4 import Dataset\n\ndef pla(mu,gamma,alpha):\n with warnings.catch_warnings():\n warnings.simplefilter('ignore')\n a = mu * gamma + (mu*alpha*(1-gamma)**2)/(1-alpha*gamma)\n a[~np.isfinite(a)] = 0\n return a\n\n\ndef calc_cre(base, pert):\n \"\"\"Calculate the cloud radiative effect and approximate split of LW radiation\n into ERFari and ERFaci.\n\n Input:\n base, pert: dicts of CMIP diagnostics required to calculate APRP:\n 'rlut' : toa outgoing longwave flux\n 'rlutcs' : toa outgoing longwave flux assuming clear sky\n\n Output:\n ERFariLW, ERFaciLW: arrays\n \"\"\"\n\n # check all required diagnostics are present\n check_vars = ['rlut', 'rlutcs']\n for var_dict in [base, pert]:\n for check_var in check_vars:\n if check_var not in var_dict.keys():\n raise ValueError('%s not present in %s' % (check_var, var_dict))\n var_dict['rlut'] = var_dict['rlut']\n var_dict['rlutcs'] = var_dict['rlutcs']\n\n ERFLW = -pert['rlut'] - (-base['rlut'])\n ERFaciLW = ERFLW - (-pert['rlutcs'] - (-base['rlutcs']))\n ERFariLW = ERFLW - ERFaciLW\n return ERFariLW, ERFaciLW\n\n\ndef calc_aprp(base, pert, lw=False, breakdown=False, globalmean=False,\n lat=None, cs_threshold=0.02):\n \"\"\"Calculate fluxes using the Approximate Radiative Perturbation method\n (Taylor et al., 2007, https://journals.ametsoc.org/doi/pdf/10.1175/JCLI4143.1)\n \n Input:\n base, pert: dicts of CMIP diagnostics required to calculate APRP:\n 'rsdt' : toa incoming shortwave flux\n 'rsus' : surface upwelling shortwave flux\n 'rsds' : surface downwelling_shortwave flux\n 'clt' : cloud area_fraction\n 'rsdscs' : surface downwelling shortwave flux assuming clear sky\n 'rsuscs' : surface upwelling shortwave flux assuming clear sky\n 'rsut' : toa outgoing shortwave flux\n 'rsutcs' : toa outgoing shortwave flux assuming clear sky\n \n Keywords:\n lw: if True, calculate LW components using cloud radiative effect\n breakdown: if True, provide the forward and reverse calculations of\n APRP in the output, along with the central difference (the mean of\n forward and reverse)\n globalmean: if True, calculate global mean diagnostics (else do\n gridpoint by gridpoint). If globalmean=True, lat must be specified\n lat: latitudes of axis 1. Only required if globalmean=True\n cs_threshold: minimum cloud fraction (0-1 scale) for calculation of\n cloudy-sky APRP. If either perturbed or control run clt is below\n this, set APRP flux to zero. Recommended, as clt appears in\n denominator. Taken from Zelinka's implementation.\n \n Output:\n central[, forward, reverse]: dict(s) of components of APRP as defined\n by equation A2 of Zelinka et al., 2014\n https://agupubs.onlinelibrary.wiley.com/doi/epdf/10.1002/2014JD021710\n\n dict elements are 't1', 't2', ..., 't9' where t? is the\n corresponding term in A2.\n\n dict(s) also contain 'ERFariSW', 'ERFaciSW' and 'albedo' where\n\n ERFariSW = t2 + t3 + t5 + t6\n ERFaciSW = t7 + t8 + t9\n albedo = t1 + t4\n\n if lw==True, central also contains 'ERFariLW' and 'ERFaciLW' as\n calculated from the cloud radiative effect.\n \"\"\"\n\n\n # check all required diagnostics are present\n if lw:\n check_vars = ['rsdt', 'rsus', 'rsds', 'clt', 'rsdscs', 'rsuscs',\n 'rsut', 'rsutcs', 'rlut', 'rlutcs']\n else:\n check_vars = ['rsdt', 'rsus', 'rsds', 'clt', 'rsdscs', 'rsuscs',\n 'rsut', 'rsutcs']\n for var_dict in [base, pert]:\n for check_var in check_vars:\n if check_var not in var_dict.keys():\n raise ValueError('%s not present in %s' % (check_var, var_dict))\n if var_dict[check_var].ndim != 3:\n raise ValueError('%s in %s has %d dimensions (should be 3)' %\n (check_var, var_dict, var_dict[check_var].ndim))\n # if we get to here, rsdt exists, so verify all diagnostics have same shape\n if var_dict[check_var].shape != var_dict['rsdt'].shape:\n raise ValueError('%s %s in %s differs in shape to rsdt %s' %\n (check_var, var_dict[check_var].shape, var_dict, var_dict['rsdt'].shape))\n # rescale cloud fraction to 0-1\n var_dict['clt'] = var_dict['clt']/100.\n\n # require lat for globalmean\n if globalmean:\n if lat is None:\n raise ValueError('lat must be specified for global mean calculation')\n elif len(lat) != base['rsdt'].shape[1]:\n raise ValueError('lat must be the same length as axis 1 of input variables')\n\n # the catch_warnings stops divide by zeros being flagged\n with warnings.catch_warnings():\n warnings.simplefilter('ignore')\n base['rsutoc'] = (base['rsut'] - (1 - base['clt'])*(base['rsutcs']))/base['clt']\n pert['rsutoc'] = (pert['rsut'] - (1 - pert['clt'])*(pert['rsutcs']))/pert['clt']\n base['rsutoc'][~np.isfinite(base['rsutoc'])] = pert['rsutoc'][~np.isfinite(base['rsutoc'])]\n pert['rsutoc'][~np.isfinite(pert['rsutoc'])] = base['rsutoc'][~np.isfinite(pert['rsutoc'])]\n base['rsutoc'][~np.isfinite(base['rsutoc'])] = base['rsutcs'][~np.isfinite(base['rsutoc'])]\n pert['rsutoc'][~np.isfinite(pert['rsutoc'])] = pert['rsutcs'][~np.isfinite(pert['rsutoc'])]\n rsutoc = 0.5*(pert['rsutoc'] + base['rsutoc'])\n rsutcs = 0.5*(pert['rsutcs'] + base['rsutcs'])\n delta_clt = pert['clt'] - base['clt']\n clt = 0.5*(pert['clt'] + base['clt'])\n delta_rsutoc = pert['rsutoc'] - base['rsutoc']\n delta_rsutcs = pert['rsutcs'] - base['rsutcs']\n\n base['rsusoc'] = (base['rsus'] - (1 - base['clt'])*(base['rsuscs']))/base['clt']\n pert['rsusoc'] = (pert['rsus'] - (1 - pert['clt'])*(pert['rsuscs']))/pert['clt']\n base['rsusoc'][~np.isfinite(base['rsusoc'])] = pert['rsusoc'][~np.isfinite(base['rsusoc'])]\n pert['rsusoc'][~np.isfinite(pert['rsusoc'])] = base['rsusoc'][~np.isfinite(pert['rsusoc'])]\n base['rsusoc'][~np.isfinite(base['rsusoc'])] = base['rsuscs'][~np.isfinite(base['rsusoc'])]\n pert['rsusoc'][~np.isfinite(pert['rsusoc'])] = pert['rsuscs'][~np.isfinite(pert['rsusoc'])]\n rsusoc = 0.5*(pert['rsusoc'] + base['rsusoc'])\n rsuscs = 0.5*(pert['rsuscs'] + base['rsuscs'])\n delta_rsusoc = pert['rsusoc'] - base['rsusoc']\n delta_rsuscs = pert['rsuscs'] - base['rsuscs']\n\n base['rsdsoc'] = (base['rsds'] - (1 - base['clt'])*(base['rsdscs']))/base['clt']\n pert['rsdsoc'] = (pert['rsds'] - (1 - pert['clt'])*(pert['rsdscs']))/pert['clt']\n base['rsdsoc'][~np.isfinite(base['rsdsoc'])] = pert['rsdsoc'][~np.isfinite(base['rsdsoc'])]\n pert['rsdsoc'][~np.isfinite(pert['rsdsoc'])] = base['rsdsoc'][~np.isfinite(pert['rsdsoc'])]\n base['rsdsoc'][~np.isfinite(base['rsdsoc'])] = base['rsdscs'][~np.isfinite(base['rsdsoc'])]\n pert['rsdsoc'][~np.isfinite(pert['rsdsoc'])] = pert['rsdscs'][~np.isfinite(pert['rsdsoc'])]\n rsdsoc = 0.5*(pert['rsdsoc'] + base['rsdsoc'])\n rsdscs = 0.5*(pert['rsdscs'] + base['rsdscs'])\n delta_rsdsoc = pert['rsdsoc'] - base['rsdsoc']\n delta_rsdscs = pert['rsdscs'] - base['rsdscs']\n \n A_oc_base = base['rsutoc']/base['rsdt']\n A_oc_base[~np.isfinite(A_oc_base)] = 0. # this is safe\n alpha_oc_base = base['rsusoc']/base['rsdsoc']\n alpha_oc_base[~np.isfinite(alpha_oc_base)] = 0.\n Q_oc_down_base = base['rsdsoc']/base['rsdt']\n Q_oc_down_base[~np.isfinite(Q_oc_down_base)] = 0.\n mu_oc_base = A_oc_base + Q_oc_down_base*(1-alpha_oc_base)\n gamma_oc_base = (mu_oc_base - Q_oc_down_base)/(mu_oc_base - alpha_oc_base*Q_oc_down_base)\n gamma_oc_base[~np.isfinite(gamma_oc_base)] = 0.\n\n A_oc_pert = pert['rsutoc']/pert['rsdt']\n A_oc_pert[~np.isfinite(A_oc_pert)] = 0.\n alpha_oc_pert = pert['rsusoc']/pert['rsdsoc']\n alpha_oc_pert[~np.isfinite(alpha_oc_pert)] = 0.\n Q_oc_down_pert = pert['rsdsoc']/pert['rsdt']\n Q_oc_down_pert[~np.isfinite(Q_oc_down_pert)] = 0.\n mu_oc_pert = A_oc_pert + Q_oc_down_pert*(1-alpha_oc_pert)\n gamma_oc_pert = (mu_oc_pert - Q_oc_down_pert)/(mu_oc_pert - alpha_oc_pert*Q_oc_down_pert)\n gamma_oc_pert[~np.isfinite(gamma_oc_pert)] = 0.\n\n A_cs_base = base['rsutcs']/base['rsdt']\n A_cs_base[~np.isfinite(A_cs_base)] = 0.\n alpha_cs_base = base['rsuscs']/base['rsdscs']\n alpha_cs_base[~np.isfinite(alpha_cs_base)] = 0.\n Q_cs_down_base = base['rsdscs']/base['rsdt']\n Q_cs_down_base[~np.isfinite(Q_cs_down_base)] = 0.\n mu_cs_base = A_cs_base + Q_cs_down_base*(1-alpha_cs_base)\n gamma_cs_base = (mu_cs_base - Q_cs_down_base)/(mu_cs_base - alpha_cs_base*Q_cs_down_base)\n gamma_cs_base[~np.isfinite(gamma_cs_base)] = 0.\n\n A_cs_pert = pert['rsutcs']/pert['rsdt']\n A_cs_pert[~np.isfinite(A_cs_pert)] = 0.\n alpha_cs_pert = pert['rsuscs']/pert['rsdscs']\n alpha_cs_pert[~np.isfinite(alpha_cs_pert)] = 0.\n Q_cs_down_pert = pert['rsdscs']/pert['rsdt']\n Q_cs_down_pert[~np.isfinite(Q_cs_down_pert)] = 0.\n mu_cs_pert = A_cs_pert + Q_cs_down_pert*(1-alpha_cs_pert)\n gamma_cs_pert = (mu_cs_pert - Q_cs_down_pert)/(mu_cs_pert - alpha_cs_pert*Q_cs_down_pert)\n gamma_cs_pert[~np.isfinite(gamma_cs_pert)] = 0.\n\n # Calculate cloudy values of gamma and mu\n gamma_pert = 1 - (1 - gamma_oc_pert)/(1-gamma_cs_pert)\n mu_pert = (mu_oc_pert)/mu_cs_pert\n mu_pert[~np.isfinite(mu_pert)] = 0.\n gamma_base = 1 - (1 - gamma_oc_base)/(1-gamma_cs_base)\n mu_base = (mu_oc_base)/mu_cs_base\n mu_base[~np.isfinite(mu_base)] = 0.\n \n dAoc_dacld = 0.5 * ( (pla(mu_oc_base,gamma_oc_base,alpha_oc_pert)-pla(mu_oc_base,gamma_oc_base,alpha_oc_base)) + (pla(mu_oc_pert,gamma_oc_pert,alpha_oc_pert) - (pla(mu_oc_pert,gamma_oc_pert,alpha_oc_base))) )\n dAoc_dmcld = 0.5 * ( (pla(mu_pert,gamma_base,alpha_oc_base)-pla(mu_base,gamma_base,alpha_oc_base)) + (pla(mu_pert,gamma_pert,alpha_oc_pert) - (pla(mu_base,gamma_pert,alpha_oc_pert))) )\n dAoc_dgcld = 0.5 * ( (pla(mu_base,gamma_pert,alpha_oc_base)-pla(mu_base,gamma_base,alpha_oc_base)) + (pla(mu_pert,gamma_pert,alpha_oc_pert) - (pla(mu_pert,gamma_base,alpha_oc_pert))) )\n\n dAoc_daaer = 0.5 * ( (pla(mu_oc_base,gamma_oc_base,alpha_cs_pert)-pla(mu_oc_base,gamma_oc_base,alpha_cs_base)) + (pla(mu_oc_pert,gamma_oc_pert,alpha_cs_pert) - (pla(mu_oc_pert,gamma_oc_pert,alpha_cs_base))) )\n dAoc_dmaer = 0.5 * ( (pla(mu_cs_pert,gamma_oc_base,alpha_oc_base)-pla(mu_cs_base,gamma_oc_base,alpha_oc_base)) + (pla(mu_cs_pert,gamma_oc_pert,alpha_oc_pert) - (pla(mu_cs_base,gamma_oc_pert,alpha_oc_pert))) )\n dAoc_dgaer = 0.5 * ( (pla(mu_oc_base,gamma_cs_pert,alpha_oc_base)-pla(mu_oc_base,gamma_cs_base,alpha_oc_base)) + (pla(mu_oc_pert,gamma_cs_pert,alpha_oc_pert) - (pla(mu_oc_pert,gamma_cs_base,alpha_oc_pert))) )\n\n dAcs_daclr = 0.5 * ( (pla(mu_cs_base,gamma_cs_base,alpha_cs_pert)-pla(mu_cs_base,gamma_cs_base,alpha_cs_base)) + (pla(mu_cs_pert,gamma_cs_pert,alpha_cs_pert) - (pla(mu_cs_pert,gamma_cs_pert,alpha_cs_base))) )\n dAcs_dmaer = 0.5 * ( (pla(mu_cs_pert,gamma_cs_base,alpha_cs_base)-pla(mu_cs_base,gamma_cs_base,alpha_cs_base)) + (pla(mu_cs_pert,gamma_cs_pert,alpha_cs_pert) - (pla(mu_cs_base,gamma_cs_pert,alpha_cs_pert))) )\n dAcs_dgaer = 0.5 * ( (pla(mu_cs_base,gamma_cs_pert,alpha_cs_base)-pla(mu_cs_base,gamma_cs_base,alpha_cs_base)) + (pla(mu_cs_pert,gamma_cs_pert,alpha_cs_pert) - (pla(mu_cs_pert,gamma_cs_base,alpha_cs_pert))) )\n\n base['rsnt'] = base['rsdt']-base['rsut']\n base['rsntcs'] = base['rsdt']-base['rsutcs']\n pert['rsnt'] = pert['rsdt']-pert['rsut']\n pert['rsntcs'] = pert['rsdt']-pert['rsutcs']\n rsnt = 0.5*(base['rsnt']+pert['rsnt'])\n rsntcs = 0.5*(base['rsntcs']+pert['rsntcs'])\n pert['rsntoc'] = pert['rsdt']-pert['rsutoc']\n base['rsntoc'] = base['rsdt']-base['rsutoc']\n rsntoc = 0.5*(pert['rsntoc']+base['rsntoc'])\n \n # t1 to t9 are the coefficients of equation A2 in Zelinka et al., 2014\n forward = {}\n reverse = {}\n central = {}\n forward['t1'] = -base['rsntcs']*(1-clt)*dAcs_daclr\n forward['t2'] = -base['rsntcs']*(1-clt)*dAcs_dgaer\n forward['t3'] = -base['rsntcs']*(1-clt)*dAcs_dmaer\n forward['t4'] = -base['rsnt']*clt*(dAoc_dacld)\n forward['t5'] = -base['rsnt']*clt*(dAoc_dgaer)\n forward['t6'] = -base['rsnt']*clt*(dAoc_dmaer)\n forward['t7'] = -base['rsnt']*clt*(dAoc_dgcld)\n forward['t8'] = -base['rsnt']*clt*(dAoc_dmcld)\n forward['t9'] = -delta_clt * (rsutoc - rsutcs)\n forward['t2_clr'] = -base['rsntcs']*dAcs_dgaer\n forward['t3_clr'] = -base['rsntcs']*dAcs_dmaer\n \n # set thresholds\n # TODO: can we avoid a hard cloud fraction threshold here?\n forward['t4'] = np.where(np.logical_or(base['clt']