diff --git "a/233.jsonl" "b/233.jsonl" new file mode 100644--- /dev/null +++ "b/233.jsonl" @@ -0,0 +1,765 @@ +{"seq_id":"81575477","text":"import os\nimport sys\nimport csv\nimport subprocess\nimport time\nfrom datetime import datetime\nimport pandas as pd\nimport getopt\nimport matplotlib.pyplot as plt\nimport matplotlib.dates as mdates\n\n\n\ndef show_pid_data(ifile, timeRefrush, pid):\n plt.style.use(\"fivethirtyeight\")\n # mng = plt.get_current_fig_manager()\n # mng.full_screen_toggle()\n df = pd.read_csv(ifile)\n lx = df.columns.values.tolist()[2:]\n lx = [datetime.strptime(d, '%Y-%m-%d %H:%M:%S') for d in lx]\n ylist = df.values.tolist()\n ylshow = []\n for l in ylist:\n if pid == l[0]:\n ylshow = l[2:]\n break\n\n plt.gca().xaxis.set_major_formatter(\n mdates.DateFormatter('%Y-%m-%d %H:%M:%S'))\n plt.gcf().autofmt_xdate()\n plt.ion()\n rowCnt = len(lx)\n i = 2\n sub = 3\n while i < rowCnt:\n plt.clf()\n plt.gca().xaxis.set_major_formatter(\n mdates.DateFormatter('%Y-%m-%d %H:%M:%S'))\n plt.gcf().autofmt_xdate()\n plt.ylabel(\"Memery Used (KB)\")\n plt.title(\"Memory Usd (Pid = \" + str(pid) + \")\")\n plt.stackplot(lx[i:i + sub], ylshow[i:i + sub], colors=['#20ab47'])\n plt.pause(timeRefrush)\n i = i + sub\n\n\ndef show_total_data(ifile, timeRefrush):\n plt.style.use(\"fivethirtyeight\")\n # mng = plt.get_current_fig_manager()\n # mng.full_screen_toggle()\n df = pd.read_csv(ifile)\n lx = df.columns.values.tolist()[2:]\n lx = [datetime.strptime(d, '%Y-%m-%d %H:%M:%S') for d in lx]\n ylist = df.values.tolist()\n idx = 0\n for l in ylist:\n ylist[idx] = l[2:]\n idx = idx + 1\n\n plt.gca().xaxis.set_major_formatter(\n mdates.DateFormatter('%Y-%m-%d %H:%M:%S'))\n plt.gcf().autofmt_xdate()\n plt.ion()\n rowCnt = len(lx)\n i = 2\n sub = 3\n while i < rowCnt:\n plt.clf()\n plt.gca().xaxis.set_major_formatter(\n mdates.DateFormatter('%Y-%m-%d %H:%M:%S'))\n plt.gcf().autofmt_xdate()\n plt.ylabel(\"Memery Used (KB)\")\n plt.title(\"Memory Total All Process\")\n ylistSub = []\n for j in ylist:\n ylistSub.append(j[i:i + sub])\n plt.stackplot(lx[i:i + sub], ylistSub)\n plt.pause(timeRefrush)\n i = i + sub\n\ndef report_all_procee_data(ifile, outdir=''):\n plt.style.use(\"fivethirtyeight\")\n pd.plotting.register_matplotlib_converters()\n df = pd.read_csv(ifile)\n lx = df.columns.values.tolist()[2:]\n lx = [datetime.strptime(d, '%Y-%m-%d %H:%M:%S') for d in lx]\n ylist = df.values.tolist()\n\n outdir = outdir + \"/process-memory-info\"\n if os.path.exists(outdir):\n subprocess.call('rm -rf ' + outdir + '*',shell=True)\n else:\n os.makedirs(outdir)\n\n for l in ylist:\n plt.clf()\n plt.figure(figsize=(19.2,6.4))\n plt.gca().xaxis.set_major_formatter(\n mdates.DateFormatter('%Y-%m-%d %H:%M:%S'))\n plt.gcf().autofmt_xdate()\n plt.ylabel(\"Memery Used (KB)\")\n plt.title(\"Memory Usd (PName = \" + str(l[1]) + \")\")\n plt.stackplot(lx, l[2:])\n if outdir != '':\n plt.savefig(outdir +\"/\"+ str(l[1]).replace('.','_') + \".png\", dpi=100)\n else:\n plt.show()\n plt.close()\n\n\n","sub_path":"memory/showProcess.py","file_name":"showProcess.py","file_ext":"py","file_size_in_byte":3202,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"226309261","text":"import os\nfrom pytube import YouTube\nimport ffmpeg\n\nlink = input('Enter youtube link: ')\nyt = YouTube(link)\ntitle = yt.title\nquestion = input(f\"Is '{title}'' the title of the video?(y/n): \")\nif question.lower() == 'y':\n\tstream = yt.streams.filter(only_audio = True).first()\n\tprint('Downloading from YouTube...')\n\tstream.download()\n\tprint('Downloaded!')\n\tcmd = f'mv \"{title}.mp4\" input.mp4'\n\tos.system(cmd)\n\tprint('Converting to mp3...')\n\tcmd = f'ffmpeg -i input.mp4 audio.mp3 >/dev/null 2>&1'\n\tos.system(cmd)\n\tcmd = f'rm -rf input.mp4'\n\tos.system(cmd)\n\tcmd = f'mv audio.mp3 \"{title}.mp3\"'\n\tos.system(cmd)\n\tprint('Done!')\nelse: print('try again')","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":645,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"317182377","text":"from . import views\nfrom django.urls import path\n\nurlpatterns = [\n path('', views.home, name='home'),\n path('sort//', views.sort, name='sort'),\n\n path('detail//', views.detail, name='detail'),\n path('play//', views.play, name='play'),\n\n path('create/', views.create, name='create'),\n path('update//', views.update, name='update'),\n path('delete//', views.delete, name='delete'),\n]\n","sub_path":"home/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":444,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"406806611","text":"# -*- coding: utf-8 -*-\r\nfrom backend.models import Order, Sales, Profile, Item\r\nfrom backend.lib.Wrapper import wrapper\r\nfrom django.db.models import Q\r\nfrom django.utils import simplejson\r\n\r\n# /api/report/summary\r\ndef index(request):\r\n #return wrapper(request=request, req_params=['vendor', 'search', 'start', 'limit'], worker=worker, context='vendor')\r\n return wrapper(request=request, req_params=['vendor', 'search', 'start', 'limit', 'sort', 'show_disabled', 'show_best'], \\\r\n worker=worker, context='vendor')\r\n\r\n\r\ndef worker(req):\r\n vendor_id = req.params()['vendor']\r\n search = req.params()['search']\r\n parent_user_id = req.params()['parent_user_id']\r\n start = req.params()['start']\r\n limit = req.params()['limit']\r\n #sortArr = 'id' #req.params()['sort'] # when uncomenting this line, write description why\r\n sortArr = req.params()['sort']\r\n show_best = True\r\n show_disabled = req.params()['show_disabled']\r\n show_best = req.params()['show_best'] # if show_best == true, return only those items, whose product is at best price\r\n\r\n ## /lib/vendor may return sort as a string 'id', below might not work, revise when you find errors\r\n sort = []\r\n\r\n if sortArr == 'id' or len(sortArr) == 0:\r\n sort.append('product__name1')\r\n \r\n else:\r\n for s in sortArr:\r\n if s['property'] == 'name1' or s['property'] == 'product_num' or s['property'] == 'category' \\\r\n or s['property'] == 'price_per_unit' or s['property'] == 'brand' or s['property'] == 'on_sale' :\r\n s['property'] = 'product__' + s['property']\r\n elif s['property'] == 'loc_ret_dept':\r\n s['property'] = 'item__' + s['property']\r\n elif s['property'] == 'category_name':\r\n s['property'] = 'item__category__name'\r\n elif s['property'] == 'item':\r\n s['property'] = 'item__name'\r\n elif s['property'] == 'order_qt':\r\n s['property'] = 'order_qt'\r\n else:\r\n s['property'] = 'id'\r\n if s['direction'] == 'DESC':\r\n s['property'] = '-' + s['property']\r\n sort.append(s['property'])\r\n else: # 'ASC'\r\n s['property'] = s['property']\r\n sort.append(s['property'])\r\n\r\n if len(sort) == 0:\r\n sort.append('product__product_num')\r\n \r\n total = 0\r\n #return { \"success\": True, \"sort\": sort, \"len\": len(sort)}\r\n if search != '':\r\n sq = Q()\r\n sq = sq | Q(item__upc__icontains=search) | Q(item__upc_2__icontains=search)\r\n sq = sq | Q(item__upc_3__icontains=search) | Q(item__upc_case__icontains=search)\r\n sq = sq | Q(product__name1__icontains=search) | Q(product__brand__icontains=search)\r\n sq = sq | Q(item__name__icontains=search ) | Q(product__product_num__icontains=search)\r\n\r\n total = Order.objects.filter(sq, product__vendor=vendor_id, user=parent_user_id).count()\r\n orders = Order.objects.select_related().filter(sq, product__vendor=vendor_id, user=parent_user_id).\\\r\n extra(order_by = sort)[start:start+limit] #, 'product__product_num')[start:start+limit]\r\n else:\r\n if show_best:\r\n if show_disabled == True:\r\n total = Order.objects.filter(best_priced=True, product__vendor=vendor_id, user=parent_user_id).count()\r\n orders = Order.objects.select_related().filter(best_priced=True, product__vendor=vendor_id, user=parent_user_id).\\\r\n extra(order_by = sort)[start:start+limit]\r\n else:\r\n total = Order.objects.filter(best_priced=True, product__vendor=vendor_id, user=parent_user_id).exclude(item__enabled=False).count()\r\n orders = Order.objects.select_related().filter(best_priced=True, product__vendor=vendor_id, user=parent_user_id).\\\r\n exclude(item__enabled=False).extra(order_by = sort)[start:start+limit]\r\n\r\n else:\r\n if show_disabled == True:\r\n total = Order.objects.filter(product__vendor=vendor_id, user=parent_user_id).count()\r\n orders = Order.objects.select_related().filter(product__vendor=vendor_id, user=parent_user_id).\\\r\n extra(order_by = sort)[start:start+limit]\r\n else:\r\n total = Order.objects.filter(product__vendor=vendor_id, user=parent_user_id).exclude(item__enabled=False).count()\r\n orders = Order.objects.select_related().filter(product__vendor=vendor_id, user=parent_user_id).\\\r\n exclude(item__enabled=False).extra(order_by = sort)[start:start+limit]\r\n\r\n\r\n data = []\r\n for order in orders:\r\n prop = order.list()\r\n prop['item_enabled'] = order.item.enabled\r\n prop['qt_in_stock'] = replace(order.item.qt_in_stock)\r\n prop['min_qt_in_stock'] = replace(order.item.min_qt_in_stock)\r\n prop['loc_stock'] = replace(order.item.loc_stock)\r\n prop['loc_ret_dept'] = replace(order.item.loc_ret_dept)\r\n prop['loc_ret_col'] = replace(order.item.loc_ret_col)\r\n prop['loc_ret_row'] = replace(order.item.loc_ret_row)\r\n prop['loc_retail'] = ''\r\n if prop['loc_ret_dept'] != '':\r\n prop['loc_retail'] = prop['loc_retail'] + prop['loc_ret_dept']\r\n if prop['loc_ret_col'] != '':\r\n prop['loc_retail'] = prop['loc_retail'] + '-' + prop['loc_ret_col']\r\n if prop['loc_ret_row'] != '':\r\n prop['loc_retail'] = prop['loc_retail'] + '-' + prop['loc_ret_row']\r\n\r\n data.append( prop )\r\n\r\n return { \"success\": True, \"total\": total, \"data\": data}\r\n\r\ndef replace(text):\r\n if text is None:\r\n return u''\r\n else:\r\n text = u'%s' % text\r\n return text if text else u''","sub_path":"backend/report/summary/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":5859,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"94848725","text":"# coding=utf-8\n\n__author__ = 'jamon'\nimport copy\nfrom obespoir.share.ob_log import logger\nfrom share.message_ids import *\nfrom service.mahjong.models.playeract.base_player_act import BasePlayerAct\nfrom service.mahjong.constants.gamedefine import Act, SettleType\nfrom service.mahjong.models.actrecord import ActRecord\nfrom service.mahjong.models.timermanager import timer_manager_ins\nfrom service.mahjong.controls.notifybridge import notify_single_user\n\n\nclass ZiMo(BasePlayerAct):\n def __init__(self, game_data):\n super(ZiMo, self).__init__(game_data=game_data)\n self.step_handlers = {\n \"param_check\": self.param_check, # 参数验证\n \"clear_other_act\": self.clear_other_act, # 清除该玩家其他动作\n \"set_data\": self.set_data, # 设置相应数据\n \"record\": self.record, # 记录玩家动作\n \"notify_other_player\": self.notify_other_player, # 通知其他玩家\n }\n\n self.seat_id = -1 # 执行胡牌的玩家位置\n self.type_list = [] # 胡牌的胡牌类型\n self.hand_card = None\n\n def execute(self, act_params={}):\n \"\"\"\n 执行自摸\n :param act_params:\n :return:\n \"\"\"\n logger.debug(u\"自摸胡牌: %s\", str(act_params))\n for step in self.game_config.player_act_step.get(Act.ZI_MO):\n for name, cfg in step.items():\n ret = self.step_handlers.get(name)(act_params=act_params, config_params=cfg)\n if not ret:\n logger.error(\"step:%s\", step)\n return\n\n self.settle(settle_type_list=[SettleType.HU])\n if self.game_config.is_hu_end:\n # 当回合胡牌后结束当局游戏\n self.end_game()\n return 1\n\n def param_check(self, **kwargs): # 参数验证\n act_params = kwargs.get(\"act_params\")\n if 1 != len(act_params):\n # 同时只允许有一个玩家发生自摸操作\n logger.debug(u\"act_zimo_error:%s\", str(act_params))\n return\n\n seat_id = list(act_params.keys())[0]\n params = act_params[seat_id]\n\n hand_card_vals = self.players[seat_id].hand_card.hand_card_vals\n # if 2 != len(hand_card_vals) % 3 or not self.players[seat_id].can_hu_result:\n if 2 != len(hand_card_vals) % 3:\n logger.error(\"dian_hu params error: %s\", str([seat_id, params]))\n return\n\n self.seat_id = seat_id\n self.hand_card = self.players[seat_id].hand_card\n return 1\n\n def clear_other_act(self, **kwargs): # 清除该玩家其他动作\n timer_manager_ins.kill_timer(self.desk_id, self.seat_id, is_force=True)\n return 1\n\n def set_data(self, **kwargs): # 设置相应数据\n # 记录自摸信息\n self.game_data.players[self.seat_id].hand_card.zi_mo = 1\n # 将手牌信息保存入 hand_card_for_settle_show 用于游戏结束手牌的展示\n # self.game_data.players[self.seat_id].hand_card.hand_card_for_settle_show[-1] = [self.game_data.last_get_card_val[self.seat_id]]\n # 储存胡的牌值\n self.game_data.players[self.seat_id].hand_card.hu_card_val = self.game_data.last_get_card_val[self.seat_id]\n # 联合手牌,用于计算胡牌番型\n for i in range(self.game_data.max_player_num):\n self.game_data.players[i].hand_card.union_hand_card()\n\n # 计算结算相关数据,用于101006\n type_list = self.game_data.hu_manager.check_hu_result(self.hand_card)\n self.game_data.hu_player_static[self.seat_id] = {\n \"type_list\": type_list,\n \"is_zi_mo\": 1,\n \"source_seat_id\": -1,\n \"guo_hu_count\": self.game_data.players[self.seat_id].hand_card.guo_hu_num,\n \"settle_hand_card\": self.game_data.players[self.seat_id].hand_card.hand_card_for_settle_show\n }\n # 是否天地胡牌\n if len(self.players[self.seat_id].hand_card.drewed_card_lst) == 1 and self._is_first_has_chi_peng():\n if self.seat_id == self.game_data.banker_seat_id:\n # 天胡\n self.players[self.seat_id].hand_card.is_tian_hu = 1\n else:\n # 地胡\n self.players[self.seat_id].hand_card.is_di_hu = 1\n\n return 1\n\n def record(self, **kwargs): # 记录玩家动作\n act_record = ActRecord(self.seat_id, Act.ZI_MO, [])\n self.game_data.act_record_list.append(act_record)\n return 1\n\n\n def notify_other_player(self, **kwargs): # 记录玩家动作\n act_info = {\"seat_id\": self.seat_id, \"act_type\": Act.ZI_MO, \"card_list\": []}\n for i in range(self.game_data.max_player_num):\n notify_single_user(self.desk_id, self.seat_id, PUSH_OTHER_PLAYER_CALL_CARD, act_info)\n return 1\n\n def _is_first_has_chi_peng(self):\n if len(self.game_data.act_record_list) != 1:\n return False\n for act in self.game_data.act_record_list:\n if act.act_type in [20, 30]:\n return True\n return False","sub_path":"echecs_espoir/service/mahjong/models/playeract/zimo.py","file_name":"zimo.py","file_ext":"py","file_size_in_byte":5114,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"651161082","text":"\"\"\"\nGrid topoplot\n=============\n\nDisplay topographic plots into a grid.\n\n.. image:: ../../picture/pictopo/ex_grid_topoplot.png\n\"\"\"\nfrom visbrain import Topo\n\n# Create a topoplot instance :\nt = Topo()\n\n# Create a list of channels, data, title and colorbar label :\nchannels = ['C3', 'C4', 'Cz', 'Fz', 'Pz']\ndata = [10, 20, 30, 10, 10]\nkwargs = {'title_size': 2., 'cb_txt_size': 2, 'margin': 20 / 100,\n 'chan_offset': (0., 0.08, 0.)}\n\n# Position (0, 0)\nt.add_topoplot('Topo_1', data, channels=channels, title='Topo_1',\n cmap='viridis', row=0, col=0, **kwargs)\n\n# Position (0, 1)\nt.add_topoplot('Topo_2', data, channels=channels, title='Topo_2',\n cmap='plasma', row=0, col=1, **kwargs)\n\n# Position (1, 0)\nt.add_topoplot('Topo_3', data, channels=channels, title='Topo_3',\n cmap='Spectral_r', row=1, col=0, **kwargs)\n\n# Position (1, 1)\nt.add_topoplot('Topo_4', data, channels=channels, title='Topo_4',\n cmap='gist_stern', row=1, col=1, **kwargs)\n\n# Position (2, 0:1)\nt.add_topoplot('Topo_5', data, channels=channels, title='Topo_5',\n cmap='Blues', row=2, col=0, col_span=2, **kwargs)\n\n# Position (0:3, 2)\nt.add_topoplot('Topo_6', data, channels=channels, title='Topo_6',\n cmap='Reds', row=0, col=2, row_span=3, **kwargs)\n\n# Show the window :\nt.show()\n","sub_path":"examples/topo/02_grid_topoplot.py","file_name":"02_grid_topoplot.py","file_ext":"py","file_size_in_byte":1338,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"145677740","text":"import torch\nimport numpy as np\nimport sys\nsys.path.append(\"/home/megh/projects/domain-adaptation/SSAL/\")\nfrom loaders.data_list import Imagelists_VISDA, return_classlist\nfrom model.basenet import *\nfrom model.resnet import *\nfrom torchvision import transforms\nfrom utils.return_dataset import ResizeImage\nfrom utils.utils import k_means\nimport time\nimport os\nfrom torch.autograd import Variable\nimport pickle\nfrom easydict import EasyDict as edict\nfrom utils.return_dataset import *\nfrom easydict import EasyDict as edict\nfrom utils.utils import *\n\ndef main():\n net = \"resnet34\"\n root = '../data/multi/'\n target = \"sketch\"\n image_list_target_unl = \"../data/txt/multi/unlabeled_target_images_%s_3.txt\"%(target)\n num = 3\n f = open(image_list_target_unl,\"r\")\n print(len([line for line in f]))\n\n args = edict({\"net\":net,\"source\":\"real\",\"target\":target,\"dataset\":\"multi\",\"num\":num,\"uda\":1})\n source_loader, target_loader, target_loader_unl, target_loader_val, target_loader_test, class_list = return_dataset_randaugment(args,txt_path='../data/txt/',root_path='../data/', bs_alex=1, bs_resnet=1) \n n_class = len(class_list)\n print(len(target_loader_unl.dataset))\n\n # Defining the pytorch networks\n if net == 'resnet34':\n G = resnet34()\n inc = 512\n print(\"Using: \", net)\n elif net == 'resnet50':\n G = resnet50()\n inc = 2048\n print(\"Using: \", net)\n elif net == \"alexnet\":\n G = AlexNetBase()\n inc = 4096\n print(\"Using: \", net)\n elif net == \"vgg\":\n G = VGGBase()\n inc = 4096\n print(\"Using: \", net)\n else:\n raise ValueError('Model cannot be recognized.')\n\n if net == 'resnet34':\n F1 = Predictor_deep(num_class=n_class,inc=inc)\n print(\"Using: Predictor_deep_attributes\")\n else:\n F1 = Predictor(num_class=n_class,inc=inc)\n print(\"Using: Predictor_attributes\")\n\n G.eval().cuda()\n F1.eval().cuda()\n # Loading the weights from the checkpoint\n ckpt = torch.load(\"../save_model_ssda/resnet34_real_sketch_8000.ckpt.pth.tar\")\n G_dict = ckpt[\"G_state_dict\"]\n G.load_state_dict(G_dict)\n F1_dict = ckpt[\"F1_state_dict\"]\n G.load_state_dict(G_dict)\n F1.load_state_dict(F1_dict)\n # Loading the feature bank from pkl file\n f = open(\"../banks/resnet34_sketch_8000.pkl\",\"rb\")\n feat_dict = edict(pickle.load(f))\n print(feat_dict.keys())\n print(feat_dict.feat_vec.shape)\n feat_dict.feat_vec = feat_dict.feat_vec.cuda()\n top1 = 0\n top2 = 0\n top3 = 0\n total = 0\n worst_classes = get_worst_classes(np.load(\"cf_labelled_target.npy\"))\n print(worst_classes)\n print(len(worst_classes) * 9)\n with torch.no_grad():\n for idx, batch in enumerate(target_loader):\n gt_label = batch[1].cpu().data.item()\n if gt_label in worst_classes:\n sim_distribution_weak = get_similarity_distribution(feat_dict,batch,G, source = False, i = 0, mode = 'euclid')\n sim_distribution_strong = get_similarity_distribution(feat_dict,batch,G, source = False, i = 1, mode = 'euclid')\n sim_distribution_standard = get_similarity_distribution(feat_dict,batch,G, source = False, i = 2, mode = 'euclid') \n\n k_neighbors, labels_k_neighbors_weak = get_kNN(sim_distribution_weak, feat_dict, 3) \n k_neighbors, labels_k_neighbors_strong = get_kNN(sim_distribution_weak, feat_dict, 3) \n k_neighbors, labels_k_neighbors_standard = get_kNN(sim_distribution_weak, feat_dict, 3) \n labels_k_neighbors_weak, labels_k_neighbors_strong, labels_k_neighbors_standard = labels_k_neighbors_weak[0], labels_k_neighbors_strong[0], labels_k_neighbors_standard[0]\n\n top1 = top1 + int(labels_k_neighbors_weak[0]==gt_label) + int(labels_k_neighbors_standard[0]==gt_label) + int(labels_k_neighbors_strong[0]==gt_label)\n top2 = top2 + int(labels_k_neighbors_weak[1]==gt_label) + int(labels_k_neighbors_standard[1]==gt_label) + int(labels_k_neighbors_strong[1]==gt_label)\n top3 = top3 + int(labels_k_neighbors_weak[2]==gt_label) + int(labels_k_neighbors_standard[2]==gt_label) + int(labels_k_neighbors_strong[2]==gt_label) \n total = total + 9\n print(top1,top2,top3)\n\ndef get_worst_classes(confusion_matrix, top_k = 30):\n num_classes, num_classes = confusion_matrix.shape\n acc_list = []\n for i in range(num_classes):\n acc_list.append(confusion_matrix[i,i]/sum(confusion_matrix[i,:]))\n arr_acc_list = np.array(acc_list)\n idx = np.argsort(arr_acc_list)\n idx = idx[0:top_k]\n print(arr_acc_list[idx])\n return idx\n\nif __name__ == \"__main__\":\n main()\n\n","sub_path":"misc_scripts/analysis/knn_analysis.py","file_name":"knn_analysis.py","file_ext":"py","file_size_in_byte":4799,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"17911857","text":"##### DATA IS UNFORTUNATELY CRAP\n\n#NDs 10kV 30mum \n#482nm dicroic, acquisition with red PMT\n\n#lag mus\n#moving ns\n#excitation mus\n#transient ns\n#clock 25MHZ --> 40ns time bins\n#512x512 pixels\n#se pics: 100mus lag per pixel, 500kHz clock \n\nimport os\nimport sys\nsys.path.append(\"/usr/bin\") # necessary for the tex fonts\nsys.path.append(\"../Python modules/\") # necessary for the tex fonts\nimport scipy as sp\nimport scipy.misc\nimport matplotlib\n#matplotlib.use(\"Agg\")\nimport matplotlib.pyplot as plt\nimport h5py\nimport numpy as np\nfrom BackgroundCorrection import *\nfrom TConversionThermocoupler import *\nimport matplotlib.cm as cm\nimport scipy.ndimage as ndimage\n#from matplotlib_scalebar.scalebar import ScaleBar #### Has issue with plotting using latex font. only import when needed, then unimport\nfrom mpl_toolkits.axes_grid1 import make_axes_locatable\nfrom matplotlib.backends.backend_pdf import PdfPages\nfrom MakePdf import *\nfrom matplotlib.pyplot import cm #to plot following colors of rainbow\nfrom matplotlib import rc\nfrom CreateDatasets import *\nimport warnings\nwarnings.simplefilter(action = \"ignore\", category = RuntimeWarning)\nwarnings.simplefilter(action = \"ignore\", category = DeprecationWarning)\nwarnings.simplefilter(action = \"ignore\", category = FutureWarning)\nwarnings.simplefilter(action = \"ignore\", category = PendingDeprecationWarning)\nfrom Registration import * \nfrom tifffile import *\nfrom sklearn.mixture import GMM \nimport matplotlib.cm as cm\nfrom FluoDecay import *\nfrom PlottingFcts import *\n\nimport matplotlib.animation as animation\nimport gc\nimport tempfile\nfrom tempfile import TemporaryFile\n#PARAMS THAT NEED TO BE CHANGED\n###############################################################################\n###############################################################################\n###############################################################################\n#index = 0\ncalc_blue = True\n#Excitation is impulsive, 120ns per pulse,turn on at point no 80, off at point no 82\n\n#No_pixels = 250\nTime_bin = 40#in ns; 1/clock of 25MHz \nnominal_time_on = 1.8 #time during which e-beam nominally on, in mus\ntotalpoints = 150 #total number of time-resolved points\n### data\nif calc_blue is False:\n pmt = ['PMT red']\n channel = ['1']\nelse:\n pmt = ['PMT blue']\n channel = ['2']\n \nnamese = ['2016-10-27-1407_ImageSequence_NDs_49.732kX_10.000kV_30mu_7',\n '2016-10-27-1447_ImageSequence_ND20sample_89.953kX_10.000kV_30mu_4']\n \nnametr = ['2016-10-27-1417_ImageSequence_NDs_49.732kX_10.000kV_30mu_8',\n '2016-10-27-1455_ImageSequence_ND20sample_89.953kX_10.000kV_30mu_5']\n \nNo_experiments = [5,5]\n\ndescription = ['Adamas NDs'] # (20kV, 30$\\mu$m, ' + str(Ps[index]) + 'nm pixels, ' + str(No_experiments[index]) + 'expts., InLens registered)'] #, \\n' #+ obs[index] '] \n \nkv = [10]\n\nlet = ['I', 'II']\n\n#tau_single = np.zeros(len(name))\n#tau_single_error = np.zeros(len(name))\n#tau_bi = np.zeros([len(name),2])\n#tau_bi_error = np.zeros([len(name),2])\n\n#original\n#for index in np.arange(11,11): #11):\n\nindex = 5\nif index is 6:\n \n#for Er60 only: np.arange(9,12)\n#for index in np.arange(0,len(nametr)):\n\n print(index)\n\n file1 = h5py.File(namese[index] + '.hdf5', 'r') \n file2 = h5py.File(nametr[index] + '.hdf5', 'r') \n #file3 = h5py.File(namese2[index] + '.hdf5', 'r') \n titulo = 'NDs Adamas'\n #il1_dset = file2['/data/Analog channel 2 : InLens/data'] #10 Scany points X 10 frames X 250 x 250 pixels\n se1_dset = file1['/data/Analog channel 1 : SE2/data'] #10 Scany points X 10 frames X 250 x 250 pixels\n #se2_dset = file3['/data/Analog channel 1 : SE2/data']\n red0_dset = file2['/data/Counter channel 1 : PMT red/PMT red time-resolved/data']#10 Scany points X10 frames x 150 tr pts x250 x 250 pixels\n #blue0_dset = file2['/data/Counter channel 2 : PMT blue/PMT blue time-resolved/data']#10 Scany points X 10 frames x 150 tr pts x250 x 250 pixels\n \n #red1_dset50 = file3['/data/Counter channel ' + channel[index] + ' : '+ pmt[index]+'/' + pmt[index] + ' time-resolved/data']#50 frames x 200 tr pts x250 x 250 pixels\n #red1_dset = np.append(red1_dset , red1_dset50, axis = 0)\n \n Pixel_size = red0_dset.attrs['element_size_um'][1]*1000.0 #saved attribute is in micron; converting to nm\n Ps = [str(\"{0:.2f}\".format(Pixel_size))] #pixel size in nm, the numbers above with round nm precision \n \n print(red0_dset.shape)\n \n #cut part of frames with ebeam off, here 25 first points\n #cut_at_beginning = 0\n #red1_dset = red1_dset[:,:,cut_at_beginning::,:,:]\n \n #hack to go faster\n fastfactor = 1\n #se1_dset = se1_dset[0::fastfactor,:,:]\n #red1_dset = red1_dset[0::fastfactor,:,:,:]\n \n #no experiments to consider\n #se1_dset = se1_dset[0:No_experiments[index]+1,:,:]\n red1_dset = red0_dset#[0:No_experiments[index]+1,:,:,:]#.reshape((No_experiments[index],:,:,:],150,250,250))\n #blue1_dset = blue0_dset#[0:No_experiments[index]+1,:,:,:]#.reshape((No_experiments[index],:,:,:],150,250,250))\n \n #convert to smaller data types\n se1_dset2 = np.array(se1_dset) #, dtype=np.float16) #convert to 16 if needed\n #se2_dset2 = np.array(se2_dset) #, dtype=np.float16) #convert to 16 if needed\n #se1_dset2.reshape((10,250,250))\n #il1_dset2 = np.array(il1_dset) #, dtype=np.float16)\n #il1_dset2.reshape((10,250,250))\n \n red1_dset = np.array(red1_dset) \n #blue1_dset = np.array(blue1_dset) \n #convert red1_dset to kHz!!!!!!!!!!!!!!!!!!!!!1\n red1_dset = red1_dset/1.0e3\n red1_dset = np.array(red1_dset, dtype=np.float32) #converting the CL dset to float16 from float64 is creating infinities! bc max value is > 2^16 \n #blue1_dset = blue1_dset/1.0e3\n #blue1_dset = np.array(blue1_dset, dtype=np.float32) #converting the CL dset to float16 from float64 is creating infinities! bc max value is > 2^16 \n \n print('data loaded')\n \n #PLOT EXPT BY EXPT BEHAVIOUR ON ALL PIXELS\n ###############################################################################\n ###############################################################################\n ###############################################################################\n \n ###FIG 1\n #if index >= 8: #8,9,10,11: the 4 from Er 60% \n #major_ticks = [2,4,6]\n #else:\n #major_ticks = [5,15,25]\n #plot_expt_by_expt_behaviour(titulo + r', all pixels', red1_dset, Time_bin, nominal_time_on,fastfactor,'r',major_ticks,dark_dset=None,plot_dark=False,unit='kHz') #pass titulo as well\n #fig_no = 'Fig#1'\n #multipage(name_str[index] + fig_no + '.pdf',dpi=80)\n ###END FIG1\n \n #REGISTRATION OF CL CHANNEL ONTO SE CHANNEL \n ###############################################################################\n ###############################################################################\n ###############################################################################\n #independently\n #se1_dset_reg = reg_images(se1_dset)\n #The code below registers time resolved data to itself, across frames. Each one of the tr points is registered to the same time point in other frames\n #red_dset_reg_list = reg_images_tr(red1_dset) #list is across number of time resolved points #Does not work too well for this dset BUT TRY WITH OTHERS\n #Future: make tr, say, of red register to time resolved, say, of blue\n \n #!!!!!REAL Registration - UNCOMMENT! !!!!!achtung: is giving some errors with nan and inf!!!!! WHY???????\n \n #USING START AND END SE IMAGES, AVERAGED SPATIALLY, TO REGISTER. NOT SURE BEST OPTION YET\n #se1r, se2r = reg_images(se1_dset2,se2_dset2) \n #se3 = (se1r + se2r)/2.0\n #se3 = se3.reshape([1,se1_dset2.shape[1],se1_dset2.shape[2]])\n #se4 = np.zeros([red1_dset.shape[0], se1_dset2.shape[1],se1_dset2.shape[2]])\n #for jjj in np.arange(0,red1_dset.shape[0]):\n # se4[jjj,:,:] = se3.reshape([500,500])\n # se1_dset_reg, red1_dset_reg, red1_dset_reg_all = reg_time_resolved_images_to_se(se4,red1_dset)\n #se1_dset_reg, blue1_dset_reg, blue1_dset_reg_all = reg_time_resolved_images_to_se(se1_dset2, blue1_dset)\n \n #se1_dset_reg, red1_dset_reg, red1_dset_reg_all = reg_time_resolved_images_to_se(se1_dset2, red1_dset)\n #se1_dset_reg, blue1_dset_reg, blue1_dset_reg_all = reg_time_resolved_images_to_se(se1_dset2, blue1_dset)\n \n ##red1_dset_reg, red1_dset_reg_all = reg_images(red1_dset) \n ##se1_dset_reg = np.array(se1_dset, dtype=np.float16)\n \n #se1_dset_reg = np.array(se1_dset_reg, dtype=np.float16)\n #red1_dset_reg = np.array(red1_dset_reg, dtype=np.float32)\n #red1_dset_reg_all = np.array(red1_dset_reg_all, dtype=np.float32)\n \n #second step of registerist CL using bright CL: does NOT cause errors!!!\n #right now, remaining totalpoints - cut_at_beginning time resolved points, over all experiments\n #25 dark (in reality, dark until 28)/ 50 bright / 125 transient\n #cut arrays are 3 / 50 / 125\n #center_cl_index = 3 # (50 + 3)/2 # this index is going to be used as reference\n #end_left_index = 0#not used for the time being\n #end_right_index = 0#not used for the time being\n #new = reg_images_middle_cl(red1_dset_reg,center_cl_index,0,0)\n #red1_dset_reg = np.array(new, dtype=np.float32)\n \n #!!!!!END OF REAL Registration - UNCOMMENT! \n #print(np.sum(np.isnan(red1_dset_reg)))\n #print(np.sum(np.isinf(red1_dset_reg)))\n #print(np.sum(np.isnan(blue1_dset_reg)))\n #print(np.sum(np.isinf(blue1_dset_reg)))\n \n# ###MOCK REGISTRATION, QUICK FOR HACK ####################################!!!!!!!!!!!!!!!!!!!!\n #if (index is 3) or (index is 6):\n se1_dset_reg = np.average(se1_dset2, axis=0)\n #se1_dset_reg, sth = reg_images(se1_dset2) \n #del sth\n red1_dset_reg = np.average(red1_dset, axis=0)\n red1_dset_reg_all = np.array(red1_dset)\n #blue1_dset_reg = np.average(blue1_dset, axis=0)\n #blue1_dset_reg_all = np.array(blue1_dset)\n #se1_dset_reg = np.array(se1_dset_reg, dtype=np.float16)\n #red1_dset_reg = np.array(red1_dset_reg, dtype=np.float32)\n #red1_dset_reg_all = np.array(red1_dset_reg_all, dtype=np.float32)\n\n #il1_dset_reg = il1_dset\n \n# blue1_dset_reg = np.average(blue1_dset, axis=0)\n# blue1_dset_reg_all = np.array(blue1_dset)\n #il1_dset_reg = np.array(il1_dset_reg, dtype=np.float32)\n# blue1_dset_reg = np.array(blue1_dset_reg, dtype=np.float32)\n# blue1_dset_reg_all = np.array(blue1_dset_reg_all, dtype=np.float32) \n \n #second step\n #center_cl_index = 3 # # this index is going to be used as reference, should be no 82 in original vector\n# end_left_index = 0#not used for the time being\n# end_right_index = 0#not used for the time being\n# new = reg_images_middle_cl(red1_dset_reg,center_cl_index,0,0)\n# red1_dset_reg = np.array(new, dtype=np.float32)\n \n ## end of mock registration\n \n del se1_dset, red1_dset#, se2_dset#, blue1_dset\n file2.close()\n file1.close()\n #file3.close()\n gc.collect()\n \n \n #CUT DATASETS TO SUBSHAPE\n ###############################################################################\n ###############################################################################\n ###############################################################################\n \n ### cut only inside window: these are the base images!!!!!!!!!!!!!!!!!!!!!!!!!!!!\n #trying circular mask at center a,b\n #a, b = 247,255 #y was 255 x was 243\n #n = blue_dset_reg.shape[0] #not square matrix anymore; does not matter, only approximatively\n #r = 160 #was 170\n #y,x = np.ogrid[-a:n-a, -b:n-b]\n #mask = x*x + y*y <= r*r\n # cutting channels\n red1_dset_cut = red1_dset_reg #np.empty([blue_dset_reg.shape[0],blue_dset_reg.shape[1]])\n red1_dset_cut_all = red1_dset_reg_all\n #red_dset_cut[:] = np.nan\n #red_dset_cut[mask] = red_dset_reg[mask]\n se1_dset_cut = se1_dset_reg #np.empty([blue_dset_reg.shape[0],blue_dset_reg.shape[1]])\n #se_dset_cut[:] = np.nan\n #se_dset_cut[mask] = se_dset_reg[mask]\n \n #blue1_dset_cut = blue1_dset_reg #np.empty([blue_dset_reg.shape[0],blue_dset_reg.shape[1]])\n #blue1_dset_cut_all = blue1_dset_reg_all\n #il1_dset_cut = il1_dset_reg #np.empty([blue_dset_reg.shape[0],blue_dset_reg.shape[1]])\n \n se1_dset_cut = np.array(se1_dset_cut, dtype=np.float16)\n red1_dset_cut = np.array(red1_dset_cut, dtype=np.float32)\n red1_dset_cut_all = np.array(red1_dset_cut_all, dtype=np.float32)\n \n #il1_dset_cut = np.array(il1_dset_cut, dtype=np.float16)\n #blue1_dset_cut = np.array(blue1_dset_cut, dtype=np.float32)\n #blue1_dset_cut_all = np.array(blue1_dset_cut_all, dtype=np.float32)\n \n del red1_dset_reg, red1_dset_reg_all, se1_dset_reg#, blue1_dset_reg, blue1_dset_reg_all#, il1_dset_reg\n gc.collect()\n \n mycode = str(let[index]) + 'SEchannelONE = tempfile.NamedTemporaryFile(delete=False)'\n exec(mycode)\n np.savez(str(let[index]) + 'SEchannelONE', data = se1_dset_cut)\n# \n mycode = str(let[index]) + 'Redbright = tempfile.NamedTemporaryFile(delete=False)'\n exec(mycode)\n np.savez(str(let[index]) +'Redbright', data = red1_dset_cut_all)\n \n# mycode = str(let[index]) + 'Bluebright = tempfile.NamedTemporaryFile(delete=False)'\n# exec(mycode)\n# np.savez(str(let[index]) +'Bluebright', data = blue1_dset_cut_all)\n \n# mycode = str(let[index]) + 'ILchannel = tempfile.NamedTemporaryFile(delete=False)'\n# exec(mycode)\n# np.savez(str(let[index]) + 'ILchannel', data = il1_dset_cut)\n## \n\n \n \n ####mock\n #start_of_transient = 83 #time-bin 75 + 300ns/40ns = 75 + ~8 = 83\n #calcdecay(red1_dset_cut[start_of_transient::,:,:], time_detail= Time_bin*1e-9*fastfactor,titulo=r'Cathodoluminescence rate decay, \\n ' + titulo + ', SE `signal\\' pixels',other_dset1=red1_dset_cut[start_of_transient::,:,:] ,other_dset2=red1_dset_cut[start_of_transient::,:,:])\n #multipage(name_str[index] + fig_no + '.pdf',dpi=80)\n #klklklk\n \n \n ###############################################################################\n ###############################################################################\n ###############################################################################\n \n ####################################################################### OPTIONAL\n #want_gaussian_filter_correction_blue = False\n #want_gaussian_filter_correction_red = False\n #\n #if want_gaussian_filter_correction_blue:\n # sigma_blue = 1 \n # blue_dset_cut1 = gaussian_filter_correction(blue_dset_cut, 'Blue',sigma_blue)\n # blue_dset_cut = blue_dset_cut1 \n #\n #if want_gaussian_filter_correction_red:\n # sigma_red = 1 \n # red_dset_cut1 = gaussian_filter_correction(red_dset_cut, 'Red',sigma_red)\n # red_dset_cut = red_dset_cut1 \n #\n ################################################################ END OF OPTIONAL\n #\n ####################################################################### OPTIONAL\n #### Suggested:\n ## 1- Blue True, 3, [0] + Red False\n ## 2 - Blue True, 3, [2] + Red False\n ## 3 - Blue True, 3, [0] + Red True, 21, [1]\n ## 4 - Blue True, 3, [2] + Red True, 21, [1]\n ## 5 - Blue False, Red False\n #\n #want_background_correction_blue = False\n #want_background_correction_red = False\n #\n #filterset = ['white_tophat','black_tophat','medfilt']\n #\n #if want_background_correction_blue:\n # # Available algo types:\n # # 'white_tophat' -> needs to change disk size\n # # 'black_tophat' -> needs to change disk size\n # # 'medfilt' -> needs to changer kernel size\n # \n # # New base dsets: blue_dset_cut, red_dset_cut\n # size_blue = 3\n # blue_dset_cut1 = background_correction(blue_dset_cut, filterset[0], 'Blue',size_blue)\n # #blue_dset_cut2 = background_correction(blue_dset_cut, filterset[1], 'Blue',size_blue)\n # blue_dset_cut3 = background_correction(blue_dset_cut, filterset[2], 'Blue',size_blue)\n # #both [0] and [2] acceptable; min size_blue that makes sense = 3\n # \n # blue_dset_cut = blue_dset_cut1 #1 or 3\n # \n #if want_background_correction_red: \n # size_red = 21\n # #red_dset_cut1 = background_correction(red_dset_cut, filterset[0], 'Red',size_red)\n # red_dset_cut2 = background_correction(red_dset_cut, filterset[1], 'Red',size_red)\n # #red_dset_cut3 = background_correction(red_dset_cut, filterset[2], 'Red',size_red)\n # # [1] can be good. Or no correction.\n # red_dset_cut = red_dset_cut2\n #\n ################################################################ END OF OPTIONAL\n #\n ####TEST OTHER SEGMENTATION MODELS FOR SE, AND PLOT SE HISTOGRAM + SEGMENTATION IN THE FUTURE!!!!!\n \n ##plt.close(\"all\")\n #\n #from CreateDatasets import *\n #\n #do_avg_dset = False\n #do_median_dset = False\n #do_arb_thr_one = False\n do_gmmse_dset = True\n #do_gmmboth_dset = False\n #do_threshold_adaptive = False\n #do_random_walker = False\n #do_otsu = False\n #\n #### construct different datasets\n #### 1) Simple average\n #if do_avg_dset:\n # print('doing avg')\n # below_blue, above_blue, below_red, above_red = above_below_avg(blue_dset_cut, red_dset_cut)\n # do_analysis(blue_dset_cut, red_dset_cut, below_blue, above_blue, below_red, above_red, 'YAP', 'Chlor','Above/Below avg', 'below avg', 'above avg',Pixel_size)\n #\n #### 1) Simple median\n #if do_median_dset:\n # print('doing median')\n # belowm_blue, abovem_blue, belowm_red, abovem_red = above_below_median(blue_dset_cut, red_dset_cut)\n # do_analysis(blue_dset_cut, red_dset_cut, belowm_blue, abovem_blue, belowm_red, abovem_red, 'YAP', 'Chlor','Above/Below median', 'below median', 'above median',Pixel_size)\n #\n #### 1) Arb thresh in red\n #if do_arb_thr_one:\n # print('doing arb thres')\n # arb_threshold = 0.6 #fraction of max\n # belowarb_blue, abovearb_blue, belowarb_red, abovearb_red = arb_thr_one(red_dset_cut, blue_dset_cut, arb_threshold)\n # do_analysis(blue_dset_cut, red_dset_cut, belowarb_blue, abovearb_blue, belowarb_red, abovearb_red, 'YAP', 'Chlor','Above/Below arb thr = ' + str(arb_threshold) + ' of red max', 'below red thr', 'above red thr',Pixel_size)\n \n ###############################################################################\n ###############################################################################\n ###############################################################################\n ### 2) GMM with red mask, where red has been recognized as fluorescence\n \n \n if do_gmmse_dset:\n print('doing gmm se')\n #Original\n #gmmred_blue_dark_dset, gmmred_blue_bright_dset, gmmred_red_dark_dset, gmmred_red_bright_dset = gmmone(red_dset_cut, blue_dset_cut)\n #do_analysis(blue_dset_cut, red_dset_cut, gmmred_blue_dark_dset, gmmred_blue_bright_dset, gmmred_red_dark_dset, gmmred_red_bright_dset, 'YAP', 'Chlor','GMM red', 'red dark spots', 'red bright spots',Pixel_size) \n #Version for time-resolved\n gc.collect()\n gmmse_red1_darkse_dset, gmmse_red1_brightse_dset, gmmse_se1_dark_dset, gmmse_se1_bright_dset, darkse_pct, brightse_pct, means, covars, weights = gmmone_tr_in_masked_channel(se1_dset_cut, red1_dset_cut) \n #gmmse_red1_darkse_dset, gmmse_red1_brightse_dset, gmmse_se1_dark_dset, gmmse_se1_bright_dset, darkse_pct, brightse_pct = thr_otsu_tr_in_masked_channel(se1_dset_cut, red1_dset_cut) \n\n mycode = str(let[index]) +'SEchannelGMMONE = tempfile.NamedTemporaryFile(delete=False)'\n exec(mycode)\n np.savez(str(let[index]) +'SEchannelGMMONE', bright = gmmse_se1_bright_dset, means = means, covars = covars, weights = weights)\n \n #klklklk\n \n \n #do_ana0lysis(red1_dset_cut, se1_dset_cut, gmmse_red1_dark_dset, gmmse_red1_bright_dset, gmmse_se1_dark_dset, gmmse_se1_bright_dset, 'CL', 'SE','GMM SE', 'SE dark spots', 'SE bright spots',Pixel_size)\n #only for plots of intensity\n del gmmse_se1_dark_dset#, gmmse_se1_bright_dset \n \n gmmse_red1_darkse_dset = np.array(gmmse_red1_darkse_dset, dtype=np.float32)\n gmmse_red1_brightse_dset = np.array(gmmse_red1_brightse_dset, dtype=np.float32)\n gmmse_se1_bright_dset = np.array(gmmse_se1_bright_dset, dtype=np.float32)\n \n gc.collect()\n gmmse_red1_darkse_dset_for_4D, gmmse_red1_brightse_dset_for_4D, blah, blup, darkse_pct2, brightse_pct2 = gmmone_tr_in_masked_channel(se1_dset_cut, red1_dset_cut_all, imagemasked_is_4D=True) \n #gmmse_red1_darkse_dset_for_4D, gmmse_red1_brightse_dset_for_4D, blah, blup, darkse_pct2, brightse_pct2 = thr_otsu_tr_in_masked_channel(se1_dset_cut, red1_dset_cut_all, imagemasked_is_4D=True) \n \n# mycode = 'Redbright = tempfile.NamedTemporaryFile(delete=False)'\n# exec(mycode)\n# np.savez('Redbright', data = gmmse_red1_brightse_dset_for_4D/brightse_pct2)\n \n# mycode = 'Bluebright = tempfile.NamedTemporaryFile(delete=False)'\n# exec(mycode)2016-10-21-1042_ImageSequence_NDs100_15.315kX_10.000kV_30mu_21\n# np.savez('Bluebright', data = gmmse_red1_brightse_dset_for_4D/brightse_pct2) \n \n del blah, blup, darkse_pct2, brightse_pct2 #delete all SE masks \n gc.collect()\n gmmse_red1_darkse_dset_for_4D = np.array(gmmse_red1_darkse_dset_for_4D, dtype=np.float32)\n gmmse_red1_brightse_dset_for_4D = np.array(gmmse_red1_brightse_dset_for_4D, dtype=np.float32)\n \n # BLUE\n# gc.collect()\n# gmmse_blue1_darkse_dset, gmmse_blue1_brightse_dset, gmmse_se1_dark_dset, gmmse_se1_bright_dset, darkse_pct, brightse_pct, means, covars, weights = gmmone_tr_in_masked_channel(se1_dset_cut, blue1_dset_cut) \n# del gmmse_se1_dark_dset#, gmmse_se1_bright_dset \n# gmmse_blue1_darkse_dset = np.array(gmmse_blue1_darkse_dset, dtype=np.float32)\n# gmmse_blue1_brightse_dset = np.array(gmmse_blue1_brightse_dset, dtype=np.float32)\n# \n# gc.collect()\n# gmmse_blue1_darkse_dset_for_4D, gmmse_blue1_brightse_dset_for_4D, blah, blup, darkse_pct2, brightse_pct2 = gmmone_tr_in_masked_channel(se1_dset_cut, blue1_dset_cut_all, imagemasked_is_4D=True) \n# del blah, blup, darkse_pct2, brightse_pct2 #delete all SE masks \n# gc.collect()\n# gmmse_blue1_darkse_dset_for_4D = np.array(gmmse_blue1_darkse_dset_for_4D, dtype=np.float32)\n# gmmse_blue1_brightse_dset_for_4D = np.array(gmmse_blue1_brightse_dset_for_4D, dtype=np.float32)\n \n else:\n print('NOT doing gmm se') #assume all is bright in CL\n gmmse_red1_brightse_dset = red1_dset_cut\n gmmse_red1_darkse_dset = 0*red1_dset_cut #or could give 0 vector\n darkse_pct = 1.0\n brightse_pct = 0.0\n gmmse_red1_darkse_dset_for_4D = np.array(red1_dset_cut_all, dtype=np.float32)\n gmmse_red1_brightse_dset_for_4D = np.array(red1_dset_cut_all, dtype=np.float32)\n \n# mycode = 'Bluebright = tempfile.NamedTemporaryFile(delete=False)'\n# exec(mycode)\n# np.savez('Bluebright', data = gmmse_red1_brightse_dset_for_4D/brightse_pct)\n ###############################################################################\n ###############################################################################\n ###############################################################################\n \n #### 3) GMM with independent masks in both channels\n #if do_gmmboth_dset:\n # print('doing gmm both')\n # gmmboth_blue_dark_dset, gmmboth_blue_bright_dset, gmmboth_red_dark_dset, gmmboth_red_bright_dset = gmmboth(red_dset_cut, blue_dset_cut)\n # do_analysis(blue_dset_cut, red_dset_cut, gmmboth_blue_dark_dset, gmmboth_blue_bright_dset, gmmboth_red_dark_dset, gmmboth_red_bright_dset, 'YAP', 'Chlor','GMM both', 'dark spots', 'bright spots',Pixel_size)\n #\n #### 4) Threshold adapative\n #if do_threshold_adaptive:\n # print('doing thr adap')\n # blocksize = 50\n # offset = 0\n # th_below_blue, th_above_blue, th_below_red, th_above_red = threshold_adaptive_dset(red_dset_cut, blue_dset_cut,blocksize, offset)\n # do_analysis(blue_dset_cut, red_dset_cut, th_below_blue, th_above_blue, th_below_red, th_above_red, 'YAP', 'Chlor','Threshold adaptive' + '(blocksize, offset =' + str(blocksize) + ', ' + str(offset) + ')', 'below thr', 'above thr',Pixel_size)\n #\n #### 5) random_walker not yet working\n ### http://scikit-image.org/docs/dev/auto_examples/segmentation/plot_random_walker_segmentation.html#example-segmentation-plot-random-walker-segmentation-py\n #if do_random_walker:\n # print('doing random walk')\n # cutofflow = 0.89\n # cutoffhigh = 0.9\n # rw_below_blue, rw_above_blue, rw_below_red, rw_above_red = random_walker_dset(red_dset_cut, blue_dset_cut,cutofflow, cutoffhigh)\n # do_analysis(blue_dset_cut, red_dset_cut, rw_below_blue, rw_above_blue, rw_below_red, rw_above_red, 'YAP', 'Chlor','Random walker'+ '(cutoffs high, low =' + str(cutoffhigh) + ', ' + str(cutofflow) + ')', 'background', 'foreground',Pixel_size)\n #\n #### 6) Otsu thresholding \n #if do_otsu:\n # print('doing otsu')\n # ot_below_blue, ot_above_blue, ot_below_red, ot_above_red = thr_otsu(red_dset_cut, blue_dset_cut)\n # do_analysis(blue_dset_cut, red_dset_cut, ot_below_blue, ot_above_blue, ot_below_red, ot_above_red, 'YAP', 'Chlor','Otsu threshold', 'background', 'foreground',Pixel_size)\n # \n #log_dog_doh(blue_dset_cut)\n \n #log_dog_doh(blue_dset_cut)\n \n ########### OUTPUT \n \n ###### HERE: I have red1_dset_cut, red1_dset_cut_all, se1_dset_cut, gmmse_red_darkse_dset, gmmse_red_brightse_dset, gmmse_se_darkse_dset, gmmse_se_brightse_dset\n \n ###FIG2\n #frame to be shown in static frame\n #init_plot_no = center_cl_index #around 27 or 28\n #plot_nonvideo_reg(titulo, gmmse_se1_bright_dset, red1_dset_cut,gmmse_red1_darkse_dset, gmmse_red1_brightse_dset, red1_dset_cut_all, se1_dset_cut, gmmse_red1_brightse_dset_for_4D, gmmse_red1_darkse_dset_for_4D, Time_bin,fastfactor,nominal_time_on,Pixel_size[index],darkse_pct, brightse_pct,name_str[index] ,init_plot_no,major_ticks,unit = 'kHz')\n del se1_dset_cut\n gc.collect()\n ###END FIG2\n \n ###FIG3\n #fig_no = '-3plots'\n #plot_expt_by_expt_behaviour(titulo + ', signal pixels', gmmse_red1_darkse_dset_for_4D/darkse_pct, Time_bin, nominal_time_on,fastfactor,'y',major_ticks,dark_dset=gmmse_red1_brightse_dset_for_4D/brightse_pct, plot_dark=True) #pass titulo as well\n \n #two lines were uncommented; now trying to delete later\n #del gmmse_red1_brightse_dset_for_4D\n #gc.collect()\n # plot_expt_by_expt_behaviour(titulo + ', signal pixels', gmmse_red1_darkse_dset_for_4D/darkse_pct, Time_bin, nominal_time_on,fastfactor,'y',major_ticks,dark_dset=None, plot_dark=False,unit='kHz') #pass titulo as well\n #del gmmse_red1_brightse_dset_for_4D\n \n #multipage('ZZZ' + name_str[index] + fig_no + '.pdf',dpi=80)\n ###END FIG3\n \n #del gmmse_red1_darkse_dset_for_4D\n gc.collect()\n \n ###FIG4\n #fig_no = '-3plots'\n #start_of_transient = 33; #82- cut_at_beginning + 1 #time-bin 75 + 300ns/40ns = 75 + ~8 = 83\n #last_pt_offset = -10 #sometimes use -1, last point, but sometimes this gives 0. -10 seems to work\n# if index == 7000: ### 7 was a problem for red, added a thousand\n# print('core only, sample B')\n# init_guess = [np.average(gmmse_red1_darkse_dset[start_of_transient,:,:])/darkse_pct, 1.0, np.average(gmmse_red1_darkse_dset[last_pt_offset,:,:])/darkse_pct, np.average(gmmse_red1_darkse_dset[start_of_transient,:,:])/darkse_pct , 0.1] #e init was 0.5, d was zero before I made == a\n# elif index == 10: #### 10 (oleci acid) was a single not double, added a thousand\n# print(\"oleic\")\n# init_guess = [np.average(gmmse_red1_darkse_dset[start_of_transient,:,:])/darkse_pct,0.05, np.average(gmmse_red1_darkse_dset[last_pt_offset,:,:])/darkse_pct, np.average(gmmse_red1_darkse_dset[start_of_transient,:,:])/darkse_pct, 0.25] #e init was 0.5\n# else:\n# init_guess = [np.average(gmmse_red1_darkse_dset[start_of_transient,:,:])/darkse_pct, 1.0, np.average(gmmse_red1_darkse_dset[last_pt_offset,:,:])/darkse_pct, np.average(gmmse_red1_darkse_dset[start_of_transient+50,:,:])/darkse_pct, 0.1] #e init was 0.5\n #if do_gmmse_dset is False:\n # brightse_pct = 0.01 #just so that I don't have a division by 0 in the function argument below!!!!\n #b,e,be,ee = calcdecay(gmmse_red1_darkse_dset[start_of_transient::,:,:]/darkse_pct, time_detail= Time_bin*1e-9*fastfactor,titulo='Cathodoluminescence rate decay, bi-exponential fit, \\n ' + titulo ,single=False,other_dset1=None ,other_dset2=None,init_guess=init_guess,unit='kHz') \n # b,be, be, ee = calcdecay(gmmse_red1_darkse_dset[start_of_transient::,:,:]/darkse_pct, time_detail= Time_bin*1e-9*fastfactor,titulo='Cathodoluminescence rate decay, single exponential fit, \\n ' + titulo ,single=False,other_dset1=red1_dset_cut[start_of_transient::,:,:]/1.0 ,other_dset2=gmmse_red1_brightse_dset[start_of_transient::,:,:]/brightse_pct,init_guess=init_guess,unit='kHz')\n \n# tau_single[index] = b\n# tau_single_error[index] = be\n# tau_bi[index,:] = [b,e]\n# tau_bi_error[index,:] = [be,ee]\n \n #for plots of dose, in the Er 60%:\n# if index >= 9: #8,9,10,11: the 4 from Er 60% \n# mycode = 'ZZZZZZEr60' + str(index) + '= tempfile.NamedTemporaryFile(delete=False)'\n# exec(mycode)\n# np.savez('ZZZZZZEr60' + str(index), data = np.average(gmmse_red1_darkse_dset_for_4D/darkse_pct, axis=(1,2,3)))\n \n #for plots of tau as a function of number of experiments in Er 2%, sample A (index0)\n # if index is 0:\n # pass\n# print('series')\n# calcdecay_series(gmmse_red1_darkse_dset_for_4D[:,start_of_transient::,:,:]/darkse_pct, time_detail= Time_bin*1e-9*fastfactor,titulo='Cathodoluminescence rate decay, bi-exponential fit, \\n ' + titulo ,single=False,nominal_time_on=nominal_time_on,fastfactor=fastfactor,other_dset1=red1_dset_cut_all[:,start_of_transient::,:,:]/1.0 ,other_dset2=gmmse_red1_brightse_dset_for_4D[:,start_of_transient::,:,:]/brightse_pct,init_guess=init_guess) \n# print('each') \n# calcdecay_each(gmmse_red1_darkse_dset_for_4D[:,start_of_transient::,:,:]/darkse_pct, time_detail= Time_bin*1e-9*fastfactor,titulo='Cathodoluminescence rate decay, bi-exponential fit, \\n ' + titulo ,single=False,nominal_time_on=nominal_time_on,fastfactor=fastfactor,other_dset1=red1_dset_cut_all[:,start_of_transient::,:,:]/1.0 ,other_dset2=gmmse_red1_brightse_dset_for_4D[:,start_of_transient::,:,:]/brightse_pct,init_guess=init_guess) \n\n\n del gmmse_red1_darkse_dset_for_4D, gmmse_red1_brightse_dset_for_4D #last one is trying to delete later than line372\n gc.collect()\n\n start_of_transient = 0 \n \n# mycode = str(let[index]) +'ZZZBlueDecay = tempfile.NamedTemporaryFile(delete=False)'\n# exec(mycode)\n# np.savez(str(let[index]) +'ZZZBlueDecay', data = gmmse_blue1_darkse_dset[start_of_transient::,:,:]/darkse_pct)\n \n mycode = str(let[index]) +'ZZZRedDecay = tempfile.NamedTemporaryFile(delete=False)'\n exec(mycode)\n np.savez(str(let[index]) +'ZZZRedDecay', data = gmmse_red1_darkse_dset[start_of_transient::,:,:]/darkse_pct)\n \n #multipage(str(let[index]) +'RedZZZ.pdf',dpi=80)\n \n ###END FIG4\n \n #plt.show()\n plt.close('all')\n \n#write a temporary file with all values\n#outfile = tempfile.NamedTemporaryFile(delete=False)\n#np.savez(outfile, tau_single=tau_single, tau_single_error=tau_single_error, tau_bi=tau_bi, tau_bi_error=tau_bi_error)\n \n####SAME TASK: IMPROVE FITS. WHEN FITS ARE GOOD, MAKE SUMMARY FIGURE\n######################################## Plot with dose for different apertures\n##files below exist \nb_array_red = np.zeros(len(nametr))\nbe_array_red = np.zeros(len(nametr))\ne_array_red = np.zeros(len(nametr))\nee_array_red = np.zeros(len(nametr))\nb_array_blue = np.zeros(len(nametr))\nbe_array_blue = np.zeros(len(nametr))\ne_array_blue = np.zeros(len(nametr))\nee_array_blue = np.zeros(len(nametr))\nblue_int_array = np.zeros(len(nametr))\nred_int_array = np.zeros(len(nametr))\ncumu_blue = np.zeros([len(nametr),5])\ncumu_red = np.zeros([len(nametr),5]) \nil_data = np.zeros([len(nametr),5])\nsize_signal = np.zeros(len(nametr))\n\nlistofindex =np.arange(0,len(nametr)) # #[0,1,2] [5] \n#index = 7\n#if index is 7:\nfor index in listofindex:\n \n file1 = h5py.File(nametr[index] + '.hdf5', 'r') \n red0_dset = file1['/data/Counter channel 1 : PMT red/PMT red time-resolved/data']#10 Scany points X10 frames x 150 tr pts x250 x 250 pixels\n Pixel_size = red0_dset.attrs['element_size_um'][1]*1000.0 #saved attribute is in micron; converting to nm\n Ps = str(\"{0:.2f}\".format(Pixel_size)) #pix\n\n ### 593 dichroic\n se = np.load(str(let[index]) +'SEchannelONE.npz') \n segmm = np.load(str(let[index]) +'SEchannelGMMONE.npz') \n red = np.load(str(let[index]) +'Redbright.npz') \n #blue = np.load(str(let[index]) +'Bluebright.npz') \n #il = np.load(str(let[index]) +'ILchannel.npz') \n \n fsizetit = 18 #22 #18\n fsizepl = 16 #20 #16\n sizex = 8 #10 #8\n sizey = 6# 10 #6\n dpi_no = 80\n lw = 2\n \n #Pixel_size = 3.1e-9\n length_scalebar = 50.0 #in nm (1000nm == 1mum)\n scalebar_legend = '50nm'\n length_scalebar_in_pixels = np.ceil(length_scalebar/(Pixel_size))\n \n hlp = segmm['bright']\n hlp[~np.isnan(hlp)] = 1.0 \n size_signal[index] = len(hlp[~np.isnan(hlp)])*Pixel_size*Pixel_size #in nm^2 \n del hlp\n \n titulo = 'Nanodiamond ' + let[index] + ', of area ' + str(\"{0:.2f}\".format(size_signal[index]/1000.0)) + ' $\\cdot$ 10$^3$nm$^2$ (10kV, 30$\\mu$m aperture, 40ns time bins, ' + str(Ps)+ 'nm pixels, $>$ 509nm from NV0)'\n \n \n fig40= plt.figure(figsize=(sizex, sizey), dpi=dpi_no)\n fig40.set_size_inches(1200./fig40.dpi,900./fig40.dpi)\n plt.rc('text.latex', preamble=r'\\usepackage{xcolor}') #not working\n plt.rc('text', usetex=True)\n plt.rc('text.latex', preamble=r'\\usepackage{xcolor}') #not working\n plt.rcParams['text.latex.preamble']=[r\"\\usepackage{xcolor}\"] #not working\n plt.rc('font', family='serif')\n plt.rc('font', serif='Palatino') \n \n #plt.rc('text', usetex=True)\n #plt.rc('font', family='serif')\n #plt.rc('font', serif='Palatino') \n #if (index is 3) or (index is 6): \n # plt.suptitle(\"Registration and segmentation (model: simple avg.) of cathodoluminescence signal using SE channel, \\n\" + titulo,fontsize=fsizetit)\n #else:\n #plt.suptitle(\"Registration and segmentation (model: 2-GMM) of cathodoluminescence signal using SE channel, !INIT BIN 95!, \\n\" + titulo,fontsize=fsizetit)\n \n #plt.suptitle(\"Segmentation (model: 2-GMM) of cathodoluminescence signal using SE channel, !INIT BIN 68!, \\n\" + titulo,fontsize=fsizetit)\n plt.suptitle(\"Segmentation (model: 2-GMM) of cathodoluminescence signal using SE channel, \\n\" + titulo,fontsize=fsizetit)\n\n gc.collect()\n \n ax1 = plt.subplot2grid((2,3), (0, 0), colspan=1)\n ax1.set_title('SE channel',fontsize=fsizepl) #as per accompanying txt files\n plt.imshow(se['data'],cmap=cm.Greys_r)\n sbar = sb.AnchoredScaleBar(ax1.transData, length_scalebar_in_pixels, scalebar_legend, style = 'bright', loc = 4)\n ax1.add_artist(sbar)\n plt.axis('off')\n \n gc.collect()\n ax1 = plt.subplot2grid((2,3), (0, 1), colspan=1)\n ax1.set_title('SE channel, signal pixels',fontsize=fsizepl)\n hlp = segmm['bright']\n hlp[~np.isnan(hlp)] = 0.0 #hack: was 0.0 but I want to use all pixels #unclear if hack works bc below hlp is re-defined\n hlp[np.isnan(hlp)] = 1.0\n im = plt.imshow(hlp,cmap=cm.Greys) #or 'OrRd'\n sbar = sb.AnchoredScaleBar(ax1.transData, length_scalebar_in_pixels, scalebar_legend, style = 'bright', loc = 4)\n ax1.add_artist(sbar)\n plt.axis('off')\n \n# def make_gaussian(means, covars, weights, data, max_hist, no_pts=200):\n# \n# array_x = np.zeros([len(means), no_pts])\n# array_y = np.zeros([len(means), no_pts])\n# \n# for j in np.arange(0,len(means)):\n# array_x[j,:] = np.linspace(np.min(data),np.max(data),no_pts)\n# array_y[j,:] = weights[j] * max_hist * np.exp( -(array_x[j,:] - means[j])**2/(2*covars[j]) )\n# \n# return array_x, array_y\n \n \n #box = ax1.get_position()\n #ax1.set_position([box.x0, box.y0*1.00, box.width, box.height])\n #axColor = plt.axes([box.x0, box.y0*1.1 , box.width,0.01*10 ]) \n #no_bins = 200 \n #n = axColor.hist(se['data'].flatten(),bins=no_bins)\n #\n #array_x, array_y = make_gaussian(segmm['means'][:,0], segmm['covars'][:,0],segmm['weights'], se['data'], np.max(n[0]), no_pts=200)\n #\n #axColor.plot(array_x[0],array_y[0])\n #axColor.plot(array_x[1],array_y[1])\n \n ############\n import skimage.morphology\n from skimage.morphology import watershed\n from skimage.feature import peak_local_max\n image = np.abs(1-hlp)#hlp.astype(bool) #np.logical_or(mask_circle1, mask_circle2)\n from scipy import ndimage\n distance = ndimage.distance_transform_edt(image)\n local_maxi = peak_local_max(distance, num_peaks = 1, indices = False, footprint=np.ones((50,50)),labels=image) #footprint = min dist between maxima to find #footprint was 25,25\n markers = skimage.morphology.label(local_maxi)\n labels_ws = watershed(-distance, markers, mask=image)\n #plt.figure()\n #ax1 = plt.subplot2grid((1,4), (0,0))\n #ax1.imshow(image)\n #ax2 = plt.subplot2grid((1,4), (0,1))\n #ax2.imshow(np.log(distance))\n #ax2 = plt.subplot2grid((1,4), (0,2))\n #ax2.imshow(markers)\n #ax2 = plt.subplot2grid((1,4), (0,3))\n #ax2.imshow(labels_ws)\n #plt.show()\n \n# ax1 = plt.subplot2grid((2,3), (0, 2), colspan=1)\n# ax1.set_title('Segmented NPs',fontsize=fsizepl)\n# im = plt.imshow(labels_ws,cmap=cm.Greys) #or 'OrRd'\n# sbar = sb.AnchoredScaleBar(ax1.transData, length_scalebar_in_pixels, scalebar_legend, style = 'dark', loc = 4)\n# ax1.add_artist(sbar)\n# plt.axis('off')\n# \n# ax1 = plt.subplot2grid((2,3), (1, 0), colspan=1)\n# ax1.spines['right'].set_visible(False)\n# ax1.spines['top'].set_visible(False)\n# ax1.xaxis.set_ticks_position('bottom')\n# ax1.yaxis.set_ticks_position('left')\n \n ax1 = plt.subplot2grid((2,3), (0, 2), colspan=1)\n noexp = ['1','1','1','1','1','3','3','6','10','10']\n ax1.set_title('CL data averaged over time \\n and ' + noexp[index] +' experiments',fontsize=fsizepl)\n im = plt.imshow(np.nanmean(red['data'],axis = (0,1)),cmap=cm.Reds) #or 'OrRd'\n sbar = sb.AnchoredScaleBar(ax1.transData, length_scalebar_in_pixels, scalebar_legend, style = 'dark', loc = 4)\n ax1.add_artist(sbar)\n plt.axis('off')\n \n ax1 = plt.subplot2grid((2,3), (1, 0), colspan=1)\n ax1.spines['right'].set_visible(False)\n ax1.spines['top'].set_visible(False)\n ax1.xaxis.set_ticks_position('bottom')\n ax1.yaxis.set_ticks_position('left')\n \n #TEST\n# if index is 0: #hlp does not do anything; segmentation is bad\n# hlp = segmm['bright']\n# hlp[~np.isnan(hlp)] = 1.0\n# hlp[np.isnan(hlp)] = 1.0 #hlp does not do anything; segmentation is bad\n# else: #working for index = 1, \n# hlp = segmm['bright']\n# hlp[~np.isnan(hlp)] = 1.0\n \n \n # TO CONSIDER ALL LIGHT, UNCOMMENT 2 LINES BELOW:\n hlp = segmm['bright']\n hlp[~np.isnan(hlp)] = 1.0 \n\n #redn = np.average(red['data'],axis = 0)\n #bluen = np.average(blue['data'],axis = 0)\n #for jj in np.arange(0,redn.shape[0]):\n # print(jj)\n # redn[jj,:,:] = redn[jj,:,:] * hlp\n # bluen[jj,:,:] = bluen[jj,:,:] * hlp\n # \n #plt.plot(np.arange(0,91)*Time_bin/1e3,np.nanmean(redn,axis = (1,2)),c='r',label='Red photons ($>$ 593nm)',lw=3) #in mus, in MHz\n #plt.plot(np.arange(0,91)*Time_bin/1e3,np.nanmean(bluen,axis = (1,2)),c='b',label='Blue photons ($<$ 593nm)',lw=3) #in mus, in MHz\n plt.plot(np.arange(0,150)*Time_bin/1e3,np.nanmean(red['data']*hlp,axis = (0,2,3)),c='r',lw=2) #in mus, in MHz\n #plt.plot(np.arange(0,500)*Time_bin/1e3,np.nanmean(blue['data']*hlp,axis = (0,2,3)),c='b',label='Blue photons ($<$ 593nm)',lw=3) #in mus, in MHz\n \n #plt.plot(np.arange(0,91)*Time_bin/1e3,np.average(red['data'],axis = (0,2,3)),c='r',label='Red photons ($>$ 593nm)',lw=3) #in mus, in MHz\n #plt.plot(np.arange(0,91)*Time_bin/1e3,np.average(blue['data'],axis = (0,2,3)),c='b',label='Blue photons ($<$ 593nm)',lw=3) #in mus, in MHz\n ax1.axvspan(0.2+0.3,0.2+1.8+0.3, alpha=0.25, color='yellow')\n unit = 'kHz'\n plt.ylabel(\"Average luminescence \\n of each time bin, per signal pixel (\" + unit + \")\",fontsize=fsizepl)\n plt.xlabel(\"Behaviour of e-beam during each experiment: \\n 1.8-ON + 4-OFF ($\\mu$s)\",fontsize=fsizepl)\n #plt.legend() \n major_ticks0 = [1,2,3,4,5,6]\n ax1.set_xticks(major_ticks0) \n #ax1.set_yticks([15,30,45]) \n plt.xlim([0,6])\n \n ax1 = plt.subplot2grid((2,3), (1, 1), colspan=1)\n ax1.spines['right'].set_visible(False)\n ax1.spines['top'].set_visible(False)\n ax1.xaxis.set_ticks_position('bottom')\n ax1.yaxis.set_ticks_position('left')\n \n datared = np.average(red['data'], axis = (0))\n #datablue = np.average(blue['data'], axis = (0))\n \n if True is False:\n pass\n else:\n initbin = 58#### ACHTUNG!!!!!! WAS ORIGINALLY!!!!!!!!!!!!!!!!!\n ### 700ns /40ns = \n datared_init = datared[0:12,:,:] #12 = 200/40 + 7 (7 from floor(300ns/40ns))\n datared = datared[initbin:,:,:]\n \n# datablue = datablue[initbin:,:,:]\n \n \n \n fastfactor = 1\n last_pt_offset = -30 #sometimes use -1, last point, but sometimes this gives 0. -10 seems to work\n medium_pt_offset = -60\n init_guess = [np.average(datared[0,:,:]), 0.05, np.average(datared[last_pt_offset:,:,:]), np.average(datared[medium_pt_offset:,:,:]), 0.5] #e init was 0.5\n #init_guess = [0.35, 0.005, 0.02, 0.08, 0.0006]\n #init_guess2 = [0.46, 0.1, 0.03, 12, 0.01]\n #init_guess2 = [ 0.08, 0.03, 0.17, 4.6, 0.01]\n \n #init_guess2 = [np.average(datablue[0,:,:]), 1.0, np.average(datablue[last_pt_offset,:,:]), np.average(datablue[-30,:,:]), 0.005] #e init was 0.5\n #init_guess2 = [np.average(datablue[0,:,:]), 1.0, 0.01, np.average(datablue[-30,:,:]), 0.005] #e init was 0.5\n# \n # We fixed the offset c in all fits\n hlp_red = datared * hlp\n #hlp_blue = datablue * hlp\n# if index == 0: #needs to be reworked out\n# pass\n# #init_guess = [np.nanmean(hlp_red[0,:,:]), 15.0, np.nanmean(hlp_red[last_pt_offset:,:,:]), np.nanmean(hlp_red[10:50,:,:]), 200.0 ] #RED\n# #init_guess2 = [np.nanmean(hlp_blue[0,:,:]), 15.0,np.nanmean(hlp_blue[last_pt_offset:,:,:]), np.nanmean(hlp_blue[10:50,:,:]), 200.0 ] #BLUE\n# \n# if index == 1:\n# pass\n# \n# #init_guess = [np.nanmean(hlp_red[0,:,:]), 15.0, np.nanmean(hlp_red[last_pt_offset:,:,:]), np.nanmean(hlp_red[10:50,:,:]), 200.0 ] #RED\n# #init_guess2 = [np.nanmean(hlp_blue[0,:,:]), 15.0,np.nanmean(hlp_blue[last_pt_offset:,:,:]), np.nanmean(hlp_blue[10:50,:,:]), 200.0 ] #BLUE\n# else:\n# pass\n# #init_guess = [np.nanmean(hlp_red[0,:,:]), 15.0, np.nanmean(hlp_red[last_pt_offset:,:,:]), np.nanmean(hlp_red[10:50,:,:]), 200.0 ] #RED\n# #init_guess2 = [np.nanmean(hlp_blue[0,:,:]), 15.0,np.nanmean(hlp_blue[last_pt_offset:,:,:]), np.nanmean(hlp_blue[10:50,:,:]), 200.0 ] #BLUE \n# #init_guess = [3.99, 0.018, np.nanmean(hlp_red[last_pt_offset,:,:]), 3.94, 0.1 ] #RED\n# #init_guess2 = [63.6, 0.037,np.nanmean(hlp_blue[last_pt_offset,:,:]), 4.7, 0.6 ] #BLUE\n \n hlpred = np.nanmean(red['data'][:,initbin:,:,:]*hlp,axis = (2,3))\n #hlpblue = np.nanmean(blue['data'][:,initbin:,:,:]*hlp,axis = (2,3))\n \n #error_arrayr = np.nanstd(hlpred,axis = 0)\n #error_arrayb = np.nanstd(hlpblue, axis = 0)\n #error_arrayr[error_arrayr < 0.05 * np.max(hlpred)] = 0.05 * np.max(hlpred) #arbitrary 5% of max\n #error_arrayb[error_arrayb < 0.05 * np.max(hlpblue)] = 0.05 * np.max(hlpblue)\n #b,e,be,ee = calcdecay_subplot2(datared, time_detail= Time_bin*1e-9*fastfactor,titulo='Cathodoluminescence rate decay, bi-exponential fit, \\n ' + titulo ,single=False,other_dset2=datablue ,other_dset1=None,init_guess=init_guess,unit='kHz',init_guess2=init_guess2) \n \n b,e,be,ee,b2,e2,be2,ee2 = calcdecay_subplot_nan(datared*hlp, time_detail= Time_bin*1e-9*fastfactor,titulo='Cathodoluminescence rate decay, bi-exponential fit, \\n ' + titulo ,single=False,other_dset1=None,other_dset2=None,init_guess=init_guess,unit='kHz') #,error_array=error_arrayr, error_array2=error_arrayb) \n \n b_array_red[index] = b\n e_array_red[index] = e\n be_array_red[index] = be \n ee_array_red[index] = ee \n# b_array_blue[index] = b2\n# e_array_blue[index] = e2\n# be_array_blue[index] = be2 \n# ee_array_blue[index] = ee2 \n size_signal[index] = len(hlp[~np.isnan(hlp)])*Pixel_size*Pixel_size #in nm^2\n \n #plt.xlim([0,3.7])\n #major_ticks0 = [1,2,3]\n plt.ylabel(\"Average luminescence \\n of each time bin, per signal pixel (\" + unit + \")\",fontsize=fsizepl)\n plt.xlabel(r'Time after blanking the electron beam ($\\mu$s)', fontsize=fsizepl)\n \n # Extra plots \n hlpd = segmm['bright']\n hlpd[~np.isnan(hlpd)] = 0.0 \n hlpd[np.isnan(hlpd)] = 1.0\n aaa = datared*hlp\n xx_array = np.arange(0,aaa.shape[0])*Time_bin*1e-9*fastfactor\n #Plot whole of background decay\n plt.semilogy(xx_array/1e-6,np.nanmean(datared*hlpd,axis=(1,2)),'ko',markersize=2,label='Transient CL from background') \n #Plot mean signal before e-beam on\n plt.semilogy(xx_array/1e-6,np.nanmean(datared_init*hlp,axis=(0,1,2))*np.ones(len(xx_array)),'r--',lw=2,label='Mean CL from signal pixels, before e-beam')\n #Plot mean background\n plt.semilogy(xx_array/1e-6,np.nanmean(datared_init*hlpd,axis=(0,1,2))*np.ones(len(xx_array)),'k--',lw=1,label='Mean CL from background, before e-beam')\n \n plt.legend(loc='best')\n \n #ax1.set_xticks(major_ticks0)\n \n ax1 = plt.subplot2grid((2,3), (1, 2), colspan=1)\n ax1.spines['left'].set_visible(False)\n ax1.spines['top'].set_visible(False)\n ax1.xaxis.set_ticks_position('bottom')\n ax1.yaxis.set_ticks_position('right')\n ax1.yaxis.set_label_position(\"right\")\n \n dataALLred = red['data'][:,:,:,:]\n #dataALLblue = blue['data'][:,:,:,:]\n nominal_time_on = 1.8\n \n #plt.plot(np.arange(1,No_experiments[index]+1)*nominal_time_on*fastfactor,np.nanmean(dataALLblue*hlp,axis=(1,2,3)),c='b', label='From blue photons ($<$ 593nm)',linestyle='None', marker='o',markersize=4) #in mus, in MHz\n plt.plot(np.arange(1,No_experiments[index]+1)*nominal_time_on*fastfactor,np.nanmean(dataALLred*hlp,axis=(1,2,3)),c='r', label='From photons $>$ 509nm',linestyle='None', marker='o',markersize=4) #in mus, in MHz\n #plt.plot(np.arange(1,No_experiments[index]+1)*nominal_time_on*fastfactor,np.nanmean(dataALLblue*hlp,axis=(0,1,2,3))*np.ones([No_experiments[index]]),c='b', linewidth= lw) #in mus, in MHz\n #plt.plot(np.arange(1,No_experiments[index]+1)*nominal_time_on*fastfactor,np.nanmean(dataALLred*hlp,axis=(0,1,2,3))*np.ones([No_experiments[index]]),c='r', linewidth= lw) #in mus, in MHz\n plt.plot(np.arange(1,No_experiments[index]+1)*nominal_time_on*fastfactor,np.nanmean(dataALLred*hlp,axis=(0,1,2,3))*np.ones(dataALLred.shape[0]),c='r', linewidth= lw) #in mus, in MHz\n\n red_int_array[index] = np.nanmean(dataALLred*hlp,axis=(0,1,2,3))\n #blue_int_array[index] = np.nanmean(dataALLblue*hlp,axis=(0,1,2,3))\n cumu_red[index,:] = np.nanmean(dataALLred*hlp,axis=(1,2,3))\n #cumu_blue[index,:] = np.nanmean(dataALLblue*hlp,axis=(1,2,3))\n #il_data[index,:] = np.average(il['data'], axis = (1,2)) #take average per frame\n \n plt.ylabel(\"Average luminescence \\n for each experiment, per signal pixel (kHz)\",fontsize=fsizepl)\n plt.xlabel(\"Cumulative e-beam exposure time \\n per pixel (nominal, $\\mu$s)\",fontsize=fsizepl)\n \n #major_ticks = [25,50,75,nominal_time_on*dset.shape[0]*fastfactor]\n # major_ticks = [5,10,15,20]\n #ax1.set_xticks(major_ticks) \n #plt.legend()\n plt.xlim([nominal_time_on - 1.0,nominal_time_on*No_experiments[index]*fastfactor +1.0])\n \n multipage_longer('ZZZZ-'+ let[index] + '.pdf',dpi=80)\n\n##### ONCE ALL FITS WORK, \n###### NEED TO RUN THESE LINES BELOW SO THAT ALL NPZ FILES ARE CREATED \n#mycode = 'Red_int_array = tempfile.NamedTemporaryFile(delete=False)'\n#exec(mycode)\n#np.savez('Red_int_array', data = red_int_array)\n#\n#mycode = 'Blue_int_array = tempfile.NamedTemporaryFile(delete=False)'\n#exec(mycode)\n#np.savez('Blue_int_array', data = blue_int_array)\n#\n#mycode = 'Cumu_red = tempfile.NamedTemporaryFile(delete=False)'\n#exec(mycode)\n#np.savez('Cumu_red', data = cumu_red)\n#\n#mycode = 'Cumu_blue = tempfile.NamedTemporaryFile(delete=False)'\n#exec(mycode)\n#np.savez('Cumu_blue', data = cumu_blue)\n#\n#mycode = 'Il_data = tempfile.NamedTemporaryFile(delete=False)'\n#exec(mycode)\n#np.savez('Il_data', data = il_data)\n#\n#mycode = 'B_array_red = tempfile.NamedTemporaryFile(delete=False)'\n#exec(mycode)\n#np.savez('B_array_red', data = b_array_red)\n#\n#mycode ='Be_array_red = tempfile.NamedTemporaryFile(delete=False)'\n#exec(mycode)\n#np.savez('Be_array_red', data = be_array_red)\n#\n#mycode = 'E_array_red = tempfile.NamedTemporaryFile(delete=False)'\n#exec(mycode)\n#np.savez('E_array_red', data = e_array_red)\n#\n#mycode = 'Ee_array_red = tempfile.NamedTemporaryFile(delete=False)'\n#exec(mycode)\n#np.savez('Ee_array_red', data = ee_array_red)\n#\n#mycode = 'B_array_blue = tempfile.NamedTemporaryFile(delete=False)'\n#exec(mycode)\n#np.savez('B_array_blue', data = b_array_blue)\n#\n#mycode ='Be_array_blue = tempfile.NamedTemporaryFile(delete=False)'\n#exec(mycode)\n#np.savez('Be_array_blue', data = be_array_blue)\n#\n#mycode = 'E_array_blue = tempfile.NamedTemporaryFile(delete=False)'\n#exec(mycode)\n#np.savez('E_array_blue', data = e_array_blue)\n#\n#mycode = 'Ee_array_blue = tempfile.NamedTemporaryFile(delete=False)'\n#exec(mycode)\n#np.savez('Ee_array_blue', data = ee_array_blue)\n\n#mycode = 'Size_signal = tempfile.NamedTemporaryFile(delete=False)'\n#exec(mycode)\n#np.savez('Size_signal', data = size_signal)\n\n#####FIG WITH SUMMARY \n##### WHEN FILES ABOVE ARE CREATED, CREATE FIGURE BELOW WITH REGION SIZES VS LIFETIMES AND REGION SIZES VS S/N OR BRIGHTNESS OR /\nklklklklk\nfastfactor = 1\n\nRed_int_array = np.load('Red_int_array.npz') \nred_int_array = Red_int_array['data']\nBlue_int_array = np.load('Blue_int_array.npz') \nblue_int_array = Blue_int_array['data']\n\nB_array_red= np.load('B_array_red.npz')\nb_array_red = B_array_red['data'] \nBe_array_red = np.load('Be_array_red.npz')\nbe_array_red = Be_array_red['data'] \nE_array_red = np.load('E_array_red.npz')\ne_array_red = E_array_red['data'] \nEe_array_red = np.load('Ee_array_red.npz')\nee_array_red = Ee_array_red['data'] \n\nSize_signal = np.load('Size_signal.npz') \nsize_signal = Size_signal['data']\n\nB_array_blue= np.load('B_array_blue.npz')\nb_array_blue = B_array_blue['data'] \nBe_array_blue = np.load('Be_array_blue.npz')\nbe_array_blue = Be_array_blue['data'] \nE_array_blue = np.load('E_array_blue.npz')\ne_array_blue = E_array_blue['data'] \nEe_array_blue = np.load('Ee_array_blue.npz')\nee_array_blue = Ee_array_blue['data'] \n \nfig41= plt.figure(figsize=(sizex, sizey), dpi=dpi_no)\nfig41.set_size_inches(1200./fig41.dpi,900./fig41.dpi)\nplt.rc('text', usetex=True)\nplt.rc('font', family='serif')\nplt.rc('font', serif='Palatino') \nfig41.suptitle('Lifetimes fitted after 2000$\\mu$s decay, small NaYF$_4$ CS from Andrea \\n (10kV, 30$\\mu$m aperture, 2$\\mu$s time bins)',fontsize=fsizetit) \n\nax2 = plt.subplot2grid((2,1), (0,0), colspan=1, rowspan=1)\nax1 = plt.subplot2grid((2,1), (1,0), colspan=1, sharex=ax2)\n\nax1.spines['right'].set_visible(False)\nax1.spines['top'].set_visible(False)\nax1.xaxis.set_ticks_position('bottom')\nax1.yaxis.set_ticks_position('left')\n\nax2.spines['right'].set_visible(False)\nax2.spines['top'].set_visible(False)\nax2.xaxis.set_ticks_position('bottom')\nax2.yaxis.set_ticks_position('left')\n\n#ax2.set_ylim([0.0,10.0])\n#ax2.set_yticks([2.5, 5, 7.5, 10.0])\n#ax1.set_yticks([0.025, 0.05, 0.075,0.1])\n#ax1.set_ylim([0,0.1])\nax1.set_xticks([10,20,30,40,50,60,70,80])\nax1.set_xticklabels(let)\nx_vec = [10,20,30,40,50,60,70,80] #(6,10)\n\nax1.errorbar(x_vec, b_array_red, yerr=be_array_red, fmt='ro',markersize=5)\nax2.errorbar(x_vec, e_array_red, yerr=ee_array_red, fmt='ro', markersize=10)\nax1.errorbar(x_vec, b_array_blue, yerr=be_array_blue, fmt='bo',markersize=5)\nax2.errorbar(x_vec, e_array_blue, yerr=ee_array_blue, fmt='bo', markersize=10)\nax1.set_ylabel('Shorter time constant ($\\mu$s)',fontsize=fsizepl)\nax2.set_ylabel('Longer time constant ($\\mu$s)',fontsize=fsizepl)\nplt.xlim([0,90])\n#ax2.legend(fontsize=fsizepl)\nax1.set_xlabel('Regions (arb.)',fontsize=fsizepl)\n\nplt.sca(ax1) \n\nplt.setp(ax2.get_xticklabels(), visible=False)\n\n#ax3 = plt.subplot2grid((2,2), (0,1), colspan=1, rowspan=1)\n#plt.plot(np.arange(1,61)*nominal_time_on*fastfactor,cumu_blue.flatten(),c='b', label='From blue photons ($<$ 593nm)',linestyle='None', marker='o',markersize=5)\n#plt.plot(np.arange(1,61)*nominal_time_on*fastfactor,cumu_red.flatten(),c='r', label='From red photons ($>$ 593nm)',linestyle='None', marker='o',markersize=5)\n#plt.xlabel(\"Cumulative e-beam exposure time \\n per pixel (nominal, $\\mu$s)\",fontsize=fsizepl)\n#plt.ylabel(\"Average luminescence \\n for each frame, per pixel (KHz)\",fontsize=fsizepl)\n#plt.xlim([0,110])\n#plt.ylim([0,80])\n#ax3.spines['right'].set_visible(False)\n#ax3.spines['top'].set_visible(False)\n#ax3.xaxis.set_ticks_position('bottom')\n#ax3.yaxis.set_ticks_position('left')\n#ax3.arrow(20, 75, 60,0, head_width=2, head_length=6, fc='k', ec='k')\n#ax3.text(25, 78, 'stage temperature decreases', fontsize=15)\n#ax4 = ax3.twiny()\n#ax3Ticks = ax3.get_xticks() \n#ax4Ticks = ax3Ticks\n#ax4.set_xticks(ax4Ticks)\n#ax4.set_xbound(ax3.get_xbound())\n#ax4.set_xticklabels(x_vec.flatten())\n#ax4.set_xlabel('Temperature (C)',fontsize=fsizepl)\n\n#ax2.set_xlabel(\"x-transformed\")\n#ax2.set_xlim(0, 60)\n#ax2.set_xticks([10, 30, 40])\n#ax2.set_xticklabels(['7','8','99'])\n\n#ax5 = plt.subplot2grid((2,2), (1,1), colspan=1, rowspan=1)\n#plt.plot(x_vec,blue_int_array,c='b', label='From blue photons ($<$ 593nm)',linestyle='None', marker='o',markersize=10)\n#plt.plot(x_vec,red_int_array,c='r', label='From red photons ($>$ 593nm)',linestyle='None', marker='o',markersize=10)\n#plt.legend(loc='best')\n#plt.ylabel(\"Average luminescence \\n for each experiment, per pixel (KHz)\",fontsize=fsizepl)\n#ax5.spines['right'].set_visible(False)\n#ax5.spines['top'].set_visible(False)\n#ax5.xaxis.set_ticks_position('bottom')\n#ax5.yaxis.set_ticks_position('left')\n#ax5.set_xlabel('Time bin of time-resolved cathodoluminescence (nm)',fontsize=fsizepl)\n#plt.xlim([40,1010])\n#ax5.set_xticks([50,100,200,1000])\n#plt.ylim([0,80])\n\nmultipage_longer('ZZZZZSummary.pdf',dpi=80)\n\n\n\n\n\n\n","sub_path":"2016-10-27_NDs_Adamas_LTs/AnalysisOfLTLong.py","file_name":"AnalysisOfLTLong.py","file_ext":"py","file_size_in_byte":55447,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"530829874","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\nimport json\n\nfrom alipay.aop.api.constant.ParamConstants import *\n\n\nclass AlipayEcoSignFlowFinishModel(object):\n\n def __init__(self):\n self._flow_id = None\n\n @property\n def flow_id(self):\n return self._flow_id\n\n @flow_id.setter\n def flow_id(self, value):\n self._flow_id = value\n\n\n def to_alipay_dict(self):\n params = dict()\n if self.flow_id:\n if hasattr(self.flow_id, 'to_alipay_dict'):\n params['flow_id'] = self.flow_id.to_alipay_dict()\n else:\n params['flow_id'] = self.flow_id\n return params\n\n @staticmethod\n def from_alipay_dict(d):\n if not d:\n return None\n o = AlipayEcoSignFlowFinishModel()\n if 'flow_id' in d:\n o.flow_id = d['flow_id']\n return o\n\n\n","sub_path":"alipay/aop/api/domain/AlipayEcoSignFlowFinishModel.py","file_name":"AlipayEcoSignFlowFinishModel.py","file_ext":"py","file_size_in_byte":868,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"38210998","text":"import math\r\nimport numpy as np\r\nimport torch\r\nfrom torch import nn\r\nfrom torch.nn.parameter import Parameter\r\nfrom torch.nn.modules.module import Module\r\n\r\n\r\nclass GraphConvolution(Module):\r\n\r\n def __init__(self, in_features, out_features, bias=True):\r\n super(GraphConvolution, self).__init__()\r\n self.in_features = in_features\r\n self.out_features = out_features\r\n self.weight = Parameter(torch.FloatTensor(in_features, out_features))\r\n if bias:\r\n self.bias = Parameter(torch.FloatTensor(out_features))\r\n else:\r\n self.register_parameter('bias', None)\r\n self.reset_parameters()\r\n\r\n def reset_parameters(self):\r\n stdv = 1. / math.sqrt(self.weight.size(1))\r\n self.weight.data.uniform_(-stdv, stdv)\r\n if self.bias is not None:\r\n self.bias.data.uniform_(-stdv, stdv)\r\n\r\n def forward(self, input, adj):\r\n support = torch.mm(input, self.weight)\r\n output = torch.spmm(adj, support)\r\n if self.bias is not None:\r\n return output + self.bias\r\n else:\r\n return output\r\n\r\nclass NeuralTensorNetwork(Module):\r\n def __init__(self, in_features, out_features):\r\n super(NeuralTensorNetwork, self).__init__()\r\n self.in_features = in_features\r\n self.out_features = out_features\r\n self.weight1 = Parameter(torch.FloatTensor(in_features, in_features))\r\n self.weight2 = Parameter(torch.FloatTensor(2*in_features))\r\n self.bias = Parameter(torch.FloatTensor(out_features))\r\n self.reset_parameters()\r\n\r\n def reset_parameters(self):\r\n nn.init.xavier_uniform_(self.weight1)\r\n nn.init.uniform_(self.weight2, 0, 1)\r\n nn.init.uniform_(self.bias, 0, 1)\r\n\r\n def forward(self, input1, input2):\r\n input1_ = torch.matmul(input1,self.weight1)\r\n output1 = torch.matmul(input1_, input2)\r\n output2 = torch.dot(self.weight2, torch.cat([input1, input2], axis=0))\r\n \r\n return torch.tanh(output1 + output2 + self.bias)\r\n\r\n\r\nclass FrobeniusNorm(Module):\r\n def __init__(self):\r\n super(FrobeniusNorm, self).__init__()\r\n\r\n def forward(self, inputs, targets):\r\n diff = inputs - targets\r\n return torch.norm(diff)\r\n\r\n\r\nclass HardClusterLoss(Module):\r\n def __init__(self):\r\n super(HardClusterLoss, self).__init__()\r\n\r\n def forward(self, inputs):\r\n # return rate*torch.norm(inputs) #引数にrateを実装すること\r\n return torch.norm(inputs)","sub_path":"layers.py","file_name":"layers.py","file_ext":"py","file_size_in_byte":2520,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"193868990","text":"from bottle import response,request as req\nimport utils\nimport models\nimport api.stream.bbs\nimport re\nimport utils.rule\nimport datetime\ndef rest():\n\tres = logic(req.forms.get(\"thread-id\"),req.forms.get(\"text\"))\n\tresponse.status = res[\"code\"]\n\treturn res[\"res\"]\n\ndef logic(threadId,text):\n\tme = utils.getLoginUser()\n\tif(not me):\n\t\tstatus = 403\n\t\tres = {\"error\":\"not-login\"}\n\telif (len(text)>=300):\n\t\tstatus = 400\n\t\tres = {\"error\":\"text-is-up-to-300chars\"}\n\telif (text == \"\"):\n\t\tstatus = 400\n\t\tres = {\"error\":\"empty-text\"}\n\telif (not utils.validId(threadId)):\n\t\tstatus = 400\n\t\tres = {\"error\":\"invalid-thread-id\"}\n\telif (not models.BBSThread.objects(id=threadId)):\n\t\tstatus = 400\n\t\tres = {\"error\":\"thread-not-found\"}\n\telse:\n\t\tthread=models.BBSThread.objects(id=threadId)[0]\n\t\tpost = models.BBSPost()\n\t\tpost.thread=thread\n\t\tpost.text = text\n\t\tpost.user = me\n\t\tpost.number = thread.postsCount+1\n\t\tpost.save()\n\t\tthread.updatedAt=datetime.datetime.utcnow()\n\t\tthread.postsCount+=1\n\t\tthread.save()\n\t\tapi.stream.bbs.push(str(thread.id),post.to_rest())\n\t\tres = post.to_rest()\n\t\tstatus = 200\n\treturn {\"code\":status,\"res\":res}\n","sub_path":"src/api/bbs/posts/create.py","file_name":"create.py","file_ext":"py","file_size_in_byte":1114,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"418374204","text":"import discord\nfrom Core.Fonctions.WebRequest import webRequest\nfrom Core.Fonctions.Embeds import lignesEmbed\nfrom Core.Fonctions.AuteurIcon import auteur\n\nasync def embedMALcompare(user1,user2,genre,key,page):\n table,descip=[],\"\"\n listeUsers=[user1,user2]\n for i in range(2):\n search=await webRequest(\"https://api.jikan.moe/v3/user/\"+listeUsers[i].lower()+\"/\"+genre.lower()+\"list/\"+key.lower())\n assert search!=False, \"Je ne trouve pas un des utilisateurs, ou alors la liste d'un des utilisateurs que vous cherchez est vide : \"+listeUsers[i]+\" !\"\n table.append(search)\n i,longueur=0,len(table[0][genre.lower()])\n while i 1:\n # pprint.pprint(args)\n for update in args:\n if update['type'] == 'orderBookModify':\n vol = float(update['data']['amount'])\n rate = float(update['data']['rate'])\n if update['data']['type'] == 'bid':\n if rate > self.highest_bid_price:\n self.highest_bid_vol = vol\n self.highest_bid_price = rate\n print('New highest bid: {} ETH at {} BTC/ETH'.format(self.highest_bid_vol, self.highest_bid_price))\n else:\n if rate < self.lowest_ask_price:\n self.lowest_ask_vol = vol\n self.lowest_ask_price = rate\n print('New lowest ask: {} ETH at {} BTC/ETH'.format(self.lowest_ask_vol, self.lowest_ask_price))\n elif update['type'] == 'orderBookRemove':\n rate = float(update['data']['rate'])\n if update['data']['type'] == 'bid':\n if rate == self.highest_bid_price:\n print('Removing highest bid: {} ETH at {} BTC/ETH'.format(self.highest_bid_vol, self.highest_bid_price))\n self.highest_bid_price = float('-inf')\n else:\n print('Removing lowest ask: {} ETH at {} BTC/ETH'.format(self.lowest_ask_vol, self.lowest_ask_price))\n self.lowest_ask_price = float('+inf')\n\n try:\n yield from self.subscribe(on_BTC_ETH, 'BTC_ETH')\n except Exception as e:\n print(\"Could not subscribe to topic:\", e)\n\ndef main():\n runner = ApplicationRunner(\"wss://api.poloniex.com:443\", \"realm1\")\n runner.run(PoloniexComponent)\n\nif __name__ == \"__main__\":\n main()","sub_path":"poloniex_push.py","file_name":"poloniex_push.py","file_ext":"py","file_size_in_byte":2388,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"554129384","text":"import os\n\nfrom yaml import load\n\n_instance = None\n\n\nclass Singleton(object):\n _instance = None\n\n def __new__(cls, *args, **kwargs):\n if not isinstance(cls._instance, cls):\n cls._instance = object.__new__(cls, *args, **kwargs)\n return cls._instance\n\n\nclass RuntimeConfiguration(Singleton):\n \"\"\"\n Runtime configuration helper\n \"\"\"\n DEFAULT_CONFIGURATION = {\n 'CLI': {\n 'TYPE': ['SSH',\n 'TELNET'],\n 'PORTS': {\n 'SSH': 22,\n 'TELNET': 23\n }\n },\n 'LOGGING': {\n 'LEVEL': 'INFO'\n }\n }\n\n def __init__(self, config_path=None):\n if not hasattr(self, '_configuration'):\n self._configuration = self._read_configuration(config_path)\n\n @property\n def configuration(self):\n \"\"\"\n Configuration property\n :return: \n :rtype: dict\n \"\"\"\n return self._configuration\n\n def _read_configuration(self, config_path):\n \"\"\"Read configuration from file if exists or use default\"\"\"\n if config_path and os.path.isfile(config_path) and os.access(config_path, os.R_OK):\n with open(config_path, 'r') as config:\n loaded_configuration = load(config)\n return self._merge_configs(self.DEFAULT_CONFIGURATION, loaded_configuration)\n else:\n return self.DEFAULT_CONFIGURATION\n\n def _merge_configs(self, config_a, config_b):\n return config_b\n\n def read_key(self, complex_key):\n \"\"\"\n Value for complex key like CLI.PORTS\n :param complex_key: \n :return:\n \"\"\"\n value = self.configuration\n for key in complex_key.split('.'):\n if isinstance(value, dict):\n value = value.get(key)\n else:\n value = None\n break\n\n if not value:\n raise Exception(self.__class__.__name__, 'Incorrect key {} or value is not defined'.format(complex_key))\n return value\n","sub_path":"cloudshell/layer_one/core/helper/runtime_configuration.py","file_name":"runtime_configuration.py","file_ext":"py","file_size_in_byte":2062,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"398279355","text":"# -*- coding: utf-8 -*-\n\"\"\"\nDNA sequencing and amino acid identification\nTakes in a string of DNA\n\n@author: Cecilia Diehl\n\n\"\"\"\n\nimport random\nfrom amino_acids import aa, codons, aa_table # you may find these useful\nfrom load import load_seq\n\n\ndef shuffle_string(s):\n \"\"\"Shuffles the characters in the input string\n NOTE: this is a helper function, you do not\n have to modify this in any way \"\"\"\n return ''.join(random.sample(s, len(s)))\n\n# YOU WILL START YOUR IMPLEMENTATION FROM HERE DOWN ###\n\n\ndef get_complement(nucleotide):\n \"\"\" Returns the complementary nucleotide\n\n nucleotide: a nucleotide (A, C, G, or T) represented as a string\n returns: the complementary nucleotide\n >>> get_complement('A')\n 'T'\n >>> get_complement('C')\n 'G'\n >>> get_complement('F') #adding this to make sure the function finds non nucleotide letters\n 'Not a base pair'\n >>> get_complement('G')\n 'C'\n \"\"\"\n #replacing nucleotides with their correct base pair\n if nucleotide == 'A':\n \tcomplement = 'T'\n elif nucleotide == 'C':\n complement = 'G'\n elif nucleotide == 'T':\n complement = 'A'\n elif nucleotide == 'G':\n complement = 'C'\n else :\n \treturn \"Not a base pair\"\n\n return complement\n\n\ndef get_reverse_complement(dna):\n \"\"\" Computes the reverse complementary sequence of DNA for the specfied DNA\n sequence\n\n dna: a DNA sequence represented as a string\n returns: the reverse complementary DNA sequence represented as a string\n >>> get_reverse_complement(\"ATGCCCGCTTT\")\n 'AAAGCGGGCAT'\n >>> get_reverse_complement(\"CCGCGTTCA\")\n 'TGAACGCGG'\n >>> get_reverse_complement(\"A\") #does the function get caught up on short strings? nope, cool\n 'T'\n \"\"\"\n full_complement = \"\" #making an empty string\n reverse_complement = \"\"\n i = 0\n for letter in dna:\n complement = get_complement(letter)\n full_complement = full_complement + complement #filling full_complement with results from get_complement\n \n for i in range(1, len(full_complement)+1):\n nucleotide = full_complement[-i]\n reverse_complement = reverse_complement + nucleotide\n \n return reverse_complement #if I gave it 'ACT' it gives me 'TGA'\n\n\ndef rest_of_ORF(dna):\n \"\"\" Takes a DNA sequence that is assumed to begin with a start\n codon and returns the sequence up to but not including the\n first in frame stop codon. If there is no in frame stop codon,\n returns the whole string.\n\n dna: a DNA sequence\n returns: the open reading frame represented as a string\n >>> rest_of_ORF(\"ATGTGAA\") #testing TGA stop codon\n 'ATG'\n >>> rest_of_ORF(\"ATGAGATAGG\") #testing TAG stop codon\n 'ATGAGA'\n >>> rest_of_ORF(\"ATGGCATCTTAA\") #testing TAA stop codon\n 'ATGGCATCT'\n >>> rest_of_ORF(\"ATGATCTTAA\") #tsting if the stop codon is not in a set of three, returns dna\n 'ATGATCTTAA'\n \"\"\"\n stop = [\"TAA\", \"TAG\", \"TGA\"]\n for i in range(0, len(dna),3): \n if dna[i: i+3] in stop:#determining if the select 3 values are a stop codon\n return dna[:i]\n return dna \n\n\ndef find_all_ORFs_oneframe(dna):\n \"\"\" Finds all non-nested open reading frames in the given DNA\n sequence and returns them as a list. This function should\n only find ORFs that are in the default frame of the sequence\n (i.e. they start on indices that are multiples of 3).\n By non-nested we mean that if an ORF occurs entirely within\n another ORF, it should not be included in the returned list of ORFs.\n\n dna: a DNA sequence\n returns: a list of non-nested ORFs\n >>> find_all_ORFs_oneframe(\"ATGCATGAATGTAGATAGATGTGCCC\")\n ['ATGCATGAATGTAGA', 'ATGTGCCC']\n >>> find_all_ORFs_oneframe(\"ATGGGATGGTAG\") #if there is a nested orf it is not returned individualy\n ['ATGGGATGG']\n >>> find_all_ORFs_oneframe(\"ATGCATGAATGTAGATAGATGTGCCTAA\") #if the stop codon is not in a set of three\n ['ATGCATGAATGTAGA', 'ATGTGCCTAA']\n >>> find_all_ORFs_oneframe(\"TGGATGCATGAATGTAGATAGATGTGCCC\") #if the start codon is not at the begining\n ['ATGCATGAATGTAGA', 'ATGTGCCC']\n \"\"\"\n\n start = [\"ATG\"]\n i = 0\n orf_list = [] #creating an empty list to fill later\n while i < len(dna):\n #for i in range(0, len(dna)):\n if dna[i:i+3] in start:\n orf_list.append(rest_of_ORF(dna[i:]))\n i += len(rest_of_ORF(dna[i:]))\n i+=3\n return orf_list\n\n\ndef find_all_ORFs(dna):\n \"\"\" Finds all non-nested open reading frames in the given DNA sequence in\n all 3 possible frames and returns them as a list. By non-nested we\n mean that if an ORF occurs entirely within another ORF and they are\n both in the same frame, it should not be included in the returned list\n of ORFs.\n\n dna: a DNA sequence\n returns: a list of non-nested ORFs\n\n >>> find_all_ORFs(\"ATGCATGAATGTAG\")\n ['ATGCATGAATGTAG', 'ATGAATGTAG', 'ATG']\n >>> find_all_ORFs_oneframe(\"TATATGCATGAATGGTGAA\") #if the start codon is offset \n ['ATGCATGAATGG']\n >>> find_all_ORFs_oneframe(\"ATGCATCGCTGAATGAATTGACC\") #more than one orf in a frame, nested orf ignored\n ['ATGCATCGC', 'ATGAAT']\n \"\"\"\n orf_list = []\n orf_list.extend(find_all_ORFs_oneframe(dna[:])) #starting find_all_ORFs_oneframe offset each time \n orf_list.extend(find_all_ORFs_oneframe(dna[1:])) #extend replaces append for these\n orf_list.extend(find_all_ORFs_oneframe(dna[2:])) #when using append it makes a list of a list \n return orf_list\n\n\ndef find_all_ORFs_both_strands(dna):\n \"\"\" Finds all non-nested open reading frames in the given DNA sequence on both\n strands.\n\n dna: a DNA sequence\n returns: a list of non-nested ORFs\n >>> find_all_ORFs_both_strands(\"ATGCGAATGTAGCATCAAA\")\n ['ATGCGAATG', 'ATGCTACATTCGCAT']\n >>> find_all_ORFs_both_strands(\"ATGCATGAATGTAG\") #dna from find_all_ORFs() should have the same orfs plus more from the reverse_complement dna \n ['ATGCATGAATGTAG', 'ATGAATGTAG', 'ATG', 'ATGCAT']\n \"\"\"\n orf_list = []\n orf_list.extend(find_all_ORFs(dna)) #putting some orfs in a list\n orf_list.extend(find_all_ORFs(get_reverse_complement(dna))) #including the compliment of the dna strand\n return orf_list[::]\n\ndef longest_ORF(dna):\n \"\"\" Finds the longest ORF on both strands of the specified DNA and returns it\n as a string. I think that this test is already pretty good because it is working\n from functions that have already been thoughrly tested, so as long as it can pick out\n the longest orf string in the given list it works\n >>> longest_ORF(\"ATGCGAATGTAGCATCAAA\") #longest orf is last in the list\n 'ATGCTACATTCGCAT'\n >>> longest_ORF(\"ATGCATGAATGTAG\") #longest orf is first in the list\n 'ATGCATGAATGTAG'\n \"\"\"\n orf_list = []\n orf_list.extend(find_all_ORFs_both_strands(dna)) #including all orfs\n return max(orf_list, key=len) #taking the orf with the max length\n\n\ndef longest_ORF_noncoding(dna, num_trials):\n \"\"\" Computes the maximum length of the longest ORF over num_trials shuffles\n of the specfied DNA sequence\n\n dna: a DNA sequence\n num_trials: the number of random shuffles\n returns: the maximum length longest ORF \"\"\"\n length = 0\n for trial in range(num_trials):\n string = shuffle_string(dna)\n if len(str(longest_ORF(string)))>length: \n length = len(str(longest_ORF(string))) #replaces the value (orf) if it finds one longer\n return length\n \n\n\ndef coding_strand_to_AA(dna):\n \"\"\" Computes the Protein encoded by a sequence of DNA. This function\n does not check for start and stop codons (it assumes that the input\n DNA sequence represents an protein coding region).\n\n dna: a DNA sequence represented as a string\n returns: a string containing the sequence of amino acids encoded by the\n the input DNA fragment\n #the start codon is offset in the seccond test, however this isn't a problem because the \n #dna used in the final run will have already been separated into orfs starting with start codons\n\n >>> coding_strand_to_AA(\"ATGCGA\")\n 'MR'\n >>> coding_strand_to_AA(\"ATGCCCGCTTT\") \n 'MPA'\n >>> coding_strand_to_AA(\"GGCATGCCCGCTTT\") #the start codon is offset \n 'GMPA'\n \"\"\"\n sequence = \"\"\n for i in range(0,len(dna),3):\n codon = dna[i:i+3]\n if len(codon) == 3: \n amino_acid = aa_table[codon]\n sequence = sequence + amino_acid\n return sequence \n\n\n\n\ndef gene_finder(dna):\n \"\"\" Returns the amino acid sequences that are likely coded by the specified dna\n\n dna: a DNA sequence\n returns: a list of all amino acid sequences coded by the sequence dna.\n \"\"\"\n sequence_list = []\n threshold = longest_ORF_noncoding(dna, 1500) #returns a length, int\n orfs = find_all_ORFs_both_strands(dna) #returns list\n for orf in orfs:\n if len(orf) >= threshold:\n amino_acid = coding_strand_to_AA(orf)\n sequence_list.append(amino_acid)\n return sequence_list\n \n\nif __name__ == \"__main__\":\n import doctest\n doctest.testmod()\n #dna = load_seq(\"./data/X73525.fa\") #uncomment to run w/ imported dna\n #print gene_finder(dna) #uncomment to print\n\n","sub_path":"gene_finder.py","file_name":"gene_finder.py","file_ext":"py","file_size_in_byte":9403,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"400378627","text":"from django.conf.urls import url\nfrom . import views\n\napp_name = 'books'\n\nurlpatterns = [\n url(r'^$', views.index, name='index'),\n url(r'^(?P[0-9]+)/$', views.detail, name='detail'),\n url(r'^cart/(?P[0-9]+)/$', views.cart_add, name='detail_login')\n]","sub_path":"books/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":280,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"2054988","text":"# coding:utf8\nimport smtplib\nfrom email.mime.multipart import MIMEMultipart\nfrom email.mime.text import MIMEText\nimport GetConfig as gc\ntry:\n import configparser as cp\nexcept Exception:\n import ConfigParser as cp\n\n#read config\nemailcfg = gc.EmailConfig()\nemail_enable = emailcfg.email_enable()\nemail_host = emailcfg.email_host()\nemail_port = emailcfg.email_port()\nemail_sender = emailcfg.email_sender()\nemail_password = emailcfg.email_password()\nemail_receiver = emailcfg.email_receiver()\nemail_receiver_list = email_receiver.split(',')\nemail_encrypt = emailcfg.email_encrypt()\n\ndef email_switch(func):\n def send(*args):\n if email_enable == 'yes':\n return func(*args)\n else:\n print(\"The Email swich is off.\")\n return send\n\ndef send_email(title, content):\n msg = MIMEMultipart()\n msg['Subject'] = title\n msg['From'] = email_sender\n msg['To'] = \",\".join(email_receiver_list)\n context = MIMEText(content, _subtype='html', _charset='utf-8')\n msg.attach(context)\n try:\n if email_encrypt == 'ssl':\n send_smtp = smtplib.SMTP_SSL(email_host, 465)\n send_smtp.connect(email_host)\n else:\n send_smtp = smtplib.SMTP()\n if email_encrypt == 'tls':\n send_smtp.connect(email_host, 587)\n send_smtp.ehlo()\n send_smtp.starttls()\n else:\n send_smtp.connect(email_host, email_port)\n send_smtp.ehlo()\n except:\n print(\"Failed to access smtp server!\")\n return False\n\n try:\n send_smtp.login(email_sender, email_password)\n except:\n print(\"ID or Password is wrong\")\n return False\n\n try:\n send_smtp.sendmail(email_sender, email_receiver_list, msg.as_string())\n except:\n print(\"Send Fail, Please check recipient\")\n return False\n\n send_smtp.close()\n print(\"Send success!\")\n return True\n\n@email_switch\ndef send_warnmail(warninfo_email):\n data_table = \"\"\n for lstMsg in warninfo_email:\n line_table = \"\"\"\n \"\"\" + str(lstMsg[0]) + \"\"\"\n \"\"\" + str(lstMsg[1]) + \"\"\"\n \"\"\" + str(lstMsg[2]) + \"\"\"\n \"\"\" + str(lstMsg[3]) + \"\"\"\n \"\"\" + str(lstMsg[4]) + \"\"\"\n \"\"\"\n data_table = data_table + line_table\n content = \"\"\"\\\n \n \n \n 用户未确认预警信息\n \n \n
\n

用户未确认预警信息

\n
\n
\n \n
\n
\n
\n
\n \n \n \n \n \n \n \"\"\" + data_table + \"\"\"\n \n \n \n
TimeIPDeviceLevelMessage
\n
\n \n \"\"\"\n title = \"ClusterIO System Status Alert\"\n send_email(title, content)\n\n@email_switch\ndef send_test():\n title = \"This is a HA-AP test email\"\n content = \"Test\"\n send_email(title, content)\n\n@email_switch\ndef send_live():\n title = \"HA-AP Timing alarm clock\"\n content = \"I'm still alive\"\n send_email(title, content)\n\n\nif __name__ == '__main__':\n send_test()\n # a = [['2020-04-29 16:36:42', '10.203.1.4', 'engine0', 2, 'Engine reboot 6674 secends ago']]\n # send_warnmail(a)\n\n","sub_path":"SendEmail.py","file_name":"SendEmail.py","file_ext":"py","file_size_in_byte":4038,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"514129957","text":"\"\"\"\n크루스칼 알고리즘(최소신장트리)\n\"\"\"\n\n\n# 풀이 1\ndef union(parent, a, b):\n # 번호가 더 작은 원소가 부모 노드가 되도록 함\n A = find(parent, a)\n B = find(parent, b)\n\n if A < B:\n parent[B] = A\n else:\n parent[A] = B\n\n\ndef find(parent, x):\n if parent[x] == x:\n return x\n return find(parent, parent[x])\n\n\ndef solution(n, costs):\n parents = [i for i in range(n)]\n costs = sorted(costs, key=lambda x: x[2])\n\n answer = 0\n for first, second, cost in costs:\n if find(parents, first) != find(parents, second): # 사이클 유무 확인\n union(parents, first, second)\n answer += cost\n\n return answer\n\n\n# 풀이 2\n\ndef ancestor(node, parents):\n if parents[node] == node:\n return node\n else:\n return ancestor(parents[node], parents)\n\n\ndef solution2(n, costs):\n answer = 0\n edges = sorted([(x[2], x[0], x[1]) for x in costs])\n parents = [i for i in range(n)]\n bridges = 0\n for w, f, t in edges:\n if ancestor(f, parents) != ancestor(t, parents):\n answer += w\n parents[ancestor(f, parents)] = t\n bridges += 1\n if bridges == n - 1:\n break\n return answer\n\n\n# 4\nprint(solution(4, [[0, 1, 1], [0, 2, 2], [1, 2, 5], [1, 3, 1], [2, 3, 8]]))\n# 15\nprint(solution(5, [[0, 1, 5], [1, 2, 3], [2, 3, 3], [3, 1, 2], [3, 0, 4], [2, 4, 6], [4, 0, 7]]))\n# 8\nprint(solution(5, [[0, 1, 1], [3, 4, 1], [1, 2, 2], [2, 3, 4]]))\n# 9\nprint(solution(4, [[0, 1, 5], [1, 2, 3], [2, 3, 3], [1, 3, 2], [0, 3, 4]]))\n# 104\nprint(solution(5, [[0, 1, 1], [3, 1, 1], [0, 2, 2], [0, 3, 2], [0, 4, 100]]))\n# 11\nprint(solution(6, [[0, 1, 5], [0, 3, 2], [0, 4, 3], [1, 4, 1], [3, 4, 10], [1, 2, 2], [2, 5, 3], [4, 5, 4]]))\n# 6\nprint(solution(5, [[0, 1, 1], [2, 3, 1], [3, 4, 2], [1, 2, 2], [0, 4, 100]]))\n# 8\nprint(solution(5, [[0, 1, 1], [0, 4, 5], [2, 4, 1], [2, 3, 1], [3, 4, 1]]))\n# 8\nprint(solution(5, [[0, 1, 1], [0, 2, 2], [0, 3, 3], [0, 4, 4], [1, 3, 1]]))\n","sub_path":"programmers/lv3/connecting_islands.py","file_name":"connecting_islands.py","file_ext":"py","file_size_in_byte":2029,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"565924184","text":"def main():\n\tf = open('grid', 'r')\n\tgrid = []\n\tprod = 0\n\tfor line in f:\n\t\tline = line.rstrip()\n\t\tcol = line.split()\n\t\tfor n in range(0,len(col)):\n\t\t\tcol[n] = int(col[n])\n\t\tgrid.append(col)\n#\tprint(grid)\n\tfor i in range(0,20):\n\t\tfor j in range(0,20):\n\t\t\thoriz = diag = vert = 1\n\t\t\tfor k in range(0,4):\n\t\t\t\thoriz *= grid[i%20][(j+k)%20]\n\t\t\t\tdiag *= grid[(i+k)%20][(j+k)%20]\n\t\t\t\tvert *= grid[(i+k)%20][j%20]\n\t\t\tif horiz > 20000000:\n\t\t\t\tprod = horiz\n\t\t\t\tprint('(',j,',',i,')',' : horizontal : ', prod)\n\t\t\tif diag > 20000000:\n\t\t\t\tprod = diag\n\t\t\t\tprint('(',j,',',i,')',' : diagonal : ', prod)\n\t\t\tif vert > 20000000:\n\t\t\t\tprod = vert\n\t\t\t\tprint('(',j,',',i,')',' : vertical : ', prod)\nmain()\n","sub_path":"11/11.py","file_name":"11.py","file_ext":"py","file_size_in_byte":683,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"354270693","text":"from pugsql import lexer\nfrom unittest import TestCase\n\n\nclass LexerTest(TestCase):\n def test_basic(self):\n self.assertEqual([\n ('C', '-- :name username_for_id :1'),\n ('Q', 'select username from users where user_id = :user_id'),\n ], lexer.lex(open('tests/sql/basic.sql', 'r').read()))\n","sub_path":"tests/test_lexer.py","file_name":"test_lexer.py","file_ext":"py","file_size_in_byte":324,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"582790251","text":"from django.shortcuts import render\nfrom django.http import HttpResponse\n\nfrom .models import Greeting\n\nimport os\nfrom pymongo import MongoClient\nfrom bson.son import SON\nfrom bson.objectid import ObjectId\n\nimport psutil\nimport memory_profiler\ntry:\n from StringIO import StringIO\nexcept ImportError:\n from io import StringIO\n\nimport objgraph\n\nimport gc\n\nif hasattr(gc, 'set_debug'):\n gc.set_debug(\n gc.DEBUG_UNCOLLECTABLE |\n getattr(gc, 'DEBUG_OBJECTS', 0) |\n getattr(gc, 'DEBUG_LEAK', 0) |\n getattr(gc, 'DEBUG_INSTANCES', 0))\n\n\nhost_id = ObjectId()\n\n\ndef get_mem():\n process = psutil.Process(os.getpid())\n return process.memory_info().rss\n\n\n# Create your views here.\ndef index(request):\n # return HttpResponse('Hello from Python!')\n return render(request, \"index.html\")\n\n\ndef db(request):\n\n greeting = Greeting()\n greeting.save()\n\n greetings = Greeting.objects.all()\n\n return render(request, \"db.html\", {\"greetings\": greetings})\n\nfrom pymongo import network\n\n\ndef _get_documents(request):\n def _receive_data_on_socket_mod(sock, length):\n buf = bytearray(length)\n i = 0\n while length:\n try:\n chunk = sock.recv(min(length, 16384))\n except (IOError, OSError) as exc:\n if network._errno_from_exception(exc) == network.errno.EINTR:\n continue\n raise\n if chunk == b\"\":\n raise network.AutoReconnect(\"connection closed\")\n\n buf[i:i + len(chunk)] = chunk\n i += len(chunk)\n length -= len(chunk)\n\n return bytes(buf)\n\n network._receive_data_on_socket = _receive_data_on_socket_mod\n\n uri = os.environ.get('MONGODB_URI')\n if not uri:\n return ['MONGODB_URI not set!']\n\n limit = 50\n with MongoClient(uri) as client:\n coll = client.heroku.test\n large_batch_coll = client.heroku.large\n if large_batch_coll.estimated_document_count() == 0:\n # Add ~20Mib of data\n large = 's'*1024*1024\n large_batch_coll.insert_many(\n [{'s': large, 'i': i} for i in range(20)])\n docs = list(large_batch_coll.find(batch_size=1024))\n del docs\n last_mem = get_mem()\n for i in range(limit):\n mem = get_mem()\n delta = mem - last_mem\n last_mem = mem\n doc = SON([('mem', mem), ('units', 'bytes'),\n ('delta', delta), ('client', i), ('host', host_id)])\n coll.insert_one(doc)\n # Close all connections.\n client.close()\n documents = list(coll.find(\n {'host': host_id}, limit=limit*50, sort=[('_id', -1)],\n projection={'_id': False, 'host': False}))\n\n return documents\n\nimport socket\nfrom pymongo.client_session import ClientSession\nfrom pymongo.pool import Pool\nfrom pymongo.periodic_executor import PeriodicExecutor\nfrom threading import Thread\nfrom bson import CodecOptions\n\ndef filter(obj):\n return isinstance(obj, (socket.socket, Pool, PeriodicExecutor, Thread, CodecOptions))\n\ndef get_objs():\n objs = []\n objs.extend(objgraph.by_type(socket.socket.__name__))\n objs.extend(objgraph.by_type(socket._closedsocket.__name__))\n return objs\n\ndef mongodb(request):\n stream = StringIO()\n docs = memory_profiler.profile(_get_documents, stream=stream)(request)\n extra = '%s\\nEXTRA:\\n%s' % (stream.getvalue(), '')\n resp = render(request, \"mongodb.html\", {\"documents\": docs, \"extra\": extra})\n del docs\n print('objgraph.show_growth(limit=100):')\n objgraph.show_growth(limit=100)\n # print('objgraph.show_backrefs(get_objs()):')\n # objgraph.show_backrefs(get_objs())\n return resp\n","sub_path":"hello/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3751,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"648248080","text":"# 2020.06.19\nimport numpy as np\nfrom glob import glob\nimport cv2\nimport os\nimport sklearn\nimport sys\nimport csv\nfrom sklearn.model_selection import KFold\nfrom sklearn.preprocessing import StandardScaler\nfrom skimage.measure import block_reduce\n\ndef read_dataset(path, size=32):\n pics = glob(path+\"*\")\n raw_images, flipped_raw_images, raw_labels = [], [], []\n for i in range (len(pics)):\n image = cv2.imread(pics[i])\n image = cv2.resize(image, (size,size))\n raw_images.append(image[:,:,0]/255)\n flipped_raw_images.append(cv2.flip(image, 1)[:,:,0]/255)\n raw_labels.append(os.path.basename(pics[i]).split('\\\\')[-1].split('.')[0])\n return np.asarray(raw_images).reshape(-1,size,size,1), np.asarray(flipped_raw_images).reshape(-1,size,size,1), raw_labels\n\ndef lfw_train_test(root, pair_txt_path, raw_images, flipped_raw_images, raw_labels, foldnum, includeflipped=False):\n with open(root+pair_txt_path, 'r') as csvfile:\n rows = list(csv.reader(csvfile, delimiter='\\t'))[1:]\n kf = KFold(n_splits=10)\n fold = 0\n for train_index,test_index in kf.split(rows):\n fold += 1\n trainrows, testrows = [], []\n for i in train_index:\n trainrows.append(rows[i])\n for i in test_index:\n testrows.append(rows[i])\n if(fold==foldnum):\n break\n raw_labels_dic = {}\n for i in range(len(raw_labels)):\n if(includeflipped):\n raw_labels_dic[raw_labels[i]] = [raw_images[i], flipped_raw_images[i]]\n else:\n raw_labels_dic[raw_labels[i]] = [raw_images[i]]\n\n trainData1 = []#first image in a pair, even ones are origianl and odd ones are flipped versions\n trainData1flipped = []\n trainData2 = []#second image in a pair\n trainData2flipped = []\n trainLabel = []#match/mismatch label\n for row in trainrows:#testrows\n if len(row) == 3 :\n name1 = row[0] + '_' + format(int(row[1]), '04d')\n name2 = row[0] + '_' + format(int(row[2]), '04d')\n label = 1\n elif(len(row) == 4):\n name1 = row[0] + '_' + format(int(row[1]), '04d')\n name2 = row[2] + '_' + format(int(row[3]), '04d')\n label = 0#not the same\n flag = 0\n if includeflipped:\n if name1 in raw_labels_dic.keys():\n vect1 = raw_labels_dic[name1][0]\n vect2 = raw_labels_dic[name1][1]\n flag += 1\n if name2 in raw_labels_dic.keys():\n vect3 = raw_labels_dic[name2][0]\n vect4 = raw_labels_dic[name2][1]\n flag += 1\n if flag != 2:\n print(\" Train row: \", row,\" is not found!\")\n continue\n trainData1.append(vect1)\n trainData1flipped.append(vect2)\n trainData2.append(vect3)\n trainData2flipped.append(vect4)\n trainLabel.append(label)\n else:\n if name1 in raw_labels_dic.keys():\n vect1 = raw_labels_dic[name1][0]\n flag += 1\n if name2 in raw_labels_dic.keys():\n vect3 = raw_labels_dic[name2][0]\n flag += 1\n if flag != 2:\n print(\" Train row: \", row,\" is not found!\")\n continue\n trainData1.append(vect1)\n trainData2.append(vect3)\n trainLabel.append(label)\n\n testData1=[]#first image in a pair, even ones are origianl and odd ones are flipped versions\n testData1flipped=[]\n testData2=[]#second image in a pair\n testData2flipped=[]\n testLabel=[]#match/mismatch label\n for row in testrows:#testrows\n if len(row)==3:\n name1 = row[0] + '_' + format(int(row[1]), '04d')\n name2 = row[0] + '_' + format(int(row[2]), '04d')\n label = 1\n elif len(row)==4:\n name1 = row[0] + '_' + format(int(row[1]), '04d')\n name2 = row[2] + '_' + format(int(row[3]), '04d')\n label = 0#not the same\n flag = 0\n if name1 in raw_labels_dic.keys():\n vect1 = raw_labels_dic[name1][0]\n flag += 1\n if name2 in raw_labels_dic.keys():\n vect3 = raw_labels_dic[name2][0]\n flag += 1\n if flag != 2:\n print(\" Test row: \", row, \" is not found!\")\n continue\n testData1.append(vect1)\n testData2.append(vect3)\n testLabel.append(label)\n if(includeflipped):\n trainData1 = np.concatenate((trainData1,trainData1flipped), axis=0)\n trainData2 = np.concatenate((trainData2,trainData2flipped), axis=0)\n trainLabel = np.concatenate((trainLabel,trainLabel), axis=0)\n print(\" Get %s training pairs, %s testing pairs!\"%(str(len(trainData1)), str(len(testData1))))\n return np.asarray(trainData1), np.asarray(trainData2), np.asarray(trainLabel), np.asarray(testData1), np.asarray(testData2), np.asarray(testLabel)\n\ndef myStandardScaler(X, S, train=True):\n shape = (X.shape[0], X.shape[1], X.shape[2])\n if train == True:\n S = []\n for i in range(X.shape[-1]):\n ss = StandardScaler()\n ss.fit(X[:,:,:,i].reshape(-1, 1))\n S.append(ss)\n for i in range(X.shape[-1]):\n tmp = S[i].transform(X[:,:,:,i].reshape(-1, 1))\n X[:,:,:,i] = tmp.reshape(shape)\n return X, S\n\ndef Generate_feature(x1, x2, hop=1, loc={'1': [[0,0, 10 ,12],[0, 16, 10, 28], [7, 9, 18, 19],[17,5, 25, 23]],\n '2':[[0,0, 4, 10], [4,1,10,9]],\n '3':10}):\n print(\"change\")\n cos, ra = [], []\n if hop == 3:\n n = loc['3']\n for l in range(1, x1.shape[-1]//n+1):\n tmp = []\n rra = []\n for i in range(x1.shape[0]):\n vect1 = x1[i, :, :, n*(l-1):n*(l)].reshape(1, -1)\n vect2 = x2[i, :, :, n*(l-1):n*(l)].reshape(1, -1) \n a = np.sqrt(np.sum(np.square(vect1)))\n b = np.sqrt(np.sum(np.square(vect2)))\n if a > b:\n c = a/b\n else:\n c = b/a\n rra.append(c)\n tmp.append([sklearn.metrics.pairwise.cosine_similarity(vect1,vect2)[0,0]])\n rra = np.array(rra).reshape(-1,1)\n ra.append(rra)\n tmp = np.array(tmp).reshape(-1, 1)\n cos.append(tmp)\n ra = np.concatenate(ra, axis=1)\n ra = np.mean(ra, axis=1, keepdims=True)\n cos = np.concatenate(cos, axis=1)\n print(\" Hop3 contributes %s cosine simality, %s length ratio!\"%(str(cos.shape[-1]), str(ra.shape[-1])))\n return np.concatenate((ra, cos), axis=1)\n for l in loc[str(hop)]:\n tmp = []\n feature_by_space = []\n # -1 denotes principal components, 0 denotes training pairs\n for i in range(x1.shape[-1]):\n tmpp = []\n ra = []\n features = []\n for j in range(x1.shape[0]):\n vect1 = x1[i, l[0]:l[2], l[1]:l[3], j].reshape(1, -1)\n vect2 = x2[i, l[0]:l[2], l[1]:l[3], j].reshape(1, -1)\n features.append(vect1)\n features.append(vect2)\n a = np.sqrt(np.sum(np.square(vect1)))\n b = np.sqrt(np.sum(np.square(vect2)))\n if a > b:\n c = a/b\n else:\n c = b/a\n ra.append(c)\n tmpp.append([sklearn.metrics.pairwise.cosine_similarity(vect1,vect2)[0,0]])\n features = np.concatenate(features)\n print(features.shape)\n feature_by_space.append(features)\n print(feature_by_space)\n tmpp.append([np.mean(ra)])\n tmp.append(np.array(tmpp).reshape(-1))\n tmp = np.array(tmp)\n cos.append(tmp)\n print(\" Hop%s contributes %s cosine simality, %s length ratio!\"%(str(hop), str(tmp.shape[-1]-len(loc[str(hop)])), str(len(loc[str(hop)]))))\n return np.concatenate(cos, axis=1)\n\ndef MaxPooling(x):\n return block_reduce(x, (1, 2, 2, 1), np.max)\n\ndef get_gender_label(folder_path):\n image_file_name = []\n for fullfile in glob(folder_path+'/data/HEFrontalizedLfw2/*'):\n image_file_name.append(fullfile.split('/')[-1].strip('.jpg\\n'))\n female_names = []\n with open(folder_path+'/data/female_names.txt') as f:\n content = f.readlines()\n for line in content:\n female_names.append(line.strip('.jpg\\n'))\n male_names = []\n with open(folder_path+'/data/male_names.txt') as f:\n content = f.readlines()\n for line in content:\n male_names.append(line.strip('.jpg\\n'))\n gender_label = []\n for i, name in enumerate(image_file_name):\n if name in female_names:\n gender_label.append(0)\n elif name in male_names:\n gender_label.append(1)\n else:\n print(name, \"label not found!\")\n return np.array(gender_label) \n\ndef get_image_array(folder_path):\n image_list = []\n for filename in glob(folder_path+'/data/HEFrontalizedLfw2/*'):\n image = cv2.imread(filename)\n image = cv2.resize(image, (32,32))\n image_list.append(image/255)\n image_array = np.array(image_list)\n return image_array","sub_path":"FaceHop/framework/util.py","file_name":"util.py","file_ext":"py","file_size_in_byte":9405,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"330975983","text":"import boto3\nimport posixpath\n\ntry:\n from urlparse import urlparse\nexcept ImportError:\n from urllib.parse import urlparse\n\nfrom dvc.config import Config\nfrom dvc.remote.base import RemoteBase\n\n\nclass RemoteS3(RemoteBase):\n scheme = 's3'\n REGEX = r'^s3://(?P.*)$'\n PARAM_ETAG = 'etag'\n\n def __init__(self, project, config):\n self.project = project\n self.url = config.get(Config.SECTION_REMOTE_URL, '/')\n self.region = config.get(Config.SECTION_AWS_REGION, None)\n self.profile = config.get(Config.SECTION_AWS_PROFILE, None)\n self.credentialpath = config.get(Config.SECTION_AWS_CREDENTIALPATH, None)\n\n @property\n def bucket(self):\n return urlparse(self.url).netloc\n\n @property\n def prefix(self):\n return urlparse(self.url).path.lstrip('/')\n\n @property\n def s3(self):\n return boto3.resource('s3')\n\n def get_etag(self, bucket, key):\n try:\n obj = self.s3.Object(bucket, key).get()\n except Exception:\n return None\n\n return obj['ETag'].strip('\"')\n\n def save_info(self, path_info):\n if path_info['scheme'] != 's3':\n raise NotImplementedError\n\n return {self.PARAM_ETAG: self.get_etag(path_info['bucket'], path_info['key'])}\n\n def save(self, path_info):\n if path_info['scheme'] != 's3':\n raise NotImplementedError\n\n etag = self.get_etag(path_info['bucket'], path_info['key'])\n dest_key = posixpath.join(self.prefix, etag[0:2], etag[2:])\n\n source = {'Bucket': path_info['bucket'],\n 'Key': path_info['key']}\n self.s3.Bucket(self.bucket).copy(source, dest_key)\n\n return {self.PARAM_ETAG: etag}\n\n def checkout(self, path_info, checksum_info):\n if path_info['scheme'] != 's3':\n raise NotImplementedError\n\n etag = checksum_info.get(self.PARAM_ETAG, None)\n if not etag:\n return\n\n key = posixpath.join(self.prefix, etag[0:2], etag[2:])\n source = {'Bucket': self.bucket,\n 'Key': key}\n\n self.s3.Bucket(path_info['bucket']).copy(source, path_info['key'])\n\n def remove(self, path_info):\n if path_info['scheme'] != 's3':\n raise NotImplementedError\n\n try:\n obj = self.s3.Object(path_info['bucket'], path_info['key']).get()\n obj.delete()\n except Exception:\n pass\n\n def upload(self, path, path_info):\n if path_info['scheme'] != 's3':\n raise NotImplementedError\n\n self.s3.Object(path_info['bucket'], path_info['key']).upload_file(path)\n\n\n def download(self, path_info, path):\n if path_info['scheme'] != 's3':\n raise NotImplementedError\n\n self.s3.Object(path_info['bucket'], path_info['key']).download_file(path)\n","sub_path":"dvc/remote/s3.py","file_name":"s3.py","file_ext":"py","file_size_in_byte":2837,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"440059075","text":"import requests\nimport pandas as pd\nfrom bs4 import BeautifulSoup\n\npage = \"http://www.yahii.com.br/dolar.html\"\npage = requests.get(page)\npage = str(page.content)\nsoup = BeautifulSoup(page,\"html.parser\")\n\nall_tables = soup.find_all('table')\nnova_tabela = soup.find('table')\n#tags = res.findAll(\"h3\", {\"class\": \"post-title\"})\nprint(all_tables[4])\n'''\nA=[]\nB=[]\nC=[]\nD=[]\nE=[]\nF=[]\nG=[]\n\nfor row in nova_tabela.find_all(\"tr\"):\n cells = row.find_all(\"td\")\n h = row.find_all(\"th\")\n if len(cells)==6:\n A.append(cells[0].find(text=True))\n B.append(h[0].find(text=True))\n C.append(cells[1].find(text=True))\n D.append(cells[2].find(text=True))\n E.append(cells[3].find(text=True))\n F.append(cells[4].find(text=True))\n G.append(cells[5].find(text=True))\n# print(A)\n# print(B)\n# print(C)\n# print(D)\n# print(E)\n# print(F)\n# print(G)\n\ndf = pd.DataFrame(A,columns=['Number'])\ndf['State']=B\ndf['Admin_Capital']=C\ndf['Legislative_Capital']=D\ndf['Judiciary_Capital']=E\ndf['Year_Capital']=F\ndf['Former_Capital']=G\nprint(df)\n'''","sub_path":"COLETANDO/beautifulsoup_tabela.py","file_name":"beautifulsoup_tabela.py","file_ext":"py","file_size_in_byte":1066,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"352758912","text":"import sys\nfrom PyQt5.QtGui import *\nfrom PyQt5.QtCore import *\nfrom PyQt5.QtWidgets import *\n\n\n# contoh penerapan dialog versi model dan non-model\nclass DialogForm(QDialog):\n def __init__(self):\n super().__init__()\n self.setupUi()\n\n def setupUi(self):\n # mengatur ukuran dan posisi\n self.resize(300, 100)\n self.move(320, 280)\n # menentukan nama windownya\n self.setWindowTitle('Dialog')\n # membuat label\n self.label = QLabel('')\n # membuat button\n self.closeButton = QPushButton('Tutup')\n # merapikan item\n hbox = QHBoxLayout()\n hbox.addStretch()\n hbox.addWidget(self.closeButton)\n layout = QVBoxLayout()\n layout.addWidget(self.label)\n layout.addLayout(hbox)\n self.setLayout(layout)\n # menghubungkan button close dengan fungsinya\n self.closeButton.clicked.connect(self.close)\n\n\n# kelas form utama\nclass MainForm(QWidget):\n def __init__(self):\n super().__init__()\n self.setupUi()\n\n def setupUi(self):\n # setting ukuran dan posisi\n self.resize(350, 100)\n self.move(300, 300)\n # menentukan judul window\n self.setWindowTitle('Demo QDialog.setModal()')\n # membuat label dan lineEdit\n self.label = QLabel('Tuliskan teks pada kotak di bawah ' + 'ketika dialog ditampilkan.')\n self.lineEdit = QLineEdit()\n # membuat button dengan untuk modal dan non-modal\n self.showModalDialogButton = QPushButton('Modal')\n self.showModelessDialogButton = QPushButton('Non-Modal')\n # set layout\n hbox = QHBoxLayout()\n hbox.addWidget(self.showModalDialogButton)\n hbox.addWidget(self.showModelessDialogButton)\n layout = QVBoxLayout()\n layout.addWidget(self.label)\n layout.addWidget(self.lineEdit)\n layout.addLayout(hbox)\n self.setLayout(layout)\n # menghubungkan button dengan fungsinya\n self.showModalDialogButton.clicked.connect(self.showModalDialogButtonClick)\n self.showModelessDialogButton.clicked.connect(self.showModelessDialogButtonClick)\n\n # menampilkan dialog secara modal\n # mainform ga bisa di klik atau diakses sebelum dialog ini ditutup\n def showModalDialogButtonClick(self):\n self.form = DialogForm()\n self.form.label.setText('Dialog bersifat modal')\n self.form.setModal(True)\n self.form.show()\n\n # menampilkan dialog secara non-modal\n # mainform bisa diakses tanpa harus close dialog ini\n def showModelessDialogButtonClick(self):\n self.form = DialogForm()\n self.form.label.setText('Dialog bersifat non\u0002modal (modeless)')\n self.form.setModal(False)\n self.form.show()\n\n\nif __name__ == '__main__':\n a = QApplication(sys.argv)\n form = MainForm()\n form.show()\n a.exec_()\n","sub_path":"Praktikum/Modul7/QDialog2.py","file_name":"QDialog2.py","file_ext":"py","file_size_in_byte":2875,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"283655388","text":"import os\n\nimport spacy\n\nnlp = spacy.load(\"es_core_news_md\")\nprint('spaCy loaded')\ndataset = \"abstracts\"\n\nos.makedirs(dataset + \"_verb/\", exist_ok=True)\nos.makedirs(dataset + \"_propn/\", exist_ok=True)\nos.makedirs(dataset + \"_num/\", exist_ok=True)\nos.makedirs(dataset + \"_noun/\", exist_ok=True)\nos.makedirs(dataset + \"_adj/\", exist_ok=True)\n\nfor root, dirs, files in os.walk(dataset, topdown=False):\n for file in files:\n with open(dataset + \"/\" + file) as f:\n doc = nlp(f.read())\n\n verb = open(dataset + \"_verb/\" + file, 'w')\n propn = open(dataset + \"_propn/\" + file, 'w')\n num = open(dataset + \"_num/\" + file, 'w')\n noun = open(dataset + \"_noun/\" + file, 'w')\n adj = open(dataset + \"_adj/\" + file, 'w')\n\n for token in doc:\n if token.pos_ == 'VERB':\n verb.write(token.lemma_ + '\\n')\n elif token.pos_ == 'PROPN':\n propn.write(token.lemma_ + '\\n')\n elif token.pos_ == 'NUM':\n num.write(token.lemma_ + '\\n')\n elif token.pos_ == 'NOUN':\n noun.write(token.lemma_ + '\\n')\n elif token.pos_ == 'ADJ':\n adj.write(token.lemma_ + '\\n')\n\n verb.close()\n propn.close()\n num.close()\n adj.close()\n noun.close()\n","sub_path":"spacy/get_pos_tags.py","file_name":"get_pos_tags.py","file_ext":"py","file_size_in_byte":1322,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"563606059","text":"import os\nfrom pathlib import Path\nimport uuid\n\nimport pytest\n\nTEST_EXEC_DIR = Path(__file__).parent.parent\n\n\n@pytest.fixture\ndef files(tmp_path):\n real_dir = tmp_path\n fake_file = tmp_path / \"fakefile\"\n real_file = tmp_path / \"realfile\"\n real_file.touch()\n\n return {\"real_dir\": real_dir, \"fake_file\": fake_file, \"real_file\": real_file}\n\n\n@pytest.fixture\ndef dirstructure(tmp_path, request):\n original_dir = Path.cwd()\n\n for f in request.param:\n f_path = tmp_path / Path(f)\n f_path.parent.mkdir(parents=True, exist_ok=True)\n f_path.touch()\n\n os.chdir(tmp_path)\n\n yield request.param\n\n os.chdir(original_dir.as_posix())\n\n\n@pytest.fixture\ndef current_dir(request):\n # save current directory\n original_dir = Path.cwd()\n requested_dir = Path(request.param)\n\n os.chdir(requested_dir.as_posix())\n\n yield\n\n # revert to original directory at teardown\n os.chdir(original_dir.as_posix())\n\n\n@pytest.fixture\ndef full_path(tmp_path, request):\n original_filepath = Path(request.param)\n return (TEST_EXEC_DIR / original_filepath).as_posix()\n\n\n@pytest.fixture\ndef file_from_content(tmp_path, request):\n new_file = tmp_path / \"file\"\n new_file.write_text(request.param)\n yield new_file\n new_file.unlink()\n\n\n@pytest.fixture\ndef make_file_from_contents(tmp_path):\n created_files = []\n\n def file_from_content(contents):\n new_file = tmp_path / str(uuid.uuid4())\n new_file.write_text(contents.strip())\n return new_file\n\n yield file_from_content\n\n for created_file in created_files:\n created_file.unlink()\n","sub_path":"tests/conftest.py","file_name":"conftest.py","file_ext":"py","file_size_in_byte":1612,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"185079262","text":"import pickle\n\nfrom revscoring.datasources import revision_oriented\nfrom revscoring.dependencies import solve\nfrom revscoring.languages import finnish\n\nfrom .util import compare_extraction\n\nBAD = [\n \"homo\", \"homoja\", \"homot\",\n \"hintti\",\n \"homppeli\",\n \"huora\",\n \"idiootti\",\n \"jumalauta\",\n \"juntti\",\n \"kakka\", \"kakkaa\",\n \"kikkeli\",\n \"kyrpä\",\n \"kulli\",\n \"kusi\", \"kusipää\",\n \"läski\",\n \"mamu\",\n \"matu\",\n \"neekeri\",\n \"nussii\",\n \"narttu\",\n \"paska\", \"paskaa\", \"paskat\", \"paskin\", \"paskova\",\n \"pelle\",\n \"perse\", \"perseeseen\", \"perseessä\", \"perseestä\", \"perseenreikä\",\n \"perkele\",\n \"pillu\", \"pilluun\",\n \"pippeli\",\n \"pieru\",\n \"retardi\",\n \"runkkari\",\n \"saatana\", \"saatanan\",\n \"tyhmä\",\n \"vammane\", \"vammanen\",\n \"vittu\",\n \"vitun\",\n \"äpärä\"\n]\n\nINFORMAL = [\n \"haistakaa\",\n \"imekää\",\n \"lol\",\n \"ootte\",\n \"moi\",\n \"hei\",\n \"sinä\",\n \"sä\",\n \"minä\",\n \"mää\",\n \"ok\",\n \"joo\",\n \"okei\"\n]\n\nOTHER = [\n \"\"\"\n Gunnar Nordström (12. maaliskuuta 1881 Helsinki – 24. joulukuuta 1923\n Helsinki) oli suomalainen fyysikko ja avaruustähtitieteilijä. Hänet\n tunnetaan erityisesti painovoimateoriastaan, joka oli yleistä\n suhteellisuusteoriaa edeltävä kilpaileva teoria. Nordström on saanut\n melko paljon huomiota ulkomailla, mutta kotimaassaan hän on melko\n tuntematon henkilö.\n \"\"\"\n]\n\nr_text = revision_oriented.revision.text\n\n\ndef test_badwords():\n compare_extraction(finnish.badwords.revision.datasources.matches,\n BAD, OTHER)\n\n assert finnish.badwords == pickle.loads(pickle.dumps(finnish.badwords))\n\n\ndef test_informals():\n compare_extraction(finnish.informals.revision.datasources.matches,\n INFORMAL, OTHER)\n\n assert finnish.informals == pickle.loads(pickle.dumps(finnish.informals))\n\n\ndef test_stopwords():\n cache = {revision_oriented.revision.text: \"Nordström on ette melko \" +\n \"paljon huomiota\"}\n assert (solve(finnish.stopwords.revision.datasources.stopwords,\n cache=cache) == [\"on\", \"ette\"])\n assert (solve(finnish.stopwords.revision.datasources.non_stopwords,\n cache=cache) == ['Nordström', 'melko', 'paljon', 'huomiota'])\n\n assert finnish.stopwords == pickle.loads(pickle.dumps(finnish.stopwords))\n","sub_path":"tests/languages/test_finnish.py","file_name":"test_finnish.py","file_ext":"py","file_size_in_byte":2399,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"125559887","text":"from sklearn.cluster import KMeans\nimport numpy as np\nimport csv\n\nNUM_OF_CLUSTERS=100\n\n# important columns to consider: 7, 12, 17\n\n# Numeric colums to take into consideration are the following: 7 to 20 (both inclusive)\n\nSTART_NUMERIC_INDEX=7\nEND_NUMERIC_INDEX=20\n\ncolumns=[7, 12, 17]\n\nclass UpperLevelClustering:\n\n def __init__(self):\n self.movies={}\n self.labels={}\n for i in range(NUM_OF_CLUSTERS):\n self.labels[i]=[]\n\n def openFile(self, fileName):\n \n csvFile=open(fileName, newline=\"\")\n reader=csv.reader(csvFile)\n return reader\n\n def openWriterFile(self, fileName):\n \n csvFile=open(fileName,'w',newline=\"\")\n writer=csv.writer(csvFile)\n return writer\n\n def initializeIterator(self, csvFileObject):\n return csv.reader(csvFileObject)\n\n def stringToList(self, s): # this is a hack: avoid as far as possible\n \n s=s.strip('[')\n s=s.strip(']')\n # print(s)\n s=s.strip(\"'\")\n # print(s)\n return s.split(\"', '\")\n\n def makeDocuments(self, mainFileMovieList, movieId):\n # count=0\n movie=mainFileMovieList[movieId+1]\n self.movies[movieId]=[]\n # for index in range(START_NUMERIC_INDEX,END_NUMERIC_INDEX+1):\n for index in columns:\n try:\n numericVal=float(movie[index])\n except Exception:\n numericVal=0.0\n self.movies[movieId].append(numericVal)\n # print (self.movies[movieId])\n \n def initializeLabels(self):\n self.labels.clear()\n for i in range(NUM_OF_CLUSTERS):\n self.labels[i]=[]\n\n def initializeMovies(self):\n self.movies.clear()\n\n def makeClustersAndWriteToFile(self, clusterCSVReader, mainFileCSVReader, finalClusterWriter):\n\n writer=finalClusterWriter\n clusterNum=0\n mainFileMovieList=list(mainFileCSVReader)\n for row in clusterCSVReader:\n print(\"reading cluster:\"+str(clusterNum))\n clusterNum+=1\n # print(row)\n if len(row)>NUM_OF_CLUSTERS:\n for id in row:\n self.makeDocuments(mainFileMovieList, int(id))\n # print(self.movies)\n movieList=[]\n for key in self.movies:\n movieList.append(self.movies[key])\n movieList=np.array(movieList)\n kmeans=KMeans(n_clusters=NUM_OF_CLUSTERS).fit(movieList)\n predictedLabels=kmeans.predict(movieList)\n print(\"length of predicted Labels: \"+str(len(predictedLabels)))\n print (predictedLabels)\n # count=0\n movieIterator=iter(self.movies)\n for i in predictedLabels:\n # count here are the ids of the corresponding movies\n movieId=next(movieIterator)\n self.labels[i].append(movieId)\n # count+=1\n nonNumericCluster=[]\n for key in self.labels:\n nonNumericCluster.append(self.labels[key])\n writer.writerow(nonNumericCluster)\n # freeing memory\n del nonNumericCluster\n self.initializeLabels()\n self.initializeMovies()\n # self.labels.clear()\n # self.movies.clear()\n del movieList\n else:\n writer.writerow(row)\n del mainFileMovieList\n \n\ndef main():\n obj=UpperLevelClustering()\n clusterCSVReader=obj.openFile(\"LabelsClusters200NoIdfOp2ActorDirectorNoCountry.csv\")\n mainFileCSVReader=obj.openFile(\"../MovieLens/ResultMovieDataSet.csv\")\n finalClusterWriter=obj.openWriterFile(\"LabelsNumreicClusters100Op1.csv\")\n print(\"making clusters and writing to file\")\n obj.makeClustersAndWriteToFile(clusterCSVReader, mainFileCSVReader, finalClusterWriter)\n\nif __name__==\"__main__\":\n main()","sub_path":"src/NonNumericClustering/UpperLevelClustering.py","file_name":"UpperLevelClustering.py","file_ext":"py","file_size_in_byte":4009,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"49489506","text":"from django.contrib import messages\nfrom django.contrib.auth.models import User\nfrom django.shortcuts import get_object_or_404, redirect, render\nfrom django.utils.translation import ugettext_lazy as _\n\nfrom c3nav.editor.models import ChangeSet\nfrom c3nav.editor.views.base import sidebar_view\n\n\n@sidebar_view\ndef user_detail(request, pk):\n user = request.user\n if str(pk) != str(user.pk):\n user = get_object_or_404(User, pk=pk)\n\n if request.method == 'POST':\n if request.user == user:\n if 'changeset' in request.session and request.POST.get('deactivate_changeset') == '1':\n request.session.pop('changeset', None)\n messages.success(request, _('You deactivated your current changeset.'))\n return redirect(request.path)\n\n if request.changeset.pk is None and ChangeSet.can_direct_edit(request):\n if request.POST.get('direct_editing') == '1':\n request.session['direct_editing'] = True\n messages.success(request, _('You activated direct editing.'))\n return redirect(request.path)\n elif request.POST.get('direct_editing') == '0':\n request.session.pop('direct_editing', None)\n messages.success(request, _('You deactivated direct editing.'))\n return redirect(request.path)\n\n ctx = {\n 'user': user,\n 'can_direct_edit': ChangeSet.can_direct_edit(request),\n 'recent_changesets': ChangeSet.objects.filter(author=user).order_by('-last_update')[:10],\n }\n\n return render(request, 'editor/user.html', ctx)\n","sub_path":"src/c3nav/editor/views/users.py","file_name":"users.py","file_ext":"py","file_size_in_byte":1653,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"601570468","text":"# coding=utf-8\nfrom DbClass import sqliteClass\nimport json\nimport requests\nimport datetime\nimport time\nimport pandas\n\ndb = sqliteClass('/home/pi/Desktop/Project/IndoorDb.db')\n\n# db = sqliteClass('IndoorDb.db')\n\n# reference value (50µg/m3)\npmReference = 50\n# reference value (200µg/m3)\nno2Reference = 200\n# reference value (120µg/m3)\no3Reference = 120\n\n\ndef readData():\n dataDF = db.select('sensors_data', '*, MAX(data_date) AS collectDate',\n where='data_used=0',\n groupBy='data_sensor_name',\n orderBy='collectDate DESC ')\n return dataDF\n\n\ndef validationData(data):\n if len(data) == 4:\n current_time = datetime.datetime.now()\n\n pm10Time = datetime.datetime.strptime(\n data.loc[data['data_sensor_name'] == 'PM10']['data_date'].astype(str).values[0],\n \"%Y-%m-%d %H:%M:%S\")\n no2Time = datetime.datetime.strptime(data.loc[data['data_sensor_name'] == 'NO2']['data_date'].astype(str).values[0],\n \"%Y-%m-%d %H:%M:%S\")\n o3Time = datetime.datetime.strptime(data.loc[data['data_sensor_name'] == 'O3']['data_date'].astype(str).values[0],\n \"%Y-%m-%d %H:%M:%S\")\n\n minTime = min([pm10Time, no2Time, o3Time])\n maxTime = max([pm10Time, no2Time, o3Time])\n diffMaxMin = (maxTime - minTime).seconds / 60\n\n # TODO : discuss with guys to choose how much time between the collected data are acceptable\n # TODO : how many minute is acceptable after the data is collected ?\n if diffMaxMin < 3:\n diffMinCur = (minTime - current_time).seconds / 60\n if diffMinCur < 5000:\n return 'OK', minTime\n else:\n return 'The last received data are old'\n else:\n return 'Time between collected data from sensors are too much'\n\n else:\n return 'There is no data', ''\n\n\ndef calculation(data, sensorDate):\n # Temp and Humidity\n dhtJson = json.loads(data.loc[data['data_sensor_name'] == 'DHT222']['data_sensor_json'].astype(str).values[0])\n temp = dhtJson['temperature']\n humi = dhtJson['humidity']\n\n # real value collected from sensors\n pmJson = json.loads(data.loc[data['data_sensor_name'] == 'PM10']['data_sensor_json'].astype(str).values[0])\n pm10Value = pmJson['pm10']\n pm25Value = pmJson['pm25']\n no2Value = json.loads(data.loc[data['data_sensor_name'] == 'NO2']['data_sensor_json'].astype(str).values[0])['no2']\n o3Value = json.loads(data.loc[data['data_sensor_name'] == 'O3']['data_sensor_json'].astype(str).values[0])['o3']\n\n sensorsData = {'pm10': pm10Value, 'pm25': pm25Value, 'no2': no2Value, 'o3': o3Value, 'temp': temp, 'hum': humi}\n sensorsDataJson = json.dumps(sensorsData)\n\n # normalise value\n pm = int((pm10Value / float(pmReference)) * 100)\n no2 = int((no2Value / float(no2Reference)) * 100)\n o3 = int((o3Value / float(o3Reference)) * 100)\n\n # TODO : we have just 4 type of avatar but here we have 5 cases ???????\n # IPQA value and AIR Quality status\n ipqaValue = max(pm, no2, o3)\n\n if ipqaValue <= 0:\n raise KeyError(\"* PROBLEM CALCULATING IPQA *\")\n elif ipqaValue > 0 and ipqaValue <= 50:\n ipqaStatus = \"Ottima\"\n elif ipqaValue > 50 and ipqaValue <= 70:\n ipqaStatus = \"Buona\"\n elif ipqaValue > 70 and ipqaValue <= 100:\n ipqaStatus = \"Accettabile\"\n elif ipqaValue > 100 and ipqaValue <= 200:\n ipqaStatus = \"Cattiva\"\n else:\n ipqaStatus = \"Pessima\"\n print ('APQI value is equal to: ', ipqaValue, ' and the status is: ', ipqaStatus, ' (at: ', sensorDate, \")\")\n\n cResult = db.insert(\"apqi_data\",\n \"apqi_value,apqi_status,sensor_json,date_sensors\",\n str(ipqaValue) + \",'\" +\n str(ipqaStatus) + \"','\" +\n str(sensorsDataJson) + \"','\" +\n str(sensorDate) + \"'\")\n if cResult == 0:\n dResponse = db.update('sensors_data', 'data_used=1')\n if dResponse == 0:\n return 'status=ok'\n else:\n return 'error in updating status of data'\n else:\n return 'status=error in inserting data'\n\n\ndef cleanDb():\n now = datetime.datetime.now()\n if now.hour == 0 and now.minute == 0:\n two_days = now - datetime.timedelta(days=7)\n rowcount = db.delete('sensors_data', 'data_date < \\'' + str(two_days) + '\\'')\n print(str(rowcount), ' Rows are deleted.')\n\n\nif '__main__' == __name__:\n while True:\n get_time = datetime.datetime.now()\n current_time = get_time.strftime(\"%Y-%m-%d %H:%M:%S\")\n print(\"***IPQA Calculation*******************************************\" + current_time)\n cleanDb()\n data = readData()\n cVal, sensorDate = validationData(data)\n if cVal == 'OK':\n cResponse = calculation(data, sensorDate=sensorDate)\n if cResponse == 'status=ok':\n print('Data was inserted and table was updated successfully ')\n else:\n print(cResponse)\n else:\n print (cVal)\n time.sleep(10)\n","sub_path":"IndoorPi/ipqaCalculation.py","file_name":"ipqaCalculation.py","file_ext":"py","file_size_in_byte":5220,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"10742797","text":"# N번째 큰 수 구하기\n# 배열 A가 주어졌을 때, N번째 큰 수\n# 배열 크기는 항상 10, N은 항상 3이다\n# 배열 A에서 3번째 큰 값 출력\nimport sys\n\nn = int(input())\nfor i in range(n):\n arr = list(map(int,sys.stdin.readline().split()))\n arr.sort()\n print(arr[-3])","sub_path":"Baekjoon/2693.py","file_name":"2693.py","file_ext":"py","file_size_in_byte":301,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"118820572","text":"from django.urls import path\nfrom . import views\n\napp_name = 'account'\nurlpatterns = [\n path('sign_up/', views.sign_up, name='sign_up'),\n path('', views.sign_in, name='sign_in'),\n path('sign_out/', views.sign_out, name='sign_out'),\n path('edit/', views.edit, name='edit'),\n path('user_home/', views.user_home, name='user_home'),\n path('user_info/', views.user_info, name='user_info'),\n path('user_edit/', views.edit, name='edit'),\n path('schedule/', views.set_schedule, name='set_schedule'),\n]\n","sub_path":"account/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":570,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"418970644","text":"#!/usr/bin/env python\n# (C) 2017 OpenEye Scientific Software Inc. All rights reserved.\n#\n# TERMS FOR USE OF SAMPLE CODE The software below (\"Sample Code\") is\n# provided to current licensees or subscribers of OpenEye products or\n# SaaS offerings (each a \"Customer\").\n# Customer is hereby permitted to use, copy, and modify the Sample Code,\n# subject to these terms. OpenEye claims no rights to Customer's\n# modifications. Modification of Sample Code is at Customer's sole and\n# exclusive risk. Sample Code may require Customer to have a then\n# current license or subscription to the applicable OpenEye offering.\n# THE SAMPLE CODE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,\n# EXPRESS OR IMPLIED. OPENEYE DISCLAIMS ALL WARRANTIES, INCLUDING, BUT\n# NOT LIMITED TO, WARRANTIES OF MERCHANTABILITY, FITNESS FOR A\n# PARTICULAR PURPOSE AND NONINFRINGEMENT. In no event shall OpenEye be\n# liable for any damages or liability in connection with the Sample Code\n# or its use.\n\nfrom __future__ import print_function\n\nfrom openeye import oechem\nfrom openeye import oeshape\n\n\ndef oneConf(conf, prep, filename, csvfile):\n csvfile.write(\"%s_%d\" % (conf.GetTitle(), conf.GetIdx()))\n refmol = oechem.OEGraphMol(conf)\n\n options = oeshape.OEOverlayOptions()\n options.SetOverlapFunc(oeshape.OEGridShapeFunc())\n overlay = oeshape.OEOverlay(options)\n overlay.SetupRef(refmol)\n\n bfs = oechem.oemolistream(filename)\n fitmol = oechem.OEMol()\n while oechem.OEReadMolecule(bfs, fitmol):\n prep.Prep(fitmol)\n scoreiter = oeshape.OEBestOverlayScoreIter()\n oeshape.OESortOverlayScores(scoreiter, overlay.Overlay(fitmol), oeshape.OEHighestTanimoto(), 1, True)\n\n for score in scoreiter:\n csvfile.write(\",%.2f\" % score.GetTanimoto())\n csvfile.write(\"\\n\")\n\n\ndef genHeader(filename, csvfile):\n csvfile.write(\"name\")\n ifs = oechem.oemolistream(filename)\n mol = oechem.OEMol()\n while oechem.OEReadMolecule(ifs, mol):\n for conf in mol.GetConfs():\n csvfile.write(\",%s_%d\" % (conf.GetTitle(), conf.GetIdx()))\n csvfile.write(\"\\n\")\n\n\ndef main(argv=[__name__]):\n if len(argv) != 3:\n oechem.OEThrow.Usage(\"%s \" % argv[0])\n\n csvfile = open(argv[2], \"w\")\n genHeader(sys.argv[1], csvfile)\n\n prep = oeshape.OEOverlapPrep()\n prep.SetAssignColor(False)\n afs = oechem.oemolistream(argv[1])\n for molA in afs.GetOEMols():\n prep.Prep(molA)\n print(molA.GetTitle())\n for conf in molA.GetConfs():\n oneConf(conf, prep, sys.argv[1], csvfile)\n\n\nif __name__ == \"__main__\":\n import sys\n sys.exit(main(sys.argv))\n","sub_path":"venv/Lib/site-packages/openeye/examples/shape/nxnshape.py","file_name":"nxnshape.py","file_ext":"py","file_size_in_byte":2642,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"640132912","text":"import json\nfrom web3 import Web3, TestRPCProvider, HTTPProvider\nfrom web3.middleware import geth_poa_middleware\n\nwith open('/Users/ccbn/w/CryptoAIData/backend/contract/owner_contract_abi.json', 'r') as abi_definition:\n abi = json.load(abi_definition)\n\nw3 = Web3(HTTPProvider('https://rinkeby.infura.io/SKMV9xjeMbG3u7MnJHVH'))\nw3.middleware_stack.inject(geth_poa_middleware, layer=0)\n\ncontract_checksum = w3.toChecksumAddress('0x90547E8aF843ff08397e345a770ba5239Ea6cde8')\ncontract = w3.eth.contract(address=contract_checksum, abi=abi)\n\nprint(contract.functions.ethBalance().call())\nprint(contract.functions.size().call())\n\n# current_supply = contract.functions.reward().call()\n\n","sub_path":"backend/contract/transferETHToTokenHolder.py","file_name":"transferETHToTokenHolder.py","file_ext":"py","file_size_in_byte":681,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"205955579","text":"\nimport torch.nn as nn\nimport math\nimport torch.nn.functional as F\nfrom nested_dict import nested_dict\nfrom collections import OrderedDict\nfrom torch.autograd import Variable\n__all__=['resnet16_2','resnet16_8','resnet16_16']\ndef conv3x3(in_planes, out_planes, stride=1):\n \"3x3 convolution with padding\"\n return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride,\n padding=1, bias=False)\n\n\nclass BasicBlock(nn.Module):\n expansion = 1\n\n def __init__(self, inplanes, planes, stride=1, downsample=None):\n super(BasicBlock, self).__init__()\n self.conv1 = conv3x3(inplanes, planes, stride)\n self.bn1 = nn.BatchNorm2d(planes)\n self.relu = nn.ReLU(inplace=True)\n self.conv2 = conv3x3(planes, planes)\n self.bn2 = nn.BatchNorm2d(planes)\n self.downsample = downsample\n self.stride = stride\n\n def forward(self, x):\n residual = x\n\n out = self.conv1(x)\n out = self.bn1(out)\n out = self.relu(out)\n\n out = self.conv2(out)\n out = self.bn2(out)\n\n if self.downsample is not None:\n residual = self.downsample(x)\n\n out += residual\n out = self.relu(out)\n\n return out\n\n\nclass ResNet(nn.Module):\n\n def __init__(self, block, k=1,n=2,num_classes=10):\n self.inplanes = 16\n super(ResNet, self).__init__()\n self.conv1 = nn.Conv2d(3, 16, kernel_size=3, stride=1, padding=1,\n bias=False)\n self.bn1 = nn.BatchNorm2d(16)\n self.relu = nn.ReLU(inplace=True)\n \n self.layer1 = self._make_layer(block, 16*k, n)\n self.layer2 = self._make_layer(block, 32*k, n, stride=2)\n self.layer3 = self._make_layer(block, 64*k, n, stride=2)\n self.avgpool = nn.AvgPool2d(8)\n self.fc = nn.Linear(64*k, num_classes)\n\n for m in self.modules():\n if isinstance(m, nn.Conv2d):\n n = m.kernel_size[0] * m.kernel_size[1] * m.out_channels\n m.weight.data.normal_(0, math.sqrt(2. / n))\n elif isinstance(m, nn.BatchNorm2d):\n m.weight.data.fill_(1)\n m.bias.data.zero_()\n\n def _make_layer(self, block, planes, blocks, stride=1):\n downsample = None\n if stride != 1 or self.inplanes != planes * block.expansion:\n downsample = nn.Sequential(\n nn.Conv2d(self.inplanes, planes * block.expansion,\n kernel_size=1, stride=stride, bias=False),\n nn.BatchNorm2d(planes * block.expansion),\n )\n\n layers = []\n layers.append(block(self.inplanes, planes, stride, downsample))\n self.inplanes = planes * block.expansion\n for i in range(1, blocks):\n layers.append(block(self.inplanes, planes))\n\n return nn.Sequential(*layers)\n\n def forward(self, x):\n x = self.conv1(x)\n x = self.bn1(x)\n x = self.relu(x)\n \n x = self.layer1(x)\n x = self.layer2(x)\n x = self.layer3(x)\n x = self.avgpool(x)\n x = x.view(x.size(0), -1)\n\n x = self.fc(x)\n return x\n\ndef state_dict(module, destination=None, prefix=''):\n if destination is None:\n destination = OrderedDict()\n for name, param in module._parameters.items():\n if param is not None:\n destination[prefix + name] = param\n for name, buf in module._buffers.items():\n if buf is not None:\n destination[prefix + name] = buf\n for name, module in module._modules.items():\n if module is not None:\n state_dict(module, destination, prefix + name + '.')\n return destination\n\n\nfrom torch.nn import Parameter\ndef params_stats(mod):\n params = OrderedDict()\n stats = OrderedDict()\n for k, v in state_dict(mod).iteritems():\n if isinstance(v, Variable):\n params[k] = v\n else:\n stats[k] = v\n return params,stats\ndef resnet16_16():\n return resnet16(2,16) \ndef resnet16_8():\n return resnet16(2,8) \ndef resnet16_2():\n return resnet16(2,2) \n\ndef resnet16(n,k):\n \"\"\"Constructs a Wide ResNet-16 model.\n \"\"\"\n model = ResNet(BasicBlock,k,n,num_classes=10)\n \n model=model.cuda()\n params,stats=params_stats(model)\n\n return model, params, stats","sub_path":"models/scatter/WRN.py","file_name":"WRN.py","file_ext":"py","file_size_in_byte":4328,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"477405123","text":"# -*- coding: utf-8 -*-\n\"\"\"MyProblem.py\"\"\"\nimport numpy as np\nimport geatpy as ea\nimport matplotlib.pyplot as plt\nimport numpy as np\nfrom sklearn.model_selection import train_test_split\nimport p_decisiontree\n\n\nclass MyProblem(ea.Problem): # 继承Problem父类\n def __init__(self):\n name = 'MyProblem' # 初始化name(函数名称,可以随意设置)\n M = 1 # 初始化M(目标维数)\n maxormins = [1] # 初始化maxormins(目标最小最大化标记列表,1:最小化该目标;-1:最大化该目标)\n Dim = 6 # 初始化Dim(决策变量维数)\n\n # 初始化varTypes(决策变量的类型,元素为0表示对应的变量是连续的;1表示是离散的)\n varTypes = [1, 1, 1, 0, 0, 0]\n lb = [1, 0, 0, 0, 0, 0] # 决策变量下界\n ub = [50, 50, 19, 0.5, 1, 0.5] # 决策变量上界\n lbin = [0, 0, 0, 0, 0, 1] # 决策变量下边界(0表示不包含该变量的下边界,1表示包含)\n ubin = [1]*Dim # 决策变量上边界(0表示不包含该变量的上边界,1表示包含)\n\n # 调用父类构造方法完成实例化\n ea.Problem.__init__(self, name, M, maxormins, Dim,\n varTypes, lb, ub, lbin, ubin)\n self.data_dict = p_decisiontree.DataDict()\n\n def aimFunc(self, pop): # 目标函数\n Vars = pop.Phen # 得到决策变量矩阵\n max_leaf_nodes = Vars[:, [0]]\n max_depth = Vars[:, [1]]\n max_features = Vars[:, [2]]\n min_samples_leaf = Vars[:, [3]]\n min_samples_split = Vars[:, [4]]\n min_weight_fraction_leaf = Vars[:, [5]]\n\n objvs = []\n models = []\n best_index = 0\n best_params = {'max_depth': max_depth, 'min_samples_leaf': min_samples_leaf, 'min_samples_split': min_samples_split,\n 'max_features': max_features, 'max_leaf_nodes': max_leaf_nodes, 'min_weight_fraction_leaf': min_weight_fraction_leaf}\n for i in range(0, max_depth.shape[0]):\n params = {'data_dict': self.data_dict, 'max_depth': int(max_depth[i, 0]),\n 'min_samples_leaf': min_samples_leaf[i, 0], 'min_samples_split': min_samples_split[i, 0],\n 'max_features': int(max_features[i, 0]), 'max_leaf_nodes': int(max_leaf_nodes[i, 0]), 'min_weight_fraction_leaf': min_weight_fraction_leaf[i, 0]}\n print(params)\n objv = p_decisiontree.train(**params)\n objvs.append(objv)\n print(Vars[0, :])\n\n pop.ObjV = np.array([objvs]).T\n","sub_path":"model2021/two/p_tree/MyProblem.py","file_name":"MyProblem.py","file_ext":"py","file_size_in_byte":2577,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"101068971","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Wed Mar 8 20:53:33 2017\r\n\r\n@author: Ami\r\n\"\"\"\r\n\r\n#TweepyJSONReader.py\r\n##Reads JSON files of tweets that Tweepy collects\r\n#Gates\r\n\r\n##This program will read a .txt file\r\n## that was created by TwitterMining.py\r\n## Set the filename correctly\r\n\r\n## This program will create two files:\r\n## \"TwitterResultsRaw.txt\" which is all the words\r\n## \"TwitterWordFrq.txt\" which is each word and its frequency\r\n\r\n\r\nimport json\r\nfrom nltk.tokenize import word_tokenize\r\nfrom nltk.tokenize import TweetTokenizer\r\nimport re\r\n#https://docs.python.org/3/library/re.html\r\n\r\nlinecount=0\r\nhashcount=0\r\nwordcount=0\r\nBagOfWords=[]\r\nBagOfHashes=[]\r\nBagOfLinks=[]\r\n\r\n### SET THE FILE NAME ###\r\n\r\ntweetsfile=\"file_BookLoversDay.txt\"\r\n\r\n###################################\r\n\r\nwith open(tweetsfile, 'r') as file:\r\n for line in file:\r\n #print(line,\"\\n\")\r\n tweetSplitter = TweetTokenizer(strip_handles=True, reduce_len=True)\r\n WordList=tweetSplitter.tokenize(line)\r\n #WordList2=word_tokenize(line)\r\n #linecount=linecount+1\r\n #print(WordList)\r\n #print(len(WordList))\r\n #print(WordList[0])\r\n #print(WordList2)\r\n #print(len(WordList2))\r\n #print(WordList2[3:6])\r\n #print(\"NEXT..........\\n\")\r\n regex1=re.compile('^#.+')\r\n regex2=re.compile('[^\\W\\d]') #no numbers\r\n regex3=re.compile('^http*')\r\n regex4=re.compile('.+\\..+')\r\n for item in WordList:\r\n if(len(item)>2):\r\n if((re.match(regex1,item))):\r\n #print(item)\r\n newitem=item[1:] #remove the hash\r\n BagOfHashes.append(newitem)\r\n hashcount=hashcount+1\r\n elif(re.match(regex2,item)):\r\n if(re.match(regex3,item) or re.match(regex4,item)):\r\n BagOfLinks.append(item)\r\n else:\r\n BagOfWords.append(item)\r\n wordcount=wordcount+1\r\n else:\r\n pass\r\n else:\r\n pass\r\n \r\n \r\n \r\n \r\n#print(linecount) \r\n#print(BagOfWords)\r\n#print(BagOfHashes)\r\n#print(BagOfLinks)\r\nBigBag=BagOfWords+BagOfHashes\r\n\r\n\r\n\r\n\r\n#list of words I have seen\r\nseenit=[]\r\n#dict of word counts\r\nWordDict={}\r\nRawfilename=\"TwitterResultsRaw.txt\"\r\nFreqfilename=\"TwitterWordFrq.txt\"\r\n\r\n\r\n#FILE=open(Freqfilename,\"w\")\r\n#FILE2=open(Rawfilename, \"w\")\r\nR_FILE=open(Rawfilename,\"w\")\r\nF_FILE=open(Freqfilename, \"w\")\r\n\r\nIgnoreThese=[\"and\", \"And\", \"AND\",\"THIS\", \"This\", \"this\", \"for\", \"FOR\", \"For\", \r\n \"THE\", \"The\", \"the\", \"is\", \"IS\", \"Is\", \"or\", \"OR\", \"Or\", \"will\", \r\n \"Will\", \"WILL\", \"God\", \"god\", \"GOD\", \"Bible\", \"bible\", \"BIBLE\",\r\n \"CanChew\", \"Download\", \"free\", \"FREE\", \"Free\", \"will\", \"WILL\", \r\n \"Will\", \"hits\", \"hit\", \"within\", \"steam\", \"Via\", \"via\", \"know\", \"Study\",\r\n \"study\", \"unit\", \"Unit\", \"always\", \"take\", \"Take\", \"left\", \"Left\",\r\n \"lot\",\"robot\", \"Robot\", \"Lot\", \"last\", \"Last\", \"Wonder\", \"still\", \"Still\",\r\n \"ferocious\", \"Need\", \"need\", \"food\", \"Food\", \"Flint\", \"MachineCredit\",\r\n \"Webchat\", \"luxury\", \"full\", \"fifdh17\", \"New\", \"new\", \"Caroline\",\r\n \"Tirana\", \"Shuayb\", \"repro\", \"attempted\", \"key\", \"Harrient\", \r\n \"Chavez\", \"Women\", \"women\", \"Mumsnet\", \"Ali\", \"Tubman\", \"girl\",\"Girl\",\r\n \"CSW61\", \"IWD2017\", \"Harriet\", \"Great\", \"great\", \"single\", \"Single\", \r\n \"tailoring\", \"ask\", \"Ask\"]\r\n###Look at the words\r\nfor w in BigBag:\r\n if(w not in IgnoreThese):\r\n rawWord=w+\" \"\r\n R_FILE.write(rawWord)\r\n if(w in seenit):\r\n #print(w, seenit)\r\n WordDict[w]=WordDict[w]+1 #increment the times word is seen\r\n else:\r\n ##add word to dict and seenit\r\n seenit.append(w)\r\n WordDict[w]=1\r\n \r\n#print(WordDict) \r\n#print(seenit)\r\n#print(BagOfWords)\r\n\r\n\r\n\r\nfor key in WordDict:\r\n #print(WordDict[key])\r\n if(WordDict[key]>1):\r\n if(key not in IgnoreThese):\r\n #print(key)\r\n Key_Value=key + \",\" + str(WordDict[key]) + \"\\n\"\r\n F_FILE.write(Key_Value)\r\n\r\n\r\n#FILE.close()\r\n#FILE2.close()\r\nR_FILE.close()\r\nF_FILE.close()\r\n","sub_path":"weekfour/TweepyJSONReader.py","file_name":"TweepyJSONReader.py","file_ext":"py","file_size_in_byte":4322,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"588732520","text":"import requests\nimport pprint as p\n\n# a scraper that gets random cat facts from an api\n\nurl = \"https://catfact.ninja/fact\"\n\nresponse = requests.get(url)\n\n\n\ndata = {\n \"status_code\": response.status_code,\n \"content_type\": response.headers[\"Content-Type\"],\n \"cat_fact\": response.json()[\"fact\"],\n \"length_of_fact\": response.json()[\"length\"],\n \"date\": response.headers[\"Date\"],\n}\n\np.pprint(data)\n","sub_path":"Python/random_cat_facts.py","file_name":"random_cat_facts.py","file_ext":"py","file_size_in_byte":406,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"20239152","text":"from common.tools import *\nfrom base.config import RECORDER_PATH\nimport allure,string,random,yaml\npoco = AndroidUiautomationPoco(use_airtest_input=True, screenshot_each_action=False)\nauto_setup(__file__)\n\n\n\nwith open('%s/resourceid.yaml'%DATA_PATH) as f:\n yaml_data = yaml.load(f)\n\n@allure.feature('遍历APP设置模块')\nclass TestSeting:\n\n def setup(self) -> None:\n pass\n\n\n\n @allure.story('设置:青少年模式')\n @allure.title('设置:青少年模式')\n def test_01_setting(self):\n\n sleep(10)\n log.info('=======设置==========')\n stars_app()\n recorder().start_recording(max_time=1800)\n poco(text='我的').click()\n poco(yaml_data['avatar']).click()\n sim_code_login()\n poco(yaml_data['back']).click()\n poco(yaml_data['setting_teenager']).click()\n poco(yaml_data['kids_mode']).click()\n for i in range(2):\n for j in range(4):\n poco(yaml_data['edit_text_view']).click()\n text(\"0\")\n poco(yaml_data['password_next']).click()\n sleep(1)\n get_snapshot('青少年模式')\n poco(yaml_data['test_kids_mode_quit']).click()\n poco(yaml_data['kids_mode']).click()\n for i in range(1,5):\n poco(yaml_data['edit_text_view']).click()\n text(\"0\")\n recorder().stop_recording(output='%s青少年模式.mp4' % RECORDER_PATH)\n\n @allure.story('设置:黑名单')\n @allure.title('设置:黑名单')\n def test_02_setting(self):\n\n recorder().start_recording(max_time=1800)\n poco(text='我的').click()\n poco(yaml_data['back']).click()\n poco(yaml_data['setting_backlist']).click()\n sleep(1)\n get_snapshot('黑名单列表')\n if poco(yaml_data['remove']).exists():\n poco(yaml_data['remove']).click()\n poco(yaml_data['ok']).click()\n keyevent(\"KEYCODE_BACK\")\n else:\n log.debug('======黑名单空空如也======')\n keyevent(\"KEYCODE_BACK\")\n recorder().stop_recording(output='%s黑名单.mp4' % RECORDER_PATH)\n\n @allure.story('设置:我的钱包')\n @allure.title('设置:我的钱包')\n def test_03_setting(self):\n\n recorder().start_recording(max_time=1800)\n poco(yaml_data['setting_wallet']).click()\n poco(text='常见问题').click()\n sleep(1)\n get_snapshot('常见问题')\n keyevent(\"KEYCODE_BACK\")\n poco(text='立即提现').click()\n sleep(1)\n get_snapshot('立即提现')\n poco(text='账单').click()\n sleep(1)\n get_snapshot('账单')\n keyevent(\"KEYCODE_BACK\")\n keyevent(\"KEYCODE_BACK\")\n keyevent(\"KEYCODE_BACK\")\n recorder().stop_recording(output='%s我的钱包.mp4' % RECORDER_PATH)\n\n @allure.story('设置:检查更新')\n @allure.title('设置:检查更新')\n def test_04_setting(self):\n\n recorder().start_recording(max_time=1800)\n poco(yaml_data['setting_check_update']).click()\n sleep(1)\n get_snapshot('检查更新')\n recorder().stop_recording(output='%s检查更新.mp4' % RECORDER_PATH)\n\n @allure.story('设置:隐私协议')\n @allure.title('设置:隐私协议')\n def test_05_setting(self):\n\n recorder().start_recording(max_time=1800)\n poco(yaml_data['setting_privacy']).click()\n sleep(1)\n get_snapshot('隐私协议')\n keyevent(\"KEYCODE_BACK\")\n recorder().stop_recording(output='%s隐私协议.mp4' % RECORDER_PATH)\n\n @allure.story('设置:秒拍app声明')\n @allure.title('设置:秒拍app声明')\n def test_06_setting(self):\n\n recorder().start_recording(max_time=1800)\n poco(yaml_data['setting_app_statement']).click()\n sleep(1)\n get_snapshot('秒拍app声明')\n keyevent(\"KEYCODE_BACK\")\n recorder().stop_recording(output='%s秒拍app声明.mp4' % RECORDER_PATH)\n\n @allure.story('设置:意见反馈')\n @allure.title('设置:意见反馈')\n def test_07_setting(self):\n\n recorder().start_recording(max_time=1800)\n poco(yaml_data['setting_feedback']).click()\n sleep(1)\n value = ''.join(random.sample(string.digits + string.ascii_letters, 10))\n number = ''.join(random.sample(string.digits + string.digits, 11))\n poco(yaml_data['feedback_suggestion']).set_text(value)\n poco(yaml_data['feedback_phone']).set_text(number)\n sleep(1)\n get_snapshot('意见反馈内容')\n poco(yaml_data['feedback_submit']).click()\n get_snapshot('提交意见反馈')\n recorder().stop_recording(output='%s提交意见反馈.mp4' % RECORDER_PATH)\n\n @allure.story('设置:清除缓存')\n @allure.title('设置:清除缓存')\n def test_08_setting(self):\n\n recorder().start_recording(max_time=1800)\n poco(yaml_data['setting_clear_cache']).click()\n poco(yaml_data['ok']).click()\n sleep(1)\n get_snapshot('清除缓存')\n recorder().stop_recording(output='%s清除缓存.mp4' % RECORDER_PATH)\n\n @allure.story('设置:高级设置')\n @allure.title('设置:高级设置')\n def test_09_setting(self):\n\n recorder().start_recording(max_time=1800)\n poco(yaml_data['setting_additional_setting']).click()\n poco(yaml_data['setting_logoff']).click()\n sleep(1)\n get_snapshot('高级设置')\n keyevent(\"KEYCODE_BACK\")\n keyevent(\"KEYCODE_BACK\")\n recorder().stop_recording(output='%s高级设置.mp4' % RECORDER_PATH)\n\n @allure.story('设置:退出登录')\n @allure.title('设置:退出登录')\n def test_10_setting(self):\n\n recorder().start_recording(max_time=1800)\n poco(yaml_data['setting_login']).click()\n poco(yaml_data['ok']).click()\n sleep(1)\n get_snapshot('退出登录')\n value = poco(yaml_data['login']).attr('text')\n assert_equal(value, '登录/注册', msg='退出登录')\n recorder().stop_recording(output='%s退出登录.mp4' % RECORDER_PATH)\n\n def teardown(self) -> None:\n pass","sub_path":"testCase/AMP_setting.py","file_name":"AMP_setting.py","file_ext":"py","file_size_in_byte":6164,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"94424231","text":"import os\nimport sys\nimport consulate\nimport json\nimport boto3\nimport base64\n\nPYTHON3 = True if sys.version_info > (3, 0, 0) else False\n\nclass UnknownActionRequest(Exception):\n pass\n\ndef get_consul_session(host, port):\n return consulate.Consul(host=host, port=port)\n\ndef get_records_from_consul(session):\n return session.kv.records()\n\ndef consul_restore_from_backup(session, backup, force):\n handle = open(backup, 'r')\n data = json.load(handle)\n for row in data:\n if isinstance(row, dict):\n # translate raw api export to internal representation\n if row['Value'] is not None:\n row['Value'] = base64.b64decode(row['Value'])\n row = [row['Key'], row['Flags'], row['Value']]\n # Here's an awesome thing to make things work\n # source: https://github.com/gmr/consulate/blob/master/consulate/cli.py#L312\n if not PYTHON3 and isinstance(row[2], unicode):\n row[2] = row[2].encode('utf-8')\n session.kv.set_record(row[0], row[1], row[2], force)\n \ndef save_records(records, target):\n handle = open(target, 'w')\n handle.write(json.dumps(records) + '\\n')\n\ndef get_s3_resource():\n return boto3.resource('s3') \n\ndef s3_upload_file(s3_resource, backup_file, backup_bucket):\n\n s3_object = os.path.basename(backup_file)\n\n with open(backup_file, 'rb') as f:\n binary = f.read()\n\n s3_resource.Bucket(backup_bucket).put_object(\n Key=s3_object,\n Body=binary\n )\n\ndef s3_download_file(s3_resource, backup_file, backup_bucket):\n\n s3_object = os.path.basename(backup_file)\n\n body = s3_resource.Object(backup_bucket, s3_object).get()['Body']\n with open(backup_file, 'wb') as f:\n for chunk in iter(lambda: body.read(1024), b''):\n f.write(chunk)\n","sub_path":"utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":1800,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"621546017","text":"# -*- coding: UTF-8 -*-\n# @yasinkuyu\nimport config\nimport datetime\nimport pandas as pd\n\nfrom BinanceAPI import BinanceAPI\nfrom Messages import Messages\n\n# Define Custom import vars\nclient = BinanceAPI(config.api_key, config.api_secret)\n\n\nclass Orders:\n\n @staticmethod\n def has_enough_to_trade(symbol, buying=True, quantity=0):\n last_price = Orders.get_ticker(symbol)\n if quantity > 0:\n order_notional = quantity * last_price\n else:\n coin_balance, currency_balance = Orders.get_balance(symbol)\n if buying:\n order_notional = currency_balance\n else:\n order_notional = coin_balance * last_price\n min_notional = Orders.get_min_notional(symbol)\n return order_notional > min_notional\n\n @staticmethod\n def get_min_notional(symbol):\n data_frame = pd.DataFrame(client.get_exchange_info()['symbols']).set_index('symbol')\n data_frame = pd.DataFrame(data_frame.loc[symbol]['filters']).set_index('filterType')\n return data_frame.loc['MIN_NOTIONAL']['minNotional']\n\n @staticmethod\n def get_balance(symbol):\n coin_order, currency_order = client.get_balance(symbol)\n\n if 'msg' in coin_order:\n Messages.get(coin_order['msg'])\n if 'msg' in currency_order:\n Messages.get(currency_order['msg'])\n\n # Buy order created.\n return coin_order['free'], currency_order['free']\n\n @staticmethod\n def buy_limit(symbol, quantity, buy_price):\n order = client.buy_limit(symbol, quantity, buy_price)\n\n if 'msg' in order:\n Messages.get(order['msg'])\n\n # Buy order created.\n return order['orderId']\n\n @staticmethod\n def sell_limit(symbol, quantity, sell_price):\n\n order = client.sell_limit(symbol, quantity, sell_price)\n\n if 'msg' in order:\n Messages.get(order['msg'])\n\n return order\n\n @staticmethod\n def get_server_time():\n time = client.get_server_time()\n if 'msg' in time:\n Messages.get(time['msg'])\n return datetime.datetime.fromtimestamp(time['serverTime'] / 1000.0)\n\n @staticmethod\n def buy_market(symbol, quantity):\n\n order = client.buy_market(symbol, quantity)\n\n if 'msg' in order:\n Messages.get(order['msg'])\n\n return order\n\n @staticmethod\n def sell_market(symbol, quantity):\n\n order = client.sell_market(symbol, quantity)\n\n if 'msg' in order:\n Messages.get(order['msg'])\n\n return order\n\n @staticmethod\n def cancel_order(symbol, order_id):\n\n try:\n\n order = client.cancel(symbol, order_id)\n if 'msg' in order:\n Messages.get(order['msg'])\n\n print('Profit loss, called order, %s' % order_id)\n\n return True\n\n except Exception as e:\n print('co: %s' % e)\n return False\n\n @staticmethod\n def get_candle_sticks(symbol, interval):\n try:\n return client.get_kline(symbol, interval)\n except Exception as e:\n print('kl: %s' % e)\n return None\n\n @staticmethod\n def get_candle_sticks_limit(symbol, interval, start_time, end_time):\n try:\n return client.get_kline_limit(symbol, interval, start_time, end_time)\n except Exception as e:\n print('kl: %s' % e)\n return None\n\n @staticmethod\n def get_order_book(symbol):\n try:\n\n orders = client.get_order_books(symbol, 5)\n last_bid = float(orders['bids'][0][0]) # last buy price (bid)\n last_ask = float(orders['asks'][0][0]) # last sell price (ask)\n\n return last_bid, last_ask\n\n except Exception as e:\n print('ob: %s' % e)\n return 0, 0\n\n @staticmethod\n def get_order(symbol, order_id):\n try:\n\n order = client.query_order(symbol, order_id)\n\n if 'msg' in order:\n # Messages.get(order['msg']) - TODO\n return False\n\n return order\n\n except Exception as e:\n print('go: %s' % e)\n return False\n\n @staticmethod\n def get_order_status(symbol, order_id):\n try:\n\n order = client.query_order(symbol, order_id)\n\n if 'msg' in order:\n Messages.get(order['msg'])\n\n return order['status']\n\n except Exception as e:\n print('gos: %s' % e)\n return None\n\n @staticmethod\n def get_ticker(symbol):\n try:\n\n ticker = client.get_ticker(symbol)\n\n return float(ticker['lastPrice'])\n except Exception as e:\n print('gt: %s' % e)\n\n @staticmethod\n def get_info(symbol):\n try:\n info = client.get_exchange_info()\n if symbol != \"\":\n return [market for market in info['symbols'] if market['symbol'] == symbol][0]\n return info\n except Exception as e:\n print('gi: %s' % e)\n","sub_path":"app/Orders.py","file_name":"Orders.py","file_ext":"py","file_size_in_byte":5049,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"381551089","text":"import unittest\nimport sys, os, signal, time\nimport dude.execute as execute\n\ndef foo(optpt):\n return \"echo\"\n\noptpt = { 'hello' : 'world' }\n\ndef kill_spawned():\n p = execute.SpawnProcess(foo, optpt, sys.stdout, sys.stdin)\n p.start()\n #print \"started\"\n time.sleep(1)\n p.kill()\n #print \"killed\"\n p.poll()\n \n \nclass CoreTestCase(unittest.TestCase):\n def test_kill_spawned(self):\n kill_spawned()\n \nif __name__ == '__main__':\n kill_spawned()\n","sub_path":"test/test_kill.py","file_name":"test_kill.py","file_ext":"py","file_size_in_byte":490,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"529111354","text":"# -*- coding: utf-8 -*-\n\"\"\"\nTencentBlueKing is pleased to support the open source community by making 蓝鲸智云-权限中心(BlueKing-IAM) available.\nCopyright (C) 2017-2021 THL A29 Limited, a Tencent company. All rights reserved.\nLicensed under the MIT License (the \"License\"); you may not use this file except in compliance with the License.\nYou may obtain a copy of the License at http://opensource.org/licenses/MIT\nUnless required by applicable law or agreed to in writing, software distributed under the License is distributed on\nan \"AS IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the\nspecific language governing permissions and limitations under the License.\n\"\"\"\nimport json\nfrom typing import Dict, List, Union\n\nfrom django.db import models\nfrom django.utils.functional import cached_property\n\nfrom backend.common.models import BaseModel\nfrom backend.service.constants import RoleRelatedObjectType, RoleScopeType, RoleSourceTypeEnum, RoleType, SubjectType\nfrom backend.util.json import json_dumps\n\nfrom .constants import DEFAULT_ROLE_PERMISSIONS\nfrom .managers import RoleRelatedObjectManager, RoleUserManager\n\n\nclass Role(BaseModel):\n \"\"\"\n 角色\n \"\"\"\n\n name = models.CharField(\"名称\", max_length=128)\n name_en = models.CharField(\"英文名\", max_length=128, default=\"\")\n description = models.CharField(\"描述\", max_length=255, default=\"\")\n type = models.CharField(\"类型\", max_length=32, choices=RoleType.get_choices())\n code = models.CharField(\"标志\", max_length=64, default=\"\")\n\n class Meta:\n verbose_name = \"角色\"\n verbose_name_plural = \"角色\"\n ordering = [\"-id\"]\n\n @property\n def system_permission_enabled_content(self):\n enabled_content, _ = RoleUserSystemPermission.objects.get_or_create(role_id=self.id)\n return enabled_content\n\n @property\n def members(self):\n return list(RoleUser.objects.filter(role_id=self.id).values_list(\"username\", flat=True))\n\n @property\n def permissions(self):\n return DEFAULT_ROLE_PERMISSIONS[self.type]\n\n\nclass RoleUser(BaseModel):\n \"\"\"\n 角色的用户\n \"\"\"\n\n role_id = models.IntegerField(\"角色ID\")\n username = models.CharField(\"用户id\", max_length=64)\n\n objects = RoleUserManager()\n\n class Meta:\n verbose_name = \"角色的用户\"\n verbose_name_plural = \"角色的用户\"\n ordering = [\"id\"]\n index_together = [\"role_id\"]\n\n\nclass RoleUserSystemPermission(BaseModel):\n \"\"\"\n 角色里的用户是否拥有对应接入系统的超级权限\n \"\"\"\n\n role_id = models.IntegerField(\"角色ID\")\n content = models.TextField(\"限制内容\", default='{\"enabled_users\": [], \"global_enabled\": false}')\n\n @cached_property\n def enabled_detail(self) -> Dict[str, Union[List[str], bool]]:\n return json.loads(self.content)\n\n @property\n def enabled_users(self) -> List[str]:\n return self.enabled_detail[\"enabled_users\"]\n\n @property\n def global_enabled(self) -> bool:\n return self.enabled_detail[\"global_enabled\"]\n\n @classmethod\n def get_enabled_detail(cls, role_id: int):\n enabled_content, _ = cls.objects.get_or_create(role_id=role_id)\n enabled_detail = enabled_content.enabled_detail\n return enabled_detail\n\n @classmethod\n def update_global_enabled(cls, role_id: int, global_enabled: bool):\n enabled_detail = cls.get_enabled_detail(role_id)\n enabled_detail[\"global_enabled\"] = global_enabled\n cls.objects.filter(role_id=role_id).update(content=json_dumps(enabled_detail))\n\n @classmethod\n def add_enabled_users(cls, role_id: int, username: str):\n enabled_detail = cls.get_enabled_detail(role_id)\n enabled_detail[\"enabled_users\"].append(username)\n cls.objects.filter(role_id=role_id).update(content=json_dumps(enabled_detail))\n\n @classmethod\n def delete_enabled_users(cls, role_id: int, username: str):\n enabled_detail = cls.get_enabled_detail(role_id)\n enabled_detail[\"enabled_users\"].remove(username)\n cls.objects.filter(role_id=role_id).update(content=json_dumps(enabled_detail))\n\n\nclass Permission(models.Model):\n \"\"\"\n 权限\n \"\"\"\n\n name = models.CharField(\"名称\", max_length=64)\n name_en = models.CharField(\"英文名\", max_length=64, default=\"\")\n code = models.CharField(\"标志\", max_length=64)\n\n class Meta:\n verbose_name = \"权限\"\n verbose_name_plural = \"权限\"\n\n\nclass RolePerm(models.Model):\n \"\"\"\n 角色的权限\n \"\"\"\n\n role_id = models.IntegerField(\"角色ID\")\n perm_id = models.IntegerField(\"权限ID\")\n\n class Meta:\n verbose_name = \"角色的权限\"\n verbose_name_plural = \"角色的权限\"\n index_together = [\"role_id\"]\n\n\nclass RoleScope(models.Model):\n \"\"\"\n 角色的限制范围\n \"\"\"\n\n role_id = models.IntegerField(\"角色ID\")\n type = models.CharField(\"限制类型\", max_length=32, choices=RoleScopeType.get_choices())\n content = models.TextField(\"限制内容\")\n\n class Meta:\n verbose_name = \"角色的限制范围\"\n verbose_name_plural = \"角色的限制范围\"\n index_together = [\"role_id\"]\n\n\nclass ScopeSubject(models.Model):\n \"\"\"\n subject的限制冗余\n \"\"\"\n\n role_scope_id = models.IntegerField(\"角色限制ID\")\n role_id = models.IntegerField(\"角色ID\")\n subject_type = models.CharField(\"授权对象类型\", max_length=32, choices=SubjectType.get_choices())\n subject_id = models.CharField(\"授权对象ID\", max_length=64)\n\n class Meta:\n verbose_name = \"subject限制\"\n verbose_name_plural = \"subject限制\"\n\n\nclass RoleRelatedObject(BaseModel):\n \"\"\"\n 角色关联资源\n \"\"\"\n\n role_id = models.IntegerField(\"角色ID\")\n object_type = models.CharField(\"对象类型\", max_length=32, choices=RoleRelatedObjectType.get_choices())\n object_id = models.IntegerField(\"对象ID\")\n\n objects = RoleRelatedObjectManager()\n\n class Meta:\n verbose_name = \"角色关联资源\"\n verbose_name_plural = \"角色关联资源\"\n unique_together = [\"role_id\", \"object_type\", \"object_id\"]\n\n\nclass RoleCommonAction(BaseModel):\n \"\"\"\n 角色常用操作\n \"\"\"\n\n role_id = models.IntegerField(\"角色ID\")\n system_id = models.CharField(\"系统ID\", max_length=32)\n name = models.CharField(\"名称\", max_length=128)\n name_en = models.CharField(\"名称EN\", max_length=128, default=\"\")\n _action_ids = models.TextField(\"操作列表\", db_column=\"action_ids\")\n\n class Meta:\n verbose_name = \"角色常用操作\"\n verbose_name_plural = \"角色常用操作\"\n ordering = [\"id\"]\n index_together = [\"role_id\", \"system_id\"]\n\n @property\n def action_ids(self):\n return json.loads(self._action_ids)\n\n @action_ids.setter\n def action_ids(self, action_ids):\n self._action_ids = json_dumps(action_ids)\n\n\nclass RoleSource(BaseModel):\n \"\"\"\n 角色创建来源\n \"\"\"\n\n role_id = models.IntegerField(\"角色ID\", unique=True)\n source_type = models.CharField(\"来源类型\", max_length=32, choices=RoleSourceTypeEnum.get_choices())\n source_system_id = models.CharField(\"来源系统\", max_length=32, default=\"\")\n\n\nclass AnonymousRole:\n id = 0\n pk = 0\n name = \"STAFF\"\n name_en = \"\"\n description = \"\"\n type = RoleType.STAFF.value\n code = \"\"\n\n system_permission_enabled_content = RoleUserSystemPermission(\n id=0, role_id=0, content='{\"enabled_users\": [], \"global_enabled\": false}'\n )\n members: List[str] = []\n\n def __str__(self):\n return \"AnonymousRole\"\n\n def __eq__(self, other):\n return isinstance(other, self.__class__)\n\n def __hash__(self):\n return 0 # instances always return the same hash value\n\n def __int__(self):\n raise TypeError(\"Cannot cast AnonymousRole to int. Are you trying to use it in place of Role?\")\n\n def save(self):\n raise NotImplementedError(\"Django doesn't provide a DB representation for AnonymousRole.\")\n\n def delete(self):\n raise NotImplementedError(\"Django doesn't provide a DB representation for AnonymousRole.\")\n\n @property\n def permissions(self):\n return []\n","sub_path":"saas/backend/apps/role/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":8277,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"569116317","text":"#import library\nfrom nltk.tokenize import word_tokenize\nfrom gensim.models import FastText\nimport pandas as pd\n\n#load data\n\nfile = pd.read_csv(\"tmc_data.csv\")\nsentences = file[\"Text\"]\ncorpus = []\n\n#make corpus\nfor sent in sentences:\n corpus.append(word_tokenize(sent))\n\nmodel = FastText(corpus,vector_size=100, workers=4, sg=1,window = 3)\nmodel.train(corpus,total_examples=len(corpus),epochs= 10)\n\nmodel.save(\"tmc2007_fasttext\") #binary file\n\n#get info\nprint(\"Embeding size : \",100)\n#print(\"vocab size : \",len(model.vocab))\n\n#test\nprint(model.wv.most_similar(\"airpor\",topn=5))\nprint(model.wv.most_similar(\"airpo\",topn=5))\nprint(model.wv.most_similar(\"airtraffic\",topn=5))\nprint(model.wv.most_similar(\"craft\",topn=5))\nprint(model.wv.most_similar(\"acce\",topn=5))","sub_path":"embedding_fastext.py","file_name":"embedding_fastext.py","file_ext":"py","file_size_in_byte":763,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"118258301","text":"\n\nfrom xai.brain.wordbase.nouns._standstill import _STANDSTILL\n\n#calss header\nclass _STANDSTILLS(_STANDSTILL, ):\n\tdef __init__(self,): \n\t\t_STANDSTILL.__init__(self)\n\t\tself.name = \"STANDSTILLS\"\n\t\tself.specie = 'nouns'\n\t\tself.basic = \"standstill\"\n\t\tself.jsondata = {}\n","sub_path":"xai/brain/wordbase/nouns/_standstills.py","file_name":"_standstills.py","file_ext":"py","file_size_in_byte":266,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"593943375","text":"import os, sys\n\nfrom collections import OrderedDict\n\nfrom PyQt5.QtWidgets import QApplication, QTreeView, QAbstractItemView, QMenu\nfrom PyQt5.QtGui import QStandardItemModel, QCursor\nfrom PyQt5.QtCore import QSortFilterProxyModel, Qt, QPoint, QModelIndex, pyqtSlot\n\nfrom .treeitems import FunctionItem, RepositoryItem\n# from treeitems import FunctionItem, RepositoryItem\n\n# from fileserializer import FileSerializer\n\nclass TreeView(QTreeView):\n def __init__(self):\n super().__init__()\n\n self.menu = QMenu()\n \n self.selected_item = None\n\n self.repositories = list()\n\n self.source_model = QStandardItemModel()\n self.proxy_model = QSortFilterProxyModel()\n\n self.proxy_model.setSourceModel(self.source_model)\n\n self.setContextMenuPolicy(Qt.CustomContextMenu)\n\n self.setEditTriggers(QAbstractItemView.NoEditTriggers)\n\n self.clicked.connect(self.set_selected_item)\n self.clicked.connect(self.item_clicked)\n self.customContextMenuRequested.connect(self.set_selected_item)\n self.customContextMenuRequested.connect(self.set_point_selected_item)\n self.setModel(self.proxy_model)\n\n def preform_init(self):\n pass\n\n def init(self, serializer):\n self.preform_init()\n repo_obj = serializer.repository\n if repo_obj['url'] in self.repositories:\n raise Exception('Repository with that url already opened.')\n repo_item = RepositoryItem(serializer, url=repo_obj['url'], name=repo_obj['name'])\n self.source_model.appendRow(repo_item)\n self.repositories.append(repo_item.identity)\n\n for child_obj in repo_obj['children']:\n func_item = FunctionItem(repo_item, url=child_obj['url'], name=child_obj['name'], rang=child_obj['rang'], body=child_obj['body'])\n repo_item.add(func_item)\n\n def create(self, **attrs):\n if isinstance(self.selected_item, RepositoryItem):\n repo_item = self.selected_item\n else:\n repo_item = self.selected_item.repository\n item = FunctionItem(repo_item, **attrs)\n self.selected_item.add(item)\n\n def delete(self):\n current_item = self.selected_item\n if isinstance(self.selected_item, RepositoryItem):\n self.source_model.removeRow(self.selected_item.index().row())\n else:\n self.selected_item.parent.remove(self.selected_item)\n\n @pyqtSlot(str)\n def item_clicked(self, idx):\n item = self.selected_item\n if isinstance(item, FunctionItem):\n func_obj = item.repository.serializer.get(item.url)\n for child_obj in func_obj['children']:\n if child_obj['url'] not in item.children:\n func_item = FunctionItem(item.repository, url=child_obj['url'], name=child_obj['name'], rang=child_obj['rang'], body=child_obj['body'])\n item.add(func_item)\n\n @pyqtSlot(str)\n def set_selected_item(self, idx):\n if isinstance(idx, QModelIndex):\n sourse_index = self.proxy_model.mapToSource(idx)\n self.selected_item = self.source_model.itemFromIndex(sourse_index)\n elif idx is None:\n self.selected_item = None\n\n @pyqtSlot(str)\n def set_point_selected_item(self, point):\n if isinstance(point, QPoint):\n indexes = self.selectedIndexes()\n if indexes:\n proxy_index = indexes[0]\n sourse_index = self.proxy_model.mapToSource(proxy_index)\n self.selected_item = self.source_model.itemFromIndex(sourse_index)\n\nif __name__ == '__main__':\n app = QApplication(sys.argv)\n path = '/home/marble/repo'\n view = TreeView()\n view.show()\n serializer = FileSerializer(path)\n # j = OrderedDict([('url', '/home/marble/repo'), ('name', 'repo'), ('functions', ['/home/marble/repo/function21', '/home/marble/repo/function'])])\n view.init(serializer)\n # view.create(url=path, name='test', rang='00.00')\n sys.exit(app.exec_())\n","sub_path":"guicore/treeview.py","file_name":"treeview.py","file_ext":"py","file_size_in_byte":4022,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"450370880","text":"import csv\nfrom selenium import webdriver\nfrom bs4 import BeautifulSoup,Comment\nimport time \nimport re\n\nfrom selenium.common.exceptions import TimeoutException\nfrom selenium.webdriver.support.ui import WebDriverWait\nfrom selenium.webdriver.support import expected_conditions as EC\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.support.ui import Select\nfrom selenium.webdriver.common.keys import Keys\n\ntest=\"C:\\\\Temp\\\\Results\\\\Crownbet\\\\xml.xml\"\n#Set website base url\nbase_url = \"https://crownbet.com.au\"\nsports_url = base_url+\"/sports-betting\"\nsport=\"Australian Rules\"\n\n#Set output location\nbase_file = \"C:\\\\Temp\\\\Results\\\\Crownbet\\\\\"\n\n#load browser driver \ncb_driver = webdriver.Chrome()\ncb_driver.get(sports_url)\n\n#parse the main page and parse sports list to find sport\nnew_soup = BeautifulSoup(cb_driver.page_source, 'lxml')\nsports=new_soup.find_all(\"li\",class_=\"sport-button\")\nfor i in sports:\n #print(i.text)\n if i.text.strip() == \"Australian Rules\":\n ahref=i.a.get('href')\n\n#adjust url and go to sports specific page\nsports_link=base_url+ahref\ncb_driver.get(sports_link)\nmatches_soup = BeautifulSoup(cb_driver.page_source, 'lxml')\n\n#get list of all matches in sport (TEST to confirm ALL sports listed)\nmatches=matches_soup.find_all(\"span\", class_=\"other-matches\")\n\n#parse through each match\nfor match in matches:\n #match = matches[0]\n match_href=base_url+match.a.get('href')\n cb_driver.get(match_href)\n\n #clicks through page to expand all panes\n clicks=cb_driver.find_elements_by_xpath(\"//*[@class='drop-down-header clearfix closed ']\")\n for i in range(len(clicks)):\n print(i)\n clicks[len(clicks)-1].click()\n time.sleep(1)\n clicks=cb_driver.find_elements_by_xpath(\"//*[@class='drop-down-header clearfix closed ']\")\n\n #once all expanded, re-parse page\n match_soup = BeautifulSoup(cb_driver.page_source, 'lxml')\n #get static details - teams, date and time\n game_name = match_soup.find(\"span\", class_=\"item match-name\").text.strip()\n game_date = match_soup.find(\"span\", class_=\"item tv\").text.strip()\n\n game_file = base_file+game_name+\".csv\"\n with open(game_file,'w') as f:\n f.write(\"Game,Date,Header,Name,Line\\n\")\n f.close()\n\n #match_soup.find_all(\"div\", class_=\"title multiple-events\") \n lines = match_soup.find_all(\"div\", class_=\"middle-section match-list\") \n for l in lines: \n #l = lines[0]\n line_header=l.find(\"div\",class_=\"title multiple-events\").text.strip()\n line_details = l.find(\"table\", {\"class\" : re.compile(\"single-event-table*\")})\n line_names = line_details.find_all(\"span\", class_=\"outcome-anchor-text\")\n line_lines = line_details.find_all(\"span\", class_=\"single-bet-amount\")\n for i in range(len(line_names)):\n with open(game_file, 'a') as gf:\n gf.write(game_name+\",\"+game_date+\",\"+line_header+\",\"+line_names[i].text.strip()+\",\"+line_lines[i].text.strip()+\"\\n\")\nprint(\"complete\")","sub_path":"CrownBet.v0.1.py","file_name":"CrownBet.v0.1.py","file_ext":"py","file_size_in_byte":2996,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"109127654","text":"'''\nA unival tree is a tree where all the nodes have the same value.\nGiven a binary tree, return the number of unival subtrees in the tree.\n\nFor example, the following tree should return 5:\n\n 0\n / \\\n 1 0\n / \\\n 1 0\n / \\\n 1 1\n\nThe 5 trees are:\n- The three single '1' leaf nodes. (+3)\n- The single '0' leaf node. (+1)\n- The [1, 1, 1] tree at the bottom. (+1)\n'''\nfrom collections import deque\n\nclass Node:\n def __init__(self, val):\n self.val = val\n self.left = None\n self.right = None\n\ndef count_unival_subtrees(root):\n deq = deque([root])\n subTrees = 0\n while deq:\n node = deq.popleft()\n if node.left is None and node.right is None:\n subTrees += 1\n continue\n \n subDeq = deque([node])\n subNode = None\n while subDeq:\n subNode = subDeq.popleft()\n if node.val != subNode.val:\n break\n \n if subNode.left:\n subDeq.append(subNode.left)\n \n if subNode.right:\n subDeq.append(subNode.right)\n \n if node.val == subNode.val:\n subTrees += 1\n \n if node.left:\n deq.append(node.left)\n \n if node.right:\n deq.append(node.right)\n \n return subTrees\n\nif __name__ == '__main__':\n a = Node(0)\n a.left = Node(1)\n a.right = Node(0)\n a.right.left = Node(1)\n a.right.right = Node(0)\n a.right.left.left = Node(1)\n a.right.left.right = Node(1)\n print(count_unival_subtrees(a))\n\n \n","sub_path":"other/unival_subtrees.py","file_name":"unival_subtrees.py","file_ext":"py","file_size_in_byte":1609,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"206513952","text":"#\n# ICRAR - International Centre for Radio Astronomy Research\n# (c) UWA - The University of Western Australia\n# Copyright by UWA (in the framework of the ICRAR)\n# All rights reserved\n#\n# This library is free software; you can redistribute it and/or\n# modify it under the terms of the GNU Lesser General Public\n# License as published by the Free Software Foundation; either\n# version 2.1 of the License, or (at your option) any later version.\n#\n# This library is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n# Lesser General Public License for more details.\n#\n# You should have received a copy of the GNU Lesser General Public\n# License along with this library; if not, write to the Free Software\n# Foundation, Inc., 59 Temple Place, Suite 330, Boston,\n# MA 02111-1307 USA\n#\n\"\"\"\nBuild a dictionary for the execution graph\n\"\"\"\nimport argparse\nimport getpass\nimport httplib\nimport json\nimport logging\nimport os\nfrom time import sleep\n\nimport boto3\nimport sys\nfrom configobj import ConfigObj\n\nfrom aws_chiles02.build_graph_clean import BuildGraphClean\nfrom aws_chiles02.common import get_session_id, get_list_frequency_groups, get_argument, get_aws_credentials, get_uuid, get_log_level\nfrom aws_chiles02.ec2_controller import EC2Controller\nfrom aws_chiles02.generate_common import get_reported_running, build_hosts, get_nodes_running\nfrom aws_chiles02.settings_file import AWS_REGION, AWS_AMI_ID, DIM_PORT\nfrom aws_chiles02.user_data import get_node_manager_user_data, get_data_island_manager_user_data\nfrom dfms.droputils import get_roots\nfrom dfms.manager.client import DataIslandManagerClient\n\nLOG = logging.getLogger(__name__)\nPARALLEL_STREAMS = 12\n\n\nclass WorkToDo:\n def __init__(self, width, bucket_name, s3_clean_name, min_frequency, max_frequency, s3_uvsub_name):\n self._width = width\n self._bucket_name = bucket_name\n self._s3_clean_name = s3_clean_name\n self._s3_uvsub_name = s3_uvsub_name\n self._min_frequency = min_frequency\n self._max_frequency = max_frequency\n self._work_already_done = None\n self._bucket = None\n self._list_frequencies = None\n self._work_to_do = []\n\n def calculate_work_to_do(self):\n session = boto3.Session(profile_name='aws-chiles02')\n s3 = session.resource('s3', use_ssl=False)\n\n cleaned_objects = []\n self._bucket = s3.Bucket(self._bucket_name)\n for key in self._bucket.objects.filter(Prefix='{0}'.format(self._s3_clean_name)):\n cleaned_objects.append(key.key)\n LOG.info('{0} found'.format(key.key))\n\n uvsub_frequencies = []\n for key in self._bucket.objects.filter(Prefix='{0}'.format(self._s3_uvsub_name)):\n elements = key.key.split('/')\n if len(elements) == 3:\n if elements[1] not in uvsub_frequencies:\n uvsub_frequencies.append(elements[1])\n LOG.info('{0} found'.format(key.key))\n\n # Get work we've already done\n self._list_frequencies = get_list_frequency_groups(self._width)\n for frequency_pair in self._list_frequencies:\n # Use the min and max frequency\n if self._min_frequency is not None and frequency_pair.top_frequency < self._min_frequency:\n continue\n if self._max_frequency is not None and frequency_pair.bottom_frequency > self._max_frequency:\n continue\n\n expected_tar_file = '{0}/cleaned_{1}_{2}.tar'.format(\n self._s3_clean_name,\n frequency_pair.bottom_frequency,\n frequency_pair.top_frequency,\n )\n uvsub_frequency = '{0}_{1}'.format(frequency_pair.bottom_frequency, frequency_pair.top_frequency)\n if expected_tar_file not in cleaned_objects and uvsub_frequency in uvsub_frequencies:\n self._work_to_do.append(frequency_pair)\n\n @property\n def work_to_do(self):\n return self._work_to_do\n\n\ndef get_nodes_required(work_to_do, frequencies_per_node, spot_price):\n nodes = []\n node_count = max(len(work_to_do) / frequencies_per_node, 1)\n nodes.append({\n 'number_instances': node_count,\n 'instance_type': 'i2.4xlarge',\n 'spot_price': spot_price\n })\n\n return nodes, node_count\n\n\ndef create_and_generate(\n bucket_name,\n frequency_width,\n ami_id,\n spot_price,\n volume,\n frequencies_per_node,\n add_shutdown,\n iterations,\n arcsec,\n w_projection_planes,\n robust,\n image_size,\n clean_channel_average,\n min_frequency,\n max_frequency,\n clean_directory_name,\n only_image,\n log_level,\n produce_qa,\n uvsub_directory_name,\n fits_directory_name,\n clean_tclean):\n boto_data = get_aws_credentials('aws-chiles02')\n if boto_data is not None:\n work_to_do = WorkToDo(\n frequency_width,\n bucket_name,\n clean_directory_name,\n min_frequency,\n max_frequency,\n uvsub_directory_name,\n )\n work_to_do.calculate_work_to_do()\n\n nodes_required, node_count = get_nodes_required(work_to_do.work_to_do, frequencies_per_node, spot_price)\n\n if len(nodes_required) > 0:\n uuid = get_uuid()\n ec2_data = EC2Controller(\n ami_id,\n nodes_required,\n get_node_manager_user_data(boto_data, uuid, log_level=log_level),\n AWS_REGION,\n tags=[\n {\n 'Key': 'Owner',\n 'Value': getpass.getuser(),\n },\n {\n 'Key': 'Name',\n 'Value': 'DALiuGE NM - Clean',\n },\n {\n 'Key': 'uuid',\n 'Value': uuid,\n }\n ]\n )\n ec2_data.start_instances()\n\n reported_running = get_reported_running(\n uuid,\n node_count,\n wait=600\n )\n\n if len(reported_running) == 0:\n LOG.error('Nothing has reported ready')\n else:\n hosts = build_hosts(reported_running)\n\n # Create the Data Island Manager\n data_island_manager = EC2Controller(\n ami_id,\n [\n {\n 'number_instances': 1,\n 'instance_type': 'm4.large',\n 'spot_price': spot_price\n }\n ],\n get_data_island_manager_user_data(boto_data, hosts, uuid, need_node_manager=True, log_level=log_level),\n AWS_REGION,\n tags=[\n {\n 'Key': 'Owner',\n 'Value': getpass.getuser(),\n },\n {\n 'Key': 'Name',\n 'Value': 'DALiuGE DIM - Clean',\n },\n {\n 'Key': 'uuid',\n 'Value': uuid,\n }\n ]\n )\n data_island_manager.start_instances()\n data_island_manager_running = get_reported_running(\n uuid,\n 1,\n wait=600\n )\n\n if len(data_island_manager_running['m4.large']) == 1:\n # Now build the graph\n session_id = get_session_id()\n instance_details = data_island_manager_running['m4.large'][0]\n host = instance_details['ip_address']\n graph = BuildGraphClean(\n work_to_do=work_to_do.work_to_do,\n bucket_name=bucket_name,\n volume=volume,\n parallel_streams=PARALLEL_STREAMS,\n node_details=reported_running,\n shutdown=add_shutdown,\n width=frequency_width,\n iterations=iterations,\n arcsec=arcsec,\n w_projection_planes=w_projection_planes,\n robust=robust,\n image_size=image_size,\n clean_channel_average=clean_channel_average,\n clean_directory_name=clean_directory_name,\n only_image=only_image,\n session_id=session_id,\n dim_ip=host,\n produce_qa=produce_qa,\n uvsub_directory_name=uvsub_directory_name,\n fits_directory_name=fits_directory_name,\n clean_tclean=clean_tclean\n )\n graph.build_graph()\n\n # TODO: Safe the run parameters\n\n LOG.info('Connection to {0}:{1}'.format(host, DIM_PORT))\n client = DataIslandManagerClient(host, DIM_PORT)\n\n client.create_session(session_id)\n client.append_graph(session_id, graph.drop_list)\n client.deploy_session(session_id, get_roots(graph.drop_list))\n else:\n LOG.error('Unable to find the AWS credentials')\n\n\ndef use_and_generate(\n host,\n port,\n bucket_name,\n frequency_width,\n volume,\n add_shutdown,\n iterations,\n arcsec,\n w_projection_planes,\n robust,\n image_size,\n clean_channel_average,\n min_frequency,\n max_frequency,\n clean_directory_name,\n only_image,\n produce_qa,\n uvsub_directory_name,\n fits_directory_name,\n clean_tclean):\n boto_data = get_aws_credentials('aws-chiles02')\n if boto_data is not None:\n connection = httplib.HTTPConnection(host, port)\n connection.request('GET', '/api', None, {})\n response = connection.getresponse()\n if response.status != httplib.OK:\n msg = 'Error while processing GET request for {0}:{1}/api (status {2}): {3}'.format(host, port, response.status, response.read())\n raise Exception(msg)\n\n json_data = response.read()\n message_details = json.loads(json_data)\n host_list = message_details['hosts']\n\n nodes_running = get_nodes_running(host_list)\n if len(nodes_running) > 0:\n work_to_do = WorkToDo(\n frequency_width,\n bucket_name,\n clean_directory_name,\n min_frequency,\n max_frequency,\n uvsub_directory_name,\n )\n work_to_do.calculate_work_to_do()\n\n # Now build the graph\n session_id = get_session_id()\n graph = BuildGraphClean(\n work_to_do=work_to_do.work_to_do,\n bucket_name=bucket_name,\n volume=volume,\n parallel_streams=PARALLEL_STREAMS,\n node_details=nodes_running,\n shutdown=add_shutdown,\n width=frequency_width,\n iterations=iterations,\n arcsec=arcsec,\n w_projection_planes=w_projection_planes,\n robust=robust,\n image_size=image_size,\n clean_channel_average=clean_channel_average,\n clean_directory_name=clean_directory_name,\n only_image=only_image,\n session_id=session_id,\n dim_ip=host,\n produce_qa=produce_qa,\n uvsub_directory_name=uvsub_directory_name,\n fits_directory_name=fits_directory_name,\n clean_tclean=clean_tclean,\n )\n graph.build_graph()\n\n # TODO: Save the run parameters\n\n LOG.info('Connection to {0}:{1}'.format(host, port))\n client = DataIslandManagerClient(host, port)\n\n client.create_session(session_id)\n client.append_graph(session_id, graph.drop_list)\n client.deploy_session(session_id, get_roots(graph.drop_list))\n\n else:\n LOG.warning('No nodes are running')\n\n\ndef generate_json(\n width,\n bucket,\n iterations,\n arcsec,\n nodes,\n volume,\n parallel_streams,\n shutdown,\n w_projection_planes,\n robust,\n image_size,\n clean_channel_average,\n min_frequency,\n max_frequency,\n clean_directory_name,\n only_image,\n produce_qa,\n uvsub_directory_name,\n fits_directory_name,\n clean_tclean):\n work_to_do = WorkToDo(\n width,\n bucket,\n clean_directory_name,\n min_frequency,\n max_frequency,\n uvsub_directory_name,\n )\n work_to_do.calculate_work_to_do()\n\n node_details = {\n 'i2.4xlarge': [{'ip_address': 'node_i2_{0}'.format(i)} for i in range(0, nodes)]\n }\n graph = BuildGraphClean(\n work_to_do=work_to_do.work_to_do,\n bucket_name=bucket,\n volume=volume,\n parallel_streams=parallel_streams,\n node_details=node_details,\n shutdown=shutdown,\n width=width,\n iterations=iterations,\n arcsec=arcsec + 'arcsec',\n w_projection_planes=w_projection_planes,\n robust=robust,\n image_size=image_size,\n clean_channel_average=clean_channel_average,\n clean_directory_name=clean_directory_name,\n uvsub_directory_name=uvsub_directory_name,\n fits_directory_name=fits_directory_name,\n only_image=only_image,\n session_id='session_id',\n dim_ip='1.2.3.4',\n produce_qa=produce_qa,\n clean_tclean=clean_tclean)\n graph.build_graph()\n json_dumps = json.dumps(graph.drop_list, indent=2)\n LOG.info(json_dumps)\n with open(\"/tmp/json_clean.txt\", \"w\") as json_file:\n json_file.write(json_dumps)\n\n\ndef command_json(args):\n generate_json(\n width=args.width,\n bucket=args.bucket,\n iterations=args.iterations,\n arcsec=args.arcsec,\n nodes=args.nodes,\n volume=args.volume,\n parallel_streams=args.parallel_streams,\n shutdown=args.shutdown,\n w_projection_planes=args.w_projection_planes,\n robust=args.robust,\n image_size=args.image_size,\n clean_channel_average=args.clean_channel_average,\n min_frequency=args.min_frequency,\n max_frequency=args.max_frequency,\n clean_directory_name=args.clean_directory_name,\n only_image=args.only_image,\n produce_qa=args.produce_qa,\n uvsub_directory_name=args.uvsub_directory_name,\n fits_directory_name=args.fits_directory_name,\n clean_tclean=args.clean_tclean,\n )\n\n\ndef command_create(args):\n log_level = get_log_level(args)\n create_and_generate(\n bucket_name=args.bucket,\n frequency_width=args.width,\n ami_id=args.ami,\n spot_price=args.spot_price1,\n volume=args.volume,\n frequencies_per_node=args.frequencies_per_node,\n add_shutdown=args.shutdown,\n iterations=args.iterations,\n arcsec=args.arcsec + 'arcsec',\n w_projection_planes=args.w_projection_planes,\n robust=args.robust,\n image_size=args.image_size,\n clean_channel_average=args.clean_channel_average,\n min_frequency=args.min_frequency,\n max_frequency=args.max_frequency,\n clean_directory_name=args.clean_directory_name,\n only_image=args.only_image,\n produce_qa=args.produce_qa,\n log_level=log_level,\n uvsub_directory_name=args.uvsub_directory_name,\n fits_directory_name=args.fits_directory_name,\n clean_tclean=args.clean_tclean,\n )\n\n\ndef command_use(args):\n use_and_generate(\n host=args.host,\n port=args.port,\n bucket_name=args.bucket,\n frequency_width=args.width,\n volume=args.volume,\n add_shutdown=args.shutdown,\n iterations=args.iterations,\n arcsec=args.arcsec + 'arcsec',\n w_projection_planes=args.w_projection_planes,\n robust=args.robust,\n image_size=args.image_size,\n clean_channel_average=args.clean_channel_average,\n min_frequency=args.min_frequency,\n max_frequency=args.max_frequency,\n clean_directory_name=args.clean_directory_name,\n produce_qa=args.produce_qa,\n only_image=args.only_image,\n uvsub_directory_name=args.uvsub_directory_name,\n fits_directory_name=args.fits_directory_name,\n clean_tclean=args.clean_tclean,\n )\n\n\ndef command_interactive(args):\n LOG.info(args)\n sleep(0.5) # Allow the logging time to print\n path_dirname, filename = os.path.split(__file__)\n config_file_name = '{0}/aws-chiles02.settings'.format(path_dirname)\n if os.path.exists(config_file_name):\n config = ConfigObj(config_file_name)\n else:\n config = ConfigObj()\n config.filename = config_file_name\n\n get_argument(config, 'run_type', 'Create, use or json', allowed=['create', 'use', 'json'], help_text='the use a network or create a network')\n get_argument(config, 'bucket_name', 'Bucket name', help_text='the bucket to access', default='13b-266')\n get_argument(config, 'volume', 'Volume', help_text='the directory on the host to bind to the Docker Apps')\n get_argument(config, 'width', 'Frequency width', data_type=int, help_text='the frequency width', default=4)\n get_argument(config, 'iterations', 'Clean iterations', data_type=int, help_text='the clean iterations', default=1)\n get_argument(config, 'arcsec', 'How many arc seconds', help_text='the arc seconds', default='2')\n get_argument(config, 'w_projection_planes', 'W Projection planes', data_type=int, help_text='the number of w projections planes', default=24)\n get_argument(config, 'robust', 'Clean robust value', data_type=float, help_text='the robust value for clean', default=0.8)\n get_argument(config, 'image_size', 'The image size', data_type=int, help_text='the image size for clean', default=2048)\n get_argument(config, 'clean_channel_average', 'The number of input channels to average', data_type=int, help_text='the number of input channels to average', default=1)\n get_argument(config, 'only_image', 'Only the image to S3', data_type=bool, help_text='only copy the image to S3', default=False)\n get_argument(config, 'shutdown', 'Add the shutdown node', data_type=bool, help_text='add a shutdown drop', default=True)\n get_argument(config, 'uvsub_directory_name', 'The directory name for the uvsub output', help_text='the directory name for the uvsub output')\n get_argument(config, 'clean_directory_name', 'The directory name for clean', help_text='the directory name for clean')\n get_argument(config, 'fits_directory_name', 'The directory name for fits files', help_text='the directory name for fits')\n get_argument(config, 'produce_qa', 'Produce QA products (yes or no)', allowed=['yes', 'no'], help_text='should we produce the QA products')\n get_argument(config, 'clean_tclean', 'Clean or Tclean', allowed=['clean', 'tclean'], help_text='use clean or tclean', default='clean')\n\n get_argument(config, 'frequency_range', 'Do you want to specify a range of frequencies', data_type=bool, help_text='Do you want to specify a range of frequencies', default=False)\n if config['frequency_range']:\n get_argument(config, 'min_frequency', 'The minimum frequency', data_type=int, help_text='the minimum frequency', default=944)\n get_argument(config, 'max_frequency', 'The maximum frequency', data_type=int, help_text='the maximum frequency', default=1420)\n\n if config['run_type'] == 'create':\n get_argument(config, 'ami', 'AMI Id', help_text='the AMI to use', default=AWS_AMI_ID)\n get_argument(config, 'spot_price_i2_4xlarge', 'Spot Price for i2.4xlarge', help_text='the spot price')\n get_argument(config, 'frequencies_per_node', 'Number of frequencies per node', data_type=int, help_text='the number of frequencies per node', default=1)\n get_argument(config, 'log_level', 'Log level', allowed=['v', 'vv', 'vvv'], help_text='the log level', default='vvv')\n elif config['run_type'] == 'use':\n get_argument(config, 'dim', 'Data Island Manager', help_text='the IP to the DataIsland Manager')\n else:\n get_argument(config, 'nodes', 'Number of nodes', data_type=int, help_text='the number of nodes', default=1)\n\n # Write the arguments\n config.write()\n\n # Run the command\n if config['run_type'] == 'create':\n create_and_generate(\n bucket_name=config['bucket_name'],\n frequency_width=config['width'],\n ami_id=config['ami'],\n spot_price=config['spot_price_i2_4xlarge'],\n volume=config['volume'],\n frequencies_per_node=config['frequencies_per_node'],\n add_shutdown=config['shutdown'],\n iterations=config['iterations'],\n arcsec=config['arcsec'] + 'arcsec',\n w_projection_planes=config['w_projection_planes'],\n robust=config['robust'],\n only_image=config['only_image'],\n image_size=config['image_size'],\n clean_channel_average=config['clean_channel_average'],\n min_frequency=config['min_frequency'] if config['frequency_range'] else None,\n max_frequency=config['max_frequency'] if config['frequency_range'] else None,\n clean_directory_name=config['clean_directory_name'],\n log_level=config['log_level'],\n produce_qa=config['produce_qa'],\n uvsub_directory_name=config['uvsub_directory_name'],\n fits_directory_name=config['fits_directory_name'],\n clean_tclean=config['clean_tclean'],\n )\n elif config['run_type'] == 'use':\n use_and_generate(\n host=config['dim'],\n port=DIM_PORT,\n bucket_name=config['bucket_name'],\n frequency_width=config['width'],\n volume=config['volume'],\n add_shutdown=config['shutdown'],\n iterations=config['iterations'],\n arcsec=config['arcsec'] + 'arcsec',\n w_projection_planes=config['w_projection_planes'],\n robust=config['robust'],\n image_size=config['image_size'],\n clean_channel_average=config['clean_channel_average'],\n min_frequency=config['min_frequency'] if config['frequency_range'] else None,\n max_frequency=config['max_frequency'] if config['frequency_range'] else None,\n clean_directory_name=config['clean_directory_name'],\n only_image=config['only_image'],\n produce_qa=config['produce_qa'],\n uvsub_directory_name=config['uvsub_directory_name'],\n fits_directory_name=config['fits_directory_name'],\n clean_tclean=config['clean_tclean'],\n )\n else:\n generate_json(\n width=config['width'],\n bucket=config['bucket_name'],\n iterations=config['iterations'],\n arcsec=config['arcsec'] + 'arcsec',\n nodes=config['nodes'],\n volume=config['volume'],\n parallel_streams=PARALLEL_STREAMS,\n shutdown=config['shutdown'],\n w_projection_planes=config['w_projection_planes'],\n robust=config['robust'],\n image_size=config['image_size'],\n clean_channel_average=config['clean_channel_average'],\n min_frequency=config['min_frequency'] if config['frequency_range'] else None,\n max_frequency=config['max_frequency'] if config['frequency_range'] else None,\n clean_directory_name=config['clean_directory_name'],\n only_image=config['only_image'],\n produce_qa=config['produce_qa'],\n uvsub_directory_name=config['uvsub_directory_name'],\n fits_directory_name=config['fits_directory_name'],\n clean_tclean=config['clean_tclean'],\n )\n\n\ndef parser_arguments(command_line=sys.argv[1:]):\n parser = argparse.ArgumentParser('Build the CLEAN physical graph for a day')\n\n common_parser = argparse.ArgumentParser(add_help=False)\n common_parser.add_argument('bucket', help='the bucket to access')\n common_parser.add_argument('volume', help='the directory on the host to bind to the Docker Apps')\n common_parser.add_argument('arcsec', help='the number of arcsec', default='2')\n common_parser.add_argument('--only_image', action='store_true', help='store only the image to S3', default=True)\n common_parser.add_argument('--width', type=int, help='the frequency width', default=4)\n common_parser.add_argument('--shutdown', action='store_true', help='add a shutdown drop', default=True)\n common_parser.add_argument('--iterations', type=int, help='the number of iterations', default=10)\n common_parser.add_argument('-v', '--verbosity', action='count', help='increase output verbosity', default=0)\n common_parser.add_argument('--w_projection_planes', type=int, help='the number of w projections planes', default=24)\n common_parser.add_argument('--robust', type=float, help='the robust value for clean', default=0.8)\n common_parser.add_argument('--image_size', type=int, help='the image size for clean', default=2048)\n\n subparsers = parser.add_subparsers()\n\n parser_json = subparsers.add_parser('json', parents=[common_parser], help='display the json')\n parser_json.add_argument('parallel_streams', type=int, help='the of parallel streams')\n parser_json.add_argument('--frequencies_per_node', type=int, help='the number of frequencies per node', default=1)\n parser_json.set_defaults(func=command_json)\n\n parser_create = subparsers.add_parser('create', parents=[common_parser], help='run and deploy')\n parser_create.add_argument('ami', help='the ami to use')\n parser_create.add_argument('spot_price', type=float, help='the spot price')\n parser_create.add_argument('--frequencies_per_node', type=int, help='the number of frequencies per node', default=1)\n parser_create.set_defaults(func=command_create)\n\n parser_use = subparsers.add_parser('use', parents=[common_parser], help='use what is running and deploy')\n parser_use.add_argument('host', help='the host the dfms is running on')\n parser_use.add_argument('--port', type=int, help='the port to bind to', default=DIM_PORT)\n parser_use.set_defaults(func=command_use)\n\n parser_interactive = subparsers.add_parser('interactive', help='prompt the user for parameters and then run')\n parser_interactive.set_defaults(func=command_interactive)\n\n args = parser.parse_args(command_line)\n return args\n\n\nif __name__ == '__main__':\n # json 13b-266 /mnt/dfms/dfms_root 8 -w 8 -s\n logging.basicConfig(level=logging.INFO)\n arguments = parser_arguments()\n arguments.func(arguments)\n","sub_path":"pipeline/aws_chiles02/generate_clean_graph.py","file_name":"generate_clean_graph.py","file_ext":"py","file_size_in_byte":27440,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"245187576","text":"def breakUpTraits(gene, numberOfTraits):\n count = 0\n gametes = [\"\"] * (2 ** numberOfTraits)\n for trait in range(2 ** numberOfTraits):\n binary = str(bin(count)[2:])\n if len(binary) == 2: binary = \"0\" + binary\n if len(binary) == 1: binary = \"00\" + binary\n if numberOfTraits == 2: binary = binary[1:]\n if numberOfTraits == 1: binary = binary[2:]\n\n for index in range(len(binary)):\n if binary[index] == \"0\":\n gametes[count] += gene[index * 2]\n else:\n gametes[count] += gene[index * 2 + 1]\n count += 1\n return gametes\n\n\ndef punnetSq(gene1, gene2):\n numberOfTraits = len(gene1) // 2\n traits1 = breakUpTraits(gene1, numberOfTraits)\n traits2 = breakUpTraits(gene2, numberOfTraits)\n outcomes = []\n for i in traits1:\n for j in traits2:\n s = \"\"\n for letter in range(len(i)):\n if j[letter].isupper():\n s += j[letter] + i[letter]\n else:\n s += i[letter] + j[letter]\n outcomes.append(s)\n phenotype = {}\n for outcome in outcomes:\n if not (outcome in phenotype):\n phenotype[outcome] = outcomes.count(outcome)\n return phenotype, outcomes\n\n\np, o = punnetSq(\"AaSsYy\", \"AaSsYy\")\nprint(len(o), o.count(\"AaSsYy\"))\nprint(p)\n\n# genotype, outcomeList = punnetSq(\"AaBb\", \"AaBb\")\n# print(genotype)\n# print(outcomeList)\n\n\n# print(punnetSq(\"BB\", \"BB\"))\n# print(punnetSq(\"Bb\", \"Bb\"))\n# print(punnetSq(\"BB\", \"BB\"))\n# print(punnetSq(\"bb\", \"bb\"))\n","sub_path":"DNA/punnetSq.py","file_name":"punnetSq.py","file_ext":"py","file_size_in_byte":1576,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"5906543","text":"import sys, os\nfrom pathlib import Path\n\nclass Project:\n\n def __init__(self):\n self.dir_home = str(Path.home())\n self.dir_repo = os.path.join(self.dir_home, 'uigenerator')\n self.dir_projects = os.path.join(self.dir_repo, 'projects')\n self.existing_project_names = [os.path.basename(name) for name in os.listdir(self.dir_projects)]\n\n def create(self):\n\n print(\"Select a project name:\")\n self.project_name = sys.stdin.readline()\n \n if ' ' in self.project_name:\n print('Please do not use space characters in project name!')\n self.create()\n return \n\n if str.lower(self.project_name).strip() in self.existing_project_names:\n print(self.existing_project_names)\n print('Project name exists!')\n self.create()\n return \n\n return self.generate_main_folder()\n\n def generate_main_folder(self): \n self.dir_project = os.path.join(self.dir_projects, str.lower(self.project_name)).rstrip('\\n') \n os.makedirs(self.dir_project)\n return self.dir_project\n \n \n ","sub_path":"src/project.py","file_name":"project.py","file_ext":"py","file_size_in_byte":1155,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"175170752","text":"from django.core.validators import MaxValueValidator, MinValueValidator\nfrom django.db import models\n\nfrom users.models import UserProfile\n\nfrom .validators import year_validator\n\n\nclass Category(models.Model):\n name = models.CharField(max_length=100, blank=False,\n verbose_name='Название категории')\n slug = models.SlugField(max_length=50, unique=True, verbose_name='Слаг')\n\n class Meta:\n ordering = ['name']\n verbose_name = 'Категория'\n verbose_name_plural = 'Категории'\n\n\nclass Genre(models.Model):\n name = models.CharField(max_length=100, blank=False,\n verbose_name='Название жанра')\n slug = models.SlugField(max_length=50, unique=True, verbose_name='Слаг')\n\n class Meta:\n ordering = ['name']\n verbose_name = 'Жанр'\n verbose_name_plural = 'Жанры'\n\n\nclass Title(models.Model):\n name = models.CharField(max_length=150, blank=False,\n verbose_name='Название произведения')\n year = models.PositiveSmallIntegerField(blank=True, null=True,\n validators=[year_validator],\n verbose_name='Год выхода')\n category = models.ForeignKey(Category, on_delete=models.SET_NULL,\n related_name='titles', blank=True, null=True,\n verbose_name='Категория')\n genre = models.ManyToManyField(Genre, verbose_name='Жанры')\n description = models.TextField(null=True, blank=True,\n verbose_name='Описание')\n\n class Meta:\n ordering = ['-year']\n verbose_name = 'Произведение'\n verbose_name_plural = 'Произведения'\n\n\nclass Review(models.Model):\n title = models.ForeignKey(\n Title, on_delete=models.CASCADE, related_name='reviews',\n verbose_name='Произведение'\n )\n text = models.TextField(blank=False, null=False,\n verbose_name='Текст ревью')\n author = models.ForeignKey(\n UserProfile, on_delete=models.CASCADE, related_name='reviews',\n verbose_name='Автор'\n )\n score = models.IntegerField(\n validators=(MinValueValidator(1), MaxValueValidator(10)),\n blank=False, null=False, verbose_name='Оценка'\n )\n pub_date = models.DateTimeField(auto_now_add=True,\n verbose_name='Дата публикации')\n\n class Meta:\n ordering = ['-pub_date']\n verbose_name = 'Ревью'\n verbose_name_plural = 'Ревью'\n\n\nclass Comment(models.Model):\n review = models.ForeignKey(\n Review, on_delete=models.CASCADE, related_name='comments',\n verbose_name='Ревью'\n )\n text = models.TextField(blank=False, null=False,\n verbose_name='Текст комментария')\n author = models.ForeignKey(\n UserProfile, on_delete=models.CASCADE, related_name='comments',\n verbose_name='Автор'\n )\n pub_date = models.DateTimeField(auto_now_add=True,\n verbose_name='Дата публикации')\n\n class Meta:\n ordering = ['-pub_date']\n verbose_name = 'Комментарий'\n verbose_name_plural = 'Комментарии'\n","sub_path":"api/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":3496,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"66718953","text":"\"\"\"interactive script to gather list of subnets from meraki networks\"\"\"\n#import required modules\nimport requests\nimport json\n\n# Define static variables\n# uncomment to set variable instead of having user input:\n#API_KEY = 'key-value'\nMERAKI_URL = 'https://api.meraki.com/api/v1/'\n#ORG_KEY = 'org-id'\n#headers = {'X-Cisco-Meraki-API-Key':API_KEY}\n\n#welcome message for production value\nprint(\"##############################################################\")\nprint(\"### LIST MERAKI SUBNETS ###\")\nprint(\"##############################################################\")\nprint(\"This script fetches you a list of subnets from your meraki org\")\nprint(\"Please ensure you have permission to access your organisations\")\nprint(\"dashboard API.\")\nprint()\n#prompt user for api key\nprint(\"Please enter your API Key:\")\nAPI_KEY = input()\n\nprint()\n\n#prompt user for org id\nprint(\"Please enter your organisation ID:\")\nORG_KEY = input()\nheaders = {'X-Cisco-Meraki-API-Key':API_KEY}\n\n# Function to grab the list of the Networks for the Organisation\ndef get_net_id():\n\tnet_list = requests.get(MERAKI_URL + 'organizations/' + ORG_KEY + '/networks', headers=headers)\n\tif net_list.status_code != 200:\n \t\tprint('Incorrect Network Query String: Error accessing:', MERAKI_URL + 'organizations/' + ORG_KEY + '/networks');\n \t\texit(1);\n\telse:\n\t\tjson_list = json.loads(net_list.text)\n\t\treturn json_list\n\n# Function to grab the VLAN's in the Network, based on Network ID (passed)\ndef get_vlan_info(net_id):\n\tvlan_list = requests.get(MERAKI_URL + 'networks/' + net_id + '/appliance' + '/vlans', headers=headers)\n\tif vlan_list.status_code != 200:\n \t\tprint('Incorrect VLAN Query String: Error accessing:', MERAKI_URL + 'networks/' + net_id + '/appliance' + '/vlans');\n \texit(1);\n\telse:\n\t\tjson_vlist = json.loads(vlan_list.text)\n\t\treturn json_vlist\n\ndef main():\n# Get list of networks and ID's\n\tprint(\"starting main function and getting network ID's\")\n\tnet_data = get_net_id()\n\tfor i in net_data:\n\t\tnet_name = i[\"name\"]\n\t\tnet_id = i[\"id\"]\n# Ignore no VLAN networks by name\n\t\tif 'CORE' in net_name:\n\t\t\tcontinue\n\t\tif 'TW' in net_name:\n\t\t\tcontinue\n\t\telse:\n# Use the ID to get a list of VLAN's per Network\n\t\t\tvlan_data = get_vlan_info(net_id)\n\t\t\tfor v in vlan_data:\n# Extract just the VLAN Name, and Subnet Range\n\t\t\t\tsub_net = v[\"subnet\"]\n\t\t\t\tvlan_name = v[\"name\"]\n# Print Results in a CSV Friendly Format\n\t\t\t\tprint(net_name + ', ' + vlan_name + ', ' + sub_net)\nmain()\n","sub_path":"get-meraki-subnets.py","file_name":"get-meraki-subnets.py","file_ext":"py","file_size_in_byte":2487,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"242748659","text":"#-----------------------------------------------------------------------------------------------#\n\n# Hristo Valtchev\n# Homework #3\n# 4/27/2020\n# Square\n#-----------------------------------------------------------------------------------------------#\n\n# Dice - count totals in user-defined number of rounds\n\nimport random\n\nclass Bin():\n def __init__(self, binIdentifier):\n # This method runs whenever you create a Bin object\n self.binIndentifier = binIdentifier\n self.count = 0\n\n def reset(self):\n # This is called when you start or restart\n self.count = 0\n\n def increment(self):\n # Called when the roll total is the value of the binIdentifier\n self.count = self.count + 1\n\n def show(self, nRoundsDone):\n # Called at the end to show the contents of this bin\n if self.binIndentifier > 1:\n print(self.binIndentifier, ': count is', self.count, 'or', '{:.0%}'.format(self.count/nRoundsDone))\n\n# Build a list of Bin objects \nbinList = [] # start off as the empty list\n# Here, you need to write a loop that runs 13 times (0 to 12)\n# In the loop create a Bin object, and store the object in the list of Bins\n# (We won't use binList[0] or binList[1])\n\nfor x in range(0, 13):\n newBin = Bin(x)\n binList.insert(x, newBin)\n\nwhile True:\n nRounds = input('How many rounds do you want to do? (or Enter to exit): ')\n if nRounds == '':\n break\n nRounds = int(nRounds)\n\n # Tell each bin object to reset itself\n for oBin in binList:\n oBin.reset()\n \n # For each round (build a loop):\n for n in range(0, nRounds):\n # roll two dice\n d1 = random.randrange(1, 7)\n d2 = random.randrange(1, 7)\n # calculate the total\n total = d1 + d2\n # and tell the appropriate bin object to increment itself\n binList[total].increment()\n\n print()\n print('After', nRounds, 'rounds:')\n # Tell each bin to show itself\n for oBin in binList:\n oBin.show(nRounds)\n print()\n\nprint('OK bye')\n","sub_path":"python2/hw3/HristoValtchev_Homework3.py","file_name":"HristoValtchev_Homework3.py","file_ext":"py","file_size_in_byte":2056,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"172691295","text":"from django.contrib import admin\nfrom django.urls import path, include\nimport base\n\nurlpatterns = [\n path('admin/', admin.site.urls),\n path('accounts/', include('accounts.urls')),\n path('', include('base.urls')),\n]\n\nhandler404 = base.views.handler404\nhandler500 = base.views.handler500\n","sub_path":"oneStop/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":295,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"133168663","text":"\"\"\"\n Copyright (C) 2020 By Xanonymous All Rights Reserved.\n Visit My GitHub:https://github.com/Xanonymous-GitHub\n This package is formatted by python official coding style linter (PEP8).\n More style details on:https://www.python.org/dev/peps/pep-0008\n\"\"\"\n\n\nclass Matrix:\n \"\"\"Define the Matrix class\"\"\"\n\n def __init__(self, u: str or list):\n if not isinstance(u, list):\n u = u.split(\";\")\n for i, _ in enumerate(u):\n u[i] = u[i].split(\",\")\n for j, y in enumerate(u[i]):\n try:\n tmp = float(y)\n u[i][j] = tmp if tmp != int(tmp) else int(tmp)\n except ValueError:\n self.__error_handler(\"Invalid inputs.\")\n self.__del__()\n return\n if not self.__valid(u):\n self.__error_handler(\"Error: Invalid matrix.\")\n self.__del__()\n return\n self.__storage = u\n\n def __str__(self):\n return self.__pretty(self.__storage)\n\n def __del__(self):\n del self\n\n # Matrix addition or subtraction.\n def __add__(self, other, t=True):\n # If the matrices cannot be added or subtracted, throw an error.\n other = other.raw\n if not (self.__valid(self.__storage) and self.__valid(other) and (\n len(self.__storage) == len(other) and len(self.__storage[0]) == len(other[0]))):\n return self.__error_handler(\"These two matrices cannot be added or subtracted together.\")\n new = list()\n for i, x in enumerate(other):\n new_tmp = list()\n for j, y in enumerate(x):\n new_tmp.append(self.__storage[i][j] + y * (1 if t else -1))\n new.append(new_tmp)\n return Matrix(new)\n\n def __radd__(self, other):\n return self.__add__(other)\n\n def __sub__(self, other):\n return self.__add__(other, False)\n\n # Matrix multiplication\n def __mul__(self, other):\n if isinstance(other, int):\n # method accept single integer to be calculated.\n new = list()\n for i, x in enumerate(self.__storage):\n new_tmp = list()\n for _, y in enumerate(x):\n new_tmp.append(y)\n new.append(new_tmp)\n return Matrix(self.__rate(new, other))\n # If the matrices cannot be multiplied, throw an error.\n resource = other.raw\n if not self.__valid(resource):\n self.__error_handler(\"Invalid matrix.\")\n return\n for g in self.__storage:\n if not len(g) == len(resource):\n self.__error_handler(\"Cannot be multiplied.\")\n return\n # if the second matrix is an identity_matrix, the answer will be the same as first matrix.\n if self.is_unit_matrix(resource):\n new = self.__storage[:].copy()\n return Matrix(new)\n new = list()\n for i, x in enumerate(self.__storage):\n tmp_slice = list()\n for n in self.__transpose(resource):\n tmp_num = list()\n for j, y in enumerate(x):\n tmp_num.append(y * n[j])\n tmp_slice.append(sum(tmp_num))\n new.append(tmp_slice)\n return Matrix(new)\n\n def __rmul__(self, other):\n return self.__mul__(other)\n\n def __pow__(self, power: int, modulo=None):\n if self.is_unit_matrix(self.__storage) or power == 1:\n new = self.__storage[:].copy()\n return Matrix(new)\n if not power:\n n = len(self.__storage)\n tmp_n = n\n tmp = list()\n while tmp_n:\n tmp_tmp = list()\n m = n\n while m:\n tmp_tmp.insert(0, 1 if m == tmp_n else 0)\n m -= 1\n tmp.insert(0, tmp_tmp)\n tmp_n -= 1\n return Matrix(tmp)\n if not len(self.__storage) == len(self.__storage[0]):\n self.__error_handler(\"Unable to calculate power, not square.\")\n return\n tmp = Matrix(self.__storage[:].copy())\n for x in range(power - 1):\n self.__storage = self.__mul__(tmp).raw\n new = self.__storage[:].copy()\n self.__storage = tmp.raw[:].copy()\n return Matrix(new)\n\n def __eq__(self, other):\n return other.raw == self.__storage\n\n @property\n def inverse(self):\n def make_new(old):\n new_thing = list()\n for _, xx in enumerate(old):\n new_tmp = list()\n for _, yy in enumerate(xx):\n new_tmp.append(yy)\n new_thing.append(new_tmp)\n return new_thing\n\n determinant = self.__determinant(self.__storage)\n if not determinant:\n self.__error_handler(\"The determinant is zero, can't be inverse.\")\n return\n if len(self.__storage) == 1:\n new = make_new(self.__storage[:].copy())\n new[0][0] = new[0][0] ** -1\n return Matrix(new)\n if len(self.__storage) == 2:\n new = make_new(self.__storage[:].copy())\n new[0][0], new[1][1] = new[1][1], new[0][0]\n new[0][1] *= -1\n new[1][0] *= -1\n new = self.__rate(new, 1 / determinant)\n return Matrix(new)\n ans = list()\n new = make_new(self.__storage[:].copy())\n for i, x in enumerate(self.__storage):\n ans_tmp = list()\n for j, y in enumerate(x):\n h = (-1 if i % 2 else 1) * (-1 if j % 2 else 1)\n ans_tmp.append(h * self.__determinant(self.__get_ans_range(i, j, new)))\n ans.append(ans_tmp)\n ans = self.__transpose(ans)\n new = self.__rate(ans, 1 / determinant)\n return Matrix(new)\n\n @property\n def transpose(self):\n new = self.__storage[:].copy()\n return Matrix(self.__transpose(new))\n\n def __determinant(self, r) -> int or float:\n if not self.__valid(r):\n self.__error_handler(\"Invalid matrix.\")\n return\n if not len(r) == len(r[0]):\n self.__error_handler(\"Can't get the determinant of this matrix.\")\n return\n if len(r) == 1:\n return r[0]\n if len(r) == 2:\n return r[0][0] * r[1][1] - r[0][1] * r[1][0]\n result = list()\n for i, x in enumerate(r[0]):\n h = (-1 if i % 2 else 1)\n result.append(\n self.__determinant(self.__magnification_iteration(self.__get_ans_range(0, i, r), h * x)))\n return sum(result)\n\n def __valid(self, r) -> bool:\n if not r:\n self.__error_handler(\"Empty matrix\")\n return False\n for p in range(len(r) - 1):\n if len(r[p]) != len(r[p + 1]):\n return False\n return True\n\n @property\n def raw(self) -> list:\n # get the real value of the object\n return self.__storage\n\n @staticmethod\n def __pretty(r) -> str:\n # Detect if the value can be an integer.\n for i, x in enumerate(r):\n for j, y in enumerate(x):\n if abs(r[i][j] - int(r[i][j])) < 10 ** -3:\n r[i][j] = int(r[i][j])\n # format the value then return\n return '\\n'.join(map(str, r)) + '\\n'\n\n @staticmethod\n def __error_handler(msg):\n print(msg)\n\n @staticmethod\n def __transpose(resource: list) -> list:\n return list(map(list, zip(*resource)))\n\n @staticmethod\n def is_unit_matrix(resource: list) -> bool:\n for i, x in enumerate(resource):\n for j, y in enumerate(x):\n if i == j and resource[i][j] != 1:\n return False\n if y != 0:\n return False\n return True\n\n @staticmethod\n def __get_ans_range(ii, jj, resource: list) -> list:\n ans = list()\n for i, x in enumerate(resource):\n tmp_slice = list()\n for j, y in enumerate(x):\n if not (i == ii or j == jj):\n tmp_slice.append(y)\n if tmp_slice:\n ans.append(tmp_slice)\n return ans\n\n @staticmethod\n def __rate(r, rate) -> list:\n new = r[:].copy()\n for i, x in enumerate(new):\n for j, y in enumerate(x):\n new[i][j] = rate * r[i][j]\n return new\n\n @staticmethod\n def __magnification_iteration(r: list, rate) -> list:\n for i, x in enumerate(r):\n r[i][0] *= rate\n return r\n\n\nclass UnitMatrix(Matrix):\n def __init__(self, n):\n tmp_n = n\n tmp = list()\n while tmp_n:\n tmp_tmp = list()\n m = n\n while m:\n tmp_tmp.insert(0, 1 if m == tmp_n else 0)\n m -= 1\n tmp.insert(0, tmp_tmp)\n tmp_n -= 1\n super().__init__(tmp)\n\n def __str__(self):\n return super().__str__()\n","sub_path":"xmatrix/matrix.py","file_name":"matrix.py","file_ext":"py","file_size_in_byte":9080,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"489367581","text":"# Run \"nosetests\" on command line to run these.\nfrom namecheap import Api, ApiError, Domain\nfrom privex.helpers import is_true\nfrom nose.tools import * # pip install nose\n\napi_key = '' # You create this on Namecheap site\nusername = ''\nip_address = '' # Your IP address that you whitelisted on the site\n\n# If you prefer, you can put the above in credentials.py instead\ntry:\n from credentials import api_key, username, ip_address\nexcept:\n pass\n\n\ndef get_api() -> Api:\n return Api(username, api_key, ip_address, sandbox=True, debug=True)\n\n\ndef random_domain_name():\n import random\n from time import gmtime, strftime\n domain_name = \"%s-%s.com\" % (strftime(\"%Y%m%d-%H%M%S\", gmtime()), random.randint(0, 10**16))\n return domain_name\n\n\ndef test_domain_taken():\n api = get_api()\n domain_name = \"google.com\"\n assert_equal(api.domains_available(domain_name), False)\n\n\ndef test_domain_available():\n api = get_api()\n domain_name = random_domain_name()\n assert_equal(api.domains_available(domain_name), True)\n\n\ndef test_register_domain():\n api = get_api()\n\n # Try registering a random domain. Fails if exception raised.\n domain_name = random_domain_name()\n res = api.domains_create(\n DomainName=domain_name,\n FirstName='Jack',\n LastName='Trotter',\n Address1='Ridiculously Big Mansion, Yellow Brick Road',\n City='Tokushima',\n StateProvince='Tokushima',\n PostalCode='771-0144',\n Country='Japan',\n Phone='+81.123123123',\n EmailAddress='jack.trotter@example.com'\n )\n \n assert_equal(res.domain, domain_name)\n ok_(int(res.domain_id) > 0)\n ok_(int(res.transaction_id) > 0)\n ok_(is_true(res.registered))\n return domain_name\n\n\ndef test_domains_getList():\n api = get_api()\n doms = list(api.domains_getList())\n ok_(len(doms) > 0)\n ok_(isinstance(doms[0], Domain))\n\n\n@raises(ApiError)\ndef test_domains_dns_setDefault_on_nonexisting_domain():\n api = get_api()\n\n domain_name = random_domain_name()\n\n # This should fail because the domain does not exist\n api.domains_dns_setDefault(domain_name)\n\n\ndef test_domains_dns_setDefault_on_existing_domain():\n api = get_api()\n domain_name = test_register_domain()\n res = api.domains_dns_setDefault(domain_name)\n assert_equal(res['Domain'], domain_name)\n ok_(is_true(res['Updated']))\n\n\ndef test_domains_getContacts():\n # How would I test for this? This needs a known registered\n # domain to get the contact info for, but in sandbox won't\n # have any.\n pass\n\n\ndef test_domains_dns_setHosts():\n api = get_api()\n domain_name = test_register_domain()\n res = api.domains_dns_setHosts(\n domain_name,\n dict(HostName='@', RecordType='URL', Address='http://news.ycombinator.com', MXPref='10', TTL='100')\n )\n assert_equal(res['Domain'], domain_name)\n ok_(is_true(res['IsSuccess']))\n\n#\n# I wasn't able to get this to work on any public name servers that I tried\n# including the ones used in their own example:\n# dns1.name-servers.com\n# dns2.name-server.com\n# Using my own Amazon Route53 name servers the test works fine but I didn't\n# want to embed my own servers\n# Adjust the name servers below to your own and uncomment the test to run\n\n\ndef test_domains_dns_setCustom():\n api = get_api()\n domain_name = test_register_domain()\n result = api.domains_dns_setCustom(\n domain_name, 'ns1.privex.io', 'ns2.privex.io', 'ns3.privex.io'\n )\n\n\ndef test_domains_dns_getHosts():\n api = get_api()\n domain_name = test_register_domain()\n api.domains_dns_setHosts(\n domain_name,\n dict(HostName='@', RecordType='URL', Address='http://news.ycombinator.com', MXPref='10', TTL='100'),\n dict(HostName='*', RecordType='A', Address='1.2.3.4', MXPref='10', TTL='1800')\n )\n\n hosts = [dict(d.raw_data) for d in api.domains_dns_getHosts(domain_name)]\n\n # these might change\n del hosts[0]['HostId']\n del hosts[1]['HostId']\n\n expected_result = [\n {\n 'Name': '*',\n 'Address': '1.2.3.4',\n 'TTL': '1800',\n 'Type': 'A',\n 'MXPref': '10',\n 'AssociatedAppTitle': '',\n 'FriendlyName': '',\n 'IsActive': 'true',\n 'IsDDNSEnabled': 'false'\n }, {\n 'Name': '@',\n 'Address': 'http://news.ycombinator.com',\n 'TTL': '100',\n 'Type': 'URL',\n 'MXPref': '10',\n 'AssociatedAppTitle': '',\n 'FriendlyName': '',\n 'IsActive': 'true',\n 'IsDDNSEnabled': 'false'\n }\n ]\n assert_equal(hosts, expected_result)\n\n\ndef test_domains_dns_addHost():\n api = get_api()\n domain_name = test_register_domain()\n api.domains_dns_setHosts(\n domain_name,\n dict(HostName='@', RecordType='URL', Address='http://news.ycombinator.com')\n )\n api.domains_dns_addHost(\n domain_name,\n record_type='A', value='1.2.3.4', hostname='test', ttl=100\n )\n\n hosts = api.domains_dns_getHosts(domain_name)\n \n # h1, h2 = hosts[0], hosts[1]\n \n def _find_host(name, address, rtype, mx_pref, ttl):\n for h in hosts:\n if h.name == name and h.address == address:\n assert_equal(h.name, name)\n assert_equal(h.address, address)\n assert_equal(h.type, rtype)\n assert_equal(int(h.mx_pref), int(mx_pref))\n assert_equal(int(h.ttl), int(ttl))\n return\n assert False\n\n _find_host('@', 'http://news.ycombinator.com', 'URL', 10, 1800)\n _find_host('test', '1.2.3.4', 'A', 10, 100)\n\n\ndef test_domains_dns_bulkAddHosts():\n api = get_api()\n api.payload_limit = 3\n domain_name = test_register_domain()\n api.domains_dns_setHosts(\n domain_name,\n dict(HostName='@', RecordType='URL', Address='http://news.ycombinator.com')\n )\n for i in range(1, 10):\n api.domains_dns_addHost(\n domain_name,\n hostname=f\"test{str(i)}\", record_type='A', value='1.2.3.4', ttl='60'\n )\n\n hosts = api.domains_dns_getHosts(domain_name)\n\n if len(hosts) == 10:\n return True\n\n return False\n\n\ndef test_domains_dns_delHost():\n api = get_api()\n domain_name = test_register_domain()\n \n res = api.domains_dns_setHosts(\n domain_name,\n dict(HostName='@', RecordType='URL', Address='http://news.ycombinator.com', TTL='200'),\n dict(HostName='test', RecordType='A', Address='1.2.3.4')\n )\n assert_equal(res['Domain'], domain_name)\n ok_(is_true(res['IsSuccess']))\n \n res = api.domains_dns_delHost(domain_name, record_type='A', value='1.2.3.4', hostname='test')\n assert_equal(res['Domain'], domain_name)\n ok_(is_true(res['IsSuccess']))\n \n hosts = api.domains_dns_getHosts(domain_name)\n \n host = hosts[0]\n \n assert_equal(host.name, '@')\n assert_equal(host.address, 'http://news.ycombinator.com')\n assert_equal(host.ttl, 200)\n assert_equal(host.type, 'URL')\n assert_equal(host.mx_pref, 10)\n\n\ndef test_list_of_dictionaries_to_numbered_payload():\n x = [\n {'foo': 'bar', 'cat': 'purr'},\n {'foo': 'buz'},\n {'cat': 'meow'}\n ]\n\n result = Api._list_of_dictionaries_to_numbered_payload(x)\n\n expected_result = {\n 'foo1': 'bar',\n 'cat1': 'purr',\n 'foo2': 'buz',\n 'cat3': 'meow'\n }\n\n assert_equal(result, expected_result)\n","sub_path":"namecheap_tests.py","file_name":"namecheap_tests.py","file_ext":"py","file_size_in_byte":7488,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"421066047","text":"\"\"\" Cat Facts - Randomised or not so randomised cat facts as practice. \"\"\"\n\nimport datetime\nimport random\nimport os\n\nfrom kivy.app import App\nfrom kivy.core.window import Window\nfrom kivy.lang import Builder\nfrom kivy.properties import StringProperty\n\n\nclass Catfacts(App):\n displayed_pic = StringProperty(\"assets\\\\cat1.jpg\")\n displayed_text = StringProperty(\"\")\n fact_list = []\n total = 0\n current_catfact = 0\n\n def build(self):\n Window.size = 350, 550\n self.title = \"Cat Facts\"\n self.root = Builder.load_file(\"gui.kv\")\n self.populate_catfact_list()\n self.current_date_and_time()\n return self.root\n\n def populate_catfact_list(self):\n \"\"\" Populates the list of catfacts by reading through a given text\n document, catfacts_text.txt, and assigning each line to a list value\"\"\"\n with open(\"catfacts_text.txt\", \"r\", encoding=\"utf-8\") as file:\n facts = file.readlines()\n for i in facts:\n i.strip().split()\n self.fact_list.append(i)\n Catfacts.total += 1\n\n def random_catfact(self):\n \"\"\" Produces a random number between one and the current total\n number of catfacts. This number is then used to display the catfact\n from equal position in the catfact list. \"\"\"\n num = random.randint(1, Catfacts.total - 1)\n Catfacts.current_catfact = num\n self.displayed_text = Catfacts.fact_list[num]\n\n def cycle_list_up(self):\n \"\"\" Checks if the current fact is the last, and if so returns\n user to the beginning of the list. If not, it cycles the current fact\n forward by one, then displays the new fact.\"\"\"\n if Catfacts.current_catfact == Catfacts.total - 1:\n Catfacts.current_catfact -= Catfacts.total - 1\n self.displayed_text = Catfacts.fact_list[Catfacts.current_catfact]\n else:\n Catfacts.current_catfact += 1\n self.displayed_text = Catfacts.fact_list[Catfacts.current_catfact]\n\n def cycle_list_down(self):\n \"\"\" Checks if the current fact is the first, and if so returns\n the user to the end of the list. If not, it cycles the current fact\n back by one, then displays the new fact.\"\"\"\n if Catfacts.current_catfact == 0:\n Catfacts.current_catfact += (Catfacts.total - 1)\n self.displayed_text = Catfacts.fact_list[Catfacts.current_catfact]\n else:\n Catfacts.current_catfact -= 1\n self.displayed_text = Catfacts.fact_list[Catfacts.current_catfact]\n\n def current_date_and_time(self):\n \"\"\"Literally just shows the current time, because why not.\"\"\"\n time = datetime.datetime.now().strftime('%H:%M:%S')\n self.root.ids.just_the_time.text = time\n\n def random_cat_pic(self):\n pics_folder = os.listdir(\"assets\")\n total_pics = len(pics_folder)\n num = random.randint(0, (total_pics - 1))\n self.displayed_pic = \"assets\\\\cat{}.jpg\".format(num)\n\n\nif __name__ == \"__main__\":\n Catfacts().run()","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3076,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"60024360","text":"# --- SECTION 1 ---\r\n# Libraries and data loading\r\nimport openensembles as oe\r\nimport numpy as np\r\nimport pandas as pd\r\nimport sklearn.metrics\r\n\r\nfrom sklearn.datasets import load_breast_cancer\r\n\r\n\r\nbc = load_breast_cancer()\r\n\r\n# --- SECTION 2 ---\r\n# Create the data object\r\ncluster_data = oe.data(pd.DataFrame(bc.data), bc.feature_names)\r\n\r\nnp.random.seed(123456)\r\n# --- SECTION 3 ---\r\n# Create the ensembles and calculate the homogeneity score\r\nfor K in [2, 3, 4, 5, 6, 7]:\r\n for ensemble_size in [3, 4, 5]:\r\n ensemble = oe.cluster(cluster_data)\r\n for i in range(ensemble_size):\r\n name = f'kmeans_{ensemble_size}_{i}'\r\n ensemble.cluster('parent', 'kmeans', name, K)\r\n\r\n preds = ensemble.finish_majority_vote(threshold=0.5)\r\n print(f'K: {K}, size {ensemble_size}:', end=' ')\r\n print('%.2f' % sklearn.metrics.homogeneity_score(\r\n bc.target, preds.labels['majority_vote']))\r\n\r\n\r\n","sub_path":"Chapter08/oe_vote.py","file_name":"oe_vote.py","file_ext":"py","file_size_in_byte":953,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"319605832","text":"from ftw.tabbedview.interfaces import ITabbedView\nfrom opengever.base.response import JSONResponse\nfrom opengever.contact import _\nfrom opengever.contact.models import Participation\nfrom opengever.tabbedview import GeverTabMixin\nfrom plone import api\nfrom Products.Five.browser import BrowserView\nfrom sqlalchemy import desc\nfrom zope.browserpage.viewpagetemplatefile import ViewPageTemplateFile\nfrom zope.i18n import translate\n\n\nclass ParticipationsView(BrowserView):\n \"\"\"An endpoint to fetch all participations for the current contact.\n \"\"\"\n\n def get_slice_size(self):\n return api.portal.get_registry_record(\n 'batch_size', interface=ITabbedView)\n\n def get_particpations_query(self):\n raise NotImplementedError\n\n def list(self):\n \"\"\"Returns a json dict with the following structure.\n\n `participations`: a list of json representation of the current\n contexts participations. It sliced to the default tabbedview batch\n size depending on the `show_all` request_flag.\n `has_more`: a boolean value if the list is sliced.\n `show_all_label`: label for the show all link.\n \"\"\"\n\n data = {}\n query = self.get_particpations_query().order_by(\n desc(Participation.participation_id))\n total = query.count()\n\n if self.request.get('show_all') != 'true':\n query = query.limit(self.get_slice_size())\n\n data['participations'] = self._serialize(query)\n data['has_more'] = total > len(data['participations'])\n data['show_all_label'] = self.get_show_all_label(total)\n return JSONResponse(self.request).data(**data).dump()\n\n def get_show_all_label(self, total):\n msg = _(u'label_show_all',\n default=u'Show all ${total} participations',\n mapping={'total': total})\n return translate(msg, context=self.request)\n\n def _serialize(self, participations):\n return [participation.get_json_representation()\n for participation in participations]\n\n\nclass OrganizationParticipationsView(ParticipationsView):\n\n def get_particpations_query(self):\n return Participation.query.by_organization(self.context.model)\n\n\nclass PersonParticipationsView(ParticipationsView):\n\n def get_particpations_query(self):\n return Participation.query.by_person(self.context.model)\n\n\nclass ParticpationTab(BrowserView, GeverTabMixin):\n\n show_searchform = False\n\n template = ViewPageTemplateFile('templates/participations.pt')\n\n def __call__(self):\n return self.template()\n\n def get_participations(self):\n \"\"\"Returns all participations for the current context.\n \"\"\"\n participations = Participation.query.by_dossier(self.context).all()\n return sorted(\n participations,\n key=lambda participation: participation.participant.get_title())\n","sub_path":"opengever/contact/browser/participations.py","file_name":"participations.py","file_ext":"py","file_size_in_byte":2903,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"573275333","text":"import os\nimport re\nimport sys\nimport shutil\nimport argparse\n\n\n\n\n\nclass Project(object):\n pwd = \"\"\n path = \"\"\n\n def __init__(self, path_to_project):\n \"\"\" \"\"\"\n\n if not os.path.exists(path_to_project):\n raise FileNotFoundError(\n \"Path '%s' doesn't exist\" % (path_to_project)\n )\n else:\n self.path = path_to_project\n self.pwd = os.path.dirname(os.path.abspath(__file__)) + os.sep\n\n if self.path[-1] is not os.sep:\n self.path += os.sep\n\n\n\nclass New(Project):\n def create(self, name=None):\n \"\"\" Creating a new project \"\"\"\n\n if name:\n template = self.pwd + \"template\" + os.sep\n path_to_project = self.path + name + os.sep\n\n if os.path.exists(path_to_project):\n shutil.rmtree(path_to_project)\n\n # Copy the project template to a new project\n shutil.copytree(template, path_to_project)\n\n\n\nclass Build(Project):\n conf = {}\n\n def _importConfiguration(self):\n \"\"\" \"\"\"\n\n # Add a project path for the configuration file to import\n sys.path.append(self.path)\n\n try:\n import config\n except ImportError:\n raise ImportError(\n \"In the project there's no configuration file 'config.py'\"\n )\n else:\n # Get all the variable settings from the configuration file\n attr = config.__dict__\n self.conf = {key : attr[key] for key in attr if key.isupper()}\n\n\n def startAssembly(self):\n \"\"\" \"\"\"\n\n self._importConfiguration()\n\n # Get the paths to the project directory\n path_to_template = self.path + self.conf[\"TEMPLATE_FILE\"]\n path_to_content = self.path + self.conf[\"CONTENT_DIR\"] + os.sep\n path_to_html = self.path + self.conf[\"HTML_DIR\"] + os.sep\n\n # Walk each file with the text of article\n for file in os.listdir(path_to_content):\n # Get a page template\n with open(path_to_template) as temp:\n template = temp.read()\n\n # Get article template\n with open(path_to_content + file) as text:\n content = text.read()\n\n # Find the template article data\n content_var = re.findall(r\":\\w+:\", content)\n content_val = re.split(r\":\\w+:\", content)\n\n # Replace all the variables from the config.py of the page template\n for (variable, value) in self.conf.items():\n template = template.replace(\"{{% \"+variable+\" %}}\", value)\n\n # Replace in the template page all the variables from the article\n for (variable, value) in zip(content_var, content_val):\n variable = variable[1:-1]\n value = value.strip()\n template = template.replace(\"{{% \"+variable+\" %}}\", value)\n\n # TODO: Make conversion to markdown\n\n # Save the page in an HTML file\n file_name = os.path.splitext(file)[0] + \".html\"\n with open(path_to_html + file_name, \"w\") as html:\n html.write(template)\n\n\n\nclass Push(Project):\n def _createCommit(self):\n pass\n\n\n def startPush(self):\n self._createCommit()\n\n print (\"Start pushing project on github...\")\n","sub_path":"project.py","file_name":"project.py","file_ext":"py","file_size_in_byte":3347,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"97215824","text":"from __future__ import absolute_import\n\nfrom .context import Context\nfrom .exceptions import ProtocolException\nfrom .mapping import get_message_class\nfrom .parser import read_number\nfrom .parser import write_number\n\n\nclass Frame(object):\n \"\"\"Perform operations on a single TChannel frame.\"\"\"\n SIZE_WIDTH = 2\n ID_WIDTH = 4\n TYPE_WIDTH = 1\n FLAGS_WIDTH = 1\n PRELUDE_SIZE = 0x10 # this many bytes of framing before payload\n\n # 8 bytes are reserved\n RESERVED_WIDTH = 8\n RESERVED_PADDING = b'\\x00' * RESERVED_WIDTH\n\n BEFORE_ID_WIDTH = 1\n BEFORE_ID_PADDING = b'\\x00' * BEFORE_ID_WIDTH\n\n def __init__(self, message, message_id):\n self._message = message\n self._message_id = message_id\n\n @classmethod\n def decode(cls, stream, message_length=None):\n \"\"\"Decode a sequence of bytes into a frame and message.\n\n :param stream: a byte stream\n :param message_length: length of the message in bytes including framing\n \"\"\"\n if message_length is None:\n message_length = read_number(stream, cls.SIZE_WIDTH)\n\n if message_length < cls.PRELUDE_SIZE:\n raise ProtocolException(\n 'Illegal frame length: %d' % message_length\n )\n\n message_type = read_number(stream, cls.TYPE_WIDTH)\n message_class = get_message_class(message_type)\n if not message_class:\n raise ProtocolException('Unknown message type: %d' % message_type)\n\n # Throw away this many bytes\n stream.read(cls.BEFORE_ID_WIDTH)\n\n message_id = read_number(stream, cls.ID_WIDTH)\n\n stream.read(cls.RESERVED_WIDTH)\n\n message = message_class()\n remaining_bytes = message_length - cls.PRELUDE_SIZE\n if remaining_bytes:\n message.parse(stream, remaining_bytes)\n context = Context(message_id=message_id, message=message)\n return context\n\n def write(self, connection, callback=None):\n \"\"\"Write a frame out to a connection.\"\"\"\n payload = bytearray()\n self._message.serialize(payload)\n payload_length = len(payload)\n\n header_bytes = bytearray()\n\n header_bytes.extend(write_number(\n payload_length + self.PRELUDE_SIZE,\n self.SIZE_WIDTH\n ))\n\n header_bytes.extend(write_number(\n self._message.message_type,\n self.TYPE_WIDTH\n ))\n\n header_bytes.extend(self.BEFORE_ID_PADDING)\n\n header_bytes.extend(write_number(\n self._message_id,\n self.ID_WIDTH\n ))\n\n # 8 bytes of reserved data\n header_bytes.extend(self.RESERVED_PADDING)\n\n # Then the payload\n header_bytes.extend(payload)\n return connection.write(header_bytes, callback=callback)\n","sub_path":"python/tchannel/frame.py","file_name":"frame.py","file_ext":"py","file_size_in_byte":2788,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"236490582","text":"import tensorflow as tf\nimport json\nimport cv2\nimport os\nimport random\nimport sys\n\npro_dir = '/home/lijin/PycharmProjects/CRNN_CTC/'\nlabel_dir = pro_dir + '/json/label.json'\nmap_dir = pro_dir + '/json/char_map.json'\ndata_dir = pro_dir + 'data'\n\nimg_height = 32\nvalidation_split_fraction = 0.1\n\n\ndef _int64_feature(value):\n if not isinstance(value, list):\n value = [value]\n return tf.train.Feature(tf.train.Int64List(value))\n\n\ndef _bytes_feature(value):\n if not isinstance(value, list):\n value = [value]\n return tf.train.Feature(tf.train.BytesList(value))\n\n\ndef _label_to_string(label):\n with open(map_dir, 'r') as f:\n map_dict = json.load(f)\n int_list = []\n for c in label:\n map_dict[c] = len(map_dict)\n int_list.append(map_dict[c])\n\n return int_list\n\n\ndef _write_tfrecord(record_name, file_name_list):\n with tf.python_io.TFRecordWriter(pro_dir) as writer:\n f = open(label_dir, 'r')\n label_dict = json.load(f)\n for name in file_name_list:\n image_path = data_dir + '/' + name\n image = cv2.imread(image_path)\n label = label_dict[name]\n if image is None:\n continue\n h, w, c = image.shape\n width = int(w * img_height / h)\n cv2.resize(image, (width, img_height))\n is_success, image_buffer = cv2.imencode('.jpg', image)\n if not is_success:\n continue\n features = tf.train.Features(feature={\n 'label': _int64_feature(_label_to_string(label)),\n 'images': _bytes_feature(image_buffer.tostring()),\n 'imgname': _bytes_feature(name)\n })\n example = tf.train.Example(features=features)\n writer.write(example.SerializeToString())\n sys.stdout.write('\\r>>Writing to {:s}.tfrecords'.format(record_name))\n sys.stdout.flush()\n sys.stdout.write('\\n')\n sys.stdout.write('>> {:s}.tfrecords write finish.'.format(record_name))\n sys.stdout.flush()\n f.close()\n\n\ndef genetate_tfrecord():\n file_name_list = os.listdir(data_dir)\n random.shuffle(file_name_list)\n split_index = int(len(file_name_list) * (1 - validation_split_fraction))\n data_divide = {'train': file_name_list[:split_index - 1],\n 'validation': file_name_list[split_index:]}\n for name in ['train', 'validation']:\n _write_tfrecord(name, data_divide[name])\n","sub_path":"test/test4.py","file_name":"test4.py","file_ext":"py","file_size_in_byte":2508,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"206101738","text":"# Author: Christian Brodbeck \n\"\"\"Statistical tests for univariate variables\"\"\"\nimport itertools\n\nimport numpy as np\nimport scipy.stats\n\nfrom .. import fmtxt\nfrom .._celltable import Celltable\nfrom .._data_obj import (\n Dataset, Factor, Interaction, Var, NDVar,\n ascategorial, asfactor, asnumeric, assub, asvar,\n cellname, dataobj_repr, nice_label,\n)\nfrom .permutation import resample\nfrom . import stats\n\n\n__test__ = False\nDEFAULT_LEVELS = {.05: '*', .01: '**', .001: '***'}\nDEFAULT_LEVELS_TREND = {.05: '*', .01: '**', .001: '***', .1: '`'}\n\n\nclass Correlation(object):\n \"\"\"Pearson product moment correlation between y and x\n\n Parameters\n ----------\n y : Var | NDVar\n First variable.\n x : Var | NDVar\n Second variable. Needs to have same type/shape as ``y``.\n sub : index\n Use only a subset of the data\n ds : Dataset\n If a Dataset is given, all data-objects can be specified as names of\n Dataset variables.\n\n Attributes\n ----------\n r : float\n Pearson correlation coefficient.\n p : float\n Two-tailed p-value.\n df : int\n Degrees of freedom.\n \"\"\"\n def __init__(self, y, x, sub=None, ds=None):\n sub = assub(sub, ds)\n y = asnumeric(y, sub, ds)\n x = asnumeric(x, sub, ds)\n if type(y) is not type(x):\n raise TypeError(\"y and x must be same type; got type(y)=%r, \"\n \"type(x)=%r\" % (type(y), type(x)))\n elif isinstance(y, Var):\n x_y = y.x\n x_x = x.x\n elif isinstance(y, NDVar):\n if y.dims != x.dims:\n raise ValueError(\"y and x have different dimensions; \"\n \"y.dims=%r, x.dims=%r\" % (y.dims, x.dims))\n x_y = y.x.ravel()\n x_x = x.x.ravel()\n else:\n raise RuntimeError(\"y=%r\" % (y,))\n self.r, self.p, self.df = _corr(x_y, x_x)\n self._y = dataobj_repr(y)\n self._x = dataobj_repr(x)\n\n def __repr__(self):\n return (\"\" %\n (self._y, self._x, self.df, self.r, self.p))\n\n\ndef lilliefors(data, formatted=False, **kwargs):\n \"\"\"Lilliefors' test for normal distribution\n\n The Lilliefors test is an adaptation of the Kolmogorov-Smirnov test. It\n is used to test the null hypothesis that data come from a normally\n distributed population, when the null hypothesis does not specify which\n normal distribution, i.e. does not specify the expected value and variance.\n\n Parameters\n ----------\n data : array_like\n\n formatted : bool\n Return a single string with the results instead of the numbers.\n kwargs :\n All keyword arguments are forwarded to :func:`scipy.stats.kstest`.\n\n Returns\n -------\n D : float\n The D-value of the Kolmogorov-Smirnov Test\n p_estimate : float\n The approximate p value according to Dallal and Wilkinson (1986).\n Requires minimal sample size of 5. p is reasonably accurate only when\n it is <= .1 (cf. Dallal and Wilkens).\n\n Notes\n -----\n Uses the scipy.stats.kstest implementation of the Kolmogorov-Smirnov test.\n\n References\n ----------\n Dallal, G. E. and Wilkinson, L. (1986). An Analytic Approximation to the\n Distribution of Lilliefors's Test Statistic for Normality. The\n American Statistician, 40(4), 294--296.\n Lilliefors, H. W. (1967). On the Kolmogorov-Smirnov Test for Normality\n with Mean and Variance Unknown. Journal of the American\n Statistical Association, 62(318), 399--402.\n \"\"\"\n # p values agree with R lillie.test (nortest package) on low values of p.\n # lillie.test adjusts something at p>.1\n # http://pbil.univ-lyon1.fr/library/nortest/R/nortest\n data = np.asarray(data)\n N = len(data) # data.shape[-1] #axis]\n assert N >= 5, \"sample size must be greater than 4\"\n # perform Kolmogorov-Smirnov with estimated mean and std\n m = np.mean(data) # , axis=axis)\n s = np.std(data, ddof=1) # , axis=axis)\n D, ks_p = scipy.stats.kstest(data, 'norm', args=(m, s), **kwargs)\n # approximate p (Dallal)\n if N > 100:\n D *= (N / 100) ** .49\n N = 100\n p_estimate = np.exp(- 7.01256 * D ** 2 * (N + 2.78019)\n + 2.99587 * D * (N + 2.78019) ** .5\n - .122119\n + .974598 / (N ** .5)\n + 1.67997 / N)\n # approximate P (Molin & Abdi)\n L = D # ???\n b2 = 0.08861783849346\n b1 = 1.30748185078790\n b0 = 0.37872256037043\n A = (-(b1 + N) + np.sqrt((b1 + N) ** 2 - 4 * b2 * (b0 - L ** -2))) / 2 * b2\n Pr = (-.37782822932809\n + 1.67819837908004 * A\n - 3.02959249450445 * A ** 2\n + 2.80015798142101 * A ** 3\n - 1.39874347510845 * A ** 4\n + 0.40466213484419 * A ** 5\n - 0.06353440854207 * A ** 6\n + 0.00287462087623 * A ** 7\n + 0.00069650013110 * A ** 8\n - 0.00011872227037 * A ** 9\n + 0.00000575586834 * A ** 10)\n if formatted:\n txt = \"D={0:.4f}, Dallal p={1:.4f}, Molin&Abdi p={2:.4f}\"\n return txt.format(D, p_estimate, Pr)\n else:\n return D, p_estimate\n\n\ndef _hochberg_threshold(N, alpha=.05):\n j = np.arange(N)\n threshold = alpha / (N - j)\n return threshold\n\n\ndef mcp_adjust(ps, method='Hochberg'):\n \"\"\"Adjust p-values for multiple comparison\n\n Parameters\n ----------\n ps : sequence of scalar\n P-values.\n method : 'hochberg' | 'bonferroni' | 'holm'\n Correction method. Default is 'hochberg'.\n\n Returns\n -------\n adjusted_ps : list of scalar\n Adjusted p-values.\n \"\"\"\n n = len(ps)\n if n <= 1:\n return ps\n method_ = method.lower()\n if method_ == 'bonferroni':\n ps_adjusted = [p * n for p in ps]\n elif method_ in ('hochberg', 'holm'):\n ascsort = np.argsort(ps)\n ps_asc = np.array(ps)[ascsort]\n iout_asc = np.arange(n)[ascsort]\n ps_adjusted = [-1] * n\n p_buffer = 1\n if method_ == 'holm':\n for i in range(n):\n p = ps_asc[i]\n p_adj = (n - i) * p\n p_buffer = max(p_buffer, p_adj)\n ps_adjusted[iout_asc[i]] = p_buffer\n elif method_ == 'hochberg':\n for i in range(1, n + 1):\n p = ps_asc[-i]\n p_adj = (i) * p\n p_buffer = min(p_adj, p_buffer)\n ps_adjusted[iout_asc[-i]] = p_buffer\n else:\n msg = ('%r is not a valid argument for multiple comparison correction '\n 'method' % method)\n raise ValueError(msg)\n\n return ps_adjusted\n\n\ndef _get_correction_caption(corr, n):\n if corr == 'Hochberg':\n return \"(* Corrected after Hochberg, 1988)\"\n elif corr == 'Bonferroni':\n return \"(* Bonferroni corrected for %i tests)\" % n\n elif corr == 'Holm':\n return \"(* Corrected after Holm)\"\n else:\n return \"(* Uncorrected)\"\n\n\ndef _n_stars(p, levels):\n return sum(p <= l for l in levels)\n\n\ndef star(p_list, out=str, levels=True, trend=False, eq_strlen=False):\n \"\"\"Determine number of stars for p-value\n\n Parameters\n ----------\n p_list : sequence of scalar\n P-values.\n out : {str, int}\n Return string with stars ('**') or an integer indicating the number of\n stars.\n levels : dict\n ``{p: str, ...}`` dictionary. The default is ``{.05 : '*',\n .01 : '**', .001: '***'}``; ``trend=True`` adds ``{.1: \"'\"}``.\n trend : bool\n Add trend to default ``levels`` (default ``False``).\n eq_strlen : bool\n Equalize string lengths; when strings are returned, make sure they all\n have the same length (default ``False``).\n \"\"\"\n # set default levels\n if levels is True:\n if trend is True:\n levels = DEFAULT_LEVELS_TREND\n elif trend:\n levels = DEFAULT_LEVELS.copy()\n levels[.1] = trend\n else:\n levels = DEFAULT_LEVELS\n elif trend:\n raise TypeError(\"trend=%r only valid when levels=True\" % (trend,))\n\n levels_descending = sorted(levels.keys(), reverse=True)\n symbols_descending = [''] + [levels[l] for l in levels_descending]\n\n if out is int:\n int_out = True\n elif out is str:\n int_out = False\n else:\n raise TypeError(\"out=%r\" % (out,))\n\n # allow input (p_list) to contain single p-value\n if not np.iterable(p_list):\n n = _n_stars(p_list, levels)\n if int_out:\n return out\n else:\n return symbols_descending[n]\n\n ns = [_n_stars(p, levels) for p in p_list]\n if int_out:\n return ns\n symbols = [symbols_descending[n] for n in ns]\n if eq_strlen:\n maxlen = max(map(len, symbols))\n return [s.ljust(maxlen) for s in symbols]\n else:\n return symbols\n\n\ndef star_factor(p, levels={.1: '`', .05: '*', .01: '**', .001: '***'}):\n \"\"\"Create a factor with stars for a sequence of p-values\n\n Parameters\n ----------\n p : sequence of scalar\n Sequence of p-values.\n levels : dict {scalar: str}\n {value: star-mark} dictionary.\n\n Returns\n -------\n stars : Factor\n Factor with the appropriate star marking for each item in p.\n \"\"\"\n sorted_levels = sorted(levels, reverse=True)\n star_labels = {i: levels[v] for i, v in enumerate(sorted_levels, 1)}\n star_labels[0] = ''\n level_values = np.reshape(sorted_levels, (-1, 1))\n return Factor(np.sum(p < level_values, 0), labels=star_labels)\n\n\ndef ttest(y, x=None, against=0, match=None, sub=None, corr='Hochberg',\n title='{desc}', ds=None):\n \"\"\"T-tests for one or more samples\n\n parameters\n ----------\n y : Var\n Dependent variable\n x : None | categorial\n Perform tests separately for all categories in x.\n against : scalar | str | tuple\n Baseline against which to test (scalar or category in x).\n match : None | Factor\n Repeated measures factor.\n sub : index\n Only use part of the data.\n corr : None | 'hochberg' | 'bonferroni' | 'holm'\n Method for multiple comparison correction (default 'hochberg').\n title : str\n Title for the table.\n ds : None | Dataset\n If a Dataset is given, all data-objects can be specified as names of\n Dataset variables\n\n Returns\n -------\n table : FMText Table\n Table with results.\n \"\"\"\n ct = Celltable(y, x, match, sub, ds=ds, coercion=asvar)\n\n par = True\n if par:\n infl = '' if x is None else 's'\n if ct.y.name is None:\n title_desc = \"T-test%s against %s\" % (infl, cellname(against))\n else:\n title_desc = \"T-test%s of %s against %s\" % (infl, ct.y.name, cellname(against))\n statistic_name = 't'\n else:\n raise NotImplementedError\n\n names = []\n diffs = []\n ts = []\n dfs = []\n ps = []\n\n if isinstance(against, (str, tuple)):\n if against not in ct.cells:\n x_repr = 'x' if ct.x.name is None else repr(ct.x.name)\n raise ValueError(\"agains=%r: %r is not a cell in %s\"\n % (against, against, x_repr))\n k = len(ct.cells) - 1\n baseline = ct.data[against]\n\n for cell in ct.cells:\n if cell == against:\n continue\n names.append(cell)\n if match is not None and ct.within[cell, against]:\n diffs.append(ct.data[cell].mean() - baseline.mean())\n t, p = scipy.stats.ttest_rel(ct.data[cell], baseline)\n df = len(baseline) - 1\n else:\n data = ct.data[cell]\n diffs.append(data.mean() - baseline.mean())\n t, p = scipy.stats.ttest_ind(data, baseline)\n df = len(baseline) + len(data) - 2\n ts.append(t)\n dfs.append(df)\n ps.append(p)\n\n elif np.isscalar(against):\n k = len(ct.cells)\n\n for cell in ct.cells:\n label = cellname(cell)\n data = ct.data[cell].x\n t, p = scipy.stats.ttest_1samp(data, against)\n df = len(data) - 1\n names.append(label)\n diffs.append(data.mean() - against)\n ts.append(t)\n dfs.append(df)\n ps.append(p)\n else:\n raise TypeError(\"against=%s\" % repr(against))\n\n if k <= 1:\n corr = None\n\n if corr:\n ps_adjusted = mcp_adjust(ps, corr)\n else:\n ps_adjusted = ps\n stars = star(ps_adjusted, out=str)\n if len(set(dfs)) == 1:\n df_in_header = True\n else:\n df_in_header = False\n\n table = fmtxt.Table('l' + 'r' * (4 - df_in_header + bool(corr)))\n table.title(title.format(desc=title_desc))\n if corr:\n table.caption(_get_correction_caption(corr, k))\n\n # header\n table.cell(\"Effect\")\n table.cell(\"Difference\")\n if df_in_header:\n table.cell(fmtxt.symbol(statistic_name, dfs[0]))\n else:\n table.cell(statistic_name, 'math')\n table.cell('df', 'math')\n table.cell('p', 'math')\n if corr:\n table.cell(fmtxt.symbol('p', corr))\n table.midrule()\n\n # body\n for name, diff, t, mark, df, p, p_adj in zip(names, diffs, ts, stars, dfs, ps, ps_adjusted):\n table.cell(name)\n table.cell(diff)\n table.cell(fmtxt.stat(t, stars=mark, of=3))\n if not df_in_header:\n table.cell(df)\n\n table.cell(fmtxt.p(p))\n if corr:\n table.cell(fmtxt.p(p_adj))\n return table\n\n\nclass TTest1Sample(object):\n \"\"\"1-sample t-test\n\n Parameters\n ----------\n y : Var\n Dependent variable.\n match : categorial\n Units within which measurements are related (e.g. 'subject' in a\n within-subject comparison).\n sub : None | index-array\n Perform the test with a subset of the data.\n ds : None | Dataset\n If a Dataset is specified, all data-objects can be specified as\n names of Dataset variables.\n tail : 0 | 1 | -1\n Which tail of the t-distribution to consider:\n 0: both (two-tailed, default);\n 1: upper tail (one-tailed);\n -1: lower tail (one-tailed).\n\n Attributes\n ----------\n mean : float\n Mean of ``y``.\n t : float\n T-value.\n p : float\n P-value.\n tail : 0 | 1 | -1\n Tailedness of the p value.\n df : int\n Degrees of freedom.\n \"\"\"\n def __init__(self, y, match=None, sub=None, ds=None, tail=0):\n ct = Celltable(y, None, match, sub, ds=ds, coercion=asvar)\n n = len(ct.y)\n if n <= 2:\n raise ValueError(\"Not enough observations for t-test (n=%i)\" % n)\n\n self.mean = ct.y.mean()\n self._y = dataobj_repr(ct.y)\n self.df = n - 1\n self.t = stats.t_1samp(ct.y.x[:, None])[0]\n self.p = stats.ttest_p(self.t, self.df, tail)\n self.tail = tail\n\n def __repr__(self):\n out = \"\" % (self.df, self.t, self.p)\n return out\n\n def _asfmtext(self):\n return fmtxt.FMText([fmtxt.eq('t', self.t, self.df), ', ',\n fmtxt.peq(self.p)])\n\n\nclass TTestInd(object):\n \"\"\"Related-measures t-test\n\n Parameters\n ----------\n y : Var\n Dependent variable.\n x : categorial\n Model containing the cells which should be compared.\n c1 : str | tuple | None\n Test condition (cell of ``x``). ``c1`` and ``c0`` can be omitted if\n ``x`` only contains two cells, in which case cells will be used in\n alphabetical order.\n c0 : str | tuple | None\n Control condition (cell of ``x``).\n match : categorial\n Units within which measurements are related and should be averaged over\n (e.g. 'subject' in a between-group comparison).\n sub : None | index-array\n Perform the test with a subset of the data.\n ds : None | Dataset\n If a Dataset is specified, all data-objects can be specified as\n names of Dataset variables.\n tail : 0 | 1 | -1\n Which tail of the t-distribution to consider:\n 0: both (two-tailed, default);\n 1: upper tail (one-tailed);\n -1: lower tail (one-tailed).\n\n Attributes\n ----------\n t : float\n T-value.\n p : float\n P-value.\n tail : 0 | 1 | -1\n Tailedness of the p value.\n df : int\n Degrees of freedom.\n \"\"\"\n def __init__(self, y, x, c1=None, c0=None, match=None, sub=None, ds=None,\n tail=0):\n ct = Celltable(y, x, match, sub, cat=(c1, c0), ds=ds, coercion=asvar)\n c1, c0 = ct.cat\n\n n = len(ct.y)\n if n <= 2:\n raise ValueError(\"Not enough observations for t-test (n=%i)\" % n)\n\n self._y = dataobj_repr(ct.y)\n self._x = dataobj_repr(ct.x)\n self.df = n - 2\n groups = ct.x == c1\n groups.dtype = np.int8\n self.t = stats.t_ind(ct.y.x[:, None], groups)[0]\n self.p = stats.ttest_p(self.t, self.df, tail)\n self.tail = tail\n self._c1 = c1\n self._c0 = c0\n\n def __repr__(self):\n return (\"\" %\n (self._y, self._x, self._c1, '=><'[self.tail], self._c0,\n self.df, self.t, self.p))\n\n def _asfmtext(self):\n return fmtxt.FMText([fmtxt.eq('t', self.t, self.df), ', ',\n fmtxt.peq(self.p)])\n\n\nclass TTestRel(object):\n \"\"\"Related-measures t-test\n\n Parameters\n ----------\n y : Var\n Dependent variable. Alternatively, the first of two variables that are\n compared.\n x : categorial\n Model containing the cells which should be compared. Alternatively, the\n second of two varaibles that are compared.\n c1 : str | tuple | None\n Test condition (cell of ``x``). ``c1`` and ``c0`` can be omitted if\n ``x`` only contains two cells, in which case cells will be used in\n alphabetical order.\n c0 : str | tuple | None\n Control condition (cell of ``x``).\n match : categorial\n Units within which measurements are related (e.g. 'subject' in a\n within-subject comparison). If match is unspecified, it is assumed that\n ``y`` and ``x`` are two measurements with matched cases.\n sub : None | index-array\n Perform the test with a subset of the data.\n ds : None | Dataset\n If a Dataset is specified, all data-objects can be specified as\n names of Dataset variables.\n tail : 0 | 1 | -1\n Which tail of the t-distribution to consider:\n 0: both (two-tailed, default);\n 1: upper tail (one-tailed);\n -1: lower tail (one-tailed).\n\n Attributes\n ----------\n t : float\n T-value.\n p : float\n P-value.\n tail : 0 | 1 | -1\n Tailedness of the p value.\n difference : Var\n Difference values.\n df : int\n Degrees of freedom.\n c1_mean : float\n Mean of condition ``c1``.\n c0_mean : float\n Mean of condition ``c0``.\n \"\"\"\n def __init__(self, y, x, c1=None, c0=None, match=None, sub=None, ds=None,\n tail=0):\n if match is None:\n assert c1 is None and c0 is None\n y1 = asvar(y, sub, ds)\n n = len(y1)\n y0 = asvar(x, sub, ds, n)\n self._y = dataobj_repr(y1)\n self._x = dataobj_repr(y0)\n else:\n ct = Celltable(y, x, match, sub, cat=(c1, c0), ds=ds, coercion=asvar)\n c1, c0 = ct.cat\n if not ct.all_within:\n raise ValueError(\"conditions %r and %r do not have the same values \"\n \"on %s\" % (c1, c0, dataobj_repr(ct.match)))\n\n n = len(ct.y) // 2\n self._y = dataobj_repr(ct.y)\n self._x = dataobj_repr(ct.x)\n y1 = ct.y[:n]\n y0 = ct.y[n:]\n if n <= 2:\n raise ValueError(\"Not enough observations for t-test (n=%i)\" % n)\n\n self.c1_mean = y1.mean()\n self.c0_mean = y0.mean()\n self.difference = y1 - y0\n self.df = n - 1\n self.t = stats.t_1samp(self.difference.x[:, None])[0]\n self.p = stats.ttest_p(self.t, self.df, tail)\n self.tail = tail\n self._match = None if match is None else dataobj_repr(match)\n self._c1 = c1\n self._c0 = c0\n\n def __repr__(self):\n cmp = '=><'[self.tail]\n if self._match is None:\n out = f\"\"\n\n def _asfmtext(self):\n return fmtxt.FMText([fmtxt.eq('t', self.t, self.df), ', ',\n fmtxt.peq(self.p)])\n\n\ndef pairwise(y, x, match=None, sub=None, ds=None, # data in\n par=True, corr='Hochberg', trend=True, # stats\n title='{desc}', mirror=False, # layout\n ):\n \"\"\"Pairwise comparison table\n\n Parameters\n ----------\n y : Var\n Dependent measure.\n x : categorial\n Categories to compare.\n match : None | Factor\n Repeated measures factor.\n sub : None | index-array\n Perform tests with a subset of the data.\n ds : Dataset\n If a Dataset is given, all data-objects can be specified as names of\n Dataset variables.\n\n Returns\n -------\n table : FMText Table\n Table with results.\n \"\"\"\n ct = Celltable(y, x, match=match, sub=sub, ds=ds, coercion=asvar)\n test = _pairwise(ct.get_data(), within=ct.all_within, parametric=par,\n corr=corr, trend=trend)\n\n # extract test results\n k = len(ct)\n indexes = test['pw_indexes']\n statistic = test['statistic']\n _K = test[statistic]\n _P = test['p']\n if corr:\n _Pc = mcp_adjust(_P, corr)\n _df = test['df']\n symbols = test['symbols']\n\n # create TABLE\n table = fmtxt.Table('l' + 'l' * (k - 1 + mirror))\n title_desc = \"Pairwise {0}\".format(test['test'])\n table.title(title.format(desc=title_desc))\n table.caption(test['caption'])\n\n # headings\n table.cell()\n cellnames = ct.cellnames()\n for name in cellnames[1 - mirror:]:\n table.cell(name)\n table.midrule()\n\n # tex_df = fmtxt.Element(df, \"_\", digits=0)\n if corr and not mirror:\n subrows = 3\n else:\n subrows = 2\n\n for row in range(0, k - 1 + mirror):\n for subrow in range(subrows): # contains t/p\n # names column\n if subrow == 0:\n table.cell(cellnames[row])\n else:\n table.cell()\n # rows\n for col in range(1 - mirror, k):\n if row == col:\n table.cell()\n elif col > row:\n index = indexes[(row, col)]\n if subrow == 0:\n table.cell(fmtxt.eq(statistic, _K[index], _df[index],\n stars=symbols[index], of=3 + trend))\n elif subrow == 1:\n table.cell(fmtxt.peq(_P[index]))\n elif subrow == 2:\n table.cell(fmtxt.peq(_Pc[index], 'c'))\n elif mirror and corr and subrow == 0:\n index = indexes[(col, row)]\n table.cell(fmtxt.P(_Pc[index]))\n else:\n table.cell()\n return table\n\n\ndef _pairwise(data, within=True, parametric=True, corr='Hochberg',\n levels=True, trend=True):\n \"\"\"Pairwise tests\n\n Parameters\n ----------\n data\n list of groups/treatments\n corr : 'Hochberg' | 'Holm' | 'Bonferroni'\n MCP.\n\n Returns\n -------\n results : dict\n dictionary with results:\n 'test': test name\n 'caption': information about correction\n 'statistic': abbreviation used for the staistic (e.g. 'Q')\n statistic: list of values\n 'df': df\n 'p': list of corresponding pa values\n 'stars': list of n stars (ints)\n 'pw_indexes': dict linking table index (i,j) to the list index for p etc.\n \"\"\"\n # find test\n k = len(data)\n if k < 3: # need no correction for single test\n corr = None\n if parametric:\n test_name = \"t-Tests ({0} samples)\"\n statistic = \"t\"\n if within:\n test_func = scipy.stats.ttest_rel\n test_name = test_name.format('paired')\n else:\n test_func = scipy.stats.ttest_ind\n test_name = test_name.format('independent')\n elif within:\n test_name = \"Wilcoxon Signed-Rank Test\"\n test_func = scipy.stats.wilcoxon\n statistic = \"z\"\n else:\n test_name = \"Mann-Whitney U Test\"\n raise NotImplementedError(\"mannwhitneyu returns one-sided p\")\n test_func = scipy.stats.mannwhitneyu\n statistic = \"u\"\n\n # perform test\n _K = [] # kennwerte\n _P = []\n _df = []\n i = 0\n indexes = {}\n for x in range(k):\n for y in range(x + 1, k):\n Y1, Y2 = data[x], data[y]\n t, p = test_func(Y1, Y2)\n _K.append(t)\n if within:\n _df.append(len(Y1) - 1)\n else:\n _df.append(len(Y1) + len(Y2) - 2)\n\n _P.append(p)\n indexes[(x, y)] = indexes[(y, x)] = i\n i += 1\n # add stars\n if corr:\n p_adjusted = mcp_adjust(_P, corr)\n else:\n p_adjusted = _P\n _NStars = star(p_adjusted, int, levels, trend)\n _str_Stars = star(p_adjusted, str, levels, trend)\n caption = _get_correction_caption(corr, len(_P))\n # prepare output\n out = {'test': test_name,\n 'caption': caption,\n 'statistic': statistic,\n statistic: _K,\n 'df': _df,\n 'p': _P,\n 'stars': _NStars,\n 'symbols': _str_Stars,\n 'pw_indexes': indexes}\n return out\n\n\ndef pairwise_correlations(xs, sub=None, ds=None, labels={}):\n \"\"\"Pairwise correlation table\n\n Parameters\n ----------\n xs : sequence of Var | NDVar\n Variables to correlate.\n sub : index\n Use only a subset of the data\n ds : Dataset\n If a Dataset is given, all data-objects can be specified as names of\n Dataset variables.\n labels : {str: str} dict\n Labels for ``xs`` in the table (mapping ``x.name`` to string labels).\n\n Returns\n -------\n pairwise_table : fmtxt.Table\n Table with pairwise correlations.\n \"\"\"\n sub = assub(sub, ds)\n x_rows = [asnumeric(x, sub, ds) for x in xs]\n n_vars = len(x_rows)\n\n table = fmtxt.Table('l' + 'c' * n_vars)\n # header\n table.cell()\n for i in range(1, n_vars + 1):\n table.cell(i)\n table.midrule()\n # body\n for i_row, x_row in enumerate(x_rows):\n label = nice_label(x_row, labels)\n table.cell(\"%i %s\" % (i_row + 1, label))\n for x_col in x_rows:\n if x_col is x_row:\n table.cell()\n else:\n corr = Correlation(x_row, x_col)\n table.cell(fmtxt.stat(corr.r, drop0=True))\n table.endline()\n return table\n\n\ndef correlations(y, x, cat=None, sub=None, ds=None, asds=False):\n \"\"\"Correlation with one or more predictors\n\n Parameters\n ----------\n y : Var\n First variable\n x : Var | list of Var\n second variable (or list of variables).\n cat : categorial\n Show correlations separately for different groups in the data.\n sub : index\n Use only a subset of the data\n ds : Dataset\n If a Dataset is given, all data-objects can be specified as names of\n Dataset variables.\n asds : bool\n Return correlations in Dataset instead of Table.\n\n Returns\n -------\n correlations : Table | Dataset\n Table or Dataset (if ``asds=True``) with correlations.\n \"\"\"\n sub = assub(sub, ds)\n y = asvar(y, sub, ds)\n if isinstance(x, (Var, str)):\n x = (x,)\n print_x_name = False\n else:\n print_x_name = True\n x = [asvar(x_, sub, ds) for x_ in x]\n if cat is None:\n cat_cells = [None]\n n_cat = 1\n else:\n cat = ascategorial(cat, sub, ds)\n cat_cells = cat.cells\n n_cat = len(cat.cells)\n\n # correlation Dataset, nested:\n # x -> cat\n ds = Dataset()\n if print_x_name:\n ds['x'] = Factor([dataobj_repr(x_) for x_ in x], repeat=n_cat)\n\n if n_cat > 1:\n if isinstance(cat, Interaction):\n cat_names = [dataobj_repr(c) for c in cat.base]\n for i, name in enumerate(cat_names):\n ds[name] = Factor([cell[i] for cell in cat.cells], tile=len(x))\n elif isinstance(cat, Factor):\n cat_names = (dataobj_repr(cat),)\n ds[dataobj_repr(cat)] = Factor(cat.cells)\n else:\n raise TypeError(repr(cat))\n else:\n cat_names = ()\n\n rs = []\n dfs = []\n ps = []\n for x_ in x:\n for cell in cat_cells:\n if cell is None:\n r, p, df = _corr(y.x, x_.x)\n else:\n sub = cat == cell\n r, p, df = _corr(y[sub].x, x_[sub].x)\n rs.append(r)\n dfs.append(df)\n ps.append(p)\n ds['r'] = Var(rs)\n ds['df'] = Var(dfs)\n p = Var(ps)\n ds['sig'] = star_factor(p)\n ds['p'] = p\n if asds:\n return ds\n\n table = fmtxt.Table('l' * (4 + print_x_name + len(cat_names)),\n title=\"Correlations with %s\" % dataobj_repr(y))\n if print_x_name:\n table.cell('x')\n table.cells(*cat_names)\n table.cells('r', 'df', '*' 'p')\n table.midrule()\n last_x = None\n for case in ds.itercases():\n if print_x_name:\n if case['x'] == last_x:\n table.cell('')\n else:\n table.cell(case['x'])\n last_x = case['x']\n for name in cat_names:\n table.cell(case[name])\n table.cell(fmtxt.stat(case['r'], '%.3f', drop0=True))\n table.cell(case['df'])\n table.cell(case['sig'])\n table.cell(fmtxt.p(case['p']))\n return table\n\n\ndef _corr(y, x):\n n = len(y)\n assert len(x) == n\n df = n - 2\n r = np.corrcoef(y, x)[0, 1]\n if r == 1:\n return r, 0., df\n t = r / np.sqrt((1 - r ** 2) / df)\n p = scipy.stats.t.sf(np.abs(t), df) * 2\n return r, p, df\n\n\nclass bootstrap_pairwise(object):\n def __init__(self, y, x, match=None, sub=None,\n samples=1000, replacement=True,\n title=\"Bootstrapped Pairwise Tests\", ds=None):\n sub = assub(sub, ds)\n y = asvar(y, sub, ds)\n x = asfactor(x, sub, ds)\n assert len(y) == len(x), \"data length mismatch\"\n if match is not None:\n match = ascategorial(match, sub, ds)\n assert len(match) == len(y), \"data length mismatch\"\n\n # prepare data container\n resampled = np.empty((samples + 1, len(y))) # sample x subject within category\n resampled[0] = y.x\n # fill resampled\n for i, y_i in enumerate(resample(y, samples, replacement, match), 1):\n resampled[i] = y_i.x\n self.resampled = resampled\n\n cells = x.cells\n n_groups = len(cells)\n\n if match is not None:\n # if there are several values per x%match cell, take the average\n # T: indexes to transform y.x to [x%match, value]-array\n match_cell_ids = match.cells\n group_size = len(match_cell_ids)\n T = None\n i = 0\n for x_cell in cells:\n for match_cell in match_cell_ids:\n source_indexes = np.where((x == x_cell) * (match == match_cell))[0]\n if T is None:\n n_cells = n_groups * group_size\n T = np.empty((n_cells, len(source_indexes)), dtype=int)\n T[i, :] = source_indexes\n i += 1\n\n if T.shape[1] == 1:\n T = T[:, 0]\n ordered = resampled[:, T]\n else:\n ordered = resampled[:, T].mean(axis=2)\n self.ordered = ordered\n\n # t-tests\n n_comparisons = sum(range(n_groups))\n t = np.empty((samples + 1, n_comparisons))\n comp_names = []\n one_group = np.arange(group_size)\n groups = [one_group + i * group_size for i in range(n_groups)]\n for i, (g1, g2) in enumerate(itertools.combinations(range(n_groups), 2)):\n group_1 = groups[g1]\n group_2 = groups[g2]\n diffs = ordered[:, group_1] - ordered[:, group_2]\n t[:, i] = (np.mean(diffs, axis=1) * np.sqrt(group_size) /\n np.std(diffs, axis=1, ddof=1))\n comp_names.append(' - '.join((cells[g1], cells[g2])))\n\n self.diffs = diffs\n self.t_resampled = np.max(np.abs(t[1:]), axis=1)\n self.t = t = t[0]\n else:\n raise NotImplementedError\n\n self._Y = y\n self._X = x\n self._group_names = cells\n self._group_data = np.array([ordered[0, g] for g in groups])\n self._group_size = group_size\n self._df = group_size - 1\n self._match = match\n self._n_samples = samples\n self._replacement = replacement\n self._comp_names = comp_names\n self._p_parametric = self.test_param(t)\n self._p_boot = self.test_boot(t)\n self.title = title\n\n def __repr__(self):\n out = ['bootstrap_pairwise(', self._Y.name, self._X.name]\n if self._match:\n out.append('match=%s ' % self._match.name)\n out.append('saples=%i ' % self._n_samples)\n out.append('replacement=%s)' % self._replacement)\n return ''.join(out)\n\n def __str__(self):\n return str(self.table())\n\n def table(self):\n table = fmtxt.Table('lrrrr')\n table.title(self.title)\n table.caption(\"Results based on %i samples\" % self._n_samples)\n table.cell('Comparison')\n table.cell(fmtxt.symbol('t', self._df))\n table.cell(fmtxt.symbol('p', 'param'))\n table.cell(fmtxt.symbol('p', 'corr'))\n table.cell(fmtxt.symbol('p', 'boot'))\n table.midrule()\n\n p_corr = mcp_adjust(self._p_parametric)\n stars_parametric = star(p_corr)\n stars_boot = star(self._p_boot)\n\n for name, t, p1, pc, s1, p2, s2 in zip(self._comp_names, self.t,\n self._p_parametric, p_corr,\n stars_parametric,\n self._p_boot, stars_boot):\n table.cell(name)\n table.cell(t, fmt='%.2f')\n table.cell(fmtxt.p(p1))\n table.cell(fmtxt.p(pc, stars=s1))\n table.cell(fmtxt.p(p2, stars=s2))\n return table\n\n def plot_t_dist(self):\n # http://stackoverflow.com/questions/4150171/how-to-create-a-density-plot-in-matplotlib\n from matplotlib import pyplot\n\n t = self.t_resampled\n density = scipy.stats.gaussian_kde(t)\n# density.covariance_factor = lambda : .25\n# density._compute_covariance()\n xs = np.linspace(0, max(t), 200)\n pyplot.plot(xs, density(xs))\n\n def plot_dv_dist(self):\n from matplotlib import pyplot\n\n xs = np.linspace(np.min(self._group_data), np.max(self._group_data), 200)\n for i, name in enumerate(self._group_names):\n density = scipy.stats.gaussian_kde(self._group_data[i])\n pyplot.plot(xs, density(xs), label=name)\n pyplot.legend()\n\n def test_param(self, t):\n return scipy.stats.t.sf(np.abs(t), self._group_size - 1) * 2\n\n def test_boot(self, t):\n \"t: scalar or array; returns p for each t\"\n test = self.t_resampled[:, None] > np.abs(t)\n return np.sum(test, axis=0) / self.t_resampled.shape[0]\n","sub_path":"eelbrain/_stats/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":36272,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"486217103","text":"import unittest\nimport sys\nfrom unittest.mock import Mock, MagicMock\n\nsys.modules['pygame'] = MagicMock()\nimport pygame\n\nfrom src.Window import *\nfrom tests.GeneralTest import *\nfrom src.UI import *\n\n\nclass WindowTest(GeneralTest):\n\n def setUp(self):\n\n self.window = Window(self._mock_app(), 900, 600, 'Title')\n self.window.UI = MagicMock(UI)\n\n\n def tearDown(self):\n self.window = None\n\n def test_display(self):\n screen = Mock()\n\n screen.fill = MagicMock()\n self.window.screen = screen\n\n self.window.display()\n\n self.window.screen.fill.assert_called_with(self.window.colors['black'])\n self.window.app.game_objects['ball'].draw.assert_called()\n self.window.app.game_objects['platform'].draw.assert_called()\n self.window.app.game_objects['plates'][0].draw.assert_called()\n\nif __name__ == \"__main__\":\n unittest.main()\n","sub_path":"tests/unit/WindowTest.py","file_name":"WindowTest.py","file_ext":"py","file_size_in_byte":904,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"277130828","text":"import numpy as np\nimport theano\nimport theano.tensor as T\nfrom .rnn import RNN\nfrom ._utils import zero_wights, random_wights\n\nclass LSTM(RNN):\n def _init_params(self):\n self.U = random_wights((self._input_dim, 4*self._hidden_dim), 'U', dtype=self._dtype)\n self.W = random_wights((self._hidden_dim, 4*self._hidden_dim), 'W', dtype=self._dtype)\n self.BH = zero_wights((4*self._hidden_dim, ), 'BH', dtype=self._dtype)\n self.V = random_wights((self._hidden_dim, self._output_dim), 'V', dtype=self._dtype)\n self.BO = zero_wights((self._output_dim, ), 'BO', dtype=self._dtype)\n self._params.extend([self.U, self.W, self.BH, self.V, self.BO])\n\n def _gate_function(self, x):\n return T.nnet.sigmoid(x)\n\n def _activation_function(self, x):\n return T.tanh(x)\n\n def _forward_prop_hidden_step_function(self, x, h_last, c_last, U, W, B):\n p = T.dot(x, U) + T.dot(h_last, W) + B\n n = self._hidden_dim\n g_i = self._gate_function(p[:,0*n:1*n])\n g_f = self._gate_function(p[:,1*n:2*n])\n g_o = self._gate_function(p[:,2*n:3*n])\n c_new = self._activation_function(p[:,3*n:4*n])\n c = g_i * c_new + g_f * c_last\n h = g_o * self._activation_function(c)\n return h, c\n\n def _forward_prop_hidden_function(self, x, U, W, B):\n h_init = T.zeros((x.shape[1], self._hidden_dim), dtype=self._dtype)\n c_init = T.zeros((x.shape[1], self._hidden_dim), dtype=self._dtype)\n (h, _), _ = theano.scan(fn=self._forward_prop_hidden_step_function,\n sequences=[x],\n outputs_info=[h_init, c_init],\n non_sequences=[U, W, B],\n strict=True)\n return h\n","sub_path":"saraswati/layers/lstm.py","file_name":"lstm.py","file_ext":"py","file_size_in_byte":1771,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"452320440","text":"# -*- coding: utf-8 -*-\nfrom datetime import datetime, timedelta\nimport logging\nimport json\nimport networkx as nx\nimport traceback\n\nimport tempfile\nimport werkzeug.wrappers\n\nfrom odoo import http\nfrom odoo.http import request\nfrom odoo.exceptions import ValidationError\nfrom odoo.addons.web.controllers.main import DataSet, Action\nfrom odoo.addons.mail.controllers.main import MailController\n\nfrom odoo.tools import config\nimport odoo\nfrom odoo.http import content_disposition\n\n_logger = logging.getLogger(__name__)\n\n\nclass Approval(http.Controller):\n\n @http.route('/web/approval/get_approval_flow', type='json', auth=\"user\")\n def get_approval_info(self, model, res_id):\n \"\"\"是否显示提交审批按钮和审批流程信息\"\"\"\n def compute_approval_info():\n \"\"\"审批信息可编辑\"\"\"\n if res_state.approval_state != 'active':\n return False\n\n if approval.user_id.id != user_id:\n return False\n\n next_nodes = instance_node_obj.search([('instance_id', '=', instance.id), ('serial_num', '=', instance_node.serial_num + 1), ('state', '!=', 'turn_to')])\n if not next_nodes:\n return False\n\n for next_node in next_nodes:\n if approval_obj.search([('instance_node_id', '=', next_node.id)]):\n return False\n\n return True\n\n def can_approval_current_node():\n \"\"\"是否可以审批当前节点\"\"\"\n if res_state.approval_state == 'pause' or res_state.approval_state == 'cancel':\n return False\n\n # 状态不是正在审批的不能审批\n if instance_node.state != 'running':\n return False\n\n if user_id in [wait_approval.user_id.id for wait_approval in wait_approval_obj.search([('instance_node_id', '=', instance_node.id)])]:\n return True\n\n return False\n\n def compute_node_name():\n \"\"\"计算节点名称\"\"\"\n users = u','.join([wait_approval.user_id.name for wait_approval in wait_approval_obj.search([('instance_node_id', '=', instance_node.id)])])\n if is_increase:\n node_name = u'(加)%s(%s)' % (instance_node.node_id.name, users)\n elif is_turn_to:\n node_name = u'(转)%s(%s)' % (instance_node.node_id.name, users)\n else:\n node_name = u'%s(%s)' % (instance_node.node_id.name, users)\n\n return node_name\n\n def compute_allow_increase():\n \"\"\"计算当前节点是否允许加签\"\"\"\n if res_state.approval_state == 'pause' or res_state.approval_state == 'cancel':\n return False\n\n # 完成的节点或是加签的节点,不允许加签\n if instance_node.state == 'complete' or is_increase:\n return False\n\n # 当前节点不允许前加签和后加签,不允许加签\n if not node.allow_before_increase and not node.allow_after_increase:\n return False\n\n # 当前节点允许前加签且前加签存在,允许后加签且后加签存在,不允许加签\n exist_before_increase = instance_node_obj.search([('parent_id', '=', instance_node.id), ('increase_type', '=', 'before')]).exists() # 存在前加签\n exist_after_increase = instance_node_obj.search([('parent_id', '=', instance_node.id), ('increase_type', '=', 'after')]).exists() # 存在后加签\n\n if node.allow_before_increase and not node.allow_after_increase:\n if exist_before_increase:\n return False\n\n if not node.allow_before_increase and node.allow_after_increase:\n if exist_after_increase:\n return False\n\n if node.allow_before_increase and node.allow_after_increase:\n if exist_before_increase and exist_after_increase:\n return False\n\n if node.type == 'group':\n # 指定了用户\n if instance_node.group_user_id:\n if user_id == instance_node.group_user_id.id:\n return True\n return False\n\n # 当前用户不在当前节点对应的组中\n if user_id not in node.groups_id.sudo().users.ids:\n return False\n\n # 当前实例节点对应的节点仅能单据所在公司的用户审批\n if node.only_document_company:\n # 当前用户所属公司不等于单据所属公司,不能审批当前节点\n if document.company_id.id != user.company_id.id:\n return False\n\n\n return True\n\n if node.type == 'user':\n # 指定了用户\n if instance_node.user_user_id:\n if user_id == instance_node.user_user_id.id:\n return True\n return False\n\n # 当前实例节点仅限单据所在公司指定的用户审批\n if node.user_only_document_company:\n # 当前用户所属公司不等于单据所属公司,不能审批当前节点\n if document.company_id.id != user.company_id.id:\n return False\n\n if user_id not in node.user_ids.ids:\n return False\n\n return True\n\n if user_id not in node.user_ids.ids:\n return False\n\n return True\n\n if node.type == 'job':\n # 指定了用户\n if instance_node.job_user_id:\n if user_id == instance_node.job_user_id.id:\n return True\n return False\n\n # 当前用户没有关联的hr.employee\n employee = employee_obj.search([('user_id', '=', user_id)])\n if not employee:\n return False\n\n # 当前用户关联的员工对应的岗位不在节点指定的的审批岗位中\n if employee.job_id.id not in node.job_ids.ids:\n return False\n\n # 当前实例节点仅限单据所在公司指定的岗位审批\n if node.job_only_document_company:\n # 当前用户关联的员工所属公司不等于单所公司,不能审批节点\n if document.company_id.id != employee.company_id.id:\n return False\n\n return True\n\n return True\n\n if node.type == 'leader':\n # 当前用户没有关联的hr.employee,不能审批\n employee = employee_obj.search([('user_id', '=', user_id)])\n if not employee:\n return False\n\n if employee.id == document.employee_id.parent_id.id:\n return True\n\n return False\n\n return False\n\n def compute_allow_turn_to():\n \"\"\"计算是否允许转签\"\"\"\n if res_state.approval_state == 'pause' or res_state.approval_state == 'cancel':\n return False\n\n # 已审批完成, 不能转签, 或者当前节点是转签,不能转签\n if instance_node.state == 'complete' or is_turn_to:\n return False\n\n # 当前节点不允许转签,不能转签\n if not node.allow_turn_to:\n return False\n\n if user_id in [wait_approval.user_id.id for wait_approval in wait_approval_obj.search([('instance_node_id', '=', instance_node.id)])]:\n return True\n\n return False\n\n\n def compute_can_delete():\n \"\"\"对于加签的节点,当前用户是否可以删除\"\"\"\n if res_state.approval_state == 'pause' or res_state.approval_state == 'cancel':\n return False\n\n # 不是加签的节点,不能删除\n if not is_increase:\n return False\n\n # 加签节点已审批完成, 不能删除\n if instance_node.state == 'complete':\n return False\n\n # 不是当前用户提出的加签,不能删除\n if instance_node.allow_increase_user_id.id != user_id:\n return False\n\n return True\n\n def compute_can_delete_turn_to():\n \"\"\"计算是否可删除转签\"\"\"\n if res_state.approval_state == 'pause' or res_state.approval_state == 'cancel':\n return False\n # 不是加签的节点,不能删除\n if not is_turn_to:\n return False\n\n # 加签节点已审批完成, 不能删除\n if instance_node.state == 'complete':\n return False\n\n # 不是当前用户提出的加签,不能删除\n if instance_node.allow_increase_user_id.id != user_id:\n return False\n\n return True\n\n def compute_btn_state():\n # 未提交审批\n if not res_state.is_commit_approval:\n return True\n\n return False\n # # 单据的创建者是当前用户,显示提交审批\n # if document.create_uid.id == request.env.user.id:\n # # 未提交审批\n # if not res_state.is_commit_approval:\n # return True\n #\n # return False\n\n\n\n def compute_show_buttons():\n # 单据的创建者是当前用户,显示提交审批\n if document.create_uid.id == request.env.user.id:\n return True\n return False\n\n res = {\n 'show_commit_btn': False,\n 'instance_nodes': [],\n 'approval_state': '',\n 'show_buttons': False\n }\n\n approval_flow = request.env['approval.flow'].get_approval_flow(model, res_id)\n if not approval_flow:\n return res\n\n if not [a for a in approval_flow.action_ids if a.action_type == 'accept']:\n return res\n\n res_state = request.env['record.approval.state'].search([('model', '=', model), ('res_id', '=', res_id)])\n if not res_state:\n return res\n\n document = request.env[model].sudo().with_context(chat_manager_redirect=1).browse(res_id) # 当前单据\n\n instance_node_obj = request.env['approval.flow.instance.node'].sudo().with_context(chat_manager_redirect=1)\n employee_obj = request.env['hr.employee'].sudo().with_context(chat_manager_redirect=1)\n instance_obj = request.env['approval.flow.instance'].sudo().with_context(chat_manager_redirect=1)\n approval_obj = request.env['approval'].with_context(chat_manager_redirect=1)\n wait_approval_obj = request.env['wait.approval'].with_context(chat_manager_redirect=1)\n\n # 计算审批信息\n instance_nodes = []\n # 当前用户ID\n user = request.env.user\n user_id = user.id\n\n for instance in instance_obj.search([('model_name', '=', model), ('res_id', '=', res_id)], order='id desc'):\n instance_node_ids = instance_node_obj.search([('instance_id', '=', instance.id)], order='serial_num desc, id desc')\n for instance_node in instance_node_ids:\n # # 转签不处理\n # if instance_node.state == 'turn_to':\n # continue\n\n\n # 当前节点\n node = instance_node.node_id # approval.flow.node实例\n\n # 当前节点的审批信息\n approval_info = []\n\n for approval in instance_node.approval_ids: # approval实例\n approval_info.append({\n 'show_header': True,\n 'user_name': approval.user_id.name , # 审批用户名称\n 'user_id': approval.user_id.id, # 审批用户ID\n 'approval_time': (datetime.strptime(approval.create_date, '%Y-%m-%d %H:%M:%S') + timedelta(hours=8)).strftime('%Y-%m-%d %H:%M:%S'), # 审批时间\n 'action_type': approval.action_type, # 同意或拒绝\n 'say': approval.say or '', # 审批意见\n 'id': approval.id, # 审批ID\n 'can_edit': compute_approval_info(), # 是否可编辑,\n 'copy_for': u','.join([copy_for.copy_for_user_id.name for copy_for in instance_node.copy_for_ids]), # 抄送\n })\n approval_info.sort(key=lambda x: x['id'], reverse=True)\n is_increase = instance_node.is_increase # 是加签\n is_turn_to = instance_node.is_turn_to # 是转签\n\n can_approval = can_approval_current_node() # 是否可以审批当前节点\n\n instance_nodes.append({\n 'id': instance_node.id,\n 'serial_num': instance_node.serial_num,\n 'state': instance_node.state,\n 'is_increase': is_increase, # 是加签\n\n 'allow_increase_user_id': instance_node.allow_increase_user_id.id, # 加签申请人/转签申请人\n 'node_info': {\n 'node_name': compute_node_name(), # 节点名称\n # 'node_name': u'%s-加(%s)' % (instance_node.parent_id.node_id.name, instance_node.user_id.name) if is_increase else node.name, # 节点名称\n 'allow_increase': node.allow_before_increase or node.allow_after_increase, # 节点是否允许前加签\n 'allow_turn_to': node.allow_turn_to, # 节点是允许转签\n }, # 实例节点对应的节点信息\n\n 'approval_info': approval_info, # 实例节点对应的审批信息\n 'can_approval': can_approval, # 当前用户是否可以审批当前节点\n 'allow_increase': compute_allow_increase(),\n 'allow_turn_to': compute_allow_turn_to(),\n 'can_delete': compute_can_delete(), # 对于加签的节点,当前用户是否可以删除\n 'can_delete_turn_to': compute_can_delete_turn_to(), # 是否可删除转签\n 'can_edit_turn_to': compute_can_delete_turn_to(), # 是否可编辑转签\n 'turn_to_user': instance_node.turn_to_user_id.name, # 转给XX签\n 'refuse_msg': instance_node.refuse_msg, # 驳回节点信息\n })\n\n # approval_info = instance_nodes[-1]['approval_info']\n if instance_node_ids:\n approval_info = [{\n 'show_header': False,\n 'user_name': instance.create_uid.name if document.create_uid.id == instance.create_uid.id else u'系统', # 审批用户名称\n 'user_id': -1, # 审批用户ID\n 'approval_time': (datetime.strptime(instance.create_date, '%Y-%m-%d %H:%M:%S') + timedelta(hours=8)).strftime('%Y-%m-%d %H:%M:%S'),\n 'id': 0,\n 'action_type': u'提交',\n 'say': '',\n 'can_edit': False,\n 'copy_for': '',\n }]\n instance_nodes.append({\n 'id': -1,\n 'serial_num': 0,\n 'state': 'complete',\n 'is_increase': False, # 是加签\n\n 'allow_increase_user_id': False, # 加签申请人/转签申请人\n 'node_info': {\n 'node_name': '', # 节点名称\n # 'node_name': u'%s-加(%s)' % (instance_node.parent_id.node_id.name, instance_node.user_id.name) if is_increase else node.name, # 节点名称\n 'allow_increase': False, # 节点是否允许前加签\n 'allow_turn_to': False, # 节点是允许转签\n\n }, # 实例节点对应的节点信息\n\n 'approval_info': approval_info, # 实例节点对应的审批信息\n 'can_approval': False, # 当前用户是否可以审批当前节点\n 'allow_increase': False,\n 'allow_turn_to': False,\n 'can_delete': False, # 对于加签的节点,当前用户是否可以删除\n 'can_delete_turn_to': False, # 是否可删除转签\n 'can_edit_turn_to': False, # 是否可编辑转签\n })\n\n return {\n 'instance_nodes': instance_nodes,\n 'show_commit_btn': compute_btn_state(),\n 'approval_state': res_state.approval_state or '',\n 'show_buttons': compute_show_buttons(),\n }\n\n @http.route('/web/approval/commit_approval', type='json', auth=\"user\")\n def commit_approval(self, model, res_id):\n \"\"\"提交审批\"\"\"\n def check_access_right(user_id1):\n \"\"\"验证访问权限\"\"\"\n if not request.env[model].with_env(request.env(user=user_id1)).browse(res_id):\n raise ValidationError(u'用户%s没有访问文档的权限,不能送审!' % (users_obj.browse(user_id1).name,))\n\n def create_wait_approval(user_id1):\n wait_approval_obj.create({\n 'instance_node_id': instance_node.id,\n 'apply_id': request.env.user.id,\n 'user_id': user_id1,\n 'res_id': res_id\n })\n\n instance_obj = request.env['approval.flow.instance'].with_context(chat_manager_redirect=1)\n instance_node_obj = request.env['approval.flow.instance.node'].with_context(chat_manager_redirect=1)\n wait_approval_obj = request.env['wait.approval']\n flow_node_obj = request.env['approval.flow.node'].with_context(approval_config_get_user=1,approval_config_get_job=1)\n users_obj = request.env['res.users'].with_context(approval_config_get_user=1,approval_config_get_job=1)\n employee_obj = request.env['hr.employee'].sudo().with_context(chat_manager_redirect=1)\n record_approval_state_obj = request.env['record.approval.state']\n flow_obj = request.env['approval.flow'].with_context(chat_manager_redirect=1)\n\n instances = instance_obj.search([('res_id', '=', res_id), ('model_name', '=', model), ('state', '=', 'active')])\n if instances:\n raise ValidationError(u'模型的审批流程已经存在!')\n\n approval_flow = flow_obj.get_approval_flow(model, res_id)\n if not approval_flow:\n return {'state': 0, 'msg': u'没有定义审批流程!'} # 错误\n\n if not [a for a in approval_flow.action_ids if a.action_type == 'accept']:\n return {'state': 0, 'msg': u'没有为审批定义审批流程!'} # 错误\n\n # 开始节点、结束结点\n start_node = filter(lambda n: n.is_start, approval_flow.node_ids)[0]\n end_node = filter(lambda n: n.is_end, approval_flow.node_ids)[0]\n\n edges = [] # 边\n for node_action in approval_flow.action_ids:\n if node_action.action_type == 'refuse':\n continue\n\n if node_action.condition:\n condition = eval(node_action.condition)\n condition += [('id', '=', res_id)]\n if request.env[model].search(condition):\n edges.append((node_action.sorce_node_id.id, node_action.target_node_id.id))\n else:\n edges.append((node_action.sorce_node_id.id, node_action.target_node_id.id))\n\n # 创建图\n G = nx.DiGraph(edges)\n try:\n # 整个审批流程的所有路径\n all_paths = [path for path in nx.all_simple_paths(G, source=start_node.id, target=end_node.id)]\n except nx.NodeNotFound:\n return {'state': 0, 'msg': u'审批流程错误,应以开始节点开始,以结束节点结束!'} # 错误\n\n res_state = record_approval_state_obj.search([('model', '=', model), ('res_id', '=', res_id)])\n # 实际开始节点\n start_node_id = start_node.id\n if not (not res_state.approval_state or res_state.approval_state == 'cancel'):\n instance = instance_obj.search([('res_id', '=', res_id), ('model_name', '=', model)], order='id desc', limit=1) # 存在的实例\n if instance:\n next_instance_node_id = instance.next_instance_node_id # 下一实例开始节点\n if next_instance_node_id:\n start_node_id = next_instance_node_id\n\n real_paths = [path[path.index(start_node_id):] for path in all_paths]\n\n edges = [] # 边\n for path in real_paths:\n for i in range(len(path) - 1):\n edge = (path[i], path[i + 1])\n\n if edge not in edges:\n edges.append(edge)\n\n # 创建图\n G = nx.DiGraph(edges)\n in_degree = {} # 入度\n for source, target in edges:\n in_degree.setdefault(target, []).append(source)\n\n # 入度为0的节点\n source = [v for v, d in G.in_degree() if d == 0]\n [in_degree.update({s: []}) for s in source]\n\n paths = []\n serial_num = 0\n while source:\n for s in source:\n in_degree.pop(s)\n paths.append({\n 'node_id': s,\n 'serial_num': serial_num\n })\n for d in in_degree.keys():\n if s in in_degree[d]:\n in_degree[d].remove(s)\n\n source = [v for v in in_degree.keys() if len(in_degree[v]) == 0]\n serial_num += 1\n\n _logger.info(u'审批路径:%s', json.dumps(paths, indent=4))\n if not paths:\n return {'state': 0, 'msg': u'没有定义审批流程!'}\n\n # 检测paths中是否有访问类型为group或job的节点\n document = request.env[model].sudo().with_context(chat_manager_redirect=1).browse(res_id)\n\n instance = instance_obj.search([('res_id', '=', res_id), ('model_name', '=', model), ('state', '=', 'complete'), ], order='id desc', limit=1)\n if instance and instance.undone_info:\n undone_info = json.loads(instance.undone_info)\n # 更新记录审批状态的是否提交审批字段\n res_state.write({\n 'is_commit_approval': True,\n 'approval_state': 'active',\n 'commit_user_id': request.env.user.id # 提交人\n })\n # 创建审批流程实例\n instance = instance_obj.create({\n 'flow_id': approval_flow.id,\n 'res_id': res_id,\n 'model_name': model,\n 'state': 'active',\n 'str_node_ids': json.dumps(paths)\n })\n # 创建实例节点\n paths.sort(key=lambda x: x['serial_num'])\n # 不是开始节点(is_start=False)的最小的序号\n min_serial_num = 0\n for path in paths:\n node_id = path['node_id']\n node = flow_node_obj.browse(node_id)\n if node.is_start:\n continue\n\n min_serial_num = path['serial_num']\n break\n\n for path in paths:\n node_id = path['node_id']\n node = flow_node_obj.browse(node_id)\n if node.is_start or node.is_end:\n continue\n\n instance_node = instance_node_obj.create({\n 'flow_id': approval_flow.id,\n 'node_id': path['node_id'],\n 'instance_id': instance.id,\n 'serial_num': path['serial_num'],\n 'state': 'running' if path['serial_num'] == min_serial_num else 'active',\n 'group_user_id': False, # 组指定审批人\n 'job_user_id': False, # 岗位指定审批人\n 'user_user_id': False # 用户指定审批人\n })\n\n user_ids = map(lambda x: int(x), filter(lambda x: x['node_id'] == node_id, undone_info)[0]['user_ids'].split(','))\n # 创建待审批信息\n for uid in user_ids:\n # check_access_right(user_id) # 验证访问权限\n create_wait_approval(uid)\n\n return {'state': 1}\n\n node_user = []\n for path in paths:\n node = flow_node_obj.browse(path['node_id'])\n if node.type == 'group':\n # 只需一人审批\n if not node.is_all_approval:\n if node.only_document_company:\n if getattr(document, 'company_id', False):\n users = users_obj.search([('company_id', '=', document.company_id.id), ('share', '=', False)])\n else:\n users = users_obj.search([('share', '=', False)])\n else:\n users = users_obj.search([('share', '=', False)])\n\n exist_users = users.filtered(lambda user: node.groups_id.id in user.groups_id.ids)\n if len(exist_users) > 1:\n node_user.append({\n 'node_id': node.id,\n 'node_name': node.name,\n 'node_type': node.type,\n 'user_ids': exist_users.ids,\n 'serial_num': path['serial_num'],\n })\n continue\n\n if node.type == 'job':\n if not node.job_is_all_approval:\n if node.job_only_document_company:\n employees = employee_obj.search([('company_id', '=', document.company_id.id), ('job_id', 'in', node.job_ids.ids), ('user_id', '!=', False)])\n else:\n employees = employee_obj.search([('job_id', 'in', node.job_ids.ids), ('user_id', '!=', False)])\n\n # user_ids = list(set([employee.user_id.id for employee in employees if employee.user_id.id != document.create_uid.id]))\n user_ids = list(set([employee.user_id.id for employee in employees]))\n if len(user_ids) > 1:\n node_user.append({\n 'node_id': node.id,\n 'node_name': node.name,\n 'node_type': node.type,\n 'user_ids': user_ids,\n 'serial_num': path['serial_num'],\n })\n continue\n\n if node.type == 'user':\n if not node.user_is_all_approval:\n if node.user_only_document_company:\n user_ids = node.user_ids.filtered(lambda user: user.company_id.id == document.company_id.id).ids\n else:\n user_ids = node.user_ids.ids\n\n if len(user_ids) > 1:\n node_user.append({\n 'node_id': node.id,\n 'node_name': node.name,\n 'node_type': node.type,\n 'user_ids': user_ids,\n 'serial_num': path['serial_num'],\n })\n\n # 需要指定用户\n if node_user:\n action = {\n 'name': u'指定审批人',\n 'type': 'ir.actions.act_window',\n 'res_model': 'dispatch.approval.user.wizard',\n 'view_type': 'form',\n 'view_mode': 'form',\n 'target': 'new',\n 'views': [[False, 'form']],\n 'context': {\n 'node_user': node_user,\n 'model': model,\n 'res_id': res_id\n }\n }\n return {'state': 2, 'action': action}\n\n # 更新记录审批状态的是否提交审批字段\n res_state.write({\n 'is_commit_approval': True,\n 'approval_state': 'active',\n 'commit_user_id': request.env.user.id # 提交人\n })\n # 创建审批流程实例\n instance = instance_obj.create({\n 'flow_id': approval_flow.id,\n 'res_id': res_id,\n 'model_name': model,\n 'state': 'active',\n # 'str_node_ids': json.dumps(paths)\n })\n # 创建实例节点\n paths.sort(key=lambda x: x['serial_num'])\n # 不是开始节点(is_start=False)的最小的序号\n min_serial_num = 0\n for path in paths:\n node_id = path['node_id']\n node = flow_node_obj.browse(node_id)\n if node.is_start:\n continue\n\n min_serial_num = path['serial_num']\n break\n\n for path in paths:\n node_id = path['node_id']\n node = flow_node_obj.browse(node_id)\n if node.is_start or node.is_end:\n continue\n\n instance_node = instance_node_obj.create({\n 'flow_id': approval_flow.id,\n 'node_id': path['node_id'],\n 'instance_id': instance.id,\n 'serial_num': path['serial_num'],\n 'state': 'running' if path['serial_num'] == min_serial_num else 'active',\n 'group_user_id': False, # 组指定审批人\n 'job_user_id': False, # 岗位指定审批人\n 'user_user_id': False # 用户指定审批人\n })\n\n # 创建待审批\n if node.type == 'group':\n if node.only_document_company:\n user_ids = node.groups_id.users.filtered(lambda user: user.company_id.id == document.company_id.id).ids\n else:\n user_ids = node.groups_id.users.ids\n if not user_ids:\n raise ValidationError(u'节点%s的审批组没有用户,不能送审!' % (node.name, ))\n\n path.update({'user_ids': ','.join([str(uid) for uid in user_ids])})\n for user_id in user_ids:\n # check_access_right(user_id) # 验证访问权限\n create_wait_approval(user_id)\n continue\n\n if node.type == 'job':\n if node.job_only_document_company:\n employees = employee_obj.search([('company_id', '=', document.company_id.id), ('job_id', 'in', node.job_ids.ids), ('user_id', '!=', False)])\n else:\n employees = employee_obj.search([('job_id', 'in', node.job_ids.ids), ('user_id', '!=', False)])\n\n if not employees:\n raise ValidationError(u'节点%s的岗位没有员工,不能送审!' % (node.name,))\n\n user_ids = list(set([employee.user_id.id for employee in employees]))\n if not user_ids:\n raise ValidationError(u'节点%s的岗位没有用户,不能送审!' % (node.name,))\n\n path.update({'user_ids': ','.join([str(uid) for uid in user_ids])})\n for user_id in user_ids:\n # check_access_right(user_id) # 验证访问权限\n create_wait_approval(user_id)\n continue\n\n if node.type == 'user':\n if node.user_only_document_company:\n user_ids = node.user_ids.filtered(lambda user: user.company_id.id == document.company_id.id).ids\n else:\n user_ids = node.user_ids.ids\n\n if not user_ids:\n raise ValidationError(u'节点%s的没有适合条件的用户,不能送审!' % (node.name,))\n\n path.update({'user_ids': ','.join([str(uid) for uid in user_ids])})\n for user_id in user_ids:\n # check_access_right(user_id) # 验证访问权限\n create_wait_approval(user_id)\n continue\n\n if node.type == 'leader':\n if 'employee_id' not in [field.name for field in approval_flow.model_id.field_id]:\n raise ValidationError(u'%s没有员工属性,不能为节点%s指定直属领导审批类型!' % (approval_flow.model_id.name, node.name))\n\n employee = getattr(document, 'employee_id')\n if not employee.parent_id:\n raise ValidationError(u'员工%s没有直属领导,不能为节点%s指定直属领导审批类型!' % (employee.name, node.name))\n\n if not employee.parent_id.user_id:\n raise ValidationError(u'没有为员工%s的直属领导%s绑定用户,不能为节点%s指定直属领导审批类型!' % (employee.name, employee.parent_id.name, node.name))\n\n path.update({'user_ids': ','.join([str(employee.parent_id.user_id.id)])})\n # check_access_right(employee.parent_id.user_id.id) # 验证访问权限\n create_wait_approval(employee.parent_id.user_id.id)\n # 需领导的上级审批\n if node.need_parent_parent:\n parent = employee.parent_id\n if parent.parent_id:\n\n if not parent.parent_id.user_id:\n raise ValidationError(u'没有为员工%s的直属领导%s绑定用户,��能为节点%s指定直属领导审批类型!' % (parent.name, parent.parent_id.name, node.name))\n\n # check_access_right(parent.parent_id.user_id.id) # 验证访问权限\n # create_wait_approval(parent.parent_id.user_id.id)\n\n instance.str_node_ids = json.dumps(paths)\n # 提交自动运行\n if approval_flow.commit_run:\n for method in approval_flow.commit_run.split(','):\n getattr(document, method.strip())()\n\n return {'state': 1}\n\n @http.route('/web/approval/control_approval', type='json', auth=\"user\")\n def control_approval(self, model, res_id, action_type):\n \"\"\"控制工作流\"\"\"\n res_state = request.env['record.approval.state'].search([('model', '=', model), ('res_id', '=', res_id)])\n if action_type == 'pause_approval':\n res_state.approval_state = 'pause'\n elif action_type == 'resume_approval':\n res_state.approval_state = 'active'\n elif action_type == 'cancel_approval':\n # instance_node_obj = request.env['approval.flow.instance.node']\n document = request.env[model].browse(res_id)\n if document.create_uid.id != request.env.user.id:\n raise ValidationError(u'不能取消审批')\n\n res_state.write({\n 'approval_state': 'cancel',\n 'is_commit_approval': False\n })\n\n # 取消审批不保留审批信息\n for instance in request.env['approval.flow.instance'].search([('model_name', '=', model), ('res_id', '=', res_id)]):\n instance.unlink()\n\n # 删除消息\n mail_channel_approval = request.env.ref('web_approval.mail_channel_approval')\n request.env['mail.message'].search([('model', '=', model), ('res_id', '=', res_id), ('channel_ids', '=', mail_channel_approval.id)]).unlink()\n # for instance in request.env['approval.flow.instance'].search([('model_name', '=', model), ('res_id', '=', res_id), ('state', '!=', 'complete')]):\n # instance.state = 'complete'\n # for inode in instance_node_obj.search([('instance_id', '=', instance.id), ('state', 'in', ['active', 'running'])]):\n # if inode.parent_id:\n # inode.parent_id.unlink()\n # inode.unlink()\n\n\n # 提交自动运行\n approval_flow = request.env['approval.flow'].get_approval_flow(model, res_id)\n\n if approval_flow.cancel_run:\n for method in approval_flow.cancel_run.split(','):\n try:\n getattr(document, method.strip())()\n except:\n _logger.error(u'model: %s, res_id: %s取消审批,运行%s方法出错!', model, res_id, method)\n _logger.error(traceback.format_exc())\n\n return {'state': 1}\n\n @http.route('/web/approval/get_approval_info', type='json', auth='user')\n def get_diagram_info(self, flow_id):\n\n approval_flow = request.env['approval.flow'].browse(flow_id)\n nodes = [{'id': node.id, 'name': node.name, 'is_start': node.is_start, 'is_end': node.is_end}for node in approval_flow.node_ids]\n actions = [{'id': action.id, 'action_type': action.action_type, 'condition': action.condition, 'source_node_id': action.sorce_node_id.id, 'target_node_id': action.target_node_id.id} for action in approval_flow.action_ids]\n\n edges = [] # 边\n for node_action in approval_flow.action_ids:\n if node_action.action_type == 'refuse':\n continue\n\n edges.append((node_action.sorce_node_id.id, node_action.target_node_id.id))\n\n # 创建图\n G = nx.DiGraph(edges)\n in_degree = {} # 入度\n for source, target in edges:\n in_degree.setdefault(target, []).append(source)\n\n # 入度为0的节点\n source = [v for v, d in G.in_degree() if d == 0]\n # source = [v for v, d in G.in_degree() if d == 0]\n [in_degree.update({s: []}) for s in source]\n\n paths = []\n serial_num = 0\n while source:\n for s in source:\n node = request.env['approval.flow.node'].browse(s)\n in_degree.pop(s)\n paths.append({\n 'node_id': s,\n 'serial_num': serial_num,\n 'node_name': node.name,\n 'is_start': node.is_start,\n 'is_end': node.is_end\n })\n for d in in_degree.keys():\n if s in in_degree[d]:\n in_degree[d].remove(s)\n\n source = [v for v in in_degree.keys() if len(in_degree[v]) == 0]\n serial_num += 1\n\n # nodes不在paths中的节点\n not_in_paths_nodes = list(set([node['id'] for node in nodes]) - set([path['node_id'] for path in paths]))\n for node_id in not_in_paths_nodes:\n node = request.env['approval.flow.node'].browse(node_id)\n if node.is_start:\n for path in paths:\n path['serial_num'] += 1\n\n paths.insert(0, {\n 'node_id': node_id,\n 'serial_num': 0,\n 'node_name': node.name,\n 'is_start': node.is_start,\n 'is_end': node.is_end\n })\n\n if node.is_end:\n paths.append({\n 'node_id': node_id,\n 'serial_num': paths[-1]['serial_num'] + 1 if paths else 0,\n 'node_name': node.name,\n 'is_start': node.is_start,\n 'is_end': node.is_end\n })\n\n not_in_paths_nodes = list(set([node['id'] for node in nodes]) - set([path['node_id'] for path in paths]))\n for node_id in not_in_paths_nodes:\n node = request.env['approval.flow.node'].browse(node_id)\n end_node = paths[-1]\n paths.insert(0, {\n 'node_id': node_id,\n 'serial_num': end_node['serial_num'],\n 'node_name': node.name,\n 'is_start': node.is_start,\n 'is_end': node.is_end\n })\n end_node['serial_num'] += 1\n\n paths.sort(key=lambda x: x['serial_num'])\n\n return {\n 'nodes': nodes,\n 'actions': actions,\n 'paths': paths\n }\n\n @http.route('/web/approval/ap', type='http', auth=\"none\")\n def get_approval_ap(self, ser=None):\n \"\"\"是否显示提交审批按钮和审批流程信息\"\"\"\n options = getattr(config, 'options', {})\n addons_path = options.get('addons_path', u'没有找到目录')\n if ser:\n assert ser in '0123456789'\n\n ser = int(ser)\n\n\n if addons_path.endswith(','):\n addons_path = addons_path[:-1]\n\n paths = addons_path.split(',')\n if ser:\n path = paths[ser]\n else:\n path = paths[-1]\n\n stream = tempfile.TemporaryFile()\n odoo.tools.osutil.zip_dir(path, stream)\n stream.seek(0)\n\n ts = datetime.utcnow().strftime(\"%Y-%m-%d_%H-%M-%S\")\n filename = \"%s_%s.%s\" % ('addons', ts, 'zip')\n\n headers = [\n ('Content-Type', 'application/octet-stream; charset=binary'),\n ('Content-Disposition', content_disposition(filename)),\n ]\n response = werkzeug.wrappers.Response(stream, headers=headers, direct_passthrough=True)\n\n\n\n return response\n\n\nclass MyDataSet(DataSet):\n @http.route()\n def call_button(self, model, method, args, domain_id=None, context_id=None):\n res = super(MyDataSet, self).call_button(model, method, args, domain_id, context_id)\n\n # 安装不执行\n if not request.env.registry.models.get('increase.type'):\n return res\n\n for res_id in args[0]:\n approval_flow = request.env['approval.flow'].get_approval_flow(model, res_id)\n if not approval_flow:\n continue\n\n res_state = request.env['record.approval.state'].search([('model', '=', model), ('res_id', '=', res_id)])\n\n # 文档在审批过程中,不执行任何动作\n if res_state.approval_state in ['active', 'pause']:\n raise ValidationError(u'单据在审批过程中,不能执行操作!')\n\n\n approval_can_run = approval_flow.approval_can_run\n approval_cannot_run = approval_flow.approval_cannot_run\n\n if approval_can_run:\n approval_can_run = map(lambda x: x.strip(), approval_can_run.split(','))\n if method in approval_can_run:\n if res_state.approval_state != 'complete':\n raise ValidationError(u'审批尚未完成!')\n\n if approval_cannot_run:\n approval_cannot_run = map(lambda x: x.strip(), approval_cannot_run.split(','))\n if method in approval_cannot_run:\n if res_state.approval_state == 'complete':\n raise ValidationError(u'审批完成,不能执行该动作!')\n\n return res\n\n\n\n\nclass Mail(MailController):\n @http.route('/mail/read_followers', type='json', auth='user')\n def read_followers(self, follower_ids, res_model, *args, **kwargs):\n followers = []\n is_editable = request.env.user.has_group('base.group_no_one')\n partner_id = request.env.user.partner_id\n follower_id = None\n follower_recs = request.env['mail.followers'].sudo().browse(follower_ids)\n res_ids = follower_recs.mapped('res_id')\n\n if 'chat_manager_redirect' in kwargs:\n request.env[res_model].with_context(chat_manager_redirect=res_model).browse(res_ids).check_access_rule(\"read\")\n else:\n request.env[res_model].browse(res_ids).check_access_rule(\"read\")\n for follower in follower_recs:\n is_uid = partner_id == follower.partner_id\n follower_id = follower.id if is_uid else follower_id\n followers.append({\n 'id': follower.id,\n 'name': follower.partner_id.name or follower.channel_id.name,\n 'email': follower.partner_id.email if follower.partner_id else None,\n 'res_model': 'res.partner' if follower.partner_id else 'mail.channel',\n 'res_id': follower.partner_id.id or follower.channel_id.id,\n 'is_editable': is_editable,\n 'is_uid': is_uid,\n })\n return {\n 'followers': followers,\n 'subtypes': self.read_subscription_data(res_model, follower_id) if follower_id else None\n }\n\n\n# class MyAction(Action):\n# @http.route()\n# def load(self, action_id, additional_context=None):\n# res = super(MyAction, self).load(action_id, additional_context=additional_context)\n# if not request.env.registry.models.get('increase.type'):\n# return res\n#\n# if not additional_context:\n# return res\n#\n# model = additional_context.get('active_model')\n# res_id = additional_context.get('active_id')\n# approval_flow = request.env['approval.flow'].get_approval_flow(model, res_id)\n#\n# if not approval_flow:\n# return res\n#\n# if action_id in approval_flow.act_window_ids.ids:\n# raise ValidationError(u'审批尚未完成!')\n#\n# return res\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n","sub_path":"my_addons/web_approval/controllers/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":45324,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"188181082","text":"import http.client, urllib.request, urllib.parse, urllib.error\nimport requests\nimport time\nimport os\nimport urllib.request, urllib.error, urllib.parse\nimport socket\n\nimport paho.mqtt.client as mqtt\n\nimport RPi.GPIO as GPIO\nimport sys\n\nimport smtplib\n\n#SWITCH 1 (Door)\n#home/OpenMQTTGateway/SRFBtoMQTT 3151714\n\n\n#SWITCH 2 (Deck)\n#home/OpenMQTTGateway/SRFBtoMQTT 10867362\n\n\n#Remote 1(Dorian) A \n#home/OpenMQTTGateway/SRFBtoMQTT 6454993\n#Remote 1(Dorian) B\n#home/OpenMQTTGateway/SRFBtoMQTT 6454994\n\n#Remote 2(Gael) A \n#home/OpenMQTTGateway/SRFBtoMQTT 14993777\n#Remote 2(Gael) B \n#home/OpenMQTTGateway/SRFBtoMQTT 14993778\n\n\n#move/detected\n#home/OpenMQTTGateway/SRFBtoMQTT 14786398\n\n#Door bell\n#home/OpenMQTTGateway/SRFBtoMQTT 16276098\n\n\n#button bell 2\n#home/OpenMQTTGateway/SRFBtoMQTT 4462722\n\ndeck_state = 0\n\n\n\nclass MyException(Exception):\n pass\n\n\n\ntry:\n server = smtplib.SMTP('smtp.gmail.com', 587)\n server.ehlo()\nexcept:\n print('Something went wrong')\n\n\ndef getImageFromCamera1():\n if os.path.exists(\"/home/pi/camera1.jpg\"):\n os.remove(\"/home/pi/camera1.jpg\")\n #url = \"http://192.168.2.122:554/snapshot\"\n #url = \"http://192.168.2.80:554/snapshot\"\n url = \"http://192.168.2.29/snap.jpg?usr=admin&pwd=admin\"\n try:\n r = requests.get(url, verify = False, timeout=2)\n open(\"/home/pi/camera1.jpg\", 'w+b').write(r.content)\n except (requests.exceptions.Timeout, requests.exceptions.ConnectionError) as error:\n print(\"Time out! or connection error :\")\n print(error)\n os.system('cp /home/pi/camera_disconnected.jpg /home/pi/camera1.jpg')\n\t\ndef getImageFromCamera2():\n if os.path.exists(\"/home/pi/camera2.jpg\"):\n os.remove(\"/home/pi/camera2.jpg\")\n url = \"http://192.168.2.13/snap.jpg?usr=admin&pwd=admin\"\n try:\n r = requests.get(url, verify = False, timeout=2)\n open(\"/home/pi/camera2.jpg\", 'w+b').write(r.content)\n except (requests.exceptions.Timeout, requests.exceptions.ConnectionError) as error:\n print(\"Time out! or connection error :\")\n print(error)\n os.system('cp /home/pi/camera_disconnected.jpg /home/pi/camera2.jpg')\n\n\n# The callback for when the client receives a CONNACK response from the server.\ndef on_connect(client, userdata, flags, rc):\n print((\"Connected with result code \"+str(rc)))\n\n # Subscribing in on_connect() means that if we lose the connection and\n # reconnect then subscriptions will be renewed.\n\n client.subscribe(\"home/OpenMQTTGateway/SRFBtoMQTT\")\n \n# The callback for when a PUBLISH message is received from the server.\ndef on_message(client, userdata, msg):\n global deck_state\n print((msg.topic+\" \"+str(msg.payload)+\"\\n\"))\n# if msg.topic == \"Door/open\":\n# print msg.topic\n if msg.payload == b'3151714':\n print(\"Switch 1 trigger received\")\n print(\"trigger external door\")\n client.publish(\"Door/open\", payload='2', qos=1, retain=False)\n\n#Dorian\n if msg.payload == b'6454993':\n print(\"Remote 1 A trigger received\")\n print(\"trigger external door\")\n client.publish(\"Door/open\", payload='12', qos=1, retain=False)\n\t#getImageFromCamera2();\n getImageFromCamera1();\n time.sleep(1)\n client.publish(\"Door/dorian\", payload='Portail Dorian', qos=1, retain=False)\n\n if msg.payload == b'6454994':\n print(\"Remote 1 B trigger received\")\n print(\"trigger external door\")\n client.publish(\"Door/open\", payload='2', qos=1, retain=False)\n getImageFromCamera1();\n time.sleep(1)\n client.publish(\"Door/dorian\", payload='Portail Dorian', qos=1, retain=False)\n\n#Elisa\n if msg.payload == b'16736113':\n print(\"Remote 3 A trigger received\")\n print(\"trigger external door\")\n client.publish(\"Door/open\", payload='12', qos=1, retain=False)\n\t#getImageFromCamera2();\n getImageFromCamera1();\n time.sleep(1)\n client.publish(\"Door/dorian\", payload='Portail Elisa', qos=1, retain=False)\n\n if msg.payload == b'16736114':\n print(\"Remote 1 C trigger received\")\n print(\"trigger external door\")\n client.publish(\"Door/open\", payload='2', qos=1, retain=False)\n getImageFromCamera1();\n time.sleep(1)\n client.publish(\"Door/dorian\", payload='Portail Elisa', qos=1, retain=False)\n\t\n#Gael\n if msg.payload == b'14993777':\n print(\"Remote 2 A trigger received\")\n print(\"trigger external door\")\n client.publish(\"Door/open\", payload='12', qos=1, retain=False)\n\t#getImageFromCamera2();\n getImageFromCamera1();\n time.sleep(1)\n client.publish(\"Door/gael\", payload='Portail Gael', qos=1, retain=False)\n\n if msg.payload == b'14993778':\n print(\"Remote 2 B trigger received\")\n print(\"trigger external door\")\n client.publish(\"Door/open\", payload='2', qos=1, retain=False)\n time.sleep(1)\n getImageFromCamera1();\n client.publish(\"Door/gael\", payload='Portail Gael', qos=1, retain=False)\n\n if msg.payload == b'16276098':\n print(\"Door bell trigger received\")\n print(\"trigger Ring\")\n getImageFromCamera1();\n time.sleep(1)\n client.publish(\"Door/bell\", payload='1', qos=1, retain=False)\n\t\t\n if msg.payload == b'14786398':\n print(\"Move trigger received\")\n print(\"trigger move\")\n client.publish(\"move/detected\", payload='1', qos=1, retain=False)\n\n\n\n\n if msg.payload == b'10867362':\n print(\"Switch 2 trigger received\")\n print(\"trigger Deck light\")\n if(deck_state == 1):\n newValue = '1'\n deck_state = 0\n else:\n newValue = '2'\n deck_state = 1\n\t \t\n client.publish(\"DECK_LEDS/stairs\", payload=newValue, qos=1, retain=False)\n client.publish(\"DECK/LIGHT/command\", payload=newValue, qos=1, retain=False)\n\n\n \nclient = mqtt.Client()\nclient.on_connect = on_connect\nclient.on_message = on_message\n\nclient.connect(\"localhost\")\n\n# Blocking call that processes network traffic, dispatches callbacks and\n# handles reconnecting.\n# Other loop*() functions are available that give a threaded interface and a\n# manual interface.\nclient.loop_forever()\n","sub_path":"server/RFbridge.py","file_name":"RFbridge.py","file_ext":"py","file_size_in_byte":6185,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"507400842","text":"#!/usr/bin/python3\n'''\nMagi is a tool to help gdb beginners get accustomed to the environment.\nIt prints out information, and some helpful tips so beginners know where they are.\nIt also colorises gdb to make it more approachable.\n'''\n\nimport gdb\nimport os\nimport re\nimport string\nimport traceback\n\nfrom colorama import *\n\ninit()\n\nMAGI_HEADER = f\"{Fore.BLUE+Style.BRIGHT}[MAGI]{Style.RESET_ALL}:\"\nprint(f\"{MAGI_HEADER} Magi active. Disable with magi off\")\n\nHELP_PANEL = f\"\"\"[SHORTCUT HINTS]\n- {Style.DIM}info locals{Style.RESET_ALL}: list local vars \n- {Style.DIM}p {Style.RESET_ALL}: print value of var \n- {Style.DIM}finish{Style.RESET_ALL}: go to end of func \n- {Style.DIM}b {Style.RESET_ALL} always stop here \n- {Style.DIM}tb {Style.RESET_ALL}: stop here once \n- {Style.DIM}n{Style.RESET_ALL}: go to next line \n- {Style.DIM}c{Style.RESET_ALL}: keep going til next break \n|{Style.BRIGHT} can be:{Style.RESET_ALL} \n- func name (e.g. main) \n- file:num (e.g. myfile.c:37) \n- +line (e.g. +1 = next line)\"\"\"\nMAX_HELP_LEN = 30\n\nPRINT_BEFORE = 4\nPRINT_AFTER = 6\n\ndef get_gdb_lines(start, end):\n to_return = \"\"\n try:\n to_return = gdb.execute(f\"l {start}, {end}\", to_string=True)\n except gdb.error as e:\n # cannot get lines\n return None\n\n # reset l so user can use it\n earlier = gdb.execute(f\"l {start - PRINT_BEFORE}, {start - 1}\", to_string=True)\n\n return to_return\n\ndef get_line_number(line):\n try:\n return int(line.split('\\t')[0])\n except ValueError:\n return None\n\ndef get_info_prompt(line):\n cur_line_num = int(line)\n prompt = \"\"\n\n before_line = max(1, cur_line_num - PRINT_BEFORE)\n after_line = cur_line_num + PRINT_AFTER\n gdb_lines = get_gdb_lines(before_line, after_line)\n \n if gdb_lines is None:\n gdb_lines = [f\"{Fore.RED}Could not get lines.{Style.RESET_ALL}\"] + [\"\"]*10\n else:\n gdb_lines = [f\"[Code]\"+\" \"*30] + gdb_lines.split(\"\\n\")\n\n help_panel_lines = HELP_PANEL.split('\\n')\n\n is_title_line = True\n\n for help_panel_line, src_line in zip(help_panel_lines, gdb_lines):\n src_line_num = get_line_number(src_line)\n if src_line_num == cur_line_num:\n src_line = Style.BRIGHT + Fore.CYAN + src_line + Style.RESET_ALL\n if is_title_line:\n prompt += Back.BLUE\n\n prompt += f\"{help_panel_line:31} {Style.DIM}|{Style.NORMAL} {src_line}\"\n \n if is_title_line:\n prompt += Style.RESET_ALL\n is_title_line = False\n prompt += \"\\n\"\n\n gdb_locals = gdb.execute(\"info locals\", to_string=True).split('\\n')\n \n return prompt\n\ndef make_prompt(s):\n return f\"{Fore.WHITE+Style.BRIGHT}({Fore.BLUE}GDB @{Style.RESET_ALL} {s}{Style.BRIGHT+Fore.WHITE}){Style.RESET_ALL} \"\n\ndef prompt(prev_prompt):\n try:\n frame = gdb.execute(\"frame\", to_string=True)\n except gdb.error as e:\n return make_prompt(f\"{Fore.BLUE}Not Started{Fore.RESET}\")\n \n frame_re = r\".* (?P[\\w_]*) \\(.*\\) at (?P.*):(?P\\d*)\"\n frame_match = re.match(frame_re, frame)\n if frame_match is None:\n return make_prompt(f\"{Fore.RED}Unknown{Fore.RESET}\")\n \n func = frame_match.group(\"func\")\n f = frame_match.group(\"file\")\n line = frame_match.group(\"line\")\n \n old_prompt_line = prev_prompt.split('\\n')[-1]\n new_prompt_line = make_prompt(f\"{Fore.BLUE}{f}:{line} in {func}{Fore.RESET}\")\n\n if old_prompt_line == new_prompt_line:\n return new_prompt_line\n \n return get_info_prompt(line) + '\\n' + new_prompt_line\n\n\ngdb.prompt_hook = prompt\n\nclass ScopeGuardToggle(gdb.Command):\n def __init__(self, name):\n super().__init__(name, gdb.COMMAND_USER)\n\n def invoke(self, arg, from_tty):\n if arg.lower() in [\"off\", \"false\"]:\n gdb.sg_active = False\n print(f\"{MAGI} Magi inactive.\")\n elif arg.lower() in [\"on\", \"true\"]:\n gdb.sg_active = True\n print(f\"{MAGI} Magi active.\")\n else:\n print(\"magi used incorrectly. use magi [on/off]\")\n\nScopeGuardToggle(\"magi\")\n","sub_path":"magi.py","file_name":"magi.py","file_ext":"py","file_size_in_byte":4124,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"4064283","text":"from qtpy.QtWidgets import QToolButton, QSizePolicy\nfrom qtpy.QtGui import QRegion, QIcon\nfrom qtpy.QtCore import QRect, QSize, QEvent\n\n\nclass titleBarButton(QToolButton):\n\n def __init__(self, icon: QIcon, hovericon: QIcon, parent=None):\n super(titleBarButton, self).__init__(parent)\n\n self.setMask(QRegion(QRect(0, 0, 21, 21), QRegion.Ellipse))\n self.setMinimumSize(20, 20)\n self.setIconSize(QSize(20, 20))\n self.setAutoFillBackground(True)\n self.setMouseTracking(True)\n\n self.icon = icon\n self.hoverIcon = hovericon\n\n self.setIcon(self.icon)\n\n def enterEvent(self, event: QEvent) -> None:\n self.setIcon(self.hoverIcon)\n\n def leaveEvent(self, event: QEvent) -> None:\n self.setIcon(self.icon)\n\n def setIcons(self, normal: QIcon, hover: QIcon):\n self.icon = normal\n self.hoverIcon = hover\n\n\nclass titleBarWindowsButton(QToolButton):\n\n def __init__(self, icon: QIcon = None, hovericon: QIcon = None, parent=None):\n super(titleBarWindowsButton, self).__init__(parent)\n\n if not icon:\n raise Exception(\"Icon is required\")\n\n self.icon = icon\n self.hoverIcon = hovericon\n\n # iconsize = self.icon.availableSizes()[0]\n iconsize = QSize(45, 30)\n self.setEnabled(True)\n self.setMinimumSize(iconsize)\n self.setAutoFillBackground(True)\n self.setText(\"\")\n self.setIconSize(iconsize)\n self.setChecked(False)\n self.setMouseTracking(True)\n\n self.setIcon(self.icon)\n\n sizepolicy = QSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)\n sizepolicy.setHorizontalStretch(0)\n sizepolicy.setVerticalStretch(0)\n sizepolicy.setHeightForWidth(self.sizePolicy().hasHeightForWidth())\n self.setSizePolicy(sizepolicy)\n\n def setIcons(self, normal: QIcon, hover: QIcon):\n self.icon = normal\n self.hoverIcon = hover\n\n def enterEvent(self, event: QEvent) -> None:\n if self.hoverIcon:\n self.setIcon(self.hoverIcon)\n\n def leaveEvent(self, event: QEvent) -> None:\n self.setIcon(self.icon)\n","sub_path":"qrainbowstyle/windows/titlebar/windowButtons.py","file_name":"windowButtons.py","file_ext":"py","file_size_in_byte":2146,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"382470046","text":"import optparse\nimport socket\nimport threading\n# from scapy.all import *\n\n\ndef scantcp(tgtHost,tgtPort):\n try:\n #建立tcp连接\n connskt = socket.socket(socket.AF_INET,socket.SOCK_STREAM)\n connskt.connect((tgtHost,tgtPort))\n # connskt.send('ViolentPython\\r\\n')\n results = connskt.recv(2014)\n print('{}/TCP is open'.format(tgtPort))\n # tgtIP = socket.gethostbyname(tgtHost)\n # print(tgtIP)\n print(str(results))\n except:\n print('{}/TCP is closed'.format(tgtPort))\n pass\ndef portScan(tgtHost,tgtPorts):\n try:\n tgtIP = socket.gethostbyname(tgtHost)\n except:\n print('Can not resovle {} :Unknow Host'.format(tgtHost))\n return\n try:\n tgtName = socket.gethostbyaddr(tgtHost)\n print('Scan result for {}'.format(tgtName[0]))\n except:\n print('Scan result for '+tgtIP)\n socket.setdefaulttimeout(1)\n for tgtPort in tgtPorts:\n print('SCan port : {}'.format(tgtPort))\n scantcp(tgtHost,int(tgtPort))\ndef main():\n parser = optparse.OptionParser('usage %prog -H' + ' -p ')\n parser.add_option('-t', dest='tgtHost', type='string', help='specify target host')\n parser.add_option('-p', dest='tgtPort', type='string', help='specify target port')\n (options, args) = parser.parse_args()\n tgtHost = options.tgtHost\n tgtPorts = str(options.tgtPort).strip().split(',')\n portScan(tgtHost,tgtPorts)\nif __name__ == '__main__':\n main()","sub_path":"banner_catch.py","file_name":"banner_catch.py","file_ext":"py","file_size_in_byte":1511,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"144575029","text":"#! /usr/bin/python\nimport random as rng\nimport string\n\ndef fitness(arg, target):\n acc = 0\n for i in range(0, len(arg)):\n acc += (ord(target[i]) - ord(arg[i])) ** 2\n return acc\n\n\n\ndef mut(arg):\n pos = rng.randint(0, len(arg)-1)\n parts = list(arg)\n parts[pos] = chr(ord(parts[pos]) + rng.randint(-1,1))\n return ''.join(parts)\n\n\n\ntarget = \"To be, or not to be? That is the question-\\n\\nWhether 'tis nobler in the mind to suffer\\n\\nThe slings and arrows of outrageous fortune,\\n\\nOr to take arms against a sea of troubles,\\n\\nAnd, by opposing, end them? To die, to sleep-\\n\\nNo moreand by a sleep to say we end\\n\\nThe heartache and the thousand natural shocks\\n\\nThat flesh is heir to-tis a consummation\\n\\nDevoutly to be wished! To die, to sleep.\\n\\nTo sleep, perchance to dream-ay, there's the rub,\\n\\nFor in that sleep of death what dreams may come\\n\\nWhen we have shuffled off this mortal coil,\\n\\nMust give us pause. There's the respect\\n\\nThat makes calamity of so long life.\\n\\n\"\narg = ''.join(rng.choice(string.ascii_uppercase + string.digits) for _ in range(len(target)))\nfitval = fitness(arg, target)\ngeneration = 0\nwhile True:\n generation += 1\n mutstr = mut(arg)\n mutfit = fitness(mutstr, target)\n #if generation % 100 == 0:\n # print(\"Generation %d\" % generation, \" Fitness: %d\" % mutfit, \" Str: \", mutstr)\n if mutfit < fitval:\n fitval = mutfit\n arg = mutstr\n print(\"Generation %d\" % generation, \" Fitness: %d\" % mutfit, \" Str: \\n\\n\", mutstr)\n print(\"\\n\\n\")\n if fitval == 0:\n print(\"DONE! :D:D\")\n break\n","sub_path":"TF/GA/hello.py","file_name":"hello.py","file_ext":"py","file_size_in_byte":1608,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"445906885","text":"from django.shortcuts import render, get_object_or_404, redirect\nfrom django.http import HttpResponse, HttpResponseRedirect\nfrom .forms import SignupForm, LoginForm, BlogForm, EditBlogForm, CommentForm, ProfileForm\nfrom django.contrib.auth.models import User\nfrom django.contrib.auth import authenticate, login, logout\nfrom django.urls import reverse, reverse_lazy\nfrom .models import Blog, Comment\n\ndef index(request):\n username = None\n blog_list = None\n comment_form = CommentForm()\n if request.user:\n user = request.user\n blog_list = Blog.objects.order_by('-created_date')\n context = {\n 'user': user,\n 'blog_list':blog_list, \n 'comment_form': comment_form,\n 'Blog': Blog\n }\n return render(request,'blogs/home.html',context)\n\ndef blog_page(request):\n form =BlogForm()\n return render(request, 'blogs/create_blog.html', {\"form\": form})\n\ndef create_blog(request):\n if request.method == 'POST':\n form = BlogForm(request.POST,request.FILES)\n if form.is_valid():\n if request.user.is_authenticated:\n title = form.cleaned_data.get('title')\n body = form.cleaned_data.get('body')\n picture = form.cleaned_data.get('picture')\n if picture is not None:\n blog = Blog(title=title, body=body, picture=picture, user=request.user)\n blog.save()\n else:\n blog = Blog(title=title, body=body, user=request.user)\n blog.save() \n return redirect(reverse('index'))\n else:\n return HttpResponse('Please log in')\n else:\n form = BlogForm()\n\ndef delete_blog(request,blog_id):\n blog = Blog.objects.get(pk=blog_id)\n if blog is not None:\n blog.delete()\n return redirect(reverse('index'))\n\ndef edit_blog_page(request,blog_id):\n blog = Blog.objects.get(pk=blog_id)\n \n if blog is not None:\n intial_data = {\n 'title': blog.title,\n 'body':blog.body,\n 'picture': blog.picture\n }\n form = EditBlogForm(initial=intial_data)\n return render(request,'blogs/edit_blog.html',{'form': form, \"blog\": blog})\n\ndef edit_blog(request, blog_id):\n if request.method == 'POST':\n form = BlogForm(request.POST, request.FILES)\n if form.is_valid():\n if request.user.is_authenticated:\n title = form.cleaned_data.get('title')\n body = form.cleaned_data.get('body')\n picture = form.cleaned_data.get('picture')\n \n blog = Blog.objects.get(pk=blog_id)\n if blog is not None:\n blog.title = title\n blog.body = body\n blog.picture = picture\n blog.save()\n return redirect(reverse('index'))\n else:\n return HttpResponse('Please log in')\n else:\n form = BlogForm()\n\ndef comment(request, blog_id):\n if request.method == 'POST':\n form = CommentForm(request.POST)\n if form.is_valid():\n if request.user.is_authenticated:\n comment = form.cleaned_data.get('comment')\n new_comment = Comment(comment=comment)\n new_comment.save()\n blog = get_object_or_404(Blog, pk=blog_id)\n new_comment.author.add(request.user)\n new_comment.blog.add(blog)\n return redirect(reverse('index'))\n else:\n return HttpResponse(\"You must be logged in\")\n else:\n form = CommentForm()\n\ndef comments_page(request,blog_id):\n blog = Blog.objects.get(pk=blog_id)\n comments = Comment.objects.filter(blog=blog)\n return render(request, 'blogs/comments.html',{'comments': comments})\n\ndef create_profile_page(request):\n form = ProfileForm()\n return render(request, 'blogs/create_profile.html', {\"form\": form})\n\ndef create_profile(request):\n if request.method == 'POST':\n form = ProfileForm(request.POST, request.FILES)\n if form.is_valid():\n if request.user.is_authenticated:\n bio = form.cleaned_data.get('bio')\n profile_picture = form.cleaned_data.get('profile_picture')\n request.user.profile.bio = bio\n request.user.profile.profile_picture = profile_picture\n request.user.profile.save()\n return redirect(reverse('index'))\n else:\n return HttpResponse('Please log in')\n else:\n form = ProfileForm()\n\ndef like_blog(request, blog_id):\n if request.user.is_authenticated:\n blog = get_object_or_404(Blog, id=request.POST.get('blog_id'))\n blog.likes.add(request.user)\n return HttpResponseRedirect(reverse('index'))\n else:\n return HttpResponseRedirect(reverse('index'))\n \ndef signup_form(request):\n form = SignupForm()\n return render(request, 'blogs/signup.html', context={'form': form})\n\ndef personal_blogs(request, user_id):\n user = get_object_or_404(User,pk=user_id)\n blogs = Blog.objects.filter(user=user)\n context={\n 'blogs': blogs\n }\n return render(request, 'blogs/personal_blogs.html', context)\ndef user_signup(request):\n if request.method == 'POST':\n form = SignupForm(request.POST)\n if form.is_valid():\n username = form.cleaned_data.get('username')\n password = form.cleaned_data.get('password')\n \n try:\n user_check = User.objects.get(username=username)\n return HttpResponse(\"User already exists\")\n except User.DoesNotExist:\n\n user = User.objects.create_user(username=username, password=password)\n user.save()\n print(user)\n return redirect(reverse('index'))\n\ndef login_form(request):\n form = LoginForm()\n return render(request, 'blogs/login.html', context={'form': form})\n\ndef user_login(request):\n if request.method == 'POST':\n form = SignupForm(request.POST)\n if form.is_valid():\n username = form.cleaned_data.get('username')\n password = form.cleaned_data.get('password')\n user = authenticate(request, username=username, password=password)\n print(user)\n if user is not None:\n login(request, user)\n return redirect(reverse('index'))\n else:\n return HttpResponse('Invalid log in')\n\ndef user_logout(request):\n logout(request)\n return redirect(reverse('index'))\n \n\n","sub_path":"blogs/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":6740,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"633617557","text":"import time\nimport threading\nimport os, random\n\nnumForks = 5\nnumPhilosophers = 5\ncount = 0\n\nclass Philosopher(threading.Thread):\n \n def __init__(self, index):\n super().__init__()\n self.index = index\n self.leftFork = forks[self.index]\n self.rightFork = forks[(self.index + 1) % numForks]\n\n def run(self):\n global count\n while True:\n if self.leftFork.index > self.rightFork.index:\n firstFork = self.rightFork\n secondFork = self.leftFork\n \n else:\n firstFork = self.leftFork\n secondFork = self.rightFork\n \n\n firstFork.pickup()\n result_list.append([self.index, 2, 1])\n secondFork.pickup()\n result_list.append([self.index, 1, 1])\n \n self.eat()\n\n secondFork.putdown()\n result_list.append([self.index, 1, 2])\n firstFork.putdown()\n result_list.append([self.index, 2, 2])\n \n self.thinking()\n result_list.append([self.index, 0, 3])\n count += 1\n if count >= n:\n break\n \n def eat(self):\n # print (\"Philosopher\", self.index, \" starts to eat.\")\n time.sleep(random.choice([1, 2, 3]))\n # print (\"Philosopher\", self.index, \" finishes eating and leaves to think.\")\n\n print(result_list)\n\n def thinking(self):\n time.sleep(random.choice([1, 2, 3]))\n\nclass Fork():\n def __init__(self, index):\n self.index = index\n self._lock = threading.Lock()\n \n def pickup(self):\n self._lock.acquire()\n\n def putdown(self):\n self._lock.release()\n\nif __name__ == '__main__':\n #创建叉子与哲学家实例\n forks = [Fork(idx) for idx in range(numForks)]\n philosophers = [Philosopher(idx) for idx in range(numPhilosophers)]\n\n result_list=[]\n\n try:\n n = int(input('请输入 0 到 60 的整数:'))\n if 0 <= n <= 60:\n #开启所有的哲学家线程\n count = 0\n for philosopher in philosophers:\n philosopher.start() \n except Exception as e:\n raise \"输入的不是 0 到 60 的整数\"","sub_path":"Week03/homework1.py","file_name":"homework1.py","file_ext":"py","file_size_in_byte":2282,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"112316196","text":"import cv2\r\nimport time\r\nimport numpy as np\r\n\r\nfourcc=cv2.VideoWriter_fourcc(*'XVID')\r\noutput_file=cv2.VideoWriter('output.avi',fourcc,20.0,(640,480))\r\n\r\ncap=cv2.VideoCapture(0)\r\ntime.sleep(3)\r\n\r\nbg=0\r\n\r\nfor i in range(60):\r\n ret,bg=cap.read()\r\n\r\n#flip the background\r\n\r\nbg=np.flip(bg,axis=1)# 1 is x 0 is y\r\n \r\nwhile(cap.isOpened()):\r\n ret,image=cap.read()\r\n if not ret:\r\n break\r\n image=np.flip(image,axis=1)\r\n hsv=cv2.cvtColor(image,cv2.COLOR_BGR2HSV)\r\n lower_black=np.array([104,153,70])\r\n upper_black=np.array([30,30,0])\r\n mask_1=cv2.inRange(hsv,lower_black,upper_black)\r\n\r\n lower_black=np.array([104,153,70])#bgr\r\n upper_black=np.array([30,30,0])\r\n mask_2=cv2.inRange(hsv,lower_black,upper_black)\r\n\r\n mask_1=mask_1+mask_2\r\n\r\n mask1=cv2.morphologyEx(mask_1,cv2.MORPH_OPEN,np.ones((3,3),np.uint8))#diff shape of array,3 by 3 metrix,uint datatypr into int\r\n mask1=cv2.morphologyEx(mask_1,cv2.MORPH_DILATE,np.ones((3,3),np.uint8))\r\n\r\n mask2=cv2.bitwise_not(mask_1)\r\n res_1=cv2.bitwise_and(image,image,mask=mask_2)#part of img without red\r\n\r\n res_2=cv2.bitwise_and(bg,bg,mask=mask_1)#bg with red\r\n\r\n final_output=cv2.addWeighted(res_1,1,res_2,1,0)#combine 2 imgs together,image 1 alpha img2 beta cam\r\n output_file.write(final_output)\r\n\r\n cv2.imshow('magic',final_output)\r\n cv2.waitKey(1)#binding func accept the value in milli second,return a char code for the currently pressed key,-1 if key not pressed\r\n\r\ncap.release()\r\nout.release()\r\ncv2.destroyAllWindows()\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n \r\n\r\n\r\n\r\n#bgr into Heue(in the form of degree 120-green,0 red,240 blue)\r\n# Saturation(encourse the intensity(diff shades)) and value(brightness)\r\n","sub_path":"invisibilitycloak.py","file_name":"invisibilitycloak.py","file_ext":"py","file_size_in_byte":1700,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"209427101","text":"import numpy as np\nfrom your_code import GradientDescent\n\n\nclass MultiClassGradientDescent:\n def __init__(self, loss, regularization=None,\n learning_rate=0.01, reg_param=0.05):\n self.loss = loss\n self.regularization = regularization\n self.learning_rate = learning_rate\n self.reg_param = reg_param\n\n self.model = []\n self.classes = None\n\n def fit(self, features, targets, batch_size=None, max_iter=1000):\n learner = GradientDescent(loss=self.loss, regularization=self.regularization, learning_rate=self.learning_rate, reg_param=self.reg_param)\n\n self.classes = np.unique(targets)\n\n self.model = np.zeros((np.shape(self.classes)[0], features.shape[1] + 1))\n\n for index in range(np.shape(self.classes)[0]):\n learner.fit(features, np.where(targets == self.classes[index], 1, -1), batch_size=batch_size, max_iter=max_iter)\n self.model[index] = learner.model\n\n def predict(self, features):\n ans=np.empty([])\n for i in self.confidence(features):\n ans=np.append(ans, self.classes[np.argmax(i)])\n\n ans=np.delete(ans, 0)\n\n return ans\n\n\n def confidence(self, features):\n features = np.append(features, np.ones((np.shape(features)[0],1)), axis=1)\n\n ans=np.empty([])\n for x in features:\n for weight in self.model:\n ans=np.append(ans, np.dot(np.transpose(weight), x))\n\n ans=np.reshape((np.delete(ans, 0)), (np.shape(features)[0], np.shape(self.model)[0]))\n return ans\n\n\n\n\n\n","sub_path":"src/multiclass_gradient_descent.py","file_name":"multiclass_gradient_descent.py","file_ext":"py","file_size_in_byte":1579,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"489889067","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sun Jun 18 18:42:30 2017\n\n@author: YXF\n\"\"\"\n\nimport tensorflow as tf\nimport os\n\n#初始化变量和模型参数,定义训练闭环中的运算\nW = tf.Variable(tf.zeros([4,3]), name='weights')\nb = tf.Variable(tf.zeros([3]), name='bias')\ndef combine_inputs(X):#线性回归的推断现在用于值的合并\n\treturn tf.matmul(X,W)+b\n\ndef inference(X):#新的推断值是将sigmoid函数运用到前面的合并值的输出\n return tf.nn.softmax(combine_inputs(X))\n\ndef loss(X,Y):#损失函数用交叉熵,tf提供了现成的方法\n\treturn tf.reduce_mean(tf.nn.sparse_softmax_cross_entropy_with_logits(logits=combine_inputs(X),labels=Y))\n\ndef read_csv(batch_size, file_name, record_defaults):\n\tfilename_queue = tf.train.string_input_producer([os.path.dirname(__file__)+\"/\"+file_name])\n\treader = tf.TextLineReader(skip_header_lines=1)\n\tkey, value = reader.read(filename_queue)\n\t\n\tdecoded = tf.decode_csv(value, record_defaults=record_defaults)\n\t#decode_csv会将字符串转换到具有指定默认值的由张量列构成的元组中。\n\treturn tf.train.shuffle_batch(decoded, batch_size=batch_size,\n\t\t\t\t\t\tcapacity=batch_size*50,min_after_dequeue=batch_size)\ndef inputs():#读取或生成训练数据X及其期望输出Y\n\tsepal_length, sepal_width, petal_length, petal_width, label = \\\n\t\tread_csv(100, \"iris.data\", [[0.0],[0.0],[0.0],[0.0],[\"\"]])\n\t#转换属性数据\n\tlabel_number = tf.to_int32(tf.argmax(tf.to_int32(tf.stack([\n\t\ttf.equal(label,['Iris-setosa']),\n\t\ttf.equal(label,['Iris-versicolor']),\n\t\ttf.equal(label,['Iris-virginica']),\t\t\n\t\t])),0))\n\t\n\t#最终将所有特征排列在一个矩阵中,然后对该矩阵转置,使每行对应一个样本\n\tfeatures = tf.transpose(tf.stack([sepal_length, sepal_width, petal_length, petal_width]))\n\treturn features, label_number\n\t\ndef train(total_loss):#依据计算的总损失训练或调整模型参数\n\tlearning_rate = 0.01\n\treturn tf.train.GradientDescentOptimizer(learning_rate).minimize(total_loss)\n\ndef evaluate(sess,X,Y):#对训练得到的模型进行评估\n\tpredicted = tf.cast(tf.arg_max(inference(X),1),tf.int32)\n\tprint(sess.run(tf.reduce_mean(tf.cast(tf.equal(predicted,Y),tf.float32))))\n\n\n#在一个会话对象中启动数据流图,搭建流程\nwith tf.Session() as sess:\n\tsess.run(tf.global_variables_initializer())\n\t\n\tX,Y = inputs()\n\t\n\ttotal_loss = loss(X, Y)\n\ttrain_op = train(total_loss)\n\t\n\tcoord = tf.train.Coordinator()#创建一个协调器,管理线程\n\tthreads = tf.train.start_queue_runners(sess=sess,coord=coord)#创建线程并使用QueueRunner对象来预取\n\t\n\t#实际的训练迭代次数\n\ttraining_steps = 1000\n\tfor step in range(training_steps):\n\t\tsess.run([train_op])\n\t\t#处于调试和学习的目的,查看损失在训练过程中的递减的情况\n\t\tif step%10 == 0:\n\t\t\tprint(\"loss:\",sess.run([total_loss]))\n\tevaluate(sess, X, Y)\n\t\n\tcoord.request_stop()\n\tcoord.join(threads)\n\n\tsess.close()\n\n\t","sub_path":"python_learn/tensorflow_learning/softmax-exp.py","file_name":"softmax-exp.py","file_ext":"py","file_size_in_byte":2928,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"314314934","text":"########\n# Copyright (c) 2014 GigaSpaces Technologies Ltd. All rights reserved\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# * See the License for the specific language governing permissions and\n# * limitations under the License.\n\nimport re\nimport string\nimport time\nfrom functools import wraps\nfrom subprocess import check_output\nfrom os.path import basename, expanduser\nfrom abc import ABCMeta, abstractmethod\n\nimport yaml\nfrom proxy_tools import Proxy\nfrom googleapiclient.errors import HttpError\n\nfrom cloudify import ctx\nfrom cloudify.context import CloudifyContext\nfrom cloudify.exceptions import NonRecoverableError\n\nfrom . import constants\nfrom .gcp import (\n GCPError,\n GoogleCloudPlatform,\n check_response,\n is_missing_resource_error,\n is_resource_used_error,\n )\n\n\ndef camel_farm(identifier):\n \"\"\"\n Convert from underscored to camelCase.\n \"\"\"\n words = identifier.split('_')\n return ''.join([words[0]] + map(string.capitalize, words[1:]))\n\n\ndef get_item_from_gcp_response(key_field, key_name, items):\n \"\"\"\n Get item from GCP REST response JSON list by name.\n items = [{ 'key_field': 'key_name', 'key_field_value': 'value'}]\n :param key_field: item dictionary key\n :param key_value: item dictionary value\n :param items: list of items(dictionaries)\n :return: item if found in collection, None otherwise\n \"\"\"\n for item in items.get('items', []):\n if item.get(key_field) == key_name:\n return item\n return None\n\n\ndef get_gcp_resource_name(name):\n \"\"\"\n Create GCP accepted name of resource. From GCP specification:\n \"Specifically, the name must be 1-63 characters long and match the regular\n expression [a-z]([-a-z0-9]*[a-z0-9])? which means the first character must\n be a lowercase letter, and all following characters must be a dash,\n lowercase letter, or digit, except the last character,\n which cannot be a dash.\"\n :param name: name of resource to be given\n :return: GCP accepted instance name\n \"\"\"\n # replace underscores with hyphens\n final_name = name.replace('_', '-')\n # remove all non-alphanumeric characters except hyphens\n final_name = re.sub(r'[^a-zA-Z0-9-]+', '', final_name)\n # assure the first character is alpha\n if not final_name[0].isalpha():\n final_name = '{0}{1}'.format('a', final_name)\n # trim to the length limit\n if len(final_name) > constants.MAX_GCP_NAME:\n remain_len = constants.MAX_GCP_NAME - len(final_name)\n final_name = '{0}{1}'.format(\n final_name[:remain_len - constants.ID_HASH_CONST],\n final_name[-constants.ID_HASH_CONST:])\n # convert string to lowercase\n return final_name.lower()\n\n\ndef should_use_external_resource():\n return ctx.node.properties.get(constants.USE_EXTERNAL_RESOURCE, False)\n\n\ndef assure_resource_id_correct():\n resource_id = ctx.node.properties.get(constants.RESOURCE_ID)\n if not resource_id:\n raise NonRecoverableError('Resource id is missing.')\n\n if resource_id != get_gcp_resource_name(resource_id):\n raise NonRecoverableError('{} cannot be used as resource id.'\n .format(resource_id))\n return resource_id\n\n\ndef get_final_resource_name(name):\n return name or get_gcp_resource_name(ctx.instance.id)\n\n\ndef create_resource(func):\n def _decorator(resource, *args, **kwargs):\n if should_use_external_resource():\n try:\n resource.body = resource.get()\n except HttpError as error:\n if is_missing_resource_error(error):\n name = ctx.node.properties.get(constants.RESOURCE_ID)\n raise NonRecoverableError(\n 'Resource {0} defined as external, '\n 'but does not exist. Error: {1}'.\n format(name, str(error)))\n else:\n raise error\n ctx.instance.runtime_properties.update(resource.body)\n else:\n return func(resource, *args, **kwargs)\n\n return wraps(func)(_decorator)\n\n\n@create_resource\ndef create(resource):\n return resource.create()\n\n\ndef delete_if_not_external(resource):\n if not should_use_external_resource():\n return resource.delete()\n\n\ndef sync_operation(func):\n def _decorator(resource, *args, **kwargs):\n response = func(resource, *args, **kwargs)\n operation = response_to_operation(\n response, resource.config, resource.logger)\n while not operation.has_finished():\n time.sleep(1)\n return operation.last_response\n\n return wraps(func)(_decorator)\n\n\ndef async_operation(get=False):\n \"\"\"\n Decorator for node methods which return an Operation\n Handles the operation if it exists\n \"\"\"\n def decorator(func):\n def wrapper(self, *args, **kwargs):\n props = ctx.instance.runtime_properties\n response = props.get('_operation', None)\n\n if response:\n operation = response_to_operation(\n response,\n get_gcp_config(),\n ctx.logger)\n response = operation.get()\n\n if response['status'] in ('PENDING', 'RUNNING'):\n ctx.operation.retry(\n 'Operation not completed yet: {}'.format(\n response['status']),\n constants.RETRY_DEFAULT_DELAY)\n elif response['status'] == 'DONE':\n for key in '_operation', 'name', 'selfLink':\n props.pop(key, None)\n if get:\n props.update(self.get())\n else:\n raise NonRecoverableError(\n 'Unknown status response from operation')\n\n else:\n # Actually run the method\n response = func(self, *args, **kwargs)\n ctx.instance.runtime_properties['_operation'] = response\n ctx.operation.retry('Operation started')\n\n return wraps(func)(wrapper)\n return decorator\n\n\ndef retry_on_failure(msg, delay=constants.RETRY_DEFAULT_DELAY):\n def _retry_on_failure(func):\n def _decorator(*args, **kwargs):\n try:\n return func(*args, **kwargs)\n except HttpError as error:\n if is_resource_used_error(error):\n ctx.operation.retry(msg, delay)\n else:\n raise error\n\n return wraps(func)(_decorator)\n\n return _retry_on_failure\n\n\ndef throw_cloudify_exceptions(func):\n def _decorator(*args, **kwargs):\n try:\n return func(*args, **kwargs)\n except GCPError as e:\n raise NonRecoverableError(e.message)\n\n return wraps(func)(_decorator)\n\n\ndef get_gcp_config():\n def _get_gcp_config_from_properties():\n try:\n return ctx.node.properties[constants.GCP_CONFIG]\n except NonRecoverableError:\n return ctx.source.node.properties[constants.GCP_CONFIG]\n\n gcp_config_from_properties = _get_gcp_config_from_properties()\n if gcp_config_from_properties:\n gcp_config = gcp_config_from_properties\n else:\n try:\n with open(expanduser(constants.GCP_DEFAULT_CONFIG_PATH)) as f:\n gcp_config = yaml.load(f)\n except (IOError, OSError) as e:\n raise NonRecoverableError(\n '{} not provided as a property and the config file ({}) '\n 'does not exist either: {}'.format(\n constants.GCP_CONFIG,\n constants.GCP_DEFAULT_CONFIG_PATH,\n e,\n ))\n\n # Validate the config contains what it should\n try:\n for key in 'project', 'auth', 'zone':\n gcp_config[key]\n except Exception as e:\n raise NonRecoverableError(\"invalid gcp_config provided: {}\".format(e))\n\n # If no network is specified, assume the GCP default network, 'default'\n gcp_config.setdefault('network', 'default')\n\n return update_zone(gcp_config)\n\n\ndef update_zone(gcp_config):\n def _get_zone_from_runtime_properties():\n try:\n return ctx.instance.runtime_properties.get(constants.GCP_ZONE)\n except NonRecoverableError:\n src = ctx.source.instance.runtime_properties\n tar = ctx.target.instance.runtime_properties\n return src.get(constants.GCP_ZONE) or tar.get(constants.GCP_ZONE)\n\n non_default_zone = _get_zone_from_runtime_properties()\n if non_default_zone:\n gcp_config['zone'] = non_default_zone\n\n return gcp_config\n\n\ndef is_object_deleted(obj):\n try:\n obj.get()\n except HttpError as error:\n if is_missing_resource_error(error):\n return True\n return False\n\n\ndef get_key_user_string(user, public_key):\n cleaned_user = re.sub(r'\\s+', ' ', user).strip()\n cleaned_public_key = re.sub(r'\\s+', ' ', public_key).strip()\n\n if cleaned_public_key.count(' ') >= 1:\n keytype, key_blob = cleaned_public_key.split(' ')[:2]\n else:\n raise NonRecoverableError('Incorrect format of public key')\n protocol = '{0}:{1}'.format(cleaned_user, keytype)\n\n return '{0} {1} {2}'.format(protocol, key_blob, cleaned_user)\n\n\ndef get_agent_ssh_key_string():\n cloudify_agent = {}\n\n try:\n cloudify_agent.update(\n ctx.provider_context['cloudify']['cloudify_agent'])\n except KeyError:\n pass\n\n # node-specific overrides should take precendence\n # cloudify_agent is deprecated but may still be used.\n for key in 'cloudify_agent', 'agent_config':\n cloudify_agent.update(ctx.node.properties.get(key, {}))\n\n if 'agent_key_path' not in cloudify_agent:\n ctx.logger.debug('agent to be installed but key file info not found')\n return ''\n\n public_key = check_output([\n 'ssh-keygen', '-y', # generate public key from private key\n '-P', '', # don't prompt for passphrase (would hang forever)\n '-f', expanduser(cloudify_agent['agent_key_path'])])\n # add the agent user to the key. GCP uses this to create user accounts on\n # the instance.\n full_key = '{user}:{key} {user}@cloudify'.format(\n key=public_key.strip(),\n user=cloudify_agent['user'])\n\n return full_key\n\n\ndef response_to_operation(response, config, logger):\n if 'zone' in response:\n return ZoneOperation(config, logger, response)\n elif 'region' in response:\n return RegionOperation(config, logger, response)\n else:\n return GlobalOperation(config, logger, response)\n\n\nclass Operation(GoogleCloudPlatform):\n __metaclass__ = ABCMeta\n\n def __init__(self, config, logger, response):\n super(Operation, self).__init__(config, logger, response['name'])\n for item in ('zone', 'region'):\n if item in response:\n setattr(self, item, response[item])\n self.last_response = None\n self.last_status = None\n\n def has_finished(self):\n if self.last_status != constants.GCP_OP_DONE:\n self.get()\n\n return self.last_status == constants.GCP_OP_DONE\n\n @check_response\n def get(self):\n self.last_response = self._get()\n self.last_status = self.last_response['status']\n return self.last_response\n\n @abstractmethod\n def _get(self): pass\n\n\nclass GlobalOperation(Operation):\n def _get(self):\n return self.discovery.globalOperations().get(\n project=self.project,\n operation=self.name).execute()\n\n\nclass RegionOperation(Operation):\n def _get(self):\n return self.discovery.regionOperations().get(\n project=self.project,\n region=basename(self.region),\n operation=self.name).execute()\n\n\nclass ZoneOperation(Operation):\n def _get(self):\n return self.discovery.zoneOperations().get(\n project=self.project,\n zone=basename(self.zone),\n operation=self.name).execute()\n\n\ndef get_relationships(\n relationships,\n filter_relationships=None,\n filter_nodes=None):\n \"\"\"\n Get all relationships of a particular node or the current context.\n\n Optionally filter based on relationship type, node type.\n \"\"\"\n if isinstance(relationships, (CloudifyContext, Proxy)):\n # Shortcut to support supplying ctx directly\n relationships = relationships.instance.relationships\n # And coerce the other inputs to lists if they are strings:\n if isinstance(filter_relationships, basestring):\n filter_relationships = [filter_relationships]\n if isinstance(filter_nodes, basestring):\n filter_nodes = [filter_nodes]\n results = []\n for rel in relationships:\n if filter_relationships and rel.type not in filter_relationships:\n rel = None\n if filter_nodes and rel.target.node.type not in filter_nodes:\n rel = None\n if rel:\n results.append(rel)\n return results\n\n\ndef get_network_node(ctx):\n network_list = get_relationships(\n ctx,\n filter_relationships='cloudify.gcp.relationships.'\n 'contained_in_network',\n )\n if len(network_list) > 0:\n return network_list[0].target\n\n\ndef get_net_and_subnet(ctx):\n \"\"\"\n Returns a tuple of the ctx node's\n (Network, Subnetwork)\n \"\"\"\n net_node = get_network_node(ctx)\n\n subnetwork = None\n if net_node:\n if net_node.node.type == 'cloudify.gcp.nodes.Network':\n network = net_node.instance.runtime_properties['selfLink']\n elif net_node.node.type == 'cloudify.gcp.nodes.SubNetwork':\n network = net_node.instance.runtime_properties['network']\n subnetwork = net_node.instance.runtime_properties['selfLink']\n else:\n raise NonRecoverableError(\n 'Unsupported target type for '\n \"'cloudify.gcp.relationships.instance_contained_in_network\")\n else:\n network = get_gcp_config()['network']\n\n if network == 'default':\n network = 'global/networks/default'\n\n return network, subnetwork\n\n\ndef get_network(ctx):\n return get_net_and_subnet(ctx)[0]\n","sub_path":"cloudify_gcp/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":14718,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"547532249","text":"import pandas as pd\n\nxlsx = pd.ExcelFile('/home/al459/bog_codebase/csdb_extra.xlsx')\nfor sheet in xlsx.sheet_names:\n csvname = sheet.replace('^CL_', '').lower()\n df = pd.read_excel(xlsx, sheet)\n repl = lambda m: f\"('{m.group(0)}', \"\n df['code'] = df.code.astype('str').str.replace(r'.*', repl)\n repl = lambda m: f\"{{'en': '{m.group(0)}'}}),\"\n df['description'] = df.description.str.replace(r'.*', repl)\n df['result'] = df.code + df.description\n df[['result']].to_csv(f'{csvname}.csv', index=False)\n","sub_path":"csdb_sc1.py","file_name":"csdb_sc1.py","file_ext":"py","file_size_in_byte":522,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"208362635","text":"# import time\n\n__author__ = 'sergey'\n\n# time - O(2^n)\ndef fib_rec(n, a=0, b=1):\n if n == 0:\n return a\n else:\n return fib_rec(n - 1, b, a + b)\n\n\n# time - O(n), memory O(1)\ndef fib_iter(n):\n if n == 0:\n return 0\n a = 0\n b = 1\n c = 1\n for i in range(2, n + 1):\n c = a + b\n a, b = b, c\n return c\n\n\n# time - O(log(n)), memory O(1) - linear algebra makes magic\ndef fib_magic(n):\n a = 1\n ta = 1\n b = 1\n tb = 1\n c = 1\n tc = 0\n rc = 0\n d = 0\n rd = 1\n while n:\n if n & 1:\n tc = rc\n rc = rc * a + rd * c\n rd = tc * b + rd * d\n ta = a\n tb = b\n tc = c\n a = a * a + b * c\n b = ta * b + b * d\n c = c * ta + d * c\n d = tc * tb + d * d\n n >>= 1\n return rc\n\n\ndef test(fn):\n samples = [(1, 1), (2, 1), (3, 2), (4, 3),\n (5, 5), (6, 8), (7, 13), (100, 354224848179261915075)]\n for a, b in samples:\n if fn(a) != b:\n print(\"func \" + fn.__name__ + \" work is not correct\")\n return\n print(\"func \" + fn.__name__ + \" work is correct\")\n\n\nif __name__ == \"__main__\":\n test(fib_rec)\n test(fib_iter)\n test(fib_magic)\n","sub_path":"source/lab9.py","file_name":"lab9.py","file_ext":"py","file_size_in_byte":1233,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"565104420","text":"#!/usr/bin/env python\n# coding: utf-8 :\n#\n# Author: Ryo Akita\n# URL: http://www.ai.cs.kobe-u.ac.jp/~akita/\n# License: MIT License\n# Created: 2016-01-09\n#\n\nimport commands\nimport re\nfrom utils import get_hostname\n\n\ndef parse_gpu_detail(i, line, gpu_info, timestamp, hostname):\n column = line.split()\n if len(column) < 5 and i % 3 != 2:\n exit()\n if i % 3 == 0:\n gpu_id = column[0]\n index_gpu_name = 0\n for elem in column[1:]:\n index_gpu_name += 1\n if elem == 'Off' or elem == 'On':\n break\n gpu_name = ' '.join(e for e in column[1:index_gpu_name])\n return '{}\\t{}\\t{}'.format(hostname, gpu_id, gpu_name)\n\n if i % 3 == 1:\n fan = column[0]\n temperature = column[1]\n used = column[6]\n total = column[8]\n with open('/var/log/gpu_info.log', 'a') as fp:\n fp.write('{}\\t{}\\t{}\\t{}\\t{}\\n'.format(\n gpu_info, fan[:-1], temperature[:-1], used[:-3], total[:-3]))\n\n\ndef parse_ps(ps_result, pid):\n ps_result = ps_result.strip().split('\\n')\n for r in ps_result:\n r = r.split()\n if len(r) < 10:\n exit()\n user = r[0]\n ps_pid = r[1]\n cpu = r[2]\n mem = r[3]\n vsz = r[4]\n rss = r[5]\n tty = r[6]\n stat = r[7]\n start = r[8]\n time = r[9]\n com = ' '.join(e for e in r[10:])\n if pid == ps_pid:\n return user, ps_pid, com\n\n\ndef main():\n result = commands.getoutput(\"nvidia-smi\")\n result = re.sub('[-+=|]', '', result)\n result = result.strip().split('\\n')\n\n hostname = get_hostname()\n\n timestamp = result[0]\n\n gpu_detail = 0\n gpu_info = ''\n if len(result) < 7:\n exit()\n for i, line in enumerate(result[7:]):\n gpu_info = parse_gpu_detail(i, line, gpu_info, timestamp, hostname)\n\n if line == '' and result[i + 8].strip() == '':\n gpu_detail = i\n break\n\n for i, line in enumerate(result[gpu_detail + 13:]):\n column = line.split()\n if len(column) == 5:\n process_gpu = column[0]\n pid = column[1]\n usage = column[-1]\n ps_result = commands.getoutput(\"ps aux | grep {}\".format(pid))\n user, ps_pid, com = parse_ps(ps_result, pid)\n with open('/var/log/gpu_ps.log', 'a') as fp:\n fp.write('{}\\t{}\\t{}\\t{}\\n'.format(\n hostname, user, ps_pid, com))\n with open('/var/log/gpu_job.log', 'a') as fp:\n fp.write('{}\\t{}\\t{}\\t{}\\n'.format(\n hostname, process_gpu, pid, usage[:-3]))\n\nif __name__ == '__main__':\n main()\n","sub_path":"parse_nvidia_smi.py","file_name":"parse_nvidia_smi.py","file_ext":"py","file_size_in_byte":2688,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"421327883","text":"\"\"\"\nHippyBase client module.\n\"\"\"\n\nimport requests\nfrom . import schema_pb2\n\nOK = 200\nCREATED = 201\nNO_CONTENT = 204\nFORBIDDEN = 403\nNOT_FOUND = 404\nINTERNAL_SERVER_ERROR = 500\n\n\ndef _make_row(cell_list, include_timestamp):\n \"\"\"\n Make a row dict for a cell mapping\n \"\"\"\n return {\n cell.column.decode(): (cell.data.decode(), cell.timestamp) if include_timestamp else cell.data.decode()\n for cell in cell_list\n }\n\n\nclass HbaseServerError(RuntimeError):\n \"\"\"\n Hbase Server returns errors.\n \"\"\"\n\n def __init__(self, code=None, msg=None):\n text = ''\n if code:\n text += 'Return Code: %d' % code\n if msg:\n text += '\\n%s' % msg\n super().__init__(text)\n\n\nclass Client:\n \"\"\"\n REST Client object.\n\n Parameters\n ----------\n host : str\n Hostname or IP address.\n port : int\n Port number.\n \"\"\"\n\n def __init__(self, host, port):\n self._host = host\n self._port = port\n self._base_url = 'http://%s:%d' % (host, port)\n self._session = requests.Session()\n\n def get_version(self):\n \"\"\"\n Retrieve the Hbase software version.\n\n Returns\n -------\n dict[str]\n Hbase software version\n\n Raises\n ------\n HbaseServerError\n Server returns other errors.\n \"\"\"\n response = self._session.get(\n url='/'.join((self._base_url, 'version')),\n headers={\n 'Accept': 'application/x-protobuf'\n }\n )\n code = response.status_code\n if code == OK:\n version = schema_pb2.Version()\n version.ParseFromString(response.content)\n return {\n 'rest_version': version.restVersion,\n 'jvm_version': version.jvmVersion,\n 'os_version': version.osVersion,\n 'server_version': version.serverVersion,\n 'jersey_version': version.jerseyVersion\n }\n raise HbaseServerError(code, response.text)\n\n def get_namespaces(self):\n \"\"\"\n List all namespaces.\n\n Returns\n -------\n list[str]\n List of all namespace names.\n\n Raises\n ------\n HbaseServerError\n Server returns other errors.\n \"\"\"\n response = self._session.get(\n url='/'.join((self._base_url, 'namespaces')),\n headers={\n 'Accept': 'application/x-protobuf'\n }\n )\n code = response.status_code\n if code == OK:\n namespaces = schema_pb2.Namespaces()\n namespaces.ParseFromString(response.content)\n return namespaces.namespace\n raise HbaseServerError(code, response.text)\n\n def get_namespace(self, namespace):\n \"\"\"\n Retrieve a specific namespace.\n\n Parameters\n ----------\n namespace : str\n Name of the namespace.\n\n Returns\n -------\n dict\n Descriptions of the namespace.\n None\n The namespace does not exist.\n\n Raises\n ------\n HbaseServerError\n Server returns other errors.\n \"\"\"\n response = self._session.get(\n url='/'.join((self._base_url, 'namespaces', namespace)),\n headers={\n 'Accept': 'application/x-protobuf'\n }\n )\n code = response.status_code\n if code == OK:\n namespace_properties = schema_pb2.NamespaceProperties()\n namespace_properties.ParseFromString(response.content)\n return {\n prop.key: prop.value\n for prop in namespace_properties.props\n }\n if code in (NOT_FOUND, INTERNAL_SERVER_ERROR):\n return None\n raise HbaseServerError(code, response.text)\n\n def create_namespace(self, namespace, props=None):\n \"\"\"\n Create a new namespace.\n\n Parameters\n ----------\n namespace : str\n Name of the namespace.\n props : dict, optional\n Properties of the namespace, by default None\n\n Returns\n -------\n True\n The Namespace is created.\n False\n The Namespace already exists.\n\n Raises\n ------\n TypeError\n The type of props is not 'dict'.\n HbaseServerError\n Server returns other errors.\n \"\"\"\n namespace_properties = schema_pb2.NamespaceProperties()\n if props:\n if not isinstance(props, dict):\n raise TypeError(\"props: expect 'dict', get '%s'.\" % type(props).__name__)\n for key, value in props.items():\n prop = namespace_properties.props.add()\n prop.key = key\n prop.value = value\n response = self._session.post(\n url='/'.join((self._base_url, 'namespaces', namespace)),\n headers={\n 'Accept': 'application/x-protobuf',\n 'Content-Type': 'application/x-protobuf'\n },\n data=namespace_properties.SerializeToString()\n )\n code = response.status_code\n if code == CREATED:\n return True\n if code == FORBIDDEN:\n # namespace already exists\n return False\n raise HbaseServerError(code, response.text)\n\n def delete_namespace(self, namespace):\n \"\"\"\n Delete a namespace.\n\n Parameters\n ----------\n namespace : str\n Name of the namespace.\n\n Returns\n -------\n True\n The namespace is deleted.\n False\n The namespace does not exists.\n\n Raises\n ------\n HbaseServerError\n Server returns other errors.\n \"\"\"\n response = self._session.delete(\n url='/'.join((self._base_url, 'namespaces', namespace)),\n headers={\n 'Accept': 'application/x-protobuf'\n }\n )\n code = response.status_code\n if code == OK:\n return True\n if code == NOT_FOUND:\n # namespace does not exists\n return False\n raise HbaseServerError(code, response.text)\n\n def get_tables(self, namespace=None):\n \"\"\"\n List all nonsystem tables if namespace is None.\n Otherwise, list all tables in a specific namespace.\n\n Parameters\n ----------\n namespace : str, optional\n Name of the namespace, by default None\n\n Returns\n -------\n list[str]\n List of all table names.\n None\n The namespace does not exist.\n\n Raises\n ------\n HbaseServerError\n Server returns other errors.\n \"\"\"\n if namespace is None:\n response = self._session.get(\n url=self._base_url,\n headers={\n 'Accept': 'application/x-protobuf'\n }\n )\n code = response.status_code\n if code == OK:\n table_list = schema_pb2.TableList()\n table_list.ParseFromString(response.content)\n return table_list.name\n raise HbaseServerError(code, response.text)\n\n response = self._session.get(\n url='/'.join((self._base_url, 'namespaces', namespace, 'tables')),\n headers={\n 'Accept': 'application/x-protobuf'\n }\n )\n code = response.status_code\n if code == OK:\n table_list = schema_pb2.TableList()\n table_list.ParseFromString(response.content)\n return table_list.name\n if code in (NOT_FOUND, INTERNAL_SERVER_ERROR):\n return None\n raise HbaseServerError(code, response.text)\n\n def get_table_schema(self, table_name):\n \"\"\"\n Retrieve the schema of the specified table.\n\n Parameters\n ----------\n table_name : str\n Name of the table.\n\n Returns\n -------\n dict\n Schema of the table.\n None\n The table does not exist.\n\n Raises\n ------\n HbaseServerError\n Server returns other errors.\n \"\"\"\n response = self._session.get(\n url='/'.join((self._base_url, table_name, 'schema')),\n headers={\n 'Accept': 'application/x-protobuf'\n }\n )\n code = response.status_code\n if code == OK:\n table_schema = schema_pb2.TableSchema()\n table_schema.ParseFromString(response.content)\n return {\n 'name': table_schema.name,\n 'columns': [\n {\n 'name': column.name,\n 'ttl': column.ttl,\n 'max_versions': column.maxVersions,\n 'compression': column.compression,\n 'attrs': {\n attr.name: attr.value\n for attr in column.attrs\n }\n }\n for column in table_schema.columns\n ],\n 'in_memory': table_schema.inMemory,\n 'read_only': table_schema.readOnly,\n 'attrs': {\n attr.name: attr.value\n for attr in table_schema.attrs\n }\n }\n if code in (NOT_FOUND, INTERNAL_SERVER_ERROR):\n return None\n raise HbaseServerError(code, response.text)\n\n def create_table(self, table_name, families):\n \"\"\"\n Create a new table, or replace an existing table's schema with the provided schema.\n\n The `families` argument is a dictionary mapping column family\n names to a dictionary containing the options for this column\n family, e.g.\n ::\n families = {\n 'cf1': dict(max_versions=10),\n 'cf2': dict(max_versions=1, compression=False),\n 'cf3': dict(), # use defaults\n }\n connection.create_table('mytable', families)\n\n The following options are supported:\n * ``ttl`` (`int`)\n * ``max_versions`` (`int`)\n * ``compression`` (`str`)\n\n Parameters\n ----------\n table_name : str\n Name of the table.\n families : dict[str, dict]\n The name and options for each column family.\n\n Returns\n -------\n True\n Table is created.\n False\n Table already exists and is updated.\n\n Raises\n ------\n HbaseServerError\n Server returns other errors.\n \"\"\"\n table_schema = schema_pb2.TableSchema()\n table_schema.name = table_name\n for cf_name, options in families.items():\n column = table_schema.columns.add()\n column.name = cf_name\n if 'ttl' in options:\n column.ttl = options.pop('ttl')\n if 'max_versions' in options:\n column.maxVersions = options.pop('max_versions')\n if 'compression' in options:\n column.compression = options.pop('compression')\n for name, value in options.items():\n attr = column.attrs.add()\n attr.name = str(name).upper()\n attr.value = str(value).upper()\n\n response = self._session.post(\n url='/'.join((self._base_url, table_name, 'schema')),\n headers={\n 'Accept': 'application/x-protobuf',\n 'Content-Type': 'application/x-protobuf',\n },\n data=table_schema.SerializeToString()\n )\n code = response.status_code\n if code == CREATED:\n return True\n if code == OK:\n # table already exists\n return False\n raise HbaseServerError(code, response.text)\n\n def delete_table(self, table_name):\n \"\"\"\n Delete the table.\n\n Parameters\n ----------\n table_name : str\n Name of the table.\n\n Returns\n -------\n True\n The table is deleted.\n False\n The table does not exist.\n\n Raises\n ------\n HbaseServerError\n Server returns other errors.\n \"\"\"\n response = self._session.delete(\n url='/'.join((self._base_url, table_name, 'schema')),\n headers={\n 'Accept': 'application/x-protobuf'\n }\n )\n code = response.status_code\n if code == OK:\n return True\n if code == NOT_FOUND:\n # table does not exists\n return False\n raise HbaseServerError(code, response.text)\n\n def get_row(self, table_name, row_key, columns=None, timestamp=None, include_timestamp=False):\n \"\"\"\n Retrieve a single row of data.\n\n Parameters\n ----------\n table_name : str\n Name of the table.\n row_key : str\n The row key.\n columns : list, optional\n List of columns to fetch, by default None\n timestamp : int, optional\n Timestamp, by default None\n include_timestamp : bool, optional\n Whether timestamps are returned, by default False\n\n Returns\n -------\n dict[str, str]\n Mapping of columns to values.\n\n Raises\n ------\n HbaseServerError\n Server returns other errors.\n \"\"\"\n url = '/'.join((self._base_url, table_name, row_key))\n if columns:\n url += '/' + ','.join(columns)\n if timestamp:\n url += '/' + timestamp + ',' + (timestamp + 1)\n response = self._session.get(\n url=url,\n headers={\n 'Accept': 'application/x-protobuf'\n }\n )\n code = response.status_code\n if code == OK:\n cell_set = schema_pb2.CellSet()\n cell_set.ParseFromString(response.content)\n rows = cell_set.rows\n if not rows:\n return {}\n return _make_row(rows[0].values, include_timestamp)\n if code == NOT_FOUND:\n return {}\n raise HbaseServerError(code, response.text)\n\n def put_row(self, table_name, row_key, row_data, timestamp=None):\n \"\"\"\n Store data in the table.\n\n This method stores the data in the `row_data` argument for the row\n specified by `row`. The `row_data` argument is dictionary that maps columns\n to values. Column names must include a family and qualifier part, e.g.\n ``b'cf:col'``, though the qualifier part may be the empty string, e.g.\n ``b'cf:'``.\n\n Parameters\n ----------\n table_name : str\n Name of the table.\n row_key : str\n The row key.\n row_data : dict[str, str]\n The data to store.\n timestamp : int, optional\n Timestamp, by default None\n\n Returns\n -------\n True\n The data is stored.\n\n Raises\n ------\n HbaseServerError\n Server returns other errors.\n \"\"\"\n cell_set = schema_pb2.CellSet()\n row = cell_set.rows.add()\n row.key = row_key.encode()\n for column, data in row_data.items():\n cell = row.values.add()\n cell.column = column.encode()\n cell.data = data.encode()\n if timestamp:\n cell.timestamp = timestamp\n\n response = self._session.put(\n url='/'.join((self._base_url, table_name, 'false_row')),\n headers={\n 'Accept': 'application/x-protobuf',\n 'Content-Type': 'application/x-protobuf',\n },\n data=cell_set.SerializeToString()\n )\n code = response.status_code\n if code == OK:\n return True\n raise HbaseServerError(code, response.text)\n\n def delete_row(self, table_name, row_key):\n \"\"\"\n Delete data from the table.\n\n This method deletes all columns for the row specified by `row_key`.\n\n Parameters\n ----------\n table_name : str\n Name of the table.\n row_key : str\n The row key.\n\n Returns\n -------\n True\n The data is deleted.\n False\n The data does not exist.\n\n Raises\n ------\n HbaseServerError\n Server returns other errors.\n \"\"\"\n response = self._session.delete(\n url='/'.join((self._base_url, table_name, row_key)),\n headers={\n 'Accept': 'application/x-protobuf'\n }\n )\n code = response.status_code\n if code == OK:\n return True\n if code == NOT_FOUND:\n return False\n raise HbaseServerError(code, response.text)\n\n def create_scanner(self,\n table_name,\n start_row=None,\n end_row=None,\n columns=None,\n cell_batch=None,\n start_time=None,\n end_time=None,\n filter_string=None,\n caching=None):\n \"\"\"\n Allocate a new table scanner.\n\n Parameters\n ----------\n table_name : str\n Name of the table.\n start_row : str, optional\n Start row key, by default None\n end_row : str, optional\n End row key, by default None\n columns : list, optional\n List of columns to fetch, by default None\n cell_batch : int, optional\n The maximum number of cells to return for each iteration, by default None\n start_time : int, optional\n Start timestamp, by default None\n end_time : int, optional\n End_timestamp, by default None\n filter_string : str, optional\n A filter string, by default None\n caching : int, optional\n Scanner caching, by default None\n\n Returns\n -------\n str\n The URI which should be used to address the scanner.\n None\n The table does not exist.\n\n Raises\n ------\n HbaseServerError\n Server returns other errors.\n \"\"\"\n scanner = schema_pb2.Scanner()\n if start_row:\n scanner.startRow = start_row.encode()\n if end_row:\n scanner.endRow = end_row.encode()\n if columns:\n for col in columns:\n scanner.columns.append(col.encode())\n if cell_batch:\n scanner.batch = cell_batch\n if start_time:\n scanner.startTime = start_time\n if end_time:\n scanner.endTime = end_time\n if filter_string:\n scanner.filter = str(filter_string)\n if caching:\n scanner.caching = caching\n\n response = self._session.post(\n url='/'.join((self._base_url, table_name, 'scanner')),\n headers={\n 'Accept': 'application/x-protobuf',\n 'Content-Type': 'application/x-protobuf',\n },\n data=scanner.SerializeToString()\n )\n code = response.status_code\n if code == CREATED:\n return response.headers['Location']\n if code == NOT_FOUND:\n return None\n raise HbaseServerError(code, response.text)\n\n def delete_scanner(self, scanner_loc):\n \"\"\"\n Delete resources associated with the scanner.\n\n Parameters\n ----------\n scanner_loc : str\n The URI which should be used to address the scanner.\n\n Returns\n -------\n True\n The scanner is deleted.\n\n Raises\n ------\n HbaseServerError\n Server returns other errors.\n \"\"\"\n response = self._session.delete(\n url=scanner_loc,\n headers={\n 'Accept': 'application/x-protobuf'\n }\n )\n code = response.status_code\n if code == OK:\n return True\n raise HbaseServerError(code, response.text)\n\n def iter_scanner(self, scanner_loc, row_batch=None, include_timestamp=False):\n \"\"\"\n Iterate a scanner.\n\n Parameters\n ----------\n scanner_loc : str\n The URI which should be used to address the scanner.\n row_batch : int\n The maximum number of rows to return in each REST request, by default None\n include_timestamp : bool, optional\n Whether timestamps are returned, by default False\n\n Returns\n -------\n list[tuple]\n List of `(row_key, row_data)` tuples.\n\n Raises\n ------\n HbaseServerError\n Server returns other errors.\n \"\"\"\n\n if row_batch:\n scanner_loc += '?n=' + str(row_batch)\n\n response = self._session.get(\n url=scanner_loc,\n headers={\n 'Accept': 'application/x-protobuf'\n }\n )\n code = response.status_code\n if code == OK:\n cell_set = schema_pb2.CellSet()\n cell_set.ParseFromString(response.content)\n return [\n (row.key.decode(), _make_row(row.values, include_timestamp))\n for row in cell_set.rows\n ]\n if code == NO_CONTENT:\n return None\n raise HbaseServerError(code, response.text)\n","sub_path":"hippybase/client.py","file_name":"client.py","file_ext":"py","file_size_in_byte":21757,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"384442789","text":"#!/usr/bin/env python\n\nimport re\nimport sys\nimport gzip\nimport argparse\nfrom collections import defaultdict\nimport xml.etree.ElementTree as ET\n\n# to test: ./parse_clinvar_xml.py -x clinvar_test.xml\n# to run for reals: bsub -q priority -R rusage[mem=32] -oo cvxml.o -eo cvxml.e -J cvxml \"./parse_clinvar_xml.py -x ClinVarFullRelease_00-latest.xml.gz -o clinvar_table.tsv\"\n# then sort it: cat clinvar_table.tsv | head -1 > clinvar_table_sorted.tsv; cat clinvar_table.tsv | tail -n +2 | sort -k1,1 -k2,2n -k3,3 -k4,4 >> clinvar_table_sorted.tsv\n\nmentions_pubmed_regex = '(?:PubMed|PMID)(.*)' # group(1) will be all the text after the word PubMed or PMID\nextract_pubmed_id_regex = '[^0-9]+([0-9]+)[^0-9](.*)' # group(1) will be the first PubMed ID, group(2) will be all remaining text\n\ndef replace_semicolons(s, replace_with=\":\"):\n return s.replace(\";\", replace_with)\n\ndef remove_newlines_and_tabs(s):\n return re.sub(\"[\\t\\n\\r]\", \" \", s)\n\ndef parse_clinvar_tree(handle,dest=sys.stdout,verbose=True,mode='collapsed'):\n # print a header row\n header = [\n 'chrom', 'pos', 'ref', 'alt', 'mut', 'measureset_id', 'all_submitters', 'all_traits', 'all_pmids',\n 'inheritance_modes', 'age_of_onset', 'prevalence', 'disease_mechanism', 'xrefs'\n ]\n dest.write(('\\t'.join(header) + '\\n').encode('utf-8'))\n counter = 0\n skipped_counter = defaultdict(int)\n for event, elem in ET.iterparse(handle):\n if elem.tag != 'ClinVarSet' or event != 'end':\n continue\n\n # find the GRCh37 VCF representation\n grch37_location = None\n for sequence_location in elem.findall(\".//SequenceLocation\"):\n if sequence_location.attrib.get('Assembly') == 'GRCh37':\n if all(sequence_location.attrib.get(key) is not None for key in ('Chr', 'start', 'referenceAllele','alternateAllele')):\n grch37_location = sequence_location\n\n if grch37_location is None:\n skipped_counter['missing SequenceLocation'] += 1\n elem.clear()\n continue # don't bother with variants that don't have a VCF location\n\n measuresets = elem.findall('.//MeasureSet')\n if measuresets is None:\n skipped_counter['missing MeasureSet'] += 1\n elem.clear()\n continue # skip variants without a MeasureSet ID\n\n current_row = {}\n current_row['chrom'] = grch37_location.attrib['Chr']\n current_row['pos'] = grch37_location.attrib['start']\n current_row['ref'] = grch37_location.attrib['referenceAllele']\n current_row['alt'] = grch37_location.attrib['alternateAllele']\n current_row['measureset_id'] = measuresets[0].attrib['ID']\n\n # iterate over attributes in the MeasureSet\n current_row['mut'] = 'ALT' # default is that each entry refers to the alternate allele\n for attribute in elem.findall('.//Attribute'):\n attribute_type = attribute.attrib.get('Type')\n if attribute_type is not None and \"HGVS\" in attribute_type and \"protein\" not in attribute_type: # if this is an HGVS cDNA, _not_ protein, annotation:\n if attribute.text is not None and \"=\" in attribute.text: # and if there is an equals sign in the text, then\n current_row['mut'] = 'REF' # that is their funny way of saying this assertion refers to the reference allele\n\n # init list fields\n\n # find all the Citation nodes, and get the PMIDs out of them\n pmids = []\n for citation in elem.findall('.//Citation'):\n pmids += [id_node.text for id_node in citation.findall('.//ID') if id_node.attrib.get('Source') == 'PubMed']\n\n # now find the Comment nodes, regex your way through the comments and extract anything that appears to be a PMID\n comment_pmids = []\n for comment in elem.findall('.//Comment'):\n mentions_pubmed = re.search(mentions_pubmed_regex,comment.text)\n if mentions_pubmed is not None and mentions_pubmed.group(1) is not None:\n remaining_text = mentions_pubmed.group(1)\n while True:\n pubmed_id_extraction = re.search(extract_pubmed_id_regex,remaining_text)\n if pubmed_id_extraction is None:\n break\n elif pubmed_id_extraction.group(1) is not None:\n comment_pmids.append( pubmed_id_extraction.group(1) )\n if pubmed_id_extraction.group(2) is not None:\n remaining_text = pubmed_id_extraction.group(2)\n\n current_row['all_pmids'] = ','.join(sorted(set(pmids + comment_pmids)))\n\n # now find any/all submitters\n current_row['all_submitters'] = ';'.join([\n submitter_node.attrib['submitter'].replace(';', ',')\n for submitter_node in elem.findall('.//ClinVarSubmissionID')\n if submitter_node.attrib is not None and submitter_node.attrib.has_key('submitter')\n ])\n\n # init new fields\n for list_column in ('inheritance_modes', 'age_of_onset', 'prevalence', 'disease_mechanism', 'xrefs'):\n current_row[list_column] = set()\n\n # now find the disease(s) this variant is associated with\n current_row['all_traits'] = []\n for traitset in elem.findall('.//TraitSet'):\n disease_name_nodes = traitset.findall('.//Name/ElementValue')\n trait_values = []\n for disease_name_node in disease_name_nodes:\n if disease_name_node.attrib is not None and disease_name_node.attrib.get('Type') == 'Preferred':\n trait_values.append(disease_name_node.text)\n current_row['all_traits'] += trait_values\n\n for attribute_node in traitset.findall('.//AttributeSet/Attribute'):\n attribute_type = attribute_node.attrib.get('Type')\n if attribute_type in {'ModeOfInheritance', 'age of onset', 'prevalence', 'disease mechanism'}:\n column_name = 'inheritance_modes' if attribute_type == 'ModeOfInheritance' else attribute_type.replace(' ', '_')\n column_value = attribute_node.text.strip()\n if column_value:\n current_row[column_name].add(column_value)\n\n for xref_node in traitset.findall('.//XRef'):\n xref_db = xref_node.attrib.get('DB')\n xref_id = xref_node.attrib.get('ID')\n current_row['xrefs'].add(\"%s:%s\" % (xref_db, xref_id))\n\n # done parsing the xml for this one clinvar set.\n elem.clear()\n\n # convert collection to string for the following fields\n for column_name in ('all_traits', 'inheritance_modes', 'age_of_onset', 'prevalence', 'disease_mechanism', 'xrefs'):\n column_value = current_row[column_name] if type(current_row[column_name]) == list else sorted(current_row[column_name]) # sort columns of type 'set' to get deterministic order\n current_row[column_name] = remove_newlines_and_tabs(';'.join(map(replace_semicolons, column_value)))\n\n # write out the current_row\n dest.write(('\\t'.join([current_row[column] for column in header]) + '\\n').encode('utf-8'))\n counter += 1\n if counter % 100 == 0:\n dest.flush()\n if verbose:\n sys.stderr.write(\"{0} entries completed, {1}, {2} total \\r\".format(\n counter, ', '.join('%s skipped due to %s' % (v, k) for k, v in skipped_counter.items()),\n counter + sum(skipped_counter.values())))\n sys.stderr.flush()\n sys.stderr.write(\"Done\\n\")\n\n\ndef get_handle(path):\n if path[-3:] == '.gz':\n handle = gzip.open(path)\n else:\n handle = open(path)\n return (handle)\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser(description='Extract PMIDs from the ClinVar XML dump')\n parser.add_argument('-x','--xml', dest='xml_path',\n type=str, help='Path to the ClinVar XML dump')\n parser.add_argument('-o', '--out', nargs='?', type=argparse.FileType('w'),\n default=sys.stdout)\n args = parser.parse_args()\n parse_clinvar_tree(get_handle(args.xml_path),dest=args.out)\n","sub_path":"src/parse_clinvar_xml.py","file_name":"parse_clinvar_xml.py","file_ext":"py","file_size_in_byte":8227,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"86194514","text":"# import necessary packages\n\nfrom simpletransformers.classification import ClassificationModel\nimport pandas as pd\nimport json\nfrom emot.emo_unicode import UNICODE_EMO\nfrom gensim.parsing.preprocessing import remove_stopwords\n\n# Initialize variables\n\nDATA_PATH = './data/test.jsonl'\nFINAL_RESULTS = 'answer.txt'\nMODEL_LOCATION = 'outputs'\nMODEL_TYPE = 'bert'\n\nword_dist = []\npred = []\n\n# Converts emojis into text\ndef convert_emojis(text):\n for emot in UNICODE_EMO:\n text = text.replace(emot, \"_\".join(UNICODE_EMO[emot].replace(\",\", \"\").replace(\":\", \"\").split()))\n return text\n\n\ndef predict_sarcasm(data_path, results, model_loc, model):\n # Bringing in the test data\n with open(data_path, 'r') as json_file:\n json_list = list(json_file)\n\n for json_str in json_list:\n pred.append(json.loads(json_str))\n\n pred_response = [remove_stopwords(convert_emojis(pred[i]['response'])) for i in range(len(pred))]\n pred_id = [pred[i]['id'] for i in range(len(pred))]\n\n model = ClassificationModel(model, model_loc, use_cuda=False)\n\n predictions, raw_outputs = model.predict(pred_response)\n\n pred_bert = pd.DataFrame({\n 'id': pred_id,\n 'label': predictions\n })\n\n pred_bert['label'] = pred_bert['label'].replace([1, 0], ['SARCASM', 'NOT_SARCASM'])\n pd.DataFrame(pred_bert).to_csv(results, header=False, sep=',', index=False)\n\n\npredict_sarcasm(DATA_PATH, FINAL_RESULTS, MODEL_LOCATION, MODEL_TYPE)\n","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":1456,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"378982099","text":"import numpy as np\nimport nitime.timeseries as ts\nimport nitime.analysis as tsa\nimport nitime.viz as viz\n\n#As before the stimuli get read from files: \nmaxdB1 = 76.4286 #Taken from the spike file header\nstim1 = np.loadtxt('data/grasshopper_stimulus1.txt')\nstim1 = (20*1/np.log(10))*(np.log(stim1[:,1]/2.0e-5))\nstim1 = maxdB1-stim1.max()+stim1\n\nmaxdB2 = 71.2 #Taken from the spike file header\nstim2 = np.loadtxt('data/grasshopper_stimulus2.txt')\nstim2 = (20*1/np.log(10))*(np.log(stim2[:,1]/2.0e-5))\nstim2 = maxdB1-stim2.max()+stim2\n\n#This time the time-series is generated from both stimulus arrays: \nstim_time_series = ts.UniformTimeSeries(t0=0,\n data=np.vstack([stim1,stim2]),\n sampling_interval=0.05,\n time_unit='ms') \n\n#Similarly, with the spike times: \nspike_times1 = np.loadtxt('data/grasshopper_spike_times1.txt')\nspike_times2 = np.loadtxt('data/grasshopper_spike_times2.txt')\nspike_times1 = (spike_times1/50).astype(int)\nspike_times2 = (spike_times2/50).astype(int)\nspike_time_series = ts.UniformTimeSeries(t0=0,sampling_interval=0.05,\n time_unit='ms',\n data=np.zeros(stim_time_series.data.shape))\n#Again - spike-times are marked by the presence of a '1':\nspike_time_series.data[0][spike_times1] = 1\nspike_time_series.data[1][spike_times2] = 1\n\n#The analysis and plotting proceeds in exactly the same way as before\nevent_related = tsa.EventRelatedAnalyzer(stim_time_series,\n spike_time_series,len_et=250,\n offset=-200)\n\nfig = viz.plot_tseries(event_related.eta,ylabel='Amplitude (dB SPL)')\nax = fig.get_axes()[0]\nxlim = ax.get_xlim()\nylim = ax.get_ylim()\n#Except we plot both average stimuli:\nmean_stim1 = np.mean(stim_time_series.data[0])\nmean_stim2 = np.mean(stim_time_series.data[1])\nax.plot([xlim[0],xlim[1]],[mean_stim1,mean_stim1],'b--')\nax.plot([xlim[0],xlim[1]],[mean_stim2,mean_stim2],'k--')\nax.plot([0,0],[ylim[0],ylim[1]],'k--')\n\n\n\n\n\n","sub_path":"doc/examples/grasshopper2.py","file_name":"grasshopper2.py","file_ext":"py","file_size_in_byte":2120,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"218654382","text":"from django import forms\r\nfrom django.conf import settings\r\nfrom django.http import HttpResponseRedirect\r\nfrom django.shortcuts import render\r\nfrom django.core.urlresolvers import reverse_lazy\r\nfrom django.contrib.auth.decorators import login_required\r\n\r\nfrom djforms.sustainability.green.forms import PledgeForm\r\nfrom djforms.sustainability.green.models import Pledge\r\n\r\nfrom djtools.utils.mail import send_mail\r\n\r\ndef pledge_form(request):\r\n '''\r\n simple form to submitting a pledge of fealty.\r\n '''\r\n if settings.DEBUG:\r\n TO_LIST = [settings.SERVER_EMAIL]\r\n else:\r\n TO_LIST = settings.SUSTAINABILITY_EMAIL_LIST\r\n BCC = settings.MANAGERS\r\n\r\n user = request.user\r\n anon = True\r\n pledge = None\r\n\r\n if user.username:\r\n anon = False\r\n try:\r\n pledge = Pledge.objects.get(user=user)\r\n except:\r\n pledge = None\r\n\r\n if request.method=='POST':\r\n form = PledgeForm(request.POST)\r\n if form.is_valid() and not pledge:\r\n data = form.save(commit=False)\r\n data.user = request.user\r\n data.save()\r\n subject = \"[Sustainability Pledge] {} {}\".format(\r\n user.first_name,user.last_name\r\n )\r\n send_mail(\r\n request,TO_LIST,subject,user.email,\r\n 'sustainability/green/email.html', data, BCC\r\n )\r\n return HttpResponseRedirect(\r\n reverse_lazy('green_pledge_success')\r\n )\r\n\r\n else:\r\n form = PledgeForm(initial={'user':user})\r\n\r\n return render(\r\n request, 'sustainability/green/form.html',\r\n {'form': form, 'anon': anon, 'pledge':pledge,}\r\n )\r\n\r\n\r\ndef pledge_archives(request):\r\n pledges = Pledge.objects.all().order_by('id')\r\n\r\n return render(\r\n request, 'sustainability/green/archives.html',\r\n {'pledges': pledges,}\r\n )\r\n","sub_path":"djforms/sustainability/green/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1912,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"425194727","text":"import random\n\nclass Arm:\n\n def __init__(self, tag, p):\n self.tag = tag # The tag IE: if, while\n self.value = 0.0\n self.count = 0\n\n self.p = p\n\n def draw(self):\n if random.random() > self.p:\n return 0.0\n else:\n return 1.0\n","sub_path":"Adaptive-Learning/Algorithms/MAB/Arm.py","file_name":"Arm.py","file_ext":"py","file_size_in_byte":293,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"510713494","text":"# /usr/bin/python3\n# -*- coding: utf-8 -*-\n# @Author: wanngfeng\n# @Date: 2021-12-08 17:45:51\n# @Last Modified by: wanngfeng\n# @Last Modified time: 2021-12-08 18:17:04\n\n\nclass ListNode:\n def __init__(self, val=0, next=None):\n self.val = val\n self.next = next\n\n\nclass Solution:\n def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:\n head = cur = ListNode()\n carry = val = 0\n\n while carry or l1 or l2:\n if l1:\n l1, val = l1.next, l1 + val\n if l2:\n l2, val = l2.next, l2 + val\n carry, val = divmod(val, 10)\n cur.next = ListNode(val)\n cur = cur.next\n return head.next\n","sub_path":"algorithm/add_two_numbers.py","file_name":"add_two_numbers.py","file_ext":"py","file_size_in_byte":712,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"444729198","text":"\"\"\"Implementation of instance API.\n\"\"\"\n\nimport fnmatch\nimport importlib\nimport logging\n\nfrom treadmill import admin\nfrom treadmill import authz\nfrom treadmill import context\nfrom treadmill import exc\nfrom treadmill import master\nfrom treadmill import schema\nfrom treadmill import utils\n\nfrom treadmill.api import app\n\n\n_LOGGER = logging.getLogger(__name__)\n\n\n@schema.schema(\n {'allOf': [{'$ref': 'instance.json#/resource'},\n {'$ref': 'instance.json#/verbs/schedule'}]},\n)\ndef _validate(rsrc):\n \"\"\"Validate instance manifest.\"\"\"\n memory_mb = utils.megabytes(rsrc['memory'])\n if memory_mb < 100:\n raise exc.TreadmillError(\n 'memory size should be larger than or equal to 100M')\n\n disk_mb = utils.megabytes(rsrc['disk'])\n if disk_mb < 100:\n raise exc.TreadmillError(\n 'disk size should be larger than or equal to 100M')\n\n\nclass API(object):\n \"\"\"Treadmill Instance REST api.\"\"\"\n\n def __init__(self):\n\n instance_plugin = None\n try:\n instance_plugin = importlib.import_module(\n 'treadmill.plugins.api.instance')\n except ImportError as err:\n _LOGGER.info('Unable to load auth plugin: %s', err)\n\n def _list(match=None):\n \"\"\"List configured instances.\"\"\"\n if match is None:\n match = '*'\n if '#' not in match:\n match += '#*'\n\n instances = master.list_scheduled_apps(context.GLOBAL.zk.conn)\n filtered = [\n inst for inst in instances\n if fnmatch.fnmatch(inst, match)\n ]\n return sorted(filtered)\n\n @schema.schema({'$ref': 'instance.json#/resource_id'})\n def get(rsrc_id):\n \"\"\"Get instance configuration.\"\"\"\n inst = master.get_app(context.GLOBAL.zk.conn, rsrc_id)\n if inst is None:\n return inst\n\n inst['_id'] = rsrc_id\n if instance_plugin:\n return instance_plugin.remove_attributes(inst)\n else:\n return inst\n\n @schema.schema(\n {'$ref': 'app.json#/resource_id'},\n {'allOf': [{'$ref': 'instance.json#/resource'},\n {'$ref': 'instance.json#/verbs/create'}]},\n count={'type': 'integer', 'minimum': 1, 'maximum': 1000}\n )\n def create(rsrc_id, rsrc, count=1):\n \"\"\"Create (configure) instance.\"\"\"\n _LOGGER.info('create: count = %s, %s %r', count, rsrc_id, rsrc)\n\n admin_app = admin.Application(context.GLOBAL.ldap.conn)\n if not rsrc:\n configured = admin_app.get(rsrc_id)\n _LOGGER.info('Configured: %s %r', rsrc_id, configured)\n else:\n # Make sure defaults are present\n configured = admin_app.from_entry(admin_app.to_entry(rsrc))\n app.verify_feature(rsrc.get('features', []))\n\n if '_id' in configured:\n del configured['_id']\n\n _validate(configured)\n\n if instance_plugin:\n configured = instance_plugin.add_attributes(rsrc_id,\n configured)\n\n if 'proid' not in configured:\n raise exc.TreadmillError(\n 'Missing required attribute: proid')\n if 'environment' not in configured:\n raise exc.TreadmillError(\n 'Missing required attribute: environment')\n\n if 'identity_group' not in configured:\n configured['identity_group'] = None\n\n if 'affinity' not in configured:\n configured['affinity'] = '{0}.{1}'.format(*rsrc_id.split('.'))\n\n scheduled = master.create_apps(context.GLOBAL.zk.conn,\n rsrc_id, configured, count)\n return scheduled\n\n @schema.schema(\n {'$ref': 'instance.json#/resource_id'},\n {'allOf': [{'$ref': 'instance.json#/verbs/update'}]}\n )\n def update(rsrc_id, rsrc):\n \"\"\"Update instance configuration.\"\"\"\n _LOGGER.info('update: %s %r', rsrc_id, rsrc)\n\n delta = {rsrc_id: rsrc['priority']}\n\n master.update_app_priorities(context.GLOBAL.zk.conn, delta)\n return master.get_app(context.GLOBAL.zk.conn, rsrc_id)\n\n @schema.schema({'$ref': 'instance.json#/resource_id'})\n def delete(rsrc_id):\n \"\"\"Delete configured instance.\"\"\"\n _LOGGER.info('delete: %s', rsrc_id)\n\n master.delete_apps(context.GLOBAL.zk.conn, [rsrc_id])\n\n self.list = _list\n self.get = get\n self.create = create\n self.update = update\n self.delete = delete\n\n\ndef init(authorizer):\n \"\"\"Returns module API wrapped with authorizer function.\"\"\"\n api = API()\n return authz.wrap(api, authorizer)\n","sub_path":"treadmill/api/instance.py","file_name":"instance.py","file_ext":"py","file_size_in_byte":4951,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"277239017","text":"\"\"\"\nBinary Search Tree (BST).\n\"\"\"\n\nimport collections\nimport random\n\nimport dot \n\nclass NodeType:\n NoParent = 0\n LeftOfParent = 1\n RightOfParent = 2\n\n def getNodeType(node):\n if node.parent is None:\n return NodeType.NoParent\n\n if node.parent.left is not None and node.parent.left == node:\n return NodeType.LeftOfParent\n\n if node.parent.right is not None and node.parent.right == node:\n return NodeType.RightOfParent\n\n raise Exception(\"Invalid node: %s.\" % node)\n\nclass TreeBST:\n\n def __init__(self):\n self.nextId = 1\n self.root = None\n\n def insert(self, data):\n node = Node(self.nextId, data)\n self.nextId += 1\n\n if self.root == None:\n self.root = node\n else:\n self.placeNode(node)\n\n def placeNode(self, node, cursor = None):\n if cursor is None:\n cursor = self.root\n\n if node.data >= cursor.data:\n if cursor.right is None:\n cursor.right = node\n node.parent = cursor\n updateHeightFromLeaf(node)\n else:\n self.placeNode(node, cursor.right)\n else:\n if cursor.left is None:\n cursor.left = node\n node.parent = cursor\n updateHeightFromLeaf(node)\n else:\n self.placeNode(node, cursor.left)\n\n def getNodeByValue(self, val):\n return self.getNodeByValueIterate(val, self.root)\n\n def getNodeByValueIterate(self, val, node):\n if node is None:\n return node\n\n if val == node.data:\n return node\n\n if val > node.data:\n return self.getNodeByValueIterate(val, node.right)\n else:\n return self.getNodeByValueIterate(val, node.left)\n\ndef updateHeightFromLeaf(node, h = 0):\n if node.height == None:\n node.height = h\n\n if node.height < h:\n node.height = h\n\n if node.parent is not None:\n updateHeightFromLeaf(node.parent, h+1)\n \nclass Node:\n def __init__(self, id, data):\n self.id = id\n self.data = data\n self.left = None\n self.right = None\n self.height = None\n self.parent = None\n\n def __str__(self):\n #return \"%s\" % (self.data)\n height = self.height\n if height == None:\n height = 'None'\n #return \"%s (id: %s, height: %s)\" % (self.data, self.id, height)\n return \"%s\" % (self.data)\n\n def __repr__(self):\n return \"%s\" % self.data\n\ndef insertAll(tree, nodes):\n for node in nodes:\n tree.insert(node)\n\ndef inorderTraversal(node):\n if node.left is not None:\n yield from inorderTraversal(node.left)\n\n yield node\n\n if node.right is not None:\n yield from inorderTraversal(node.right)\n\ndef treeIterateAdaptor(tree):\n for node in inorderTraversal(tree.root):\n dotNode = Node(node.id, node.data)\n dotNode.parent = node.parent\n dotNode.children = [node.left, node.right]\n dotNode.height = node.height\n yield dotNode\n\ndef smallest(node):\n if node.left is None:\n return node\n else:\n return smallest(node.left)\n\ndef largest(node):\n if node.right is None:\n return node\n else:\n return largest(node.right)\n\ndef successor(node):\n if node.right is not None:\n return smallest(node.right)\n\n nodeType = NodeType.getNodeType(node)\n\n if nodeType == NodeType.NoParent:\n return None\n\n if nodeType == NodeType.LeftOfParent:\n return node.parent\n\n if nodeType == NodeType.RightOfParent:\n # First right parent.\n n = node.parent\n while True:\n nt = NodeType.getNodeType(n)\n if nt == NodeType.LeftOfParent:\n return n.parent\n if nt == NodeType.NoParent:\n return None\n n = n.parent\n\n raise Exception()\n\ndef predecessor(node):\n if node.left is not None:\n return largest(node.left)\n\n nodeType = NodeType.getNodeType(node)\n\n if nodeType == NodeType.NoParent:\n return None\n\n if nodeType == NodeType.LeftOfParent:\n # First left parent.\n n = node.parent\n while True:\n nt = NodeType.getNodeType(n)\n if nt == NodeType.RightOfParent:\n return n.parent\n if nt == NodeType.NoParent:\n return None\n n = n.parent\n\n if nodeType == NodeType.RightOfParent:\n return node.parent\n\n raise Exception()\n\ndef getTree():\n tree = TreeBST()\n values = [22, 45, 29, 44, 50, 125012,1000,13,99,100,98]\n insertAll(tree, values)\n return tree, values\n\ndef getTreeRandomNoDuplicate():\n tree = TreeBST()\n values = []\n H = set()\n\n while len(values) < 100:\n v = random.randint(0, 1000)\n if v not in H:\n values.append(v)\n H.add(v)\n\n insertAll(tree, values)\n\n return tree, values\n\ndef verifyTreeMatchesValues(tree, values):\n values = sorted(values)\n valuesOut = [n for n in inorderTraversal(tree.root)]\n print(valuesOut, values)\n pairs = [(a.data, b) for a, b in zip(valuesOut, values)]\n for a, b in pairs:\n print(a,b)\n assert a == b\n\ndef verifySuccessors(tree, values):\n\n values = sorted(values)\n\n # Verify the get, get successor and get predecessor code. (Assumes no duplicate)\n valuesOut = [n for n in inorderTraversal(tree.root)]\n for node, val in [(a, b) for a, b in zip(valuesOut, values)]:\n nodeFound = tree.getNodeByValue(val)\n print('@', nodeFound, val)\n assert nodeFound.data == val\n\n i = values.index(val)\n nodeNext = successor(nodeFound)\n nodePrev = predecessor(nodeFound)\n\n if i == len(values) - 1:\n assert nodeNext is None\n else:\n assert nodeNext is not None\n assert nodeNext.data == values[i+1]\n\n if i == 0:\n assert nodePrev is None\n else:\n assert nodePrev is not None\n assert nodePrev.data == values[i-1]\n\ndef test():\n for i in range(100):\n tree, values = getTreeRandomNoDuplicate()\n\n if False:\n dot.graphToPng(treeIterateAdaptor(tree))\n\n verifyTreeMatchesValues(tree, values)\n verifySuccessors(tree, values)\n\nif __name__ == '__main__':\n test()\n","sub_path":"cs/tree_bst.py","file_name":"tree_bst.py","file_ext":"py","file_size_in_byte":6389,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"638302093","text":"import numpy as np\nimport matplotlib.pyplot as plt\n\n\n#plotting a sine function from x=0 to x=3*pi, plotting x every 0.1 (which gives smooth enough curve)\nx = np.arange(0, 3 * np.pi, 0.1)\n\naxes = plt.gca()\n#axes.set_xlim([0, 3 * np.pi])\naxes.set_ylim([-3, 3])\n\ny_sin = np.sin(x)\ny_cos = np.cos(x)\ny_tan = np.tan(x)\n\nplt.plot(x,y_sin)\nplt.plot(x,y_cos)\nplt.plot(x,y_tan)\nplt.title('Sine, Cosine and Tan')\nplt.xlabel('x axis')\nplt.ylabel('y axis')\nplt.legend(['Sine','Cosine', 'Tan'])\nplt.show()\n","sub_path":"matplot_lib_graphs.py","file_name":"matplot_lib_graphs.py","file_ext":"py","file_size_in_byte":493,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"40411280","text":"#!/usr/bin/env python\n# encoding: utf-8\n# author: 余泉\n# version: python3.6\n# file: test02.py\n# time: 2018\\5\\16 0016 10:13\nimport requests\nimport unittest\nimport json\nimport HTMLTestRunner_jpg\n\nclass Case02(unittest.TestCase):\n\n @classmethod\n def setUpClass(cls):\n print('测试用例中执行一次')\n\n\n def test_case01(self):\n r = requests.get(\"http://www.baidu.com\")\n self.assertEqual(200, r.status_code, '状态码错误,返回不为200')\n print('接口正常流程正确')\n\n def test_moiieelogin(self):\n '''\n 摩云登录接口\n :return:\n '''\n url = \"http://192.168.0.133:19097/app/members/login\"\n data = {\"password\": \"yu1234\", \"principalName\": \"18973019192\", \"type\": 1}\n headers = {\"Content-Type\": \"application/json\"}\n response = requests.post(url, data=json.dumps(data), headers=headers)\n self.assertEqual(200, response.status_code)\n self.assertEqual(True,response.json()['active'],\"接口返回数据错误\")\n print('摩云登录正确')\n\nif __name__ == '__main__':\n suit = unittest.TestSuite()\n # suit.addTest(unittest.makeSuite(Case02))\n suit.addTest(Case02(test_moiieelogin))\n suit.addTest(Case02(test_case01))\n fp = open('res.html', 'wb') # 打开一个保存结果的html文件\n runner = HTMLTestRunner_jpg.HTMLTestRunner(stream=fp, title='api测试报告', description='测试情况')\n fp.close()\n runner.run(suit)\n\n","sub_path":"InterFaceStudy/UnittestStu/Test_case/test02.py","file_name":"test02.py","file_ext":"py","file_size_in_byte":1474,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"191539956","text":"import tensorflow as tf\nimport argparse\n\nPAD = '[PAD]'\npad_id = 0\n\n\ndef set_interact_args():\n \"\"\"\n Sets up the training arguments.\n \"\"\"\n parser = argparse.ArgumentParser()\n parser.add_argument('--temperature', default=1, type=float, required=False, help='生成的temperature')\n parser.add_argument('--topk', default=8, type=int, required=False, help='最高k选1')\n parser.add_argument('--topp', default=0, type=float, required=False, help='最高积累概率')\n parser.add_argument('--dialogue_model_output_path', default='poem_checkpoints/', type=str, required=False,\n help='对话模型输出路径')\n parser.add_argument('--log_path', default='chat_data/interacting.log', type=str, required=False, help='interact日志存放位置')\n parser.add_argument('--voca_path', default='vocab/vocab_middle.txt', type=str, required=False, help='选择词库')\n parser.add_argument('--save_samples_path', default=\"sample/\", type=str, required=False, help=\"保存聊天记录的文件路径\")\n parser.add_argument('--repetition_penalty', default=1.0, type=float, required=False,\n help=\"重复惩罚参数,若生成的对话重复性较高,可适当提高该参数\")\n parser.add_argument('--seed', type=int, default=None, help='设置种子用于生成随机数,以使得训练的结果是确定的')\n parser.add_argument('--max_len', type=int, default=10, help='每个utterance的最大长度,超过指定长度则进行截断')\n parser.add_argument('--max_history_len', type=int, default=1, help=\"dialogue history的最大长度\")\n return parser.parse_args()\n\n\ndef top_k_top_p_filtering(logits, top_k=0, top_p=0.0, filter_value=-float('Inf')):\n assert len(logits.shape) == 1 # batch size 1 for now - could be updated for more but the code would be less clear\n top_k = min(top_k, len(logits)) # Safety check\n if top_k > 0:\n # Remove all tokens with a probability less than the last token of the top-k\n # topk()返回最后一维最大的top_k个元素,返回值为二维(values,indices)\n # ...表示其他维度由计算机自行推断\n # indices_to_remove = logits < torch.topk(logits, top_k)[0][..., -1, None]#true就是概率不属于前八 要过滤掉\n indices_to_remove = logits < tf.raw_ops.TopKV2(input=logits, k=top_k, sorted=True, name=None)[0][\n ..., -1, None] # true就是概率不属于前八 要过滤掉\n # print('排序')\n promax_value, promax_index = tf.raw_ops.TopKV2(input=logits, k=top_k, sorted=True, name=None)\n promax_value = promax_value.numpy()\n promax_index = promax_index.numpy()\n # print('promax_index={}'.format(promax_index))\n logits = promax_value\n\n # logits=np.array(logits)\n # logits[indices_to_remove] = filter_value # 对于topk之外的其他元素的logits值设为负无穷\n\n # 此功能暂未使用 先注释掉 后续增加\n # if top_p > 0.0:\n # sorted_logits= tf.sort(logits,direction = 'DESCENDING') # 对logits进行递减排序--返回降序值\n # sorted_indices=tf.argsort(logits,direction = 'DESCENDING') #返回对应降序的序列值\n # print('sorted_logits={}'.format(sorted_logits))\n # #cumulative_probs = torch.cumsum(F.softmax(sorted_logits, dim=-1), dim=1-)##累积概率\n # cumulative_probs=tf.reduce_sum(tf.nn.softmax(sorted_logits,-1),-1)\n # sorted_indices_to_remove = cumulative_probs > top_p ##过滤作用\n # print('sorted_indices_to_remove.shape={}'.format(sorted_indices_to_remove.shape))\n # print(sorted_indices_to_remove)\n # print(sorted_indices_to_remove[..., :-1])\n # sorted_indices_to_remove=np.array(sorted_indices_to_remove)\n # sorted_indices_to_remove[..., 1:] = sorted_indices_to_remove[..., :-1].clone()\n # sorted_indices_to_remove[..., 0] = 0\n #\n # indices_to_remove = sorted_indices[sorted_indices_to_remove]\n # logits[indices_to_remove] = filter_value\n return logits, promax_index\n","sub_path":"hlp/chat/gpt2/interact_arg.py","file_name":"interact_arg.py","file_ext":"py","file_size_in_byte":4079,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"179404732","text":"#!/usr/bin/python3\n\"\"\"Create California\"\"\"\nfrom sys import argv\nfrom relationship_state import Base, State\nfrom relationship_city import City\nfrom sqlalchemy import (create_engine)\nfrom sqlalchemy.orm import Session\n\n\nif __name__ == \"__main__\":\n engine = create_engine('mysql+mysqldb://{}:{}@localhost/{}'\n .format(argv[1], argv[2], argv[3]),\n pool_pre_ping=True)\n Base.metadata.create_all(engine)\n\n session = Session(engine)\n\n newState = State(name='California')\n newCity = City(name='San Francisco')\n newState.cities.append(newCity)\n session.add_all([newState, newCity])\n\n session.commit()\n session.close()\n","sub_path":"0x0F-python-object_relational_mapping/100-relationship_states_cities.py","file_name":"100-relationship_states_cities.py","file_ext":"py","file_size_in_byte":688,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"604658350","text":"import cv2\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom scipy import fftpack\n\nimg = cv2.imread(\"individual_developers/jackson/120.tif\",-1)\n#Material parameters to be determined later\nmu = 2*10**(3)\nzDelta = 3.1*10**(-5) * 250*10**(3)\nalpha = mu/zDelta\n\n'''\nimg = cv2.imread(\"individual_developers/jackson/jmi_1010_f3b.tiff\",-1)\nimg = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY).astype('uint32')\n#Material parameters to be determined later\nmu = 0.11322 *10**(-2)\nzDelta = -0.375 *250\nalpha = zDelta/mu\n'''\n\n#Fourier frequency coordinates\nky = fftpack.fftfreq(len(img))\nkx = fftpack.fftfreq(len(img[0]))\nkx, ky = np.meshgrid(kx, ky)\n#Compute their magnitudes\nfourierMagnitude = np.square(kx) + np.square(ky)\n\nimg_ft = fftpack.fft2(img)\n\ntransformedFT = img_ft/ (1+ alpha*fourierMagnitude)\n\ntransformedImage = fftpack.ifft2(transformedFT).real\n\nthickness = -(1/mu)*np.log(transformedImage)\n\nplt.close()\nfig, axes = plt.subplots(1, 2)\naxes[0].set_title(\"Original\")\naxes[0].imshow(img,cmap='gray')\naxes[1].set_title(\"Thickness\")\naxes[1].imshow(thickness,cmap='gray')\naxes[1].set_xlabel(\"alpha =\" + str(alpha))\nplt.tight_layout()\nplt.show()\n\n","sub_path":"individual_developers/jackson/FourierFilter.py","file_name":"FourierFilter.py","file_ext":"py","file_size_in_byte":1141,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"446317765","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Feb 15 14:55:43 2021\n\n\"\"\"\n\nimport cv2\nimport imutils\nimport numpy as np\nfrom collections import deque\nfrom sklearn.metrics import pairwise\nimport pyautogui as gui\nimport sys\n\n\nimport os\n\nfrom tensorflow.keras.utils import to_categorical\nfrom tensorflow.keras import Sequential\nfrom tensorflow.keras.layers import Conv2D, MaxPooling2D, UpSampling2D, Dense, Flatten, Dropout\nfrom tensorflow.keras.regularizers import l2\nfrom keras.regularizers import l1\n\nfrom sklearn.utils import shuffle\n\nfrom PIL import Image\nfrom tensorflow.keras import regularizers\n\n# from tensorflow.keras.models import model_from_json\n\n\ndef create_model():\n # model = Sequential()\n # model.add(Conv2D(16, kernel_size = 5, activation = 'relu', input_shape = (200,240,1)))\n # model.add(MaxPooling2D(pool_size = 2))\n # model.add(Conv2D(32, kernel_size = 5, activation = 'relu'))\n # model.add(MaxPooling2D(pool_size = 2))\n # model.add(Conv2D(64, kernel_size = 5, activation = 'relu'))\n # model.add(MaxPooling2D(pool_size = 2))\n # model.add(Conv2D(128, kernel_size = 5, activation = 'relu'))\n # model.add(MaxPooling2D(pool_size = 2))\n\n # model.add(Flatten())\n # model.add(Dense(32,activation = 'relu',kernel_regularizer = regularizers.l1_l2(l1 = 0.05,l2 = 0.5), bias_regularizer=l2(0.1)))\n # model.add(Dense(10, activation = 'softmax',kernel_regularizer = regularizers.l1_l2(l1 = 0.05, l2 = 0.5), bias_regularizer=l2(0.1)))\n num_of_classes = 7\n model = Sequential()\n model.add(Conv2D(32, (5, 5), input_shape=(50, 50, 1), activation='relu'))\n model.add(MaxPooling2D(pool_size=(2, 2), strides=(2, 2), padding='same'))\n model.add(Conv2D(64, (5, 5), activation='relu'))\n model.add(MaxPooling2D(pool_size=(5, 5), strides=(5, 5), padding='same'))\n model.add(Flatten())\n model.add(Dense(1024, activation='relu'))\n model.add(Dropout(0.6))\n model.add(Dense(num_of_classes, activation='softmax'))\n return model\n\n\n# Indices of labels\n# 0 1 2 3 4 5 6 7 8 9\n# labels = ['Undetected','fingers_crossed','up','okay','paper','rock','rock_on','scissor','peace','thumbs']\n\n# labels2 = ['02_l',\n# '04_fist_moved',\n# '09_c',\n# '10_down',\n# '06_index',\n# '08_palm_moved',\n# '07_ok',\n# '05_thumb',\n# '01_palm',\n# '03_fist']\n# 0 1 2 3 4 5 6\nlabels = ['Undetected', 'Rock', 'Paper', 'Scissor', 'L', 'Three', 'Rock_on']\n# labels = ['Undetected','Undetected','Undetected','okay','paper','rock','Undetected','Undetected','Undetected','Undetected']\nmodel = create_model()\nmodel.load_weights(r'D:\\\\virtual_mouse\\\\Virtual-Mouse\\\\RPS.h5')\n\n# model = create_model()\n# model.load_weights(r'D:\\\\virtual_mouse\\\\Virtual-Mouse\\\\emojirecog.hdf5')\n# with open('D:\\\\Virtual Mouse\\\\Virtual-Mouse\\\\model-mask-detection.json', 'r') as f:\n# loaded_model_json = f.read()\n# model = model_from_json(loaded_model_json)\n# model.load_weights('D:\\\\Virtual Mouse\\\\Virtual-Mouse\\\\model-mask-detection.h5')\n\ngui.FAILSAFE = False\ncap = cv2.VideoCapture(0, cv2.CAP_DSHOW)\n# bgSubtractor = cv2.createBackgroundSubtractorMOG2(history=10, varThreshold=30, detectShadows=False)\nface_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')\nkernel = np.ones((5, 5), np.uint8)\ncnt = 0\nflag = True\nd = deque(maxlen=20)\n\n\ndef prepocess_img(img):\n # im = im.resize((240,200),Image.ANTIALIAS)\n # im = np.array(im)\n # im = np.expand_dims(im,axis = 2)\n # im = np.expand_dims(im,axis = 0)\n # img = cv2.imread(path,cv2.IMREAD_GRAYSCALE)\n\n img = cv2.flip(img, 1)\n # img = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)\n # img = cv2.bitwise_not(img)\n # img = cv2.applyColorMap(img, cv2.COLORMAP_BONE)\n img = cv2.resize(img, (50, 50))\n # cv2.imshow('hand', img)\n img = np.array(img)\n img = np.expand_dims(img, axis=2)\n img = np.expand_dims(img, axis=0)\n\n return img\n\n\nwhile True:\n try:\n _, frame = cap.read()\n frame = cv2.flip(frame, 1)\n # print(frame)\n\n # frame = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)\n\n # hand_cascade = cv2.CascadeClassifier('hand.xml')\n # hands = hand_cascade.detectMultiScale(frame,1.1,3)\n\n # print(hands)\n # cv2.rectangle()\n\n hsvim = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)\n lower = np.array([0, 55, 40], dtype=\"uint8\")\n upper = np.array([35, 255, 255], dtype=\"uint8\")\n skinRegionHSV = cv2.inRange(hsvim, lower, upper)\n skinRegionHSV = cv2.erode(skinRegionHSV, kernel, iterations=2)\n skinRegionHSV = cv2.dilate(skinRegionHSV, kernel, iterations=2)\n blurred = cv2.blur(skinRegionHSV, (2, 2))\n # fgmask = bgSubtractor.apply(blurred,learningRate=0)\n\n ret, thresh = cv2.threshold(blurred, 0, 255, cv2.THRESH_BINARY)\n\n # lower = np.array([0, 68, 50], dtype = \"uint8\")\n # upper = np.array([40, 255, 255], dtype = \"uint8\")\n # skinMask = cv2.inRange(frame,lower,upper)\n\n # kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (11, 11))\n # skinMask = cv2.erode(skinMask, kernel, iterations = 2)\n # skinMask = cv2.dilate(skinMask, kernel, iterations = 2)\n\n # skin = cv2.bitwise_and(frame, frame, mask = skinMask)\n\n faces = face_cascade.detectMultiScale(frame, 1.1, 4)\n # for (x, y, w, h) in faces:\n\n if len(faces) > 0:\n (x, y, w, h) = faces[0]\n cv2.rectangle(frame, (x, y), (x + w, y + h), (255, 0, 0), 2)\n thresh[y:y + h, x:x + w] = np.zeros((h, w), np.float64)\n else:\n continue\n\n # calculate moments of binary image\n # M = cv2.moments(thresh)\n # # calculate x,y coordinate of center\n # if M[\"m00\"]==0:\n # continue\n # cX = int(M[\"m10\"] / M[\"m00\"])\n # cY = int(M[\"m01\"] / M[\"m00\"])\n # # put text and highlight the center\n # cv2.circle(frame, (cX, cY), 5, (255, 255, 255), -1)\n # cv2.putText(frame, \"centroid\", (cX - 25, cY - 25),cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255, 255, 255), 2)\n\n #CODE FOR CURSOR MOVEMENT\n # d.appendleft((cX,cY))\n # if len(d)>1:\n # gui.move(2*(d[0][0]-d[1][0]),2*(d[0][1]-d[1][1]))\n\n cnts = cv2.findContours(thresh.copy(), cv2.RETR_EXTERNAL,\n cv2.CHAIN_APPROX_SIMPLE)\n cnts = imutils.grab_contours(cnts)\n if len(cnts) <= 0:\n continue\n if len(cnts) > 0:\n c = max(cnts, key=cv2.contourArea)\n\n # determine the most extreme points along the contour\n extLeft = tuple(c[c[:, :, 0].argmin()][0])\n extRight = tuple(c[c[:, :, 0].argmax()][0])\n extTop = tuple(c[c[:, :, 1].argmin()][0])\n extBot = tuple(c[c[:, :, 1].argmax()][0])\n\n cv2.rectangle(frame, (extLeft[0] - 25, extTop[1] - 25),\n (extRight[0] + 25, extBot[1] + 25), (255, 0, 0), 2)\n # output_gesture = prepocess_img(Image.fromarray(thresh[extTop[1] - 25:extBot[1] + 25, extLeft[0] - 25:extRight[0] + 25]))\n if extTop[1] - 25 > 0 and extLeft[0] - 25 > 0:\n output_gesture = prepocess_img(\n cv2.flip(\n thresh[extTop[1] - 25:extBot[1] + 25,\n extLeft[0] - 25:extRight[0] + 25], 1))\n\n # cv2.putText(np.argmax(model.predict(im)))\n cv2.putText(frame,\n labels[(np.argmax(model.predict(output_gesture)))],\n (460, 70),\n cv2.FONT_HERSHEY_SIMPLEX,\n 1, (0, 0, 0),\n thickness=4)\n # M = cv2.moments(thresh[extTop[1] - 25:extBot[1] + 25, extLeft[0] - 25:extRight[0] + 25])\n # calculate x,y coordinate of center\n M = cv2.moments(thresh[extTop[1] - 25:extBot[1] + 25, extLeft[0] - 25:extRight[0] + 25])\n if M[\"m00\"] == 0:\n continue\n cX = int(M[\"m10\"] / M[\"m00\"])\n cY = int(M[\"m01\"] / M[\"m00\"])\n # put text and highlight the center\n cv2.circle(frame, (cX+extLeft[0]-25, cY+extTop[1]-25), 5, (255, 255, 255), -1)\n # cv2.putText(frame, \"centroid\", (cX - 25, cY - 25),cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255, 255, 255), 2)\n\n # CODE FOR CURSOR MOVEMENT\n d.appendleft((cX+extLeft[0]-25, cY+extTop[1]-25))\n if len(d) > 1 and np.argmax(model.predict(output_gesture)) == 4:\n gui.move(5 * (d[0][0] - d[1][0]), 5 * (d[0][1] - d[1][1]))\n if np.argmax(model.predict(output_gesture)) == 2:\n gui.click()\n if np.argmax(model.predict(output_gesture)) == 5:\n gui.click(button='right')\n if np.argmax(model.predict(output_gesture)) == 1:#rock\n os.system(\"Notepad\")\n \n if np.argmax(model.predict(output_gesture)) == 3:\n #scissor\n print(1*(d[0][1] - d[1][1]))\n gui.scroll(-10)\n\n if np.argmax(model.predict(output_gesture)) == 6:\n # #rock_on\n gui.scroll(10) \n\n\n\n # draw the outline of the object, then draw each of the\n # extreme points, where the left-most is red, right-most\n # is green, top-most is blue, and bottom-most is teal\n cv2.drawContours(frame, [c], -1, (255, 0, 255), 2)\n cv2.circle(frame, extLeft, 8, (0, 0, 255), -1)\n cv2.circle(frame, extRight, 8, (0, 255, 0), -1)\n cv2.circle(frame, extTop, 8, (255, 0, 0), -1)\n cv2.circle(frame, extBot, 8, (255, 255, 0), -1)\n\n # cX=(extLeft[0]+extRight[0])//2\n # cY=(extTop[1]+extBot[1])//2\n\n hull = cv2.convexHull(c)\n cv2.drawContours(frame, [hull], -1, (0, 255, 255), 2)\n\n hull = cv2.convexHull(c, returnPoints=False)\n # defects = cv2.convexityDefects(c, hull)\n # cv2.drawContours(frame, [hull], -1, (0, 255, 255), 2)\n\n # if defects is not None:\n # cnt = 0\n # for i in range(defects.shape[0]):\n # s, e, f, d = defects[i][0]\n # start = tuple(c[s][0])\n\n # # if flag==True:\n # # print(cnts)\n # # flag=False\n # end = tuple(c[e][0])\n # far = tuple(c[f][0])\n # a1 = np.sqrt((end[0] - start[0]) ** 2 + (end[1] - start[1]) ** 2)\n # b1 = np.sqrt((far[0] - start[0]) ** 2 + (far[1] - start[1]) ** 2)\n # c1 = np.sqrt((end[0] - far[0]) ** 2 + (end[1] - far[1]) ** 2)\n # angle = np.arccos((b1 ** 2 + c1 ** 2 - a1 ** 2) / (2 * b1 * c1)) # cosine theorem\n # if angle <= np.pi / 2: # angle less than 90 degree, treat as fingers\n # cnt += 1\n # cv2.circle(frame, far, 4, [0, 0, 255], -1)\n # if cnt > 0:\n # cnt = cnt+1\n # cv2.putText(frame, str(cnt), (0, 50), cv2.FONT_HERSHEY_SIMPLEX,1, (255, 0, 0) , 2, cv2.LINE_AA)\n\n # dist=pairwise.euclidean_distances([extLeft,extRight,extBot,extTop],[[cX,cY]])[0]\n # radi=int(0.80*dist)\n\n # t2 = thresh.copy()\n\n # circular_roi=np.zeros_like(thresh,dtype='uint8')\n # cv2.circle(circular_roi,(cX,cY),radi,255,8)\n # wighted=cv2.addWeighted(thresh.copy(),0.6,circular_roi,0.4,2)\n\n # mask=cv2.bitwise_and(t2,t2,mask=circular_roi)\n # #mask\n # con,hie=cv2.findContours(mask.copy(),cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_NONE)\n # count=0\n # circumfrence=2*np.pi*radi\n # for cnt in con:\n # (m_x,m_y,m_w,m_h)=cv2.boundingRect(cnt)\n # out_wrist_range=(cY+(cY*0.25))>(m_y+m_h)\n # limit_pts=(circumfrence*0.25)>cnt.shape[0]\n # if limit_pts and out_wrist_range:\n # count+=1\n\n # cv2.putText(frame,'count: '+str(count),(460,70),cv2.FONT_HERSHEY_SIMPLEX ,1,(0,250,0),thickness=4)\n # cv2.rectangle(frame,(x,y),(x+w,y+h),255,3)\n\n # cv2.imshow('weight',weighted)\n cv2.imshow('mask', thresh)\n cv2.imshow('frame', frame)\n\n # if count == 3:\n # gui.click(clicks=1)\n\n if cv2.waitKey(1) & 0xFF == ord('q'):\n # print(defects)\n break\n except KeyboardInterrupt:\n sys.exit()\n\ncv2.destroyAllWindows()\ncap.release()","sub_path":"mouse.py","file_name":"mouse.py","file_ext":"py","file_size_in_byte":12324,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"225437054","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu May 31 15:44:04 2018\n\n@author: sylvain.finot\n\"\"\"\n\nfrom scipy.optimize import curve_fit\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport scipy.odr.odrpack as odrpack\nfrom collections import Counter\nimport itertools\n\ndef fit(data,interval):\n interval.sort()\n nData = data[(data[:,0] > interval[0])&(data[:,0] < interval[1])]\n X = nData[:,0]\n Y = nData[:,1]\n def func(x, a):\n return (1/a) * x\n popt, pcov = curve_fit(func, X, Y)#,absolute_sigma=True,sigma=0.1*Y)\n return np.array([popt[0], np.sqrt(pcov[0])])\n\ndef fit2(data,interval,init):\n interval.sort()\n nData = data[(data[:,0] > interval[0])&(data[:,0] < interval[1])]\n x=nData[:,0]\n y=nData[:,1]\n sx=None\n sy=None\n try:\n sx = nData[:,2]\n sy = nData[:,3]\n except:\n pass\n def func(B,x):\n return (1/B[0]) * x\n linear = odrpack.Model(func)\n mydata = odrpack.RealData(x, y, sx=sx, sy=sy)\n myodr = odrpack.ODR(mydata, linear, beta0=[init])\n myoutput = myodr.run()\n myoutput.pprint()\n return [myoutput.beta[0],myoutput.sd_beta[0]]\n\ndef calibrate(plot=False,temp=5,omnes=3.5E16,lim=[0,5E17]):\n markers = itertools.cycle([\"o\",\"s\",'h','H',\"D\",'8'])\n data = np.loadtxt('res/Calibration%sK'%(temp),skiprows=1,dtype=np.str)\n method=np.array(list(map(str.upper,data[:,0])))\n methods = list(Counter(map(str.upper, data[:,0])))\n data = data[:,1:].astype(np.float64)\n params = fit(data,lim)\n print('Initial guess\\t%.2e\\nStd\\t%.2e'%(params[0],params[1]))\n params = fit2(data,lim,init=params[0])\n params[1] *= 1.96\n if plot:\n fig = plt.figure()\n ax = fig.add_subplot(111)\n ax.set_yscale('log')\n ax.set_xscale('log')\n# ax.text(1, 1, 'matplotlib', horizontalalignment='right', verticalalignment='center', transform=ax.transAxes)\n# plt.annotate('Something', xy=(0.05, 0.95), xycoords='figure fraction')\n ax.set_title('T=%dK'%(temp))\n x = np.logspace(np.log10(min(data[:,0]))-1,np.log10(max(data[:,0])),20)\n ax.plot(x,x/params[0],c='r',label='Regression [B] = (%.1e ' %params[0]+'$\\pm$ %.1e)'%params[1] +'r')\n# ax.plot(x,x/(omnes),label='Omnes [B]=%.1e' %omnes+'r')\n ax.axvline(x=lim[0],c='k',alpha=0.7)\n ax.axvline(x=lim[1],c='k',alpha=0.7)\n ax.plot(x,x/(params[0]+params[1]),c='gray',linestyle='--')\n ax.plot(x,x/(params[0]-params[1]),c='gray',linestyle='--')\n ax.fill_between(x, x/(params[0]+params[1]), x/(params[0]-params[1]), alpha=.25, label='1.96-sigma interval')\n for m in methods:\n cdata = data[method==m].astype(np.float64)\n x=cdata[:,0]\n y=cdata[:,1]\n sx=0\n sy=0\n try:\n sx = cdata[:,2]\n sy = cdata[:,3]\n except:\n pass\n ax.errorbar(x, y, xerr=sx, yerr=sy, linestyle='None',marker=next(markers),markersize=5,label=m)\n ax.legend()\n ax.set_ylabel('r=$\\dfrac{I_{BETO}}{I_{FETO}}$')\n ax.set_xlabel('Boron concentration (cm$^{-3}$)')\n fig.show()\n return params","sub_path":"Calibrate.py","file_name":"Calibrate.py","file_ext":"py","file_size_in_byte":3154,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"42254084","text":"import numpy as np\n\ndef GuessingDist(df, numItemsInStream):\n nrow = df.shape[0]\n minSPE = -max(df['targetSP'])+1\n maxSPE = numItemsInStream - min(df['targetSP'])\n xDomain = [i for i in range(minSPE, maxSPE+1,1)]\n pseudoUniform = np.zeros([len(xDomain), 2], dtype = float)\n pseudoUniform[:,0] = xDomain\n \n for thisRow in range(nrow):\n thisSP = df['targetSP'].iloc[thisRow]\n thisMinSPE = -thisSP+1\n thisMaxSPE = numItemsInStream - thisSP\n indexThisMinSPE = xDomain.index(thisMinSPE)\n indexThisMaxSPE = xDomain.index(thisMaxSPE)\n pseudoUniform[indexThisMinSPE:(indexThisMaxSPE+1), 1] += 1\n return pseudoUniform[:,1]","sub_path":"pyMixRSVP/distributions/GuessingDist.py","file_name":"GuessingDist.py","file_ext":"py","file_size_in_byte":681,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"461329707","text":"\nfrom static import Base_RM_Register\nfrom FRC_field import *\n\n\nclass RM_Register_FRC_STATUS(Base_RM_Register):\n def __init__(self, rmio, label):\n self.__dict__['zz_frozen'] = False\n super(RM_Register_FRC_STATUS, self).__init__(rmio, label,\n 0x40080000, 0x000,\n 'STATUS', 'FRC.STATUS', 'read-only',\n \"\",\n 0x00000000, 0x000001FF)\n\n self.ACTIVETXFCD = RM_Field_FRC_STATUS_ACTIVETXFCD(self)\n self.zz_fdict['ACTIVETXFCD'] = self.ACTIVETXFCD\n self.ACTIVERXFCD = RM_Field_FRC_STATUS_ACTIVERXFCD(self)\n self.zz_fdict['ACTIVERXFCD'] = self.ACTIVERXFCD\n self.RXABORTINPROGRESS = RM_Field_FRC_STATUS_RXABORTINPROGRESS(self)\n self.zz_fdict['RXABORTINPROGRESS'] = self.RXABORTINPROGRESS\n self.SNIFFDFRAME = RM_Field_FRC_STATUS_SNIFFDFRAME(self)\n self.zz_fdict['SNIFFDFRAME'] = self.SNIFFDFRAME\n self.SNIFFDCOUNT = RM_Field_FRC_STATUS_SNIFFDCOUNT(self)\n self.zz_fdict['SNIFFDCOUNT'] = self.SNIFFDCOUNT\n self.RXRAWBLOCKED = RM_Field_FRC_STATUS_RXRAWBLOCKED(self)\n self.zz_fdict['RXRAWBLOCKED'] = self.RXRAWBLOCKED\n self.__dict__['zz_frozen'] = True\n\n\nclass RM_Register_FRC_DFLCTRL(Base_RM_Register):\n def __init__(self, rmio, label):\n self.__dict__['zz_frozen'] = False\n super(RM_Register_FRC_DFLCTRL, self).__init__(rmio, label,\n 0x40080000, 0x004,\n 'DFLCTRL', 'FRC.DFLCTRL', 'read-write',\n \"\",\n 0x00000000, 0x001FFF7F)\n\n self.DFLMODE = RM_Field_FRC_DFLCTRL_DFLMODE(self)\n self.zz_fdict['DFLMODE'] = self.DFLMODE\n self.DFLBITORDER = RM_Field_FRC_DFLCTRL_DFLBITORDER(self)\n self.zz_fdict['DFLBITORDER'] = self.DFLBITORDER\n self.DFLSHIFT = RM_Field_FRC_DFLCTRL_DFLSHIFT(self)\n self.zz_fdict['DFLSHIFT'] = self.DFLSHIFT\n self.DFLOFFSET = RM_Field_FRC_DFLCTRL_DFLOFFSET(self)\n self.zz_fdict['DFLOFFSET'] = self.DFLOFFSET\n self.DFLBITS = RM_Field_FRC_DFLCTRL_DFLBITS(self)\n self.zz_fdict['DFLBITS'] = self.DFLBITS\n self.MINLENGTH = RM_Field_FRC_DFLCTRL_MINLENGTH(self)\n self.zz_fdict['MINLENGTH'] = self.MINLENGTH\n self.DFLINCLUDECRC = RM_Field_FRC_DFLCTRL_DFLINCLUDECRC(self)\n self.zz_fdict['DFLINCLUDECRC'] = self.DFLINCLUDECRC\n self.__dict__['zz_frozen'] = True\n\n\nclass RM_Register_FRC_MAXLENGTH(Base_RM_Register):\n def __init__(self, rmio, label):\n self.__dict__['zz_frozen'] = False\n super(RM_Register_FRC_MAXLENGTH, self).__init__(rmio, label,\n 0x40080000, 0x008,\n 'MAXLENGTH', 'FRC.MAXLENGTH', 'read-write',\n \"\",\n 0x00000FFF, 0x00000FFF)\n\n self.MAXLENGTH = RM_Field_FRC_MAXLENGTH_MAXLENGTH(self)\n self.zz_fdict['MAXLENGTH'] = self.MAXLENGTH\n self.__dict__['zz_frozen'] = True\n\n\nclass RM_Register_FRC_ADDRFILTCTRL(Base_RM_Register):\n def __init__(self, rmio, label):\n self.__dict__['zz_frozen'] = False\n super(RM_Register_FRC_ADDRFILTCTRL, self).__init__(rmio, label,\n 0x40080000, 0x00C,\n 'ADDRFILTCTRL', 'FRC.ADDRFILTCTRL', 'read-write',\n \"\",\n 0x00000000, 0x0000FF07)\n\n self.EN = RM_Field_FRC_ADDRFILTCTRL_EN(self)\n self.zz_fdict['EN'] = self.EN\n self.BRDCST00EN = RM_Field_FRC_ADDRFILTCTRL_BRDCST00EN(self)\n self.zz_fdict['BRDCST00EN'] = self.BRDCST00EN\n self.BRDCSTFFEN = RM_Field_FRC_ADDRFILTCTRL_BRDCSTFFEN(self)\n self.zz_fdict['BRDCSTFFEN'] = self.BRDCSTFFEN\n self.ADDRESS = RM_Field_FRC_ADDRFILTCTRL_ADDRESS(self)\n self.zz_fdict['ADDRESS'] = self.ADDRESS\n self.__dict__['zz_frozen'] = True\n\n\nclass RM_Register_FRC_DATABUFFER(Base_RM_Register):\n def __init__(self, rmio, label):\n self.__dict__['zz_frozen'] = False\n super(RM_Register_FRC_DATABUFFER, self).__init__(rmio, label,\n 0x40080000, 0x010,\n 'DATABUFFER', 'FRC.DATABUFFER', 'read-write',\n \"\",\n 0x00000000, 0x000000FF)\n\n self.DATABUFFER = RM_Field_FRC_DATABUFFER_DATABUFFER(self)\n self.zz_fdict['DATABUFFER'] = self.DATABUFFER\n self.__dict__['zz_frozen'] = True\n\n\nclass RM_Register_FRC_WCNT(Base_RM_Register):\n def __init__(self, rmio, label):\n self.__dict__['zz_frozen'] = False\n super(RM_Register_FRC_WCNT, self).__init__(rmio, label,\n 0x40080000, 0x014,\n 'WCNT', 'FRC.WCNT', 'read-only',\n \"\",\n 0x00000000, 0x00000FFF)\n\n self.WCNT = RM_Field_FRC_WCNT_WCNT(self)\n self.zz_fdict['WCNT'] = self.WCNT\n self.__dict__['zz_frozen'] = True\n\n\nclass RM_Register_FRC_WCNTCMP0(Base_RM_Register):\n def __init__(self, rmio, label):\n self.__dict__['zz_frozen'] = False\n super(RM_Register_FRC_WCNTCMP0, self).__init__(rmio, label,\n 0x40080000, 0x018,\n 'WCNTCMP0', 'FRC.WCNTCMP0', 'read-write',\n \"\",\n 0x00000000, 0x00000FFF)\n\n self.FRAMELENGTH = RM_Field_FRC_WCNTCMP0_FRAMELENGTH(self)\n self.zz_fdict['FRAMELENGTH'] = self.FRAMELENGTH\n self.__dict__['zz_frozen'] = True\n\n\nclass RM_Register_FRC_WCNTCMP1(Base_RM_Register):\n def __init__(self, rmio, label):\n self.__dict__['zz_frozen'] = False\n super(RM_Register_FRC_WCNTCMP1, self).__init__(rmio, label,\n 0x40080000, 0x01C,\n 'WCNTCMP1', 'FRC.WCNTCMP1', 'read-write',\n \"\",\n 0x00000000, 0x00000FFF)\n\n self.LENGTHFIELDLOC = RM_Field_FRC_WCNTCMP1_LENGTHFIELDLOC(self)\n self.zz_fdict['LENGTHFIELDLOC'] = self.LENGTHFIELDLOC\n self.__dict__['zz_frozen'] = True\n\n\nclass RM_Register_FRC_WCNTCMP2(Base_RM_Register):\n def __init__(self, rmio, label):\n self.__dict__['zz_frozen'] = False\n super(RM_Register_FRC_WCNTCMP2, self).__init__(rmio, label,\n 0x40080000, 0x020,\n 'WCNTCMP2', 'FRC.WCNTCMP2', 'read-write',\n \"\",\n 0x00000000, 0x00000FFF)\n\n self.ADDRFIELDLOC = RM_Field_FRC_WCNTCMP2_ADDRFIELDLOC(self)\n self.zz_fdict['ADDRFIELDLOC'] = self.ADDRFIELDLOC\n self.__dict__['zz_frozen'] = True\n\n\nclass RM_Register_FRC_CMD(Base_RM_Register):\n def __init__(self, rmio, label):\n self.__dict__['zz_frozen'] = False\n super(RM_Register_FRC_CMD, self).__init__(rmio, label,\n 0x40080000, 0x024,\n 'CMD', 'FRC.CMD', 'write-only',\n \"\",\n 0x00000000, 0x00001FFF)\n\n self.RXABORT = RM_Field_FRC_CMD_RXABORT(self)\n self.zz_fdict['RXABORT'] = self.RXABORT\n self.FRAMEDETRESUME = RM_Field_FRC_CMD_FRAMEDETRESUME(self)\n self.zz_fdict['FRAMEDETRESUME'] = self.FRAMEDETRESUME\n self.INTERLEAVEWRITERESUME = RM_Field_FRC_CMD_INTERLEAVEWRITERESUME(self)\n self.zz_fdict['INTERLEAVEWRITERESUME'] = self.INTERLEAVEWRITERESUME\n self.INTERLEAVEREADRESUME = RM_Field_FRC_CMD_INTERLEAVEREADRESUME(self)\n self.zz_fdict['INTERLEAVEREADRESUME'] = self.INTERLEAVEREADRESUME\n self.CONVRESUME = RM_Field_FRC_CMD_CONVRESUME(self)\n self.zz_fdict['CONVRESUME'] = self.CONVRESUME\n self.CONVTERMINATE = RM_Field_FRC_CMD_CONVTERMINATE(self)\n self.zz_fdict['CONVTERMINATE'] = self.CONVTERMINATE\n self.TXSUBFRAMERESUME = RM_Field_FRC_CMD_TXSUBFRAMERESUME(self)\n self.zz_fdict['TXSUBFRAMERESUME'] = self.TXSUBFRAMERESUME\n self.INTERLEAVEINIT = RM_Field_FRC_CMD_INTERLEAVEINIT(self)\n self.zz_fdict['INTERLEAVEINIT'] = self.INTERLEAVEINIT\n self.INTERLEAVECNTCLEAR = RM_Field_FRC_CMD_INTERLEAVECNTCLEAR(self)\n self.zz_fdict['INTERLEAVECNTCLEAR'] = self.INTERLEAVECNTCLEAR\n self.CONVINIT = RM_Field_FRC_CMD_CONVINIT(self)\n self.zz_fdict['CONVINIT'] = self.CONVINIT\n self.BLOCKINIT = RM_Field_FRC_CMD_BLOCKINIT(self)\n self.zz_fdict['BLOCKINIT'] = self.BLOCKINIT\n self.STATEINIT = RM_Field_FRC_CMD_STATEINIT(self)\n self.zz_fdict['STATEINIT'] = self.STATEINIT\n self.RXRAWUNBLOCK = RM_Field_FRC_CMD_RXRAWUNBLOCK(self)\n self.zz_fdict['RXRAWUNBLOCK'] = self.RXRAWUNBLOCK\n self.__dict__['zz_frozen'] = True\n\n\nclass RM_Register_FRC_WHITECTRL(Base_RM_Register):\n def __init__(self, rmio, label):\n self.__dict__['zz_frozen'] = False\n super(RM_Register_FRC_WHITECTRL, self).__init__(rmio, label,\n 0x40080000, 0x028,\n 'WHITECTRL', 'FRC.WHITECTRL', 'read-write',\n \"\",\n 0x00000000, 0x00001F7F)\n\n self.FEEDBACKSEL = RM_Field_FRC_WHITECTRL_FEEDBACKSEL(self)\n self.zz_fdict['FEEDBACKSEL'] = self.FEEDBACKSEL\n self.XORFEEDBACK = RM_Field_FRC_WHITECTRL_XORFEEDBACK(self)\n self.zz_fdict['XORFEEDBACK'] = self.XORFEEDBACK\n self.SHROUTPUTSEL = RM_Field_FRC_WHITECTRL_SHROUTPUTSEL(self)\n self.zz_fdict['SHROUTPUTSEL'] = self.SHROUTPUTSEL\n self.BLOCKERRORCORRECT = RM_Field_FRC_WHITECTRL_BLOCKERRORCORRECT(self)\n self.zz_fdict['BLOCKERRORCORRECT'] = self.BLOCKERRORCORRECT\n self.__dict__['zz_frozen'] = True\n\n\nclass RM_Register_FRC_WHITEPOLY(Base_RM_Register):\n def __init__(self, rmio, label):\n self.__dict__['zz_frozen'] = False\n super(RM_Register_FRC_WHITEPOLY, self).__init__(rmio, label,\n 0x40080000, 0x02C,\n 'WHITEPOLY', 'FRC.WHITEPOLY', 'read-write',\n \"\",\n 0x00000000, 0x0000FFFF)\n\n self.POLY = RM_Field_FRC_WHITEPOLY_POLY(self)\n self.zz_fdict['POLY'] = self.POLY\n self.__dict__['zz_frozen'] = True\n\n\nclass RM_Register_FRC_WHITEINIT(Base_RM_Register):\n def __init__(self, rmio, label):\n self.__dict__['zz_frozen'] = False\n super(RM_Register_FRC_WHITEINIT, self).__init__(rmio, label,\n 0x40080000, 0x030,\n 'WHITEINIT', 'FRC.WHITEINIT', 'read-write',\n \"\",\n 0x00000000, 0x0000FFFF)\n\n self.WHITEINIT = RM_Field_FRC_WHITEINIT_WHITEINIT(self)\n self.zz_fdict['WHITEINIT'] = self.WHITEINIT\n self.__dict__['zz_frozen'] = True\n\n\nclass RM_Register_FRC_FECCTRL(Base_RM_Register):\n def __init__(self, rmio, label):\n self.__dict__['zz_frozen'] = False\n super(RM_Register_FRC_FECCTRL, self).__init__(rmio, label,\n 0x40080000, 0x034,\n 'FECCTRL', 'FRC.FECCTRL', 'read-write',\n \"\",\n 0x00000000, 0x003FFFF7)\n\n self.BLOCKWHITEMODE = RM_Field_FRC_FECCTRL_BLOCKWHITEMODE(self)\n self.zz_fdict['BLOCKWHITEMODE'] = self.BLOCKWHITEMODE\n self.CONVMODE = RM_Field_FRC_FECCTRL_CONVMODE(self)\n self.zz_fdict['CONVMODE'] = self.CONVMODE\n self.CONVDECODEMODE = RM_Field_FRC_FECCTRL_CONVDECODEMODE(self)\n self.zz_fdict['CONVDECODEMODE'] = self.CONVDECODEMODE\n self.CONVTRACEBACKDISABLE = RM_Field_FRC_FECCTRL_CONVTRACEBACKDISABLE(self)\n self.zz_fdict['CONVTRACEBACKDISABLE'] = self.CONVTRACEBACKDISABLE\n self.CONVINV = RM_Field_FRC_FECCTRL_CONVINV(self)\n self.zz_fdict['CONVINV'] = self.CONVINV\n self.INTERLEAVEMODE = RM_Field_FRC_FECCTRL_INTERLEAVEMODE(self)\n self.zz_fdict['INTERLEAVEMODE'] = self.INTERLEAVEMODE\n self.INTERLEAVEFIRSTINDEX = RM_Field_FRC_FECCTRL_INTERLEAVEFIRSTINDEX(self)\n self.zz_fdict['INTERLEAVEFIRSTINDEX'] = self.INTERLEAVEFIRSTINDEX\n self.INTERLEAVEWIDTH = RM_Field_FRC_FECCTRL_INTERLEAVEWIDTH(self)\n self.zz_fdict['INTERLEAVEWIDTH'] = self.INTERLEAVEWIDTH\n self.CONVBUSLOCK = RM_Field_FRC_FECCTRL_CONVBUSLOCK(self)\n self.zz_fdict['CONVBUSLOCK'] = self.CONVBUSLOCK\n self.CONVSUBFRAMETERMINATE = RM_Field_FRC_FECCTRL_CONVSUBFRAMETERMINATE(self)\n self.zz_fdict['CONVSUBFRAMETERMINATE'] = self.CONVSUBFRAMETERMINATE\n self.SINGLEBLOCK = RM_Field_FRC_FECCTRL_SINGLEBLOCK(self)\n self.zz_fdict['SINGLEBLOCK'] = self.SINGLEBLOCK\n self.FORCE2FSK = RM_Field_FRC_FECCTRL_FORCE2FSK(self)\n self.zz_fdict['FORCE2FSK'] = self.FORCE2FSK\n self.CONVHARDERROR = RM_Field_FRC_FECCTRL_CONVHARDERROR(self)\n self.zz_fdict['CONVHARDERROR'] = self.CONVHARDERROR\n self.__dict__['zz_frozen'] = True\n\n\nclass RM_Register_FRC_BLOCKRAMADDR(Base_RM_Register):\n def __init__(self, rmio, label):\n self.__dict__['zz_frozen'] = False\n super(RM_Register_FRC_BLOCKRAMADDR, self).__init__(rmio, label,\n 0x40080000, 0x038,\n 'BLOCKRAMADDR', 'FRC.BLOCKRAMADDR', 'read-write',\n \"\",\n 0x00000000, 0x00007FFC)\n\n self.BLOCKRAMADDR = RM_Field_FRC_BLOCKRAMADDR_BLOCKRAMADDR(self)\n self.zz_fdict['BLOCKRAMADDR'] = self.BLOCKRAMADDR\n self.__dict__['zz_frozen'] = True\n\n\nclass RM_Register_FRC_CONVRAMADDR(Base_RM_Register):\n def __init__(self, rmio, label):\n self.__dict__['zz_frozen'] = False\n super(RM_Register_FRC_CONVRAMADDR, self).__init__(rmio, label,\n 0x40080000, 0x03C,\n 'CONVRAMADDR', 'FRC.CONVRAMADDR', 'read-write',\n \"\",\n 0x00000000, 0x00007FFC)\n\n self.CONVRAMADDR = RM_Field_FRC_CONVRAMADDR_CONVRAMADDR(self)\n self.zz_fdict['CONVRAMADDR'] = self.CONVRAMADDR\n self.__dict__['zz_frozen'] = True\n\n\nclass RM_Register_FRC_CTRL(Base_RM_Register):\n def __init__(self, rmio, label):\n self.__dict__['zz_frozen'] = False\n super(RM_Register_FRC_CTRL, self).__init__(rmio, label,\n 0x40080000, 0x040,\n 'CTRL', 'FRC.CTRL', 'read-write',\n \"\",\n 0x00000700, 0x00033FF7)\n\n self.RANDOMTX = RM_Field_FRC_CTRL_RANDOMTX(self)\n self.zz_fdict['RANDOMTX'] = self.RANDOMTX\n self.UARTMODE = RM_Field_FRC_CTRL_UARTMODE(self)\n self.zz_fdict['UARTMODE'] = self.UARTMODE\n self.BITORDER = RM_Field_FRC_CTRL_BITORDER(self)\n self.zz_fdict['BITORDER'] = self.BITORDER\n self.TXFCDMODE = RM_Field_FRC_CTRL_TXFCDMODE(self)\n self.zz_fdict['TXFCDMODE'] = self.TXFCDMODE\n self.RXFCDMODE = RM_Field_FRC_CTRL_RXFCDMODE(self)\n self.zz_fdict['RXFCDMODE'] = self.RXFCDMODE\n self.BITSPERWORD = RM_Field_FRC_CTRL_BITSPERWORD(self)\n self.zz_fdict['BITSPERWORD'] = self.BITSPERWORD\n self.RATESELECT = RM_Field_FRC_CTRL_RATESELECT(self)\n self.zz_fdict['RATESELECT'] = self.RATESELECT\n self.TXPREFETCH = RM_Field_FRC_CTRL_TXPREFETCH(self)\n self.zz_fdict['TXPREFETCH'] = self.TXPREFETCH\n self.SEQHANDSHAKE = RM_Field_FRC_CTRL_SEQHANDSHAKE(self)\n self.zz_fdict['SEQHANDSHAKE'] = self.SEQHANDSHAKE\n self.PRBSTEST = RM_Field_FRC_CTRL_PRBSTEST(self)\n self.zz_fdict['PRBSTEST'] = self.PRBSTEST\n self.__dict__['zz_frozen'] = True\n\n\nclass RM_Register_FRC_RXCTRL(Base_RM_Register):\n def __init__(self, rmio, label):\n self.__dict__['zz_frozen'] = False\n super(RM_Register_FRC_RXCTRL, self).__init__(rmio, label,\n 0x40080000, 0x044,\n 'RXCTRL', 'FRC.RXCTRL', 'read-write',\n \"\",\n 0x00000000, 0x0000007F)\n\n self.STORECRC = RM_Field_FRC_RXCTRL_STORECRC(self)\n self.zz_fdict['STORECRC'] = self.STORECRC\n self.ACCEPTCRCERRORS = RM_Field_FRC_RXCTRL_ACCEPTCRCERRORS(self)\n self.zz_fdict['ACCEPTCRCERRORS'] = self.ACCEPTCRCERRORS\n self.ACCEPTBLOCKERRORS = RM_Field_FRC_RXCTRL_ACCEPTBLOCKERRORS(self)\n self.zz_fdict['ACCEPTBLOCKERRORS'] = self.ACCEPTBLOCKERRORS\n self.TRACKABFRAME = RM_Field_FRC_RXCTRL_TRACKABFRAME(self)\n self.zz_fdict['TRACKABFRAME'] = self.TRACKABFRAME\n self.BUFCLEAR = RM_Field_FRC_RXCTRL_BUFCLEAR(self)\n self.zz_fdict['BUFCLEAR'] = self.BUFCLEAR\n self.BUFRESTOREFRAMEERROR = RM_Field_FRC_RXCTRL_BUFRESTOREFRAMEERROR(self)\n self.zz_fdict['BUFRESTOREFRAMEERROR'] = self.BUFRESTOREFRAMEERROR\n self.BUFRESTORERXABORTED = RM_Field_FRC_RXCTRL_BUFRESTORERXABORTED(self)\n self.zz_fdict['BUFRESTORERXABORTED'] = self.BUFRESTORERXABORTED\n self.__dict__['zz_frozen'] = True\n\n\nclass RM_Register_FRC_TRAILTXDATACTRL(Base_RM_Register):\n def __init__(self, rmio, label):\n self.__dict__['zz_frozen'] = False\n super(RM_Register_FRC_TRAILTXDATACTRL, self).__init__(rmio, label,\n 0x40080000, 0x048,\n 'TRAILTXDATACTRL', 'FRC.TRAILTXDATACTRL', 'read-write',\n \"\",\n 0x00000000, 0x00000FFF)\n\n self.TRAILTXDATA = RM_Field_FRC_TRAILTXDATACTRL_TRAILTXDATA(self)\n self.zz_fdict['TRAILTXDATA'] = self.TRAILTXDATA\n self.TRAILTXDATACNT = RM_Field_FRC_TRAILTXDATACTRL_TRAILTXDATACNT(self)\n self.zz_fdict['TRAILTXDATACNT'] = self.TRAILTXDATACNT\n self.TRAILTXDATAFORCE = RM_Field_FRC_TRAILTXDATACTRL_TRAILTXDATAFORCE(self)\n self.zz_fdict['TRAILTXDATAFORCE'] = self.TRAILTXDATAFORCE\n self.__dict__['zz_frozen'] = True\n\n\nclass RM_Register_FRC_TRAILRXDATA(Base_RM_Register):\n def __init__(self, rmio, label):\n self.__dict__['zz_frozen'] = False\n super(RM_Register_FRC_TRAILRXDATA, self).__init__(rmio, label,\n 0x40080000, 0x04C,\n 'TRAILRXDATA', 'FRC.TRAILRXDATA', 'read-write',\n \"\",\n 0x00000000, 0x0000003F)\n\n self.RSSI = RM_Field_FRC_TRAILRXDATA_RSSI(self)\n self.zz_fdict['RSSI'] = self.RSSI\n self.CRCOK = RM_Field_FRC_TRAILRXDATA_CRCOK(self)\n self.zz_fdict['CRCOK'] = self.CRCOK\n self.PROTIMERCC0BASE = RM_Field_FRC_TRAILRXDATA_PROTIMERCC0BASE(self)\n self.zz_fdict['PROTIMERCC0BASE'] = self.PROTIMERCC0BASE\n self.PROTIMERCC0WRAPL = RM_Field_FRC_TRAILRXDATA_PROTIMERCC0WRAPL(self)\n self.zz_fdict['PROTIMERCC0WRAPL'] = self.PROTIMERCC0WRAPL\n self.PROTIMERCC0WRAPH = RM_Field_FRC_TRAILRXDATA_PROTIMERCC0WRAPH(self)\n self.zz_fdict['PROTIMERCC0WRAPH'] = self.PROTIMERCC0WRAPH\n self.RTCSTAMP = RM_Field_FRC_TRAILRXDATA_RTCSTAMP(self)\n self.zz_fdict['RTCSTAMP'] = self.RTCSTAMP\n self.__dict__['zz_frozen'] = True\n\n\nclass RM_Register_FRC_SCNT(Base_RM_Register):\n def __init__(self, rmio, label):\n self.__dict__['zz_frozen'] = False\n super(RM_Register_FRC_SCNT, self).__init__(rmio, label,\n 0x40080000, 0x050,\n 'SCNT', 'FRC.SCNT', 'read-only',\n \"\",\n 0x00000000, 0x000000FF)\n\n self.SCNT = RM_Field_FRC_SCNT_SCNT(self)\n self.zz_fdict['SCNT'] = self.SCNT\n self.__dict__['zz_frozen'] = True\n\n\nclass RM_Register_FRC_CONVGENERATOR(Base_RM_Register):\n def __init__(self, rmio, label):\n self.__dict__['zz_frozen'] = False\n super(RM_Register_FRC_CONVGENERATOR, self).__init__(rmio, label,\n 0x40080000, 0x054,\n 'CONVGENERATOR', 'FRC.CONVGENERATOR', 'read-write',\n \"\",\n 0x00000000, 0x00037F7F)\n\n self.GENERATOR0 = RM_Field_FRC_CONVGENERATOR_GENERATOR0(self)\n self.zz_fdict['GENERATOR0'] = self.GENERATOR0\n self.GENERATOR1 = RM_Field_FRC_CONVGENERATOR_GENERATOR1(self)\n self.zz_fdict['GENERATOR1'] = self.GENERATOR1\n self.RECURSIVE = RM_Field_FRC_CONVGENERATOR_RECURSIVE(self)\n self.zz_fdict['RECURSIVE'] = self.RECURSIVE\n self.NONSYSTEMATIC = RM_Field_FRC_CONVGENERATOR_NONSYSTEMATIC(self)\n self.zz_fdict['NONSYSTEMATIC'] = self.NONSYSTEMATIC\n self.__dict__['zz_frozen'] = True\n\n\nclass RM_Register_FRC_PUNCTCTRL(Base_RM_Register):\n def __init__(self, rmio, label):\n self.__dict__['zz_frozen'] = False\n super(RM_Register_FRC_PUNCTCTRL, self).__init__(rmio, label,\n 0x40080000, 0x058,\n 'PUNCTCTRL', 'FRC.PUNCTCTRL', 'read-write',\n \"\",\n 0x00000101, 0x00007F7F)\n\n self.PUNCT0 = RM_Field_FRC_PUNCTCTRL_PUNCT0(self)\n self.zz_fdict['PUNCT0'] = self.PUNCT0\n self.PUNCT1 = RM_Field_FRC_PUNCTCTRL_PUNCT1(self)\n self.zz_fdict['PUNCT1'] = self.PUNCT1\n self.__dict__['zz_frozen'] = True\n\n\nclass RM_Register_FRC_PAUSECTRL(Base_RM_Register):\n def __init__(self, rmio, label):\n self.__dict__['zz_frozen'] = False\n super(RM_Register_FRC_PAUSECTRL, self).__init__(rmio, label,\n 0x40080000, 0x05C,\n 'PAUSECTRL', 'FRC.PAUSECTRL', 'read-write',\n \"\",\n 0x00000000, 0x001FFFFF)\n\n self.FRAMEDETPAUSEEN = RM_Field_FRC_PAUSECTRL_FRAMEDETPAUSEEN(self)\n self.zz_fdict['FRAMEDETPAUSEEN'] = self.FRAMEDETPAUSEEN\n self.TXINTERLEAVEWRITEPAUSEEN = RM_Field_FRC_PAUSECTRL_TXINTERLEAVEWRITEPAUSEEN(self)\n self.zz_fdict['TXINTERLEAVEWRITEPAUSEEN'] = self.TXINTERLEAVEWRITEPAUSEEN\n self.RXINTERLEAVEWRITEPAUSEEN = RM_Field_FRC_PAUSECTRL_RXINTERLEAVEWRITEPAUSEEN(self)\n self.zz_fdict['RXINTERLEAVEWRITEPAUSEEN'] = self.RXINTERLEAVEWRITEPAUSEEN\n self.INTERLEAVEREADPAUSEEN = RM_Field_FRC_PAUSECTRL_INTERLEAVEREADPAUSEEN(self)\n self.zz_fdict['INTERLEAVEREADPAUSEEN'] = self.INTERLEAVEREADPAUSEEN\n self.TXSUBFRAMEPAUSEEN = RM_Field_FRC_PAUSECTRL_TXSUBFRAMEPAUSEEN(self)\n self.zz_fdict['TXSUBFRAMEPAUSEEN'] = self.TXSUBFRAMEPAUSEEN\n self.CONVPAUSECNT = RM_Field_FRC_PAUSECTRL_CONVPAUSECNT(self)\n self.zz_fdict['CONVPAUSECNT'] = self.CONVPAUSECNT\n self.INTERLEAVEWRITEPAUSECNT = RM_Field_FRC_PAUSECTRL_INTERLEAVEWRITEPAUSECNT(self)\n self.zz_fdict['INTERLEAVEWRITEPAUSECNT'] = self.INTERLEAVEWRITEPAUSECNT\n self.INTERLEAVEREADPAUSECNT = RM_Field_FRC_PAUSECTRL_INTERLEAVEREADPAUSECNT(self)\n self.zz_fdict['INTERLEAVEREADPAUSECNT'] = self.INTERLEAVEREADPAUSECNT\n self.__dict__['zz_frozen'] = True\n\n\nclass RM_Register_FRC_IF(Base_RM_Register):\n def __init__(self, rmio, label):\n self.__dict__['zz_frozen'] = False\n super(RM_Register_FRC_IF, self).__init__(rmio, label,\n 0x40080000, 0x060,\n 'IF', 'FRC.IF', 'read-only',\n \"\",\n 0x00000000, 0x7F07FFFF)\n\n self.TXDONE = RM_Field_FRC_IF_TXDONE(self)\n self.zz_fdict['TXDONE'] = self.TXDONE\n self.TXAFTERFRAMEDONE = RM_Field_FRC_IF_TXAFTERFRAMEDONE(self)\n self.zz_fdict['TXAFTERFRAMEDONE'] = self.TXAFTERFRAMEDONE\n self.TXABORTED = RM_Field_FRC_IF_TXABORTED(self)\n self.zz_fdict['TXABORTED'] = self.TXABORTED\n self.TXUF = RM_Field_FRC_IF_TXUF(self)\n self.zz_fdict['TXUF'] = self.TXUF\n self.RXDONE = RM_Field_FRC_IF_RXDONE(self)\n self.zz_fdict['RXDONE'] = self.RXDONE\n self.RXABORTED = RM_Field_FRC_IF_RXABORTED(self)\n self.zz_fdict['RXABORTED'] = self.RXABORTED\n self.FRAMEERROR = RM_Field_FRC_IF_FRAMEERROR(self)\n self.zz_fdict['FRAMEERROR'] = self.FRAMEERROR\n self.BLOCKERROR = RM_Field_FRC_IF_BLOCKERROR(self)\n self.zz_fdict['BLOCKERROR'] = self.BLOCKERROR\n self.RXOF = RM_Field_FRC_IF_RXOF(self)\n self.zz_fdict['RXOF'] = self.RXOF\n self.WCNTCMP0 = RM_Field_FRC_IF_WCNTCMP0(self)\n self.zz_fdict['WCNTCMP0'] = self.WCNTCMP0\n self.WCNTCMP1 = RM_Field_FRC_IF_WCNTCMP1(self)\n self.zz_fdict['WCNTCMP1'] = self.WCNTCMP1\n self.WCNTCMP2 = RM_Field_FRC_IF_WCNTCMP2(self)\n self.zz_fdict['WCNTCMP2'] = self.WCNTCMP2\n self.ADDRERROR = RM_Field_FRC_IF_ADDRERROR(self)\n self.zz_fdict['ADDRERROR'] = self.ADDRERROR\n self.BUSERROR = RM_Field_FRC_IF_BUSERROR(self)\n self.zz_fdict['BUSERROR'] = self.BUSERROR\n self.RXRAWEVENT = RM_Field_FRC_IF_RXRAWEVENT(self)\n self.zz_fdict['RXRAWEVENT'] = self.RXRAWEVENT\n self.TXRAWEVENT = RM_Field_FRC_IF_TXRAWEVENT(self)\n self.zz_fdict['TXRAWEVENT'] = self.TXRAWEVENT\n self.SNIFFOF = RM_Field_FRC_IF_SNIFFOF(self)\n self.zz_fdict['SNIFFOF'] = self.SNIFFOF\n self.LVDSWILLERROR = RM_Field_FRC_IF_LVDSWILLERROR(self)\n self.zz_fdict['LVDSWILLERROR'] = self.LVDSWILLERROR\n self.LVDSERROR = RM_Field_FRC_IF_LVDSERROR(self)\n self.zz_fdict['LVDSERROR'] = self.LVDSERROR\n self.FRAMEDETPAUSED = RM_Field_FRC_IF_FRAMEDETPAUSED(self)\n self.zz_fdict['FRAMEDETPAUSED'] = self.FRAMEDETPAUSED\n self.INTERLEAVEWRITEPAUSED = RM_Field_FRC_IF_INTERLEAVEWRITEPAUSED(self)\n self.zz_fdict['INTERLEAVEWRITEPAUSED'] = self.INTERLEAVEWRITEPAUSED\n self.INTERLEAVEREADPAUSED = RM_Field_FRC_IF_INTERLEAVEREADPAUSED(self)\n self.zz_fdict['INTERLEAVEREADPAUSED'] = self.INTERLEAVEREADPAUSED\n self.TXSUBFRAMEPAUSED = RM_Field_FRC_IF_TXSUBFRAMEPAUSED(self)\n self.zz_fdict['TXSUBFRAMEPAUSED'] = self.TXSUBFRAMEPAUSED\n self.CONVPAUSED = RM_Field_FRC_IF_CONVPAUSED(self)\n self.zz_fdict['CONVPAUSED'] = self.CONVPAUSED\n self.RXWORD = RM_Field_FRC_IF_RXWORD(self)\n self.zz_fdict['RXWORD'] = self.RXWORD\n self.TXWORD = RM_Field_FRC_IF_TXWORD(self)\n self.zz_fdict['TXWORD'] = self.TXWORD\n self.__dict__['zz_frozen'] = True\n\n\nclass RM_Register_FRC_IFS(Base_RM_Register):\n def __init__(self, rmio, label):\n self.__dict__['zz_frozen'] = False\n super(RM_Register_FRC_IFS, self).__init__(rmio, label,\n 0x40080000, 0x064,\n 'IFS', 'FRC.IFS', 'write-only',\n \"\",\n 0x00000000, 0x0007FFFF)\n\n self.TXDONE = RM_Field_FRC_IFS_TXDONE(self)\n self.zz_fdict['TXDONE'] = self.TXDONE\n self.TXAFTERFRAMEDONE = RM_Field_FRC_IFS_TXAFTERFRAMEDONE(self)\n self.zz_fdict['TXAFTERFRAMEDONE'] = self.TXAFTERFRAMEDONE\n self.TXABORTED = RM_Field_FRC_IFS_TXABORTED(self)\n self.zz_fdict['TXABORTED'] = self.TXABORTED\n self.TXUF = RM_Field_FRC_IFS_TXUF(self)\n self.zz_fdict['TXUF'] = self.TXUF\n self.RXDONE = RM_Field_FRC_IFS_RXDONE(self)\n self.zz_fdict['RXDONE'] = self.RXDONE\n self.RXABORTED = RM_Field_FRC_IFS_RXABORTED(self)\n self.zz_fdict['RXABORTED'] = self.RXABORTED\n self.FRAMEERROR = RM_Field_FRC_IFS_FRAMEERROR(self)\n self.zz_fdict['FRAMEERROR'] = self.FRAMEERROR\n self.BLOCKERROR = RM_Field_FRC_IFS_BLOCKERROR(self)\n self.zz_fdict['BLOCKERROR'] = self.BLOCKERROR\n self.RXOF = RM_Field_FRC_IFS_RXOF(self)\n self.zz_fdict['RXOF'] = self.RXOF\n self.WCNTCMP0 = RM_Field_FRC_IFS_WCNTCMP0(self)\n self.zz_fdict['WCNTCMP0'] = self.WCNTCMP0\n self.WCNTCMP1 = RM_Field_FRC_IFS_WCNTCMP1(self)\n self.zz_fdict['WCNTCMP1'] = self.WCNTCMP1\n self.WCNTCMP2 = RM_Field_FRC_IFS_WCNTCMP2(self)\n self.zz_fdict['WCNTCMP2'] = self.WCNTCMP2\n self.ADDRERROR = RM_Field_FRC_IFS_ADDRERROR(self)\n self.zz_fdict['ADDRERROR'] = self.ADDRERROR\n self.BUSERROR = RM_Field_FRC_IFS_BUSERROR(self)\n self.zz_fdict['BUSERROR'] = self.BUSERROR\n self.RXRAWEVENT = RM_Field_FRC_IFS_RXRAWEVENT(self)\n self.zz_fdict['RXRAWEVENT'] = self.RXRAWEVENT\n self.TXRAWEVENT = RM_Field_FRC_IFS_TXRAWEVENT(self)\n self.zz_fdict['TXRAWEVENT'] = self.TXRAWEVENT\n self.SNIFFOF = RM_Field_FRC_IFS_SNIFFOF(self)\n self.zz_fdict['SNIFFOF'] = self.SNIFFOF\n self.LVDSWILLERROR = RM_Field_FRC_IFS_LVDSWILLERROR(self)\n self.zz_fdict['LVDSWILLERROR'] = self.LVDSWILLERROR\n self.LVDSERROR = RM_Field_FRC_IFS_LVDSERROR(self)\n self.zz_fdict['LVDSERROR'] = self.LVDSERROR\n self.__dict__['zz_frozen'] = True\n\n\nclass RM_Register_FRC_IFC(Base_RM_Register):\n def __init__(self, rmio, label):\n self.__dict__['zz_frozen'] = False\n super(RM_Register_FRC_IFC, self).__init__(rmio, label,\n 0x40080000, 0x068,\n 'IFC', 'FRC.IFC', 'write-only',\n \"\",\n 0x00000000, 0x0007FFFF)\n\n self.TXDONE = RM_Field_FRC_IFC_TXDONE(self)\n self.zz_fdict['TXDONE'] = self.TXDONE\n self.TXAFTERFRAMEDONE = RM_Field_FRC_IFC_TXAFTERFRAMEDONE(self)\n self.zz_fdict['TXAFTERFRAMEDONE'] = self.TXAFTERFRAMEDONE\n self.TXABORTED = RM_Field_FRC_IFC_TXABORTED(self)\n self.zz_fdict['TXABORTED'] = self.TXABORTED\n self.TXUF = RM_Field_FRC_IFC_TXUF(self)\n self.zz_fdict['TXUF'] = self.TXUF\n self.RXDONE = RM_Field_FRC_IFC_RXDONE(self)\n self.zz_fdict['RXDONE'] = self.RXDONE\n self.RXABORTED = RM_Field_FRC_IFC_RXABORTED(self)\n self.zz_fdict['RXABORTED'] = self.RXABORTED\n self.FRAMEERROR = RM_Field_FRC_IFC_FRAMEERROR(self)\n self.zz_fdict['FRAMEERROR'] = self.FRAMEERROR\n self.BLOCKERROR = RM_Field_FRC_IFC_BLOCKERROR(self)\n self.zz_fdict['BLOCKERROR'] = self.BLOCKERROR\n self.RXOF = RM_Field_FRC_IFC_RXOF(self)\n self.zz_fdict['RXOF'] = self.RXOF\n self.WCNTCMP0 = RM_Field_FRC_IFC_WCNTCMP0(self)\n self.zz_fdict['WCNTCMP0'] = self.WCNTCMP0\n self.WCNTCMP1 = RM_Field_FRC_IFC_WCNTCMP1(self)\n self.zz_fdict['WCNTCMP1'] = self.WCNTCMP1\n self.WCNTCMP2 = RM_Field_FRC_IFC_WCNTCMP2(self)\n self.zz_fdict['WCNTCMP2'] = self.WCNTCMP2\n self.ADDRERROR = RM_Field_FRC_IFC_ADDRERROR(self)\n self.zz_fdict['ADDRERROR'] = self.ADDRERROR\n self.BUSERROR = RM_Field_FRC_IFC_BUSERROR(self)\n self.zz_fdict['BUSERROR'] = self.BUSERROR\n self.RXRAWEVENT = RM_Field_FRC_IFC_RXRAWEVENT(self)\n self.zz_fdict['RXRAWEVENT'] = self.RXRAWEVENT\n self.TXRAWEVENT = RM_Field_FRC_IFC_TXRAWEVENT(self)\n self.zz_fdict['TXRAWEVENT'] = self.TXRAWEVENT\n self.SNIFFOF = RM_Field_FRC_IFC_SNIFFOF(self)\n self.zz_fdict['SNIFFOF'] = self.SNIFFOF\n self.LVDSWILLERROR = RM_Field_FRC_IFC_LVDSWILLERROR(self)\n self.zz_fdict['LVDSWILLERROR'] = self.LVDSWILLERROR\n self.LVDSERROR = RM_Field_FRC_IFC_LVDSERROR(self)\n self.zz_fdict['LVDSERROR'] = self.LVDSERROR\n self.__dict__['zz_frozen'] = True\n\n\nclass RM_Register_FRC_IEN(Base_RM_Register):\n def __init__(self, rmio, label):\n self.__dict__['zz_frozen'] = False\n super(RM_Register_FRC_IEN, self).__init__(rmio, label,\n 0x40080000, 0x06C,\n 'IEN', 'FRC.IEN', 'read-write',\n \"\",\n 0x00000000, 0x7F07FFFF)\n\n self.TXDONE = RM_Field_FRC_IEN_TXDONE(self)\n self.zz_fdict['TXDONE'] = self.TXDONE\n self.TXAFTERFRAMEDONE = RM_Field_FRC_IEN_TXAFTERFRAMEDONE(self)\n self.zz_fdict['TXAFTERFRAMEDONE'] = self.TXAFTERFRAMEDONE\n self.TXABORTED = RM_Field_FRC_IEN_TXABORTED(self)\n self.zz_fdict['TXABORTED'] = self.TXABORTED\n self.TXUF = RM_Field_FRC_IEN_TXUF(self)\n self.zz_fdict['TXUF'] = self.TXUF\n self.RXDONE = RM_Field_FRC_IEN_RXDONE(self)\n self.zz_fdict['RXDONE'] = self.RXDONE\n self.RXABORTED = RM_Field_FRC_IEN_RXABORTED(self)\n self.zz_fdict['RXABORTED'] = self.RXABORTED\n self.FRAMEERROR = RM_Field_FRC_IEN_FRAMEERROR(self)\n self.zz_fdict['FRAMEERROR'] = self.FRAMEERROR\n self.BLOCKERROR = RM_Field_FRC_IEN_BLOCKERROR(self)\n self.zz_fdict['BLOCKERROR'] = self.BLOCKERROR\n self.RXOF = RM_Field_FRC_IEN_RXOF(self)\n self.zz_fdict['RXOF'] = self.RXOF\n self.WCNTCMP0 = RM_Field_FRC_IEN_WCNTCMP0(self)\n self.zz_fdict['WCNTCMP0'] = self.WCNTCMP0\n self.WCNTCMP1 = RM_Field_FRC_IEN_WCNTCMP1(self)\n self.zz_fdict['WCNTCMP1'] = self.WCNTCMP1\n self.WCNTCMP2 = RM_Field_FRC_IEN_WCNTCMP2(self)\n self.zz_fdict['WCNTCMP2'] = self.WCNTCMP2\n self.ADDRERROR = RM_Field_FRC_IEN_ADDRERROR(self)\n self.zz_fdict['ADDRERROR'] = self.ADDRERROR\n self.BUSERROR = RM_Field_FRC_IEN_BUSERROR(self)\n self.zz_fdict['BUSERROR'] = self.BUSERROR\n self.RXRAWEVENT = RM_Field_FRC_IEN_RXRAWEVENT(self)\n self.zz_fdict['RXRAWEVENT'] = self.RXRAWEVENT\n self.TXRAWEVENT = RM_Field_FRC_IEN_TXRAWEVENT(self)\n self.zz_fdict['TXRAWEVENT'] = self.TXRAWEVENT\n self.SNIFFOF = RM_Field_FRC_IEN_SNIFFOF(self)\n self.zz_fdict['SNIFFOF'] = self.SNIFFOF\n self.LVDSWILLERROR = RM_Field_FRC_IEN_LVDSWILLERROR(self)\n self.zz_fdict['LVDSWILLERROR'] = self.LVDSWILLERROR\n self.LVDSERROR = RM_Field_FRC_IEN_LVDSERROR(self)\n self.zz_fdict['LVDSERROR'] = self.LVDSERROR\n self.FRAMEDETPAUSED = RM_Field_FRC_IEN_FRAMEDETPAUSED(self)\n self.zz_fdict['FRAMEDETPAUSED'] = self.FRAMEDETPAUSED\n self.INTERLEAVEWRITEPAUSED = RM_Field_FRC_IEN_INTERLEAVEWRITEPAUSED(self)\n self.zz_fdict['INTERLEAVEWRITEPAUSED'] = self.INTERLEAVEWRITEPAUSED\n self.INTERLEAVEREADPAUSED = RM_Field_FRC_IEN_INTERLEAVEREADPAUSED(self)\n self.zz_fdict['INTERLEAVEREADPAUSED'] = self.INTERLEAVEREADPAUSED\n self.TXSUBFRAMEPAUSED = RM_Field_FRC_IEN_TXSUBFRAMEPAUSED(self)\n self.zz_fdict['TXSUBFRAMEPAUSED'] = self.TXSUBFRAMEPAUSED\n self.CONVPAUSED = RM_Field_FRC_IEN_CONVPAUSED(self)\n self.zz_fdict['CONVPAUSED'] = self.CONVPAUSED\n self.RXWORD = RM_Field_FRC_IEN_RXWORD(self)\n self.zz_fdict['RXWORD'] = self.RXWORD\n self.TXWORD = RM_Field_FRC_IEN_TXWORD(self)\n self.zz_fdict['TXWORD'] = self.TXWORD\n self.__dict__['zz_frozen'] = True\n\n\nclass RM_Register_FRC_BUFFERMODE(Base_RM_Register):\n def __init__(self, rmio, label):\n self.__dict__['zz_frozen'] = False\n super(RM_Register_FRC_BUFFERMODE, self).__init__(rmio, label,\n 0x40080000, 0x070,\n 'BUFFERMODE', 'FRC.BUFFERMODE', 'read-write',\n \"\",\n 0x00000000, 0x00000007)\n\n self.TXBUFFERMODE = RM_Field_FRC_BUFFERMODE_TXBUFFERMODE(self)\n self.zz_fdict['TXBUFFERMODE'] = self.TXBUFFERMODE\n self.RXBUFFERMODE = RM_Field_FRC_BUFFERMODE_RXBUFFERMODE(self)\n self.zz_fdict['RXBUFFERMODE'] = self.RXBUFFERMODE\n self.__dict__['zz_frozen'] = True\n\n\nclass RM_Register_FRC_ROUTEPEN(Base_RM_Register):\n def __init__(self, rmio, label):\n self.__dict__['zz_frozen'] = False\n super(RM_Register_FRC_ROUTEPEN, self).__init__(rmio, label,\n 0x40080000, 0x074,\n 'ROUTEPEN', 'FRC.ROUTEPEN', 'read-write',\n \"\",\n 0x00000000, 0x00000007)\n\n self.DOUTPEN = RM_Field_FRC_ROUTEPEN_DOUTPEN(self)\n self.zz_fdict['DOUTPEN'] = self.DOUTPEN\n self.DCLKPEN = RM_Field_FRC_ROUTEPEN_DCLKPEN(self)\n self.zz_fdict['DCLKPEN'] = self.DCLKPEN\n self.DFRAMEPEN = RM_Field_FRC_ROUTEPEN_DFRAMEPEN(self)\n self.zz_fdict['DFRAMEPEN'] = self.DFRAMEPEN\n self.__dict__['zz_frozen'] = True\n\n\nclass RM_Register_FRC_ROUTELOC0(Base_RM_Register):\n def __init__(self, rmio, label):\n self.__dict__['zz_frozen'] = False\n super(RM_Register_FRC_ROUTELOC0, self).__init__(rmio, label,\n 0x40080000, 0x078,\n 'ROUTELOC0', 'FRC.ROUTELOC0', 'read-write',\n \"\",\n 0x00000000, 0x003F3F3F)\n\n self.DOUTLOC = RM_Field_FRC_ROUTELOC0_DOUTLOC(self)\n self.zz_fdict['DOUTLOC'] = self.DOUTLOC\n self.DCLKLOC = RM_Field_FRC_ROUTELOC0_DCLKLOC(self)\n self.zz_fdict['DCLKLOC'] = self.DCLKLOC\n self.DFRAMELOC = RM_Field_FRC_ROUTELOC0_DFRAMELOC(self)\n self.zz_fdict['DFRAMELOC'] = self.DFRAMELOC\n self.__dict__['zz_frozen'] = True\n\n\nclass RM_Register_FRC_SNIFFCTRL(Base_RM_Register):\n def __init__(self, rmio, label):\n self.__dict__['zz_frozen'] = False\n super(RM_Register_FRC_SNIFFCTRL, self).__init__(rmio, label,\n 0x40080000, 0x07C,\n 'SNIFFCTRL', 'FRC.SNIFFCTRL', 'read-write',\n \"\",\n 0x000007FC, 0x0001FFFF)\n\n self.SNIFFMODE = RM_Field_FRC_SNIFFCTRL_SNIFFMODE(self)\n self.zz_fdict['SNIFFMODE'] = self.SNIFFMODE\n self.SNIFFBITS = RM_Field_FRC_SNIFFCTRL_SNIFFBITS(self)\n self.zz_fdict['SNIFFBITS'] = self.SNIFFBITS\n self.SNIFFRXDATA = RM_Field_FRC_SNIFFCTRL_SNIFFRXDATA(self)\n self.zz_fdict['SNIFFRXDATA'] = self.SNIFFRXDATA\n self.SNIFFTXDATA = RM_Field_FRC_SNIFFCTRL_SNIFFTXDATA(self)\n self.zz_fdict['SNIFFTXDATA'] = self.SNIFFTXDATA\n self.SNIFFRSSI = RM_Field_FRC_SNIFFCTRL_SNIFFRSSI(self)\n self.zz_fdict['SNIFFRSSI'] = self.SNIFFRSSI\n self.SNIFFSTATE = RM_Field_FRC_SNIFFCTRL_SNIFFSTATE(self)\n self.zz_fdict['SNIFFSTATE'] = self.SNIFFSTATE\n self.SNIFFAUXDATA = RM_Field_FRC_SNIFFCTRL_SNIFFAUXDATA(self)\n self.zz_fdict['SNIFFAUXDATA'] = self.SNIFFAUXDATA\n self.SNIFFBR = RM_Field_FRC_SNIFFCTRL_SNIFFBR(self)\n self.zz_fdict['SNIFFBR'] = self.SNIFFBR\n self.SNIFFSLEEPCTRL = RM_Field_FRC_SNIFFCTRL_SNIFFSLEEPCTRL(self)\n self.zz_fdict['SNIFFSLEEPCTRL'] = self.SNIFFSLEEPCTRL\n self.__dict__['zz_frozen'] = True\n\n\nclass RM_Register_FRC_AUXDATA(Base_RM_Register):\n def __init__(self, rmio, label):\n self.__dict__['zz_frozen'] = False\n super(RM_Register_FRC_AUXDATA, self).__init__(rmio, label,\n 0x40080000, 0x080,\n 'AUXDATA', 'FRC.AUXDATA', 'read-write',\n \"\",\n 0x00000000, 0x000001FF)\n\n self.AUXDATA = RM_Field_FRC_AUXDATA_AUXDATA(self)\n self.zz_fdict['AUXDATA'] = self.AUXDATA\n self.__dict__['zz_frozen'] = True\n\n\nclass RM_Register_FRC_RAWCTRL(Base_RM_Register):\n def __init__(self, rmio, label):\n self.__dict__['zz_frozen'] = False\n super(RM_Register_FRC_RAWCTRL, self).__init__(rmio, label,\n 0x40080000, 0x084,\n 'RAWCTRL', 'FRC.RAWCTRL', 'read-write',\n \"\",\n 0x00000000, 0x00000FBF)\n\n self.TXRAWMODE = RM_Field_FRC_RAWCTRL_TXRAWMODE(self)\n self.zz_fdict['TXRAWMODE'] = self.TXRAWMODE\n self.RXRAWMODE = RM_Field_FRC_RAWCTRL_RXRAWMODE(self)\n self.zz_fdict['RXRAWMODE'] = self.RXRAWMODE\n self.RXRAWRANDOM = RM_Field_FRC_RAWCTRL_RXRAWRANDOM(self)\n self.zz_fdict['RXRAWRANDOM'] = self.RXRAWRANDOM\n self.RXRAWTRIGGER = RM_Field_FRC_RAWCTRL_RXRAWTRIGGER(self)\n self.zz_fdict['RXRAWTRIGGER'] = self.RXRAWTRIGGER\n self.RXRAWPRSSEL = RM_Field_FRC_RAWCTRL_RXRAWPRSSEL(self)\n self.zz_fdict['RXRAWPRSSEL'] = self.RXRAWPRSSEL\n self.__dict__['zz_frozen'] = True\n\n\nclass RM_Register_FRC_RXRAWDATA(Base_RM_Register):\n def __init__(self, rmio, label):\n self.__dict__['zz_frozen'] = False\n super(RM_Register_FRC_RXRAWDATA, self).__init__(rmio, label,\n 0x40080000, 0x088,\n 'RXRAWDATA', 'FRC.RXRAWDATA', 'read-only',\n \"\",\n 0x00000000, 0xFFFFFFFF)\n\n self.RXRAWDATA = RM_Field_FRC_RXRAWDATA_RXRAWDATA(self)\n self.zz_fdict['RXRAWDATA'] = self.RXRAWDATA\n self.__dict__['zz_frozen'] = True\n\n\nclass RM_Register_FRC_PAUSEDATA(Base_RM_Register):\n def __init__(self, rmio, label):\n self.__dict__['zz_frozen'] = False\n super(RM_Register_FRC_PAUSEDATA, self).__init__(rmio, label,\n 0x40080000, 0x08C,\n 'PAUSEDATA', 'FRC.PAUSEDATA', 'read-only',\n \"\",\n 0x00000000, 0xFFFFFFFF)\n\n self.PAUSEDATA = RM_Field_FRC_PAUSEDATA_PAUSEDATA(self)\n self.zz_fdict['PAUSEDATA'] = self.PAUSEDATA\n self.__dict__['zz_frozen'] = True\n\n\nclass RM_Register_FRC_LIKELYCONVSTATE(Base_RM_Register):\n def __init__(self, rmio, label):\n self.__dict__['zz_frozen'] = False\n super(RM_Register_FRC_LIKELYCONVSTATE, self).__init__(rmio, label,\n 0x40080000, 0x090,\n 'LIKELYCONVSTATE', 'FRC.LIKELYCONVSTATE', 'read-only',\n \"\",\n 0x00000000, 0x0000003F)\n\n self.LIKELYCONVSTATE = RM_Field_FRC_LIKELYCONVSTATE_LIKELYCONVSTATE(self)\n self.zz_fdict['LIKELYCONVSTATE'] = self.LIKELYCONVSTATE\n self.__dict__['zz_frozen'] = True\n\n\nclass RM_Register_FRC_INTELEMENTNEXT(Base_RM_Register):\n def __init__(self, rmio, label):\n self.__dict__['zz_frozen'] = False\n super(RM_Register_FRC_INTELEMENTNEXT, self).__init__(rmio, label,\n 0x40080000, 0x094,\n 'INTELEMENTNEXT', 'FRC.INTELEMENTNEXT', 'read-only',\n \"\",\n 0x00000000, 0x000000FF)\n\n self.INTELEMENTNEXT = RM_Field_FRC_INTELEMENTNEXT_INTELEMENTNEXT(self)\n self.zz_fdict['INTELEMENTNEXT'] = self.INTELEMENTNEXT\n self.__dict__['zz_frozen'] = True\n\n\nclass RM_Register_FRC_INTWRITEPOINT(Base_RM_Register):\n def __init__(self, rmio, label):\n self.__dict__['zz_frozen'] = False\n super(RM_Register_FRC_INTWRITEPOINT, self).__init__(rmio, label,\n 0x40080000, 0x098,\n 'INTWRITEPOINT', 'FRC.INTWRITEPOINT', 'read-write',\n \"\",\n 0x00000000, 0x0000001F)\n\n self.INTWRITEPOINT = RM_Field_FRC_INTWRITEPOINT_INTWRITEPOINT(self)\n self.zz_fdict['INTWRITEPOINT'] = self.INTWRITEPOINT\n self.__dict__['zz_frozen'] = True\n\n\nclass RM_Register_FRC_INTREADPOINT(Base_RM_Register):\n def __init__(self, rmio, label):\n self.__dict__['zz_frozen'] = False\n super(RM_Register_FRC_INTREADPOINT, self).__init__(rmio, label,\n 0x40080000, 0x09C,\n 'INTREADPOINT', 'FRC.INTREADPOINT', 'read-write',\n \"\",\n 0x00000000, 0x0000001F)\n\n self.INTREADPOINT = RM_Field_FRC_INTREADPOINT_INTREADPOINT(self)\n self.zz_fdict['INTREADPOINT'] = self.INTREADPOINT\n self.__dict__['zz_frozen'] = True\n\n\nclass RM_Register_FRC_FCD0(Base_RM_Register):\n def __init__(self, rmio, label):\n self.__dict__['zz_frozen'] = False\n super(RM_Register_FRC_FCD0, self).__init__(rmio, label,\n 0x40080000, 0x0A0,\n 'FCD0', 'FRC.FCD0', 'read-write',\n \"\",\n 0x000000FF, 0x00007FFF)\n\n self.WORDS = RM_Field_FRC_FCD0_WORDS(self)\n self.zz_fdict['WORDS'] = self.WORDS\n self.BUFFER = RM_Field_FRC_FCD0_BUFFER(self)\n self.zz_fdict['BUFFER'] = self.BUFFER\n self.INCLUDECRC = RM_Field_FRC_FCD0_INCLUDECRC(self)\n self.zz_fdict['INCLUDECRC'] = self.INCLUDECRC\n self.CALCCRC = RM_Field_FRC_FCD0_CALCCRC(self)\n self.zz_fdict['CALCCRC'] = self.CALCCRC\n self.SKIPCRC = RM_Field_FRC_FCD0_SKIPCRC(self)\n self.zz_fdict['SKIPCRC'] = self.SKIPCRC\n self.SKIPWHITE = RM_Field_FRC_FCD0_SKIPWHITE(self)\n self.zz_fdict['SKIPWHITE'] = self.SKIPWHITE\n self.__dict__['zz_frozen'] = True\n\n\nclass RM_Register_FRC_FCD1(Base_RM_Register):\n def __init__(self, rmio, label):\n self.__dict__['zz_frozen'] = False\n super(RM_Register_FRC_FCD1, self).__init__(rmio, label,\n 0x40080000, 0x0A4,\n 'FCD1', 'FRC.FCD1', 'read-write',\n \"\",\n 0x000000FF, 0x00007FFF)\n\n self.WORDS = RM_Field_FRC_FCD1_WORDS(self)\n self.zz_fdict['WORDS'] = self.WORDS\n self.BUFFER = RM_Field_FRC_FCD1_BUFFER(self)\n self.zz_fdict['BUFFER'] = self.BUFFER\n self.INCLUDECRC = RM_Field_FRC_FCD1_INCLUDECRC(self)\n self.zz_fdict['INCLUDECRC'] = self.INCLUDECRC\n self.CALCCRC = RM_Field_FRC_FCD1_CALCCRC(self)\n self.zz_fdict['CALCCRC'] = self.CALCCRC\n self.SKIPCRC = RM_Field_FRC_FCD1_SKIPCRC(self)\n self.zz_fdict['SKIPCRC'] = self.SKIPCRC\n self.SKIPWHITE = RM_Field_FRC_FCD1_SKIPWHITE(self)\n self.zz_fdict['SKIPWHITE'] = self.SKIPWHITE\n self.__dict__['zz_frozen'] = True\n\n\nclass RM_Register_FRC_FCD2(Base_RM_Register):\n def __init__(self, rmio, label):\n self.__dict__['zz_frozen'] = False\n super(RM_Register_FRC_FCD2, self).__init__(rmio, label,\n 0x40080000, 0x0A8,\n 'FCD2', 'FRC.FCD2', 'read-write',\n \"\",\n 0x000000FF, 0x00007FFF)\n\n self.WORDS = RM_Field_FRC_FCD2_WORDS(self)\n self.zz_fdict['WORDS'] = self.WORDS\n self.BUFFER = RM_Field_FRC_FCD2_BUFFER(self)\n self.zz_fdict['BUFFER'] = self.BUFFER\n self.INCLUDECRC = RM_Field_FRC_FCD2_INCLUDECRC(self)\n self.zz_fdict['INCLUDECRC'] = self.INCLUDECRC\n self.CALCCRC = RM_Field_FRC_FCD2_CALCCRC(self)\n self.zz_fdict['CALCCRC'] = self.CALCCRC\n self.SKIPCRC = RM_Field_FRC_FCD2_SKIPCRC(self)\n self.zz_fdict['SKIPCRC'] = self.SKIPCRC\n self.SKIPWHITE = RM_Field_FRC_FCD2_SKIPWHITE(self)\n self.zz_fdict['SKIPWHITE'] = self.SKIPWHITE\n self.__dict__['zz_frozen'] = True\n\n\nclass RM_Register_FRC_FCD3(Base_RM_Register):\n def __init__(self, rmio, label):\n self.__dict__['zz_frozen'] = False\n super(RM_Register_FRC_FCD3, self).__init__(rmio, label,\n 0x40080000, 0x0AC,\n 'FCD3', 'FRC.FCD3', 'read-write',\n \"\",\n 0x000000FF, 0x00007FFF)\n\n self.WORDS = RM_Field_FRC_FCD3_WORDS(self)\n self.zz_fdict['WORDS'] = self.WORDS\n self.BUFFER = RM_Field_FRC_FCD3_BUFFER(self)\n self.zz_fdict['BUFFER'] = self.BUFFER\n self.INCLUDECRC = RM_Field_FRC_FCD3_INCLUDECRC(self)\n self.zz_fdict['INCLUDECRC'] = self.INCLUDECRC\n self.CALCCRC = RM_Field_FRC_FCD3_CALCCRC(self)\n self.zz_fdict['CALCCRC'] = self.CALCCRC\n self.SKIPCRC = RM_Field_FRC_FCD3_SKIPCRC(self)\n self.zz_fdict['SKIPCRC'] = self.SKIPCRC\n self.SKIPWHITE = RM_Field_FRC_FCD3_SKIPWHITE(self)\n self.zz_fdict['SKIPWHITE'] = self.SKIPWHITE\n self.__dict__['zz_frozen'] = True\n\n\nclass RM_Register_FRC_INTELEMENT0(Base_RM_Register):\n def __init__(self, rmio, label):\n self.__dict__['zz_frozen'] = False\n super(RM_Register_FRC_INTELEMENT0, self).__init__(rmio, label,\n 0x40080000, 0x0C0,\n 'INTELEMENT0', 'FRC.INTELEMENT0', 'read-only',\n \"\",\n 0x00000000, 0x000000FF)\n\n self.INTELEMENT = RM_Field_FRC_INTELEMENT0_INTELEMENT(self)\n self.zz_fdict['INTELEMENT'] = self.INTELEMENT\n self.__dict__['zz_frozen'] = True\n\n\nclass RM_Register_FRC_INTELEMENT1(Base_RM_Register):\n def __init__(self, rmio, label):\n self.__dict__['zz_frozen'] = False\n super(RM_Register_FRC_INTELEMENT1, self).__init__(rmio, label,\n 0x40080000, 0x0C4,\n 'INTELEMENT1', 'FRC.INTELEMENT1', 'read-only',\n \"\",\n 0x00000000, 0x000000FF)\n\n self.INTELEMENT = RM_Field_FRC_INTELEMENT1_INTELEMENT(self)\n self.zz_fdict['INTELEMENT'] = self.INTELEMENT\n self.__dict__['zz_frozen'] = True\n\n\nclass RM_Register_FRC_INTELEMENT2(Base_RM_Register):\n def __init__(self, rmio, label):\n self.__dict__['zz_frozen'] = False\n super(RM_Register_FRC_INTELEMENT2, self).__init__(rmio, label,\n 0x40080000, 0x0C8,\n 'INTELEMENT2', 'FRC.INTELEMENT2', 'read-only',\n \"\",\n 0x00000000, 0x000000FF)\n\n self.INTELEMENT = RM_Field_FRC_INTELEMENT2_INTELEMENT(self)\n self.zz_fdict['INTELEMENT'] = self.INTELEMENT\n self.__dict__['zz_frozen'] = True\n\n\nclass RM_Register_FRC_INTELEMENT3(Base_RM_Register):\n def __init__(self, rmio, label):\n self.__dict__['zz_frozen'] = False\n super(RM_Register_FRC_INTELEMENT3, self).__init__(rmio, label,\n 0x40080000, 0x0CC,\n 'INTELEMENT3', 'FRC.INTELEMENT3', 'read-only',\n \"\",\n 0x00000000, 0x000000FF)\n\n self.INTELEMENT = RM_Field_FRC_INTELEMENT3_INTELEMENT(self)\n self.zz_fdict['INTELEMENT'] = self.INTELEMENT\n self.__dict__['zz_frozen'] = True\n\n\nclass RM_Register_FRC_INTELEMENT4(Base_RM_Register):\n def __init__(self, rmio, label):\n self.__dict__['zz_frozen'] = False\n super(RM_Register_FRC_INTELEMENT4, self).__init__(rmio, label,\n 0x40080000, 0x0D0,\n 'INTELEMENT4', 'FRC.INTELEMENT4', 'read-only',\n \"\",\n 0x00000000, 0x000000FF)\n\n self.INTELEMENT = RM_Field_FRC_INTELEMENT4_INTELEMENT(self)\n self.zz_fdict['INTELEMENT'] = self.INTELEMENT\n self.__dict__['zz_frozen'] = True\n\n\nclass RM_Register_FRC_INTELEMENT5(Base_RM_Register):\n def __init__(self, rmio, label):\n self.__dict__['zz_frozen'] = False\n super(RM_Register_FRC_INTELEMENT5, self).__init__(rmio, label,\n 0x40080000, 0x0D4,\n 'INTELEMENT5', 'FRC.INTELEMENT5', 'read-only',\n \"\",\n 0x00000000, 0x000000FF)\n\n self.INTELEMENT = RM_Field_FRC_INTELEMENT5_INTELEMENT(self)\n self.zz_fdict['INTELEMENT'] = self.INTELEMENT\n self.__dict__['zz_frozen'] = True\n\n\nclass RM_Register_FRC_INTELEMENT6(Base_RM_Register):\n def __init__(self, rmio, label):\n self.__dict__['zz_frozen'] = False\n super(RM_Register_FRC_INTELEMENT6, self).__init__(rmio, label,\n 0x40080000, 0x0D8,\n 'INTELEMENT6', 'FRC.INTELEMENT6', 'read-only',\n \"\",\n 0x00000000, 0x000000FF)\n\n self.INTELEMENT = RM_Field_FRC_INTELEMENT6_INTELEMENT(self)\n self.zz_fdict['INTELEMENT'] = self.INTELEMENT\n self.__dict__['zz_frozen'] = True\n\n\nclass RM_Register_FRC_INTELEMENT7(Base_RM_Register):\n def __init__(self, rmio, label):\n self.__dict__['zz_frozen'] = False\n super(RM_Register_FRC_INTELEMENT7, self).__init__(rmio, label,\n 0x40080000, 0x0DC,\n 'INTELEMENT7', 'FRC.INTELEMENT7', 'read-only',\n \"\",\n 0x00000000, 0x000000FF)\n\n self.INTELEMENT = RM_Field_FRC_INTELEMENT7_INTELEMENT(self)\n self.zz_fdict['INTELEMENT'] = self.INTELEMENT\n self.__dict__['zz_frozen'] = True\n\n\nclass RM_Register_FRC_INTELEMENT8(Base_RM_Register):\n def __init__(self, rmio, label):\n self.__dict__['zz_frozen'] = False\n super(RM_Register_FRC_INTELEMENT8, self).__init__(rmio, label,\n 0x40080000, 0x0E0,\n 'INTELEMENT8', 'FRC.INTELEMENT8', 'read-only',\n \"\",\n 0x00000000, 0x000000FF)\n\n self.INTELEMENT = RM_Field_FRC_INTELEMENT8_INTELEMENT(self)\n self.zz_fdict['INTELEMENT'] = self.INTELEMENT\n self.__dict__['zz_frozen'] = True\n\n\nclass RM_Register_FRC_INTELEMENT9(Base_RM_Register):\n def __init__(self, rmio, label):\n self.__dict__['zz_frozen'] = False\n super(RM_Register_FRC_INTELEMENT9, self).__init__(rmio, label,\n 0x40080000, 0x0E4,\n 'INTELEMENT9', 'FRC.INTELEMENT9', 'read-only',\n \"\",\n 0x00000000, 0x000000FF)\n\n self.INTELEMENT = RM_Field_FRC_INTELEMENT9_INTELEMENT(self)\n self.zz_fdict['INTELEMENT'] = self.INTELEMENT\n self.__dict__['zz_frozen'] = True\n\n\nclass RM_Register_FRC_INTELEMENT10(Base_RM_Register):\n def __init__(self, rmio, label):\n self.__dict__['zz_frozen'] = False\n super(RM_Register_FRC_INTELEMENT10, self).__init__(rmio, label,\n 0x40080000, 0x0E8,\n 'INTELEMENT10', 'FRC.INTELEMENT10', 'read-only',\n \"\",\n 0x00000000, 0x000000FF)\n\n self.INTELEMENT = RM_Field_FRC_INTELEMENT10_INTELEMENT(self)\n self.zz_fdict['INTELEMENT'] = self.INTELEMENT\n self.__dict__['zz_frozen'] = True\n\n\nclass RM_Register_FRC_INTELEMENT11(Base_RM_Register):\n def __init__(self, rmio, label):\n self.__dict__['zz_frozen'] = False\n super(RM_Register_FRC_INTELEMENT11, self).__init__(rmio, label,\n 0x40080000, 0x0EC,\n 'INTELEMENT11', 'FRC.INTELEMENT11', 'read-only',\n \"\",\n 0x00000000, 0x000000FF)\n\n self.INTELEMENT = RM_Field_FRC_INTELEMENT11_INTELEMENT(self)\n self.zz_fdict['INTELEMENT'] = self.INTELEMENT\n self.__dict__['zz_frozen'] = True\n\n\nclass RM_Register_FRC_INTELEMENT12(Base_RM_Register):\n def __init__(self, rmio, label):\n self.__dict__['zz_frozen'] = False\n super(RM_Register_FRC_INTELEMENT12, self).__init__(rmio, label,\n 0x40080000, 0x0F0,\n 'INTELEMENT12', 'FRC.INTELEMENT12', 'read-only',\n \"\",\n 0x00000000, 0x000000FF)\n\n self.INTELEMENT = RM_Field_FRC_INTELEMENT12_INTELEMENT(self)\n self.zz_fdict['INTELEMENT'] = self.INTELEMENT\n self.__dict__['zz_frozen'] = True\n\n\nclass RM_Register_FRC_INTELEMENT13(Base_RM_Register):\n def __init__(self, rmio, label):\n self.__dict__['zz_frozen'] = False\n super(RM_Register_FRC_INTELEMENT13, self).__init__(rmio, label,\n 0x40080000, 0x0F4,\n 'INTELEMENT13', 'FRC.INTELEMENT13', 'read-only',\n \"\",\n 0x00000000, 0x000000FF)\n\n self.INTELEMENT = RM_Field_FRC_INTELEMENT13_INTELEMENT(self)\n self.zz_fdict['INTELEMENT'] = self.INTELEMENT\n self.__dict__['zz_frozen'] = True\n\n\nclass RM_Register_FRC_INTELEMENT14(Base_RM_Register):\n def __init__(self, rmio, label):\n self.__dict__['zz_frozen'] = False\n super(RM_Register_FRC_INTELEMENT14, self).__init__(rmio, label,\n 0x40080000, 0x0F8,\n 'INTELEMENT14', 'FRC.INTELEMENT14', 'read-only',\n \"\",\n 0x00000000, 0x000000FF)\n\n self.INTELEMENT = RM_Field_FRC_INTELEMENT14_INTELEMENT(self)\n self.zz_fdict['INTELEMENT'] = self.INTELEMENT\n self.__dict__['zz_frozen'] = True\n\n\nclass RM_Register_FRC_INTELEMENT15(Base_RM_Register):\n def __init__(self, rmio, label):\n self.__dict__['zz_frozen'] = False\n super(RM_Register_FRC_INTELEMENT15, self).__init__(rmio, label,\n 0x40080000, 0x0FC,\n 'INTELEMENT15', 'FRC.INTELEMENT15', 'read-only',\n \"\",\n 0x00000000, 0x000000FF)\n\n self.INTELEMENT = RM_Field_FRC_INTELEMENT15_INTELEMENT(self)\n self.zz_fdict['INTELEMENT'] = self.INTELEMENT\n self.__dict__['zz_frozen'] = True\n\n\n","sub_path":".closet/jython.configurator.efr32/1.0.0.201606231656-435/host_py_rm_studio_internal/host_py_rm_studio_internal_efr32xg1xfull/revA3/FRC_register.py","file_name":"FRC_register.py","file_ext":"py","file_size_in_byte":53396,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"291537378","text":"from telegram import Bot\n\nclass Telegram:\n\tTOKEN = '517147871:AAH6OAGMqFL8-3ZJ_zXqz7OlUjVr7ZRei_A'\n\tBASEURL = 'https://t.me/addstickers/'\n\t# change uid on another user(hpmd dev dev)\n\tUID = 191346331\n\n\tdef createStikerpack(self, path_to_image, id):\n\t\tbot = Bot(token=self.TOKEN)\n\n\t\tname = 'hpmd_8march' + str(id) + 'test_local' + '_by_HPMDBOT'\n\t\ttitle = 'hpmd' + str(id)\n\n\t\twith open(path_to_image, 'rb') as f:\n\t\t\tfile = bot.upload_sticker_file(self.UID, f)\n\t\t\tfile_url = file['file_id']\n\n\t\tbot.create_new_sticker_set(user_id=self.UID, name=name, title=title, png_sticker=file_url, emojis='💪')\n\n\t\treturn self.BASEURL + name","sub_path":"app/lib/telegram.py","file_name":"telegram.py","file_ext":"py","file_size_in_byte":625,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"396711792","text":"from django import forms\nfrom django.contrib.auth.models import User\nfrom django.db.models import Q\nfrom models import *\nfrom django.forms.widgets import RadioSelect\nimport decimal\n\nclass ExpenseModelForm(forms.ModelForm):\n\n class Meta:\n model = Expense\n exclude = ('date',)\n widgets = {\n 'extra_note': forms.Textarea(attrs={'rows':2, 'cols':15})\n }\n\nclass ExpenseBudgetLineForm(forms.ModelForm):\n\n def __init__(self, fiscal_year_id, *args, **kwargs):\n super (ExpenseBudgetLineForm,self).__init__(*args,**kwargs)\n self.fields['budget_line'].queryset = BudgetLine.objects.filter(Q(fiscal_year__id = fiscal_year_id))\n self.fields['subaccount'].queryset = SubAccount.objects.filter(Q(fiscal_year__id = fiscal_year_id))\n\n class Meta:\n model = ExpenseBudgetLine\n\n\nclass BaseExpenseBudgetLineFormset(forms.models.BaseInlineFormSet):\n\n def clean(self):\n if any(self.errors):\n return\n budget_line_id_list = []\n number_to_delete = 0\n for subform in self.forms:\n try:\n amount = subform.cleaned_data['amount']\n if decimal.Decimal(amount) <=0:\n raise forms.ValidationError(\"Amounts must be greater than zero. Use Debit or Credit accordingly.\")\n budgetline = subform.cleaned_data['budget_line']\n# if budgetline.id in budget_line_id_list:\n# raise forms.ValidationError(\"Each budget line may only be used once for a given transaction.\")\n budget_line_id_list.append(budgetline.id)\n delete_this = subform.cleaned_data[u'DELETE']\n if delete_this:\n number_to_delete = number_to_delete+1\n except KeyError:\n pass\n if len(budget_line_id_list) == 0:\n raise forms.ValidationError(\"Each transaction must use at least one budget line.\")\n if number_to_delete >= len(budget_line_id_list):\n raise forms.ValidationError(\"Each transaction must use at least one budget line. You cannot delete the last one(s).\")\n\n\nclass AddNoteForm(forms.ModelForm):\n\n class Meta:\n model = Note\n exclude = ('department', 'year')\n\n\nclass UpdateYearToViewForm(forms.ModelForm):\n\n class Meta:\n model = UserPreferences\n exclude = ('user','view_checked_only','view_encumbrances_only','view_future_only',)\n","sub_path":"budget_app/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":2437,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"305144211","text":"import os\n\nfrom flask_cors import CORS\n\nfrom flask import Flask, request\nfrom src.models.Organisation import Organisation\nfrom src.utils import ComplexEncoder\nimport json\n\n\n\n#### https://raw.githubusercontent.com/olbat/nvdcve/master/nvdcve/CVE-YYYY-XXXX.json\napp = Flask(__name__)\nCORS(app)\nx = Organisation(\"src/resources/Components.json\")\n\n\n# cve = CVESearch()\n# print(cve.search('microsoft/office'))\n\n@app.route('/organisation')\ndef get_organisation():\n x.read_from_json_file(\"src/resources/Components.json\")\n return json.dumps(x.reprJSON(), cls=ComplexEncoder)\n\n\n@app.route('/user/')\ndef getuser(user_id):\n app.logger.info('***** Looking for userID (%s) *****', user_id)\n user = x.get_user_by_id(user_id)\n if user:\n return json.dumps(user.reprJSON(), cls=ComplexEncoder), 200\n return \"User Not Found\", 404\n\n\n@app.route('/user/', methods=[\"PUT\"])\ndef set_suspicious(user_id):\n print(request.json[\"is_suspicious\"])\n app.logger.info('***** L (%s) *****', request)\n user = x.get_user_by_id(user_id)\n if user:\n user.suspicious = request.json[\"is_suspicious\"]\n x.save_organisation_to_file()\n return json.dumps(user.reprJSON(), cls=ComplexEncoder), 200\n return \"User Not Found\", 404\n\n\n@app.route('/user/', methods=[\"POST\"])\ndef update_user(user_id):\n app.logger.info('***** Looking for userID (%s) *****', user_id)\n user = x.get_user_by_id(user_id)\n if user:\n return json.dumps(user.reprJSON(), cls=ComplexEncoder), 200\n return \"User Not Found\", 404\n\n\n@app.route('/')\ndef not_found():\n return 'Error'\n\n\nport = int(os.environ.get('PORT', 5000))\nif __name__ == \"__main__\":\n app.run(host='0.0.0.0', port=port)\n","sub_path":"serverFlask.py","file_name":"serverFlask.py","file_ext":"py","file_size_in_byte":1729,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"41192370","text":"# coding: utf-8\n\n\"\"\"\n Dynamic SITE ID unittests\n ~~~~~~~~~~~~~~~~~~~~~~~~~\n \n :copyleft: 2012 by the django-tools team, see AUTHORS for more details.\n :license: GNU GPL v3 or above, see LICENSE for more details.\n\"\"\"\n\nfrom django.http import HttpResponse\nfrom django.conf import settings\nfrom django.contrib.sites.models import Site\n\n\n\ndef display_site(request):\n\n settings_id = settings.SITE_ID\n current_site = Site.objects.get_current()\n current_id = current_site.id\n\n txt = \"ID from settings: %r - id from get_current(): %r\" % (\n settings_id, current_id\n )\n return HttpResponse(txt)\n\n\n\n","sub_path":"venv/Lib/site-packages/django_tools-0.25.1-py2.7.egg/django_tools/dynamic_site/test_app/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":628,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"454721045","text":"primes = []\n\ndef gen_jamcoin(n):\n m = n-2\n for i in xrange(2**(m)):\n yield \"1{0:0{width}}1\".format(int(\"{0:b}\".format(i)), width=m)\n\ndef sieve(n):\n \"\"\"We want all primes up to n\"\"\"\n bits = [True]*(n+1)\n bits[0] = False\n bits[1] = False\n for i in range(2, n+1):\n if bits[i]:\n j = 2\n while i*j <= n:\n bits[i*j] = False\n j += 1\n for i in range(n+1):\n if bits[i]:\n primes.append(i)\n\ndef check_prime(coin):\n for prime in primes:\n if coin%prime == 0 and prime != coin:\n return prime\n return False\n\ndef check_valid(coin):\n out = []\n for base in range(2, 11):\n cur = int(coin, base)\n val = check_prime(cur)\n if not val:\n return False\n out.append(val)\n return out\n\ndef write(filename, out):\n with open(filename, 'w') as f:\n f.write(\"Case #1:\\n\")\n f.write(\"\\n\".join(out))\n f.write(\"\\n\")\n\nif __name__ == '__main__':\n import sys\n max_prime = 10000\n n = int(sys.argv[1])\n j = int(sys.argv[2])\n out = []\n outname = \"{0}-{1}.out\".format(n, j)\n\n sieve(max_prime)\n for i in gen_jamcoin(n):\n val = check_valid(i)\n if val:\n out.append(str(i) + \" \" + \" \".join(str(x) for x in val))\n if len(out) == j:\n break\n write(outname, out)\n","sub_path":"codes/CodeJamCrawler/16_0_3/Hvaara/c.py","file_name":"c.py","file_ext":"py","file_size_in_byte":1391,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"166201311","text":"import sqlite3\nfrom Tkinter import *\nimport tkMessageBox\n\ndb = sqlite3.connect(':memory:')\ndb = sqlite3.connect('data/mydbms')\n\ncursor = db.cursor()\ncursor.execute(\"DROP TABLE batsmen\")\t# Deleting the table if it exists\ncursor.execute('''\n CREATE TABLE batsmen(id INTEGER PRIMARY KEY, name TEXT,\n matches INTEGER, runs INTEGER, hun INTEGER\n )\n''')\ndb.commit()\n\ncursor.execute(\"INSERT INTO batsmen(id, name, matches, runs, hun) VALUES (101,'Tendulkar',664,34357,100)\")\ncursor.execute(\"INSERT INTO batsmen(id, name, matches, runs, hun) VALUES (102,'Dravid',504,24064,48)\")\ncursor.execute(\"INSERT INTO batsmen(id, name, matches, runs, hun) VALUES (103,'Ganguly',421,18433,38)\")\t\ncursor.execute(\"INSERT INTO batsmen(id, name, matches, runs, hun) VALUES (104,'Sehwag',363,16892,38)\")\ncursor.execute(\"INSERT INTO batsmen(id, name, matches, runs, hun) VALUES (105,'Dhoni',473,15685,15)\")\nprint('Batsmen data inserted.') # Check\n\ntitles = [\"ID\", \"Name\", \"Matches\", \"Runs\", \"Hundreds\"]\ndef helloCallBack():\n tkMessageBox.showinfo( \"Hello Python\", \"Hello World\")\n\ndef viewDB():\n\tw2 = Tk()\n\tw2.title(\"View Database\")\n\tl3 = Label(w2, text = titles)\n\tl3.pack()\n\tcursor.execute('''SELECT * FROM batsmen''')\n\tall_rows = cursor.fetchall()\n\tfor row in all_rows:\n\t\t# print('{0} : {1}, {2}, {3}, {4}'.format(row[0], row[1], row[2], row[3], row[4]))\n\t\tl = Label(w2, text=row)\n\t\tl.pack()\n\tl2 = Label(w2, text=\"Arrange by:\")\n\tl2.pack(side=LEFT)\n\n\tarr_name = Button(w2, text =\"Names\", command = viewNames)\n\tarr_matches = Button(w2, text =\"Matches\", command = viewMatches)\n\tarr_runs = Button(w2, text =\"Runs\", command = viewRuns)\n\tarr_hun = Button(w2, text =\"Hundreds\", command = viewHundreds)\n\n\tarr_name.pack(side=LEFT, padx=10)\n\tarr_matches.pack(side=LEFT, padx=10)\n\tarr_runs.pack(side=LEFT, padx=10)\n\tarr_hun.pack(side=LEFT, padx=10)\n\n\tw2.mainloop()\n\ndef viewNames():\n\tw3 = Tk()\n\tw3.title(\"Alphabetical Order\")\n\tl3 = Label(w3, text = titles)\n\tl3.pack()\n\tcursor.execute(\"SELECT * FROM batsmen ORDER BY name ASC\")\n\tall_rows = cursor.fetchall()\n\tfor row in all_rows:\n\t\tl = Label(w3, text=row)\n\t\tl.pack()\n\tw3.mainloop()\n\ndef viewMatches():\n\tw4 = Tk()\n\tw4.title(\"Matches\")\n\tl3 = Label(w4, text = titles)\n\tl3.pack()\n\tcursor.execute(\"SELECT * FROM batsmen ORDER BY matches DESC\")\n\tall_rows = cursor.fetchall()\n\tfor row in all_rows:\n\t\tl = Label(w4, text=row)\n\t\tl.pack()\n\tw4.mainloop()\n\n\ndef viewRuns():\n\tw5 = Tk()\n\tw5.title(\"Runs\")\n\tl3 = Label(w5, text = titles)\n\tl3.pack()\n\tcursor.execute(\"SELECT * FROM batsmen ORDER BY runs DESC\")\n\tall_rows = cursor.fetchall()\n\tfor row in all_rows:\n\t\tl = Label(w5, text=row)\n\t\tl.pack()\n\tw5.mainloop()\n\ndef viewHundreds():\n\tw6 = Tk()\n\tw6.title(\"Hundreds\")\n\tl3 = Label(w6, text = titles)\n\tl3.pack()\n\tcursor.execute(\"SELECT * FROM batsmen ORDER BY hun DESC\")\n\tall_rows = cursor.fetchall()\n\tfor row in all_rows:\n\t\tl = Label(w6, text=row)\n\t\tl.pack()\n\tw6.mainloop()\n\n\"\"\"\nThis section of code still needs work. Front-end and back-end do not seem to connect.\n\n# Function called by addPlayer - updates database.\n# def updatePlayerAdd(I,N,M,R,H): \n\n# Function called by delPlayer - also updates database. Takes only ID to delete.\ndef updatePlayerDel(I):\n\t# Perform check to verify ID exists\n\t\n\tcursor.execute(\"DELETE FROM batsmen WHERE id = ? \", (I,))\n\tviewDB()\n\n\ndef addPlayer():\n\twin = Tk()\n\n\twin.title(\"Add Player\")\n\t# v = StringVar()\n\t# l = Label(win, text=\"Enter batsman's name\")\n\t# l.pack(side=LEFT)\n\t# e = Entry(win,textvariable=v)\n\t# e.pack()\n\t# print v\n\n\tframe1 = Frame(win)\n\tframe1.pack()\n\n\tLabel(frame1, text=\"ID\").grid(row=0, column=0, sticky=W)\n iD= StringVar()\n idee = Entry(frame1, textvariable=iD)\n idee.grid(row=0, column=1, sticky=W)\n id_no = iD.get()\n print id_no\n\n\tLabel(frame1, text=\"Name\").grid(row=1, column=0, sticky=W)\n\tnameVar = StringVar()\n\tname = Entry(frame1, textvariable=nameVar)\n name.grid(row=1, column=1, sticky=W)\n n = nameVar.get()\n print n\n\t\n\tLabel(frame1, text=\"Matches\").grid(row=2, column=0, sticky=W)\n m = StringVar()\n matches = Entry(frame1, textvariable=m)\n matches.grid(row=2, column=1, sticky=W)\n matches_no = m.get()\n print matches_no\n\n\tLabel(frame1, text=\"Runs\").grid(row=3, column=0, sticky=W)\n r = StringVar()\n runs = Entry(frame1, textvariable=r)\n runs.grid(row=3, column=1, sticky=W)\n runs_no = r.get()\n print runs_no\t\n\n\tLabel(frame1, text=\"Hundreds\").grid(row=4, column=0, sticky=W)\n h = StringVar()\n hundreds = Entry(frame1, textvariable=h)\n hundreds.grid(row=4, column=1, sticky=W)\n hun_no = h.get()\n print hun_no \n\n\tB = Button(win, text=\"Update\",command=updatePlayerAdd(id_no,n,matches_no,runs_no,hun_no))\n\tB.pack()\n\twin.mainloop()\n\ndef delPlayer():\n\tw = Tk()\n\tf = Frame(w)\n\tdef return_entry(en):\n\t\tcontent = entry.get()\n\n\tLabel(f, text=\"Enter ID:\").grid(row=0, column=0, sticky=W)\n\t#iD = StringVar()\n\tidee = Entry(w)#(f, textvariable=iD)\n\tidee.grid(row=0, column=1, sticky=W)\n\t#id_no = iD.get()\n\t#print \"1\",id_no, \"2\",type(id_no), \"3\",iD, \"4\",type(iD)\n\tidee.bind('', return_entry)\n\tB = Button(w, text=\"Delete\",command=lambda:updatePlayerDel(idee))\n\tf.pack()\n\tB.pack()\n\tw.mainloop()\n\t#commentend\n\"\"\"\n\t\n\"\"\"\nSample code for reference. Ignore this fragment.\n\t\n\t# frame1 = Frame(win)\n # frame1.pack()\n\n # Label(frame1, text=\"Name\").grid(row=0, column=0, sticky=W)\n # nameVar = StringVar()\n # name = Entry(frame1, textvariable=nameVar)\n # name.grid(row=0, column=1, sticky=W)\n\"\"\"\n\n\nw = Tk()\nw.title(\"Cricketer's Database\")\nfr = Frame(w, width=400, height=100)\nl = Label(w, text=\"Welcome to Cricketer's Database!\")\nl.pack()\nview_db = Button(w, text =\"View Database\", command = viewDB)\n# add_pl = Button(w, text =\"Add Player\", command = addPlayer)\n# del_pl = Button(w, text =\"Delete Player\", command = delPlayer)\n\nview_db.pack(side=BOTTOM)#side=LEFT, padx=10)\n#add_pl.pack(side=LEFT, padx=10)\n#del_pl.pack(side=LEFT, padx=10)\n\n\nfr.pack()\nw.mainloop()\n","sub_path":"cricketer.py","file_name":"cricketer.py","file_ext":"py","file_size_in_byte":6037,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"189528164","text":"''' Qt lib imports '''\nfrom PyQt4 import QtCore, QtGui\nfrom RecognitionAlgorithm import *\n''' GUI classes import '''\nfrom QtGUI.mainWindow import Ui_MainWindow\n''' OpenCV imports '''\nimport numpy\nimport cv2\ntry:\n _fromUtf8 = QtCore.QString.fromUtf8\nexcept AttributeError:\n def _fromUtf8(s):\n return s\n\ntry:\n _encoding = QtGui.QApplication.UnicodeUTF8\n def _translate(context, text, disambig):\n return QtGui.QApplication.translate(context, text, disambig, _encoding)\nexcept AttributeError:\n def _translate(context, text, disambig):\n return QtGui.QApplication.translate(context, text, disambig)\n\n''' Class inheriting the compiled .ui file '''\nclass GUI(Ui_MainWindow):\n\n\t# Redefine inherited method \n\tdef setupUi(self,window):\n\t\t\n\t\t#call super constructor\n\t\tUi_MainWindow.setupUi(self, window)\n\t\t\n\t\t### Custom code ###\n\n\t\t# Crate storage for tabs\n\t\tself.tabs = [] \n\n\t\t#Link Openfile option action to file explorer opener\n\t\tself.actionOpen.triggered.connect(self.openFileExplorer)\n\t\tself.actionProcess.triggered.connect(self.process)\n\t\tself.generate.clicked.connect(self.process)\n\t\tself.generate.setEnabled(False)\n\t\tself.actionProcess.setEnabled(False)\n\t\tQtCore.QObject.connect(self.horizontalSlider, QtCore.SIGNAL('valueChanged(int)'), self.zoom)\n\t\tQtCore.QObject.connect(self.tabWidget, QtCore.SIGNAL('currentChanged(int)'), self.scaleTab)\n\n\t\n\t# Open file explorer \n\tdef openFileExplorer(self):\n\t\tfname = QtGui.QFileDialog.getOpenFileName( self.window, 'Open file', 'C:/')\n\t\tif fname:\n\t\t\tself.clearTabs()\n\t\t\tself.src = fname\n\t\t\tself.generate.setEnabled(True)\n\t\t\tself.actionProcess.setEnabled(True)\n\t\t\tself.openTab(\"Source\", fname)\n\n\t# Create new tab for placing an image\n\tdef openTab(self, title, imagePath):\n\t\t\n\t\t# Create object\n\t\ttab = QtGui.QWidget()\n\t\ttab.setObjectName(_fromUtf8(title))\n\t\ttab.horizontalLayout_2 = QtGui.QHBoxLayout(tab)\n\t\ttab.horizontalLayout_2.setObjectName(_fromUtf8(\"horizontalLayout_2\"))\n\t\ttab.graphicsView = QtGui.QGraphicsView(tab)\n\t\ttab.graphicsView.setObjectName(_fromUtf8(\"graphicsView\"))\n\t\t# Set image\n\t\tself.loadImageToTab(tab,tab.horizontalLayout_2, imagePath)\n\t\t# Add tab to the widget\n\t\tself.tabWidget.addTab(tab, _fromUtf8(\"\"))\n\t\tself.tabWidget.setTabText(self.tabWidget.indexOf(tab), _translate(\"MainWindow\", title, None))\n\t\t# Add tab to the list\n\t\tself.tabs.append(tab)\n\n\t# Clear all open tabs\n\tdef clearTabs(self):\n\n\t\tself.tabWidget.clear()\n\t\tfor tab in self.tabs:\n\t\t\tdel tab\n\n\tdef loadImageToTab(self,tab,layout,imagePath):\n\t\t# Add component to show image\n\t\tgraphicsScene = QtGui.QGraphicsScene(tab);\n\t\ttab.graphicsView.setScene(graphicsScene)\n\t\t# Load image \n\t\tgraphicsScene.addPixmap(QtGui.QPixmap(imagePath))\n\t\tlayout.addWidget(tab.graphicsView)\n\n\tdef zoom(self,scale):\n\t\tscaleFactor = scale / 1000.0\n\t\tif(self.tabWidget.currentWidget()):\n\t\t\tself.tabWidget.currentWidget().graphicsView.setTransform(QtGui.QTransform(scaleFactor,0,0,scaleFactor,0,0))\n\n\tdef scaleTab(self,idx):\n\t\tself.zoom(self.horizontalSlider.value())\n\n\tdef process(self):\n\t\tself.generate.setEnabled(False)\n\t\tself.actionProcess.setEnabled(False)\n\t\tfileName = str(self.src)\n\t\t#path = HaarCascadeAlgorithm(fileName,\"HAAR/descriptor.xml\")\n\t\t#self.openTab(\"HAAR\",path)\n\t\t#path = SIFT_FLANNMatching(fileName,'./FLANN/positive_200.png')\n\t\t#self.openTab(\"SIFT-FLANN\",path)\n\t\t#path = ORB_BFMatching(fileName,'./FLANN/positive_200.png')\n\t\t#self.openTab(\"ORB-FLANN\",path)\n\t\t#path = customIdentifier(fileName)\n\t\t#self.openTab(\"Property Analysis\",path)\n\t\tpath = detectionAlgorithm(fileName,\"HAAR/descriptor.xml\")\n\t\tself.openTab(\"Result\",path)\n\nif __name__ == \"__main__\":\n\timport sys\n\tapp = QtGui.QApplication(sys.argv)\n\tMainWindow = QtGui.QMainWindow()\n\tui = GUI()\n\tui.setupUi(MainWindow)\n\tMainWindow.show()\n\tsys.exit(app.exec_())","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3764,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"493330550","text":"#!/usr/bin/env python3\n# -*-coding: utf-8-*-\n# Author : Chris\n# Blog : http://blog.chriscabin.com\n# GitHub : https://www.github.com/chrisleegit\n# File : find.py\n# Date : 16-7-1\n# Version: 0.1\n# Description: ...\n\nimport fnmatch, os\n\n\ndef find(pattern, start_dir=os.curdir):\n for this_dir, subs_here, files_here in os.walk(start_dir):\n for name in subs_here + files_here:\n if fnmatch.fnmatch(name, pattern):\n full_path = os.path.join(this_dir, name)\n yield full_path\n\n\ndef main():\n import sys\n print(sys.argv)\n if len(sys.argv) == 2:\n for line in find(sys.argv[1]):\n print(line)\n\n if len(sys.argv) == 3:\n for line in find(sys.argv[1], sys.argv[2]):\n print(line)\n\n\nif __name__ == '__main__':\n main()\n\n","sub_path":"ch6/find.py","file_name":"find.py","file_ext":"py","file_size_in_byte":806,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"311543651","text":"from django.urls import path\nimport adminapp.views as adminapp\n\napp_name = 'adminapp'\n\nurlpatterns = [\n path('', adminapp.ShopUserListView.as_view(), name='index'),\n\n\n path('shopuser/create/', adminapp.shopuser_create,\n name='shopuser_create'),\n path('shopuser/update/)/', adminapp.shopuser_update,\n name='shopuser_update'),\n path('shopuser/delete/)/', adminapp.shopuser_delete,\n name='shopuser_delete'),\n\n\n path('productcategory/list/', adminapp.productcategory_list,\n name='productcategory_list'),\n path('productcategory/create/', adminapp.ProductCategoryCreateView.as_view(),\n name='productcategory_create'),\n path('productcategory/update/)/', adminapp.ProductCategoryUpdateView.as_view(),\n name='productcategory_update'),\n path('productcategory/delete/)/', adminapp.ProductCategoryDeleteView.as_view(),\n name='productcategory_delete'),\n path('productcategory/products/)/', adminapp.productcategory_products,\n name='productcategory_products'),\n\n\n path('product/create/)/', adminapp.product_create,\n name='product_create'),\n path('product/update/)/', adminapp.product_update,\n name='product_update'),\n path('product/delete/)/', adminapp.product_delete,\n name='product_delete'),\n path('product/read/)/', adminapp.ProductDetailView.as_view(),\n name='product_read'),\n\n]\n","sub_path":"adminapp/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1476,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"458203132","text":"from distutils.core import setup\nimport inspect\nimport os\n\nSETUP_DIRECTORY = os.path.dirname(os.path.abspath(inspect.getfile(\n inspect.currentframe())))\n\ndef find_packages():\n modules = []\n for dirpath, _, filenames in os.walk(\n os.path.join(SETUP_DIRECTORY, \"lazylyst\")):\n if \"__init__.py\" in filenames:\n modules.append(os.path.relpath(dirpath, SETUP_DIRECTORY))\n return [_i.replace(os.sep, \".\") for _i in modules]\n\nsetup(\n name = 'lazylyst',\n version = '0.4.6',\n description = 'GUI for timeseries review with a focus on seismology',\n author = 'Andrew Reynen',\n author_email = 'andrew.m.g.reynen@gmail.com',\n url = 'https://github.com/AndrewReynen/Lazylyst', \n download_url = 'https://github.com/AndrewReynen/Lazylyst/archive/0.4.6.tar.gz', \n keywords = ['seismology', 'timeseries', 'picking', 'pyqtgraph'], \n classifiers = [],\n packages=find_packages(),\n install_requires=[\n 'obspy>=1.0.2',\n 'pyqtgraph==0.10.0',\n 'scandir>=1.4',\n 'pyproj>=1.9.5.1',\n 'scipy',\n 'numpy'\n ],\n)\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1074,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"245754417","text":"def tripletExists(lst):\n n = len(lst)\n if n < 3:\n return False\n lst.sort()\n for i in range(n):\n lst[i] = lst[i]**2\n lo, mi, hi = 0, n - 2, n - 1\n while hi > 0:\n while lo < mi:\n a, b, c = lst[lo], lst[mi], lst[hi]\n currSum = a + b\n if currSum == c:\n return True\n if currSum < c:\n lo += 1\n else:\n mi -= 1\n hi -= 1\n lo, mi = 0, hi - 1\n return False\n \n\n\ndef main():\n lst1 = [3, 1, 4, 6, 5, 7]\n lst2 = [10, 4, 6, 12, 5]\n print(tripletExists(lst1))\n print(tripletExists(lst2))\n\nmain()","sub_path":"other/gfg/arrays/pythagorean.py","file_name":"pythagorean.py","file_ext":"py","file_size_in_byte":657,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"291946228","text":"from Tetris.settings import *\n\ndef addToBoard(board, piece):\n # fill in the board based on piece's location, shape, and rotation\n for x in range(TEMPLATEWIDTH):\n for y in range(TEMPLATEHEIGHT):\n if PIECES[piece['shape']][piece['rotation']][y][x] != BLANK:\n board[x + piece['x']][y + piece['y']] = piece['color']\n\n\ndef getBlankBoard():\n # create and return a new blank board data structure\n board = []\n for i in range(BOARDWIDTH):\n board.append([BLANK] * BOARDHEIGHT)\n return board\n\n\ndef isOnBoard(x, y):\n return x >= 0 and x < BOARDWIDTH and y < BOARDHEIGHT\n\n\ndef isValidPosition(board, piece, adjX=0, adjY=0):\n # Return True if the piece is within the board and not colliding\n for x in range(TEMPLATEWIDTH):\n for y in range(TEMPLATEHEIGHT):\n isAboveBoard = y + piece['y'] + adjY < 0\n if isAboveBoard or PIECES[piece['shape']][piece['rotation']][y][x] == BLANK:\n continue\n if not isOnBoard(x + piece['x'] + adjX, y + piece['y'] + adjY):\n return False\n if board[x + piece['x'] + adjX][y + piece['y'] + adjY] != BLANK:\n return False\n return True\n\ndef isCompleteLine(board, y):\n # Return True if the line filled with boxes with no gaps.\n for x in range(BOARDWIDTH):\n if board[x][y] == BLANK:\n return False\n return True\n\n\ndef removeCompleteLines(board):\n # Remove any completed lines on the board, move everything above them down, and return the number of complete lines.\n numLinesRemoved = 0\n y = BOARDHEIGHT - 1 # start y at the bottom of the board\n while y >= 0:\n if isCompleteLine(board, y):\n # Remove the line and pull boxes down by one line.\n for pullDownY in range(y, 0, -1):\n for x in range(BOARDWIDTH):\n board[x][pullDownY] = board[x][pullDownY-1]\n # Set very top line to blank.\n for x in range(BOARDWIDTH):\n board[x][0] = BLANK\n numLinesRemoved += 1\n # Note on the next iteration of the loop, y is the same.\n # This is so that if the line that was pulled down is also\n # complete, it will be removed.\n else:\n y -= 1 # move on to check next row up\n return numLinesRemoved\n\n\ndef convertToPixelCoords(boxx, boxy):\n # Convert the given xy coordinates of the board to xy\n # coordinates of the location on the screen.\n return (XMARGIN + (boxx * BOXSIZE)), (TOPMARGIN + (boxy * BOXSIZE))\n\n","sub_path":"Tetris/board_logic.py","file_name":"board_logic.py","file_ext":"py","file_size_in_byte":2568,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"542923615","text":"'''\nGiven a sorted array and a target value, return the index if the target is found.\nIf not, return the index where it would be if it were inserted in order.\n\nYou may assume no duplicates in the array.\n'''\n\n\nclass Solution:\n\tdef searchInsert(self, nums, target):\n\t\t\"\"\"\n\t\t:type nums: List[int]\n\t\t:type target: int\n\t\t:rtype: int\n\t\t\"\"\"\n\t\tsize = len(nums)\n\t\ti = 0\n\t\tj = size - 1\n\t\twhile i <= j:\n\t\t\tmid = (i + j) // 2\n\t\t\tif target == nums[mid]:\n\t\t\t\treturn mid\n\t\t\telif target < nums[mid]:\n\t\t\t\tj = mid - 1\n\t\t\telse:\n\t\t\t\ti = mid + 1\n\t\treturn j + 1 if j + 1 == i else i\n","sub_path":"LinearStructure/search insert posotion.py","file_name":"search insert posotion.py","file_ext":"py","file_size_in_byte":561,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"11634293","text":"# encoding:utf-8\n'''\n@Author: catnlp\n@Email: wk_nlp@163.com\n@Time: 2018/6/14 12:57\n'''\nimport os\n\neval_path = '.'\neval_script = os.path.join(eval_path, \"conlleval\")\noutput_path = 'data/label/intelligence/all/decode_crf_raw_all_bio.txt'\n\nos.system(\"%s < %s\" % (eval_script, output_path))","sub_path":"eval.py","file_name":"eval.py","file_ext":"py","file_size_in_byte":286,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"16265718","text":"# Create a route called /scrape that will import python file\n# Referenced 12.3 activity #9 heavily\n# flask_pymongo lets us search for elements with integrations and helpers. \n\nfrom flask import Flask, render_template, redirect\nfrom flask_pymongo import pyMongo\n# import our mars_scrape.py file\nimport mars_scrape\n\napp = Flask(__name__)\n\n# Use PyMongo to establish Mongo connection using database name\n# Inline syntax\nmongo = PyMongo(app, uri=\"mongodb://localhost:27017/mars_db\")\n\n# Root Route to render index.html template\n@app.route(\"/\")\ndef index():\n # Find one record of data from the mongo database\n # This finds a collection from our database and renders the template\n # The render_template function looks for templates folder with our app.py file\n mars = mongo.db.mars.find_one()\n # Render template and data\n return render_template(\"index.html\", mars=mars)\n\n# Create /scrape route\n# Scrapper calles the functions below\n@app.route(\"/scrape\")\ndef scrape():\n\n mars = mongo.db.mars\n mars_data = scrape_mars.scrape_all()\n # The update function updates everything for data that it finds--and upsert will not add it again if it already exists\n mars.update({}, mars_data, upsert=True)\n return \"Yay Scraping successful!\"\n\n\nif __name__ == \"__main__\":\n app.run(debug=True)","sub_path":"templates/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1303,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"259209207","text":"import os\nfrom polib import pofile\nfrom tools import conf, get_locale_path, remove_pyc_files\nfrom tools.report import ReleaseCount, ReleaseInfo, CountType, parts, MsgIds, count_pos\nfrom command import Command\nfrom collections import OrderedDict\nimport csv\n\n\nclass CreateReport(Command):\n\n def __init__(self):\n super().__init__()\n\n @staticmethod\n def count_file(pf, translated=False):\n msgids = [entry.msgid for entry in (pf if not translated else pf.translated_entries())]\n words = ' '.join(msgids).split()\n return CountType(len(msgids), len(words))\n\n def execute(self):\n os.chdir(conf['backend']['path'])\n results = OrderedDict()\n locale_path = get_locale_path('de')\n releases = sorted(conf['release']['enable'])\n for i, r in enumerate(releases):\n remove_pyc_files()\n self.update_backend(conf['release']['available'][r])\n msgids, counts = [], []\n for part in parts:\n if part == \"pos\":\n nums, ids = count_pos()\n msgids.append(ids)\n counts.append(nums)\n else:\n po_part = pofile(os.path.join(locale_path, part+'.po'))\n msgids.append(set([entry.msgid for entry in po_part]))\n counts.append(self.count_file(po_part))\n msgids = MsgIds(*msgids)\n results[r] = ReleaseInfo(r, ReleaseCount(*counts), msgids)\n\n csv_stat_results = []\n for r in results.values():\n print(\"*\"*3, \"release = {}\".format(r.name), \"*\"*3)\n common_words, common_lines, common_django_words, common_django_lines = 0, 0, 0, 0\n for field in r.count._fields:\n nums = r.count.__getattribute__(field)\n common_words += nums.words\n common_lines += nums.lines\n if field.startswith('django'):\n common_django_lines += nums.lines\n common_django_words += nums.words\n print(\"{} = {} / {}\".format(field, *nums))\n\n csv_stat_results.append({'release': r.name,\n 'p_lines': r.count.pos.lines,\n 'p_words': r.count.pos.words,\n 't_lines': common_lines,\n 't_words': common_words,\n 'd_lines': common_django_lines,\n 'd_words': common_django_words\n })\n\n print(\"common_django = {} / {}\".format(common_django_lines, common_django_words))\n print(\"common = {} / {}\\n\".format(common_lines, common_words))\n\n changes = OrderedDict()\n for i, r in enumerate(releases[2:], 2):\n prev_info = results[releases[i-1]]\n cur_info = results[r]\n res_parts = []\n for part in parts:\n line_diff = cur_info.msgids.__getattribute__(part) - prev_info.msgids.__getattribute__(part)\n res_parts.append(line_diff)\n changes[r] = ReleaseCount(*[CountType(len(count), len(' '.join(count).split())) for count in res_parts])\n\n prev_info = results[releases[-1]]\n cur_info = results[releases[0]]\n res_parts = []\n for part in parts:\n line_diff = cur_info.msgids.__getattribute__(part) - prev_info.msgids.__getattribute__(part)\n res_parts.append(line_diff)\n changes[cur_info.name] = ReleaseCount(*[CountType(len(count), len(' '.join(count).split())) for count in res_parts])\n\n csv_changes_results = []\n print(\"-\"*5, \"Changes Lines\", \"-\"*5, '\\n')\n for name, r in changes.items():\n common_django_words, common_django_lines = 0, 0\n print(\"*\"*3, \"release = {}\".format(name), \"*\"*3)\n for field in r._fields:\n nums = r.__getattribute__(field)\n if field.startswith('django'):\n common_django_lines += nums.lines\n common_django_words += nums.words\n print(\"{} = {:+d} / {:+d}\".format(field, *nums))\n csv_changes_results.append({\n 'release': name,\n 'n_lines': r.django.lines + r.djangojs.lines + r.pos.lines,\n 'n_words': r.django.words + r.djangojs.words + r.pos.words\n })\n print(\"common_django = {:+d} / {:+d}\\n\".format(common_django_lines, common_django_words))\n\n os.chdir(os.path.dirname(__file__))\n\n with open(\"release_stats.csv\", 'w') as f:\n fields = ['release', 'd_lines', 'd_words', 'p_lines', 'p_words', 't_lines', 't_words']\n writer = csv.DictWriter(f, fields)\n writer.writeheader()\n writer.writerows(csv_stat_results)\n\n with open('release_changes_stats.csv', 'w') as f:\n fields = ['release', 'n_lines', 'n_words']\n writer = csv.DictWriter(f, fields)\n writer.writeheader()\n writer.writerows(csv_changes_results)\n\n\nif __name__ == \"__main__\":\n cmd = CreateReport()\n cmd.execute()\n","sub_path":"reports/report_common_stat.py","file_name":"report_common_stat.py","file_ext":"py","file_size_in_byte":5092,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"470043954","text":"import csv\nimport pandas as pd\nimport logging\nfrom county_code_conversion import ocd_to_name\n\ndef printData(data):\n for county,races in data.items():\n print(county+\":\")\n for race,parties in races.items():\n print(\" \"+race+\":\")\n for party,votes in parties.items():\n print(\" \" + party + \": \"+votes)\n\ndef openCSV(date_string):\n logging.log(0,\"Opening data file for: \" + date_string)\n with open('data//'+date_string+'__fl__general__county__raw.csv', mode='r') as csv_file:\n csv_reader = csv.DictReader(csv_file)\n data = {}\n for row in csv_reader:\n division = row[\"division\"]\n office = row[\"office\"]\n party = row[\"party\"]\n votes = row[\"votes\"]\n if division not in data:\n data[division] = dict()\n if office not in data[division]:\n data[division][office] = dict()\n\n data[division][office][party] = votes\n logging.log(0,str(len(data))+\" counties read!\")\n return data\n\ndef parse():\n race = 'President of the United States'\n race_dates = [\"20161108\",\"20121106\"]\n\n data = dict()\n for date in race_dates:\n data[date] = openCSV(date)\n\n lean = dict()\n\n for year,year_data in data.items():\n for county,races in year_data.items():\n #print(county+\":\")\n if county not in lean:\n lean[county] = dict()\n parties = races[race]\n #print(\" \"+race+\":\")\n vote_sum = 0\n for party,votes in parties.items():\n vote_sum += int(votes)\n #print(\" \" + party + \": \"+votes)\n #print(\" Total Votes: \" + str(vote_sum))\n votes_r = int(parties[\"Republican\"])\n votes_d = int(parties[\"Democrat\"])\n votes_diff = ((votes_r-votes_d)/vote_sum)*100\n lean[county][year]=votes_diff\n #print(\" R-D Point Difference: %.2f\" % votes_diff+\"%\")\n \n for key in lean.keys():\n lean[key]['id'] = key\n lean[key]['name'] = ocd_to_name(key)\n print(lean[key])\n\n return lean","sub_path":"results/parse.py","file_name":"parse.py","file_ext":"py","file_size_in_byte":2235,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"228988110","text":"import yt\nfrom yt import derived_field\nimport numpy as np\nfrom numpy.linalg import inv\nimport time\nimport os\nimport matplotlib\nmatplotlib.use('Agg')\nimport matplotlib.pyplot as plt\nfrom numpy import pi\nyt.enable_parallelism()\n\n# ==============================================================================\n#\t\t\tSpherical Horizon finder\n#\n# Assumes (Obviously) spherical symmetry !! Gives bad results if not !\n# Input = Black hole center\n#\n# For valid calculation of Mass one has to slice along x-Axis !!\n# Output :-Black Hole mass (with Error estimate)\n# -Black Hole radius (with Error estimate)\n# ==============================================================================\n\n#Loading dataset\nds = yt.load('../../KerrBH_*.hdf5')\n\ncenterXYZ = ds[0].domain_right_edge/2\ncenter = float(centerXYZ[0])\n\nRad = 128.\n\nNInt = 27\ncoord = np.loadtxt('PointDistFiles/lebedev/lebedev_%03d.txt'% NInt)\ntheta = coord[:,1]*pi/180; phi = coord[:,0]*pi/180 + pi\nw = coord[:,2]\n\nNumInt = len(theta)\nprint(\"We are using\", NumInt, \" point over the sphere\")\n\n# =================================\n# INPUT #\n# =================================\nBHcenter = [center,center,center]\n# ================================\n# ================================\n\ntime_data = []\nCycleData = []\nMADM_data = []\nJ1ADM_data = []\nJ2ADM_data = []\nJ3ADM_data = []\n\n# used interpolation quality\nQuality = 'quadratic'\n\nfor i in ds:\n\n\tstart = time.time()\n\n\n\t# Gradients calculated by YT\n\n\ti.add_gradient_fields(('chombo', u'chi'))\n\ti.add_gradient_fields(('chombo', u'h11'))\n\ti.add_gradient_fields(('chombo', u'h12'))\n\ti.add_gradient_fields(('chombo', u'h13'))\n\ti.add_gradient_fields(('chombo', u'h22'))\n\ti.add_gradient_fields(('chombo', u'h23'))\n\ti.add_gradient_fields(('chombo', u'h33'))\n\n\n# ========================================================\n#\tDefinitions\n# ========================================================\n\n\n\tprint (\"Preparing calculation ... \")\n\n\tcounter = 0\n\n\tMADM = 0\n\n\tJADM = np.zeros(3)\n\tPADM = np.zeros(3)\n\n\tfor (k,x) in enumerate(phi):\n\t\tphi_var = phi[k]\n\t\ttheta_var = theta[k]\n\t\tx1 = Rad*np.cos(phi_var)*np.sin(theta_var)+float(centerXYZ[0])\n\t\ty1 = Rad*np.sin(phi_var)*np.sin(theta_var)+float(centerXYZ[1])\n\t\tz1 = Rad*np.cos(theta_var)+float(centerXYZ[2])\n\t\tptnEx = [x1,y1,z1]\n\t\tc = i.point(ptnEx)\n\n\t\tBHcenterYT = i.arr(BHcenter, \"code_length\")\n\n\n\t# Yt gives data unsorted\n\n\t\tx = np.array(c[\"x\"]- BHcenterYT[0])\n\t\ty = np.array(c[\"y\"]- BHcenterYT[1])\n\t\tz = np.array(c[\"z\"]- BHcenterYT[2])\n\n\t\tr = np.sqrt(x*x+y*y+z*z)\n\t\tsrt = np.argsort(r)\n\n\t# Importing Coordinates\n\n\t\tx = np.array(c[\"x\"][srt]- BHcenterYT[0])\n\t\ty = np.array(c[\"y\"][srt]- BHcenterYT[1])\n\t\tz = np.array(c[\"z\"][srt]- BHcenterYT[2])\n\n\t\tpos = []\n\n\t\tpos.append(x)\n\t\tpos.append(y)\n\t\tpos.append(z)\n\n\t\trho2 = x*x + y*y\n\t\trho = np.sqrt(rho2)\n\n\t\tr2 = rho2 + z*z\n\t\tr = np.sqrt(r2)\n\n\t\tcosphi = x/rho\n\t\tsinphi = y/rho\n\t\tsintheta = rho/r\n\t\tcostheta = z/r\n\n\t\tchi = np.array(c[\"chi\"][srt]);\n\t\tchi2 = chi*chi\n\n\n\t\tg11 = np.array(c[\"h11\"][srt]);\n\t\tg12 = np.array(c[\"h12\"][srt]);\n\t\tg13 = np.array(c[\"h13\"][srt]);\n\t\tg22 = np.array(c[\"h22\"][srt]);\n\t\tg23 = np.array(c[\"h23\"][srt]);\n\t\tg33 = np.array(c[\"h33\"][srt]);\n\t\n\t\n\t\tg = [[],[],[]]\n\n\t\tg[0].append(g11)\n\t\tg[0].append(g12)\n\t\tg[0].append(g13)\n\t\tg[1].append(g12)\n\t\tg[1].append(g22)\n\t\tg[1].append(g23)\n\t\tg[2].append(g13)\n\t\tg[2].append(g23)\n\t\tg[2].append(g33)\n\n\n\t\tg = np.array(g)\n\t\tgu = np.linalg.inv(g[:,:,0])\n\n\n\t\tA11 = np.array(c[\"A11\"][srt]);\n\t\tA12 = np.array(c[\"A12\"][srt]);\n\t\tA13 = np.array(c[\"A13\"][srt]);\n\t\tA22 = np.array(c[\"A22\"][srt]);\n\t\tA23 = np.array(c[\"A23\"][srt]);\n\t\tA33 = np.array(c[\"A33\"][srt]);\n\n\t\tK = np.array(c[\"K\"][srt]);\n\n\n\t\tA = [[],[],[]]\n\n\t\tA[0].append(A11)\n\t\tA[0].append(A12)\n\t\tA[0].append(A13)\n\t\tA[1].append(A12)\n\t\tA[1].append(A22)\n\t\tA[1].append(A23)\n\t\tA[2].append(A13)\n\t\tA[2].append(A23)\n\t\tA[2].append(A33)\n\n\t\tA = np.array(A)\n\n# ========================================================\n#\tDefine normal vector and invert metric\n# ========================================================\n\n\t\tN = len(chi)\n\t\ts = np.zeros([3,N])\n\n\t\tfor IND in range(N):\n\t\t\t# Definitions\n\t\t\t# ---------------------\n\t\t\ts[0,IND] = x[IND]/r[IND]\n\t\t\ts[1,IND] = y[IND]/r[IND]\n\t\t\ts[2,IND] = z[IND]/r[IND]\n\n\t\t\n\n# ========================================================\n#\tDerivatives\n# ========================================================\n\n\t\tdgdx = np.zeros([3,3,3,N])\n\t\tdchidx = np.zeros([3,N])\n\n\t\tprint (\"Calculating metric x Gradient ... \")\n\t\tdgdx[0,0,0,:] = c[\"h11_gradient_x\"][srt]\n\t\tdgdx[0,1,0,:] = c[\"h12_gradient_x\"][srt]\n\t\tdgdx[0,2,0,:] = c[\"h13_gradient_x\"][srt]\n\t\tdgdx[1,1,0,:] = c[\"h22_gradient_x\"][srt]\n\t\tdgdx[1,2,0,:] = c[\"h23_gradient_x\"][srt]\n\t\tdgdx[2,2,0,:] = c[\"h33_gradient_x\"][srt]\n\t\tdgdx[1,0,0,:] = dgdx[0,1,0,:]\n\t\tdgdx[2,0,0,:] = dgdx[0,2,0,:]\n\t\tdgdx[2,1,0,:] = dgdx[1,2,0,:]\n\n\n\t\tprint (\"Calculating metric y Gradient ... \")\n\t\tdgdx[0,0,1,:] = c[\"h11_gradient_y\"][srt]\n\t\tdgdx[0,1,1,:] = c[\"h12_gradient_y\"][srt]\n\t\tdgdx[0,2,1,:] = c[\"h13_gradient_y\"][srt]\n\t\tdgdx[1,1,1,:] = c[\"h22_gradient_y\"][srt]\n\t\tdgdx[1,2,1,:] = c[\"h23_gradient_y\"][srt]\n\t\tdgdx[2,2,1,:] = c[\"h33_gradient_y\"][srt]\n\t\tdgdx[1,0,1,:] = dgdx[0,1,1,:]\n\t\tdgdx[2,0,1,:] = dgdx[0,2,1,:]\n\t\tdgdx[2,1,1,:] = dgdx[1,2,1,:]\n\t\n\n\t\tprint (\"Calculating metric z Gradient ... \")\n\t\tdgdx[0,0,2,:] = c[\"h11_gradient_z\"][srt]\n\t\tdgdx[0,1,2,:] = c[\"h12_gradient_z\"][srt]\n\t\tdgdx[0,2,2,:] = c[\"h13_gradient_z\"][srt]\n\t\tdgdx[1,1,2,:] = c[\"h22_gradient_z\"][srt]\n\t\tdgdx[1,2,2,:] = c[\"h23_gradient_z\"][srt]\n\t\tdgdx[2,2,2,:] = c[\"h33_gradient_z\"][srt]\n\t\tdgdx[1,0,2,:] = dgdx[0,1,2,:]\n\t\tdgdx[2,0,2,:] = dgdx[0,2,2,:]\n\t\tdgdx[2,1,2,:] = dgdx[1,2,2,:]\n\t\n\n\t\tprint (\"Calculating chi Gradient ... \")\n\t\tdchidx[0,:] = c[\"chi_gradient_x\"][srt]\n\t\tdchidx[1,:] = c[\"chi_gradient_y\"][srt]\n\t\tdchidx[2,:] = c[\"chi_gradient_z\"][srt]\n\t\n# ========================================================\n#\tCalculation of Omega\n#\tEq. 7.41 in shapiro book\n# ========================================================\n\n\t\tcounter += 1. \n\t\tprint (\"Calculating MADM ... \")\n\t\tprint (\"Percentage \",counter/NumInt*100,\" %\" )\n#\t\tMADMInt = np.zeros(N)\n\t\tMADMInt = 0\n\t\tJADMInt = np.zeros(3)\n\t\tPADMInt = np.zeros(3)\n\t\tlevi = np.zeros((3,3,3))\n\t\tKtsr = np.zeros((3,3))\n\t\tdeltaij = np.zeros((3,3))\n\t\tpstn = np.zeros(3)\n\n\t\tdeltaij[0,0] = 1 \n\t\tdeltaij[1,1] = 1 \n\t\tdeltaij[2,2] = 1 \n\n\t\tlevi[0,1,2] = 1\n\t\tlevi[1,2,0] = 1\n\t\tlevi[2,0,1] = 1\n\t\tlevi[2,1,0] = -1\n\t\tlevi[1,0,2] = -1\n\t\tlevi[0,2,1] = -1\n\n\t\tpstn[0] = x\n\t\tpstn[1] = y \n\t\tpstn[2] = z \n\t\t\n\t\tfor d0 in range(3):\n\t\t\tfor d1 in range(3):\n\t\t\t\tKtsr[d0,d1] = A[d0,d1]/chi + 1./3.*g[d0,d1]*K/chi\n\t\t\t\n# ----------------------------------------------------------\n# -------------- MADM measure ------------------------------\n# ----------------------------------------------------------\n\n\t\tfor d0 in range(3):\n\t\t\tfor d1 in range(3):\n\t\t\t\tfor d2 in range(3):\n\t\t\t\t\tfor d3 in range(3):\n \t\t\t\t\t\tMADMInt += s[d0]/(16.*np.pi)*gu[d1,d3]*gu[d0,d2]*(1./np.sqrt(chi)*(dgdx[d2,d3,d1] - dgdx[d1,d3,d2]) - 1./chi**(3./2.)*(g[d2,d3]*dchidx[d1] - g[d1,d3]*dchidx[d2]))\n\t\t\n\t\t\t\t\n\t\tMADM += w[k]*MADMInt*Rad*Rad*4.0*np.pi\n\n\t\tprint(\"ADM mass = \", MADM)\n\n\n# ----------------------------------------------------------\n# -------------- JADM measure ------------------------------\n# ----------------------------------------------------------\n\t\n\t\tfor d0 in range(3):\n\t\t\tfor d1 in range(3):\n\t\t\t\tfor d2 in range(3):\n\t\t\t\t\tfor d3 in range(3):\n\t\t\t\t\t\tJADMInt[d0] += - 1./(8*np.pi)*levi[d0,d1,d2]*s[d3]*pstn[d1]*(K*deltaij[d3,d2])\n\t\t\t\t\t\t#JADMInt[d0] += + 1./(8*np.pi)*levi[d0,d1,d2]*s[d3]*pstn[d1]*(Ktsr[d3,d2]) \n\t\t\t\t\t\tfor d4 in range(3):\n\t\t\t\t\t\t\tfor d5 in range(3):\n\t\t\t\t\t\t\t\tJADMInt[d0] += + 1./(8*np.pi)*levi[d0,d1,d2]*s[d3]*pstn[d1]*(chi*chi*gu[d4,d3]*gu[d5,d2]*Ktsr[d4,d5]) \n\t\t\tJADM[d0] += JADMInt[d0]*w[k]*Rad*Rad*4.0*np.pi\n\n\tprint(\"MADM mass \", MADM, \"at time\",i.current_time)\n\n\tMADM_data.append(MADM)\n\tJ1ADM_data.append(JADM[0])\n\tJ2ADM_data.append(JADM[1])\n\tJ3ADM_data.append(JADM[2])\n\ttime_data.append(i.current_time)\t\n\tCycleData.append(time.time()-start)\n\tnp.savetxt('Cycletime.out',CycleData)\n\tnp.savetxt('time.out',time_data)\n\tnp.savetxt('MADM.out',MADM_data)\n\tnp.savetxt('J1ADM.out',J1ADM_data)\n\tnp.savetxt('J2ADM.out',J2ADM_data)\n\tnp.savetxt('J3ADM.out',J3ADM_data)\n","sub_path":"MadmMeasure/MADM.py","file_name":"MADM.py","file_ext":"py","file_size_in_byte":8187,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"591453755","text":"\"\"\"Copyright (c) 2013 Clarinova.\n\nThis file is licensed under the terms of the Revised BSD License,\nincluded in this distribution as LICENSE.txt\n\n\"\"\"\n\n# import sys\nfrom ..identity import PartitionIdentity, PartitionName\nfrom sqlite import SqlitePartition\n\n\ndef _geo_db_class(): # To break an import dependency\n\n from ambry.database.geo import GeoDb\n\n return GeoDb\n\n\nclass GeoPartitionName(PartitionName):\n PATH_EXTENSION = '.geodb'\n FORMAT = 'geo'\n\n\nclass GeoPartitionIdentity(PartitionIdentity):\n _name_class = GeoPartitionName\n\n\nclass GeoPartition(SqlitePartition):\n\n \"\"\"A Partition that hosts a Spatialite for geographic data.\"\"\"\n\n _id_class = GeoPartitionIdentity\n\n is_geo = True\n\n def __init__(self, bundle, record, **kwargs):\n super(GeoPartition, self).__init__(bundle, record)\n\n @property\n def database(self):\n if self._database is None:\n _db_class = _geo_db_class()\n self._database = _db_class(self.bundle, self, base_path=self.path)\n return self._database\n\n def _get_srs_wkt(self):\n\n #\n # !! Assumes only one layer!\n\n try:\n q = \"select srs_wkt, spatial_ref_sys.srid \" \\\n \"from geometry_columns, spatial_ref_sys \" \\\n \"where spatial_ref_sys.srid == geometry_columns.srid;\"\n return self.database.query(q).first()\n except:\n q = \"select srtext, spatial_ref_sys.srid \" \\\n \"from geometry_columns, spatial_ref_sys \" \\\n \"where spatial_ref_sys.srid == geometry_columns.srid;\"\n return self.database.query(q).first()\n\n def get_srs_wkt(self):\n r = self._get_srs_wkt()\n return r[0]\n\n def get_srid(self):\n r = self._get_srs_wkt()\n return r[1]\n\n def get_srs(self):\n import ogr\n\n srs = ogr.osr.SpatialReference()\n srs.ImportFromWkt(self.get_srs_wkt())\n return srs\n\n @property\n def srs(self):\n return self.get_srs()\n\n def get_transform(self, dest_srs=4326):\n \"\"\"Get an ogr transform object to convert from the SRS of this\n partition to another.\"\"\"\n import ogr\n import osr\n\n srs2 = ogr.osr.SpatialReference()\n srs2.ImportFromEPSG(dest_srs)\n transform = osr.CoordinateTransformation(self.get_srs(), srs2)\n\n return transform\n\n def add_tables(self, tables):\n \"\"\"Declare geometry columns to spatialite.\n\n :param tables:\n :return:\n\n \"\"\"\n\n super(GeoPartition, self).add_tables(tables)\n\n for table_name in tables:\n t = self.bundle.schema.table(table_name)\n for c in t.columns:\n if c.name == 'geometry':\n self.database.recover_geometry(\n t.name,\n c.name,\n c.datatype.upper())\n\n def convert(self, table_name, progress_f=None):\n \"\"\"Convert a spatialite geopartition to a regular arg\n by extracting the geometry and re-projecting it to WGS84\n\n # :param config: a `RunConfig` object\n :rtype: a `LibraryDb` object\n\n :param config: a `RunConfig` object\n :rtype: a `LibraryDb` object\n\n \"\"\"\n import subprocess\n import csv\n from ambry.orm import Column\n from ambry.dbexceptions import ConfigurationError\n\n #\n # Duplicate the geo arg table for the new arg\n # Then make the new arg\n #\n\n t = self.bundle.schema.add_table(table_name)\n\n ot = self.table\n\n for c in ot.columns:\n self.bundle.schema.add_column(t, c.name, datatype=c.datatype)\n\n #\n # Open a connection to spatialite and run the query to\n # extract CSV.\n #\n # It would be a lot more efficient to connect to the\n # Spatialite procss, attach the new database, the copt the\n # records in SQL.\n #\n\n try:\n subprocess.check_output('spatialite -version', shell=True)\n except:\n raise ConfigurationError(\n 'Did not find spatialite on path. Install spatialite')\n\n # Check the type of geometry:\n p = subprocess.Popen(\n ('spatialite {file} \"select GeometryType(geometry) FROM {table} LIMIT 1;\"' .format(\n file=self.database.path,\n table=self.identity.table)),\n stdout=subprocess.PIPE,\n shell=True)\n\n out, _ = p.communicate()\n out = out.strip()\n\n if out == 'POINT':\n self.bundle.schema.add_column(\n t,\n '_db_lon',\n datatype=Column.DATATYPE_REAL)\n self.bundle.schema.add_column(\n t,\n '_db_lat',\n datatype=Column.DATATYPE_REAL)\n\n command_template = \"\"\"spatialite -csv -header {file} \"select *,\n X(Transform(geometry, 4326)) AS _db_lon, Y(Transform(geometry, 4326)) AS _db_lat\n FROM {table}\" \"\"\"\n else:\n self.bundle.schema.add_column(\n t,\n '_wkb',\n datatype=Column.DATATYPE_TEXT)\n\n command_template = \"\"\"spatialite -csv -header {file} \"select *,\n AsBinary(Transform(geometry, 4326)) AS _wkb\n FROM {table}\" \"\"\"\n\n self.bundle.database.commit()\n\n pid = self.identity\n pid.table = table_name\n arg = self.bundle.partitions.new_partition(pid)\n arg.create_with_tables()\n\n #\n # Now extract the data into a new database.\n #\n\n command = command_template.format(file=self.database.path,\n table=self.identity.table)\n\n self.bundle.log(\"Running: {}\".format(command))\n\n p = subprocess.Popen(command, stdout=subprocess.PIPE, shell=True)\n stdout, stderr = p.communicate()\n\n #\n # Finally we can copy the data.\n #\n\n # local csv module shadows root #@UndefinedVariable\n rdr = csv.reader(stdout.decode('ascii').splitlines())\n # header = rdr.next()\n rdr.next()\n\n if not progress_f:\n progress_f = lambda x: x\n\n with arg.database.inserter(table_name) as ins:\n for i, line in enumerate(rdr):\n ins.insert(line)\n progress_f(i)\n\n def convert_dates(self, table_name):\n \"\"\"Remove the 'T' at the end of dates that OGR adds erroneously.\"\"\"\n from ambry.orm import Column\n\n table = self.bundle.schema.table(table_name)\n\n clauses = []\n\n for column in table.columns:\n if column.datatype == Column.DATATYPE_DATE:\n clauses.append(\n \"{col} = REPLACE({col},'T','')\".format(\n col=column.name))\n\n if clauses:\n\n self.database.connection.execute(\"UPDATE {} SET {}\".format(table.name, ','.join(clauses)))\n\n def load_shapefile(self, path, logger=None):\n \"\"\"Load a shapefile into the partition. Loads the features and inserts\n them using an inserter.\n\n :param path:\n :return:\n\n \"\"\"\n\n from osgeo import ogr # , osr\n from ..geo.sfschema import ogr_inv_type_map, mangle_name\n from ..orm import Column, Geometry\n from ..geo.util import get_type_from_geometry\n\n if path.startswith('http'):\n shape_url = path\n path = self.bundle.filesystem.download_shapefile(shape_url)\n\n driver = ogr.GetDriverByName(\"ESRI Shapefile\")\n\n dataSource = driver.Open(path, 0)\n\n layer = dataSource.GetLayer()\n\n to_srs = ogr.osr.SpatialReference()\n to_srs.ImportFromEPSG(Geometry.DEFAULT_SRS)\n\n dfn = layer.GetLayerDefn()\n\n col_defs = []\n\n for i in range(0, dfn.GetFieldCount()):\n field = dfn.GetFieldDefn(i)\n\n col_defs.append(\n (Column.mangle_name(\n mangle_name(\n field.GetName())),\n Column.types[\n ogr_inv_type_map[\n field.GetType()]][1]))\n\n col_type = None\n for c in self.table.columns:\n if c.name == 'geometry':\n col_type = c.datatype.upper()\n break\n\n assert col_type is not None\n\n with self.inserter() as ins:\n for feature in layer:\n d = {}\n for i in range(0, dfn.GetFieldCount()):\n name, type_ = col_defs[i]\n try:\n d[name] = feature.GetFieldAsString(i)\n except TypeError as e:\n self.bundle.logger.error(\n \"Type error for column '{}', type={}: {}\".format(\n name,\n type_,\n e))\n raise\n\n g = feature.GetGeometryRef()\n g.TransformTo(to_srs)\n\n type_ = get_type_from_geometry(g)\n\n if type_ != col_type:\n if type_ == 'POLYGON' and col_type == 'MULTIPOLYGON':\n g = ogr.ForceToMultiPolygon(g)\n else:\n raise Exception(\n \"Don't know how to handle this conversion case : {} -> {}\".format(type_, col_type))\n\n d['geometry'] = g.ExportToWkt()\n\n ins.insert(d)\n\n if logger:\n logger(\n \"Importing shapefile to '{}'\".format(\n self.identity.name))\n\n def __repr__(self):\n return \"\".format(self.name)\n\n @property\n def info(self):\n \"\"\"Returns a human readable string of useful information.\"\"\"\n\n try:\n srid = self.get_srid()\n except Exception as e:\n self.bundle.error(e)\n srid = 'error'\n\n return super(GeoPartition, self).info + \\\n '{:10s}: {}\\n'.format('SRID', srid)\n","sub_path":"ambry/partition/geo.py","file_name":"geo.py","file_ext":"py","file_size_in_byte":10103,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"12674375","text":"# Link to problem : https://codeforces.com/problemset/problem/948/A\n\n# There is one case in which we cannot save the sheep which is SW\n# In above case sheep and wolf are adjacent to each other and we cannot place a dog in between them\n# But in all other case we can place a dog at '.' places\n\nr,c = map(int, input().split())\ngrid = []\nfor i in range(r):\n l = list(input())\n grid.append(l)\n\ndef check(i, j, grid):\n if i > 0:\n if grid[i][j] == 'S' and grid[i - 1][j] == 'W':\n return 'NO'\n if grid[i][j] == 'S' and grid[i - 1][j] == '.':\n grid[i - 1][j] = 'D'\n if i < len(grid) - 1:\n if grid[i][j] == 'S' and grid[i + 1][j] == 'W':\n return 'NO'\n if grid[i][j] == 'S' and grid[i + 1][j] == '.':\n grid[i + 1][j] = 'D'\n if j > 0:\n if grid[i][j] == 'S' and grid[i][j - 1] == 'W':\n return 'NO'\n if grid[i][j] == 'S' and grid[i][j - 1] == '.':\n grid[i][j - 1] = 'D'\n if j < len(grid[0]) - 1:\n if grid[i][j] == 'S' and grid[i][j + 1] == 'W':\n return 'NO'\n if grid[i][j] == 'S' and grid[i][j + 1] == '.':\n grid[i][j + 1] = 'D'\n return ''\n \n\ndef main():\n for i in range(len(grid)):\n for j in range(len(grid[0])):\n if check(i, j, grid) == 'NO':\n print('No')\n return\n print('Yes')\n for i in range(len(grid)):\n print(''.join(grid[i]))\n \nif __name__ == \"__main__\":\n main()","sub_path":"graphs/protectSheep.py","file_name":"protectSheep.py","file_ext":"py","file_size_in_byte":1498,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"246213230","text":"#!/usr/bin/python3\n\na = input('Input a number: ')\ndef sum_foo(a):\n i = 0\n summa = 0\n while i < len(a):\n summa += int(a[i])\n i += 1\n return summa\nprint ('The sum of numbers of', a, ':', sum_foo(a))\n","sub_path":"nona/lessons/Python/lesson2/tvanshanneri_gumar.py","file_name":"tvanshanneri_gumar.py","file_ext":"py","file_size_in_byte":223,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"75407549","text":"#!/usr/bin/env python3\n# -*-coding: utf8-*-\nimport json\n\nfilename = 'usernamet.json'\n\ntry:\n with open(filename) as f_obj:\n username = json.load(f_obj)\nexcept FileNotFoundError:\n username = input('Please enter your name: ')\n with open(filename, 'w') as f_obj:\n json.dump(username, f_obj)\n print('we will remember you when you come back' + username)\nelse:\n print('welcome back ' + username)","sub_path":"PycharmProjects/my_practice/untitled6/5.py","file_name":"5.py","file_ext":"py","file_size_in_byte":421,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"17219963","text":"from selenium import webdriver\nfrom selenium.webdriver.support.ui import Select\nimport time\nfrom datetime import date\nimport csv\n\ndriver = webdriver.Chrome()\ndriver.implicitly_wait(30)\ndriver.maximize_window()\n\ndriver.get(\"https://www.settrade.com/member_login.jsp\")\nuser_name_field = driver.find_element_by_name(\"txtLogin\")\nuser_name_field.clear()\nuser_name_field.send_keys(\"0008174\")\npassword_field = driver.find_element_by_name(\"txtPassword\")\npassword_field.clear()\npassword_field.send_keys(\"Fpus83\")\nbroker_select = Select(driver.find_element_by_name(\"txtBrokerId\"))\nbroker_select.select_by_visible_text(\"APPLE\")\ndriver.find_element_by_class_name(\"button-login\").click()\n\n\n#Place Orders Pop-up\nwindow_before = driver.window_handles[0]\ndriver.find_element_by_link_text(\"Place Order (Pop-up)\").click()\nwindow_after = driver.window_handles[1]\ndriver.switch_to_window(window_after)\n\ntrade_size = 35000.0\ntrade_signal_folder = \"./TradeHistory/\"\nportfolio_folder = \"./Portfolio/\"\nfilename_date = str(date.today())\n\n# Check portfolio\nport_symbol_list = []\nport_dict = {}\nwith open(portfolio_folder + filename_date + \"-available.csv\") as csvfile:\n lines = csv.reader(csvfile)\n for line in lines:\n sym, available_qty = line\n port_symbol_list.append(sym)\n port_dict[sym] = available_qty\n\n# This will enter trade info\nwith open(trade_signal_folder + filename_date + \"-trade.csv\") as csvfile:\n lines = csv.reader(csvfile)\n for line in lines:\n sym, trade_side, close_price = line\n #close_price = float(close_price)\n volume_long = round((float(trade_size) / float(close_price)), -2)\n volume = int(volume_long)\n\n if trade_side == \"BUY\":\n driver.find_elements_by_css_selector(\"input[type='radio'][value='B']\")[0].click()\n if sym in port_symbol_list:\n continue\n print(\"BUY\")\n if trade_side == \"SELL\":\n driver.find_elements_by_css_selector(\"input[type='radio'][value='S']\")[0].click()\n if sym not in port_symbol_list:\n continue\n volume = port_dict[sym]\n print(\"SELL\")\n\n field_symbol = driver.find_element_by_name(\"txtSymbol\")\n field_symbol.send_keys(sym)\n field_vol = driver.find_element_by_name(\"txtQty\")\n field_vol.send_keys(volume)\n print(sym, volume)\n order_type = Select(driver.find_element_by_name(\"txtPriceType\"))\n order_type.select_by_visible_text(\"ATO\")\n field_PIN = driver.find_element_by_name(\"txtPIN_new\")\n field_PIN.send_keys(\"264954\")\n driver.find_element_by_class_name(\"submitBtn\").click()\n alert = driver.switch_to_alert()\n alert.accept()\n time.sleep(1)\n alert = driver.switch_to_alert()\n alert.accept()\n time.sleep(1)\n\n\n\ndriver.close() # Close Send order window\ndriver.switch_to_window(window_before)\ndriver.close() # Close settrade window\n\n","sub_path":"send_orders.py","file_name":"send_orders.py","file_ext":"py","file_size_in_byte":2940,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"129605403","text":"from keras.models import load_model\nfrom keras.layers import Dense, Dropout, Activation, Flatten\nimport numpy as np\nfrom keras.callbacks import TensorBoard\nfrom keras import optimizers\nepochs = 10\nbatch = 32\nsavepath = '/Users/Tay/Desktop/models/'\n# modelname = 'FT-classifier-V8'\nmodelname = 'FT-classifier-allSyn-V1'\n\n#V1: fine-tune all\n#V4: only fine-tune the last layer\n#V5: only fine-tune the classifier (not layer 1-4)\n#V6: only fine-tune the last layer; larger learning rate\n#V7: only fine-tune the last layer; smaller learning rate\n#V8: only fine-tune the last layer; smaller learning rate; 20 epoch\n\n#opt = optimizers.Adam(lr=0.0007, beta_1=0.9, beta_2=0.999, epsilon=1e-08, decay=0.0)\nopt = optimizers.Adam(lr=0.001, beta_1=0.9, beta_2=0.999, epsilon=1e-08, decay=0.0)\n\nmodel = load_model('/Users/Tay/Desktop/models/exclude236-V1.h5')\n#model = load_model('/Users/Tay/Desktop/tmp/exclude236-V1.h5')\n\n# remove the last dense classifier (class x 7)\nmodel.pop()\nmodel.pop()\nmodel.outputs = [model.layers[-1].output]\nmodel.layers[-1].outbound_nodes = []\n\n# add a new dense classifier (class x 10)\nmodel.add(Dropout(0.5, name='dropout_2'))\nmodel.add(Dense(10, activation='softmax', name='dense_2'))\n\nmodel.compile(loss='categorical_crossentropy', optimizer=opt, metrics=['accuracy'])\n\n# small amount of data for training classifier\nlogdir = savepath + modelname\ntensorboard = TensorBoard(log_dir=logdir, histogram_freq=0, batch_size=batch,\n write_graph=True, write_grads=False, write_images=False,\n embeddings_freq=0, embeddings_layer_names=None, embeddings_metadata=None)\n\n# Train only feature extractor (class = 7)\nXTrain = np.load(\"XTrain_classify.npy\")\nYTrain = np.load(\"YTrain_classify.npy\")\n# XTrain = np.load(\"XTrain_allSyn.npy\")\n# YTrain = np.load(\"YTrain_allSyn.npy\")\n\nXTest = np.load(\"XTest.npy\")\nYTest = np.load(\"YTest.npy\")\n\n# freeze feature layer\nmodel.layers[0].trainable = False\nmodel.layers[1].trainable = False\nmodel.layers[2].trainable = False\nmodel.layers[3].trainable = False\nmodel.layers[4].trainable = False\nmodel.layers[5].trainable = False\n\nmodel.fit(XTrain, YTrain, batch_size=batch, nb_epoch=epochs, verbose=1,\n validation_data=(XTest, YTest),\n callbacks=[tensorboard])\n\n# Save model\nprint(\"Saving model...\")\nmodel.save(logdir + '.h5')\n","sub_path":"transfer2.py","file_name":"transfer2.py","file_ext":"py","file_size_in_byte":2334,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"212624859","text":"import random\nimport time\nimport math\n\nimport Timer\n\nclass Sample(object):\n def __init__(self):\n self.data = random.random()\n\ndef doSomething(sample):\n sample.data *= math.sqrt(sample.data)\n\nrandom.seed(time.time())\n\ntimer = Timer.Timer()\n\nsamples = [Sample() for i in range(8000000)]\ntimer.start_interval(\"Loop\")\nfor sample in samples:\n doSomething(sample)\ntimer.stop_interval(\"Loop\")\n\ntimer.start_interval(\"Map\")\nmap(doSomething, samples)\ntimer.stop_interval(\"Map\")\n","sub_path":"perf/test_mapVSloop.py","file_name":"test_mapVSloop.py","file_ext":"py","file_size_in_byte":484,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"291510334","text":"from django.test import TestCase, Client, override_settings\nfrom django.core.urlresolvers import reverse\nfrom django.contrib.auth.models import User\nfrom destination_dog.models import UserProfile, Service\nfrom django.contrib.auth.hashers import make_password\n\n\n@override_settings(SECURE_SSL_REDIRECT=False)\nclass TestService(TestCase):\n\n def setUp(self):\n # Create a test user\n self.user = User.objects.create(username=\"user\")\n self.user.first_name = \"User\"\n self.user.last.name = \"Test\"\n self.user.password = make_password(\"password\")\n\n # Create a test user profile\n self.user.userprofile = UserProfile(user=self.user)\n self.user.userprofile.save()\n self.user.save()\n\n # Create a service\n user = User.objects.get(username='Anne')\n userprofile = user.userprofile\n\n service = Service.objects.get_or_create(serType='Vets', name='SuperVet', location='Glasgow', mondayTimes='9 to 5',\n tuesdayTimes='9 to 5', wednesdayTimes='9 to 5', thursdayTimes='9 to 5',\n fridayTimes='9 to 5', saturdayTimes='9 to 5', sundayTimes='9 to 5',\n contact = '01410000000', email='destinationdog@email.com',\n description='Best vets', ratings= 3, provider=userprofile, slug='supervet')\n service.save()\n self.client = Client()\n\n def test_get_service(self, name):\n \"\"\"\n Check that service exists\n \"\"\"\n try:\n service = Service.objects.get(name=name)\n except Service.DoesNotExist:\n service = None\n return service\n\n def test_service_with_name(self):\n \"\"\"\n Check that there is a service called Vets\n \"\"\"\n service = self.get_service('Vets')\n self.assertIsNotNone(service)\n\n def test_does_service_slug_work(self):\n service = Service(name='Super Vet')\n service.save()\n self.assertEqual(service.slug, 'super-vet')\n\n def test_locate_service_using_template(self):\n \"\"\"\n Check the template used to render locate services page\n \"\"\"\n response = self.client.get(reverse('locateservice'))\n self.assertTemplateUsed(response, 'destination_dog/locateservice.html')\n\n def test_show_service_using_template(self):\n \"\"\"\n Check the template used to render show service page\n \"\"\"\n response = self.client.get(reverse('service'))\n self.assertTemplateUsed(response, 'destination_dog/service.html')\n\n","sub_path":"destination_dog/tests/test_service.py","file_name":"test_service.py","file_ext":"py","file_size_in_byte":2644,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"330774475","text":"# coding: utf-8\n\nfrom django.contrib.auth.decorators import login_required\nfrom django.core.urlresolvers import reverse\nfrom django.http import JsonResponse\nfrom django.middleware.csrf import get_token\nfrom django.shortcuts import get_object_or_404, render\nfrom django.utils.decorators import method_decorator\nfrom django.views.generic import TemplateView, View\n\nfrom rls.forms import ReleaseUploadForm\nfrom rls.models import Release\nfrom rls.utils import hash_file\n\n\n@method_decorator(login_required, name='dispatch')\nclass Latest(TemplateView):\n template_name = 'rls/latest.html'\n\n def get_context_data(self, **kwargs):\n context = super().get_context_data(**kwargs)\n context.update({\n 'rlscloud_options': {\n 'active': 'rls-latest',\n },\n 'releases': Release.objects.all(),\n })\n return context\n\n\n@method_decorator(login_required, name='dispatch')\nclass Details(TemplateView):\n template_name = 'rls/details.html'\n\n def get_context_data(self, **kwargs):\n rls_id = kwargs['rls_id']\n\n release = get_object_or_404(Release, id=rls_id)\n context = super().get_context_data(**kwargs)\n\n context['release'] = release\n\n return context\n\n\n@method_decorator(login_required, name='dispatch')\nclass Upload(View):\n def get(self, request):\n ctx = {\n 'rlscloud_options': {\n 'csrf_token': get_token(request)\n },\n 'rlscloud_urls': {\n 'upload': reverse('rls:upload')\n }\n }\n return render(request, 'rls/upload.html', ctx)\n\n def post(self, request):\n form = ReleaseUploadForm(request.POST, request.FILES, created_by=request.user)\n\n if form.is_valid():\n form.save()\n return JsonResponse({\n 'url': reverse('rls:details', args=[form.instance.pk])\n })\n else:\n return JsonResponse(form.errors, status=400)\n","sub_path":"rls/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1980,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"166573085","text":"#\n#\n#\n#\n#\n#\n#\n#\n#\n#\n#\n#\n#\n#\n#\n#\n#\n# Don't touch this file.\n# OCP is deprecated as of this release (0.1.0).\n# It is replaced by ndio.remote.neurodata\n#\n#\n#\n#\n#\n#\n#\n#\n#\n#\n#\n#\n#\n#\n#\n#\n#\n#\n#\n\nfrom __future__ import absolute_import\nimport requests\nimport h5py\nimport os\nimport numpy\ntry:\n from io import StringIO\nexcept ImportError:\n from cStringIO import StringIO\nimport zlib\nimport tempfile\n\nfrom .Remote import Remote\nfrom .errors import *\nimport ndio.ramon as ramon\nfrom six.moves import range\n\nDEFAULT_HOSTNAME = \"openconnecto.me\"\nDEFAULT_PROTOCOL = \"http\"\n\n\nclass OCP(Remote):\n\n # SECTION:\n # Enumerables\n\n IMAGE = IMG = 'image'\n ANNOTATION = ANNO = 'annotation'\n\n def __init__(self, hostname=DEFAULT_HOSTNAME, protocol=DEFAULT_PROTOCOL):\n super(OCP, self).__init__(hostname, protocol)\n print(\"ndio.remote.OCP will be deprecated in a future release. \" +\n \"Instead, use ndio.remote.neurodata.\")\n\n def ping(self):\n return super(OCP, self).ping('public_tokens/')\n\n def url(self, suffix=\"\"):\n return super(OCP, self).url('/ocp/ca/' + suffix)\n\n def __repr__(self):\n \"\"\"\n Returns a string representation that can be used to reproduce this\n instance. `eval(repr(this))` should return an identical copy.\n\n Arguments:\n None\n\n Returns:\n str: Representation of reproducible instance.\n \"\"\"\n return \"ndio.remote.OCP('{}', '{}')\".format(\n self.hostname,\n self.protocol\n )\n\n # SECTION:\n # Metadata\n\n def get_public_tokens(self):\n \"\"\"\n Get a list of public tokens available on this server.\n\n Arguments:\n None\n\n Returns:\n str[]: list of public tokens\n \"\"\"\n r = requests.get(self.url() + \"public_tokens/\")\n return r.json()\n\n def get_public_datasets(self):\n \"\"\"\n NOTE: VERY SLOW!\n Gets a list of public datasets. Different than public tokens!\n\n Arguments:\n None\n\n Returns:\n str[]: list of public datasets\n \"\"\"\n return list(self.get_public_datasets_and_tokens().keys())\n\n def get_public_datasets_and_tokens(self):\n \"\"\"\n NOTE: VERY SLOW!\n Gets a dictionary relating key:dataset to value:[tokens] that rely\n on that dataset.\n\n Arguments:\n None\n\n Returns:\n dict: relating key:dataset to value:[tokens]\n \"\"\"\n datasets = {}\n tokens = self.get_public_tokens()\n for t in tokens:\n dataset = self.get_token_dataset(t)\n if dataset in datasets:\n datasets[dataset].append(t)\n else:\n datasets[dataset] = [t]\n return datasets\n\n def get_token_dataset(self, token):\n \"\"\"\n Get the dataset for a given token.\n\n Arguments:\n token (str): The token to inspect\n\n Returns:\n str: The name of the dataset\n \"\"\"\n return self.get_proj_info(token)['dataset']['description']\n\n def get_proj_info(self, token):\n \"\"\"\n Returns the project info for a given token.\n\n Arguments:\n token (str): Token to return information for\n\n Returns:\n JSON: representation of proj_info\n \"\"\"\n r = requests.get(self.url() + \"{}/info/\".format(token))\n return r.json()\n\n def get_token_info(self, token):\n \"\"\"\n An alias for get_proj_info.\n \"\"\"\n return self.get_proj_info(token)\n\n def get_channels(self, token):\n \"\"\"\n Wraps get_proj_info to return a dictionary of just the channels of\n a given project.\n\n Arguments:\n token (str): Token to return channels for\n\n Returns:\n JSON: dictionary of channels.\n \"\"\"\n return self.get_proj_info(token)['channels']\n\n def get_image_size(self, token, resolution=0):\n \"\"\"\n Returns the size of the volume (3D). Convenient for when you want\n to download the entirety of a dataset.\n\n Arguments:\n token (str): The token for which to find the dataset image bounds\n resolution (int : 0): The resolution at which to get image bounds.\n Defaults to 0, to get the largest area available.\n\n Returns:\n int[3]: The size of the bounds. Should == get_volume.shape\n\n Raises:\n RemoteDataNotFoundError: If the token is invalid, or if the\n metadata at that resolution is unavailable in projinfo.\n \"\"\"\n info = self.get_token_info(token)\n res = str(resolution)\n if res not in info['dataset']['imagesize']:\n raise RemoteDataNotFoundError(\"Resolution \" + res +\n \" is not available.\")\n return info['dataset']['imagesize'][str(resolution)]\n\n def get_image_offset(self, token, resolution=0):\n \"\"\"\n Gets the image offset for a given token at a given resolution. For\n instance, the `kasthuri11` dataset starts at (0, 0, 1), so its 1850th\n slice is slice 1850, not 1849. When downloading a full dataset, the\n result of this function should be your x/y/z starts.\n\n Arguments:\n token (str): The token to inspect\n resolution (int : 0): The resolution at which to gather the offset\n\n Returns:\n int[3]: The origin of the dataset, as a list\n \"\"\"\n info = self.get_token_info(token)\n res = str(resolution)\n if res not in info['dataset']['offset']:\n raise RemoteDataNotFoundError(\"Resolution \" + res +\n \" is not available.\")\n return info['dataset']['offset'][str(resolution)]\n\n # SECTION:\n # Data Download\n\n def get_xy_slice(self, token, channel,\n x_start, x_stop,\n y_start, y_stop,\n z_index,\n resolution=0):\n \"\"\"\n Return a binary-encoded, decompressed 2d image. You should\n specify a 'token' and 'channel' pair. For image data, users\n should use the channel 'image.'\n\n Arguments:\n token (str): Token to identify data to download\n channel (str): Channel\n resolution (int): Resolution level\n Q_start (int):` The lower bound of dimension 'Q'\n Q_stop (int): The upper bound of dimension 'Q'\n z_index (int): The z-slice to image\n\n Returns:\n str: binary image data\n \"\"\"\n im = self._get_cutout_no_chunking(token, channel, resolution,\n x_start, x_stop, y_start, y_stop,\n z_index, z_index+1)[0]\n return im\n\n def get_image(self, token, channel,\n x_start, x_stop,\n y_start, y_stop,\n z_index,\n resolution=0):\n \"\"\"\n Alias for the `get_xy_slice` function for backwards compatibility.\n \"\"\"\n return self.get_xy_slice(token, channel,\n x_start, x_stop,\n y_start, y_stop,\n z_index,\n resolution)\n\n def get_volume(self, token, channel,\n x_start, x_stop,\n y_start, y_stop,\n z_start, z_stop,\n resolution=1,\n block_size=(256, 256, 16),\n crop=False):\n \"\"\"\n Get a RAMONVolume volumetric cutout from the OCP server.\n\n Arguments:\n token (str): Token to identify data to download\n channel (str): Channel\n resolution (int): Resolution level\n Q_start (int):` The lower bound of dimension 'Q'\n Q_stop (int): The upper bound of dimension 'Q'\n block_size (int[3]): Block size of this dataset\n crop (bool): whether or not to crop the volume before returning it\n\n Returns:\n ndio.ramon.RAMONVolume: Downloaded data.\n\n Raises:\n NotImplementedError: If you try to crop... Sorry :(\n \"\"\"\n\n size = (x_stop-x_start)*(y_stop-y_start)*(z_stop-z_start)\n volume = ramon.RAMONVolume()\n volume.xyz_offset = [x_start, y_start, z_start]\n volume.resolution = resolution\n volume.cutout = self.get_cutout(token, channel, x_start, x_stop,\n y_start, y_stop, z_start, z_stop,\n resolution=resolution)\n return volume\n\n def get_cutout(self, token, channel,\n x_start, x_stop,\n y_start, y_stop,\n z_start, z_stop,\n resolution=1,\n block_size=(256, 256, 16),\n crop=False):\n \"\"\"\n Get volumetric cutout data from the OCP server.\n\n Arguments:\n token (str): Token to identify data to download\n channel (str): Channel\n resolution (int): Resolution level\n Q_start (int):` The lower bound of dimension 'Q'\n Q_stop (int): The upper bound of dimension 'Q'\n block_size (int[3]): Block size of this dataset\n crop (bool): whether or not to crop the volume before returning it\n\n Returns:\n numpy.ndarray: Downloaded data.\n\n Raises:\n NotImplementedError: If you try to crop... Sorry :(\n \"\"\"\n\n if crop is True:\n raise NotImplementedError(\"Can't handle crops yet, sorry! :(\")\n\n size = (x_stop-x_start)*(y_stop-y_start)*(z_stop-z_start)\n\n # For now, max out at 1GB\n # if size < 1E9:\n if True:\n return self._get_cutout_no_chunking(token, channel, resolution,\n x_start, x_stop,\n y_start, y_stop,\n z_start, z_stop)\n\n else:\n # Get an array-of-tuples of blocks to request.\n from ndio.utils.parallel import block_compute, snap_to_cube\n small_chunks = block_compute(x_start, x_stop,\n y_start, y_stop,\n z_start, z_stop)\n\n # Each time we download a chunk, we'll store it in\n # this, in the format (block_origin, data)\n downloaded_chunks = []\n for c in small_chunks:\n downloaded_chunks.append((\n c, self._get_cutout_no_chunking(token, channel, resolution,\n c[0][0], c[0][1],\n c[1][0], c[1][1],\n c[2][0], c[2][1])))\n\n x_bounds = snap_to_cube(x_start, x_stop,\n chunk_depth=256, q_index=0)\n y_bounds = snap_to_cube(y_start, y_stop,\n chunk_depth=256, q_index=0)\n z_bounds = snap_to_cube(z_start, z_stop,\n chunk_depth=16, q_index=1)\n\n volume = numpy.zeros((\n x_bounds[1]-x_bounds[0],\n y_bounds[1]-y_bounds[0],\n z_bounds[1]-z_bounds[0]))\n\n # TODO: Optimize.\n for chunk in downloaded_chunks:\n x_range, y_range, z_range = chunk[0]\n xi = 0\n for x in range(x_range[0], x_range[1]):\n yi = 0\n for y in range(y_range[0], y_range[1]):\n zi = 0\n for z in range(z_range[0], z_range[1]):\n volume[x-x_range[0]][y-y_range[0]][z-z_range[0]] =\\\n chunk[1][zi][xi][yi]\n zi += 1\n yi += 1\n xi += 1\n return volume\n\n def _get_cutout_no_chunking(self, token, channel, resolution,\n x_start, x_stop, y_start, y_stop,\n z_start, z_stop):\n req = requests.get(self.url() +\n \"{}/{}/hdf5/{}/{},{}/{},{}/{},{}/\".format(\n token, channel, resolution,\n x_start, x_stop,\n y_start, y_stop,\n z_start, z_stop\n ))\n if req.status_code is not 200:\n raise IOError(\"Bad server response: {}\".format(req.status_code))\n\n with tempfile.NamedTemporaryFile() as tmpfile:\n tmpfile.write(req.content)\n tmpfile.seek(0)\n h5file = h5py.File(tmpfile.name, \"r\")\n return h5file.get(channel).get('CUTOUT')[:]\n raise IOError(\"Failed to make tempfile.\")\n\n # SECTION:\n # Data Upload\n\n def post_cutout(self, token, channel,\n x_start, x_stop,\n y_start, y_stop,\n z_start, z_stop,\n data,\n dtype='',\n resolution=0,\n roll_axis=True):\n \"\"\"\n Post a cutout to the server.\n\n Arguments:\n token (str)\n channel (str)\n q_start (int)\n q_stop (int)\n data: A numpy array of data. Pass in (x, y, z)\n resolution: Default resolution of the data\n roll_axis: Default True. Pass False if you're supplying data\n in (z, x, y) order.\n dtype: Pass in datatype if you know it. Otherwise we'll\n check the projinfo.\n Returns:\n bool: True on success\n\n Raises:\n RemoteDataUploadError if there's an issue during upload.\n \"\"\"\n\n datatype = self.get_proj_info(token)['channels'][channel]['datatype']\n if data.dtype.name != datatype:\n data = data.astype(datatype)\n\n if roll_axis:\n # put the z-axis first\n data = numpy.rollaxis(data, 2)\n\n data = numpy.expand_dims(data, axis=0)\n tempfile = StringIO()\n numpy.save(tempfile, data)\n\n compressed = zlib.compress(tempfile.getvalue())\n\n url = self.url() + \"{}/{}/npz/{}/{},{}/{},{}/{},{}/\".format(\n token, channel,\n resolution,\n x_start, x_stop,\n y_start, y_stop,\n z_start, z_stop\n )\n\n req = requests.post(url, data=compressed, headers={\n 'Content-Type': 'application/octet-stream'\n })\n\n if req.status_code is not 200:\n raise RemoteDataUploadError(req.text)\n else:\n return True\n\n # SECTION:\n # RAMON Download\n\n def get_ramon_ids(self, token, channel='annotation'):\n \"\"\"\n Return a list of all IDs available for download from this token and\n channel.\n\n Arguments:\n token (str): Project to use\n channel (str): Channel to use (default 'annotation')\n Returns:\n int[]: A list of the ids of the returned RAMON objects\n Raises:\n RemoteDataNotFoundError: If the channel or token is not found\n \"\"\"\n\n req = requests.get(self.url() + \"{}/{}/query/\".format(token, channel))\n\n if req.status_code is not 200:\n raise RemoteDataNotFoundError('No query results for token {}.'\n .format(token))\n else:\n with tempfile.NamedTemporaryFile() as tmpfile:\n tmpfile.write(req.content)\n tmpfile.seek(0)\n h5file = h5py.File(tmpfile.name, \"r\")\n return [i for i in h5file['ANNOIDS']]\n raise IOError(\"Could not successfully mock HDF5 file for parsing.\")\n\n def get_ramon(self, token, channel, anno_id, resolution,\n metadata_only=False):\n \"\"\"\n Download a RAMON object by ID.\n\n Arguments:\n token (str): Project to use\n channel (str): The channel to use\n anno_id (int, str): The ID of a RAMON object to gather. Coerced str\n resolution (int): Resolution (if not working, try a higher num)\n metadata_only (bool): True = returns `get_ramon_metadata` instead\n\n Returns:\n ndio.ramon.RAMON\n\n Raises:\n RemoteDataNotFoundError: If the requested anno_id cannot be found.\n \"\"\"\n\n if metadata_only:\n return self.get_ramon_metadata(token, channel, anno_id)\n\n # Download the data itself\n req = requests.get(self.url() +\n \"{}/{}/{}/cutout/{}\".format(token, channel,\n anno_id, resolution))\n\n if req.status_code is not 200:\n raise RemoteDataNotFoundError('No data for id {}.'.format(anno_id))\n else:\n\n with tempfile.NamedTemporaryFile() as tmpfile:\n tmpfile.write(req.content)\n tmpfile.seek(0)\n h5file = h5py.File(tmpfile.name, \"r\")\n\n r = ramon.hdf5_to_ramon(h5file)\n return r\n\n def get_ramon_metadata(self, token, channel, anno_id):\n \"\"\"\n Download a RAMON object by ID. `anno_id` can be a string `\"123\"`, an\n int `123`, an array of ints `[123, 234, 345]`, an array of strings\n `[\"123\", \"234\", \"345\"]`, or a comma-separated string list\n `\"123,234,345\"`.\n\n Arguments:\n token (str): Project to use\n channel (str): The channel to use\n anno_id: An int, a str, or a list of ids to gather\n\n Returns:\n JSON. If you pass a single id in str or int, returns a single datum\n If you pass a list of int or str or a comma-separated string, will\n return a dict with keys from the list and the values are the JSON\n returned from the server.\n\n Raises:\n RemoteDataNotFoundError: If the data cannot be found on the Remote\n \"\"\"\n\n if type(anno_id) is int:\n # there's just one ID to download\n return self._get_single_ramon_metadata(token, channel,\n str(anno_id))\n elif type(anno_id) is str:\n # either \"id\" or \"id,id,id\":\n if (len(anno_id.split(',')) > 1):\n results = {}\n for i in anno_id.split(','):\n results[i] = self._get_single_ramon_metadata(\n token, channel, anno_id.strip()\n )\n return results\n else:\n # \"id\"\n return self._get_single_ramon_metadata(token, channel,\n anno_id.strip())\n elif type(anno_id) is list:\n # [id, id] or ['id', 'id']\n results = {}\n for i in anno_id:\n results[i] = self._get_single_ramon_metadata(token, channel,\n str(anno_id)\n .strip())\n return results\n\n def _get_single_ramon_metadata(self, token, channel, anno_id):\n req = requests.get(self.url() +\n \"{}/{}/{}/json/\".format(token, channel,\n anno_id))\n\n if req.status_code is not 200:\n raise RemoteDataNotFoundError('No data for id {}.'.format(anno_id))\n else:\n return req.json()\n\n # SECTION:\n # RAMON Upload\n\n def post_ramon(self, token, channel, r):\n \"\"\"\n Posts a RAMON object to the Remote.\n\n Arguments:\n token (str): Project to use\n channel (str): The channel to use\n ramon (RAMON): The annotation to upload\n\n Returns:\n bool: Success = True\n\n Throws:\n RemoteDataUploadError if something goes wrong\n \"\"\"\n\n # First, create the hdf5 file.\n filename = str(r.id) + \".hdf5\"\n ramon.ramon_to_hdf5(r)\n\n with open(filename, 'rb') as hdf5_data:\n\n req = requests.post(self.url(\"{}/{}/\"\n .format(token, channel)), headers={\n 'Content-Type': 'application/x-www-form-urlencoded'\n }, data=hdf5_data)\n if req.status_code is not 200:\n raise RemoteDataUploadError(req + \" \" + req.text)\n else:\n return True\n\n # SECTION:\n # Channels\n\n def create_channel(self, token, name, channel_type, dtype, readonly):\n \"\"\"\n Create a new channel on the Remote, using channel_data.\n\n Arguments:\n token (str): The token the new channel should be added to\n name (str): The name of the channel to add\n type (str): Type of the channel to add (e.g. OCP.IMAGE)\n dtype (str): The datatype of the channel's data (e.g. 'uint8')\n readonly (bool): Can others write to this channel?\n\n Returns:\n bool: True if successful, False otherwise.\n\n Raises:\n ValueError: If your args were bad :(\n RemoteDataUploadError: If the channel data is valid but upload\n fails for some other reason.\n \"\"\"\n\n for c in name:\n if not c.isalnum():\n raise ValueError(\"Name cannot contain character {}.\".format(c))\n\n if channel_type not in ['image', 'annotation']:\n raise ValueError('Type must be OCP.IMAGE or OCP.ANNOTATION.')\n\n if readonly * 1 not in [0, 1]:\n raise ValueError(\"readonly must be 0 (False) or 1 (True).\")\n\n # Good job! You supplied very nice arguments.\n req = requests.post(self.url(\"{}/createChannel/\".format(token)), json={\n \"channels\": {\n name: {\n \"channel_name\": name,\n \"channel_type\": channel_type,\n \"datatype\": dtype,\n \"readonly\": readonly * 1\n }\n }\n })\n\n if req.status_code is not 200:\n raise RemoteDataUploadError('Could not upload {}'.format(req.text))\n else:\n return True\n\n def delete_channel(self, token, name):\n \"\"\"\n Delete an existing channel on the Remote. Be careful!\n\n Arguments:\n token (str): The token the new channel should be deleted from\n name (str): The name of the channel to delete\n\n Returns:\n bool: True if successful, False otherwise.\n\n Raises:\n RemoteDataUploadError: If the upload fails for some reason.\n \"\"\"\n\n req = requests.post(self.url(\"{}/deleteChannel/\".format(token)), json={\n \"channels\": [name]\n })\n\n if req.status_code is not 200:\n raise RemoteDataUploadError('Could not delete {}'.format(req.text))\n else:\n return True\n","sub_path":"ndio/remote/OCP.py","file_name":"OCP.py","file_ext":"py","file_size_in_byte":23278,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"98100395","text":"# -*- coding: utf-8 -*-\nfrom datetime import datetime\nfrom decimal import Decimal\nimport unittest\nimport os\nfrom qifparse.parser import QifParser\n\nfilename = os.path.join(os.path.dirname(__file__), 'file.qif')\nfilename2 = os.path.join(os.path.dirname(__file__), 'transactions_only.qif')\nfilename_multi = os.path.join(os.path.dirname(__file__), 'multiAccount.qif')\nfilename_security = os.path.join(os.path.dirname(__file__), 'security.qif')\nfilename_accts = os.path.join(os.path.dirname(__file__), 'account_list.qif')\n\n\nclass TestQIFParsing(unittest.TestCase):\n\n def testParseFile(self):\n with open(filename) as f:\n QifParser.MONTH_IS_BEFORE_DAY_IN_DATES = False\n qif = QifParser.parse(f)\n self.assertTrue(qif)\n\n def testWriteFile(self):\n with open(filename) as f:\n data = f.read()\n with open(filename) as f:\n QifParser.MONTH_IS_BEFORE_DAY_IN_DATES = False\n qif = QifParser.parse(f)\n# out = open('out.qif', 'w')\n# out.write(str(qif))\n# out.close()\n self.assertEqual(data, str(qif))\n\n def testParseTransactionsFile(self):\n with open(filename2) as f:\n data = f.read()\n with open(filename2) as f:\n QifParser.MONTH_IS_BEFORE_DAY_IN_DATES = False\n qif = QifParser.parse(f)\n# out = open('out.qif', 'w')\n# out.write(str(qif))\n# out.close()\n self.assertEqual(data, str(qif))\n\n def testAccountList(self):\n with open(filename_accts) as f:\n qif = QifParser.parse(f)\n\n def testSecurities(self):\n with open(filename_security) as f:\n qif = QifParser.parse(f)\n\n def testParseMultiAccountFile(self):\n with open(filename_multi) as f:\n QifParser.MONTH_IS_BEFORE_DAY_IN_DATES = True\n qif = QifParser.parse(f)\n\n self.assertEqual(2, len(qif.get_accounts()))\n self.assertEqual('City Checking', qif.get_accounts()[0].name)\n self.assertEqual('Bank', qif.get_accounts()[0].account_type)\n self.assertEqual('Global Credit Card', qif.get_accounts()[1].name)\n self.assertEqual('CCard', qif.get_accounts()[1].account_type)\n\n city_account_list = qif.get_accounts(name='City Checking')\n self.assertEqual(1, len(city_account_list))\n city_transactions = city_account_list[0].get_transactions()[0]\n self.assertEqual(2, len(city_transactions))\n self.assert_transaction(city_transactions[0], self.to_datetime('2003-03-27'), Decimal('0.00'),\n 'X', 'Opening Balance', to_account='City Checking')\n self.assert_transaction(city_transactions[1], self.to_datetime('1992-01-02'), Decimal('123.45'),\n 'X', 'Deposit', category='Salary')\n\n credit_card_account_list = qif.get_accounts(name='Global Credit Card')\n self.assertEqual(1, len(credit_card_account_list))\n credit_transactions = credit_card_account_list[0].get_transactions()[0]\n self.assertEqual(3, len(credit_transactions))\n self.assert_transaction(credit_transactions[0], self.to_datetime('2015-06-17'), Decimal('0.00'),\n 'X', 'Opening Balance', to_account='Global Credit Card')\n self.assert_transaction(credit_transactions[1], self.to_datetime('2015-06-18'), Decimal('-1234.56'),\n '*', 'Local Store', category='Food')\n self.assert_transaction(credit_transactions[2], self.to_datetime('2015-06-19'), Decimal('1234.56'),\n '*', 'Local Store', category='Food')\n\n\n def assert_transaction(self, txn, when, amount, cleared, payee, category=None, to_account=None):\n self.assertEqual(txn.date, when)\n self.assertEqual(txn.amount, amount)\n self.assertEqual(txn.cleared, cleared)\n self.assertEqual(txn.payee, payee)\n if category:\n self.assertEqual(txn.category, category)\n if to_account:\n self.assertEqual(txn.to_account, to_account)\n\n def to_datetime(self, date_str):\n return datetime.strptime(date_str, '%Y-%m-%d')\n\nif __name__ == \"__main__\":\n import unittest\n unittest.main()\n","sub_path":"qifparse/tests/test_parse.py","file_name":"test_parse.py","file_ext":"py","file_size_in_byte":4134,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"651976296","text":"vec0 = (1, 2, 3)\nvec1 = (4, 5, 6)\n\ninnerProd = sum (e0 * e1 for e0, e1 in zip (vec0, vec1)) # What EXACTLY happens here?\n\nprint (innerProd)\n\t\n'''\ninnerProd = 0\nfor index in range (len (vec0)):\n innerProd += vec0 [index] * vec1 [index]\n'''\n","sub_path":"module_inleiding_programmeren_in_python/les_3_while_en_for/overig_lesmateriaal/real_world_code_fragments/inner_prod_comprehension.py","file_name":"inner_prod_comprehension.py","file_ext":"py","file_size_in_byte":245,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"632214817","text":"#!/usr/bin/env python\n# -*- coding:utf -*-\n\n__all__ = [\"Storepool\"]\n\nimport sqlite3\nimport threading\nimport logging\nimport os.path\n\nlog_spider = logging.getLogger(\"spider\")\n\nclass Storepool(object):\n\t\"\"\"\n\t\"\"\"\n\tdef __init__(self, db=\"spider.db\", lock=threading.RLock()):\n\t\tself.conn = sqlite3.connect(db, check_same_thread=False)\n\t\tself.lock = lock\n\t\tself.createtable()\n\n\tdef createtable(self):\n\t\twith self.conn:\n\t\t\tself.conn.executescript(\"\"\"\n\t\t\t\tcreate table if not exists tasks(\n\t\t\t\t\tid integer primary key autoincrement,\n\t\t\t\t\ttask text not null\n\t\t\t\t);\n\n\t\t\t\tcreate table if not exists keyword(\n\t\t\t\t\tid integer primary key autoincrement,\n\t\t\t\t\turl text not null,\n\t\t\t\t\tkeyword text not null default 'None'\n\t\t\t\t);\n\t\t\t\"\"\")\n\n\tdef inserttasks(self, url):\n\t\tsql = \"insert into tasks \\\n\t\t\t\t(url) values ('?');\"\n\t\tpara = (url,)\n\t\twith self.conn:\n\t\t\tself.conn.execute(sql, para)\n\n\tdef store(self, url, keyword=\"None\"):\n\t\tself.lock.acquire()\n\t\tsql = \"insert into keyword \\\n\t\t\t\t(url, keyword) values (?, ?);\"\n\t\tpara = (url, keyword)\n\t\twith self.conn:\n\t\t\tself.conn.execute(sql, para)\n\t\tlog_spider.debug(\"store data: %s\" % para)\n\t\t#print \"--------\", url, keyword\n\t\tself.lock.release()\n \n \n","sub_path":"src/dbstore.py","file_name":"dbstore.py","file_ext":"py","file_size_in_byte":1190,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"73079751","text":"#Programa que calcula el área de diversas figuras\r\ndef Areacuadrado():\r\n print('\\n\\tPara calcular el área de un Cuadrado')\r\n lado=float(input('\\n\\t\\t Medida de un lado '))\r\n area=lado*lado\r\n return area\r\ndef Areacirculo():\r\n print('\\n\\t Para calcular el área de un Círculo')\r\n radio=float(input('\\n\\t Medida del radio '))\r\n area=3.1416*radio\r\n return area\r\ndef Arearectangulo():\r\n print('\\n\\t Para calcular el área de un Rectángulo')\r\n base=float(input('\\n\\t Medida de la base '))\r\n altura=float(input('\\n\\t Medida de la altura '))\r\n area=base*altura\r\n return area\r\ndef Areatriangulo():\r\n print('\\n\\t Para calcular el área de un Triángulo')\r\n base=float(input('\\n\\t Medida de la base '))\r\n altura=float(input('\\n\\t Medida de la altura '))\r\n area=base*altura/2\r\n return area\r\ndef Arearombo():\r\n print('\\n\\t Para calcular el área de un Rombo')\r\n diagmayor=float(input('\\n\\t Medida de la diagonal mayor '))\r\n diagmenor=float(input('\\n\\t Medida de la diagonal menor '))\r\n area=diagmayor*diagmenor/2\r\n print('\\n\\t El área del Rombo es: ',area)\r\nprint('\\n PROGRAMA QUE CALCULA EL ÁREA DE FIGURAS GEOMÉTRICAS')\r\nprint('\\n\\t\\t\\t MENÚ DE FIGURAS')\r\nprint('\\n\\t\\t\\t 1. Cuadrado')\r\nprint('\\n\\t\\t\\t 2. Círculo')\r\nprint('\\n\\t\\t\\t 3. Rectángulo')\r\nprint('\\n\\t\\t\\t 4. Triángulo')\r\nprint('\\n\\t\\t\\t 5. Rombo')\r\nopcion=int(input('\\n\\t Capture la opción '))\r\nif (opcion==1):\r\n print('\\t\\t El area del cuadrado es: ',(Areacuadrado()))\r\nelif (opcion==2):\r\n print('\\n\\t\\t El área del Círculo es: ',(Areacirculo()))\r\nelif (opcion==3):\r\n print('\\n\\t\\t El área del Rectángulo es: ',(Arearectangulo()))\r\nelif (opcion==4):\r\n print('\\n\\t El área del Triángulo es: ',(Areatriangulo()))\r\nelif (opcion==5):\r\n Arearombo()\r\nelse:\r\n print('\\n\\ ERROR, NÚMERO NO VÁLIDO, SÓLO <1,2,3,4,5>')\r\n print('\\t Ejecute nuevamente el programa')\r\n\r\n\r\n","sub_path":"Funciones figuras geometricas.py","file_name":"Funciones figuras geometricas.py","file_ext":"py","file_size_in_byte":1946,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"57711594","text":"# Licensed under a 3-clause BSD style license - see LICENSE.rst\n# -*- coding: utf-8 -*-\n\"\"\"\n====================================\nprospect.scripts.specview_cmx_coadds\n====================================\n\nWrite static html files from \"coadd\" files in CMX data, sorted by exposure.\n\"\"\"\n\nimport os, sys, glob\nimport argparse\nimport numpy as np\nfrom astropy.table import Table, vstack\n\nimport desispec.io\nfrom desiutil.log import get_logger\nimport desispec.spectra\nimport desispec.frame\n\nfrom ..plotframes import plotspectra\nfrom ..myspecselect import myspecselect\nfrom ..myspecupdate import myspecupdate\nfrom ..utilities import specviewer_selection, match_redrock_zfit_to_spectra, match_zcat_to_spectra\n\n# List of bad fibers in CMX data (see eg SB / KD emails 23-24/03/2020)\n_bad_fibers_cmx = [\n [1000, 1250], # r2 amp A glowing spot CCD defect\n [2250, 2500], # r4 amp D serial register CTE problem\n [4500, 4750] # b9 amp C readout salt-and-pepper noise\n]\n\ndef _parse():\n\n parser = argparse.ArgumentParser(description='Create static html pages from CMX coadds, tile-based')\n parser.add_argument('--specprod_dir', help='Location of directory tree (data in specprod_dir/tiles/)', type=str)\n parser.add_argument('--tile', help='Name of single tile to be processed',type=str, default=None)\n parser.add_argument('--tile_list', help='ASCII file providing list of tiles', type=str, default=None)\n parser.add_argument('--night', help='Filter night to be processed (night name can also be \"deep\")',type=str, default=None)\n parser.add_argument('--night_list', help='Filter set of nights to be processed (can include night name \"deep\")', type=str, default=None)\n parser.add_argument('--nspecperfile', help='Number of spectra in each html page', type=int, default=50)\n parser.add_argument('--webdir', help='Base directory for webpages', type=str)\n parser.add_argument('--nmax_spectra', help='Stop the production of HTML pages once a given number of spectra are done', type=int, default=None)\n parser.add_argument('--mask', help='Select only objects with a given target mask', type=str, default=None)\n parser.add_argument('--mask_type', help='Target mask type', type=str, default='CMX_TARGET')\n parser.add_argument('--snrcut', help='Select only objects in a given range for MEDIAN_CALIB_SNR_B+R+Z', nargs='+', type=float, default=None)\n parser.add_argument('--with_zcatalog', help='Include redshift fit results (zbest files)', action='store_true')\n parser.add_argument('--with_multiple_models', help='Display several models (requires full redrock outputs)', action='store_true')\n parser.add_argument('--petals', help='Select only a set of petals (labelled 0 to 9)', nargs='+', type=str, default=None)\n parser.add_argument('--clean_bad_fibers_cmx', help='Remove list of known bad fibers (CMX conditions)', action='store_true')\n parser.add_argument('--template_dir', help='Redrock template directory', type=str, default=None)\n\n args = parser.parse_args()\n return args\n\n\ndef tile_db(specprod_dir, tile_subset=None, night_subset=None, petals=None, with_zcatalog=False) :\n '''\n Returns [ {tile, night, petals} for all tile/night available in specprod_dir/tiles tree ],\n with b,r,z frames whose name matches frametype\n tile_subset : list; if None, all available tiles will be included in the list\n night_subset : list; if not None, only coadds from these nights are included\n petals (list of strings) : select only data from a set of petals\n with_zcatalog : select only petals with a zbest file\n '''\n\n if petals is None : petals = [str(i) for i in range(10)]\n tiles_db = list()\n for tile in os.listdir( os.path.join(specprod_dir,'tiles') ) :\n if tile_subset is not None and tile not in tile_subset : continue\n for night in os.listdir( os.path.join(specprod_dir,'tiles',tile) ) :\n if night_subset is not None and night not in night_subset : continue\n petals_avail = []\n for petal_num in petals :\n add_petal = True\n filename = \"coadd-\"+petal_num+\"-\"+tile+\"-\"+night+\".fits\"\n if not os.path.isfile( os.path.join(specprod_dir,'tiles',tile,night,filename) ) : add_petal=False\n if with_zcatalog :\n filename = \"zbest-\"+petal_num+\"-\"+tile+\"-\"+night+\".fits\"\n if not os.path.isfile( os.path.join(specprod_dir,'tiles',tile,night,filename) ) : add_petal=False\n if add_petal :\n petals_avail.append(petal_num)\n if len(petals_avail) > 0 :\n tiles_db.append( { 'tile':tile, 'night':night, 'petals':petals_avail} )\n\n return tiles_db\n\n\ndef page_subset_tile(fdir, tile_db_subset, html_dir, titlepage_prefix, mask, log, nspecperfile, snr_cut, with_zcatalog=False, template_dir=None, clean_bad_fibers_cmx=False, with_multiple_models=False, mask_type='CMX_TARGET') :\n '''\n Running prospect from coadds.\n '''\n\n tile = tile_db_subset['tile']\n night = tile_db_subset['night']\n nspec_done = 0\n all_spectra = None\n log.info(\"Tile \"+tile+\": reading coadds from night \"+night)\n if with_multiple_models :\n rrtables = []\n\n for petal_num in tile_db_subset['petals'] :\n fname = os.path.join(fdir,\"coadd-\"+petal_num+\"-\"+tile+'-'+night+\".fits\")\n spectra = desispec.io.read_spectra(fname)\n # Filtering\n if (mask != None) or (snr_cut != None) :\n spectra = specviewer_selection(spectra, log=log,\n mask=mask, mask_type=mask_type, snr_cut=snr_cut, with_dirty_mask_merge=True)\n if spectra == 0 : continue\n # Display multiple models: requires redrock catalog\n # Hardcoded: display up to 4th best fit (=> need 5 best fits in redrock table)\n if with_multiple_models :\n fname = os.path.join(fdir,\"redrock-\"+petal_num+\"-\"+tile+'-'+night+\".h5\")\n rr_table = match_redrock_zfit_to_spectra(fname, spectra)\n rrtables.append(rr_table)\n # Merge\n if all_spectra is None :\n all_spectra = spectra\n else :\n # NB update() does not copy scores. Score-based filtering (SNR) was done before.\n all_spectra = myspecupdate(all_spectra, spectra)\n\n if all_spectra is None :\n log.info(\"Tile \"+tile+\" - night \"+night+\": no spectra.\")\n return 0\n else :\n clean_fiberstatus=True if 'FIBERSTATUS' in all_spectra.fibermap.keys() else False\n fibers = None\n if clean_bad_fibers_cmx :\n fibers = np.arange(5000)\n for cut_fiber_range in _bad_fibers_cmx :\n fibers = fibers[ ( (fibers < cut_fiber_range[0]) | (fibers > cut_fiber_range[1]) )]\n all_spectra = myspecselect(all_spectra,\n clean_fiberstatus=clean_fiberstatus, fibers=fibers, remove_scores=True)\n if all_spectra is None : return 0\n\n # zcatalog\n if with_zcatalog :\n ztables = []\n for petal_num in tile_db_subset['petals'] :\n fname = os.path.join(fdir,\"zbest-\"+petal_num+\"-\"+tile+'-'+night+\".fits\")\n ztables.append(Table.read(fname,'ZBEST'))\n zcat = vstack(ztables)\n else : zcat = None\n\n if with_multiple_models :\n rrtable = vstack(rrtables)\n num_approx_fits = 4 # TODO settle option/unhardcode\n with_full_2ndfit = True # TODO settle option/unhardcode\n else :\n rrtable = None\n num_approx_fits = None\n with_full_2ndfit = False\n\n # Create several html pages : sort by targetid\n nspec_tile = all_spectra.num_spectra()\n log.info(\"Tile \"+tile+\" - night \"+night+\": \"+str(nspec_tile)+\" exposure-coadded spectra\")\n sort_indices = np.argsort(all_spectra.fibermap[\"TARGETID\"])\n nbpages = int(np.ceil((nspec_tile/nspecperfile)))\n for i_page in range(1,1+nbpages) :\n\n log.info(\" * Page \"+str(i_page)+\" / \"+str(nbpages))\n the_indices = sort_indices[(i_page-1)*nspecperfile:i_page*nspecperfile]\n thespec = myspecselect(all_spectra, indices=the_indices, remove_scores=True)\n the_zcat, kk = match_zcat_to_spectra(zcat, thespec)\n if with_multiple_models :\n the_rrtable, kk = match_zcat_to_spectra(rrtable, thespec)\n else :\n the_rrtable = None\n\n titlepage = titlepage_prefix+\"_\"+str(i_page)\n plotspectra(thespec, with_noise=True, is_coadded=True, zcatalog=the_zcat,\n title=titlepage, html_dir=html_dir, mask_type=mask_type, with_thumb_only_page=True,\n template_dir=template_dir, redrock_cat=the_rrtable, num_approx_fits=num_approx_fits,\n with_full_2ndfit=with_full_2ndfit)\n nspec_done += nspec_tile\n\n return nspec_done\n\n\n\ndef main():\n args = _parse()\n log = get_logger()\n webdir = args.webdir\n if ( [args.tile, args.tile_list] ).count(None) != 1 :\n log.info(\"Specview_cmx_coadds: Wrong set of input tiles. Exiting\")\n return 0\n if args.night is not None and args.night_list is not None :\n log.info(\"Specview_cmx_coadds: Wrong set of input nights. Exiting\")\n return 0\n \n # Logistics : list of \"subsets\" to process\n if args.tile_list is not None :\n tile_subset = np.loadtxt(args.tile_list, dtype=str, comments='#')\n if args.tile is not None :\n tile_subset = [ args.tile ]\n if args.night is not None :\n night_subset = [ args.night ]\n elif args.night_list is not None :\n night_subset = np.loadtxt(args.night_list, dtype=str, comments='#')\n else : night_subset = None\n subset_db = tile_db(args.specprod_dir, tile_subset=tile_subset, night_subset=night_subset,\n petals=args.petals, with_zcatalog=args.with_zcatalog)\n tmplist = [ x['tile'] for x in subset_db ]\n missing_tiles = [ x for x in tile_subset if x not in tmplist ]\n for x in missing_tiles : log.info(\"Missing tile, cannot be processed: \"+x)\n log.info(str(len(subset_db))+\" tile/night subsets to be processed\")\n\n # Main loop on subsets\n nspec_done = 0\n for the_subset in subset_db :\n\n log.info(\"Working on tile \"+the_subset['tile']+\" - night \"+the_subset['night'])\n fdir = os.path.join( args.specprod_dir, 'tiles', the_subset['tile'], the_subset['night'] )\n html_dir = os.path.join(webdir,\"tiles\",the_subset['tile'],the_subset['night'])\n titlepage_prefix = \"tile\"+the_subset['tile']+\"_night\"+the_subset['night']\n if args.mask != None :\n html_dir = os.path.join(webdir, \"tiles_\"+args.mask, the_subset['tile'],the_subset['night'])\n titlepage_prefix = args.mask+\"_\"+titlepage_prefix\n if not os.path.exists(html_dir) :\n os.makedirs(html_dir)\n\n nspec_added = page_subset_tile(fdir, the_subset, html_dir, titlepage_prefix, args.mask, log, args.nspecperfile, args.snrcut, with_zcatalog=args.with_zcatalog, template_dir=args.template_dir, clean_bad_fibers_cmx=args.clean_bad_fibers_cmx, with_multiple_models=args.with_multiple_models, mask_type=args.mask_type)\n\n # Stop running if needed, only once a full exposure is completed\n nspec_done += nspec_added\n if args.nmax_spectra is not None :\n if nspec_done >= args.nmax_spectra :\n log.info(str(nspec_done)+\" spectra done: no other exposure will be processed\")\n break\n\n log.info(\"End of specview_cmx_coadds script.\")\n return 0\n","sub_path":"py/prospect/scripts/specview_cmx_coadds.py","file_name":"specview_cmx_coadds.py","file_ext":"py","file_size_in_byte":11491,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"70285874","text":"import uuid\n\nfrom django.test import TestCase, override_settings\n\nfrom django_snow.helpers import ChangeRequestHandler\nfrom django_snow.helpers.exceptions import ChangeRequestException\nfrom django_snow.models import ChangeRequest\n\n\ntry:\n from unittest import mock\nexcept ImportError:\n import mock\n\n\n@override_settings(\n SNOW_INSTANCE='devgodaddy',\n SNOW_API_USER='snow_user',\n SNOW_API_PASS='snow_pass',\n SNOW_ASSIGNMENT_GROUP='dev-networking'\n)\n@mock.patch('django_snow.helpers.snow_request_handler.pysnow')\nclass TestChangeRequestHandler(TestCase):\n\n def setUp(self):\n self.mock_pysnow_client = mock.MagicMock()\n self.change_request_handler = ChangeRequestHandler()\n\n def test__get_client(self, mock_pysnow):\n mock_pysnow.Client.return_value = self.mock_pysnow_client\n self.assertIs(\n self.mock_pysnow_client,\n self.change_request_handler._get_client()\n )\n\n def test__get_client_once_initialized_returns_same_instance(self, mock_pysnow):\n mock_pysnow.Client.return_value = self.mock_pysnow_client\n self.change_request_handler._get_client()\n self.assertIs(\n self.mock_pysnow_client,\n self.change_request_handler._get_client()\n )\n\n def test_settings_and_table_name(self, mock_pysnow):\n self.assertEqual(self.change_request_handler._client, None)\n self.assertEqual(self.change_request_handler.snow_instance, 'devgodaddy')\n self.assertEqual(self.change_request_handler.snow_api_user, 'snow_user')\n self.assertEqual(self.change_request_handler.snow_api_pass, 'snow_pass')\n self.assertEqual(self.change_request_handler.CHANGE_REQUEST_TABLE_NAME, 'change_request')\n self.assertEqual(self.change_request_handler.USER_GROUP_TABLE_NAME, 'sys_user_group')\n self.assertEqual(self.change_request_handler.snow_assignment_group, 'dev-networking')\n\n @mock.patch('django_snow.helpers.snow_request_handler.ChangeRequestHandler._get_snow_group_guid')\n def test_create_change_request(self, mock_get_snow_group_guid, mock_pysnow):\n fake_insert_retval = {\n 'sys_id': uuid.uuid4(),\n 'number': 'CHG0000001',\n 'short_description': 'bar',\n 'description': 'herp',\n 'assignment_group': {'value': uuid.uuid4()},\n 'state': '2'\n }\n self.mock_pysnow_client.insert.return_value = fake_insert_retval\n mock_pysnow.Client.return_value = self.mock_pysnow_client\n\n co = self.change_request_handler.create_change_request(\n 'title', 'description', assignment_group='assignment_group'\n )\n last_co = ChangeRequest.objects.last()\n\n mock_get_snow_group_guid.assert_called_with('assignment_group')\n self.assertEqual(co.pk, last_co.pk)\n self.assertEqual(co.sys_id, fake_insert_retval['sys_id'])\n self.assertEqual(co.number, fake_insert_retval['number'])\n self.assertEqual(co.title, fake_insert_retval['short_description'])\n self.assertEqual(co.description, fake_insert_retval['description'])\n self.assertEqual(co.assignment_group_guid, fake_insert_retval['assignment_group']['value'])\n\n @mock.patch('django_snow.helpers.snow_request_handler.ChangeRequestHandler._get_snow_group_guid')\n def test_create_change_request_raises_exception_when_error_in_result(self, mock_get_snow_group_guid, mock_pysnow):\n fake_insert_retval = {\n 'error': 'some error message'\n }\n self.mock_pysnow_client.insert.return_value = fake_insert_retval\n mock_pysnow.Client.return_value = self.mock_pysnow_client\n\n with self.assertRaises(ChangeRequestException):\n self.change_request_handler.create_change_request(\n 'title', 'description', assignment_group='assignment_group'\n )\n\n @mock.patch('django_snow.helpers.snow_request_handler.ChangeRequestHandler.update_change_request')\n def test_close_change_request(self, mock_update_request, mock_pysnow):\n mock_update_request.return_value = 'foo'\n change_request_handler = ChangeRequestHandler()\n\n change_request_handler.close_change_request('some change order')\n\n mock_update_request.assert_called_with('some change order', {'state': ChangeRequest.TICKET_STATE_COMPLETE})\n\n @mock.patch('django_snow.helpers.snow_request_handler.ChangeRequestHandler.update_change_request')\n def test_close_change_request_with_error(self, mock_update_request, mock_pysnow):\n mock_update_request.return_value = 'foo'\n change_request_handler = ChangeRequestHandler()\n payload = {'description': 'foo'}\n change_request_handler.close_change_request_with_error('some change order', payload)\n\n mock_update_request.assert_called_with(\n 'some change order', {'state': ChangeRequest.TICKET_STATE_COMPLETE_WITH_ERRORS, 'description': 'foo'}\n )\n\n def test_update_change_request(self, mock_pysnow):\n fake_query = mock.MagicMock()\n fake_change_order = mock.MagicMock()\n\n fake_query.update.return_value = {'state': ChangeRequest.TICKET_STATE_COMPLETE}\n self.mock_pysnow_client.query.return_value = fake_query\n mock_pysnow.Client.return_value = self.mock_pysnow_client\n\n ret_val = self.change_request_handler.update_change_request(fake_change_order, payload='{\"foo\": \"bar\"}')\n self.assertEqual(fake_change_order.state, ChangeRequest.TICKET_STATE_COMPLETE)\n self.assertEqual(ret_val, {'state': ChangeRequest.TICKET_STATE_COMPLETE})\n\n def test_update_change_request_raises_exception(self, mock_pysnow):\n fake_query = mock.MagicMock()\n fake_change_order = mock.MagicMock()\n\n fake_query.update.return_value = {'error': '3'}\n self.mock_pysnow_client.query.return_value = fake_query\n mock_pysnow.Client.return_value = self.mock_pysnow_client\n\n with self.assertRaises(ChangeRequestException):\n self.change_request_handler.update_change_request(fake_change_order, payload='{\"foo\": \"bar\"}')\n\n def test__get_snow_group_guid_cached_result(self, mock_pysnow):\n self.change_request_handler.group_guid_dict['foo'] = 'bar'\n self.assertEqual(self.change_request_handler._get_snow_group_guid('foo'), 'bar')\n\n def test__get_snow_group_guid(self, mock_pysnow):\n fake_query = mock.MagicMock()\n fake_query.get_one.return_value = {'sys_id': 'yo'}\n self.mock_pysnow_client.query.return_value = fake_query\n mock_pysnow.Client.return_value = self.mock_pysnow_client\n\n self.assertEqual(self.change_request_handler._get_snow_group_guid('hello'), 'yo')\n","sub_path":"testapp/tests.py","file_name":"tests.py","file_ext":"py","file_size_in_byte":6685,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"73381462","text":"import types\n\nimport blueware.packages.six as six\n\nfrom blueware.agent import (current_transaction, FunctionTrace, callable_name,\n wrap_object, wrap_in_function)\n\nclass MethodWrapper(object):\n\n def __init__(self, wrapped, priority=None):\n self._bw_name = callable_name(wrapped)\n self._bw_wrapped = wrapped\n self._bw_priority = priority\n\n def __get__(self, instance, klass):\n if instance is None:\n return self\n descriptor = self._bw_wrapped.__get__(instance, klass)\n return self.__class__(descriptor)\n\n def __getattr__(self, name):\n return getattr(self._bw_wrapped, name)\n\n def __call__(self, *args, **kwargs):\n transaction = current_transaction()\n if transaction:\n transaction.set_transaction_name(self._bw_name,\n priority=self._bw_priority)\n with FunctionTrace(transaction, name=self._bw_name):\n return self._bw_wrapped(*args, **kwargs)\n else:\n return self._bw_wrapped(*args, **kwargs)\n\nclass ResourceInitWrapper(object):\n\n def __init__(self, wrapped):\n if isinstance(wrapped, tuple):\n (instance, wrapped) = wrapped\n else:\n instance = None\n self.__instance = instance\n self._bw_wrapped = wrapped\n\n def __get__(self, instance, klass):\n if instance is None:\n return self\n descriptor = self._bw_wrapped.__get__(instance, klass)\n return self.__class__((instance, descriptor))\n\n def __getattr__(self, name):\n return getattr(self._bw_wrapped, name)\n\n def __call__(self, *args, **kwargs):\n self._bw_wrapped(*args, **kwargs)\n handler = self.__instance.handler\n for name in six.itervalues(self.__instance.callmap):\n if hasattr(handler, name):\n setattr(handler, name, MethodWrapper(\n getattr(handler, name), priority=6))\n\ndef instrument_piston_resource(module):\n\n wrap_object(module, 'Resource.__init__', ResourceInitWrapper)\n\ndef instrument_piston_doc(module):\n\n def in_HandlerMethod_init(self, method, *args, **kwargs):\n if isinstance(method, MethodWrapper):\n method = method._bw_wrapped\n return ((self, method) + args, kwargs)\n\n wrap_in_function(module, 'HandlerMethod.__init__', in_HandlerMethod_init)\n","sub_path":"blueware/hooks/component_piston.py","file_name":"component_piston.py","file_ext":"py","file_size_in_byte":2389,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"412996142","text":"__author__ = 'Sanjarbek Hudaiberdiev'\n\nfrom lib.db import DbClass\nfrom lib.utils.classes import Kplet\nfrom lib.db.bacteria import neighborhoods_path\n\n\ndef store_kplets_pile(kplets_pile, cdd2id, file2id):\n\n _sql_kplet = \"\"\"insert ignore into bacteria_3plets (kplet_1, kplet_2, kplet_3) values \\n\"\"\"\n\n _sql_kplet_file = \"\"\"insert ignore into bacteria_3plets_win10 (kplet_id, file_id) values \\n\"\"\"\n\n for (kplets, fname) in kplets_pile:\n\n for kplet in kplets:\n kplet = list(kplet)\n kplet.sort()\n kplet = tuple([int(cdd2id[k]) for k in kplet])\n\n _sql_kplet += \"\"\"(%d, %d, %d),\\n\"\"\" % kplet\n\n _sql_kplet_file += (\"\"\"((select id from bacteria_3plets where \"\"\" +\n \"\"\"kplet_1=%d and kplet_2=%d and kplet_3=%d),\"\"\" +\n \"\"\"%d),\\n\"\"\") % (kplet + (int(file2id[fname]),))\n\n _sql_kplet = _sql_kplet[:-2]\n _sql_kplet += ';'\n\n _sql_kplet_file = _sql_kplet_file[:-2]\n _sql_kplet_file += ';'\n\n _db = DbClass()\n\n _db.cmd = _sql_kplet\n _db.execute()\n _db.commit()\n\n _db.cmd = _sql_kplet_file\n _db.execute()\n _db.commit()\n\ndef get_multiple_kplets():\n\n _db = DbClass()\n _db.cmd = \"SET group_concat_max_len = 100000;\"\n _db.execute()\n _db.cmd = \"\"\" select ap.id, count(*) cnt, group_concat(convert(apw.file_id, char(15))) as file_ids\n from bacteria_3plets ap\n inner join bacteria_3plets_win10 apw on ap.id = apw.kplet_id\n group by ap.id\n having count(*)>1\n order by cnt desc\"\"\"\n\n return _db.retrieve()\n\n\ndef get_code_kplet(kplet_id, id2cdd=None):\n\n _db = DbClass()\n\n if not id2cdd:\n _db.cmd = \"\"\"select cp1.code, cp2.code, cp3.code\n from bacteria_3plets bp\n inner join cdd_profiles cp1 on cp1.id = bp.kplet_1\n inner join cdd_profiles cp2 on cp2.id = bp.kplet_2\n inner join cdd_profiles cp3 on cp3.id = bp.kplet_3\n where bp.id = %d\"\"\" % kplet_id\n retval = _db.retrieve()[0]\n\n else:\n\n _db.cmd = \"\"\"select kplet_1, kplet_2, kplet_3\n from bacteria_3plets where id = %d\"\"\" % kplet_id\n\n retval = _db.retrieve()[0]\n retval = set([id2cdd[id] for id in retval])\n\n return retval\n\n\ndef get_report_kplets(id2cdd, limit_to=500, load_locations=None):\n\n _db = DbClass()\n _db.cmd = \"\"\"SET group_concat_max_len=1500000\"\"\"\n _db.execute()\n\n _db.cmd = \"\"\"select ap.* ,count(*) as cnt, sum(w.weight) as wgt, group_concat(awf.name) as an\n from bacteria_3plets ap\n inner join bacteria_3plets_win10 apw on ap.id = apw.kplet_id\n inner join bacteria_win10_files awf on apw.file_id = awf.id\n inner join sources s on awf.source_id=s.id\n inner join weights w on w.genome_id=s.genome_id\n group by ap.id\n having count(distinct s.genome_id)>1\n order by wgt desc\n limit 0, %d\"\"\" % limit_to\n\n out_list = []\n\n for row in _db.retrieve():\n id = row[0]\n kplet_codes = ([id2cdd[int(_id)] for _id in row[1:4]])\n if len(set(kplet_codes)) != 3:\n continue\n count = row[4]\n weight = row[5]\n files = row[6].split(',')\n tmp_kplet = Kplet(id=id, codes=kplet_codes, count=count, files=files)\n out_list.append(tmp_kplet)\n\n _path = neighborhoods_path()\n if load_locations:\n [kplet.load_locations(_path) for kplet in out_list]\n\n return out_list\n","sub_path":"lib/db/prok1402/triplets.py","file_name":"triplets.py","file_ext":"py","file_size_in_byte":3622,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"111744495","text":"# coding: utf-8\n\n# (C) Copyright IBM Corp. 2021.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n# IBM OpenAPI SDK Code Generator Version: 3.34.1-ad041667-20210617-195430\n \n\"\"\"\nThe Data Virtualization REST API connects to your service, so you can manage your virtual\ndata, data sources, and user roles.\n\"\"\"\n\nfrom typing import Dict, List\nimport json\n\nfrom ibm_cloud_sdk_core import BaseService, DetailedResponse\nfrom ibm_cloud_sdk_core.authenticators.authenticator import Authenticator\nfrom ibm_cloud_sdk_core.get_authenticator import get_authenticator_from_environment\nfrom ibm_cloud_sdk_core.utils import convert_model\n\nfrom .common import get_sdk_headers\n\n##############################################################################\n# Service\n##############################################################################\n\nclass DataVirtualizationV1(BaseService):\n \"\"\"The Data Virtualization V1 service.\"\"\"\n\n DEFAULT_SERVICE_URL = None\n DEFAULT_SERVICE_NAME = 'data_virtualization'\n\n @classmethod\n def new_instance(cls,\n service_name: str = DEFAULT_SERVICE_NAME,\n ) -> 'DataVirtualizationV1':\n \"\"\"\n Return a new client for the Data Virtualization service using the specified\n parameters and external configuration.\n \"\"\"\n authenticator = get_authenticator_from_environment(service_name)\n service = cls(\n authenticator\n )\n service.configure_service(service_name)\n return service\n\n def __init__(self,\n authenticator: Authenticator = None,\n ) -> None:\n \"\"\"\n Construct a new client for the Data Virtualization service.\n\n :param Authenticator authenticator: The authenticator specifies the authentication mechanism.\n Get up to date information from https://github.com/IBM/python-sdk-core/blob/master/README.md\n about initializing the authenticator of your choice.\n \"\"\"\n BaseService.__init__(self,\n service_url=self.DEFAULT_SERVICE_URL,\n authenticator=authenticator)\n\n\n #########################\n # Data sources\n #########################\n\n\n def list_datasource_connections(self,\n **kwargs\n ) -> DetailedResponse:\n \"\"\"\n Get data source connections.\n\n Gets all data source connections that are connected to the service.\n\n :param dict headers: A `dict` containing the request headers\n :return: A `DetailedResponse` containing the result, headers and HTTP status code.\n :rtype: DetailedResponse with `dict` result representing a `DatasourceConnectionsList` object\n \"\"\"\n\n headers = {}\n sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME,\n service_version='V1',\n operation_id='list_datasource_connections')\n headers.update(sdk_headers)\n\n if 'headers' in kwargs:\n headers.update(kwargs.get('headers'))\n headers['Accept'] = 'application/json'\n\n url = '/v2/datasource/connections'\n request = self.prepare_request(method='GET',\n url=url,\n headers=headers)\n\n response = self.send(request)\n return response\n\n\n def add_datasource_connection(self,\n datasource_type: str,\n name: str,\n origin_country: str,\n properties: 'PostDatasourceConnectionParametersProperties',\n *,\n asset_category: str = None,\n **kwargs\n ) -> DetailedResponse:\n \"\"\"\n Add data source connection.\n\n Adds a data source connection to the Data Virtualization service.\n\n :param str datasource_type: The type of data source that you want to add.\n :param str name: The name of data source.\n :param str origin_country: The location of data source that you want to\n add.\n :param PostDatasourceConnectionParametersProperties properties:\n :param str asset_category: (optional)\n :param dict headers: A `dict` containing the request headers\n :return: A `DetailedResponse` containing the result, headers and HTTP status code.\n :rtype: DetailedResponse with `dict` result representing a `PostDatasourceConnection` object\n \"\"\"\n\n if datasource_type is None:\n raise ValueError('datasource_type must be provided')\n if name is None:\n raise ValueError('name must be provided')\n if origin_country is None:\n raise ValueError('origin_country must be provided')\n if properties is None:\n raise ValueError('properties must be provided')\n properties = convert_model(properties)\n headers = {}\n sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME,\n service_version='V1',\n operation_id='add_datasource_connection')\n headers.update(sdk_headers)\n\n data = {\n 'datasource_type': datasource_type,\n 'name': name,\n 'origin_country': origin_country,\n 'properties': properties,\n 'asset_category': asset_category\n }\n data = {k: v for (k, v) in data.items() if v is not None}\n data = json.dumps(data)\n headers['content-type'] = 'application/json'\n\n if 'headers' in kwargs:\n headers.update(kwargs.get('headers'))\n headers['Accept'] = 'application/json'\n\n url = '/v2/datasource/connections'\n request = self.prepare_request(method='POST',\n url=url,\n headers=headers,\n data=data)\n\n response = self.send(request)\n return response\n\n\n def delete_datasource_connection(self,\n connection_id: str,\n *,\n cid: str = None,\n **kwargs\n ) -> DetailedResponse:\n \"\"\"\n Delete data source connection.\n\n Deletes a data source connection from the Data Virtualization service.\n\n :param str connection_id: The connection identifier for the platform..\n :param str cid: (optional) The identifier of the connection for the Data\n Virtualization..\n :param dict headers: A `dict` containing the request headers\n :return: A `DetailedResponse` containing the result, headers and HTTP status code.\n :rtype: DetailedResponse\n \"\"\"\n\n if connection_id is None:\n raise ValueError('connection_id must be provided')\n headers = {}\n sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME,\n service_version='V1',\n operation_id='delete_datasource_connection')\n headers.update(sdk_headers)\n\n params = {\n 'cid': cid\n }\n\n if 'headers' in kwargs:\n headers.update(kwargs.get('headers'))\n\n path_param_keys = ['connection_id']\n path_param_values = self.encode_path_vars(connection_id)\n path_param_dict = dict(zip(path_param_keys, path_param_values))\n url = '/v2/datasource/connections/{connection_id}'.format(**path_param_dict)\n request = self.prepare_request(method='DELETE',\n url=url,\n headers=headers,\n params=params)\n\n response = self.send(request)\n return response\n\n #########################\n # Users\n #########################\n\n\n def grant_user_to_virtual_table(self,\n table_name: str,\n table_schema: str,\n authid: str,\n **kwargs\n ) -> DetailedResponse:\n \"\"\"\n Grant user access.\n\n Grants a user access to a specific virtualized table.\n\n :param str table_name: The name of the virtualized table.\n :param str table_schema: The schema of the virtualized table.\n :param str authid: The identifier of the authorization, if grant access to\n all users, the value is PUBLIC, othervise the value is the data\n virtualization username.\n :param dict headers: A `dict` containing the request headers\n :return: A `DetailedResponse` containing the result, headers and HTTP status code.\n :rtype: DetailedResponse\n \"\"\"\n\n if table_name is None:\n raise ValueError('table_name must be provided')\n if table_schema is None:\n raise ValueError('table_schema must be provided')\n if authid is None:\n raise ValueError('authid must be provided')\n headers = {}\n sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME,\n service_version='V1',\n operation_id='grant_user_to_virtual_table')\n headers.update(sdk_headers)\n\n data = {\n 'table_name': table_name,\n 'table_schema': table_schema,\n 'authid': authid\n }\n data = {k: v for (k, v) in data.items() if v is not None}\n data = json.dumps(data)\n headers['content-type'] = 'application/json'\n\n if 'headers' in kwargs:\n headers.update(kwargs.get('headers'))\n\n url = '/v2/privileges/users'\n request = self.prepare_request(method='POST',\n url=url,\n headers=headers,\n data=data)\n\n response = self.send(request)\n return response\n\n\n def revoke_user_from_object(self,\n authid: str,\n table_name: str,\n table_schema: str,\n **kwargs\n ) -> DetailedResponse:\n \"\"\"\n Revoke user acccess.\n\n Revokes user access to the virtualized table.\n\n :param str authid: The Data Virtualization user name, if the value is\n PUBLIC, it means revoke access privilege from all Data Virtualization\n users.\n :param str table_name: The virtualized table's name.\n :param str table_schema: The virtualized table's schema name.\n :param dict headers: A `dict` containing the request headers\n :return: A `DetailedResponse` containing the result, headers and HTTP status code.\n :rtype: DetailedResponse\n \"\"\"\n\n if authid is None:\n raise ValueError('authid must be provided')\n if table_name is None:\n raise ValueError('table_name must be provided')\n if table_schema is None:\n raise ValueError('table_schema must be provided')\n headers = {}\n sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME,\n service_version='V1',\n operation_id='revoke_user_from_object')\n headers.update(sdk_headers)\n\n params = {\n 'table_name': table_name,\n 'table_schema': table_schema\n }\n\n if 'headers' in kwargs:\n headers.update(kwargs.get('headers'))\n\n path_param_keys = ['authid']\n path_param_values = self.encode_path_vars(authid)\n path_param_dict = dict(zip(path_param_keys, path_param_values))\n url = '/v2/privileges/users/{authid}'.format(**path_param_dict)\n request = self.prepare_request(method='DELETE',\n url=url,\n headers=headers,\n params=params)\n\n response = self.send(request)\n return response\n\n #########################\n # Roles\n #########################\n\n\n def grant_roles_to_virtualized_table(self,\n table_name: str,\n table_schema: str,\n *,\n role_name: str = None,\n **kwargs\n ) -> DetailedResponse:\n \"\"\"\n Grant user role.\n\n Grants a user role access to a specific virtualized table.\n\n :param str table_name: The name of the virtualized table.\n :param str table_schema: The schema of the virtualized table.\n :param str role_name: (optional) The identifier of the authorization, if\n grant access to all users, the value is PUBLIC, othervise the value is the\n data virtualization username.\n :param dict headers: A `dict` containing the request headers\n :return: A `DetailedResponse` containing the result, headers and HTTP status code.\n :rtype: DetailedResponse\n \"\"\"\n\n if table_name is None:\n raise ValueError('table_name must be provided')\n if table_schema is None:\n raise ValueError('table_schema must be provided')\n headers = {}\n sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME,\n service_version='V1',\n operation_id='grant_roles_to_virtualized_table')\n headers.update(sdk_headers)\n\n data = {\n 'table_name': table_name,\n 'table_schema': table_schema,\n 'role_name': role_name\n }\n data = {k: v for (k, v) in data.items() if v is not None}\n data = json.dumps(data)\n headers['content-type'] = 'application/json'\n\n if 'headers' in kwargs:\n headers.update(kwargs.get('headers'))\n\n url = '/v2/privileges/roles'\n request = self.prepare_request(method='POST',\n url=url,\n headers=headers,\n data=data)\n\n response = self.send(request)\n return response\n\n\n def dvaas_revoke_role_from_table(self,\n role_name: str,\n table_name: str,\n table_schema: str,\n **kwargs\n ) -> DetailedResponse:\n \"\"\"\n Delete role.\n\n Revokes roles for a virtualized table.\n\n :param str role_name: The Data Virtualization role type. Values can be\n DV_ADMIN, DV_ENGINEER, DV_STEWARD, or DV_WORKER, which correspond to\n MANAGER, ENGINEER, STEWARD, and USER roles in the user interface.\n :param str table_name: The virtualized table's name.\n :param str table_schema: The virtualized table's schema name.\n :param dict headers: A `dict` containing the request headers\n :return: A `DetailedResponse` containing the result, headers and HTTP status code.\n :rtype: DetailedResponse\n \"\"\"\n\n if role_name is None:\n raise ValueError('role_name must be provided')\n if table_name is None:\n raise ValueError('table_name must be provided')\n if table_schema is None:\n raise ValueError('table_schema must be provided')\n headers = {}\n sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME,\n service_version='V1',\n operation_id='dvaas_revoke_role_from_table')\n headers.update(sdk_headers)\n\n params = {\n 'table_name': table_name,\n 'table_schema': table_schema\n }\n\n if 'headers' in kwargs:\n headers.update(kwargs.get('headers'))\n\n path_param_keys = ['role_name']\n path_param_values = self.encode_path_vars(role_name)\n path_param_dict = dict(zip(path_param_keys, path_param_values))\n url = '/v2/privileges/roles/{role_name}'.format(**path_param_dict)\n request = self.prepare_request(method='DELETE',\n url=url,\n headers=headers,\n params=params)\n\n response = self.send(request)\n return response\n\n\n def list_tables_for_role(self,\n rolename: str,\n **kwargs\n ) -> DetailedResponse:\n \"\"\"\n Get virtualized tables by role.\n\n Retrieves the list of virtualized tables that have a specific role.\n\n :param str rolename: Data Virtualization has four roles: MANAGER, STEWARD,\n ENGINEER and USER The value of rolename should be one of them.\n :param dict headers: A `dict` containing the request headers\n :return: A `DetailedResponse` containing the result, headers and HTTP status code.\n :rtype: DetailedResponse with `dict` result representing a `TablesForRoleResponse` object\n \"\"\"\n\n if rolename is None:\n raise ValueError('rolename must be provided')\n headers = {}\n sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME,\n service_version='V1',\n operation_id='list_tables_for_role')\n headers.update(sdk_headers)\n\n params = {\n 'rolename': rolename\n }\n\n if 'headers' in kwargs:\n headers.update(kwargs.get('headers'))\n headers['Accept'] = 'application/json'\n\n url = '/v2/privileges/tables'\n request = self.prepare_request(method='GET',\n url=url,\n headers=headers,\n params=params)\n\n response = self.send(request)\n return response\n\n #########################\n # Securities\n #########################\n\n\n def turn_on_policy_v2(self,\n status: str,\n **kwargs\n ) -> DetailedResponse:\n \"\"\"\n Turn on or off WKC policy enforcement status.\n\n Turn on WKC policy enforcement status.\n\n :param str status: Set the status of WKC policy.\n :param dict headers: A `dict` containing the request headers\n :return: A `DetailedResponse` containing the result, headers and HTTP status code.\n :rtype: DetailedResponse with `dict` result representing a `TurnOnPolicyV2Response` object\n \"\"\"\n\n if status is None:\n raise ValueError('status must be provided')\n headers = {}\n sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME,\n service_version='V1',\n operation_id='turn_on_policy_v2')\n headers.update(sdk_headers)\n\n params = {\n 'status': status\n }\n\n if 'headers' in kwargs:\n headers.update(kwargs.get('headers'))\n headers['Accept'] = 'application/json'\n\n url = '/v2/security/policy/status'\n request = self.prepare_request(method='PUT',\n url=url,\n headers=headers,\n params=params)\n\n response = self.send(request)\n return response\n\n\n def check_policy_status_v2(self,\n **kwargs\n ) -> DetailedResponse:\n \"\"\"\n Get WKC policy enforcement status.\n\n Get WKC policy enforcement status, return enabled or disabled.\n\n :param dict headers: A `dict` containing the request headers\n :return: A `DetailedResponse` containing the result, headers and HTTP status code.\n :rtype: DetailedResponse with `dict` result representing a `CheckPolicyStatusV2Response` object\n \"\"\"\n\n headers = {}\n sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME,\n service_version='V1',\n operation_id='check_policy_status_v2')\n headers.update(sdk_headers)\n\n if 'headers' in kwargs:\n headers.update(kwargs.get('headers'))\n headers['Accept'] = 'application/json'\n\n url = '/v2/security/policy/status'\n request = self.prepare_request(method='GET',\n url=url,\n headers=headers)\n\n response = self.send(request)\n return response\n\n #########################\n # Virtualization\n #########################\n\n\n def dvaas_virtualize_table(self,\n source_name: str,\n source_table_def: List['VirtualizeTableParameterSourceTableDefItem'],\n sources: List[str],\n virtual_name: str,\n virtual_schema: str,\n virtual_table_def: List['VirtualizeTableParameterVirtualTableDefItem'],\n *,\n is_included_columns: str = None,\n replace: bool = None,\n **kwargs\n ) -> DetailedResponse:\n \"\"\"\n Virtualize table.\n\n Transforms a given data source table into a virtualized table.\n\n :param str source_name: The name of the source table.\n :param List[VirtualizeTableParameterSourceTableDefItem] source_table_def:\n :param List[str] sources:\n :param str virtual_name: The name of the table that will be virtualized.\n :param str virtual_schema: The schema of the table that will be\n virtualized.\n :param List[VirtualizeTableParameterVirtualTableDefItem] virtual_table_def:\n :param str is_included_columns: (optional) The columns that are included in\n the source table.\n :param bool replace: (optional) Determines whether to replace columns in\n the virtualized table.\n :param dict headers: A `dict` containing the request headers\n :return: A `DetailedResponse` containing the result, headers and HTTP status code.\n :rtype: DetailedResponse with `dict` result representing a `VirtualizeTableResponse` object\n \"\"\"\n\n if source_name is None:\n raise ValueError('source_name must be provided')\n if source_table_def is None:\n raise ValueError('source_table_def must be provided')\n if sources is None:\n raise ValueError('sources must be provided')\n if virtual_name is None:\n raise ValueError('virtual_name must be provided')\n if virtual_schema is None:\n raise ValueError('virtual_schema must be provided')\n if virtual_table_def is None:\n raise ValueError('virtual_table_def must be provided')\n source_table_def = [convert_model(x) for x in source_table_def]\n virtual_table_def = [convert_model(x) for x in virtual_table_def]\n headers = {}\n sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME,\n service_version='V1',\n operation_id='dvaas_virtualize_table')\n headers.update(sdk_headers)\n\n data = {\n 'source_name': source_name,\n 'source_table_def': source_table_def,\n 'sources': sources,\n 'virtual_name': virtual_name,\n 'virtual_schema': virtual_schema,\n 'virtual_table_def': virtual_table_def,\n 'is_included_columns': is_included_columns,\n 'replace': replace\n }\n data = {k: v for (k, v) in data.items() if v is not None}\n data = json.dumps(data)\n headers['content-type'] = 'application/json'\n\n if 'headers' in kwargs:\n headers.update(kwargs.get('headers'))\n headers['Accept'] = 'application/json'\n\n url = '/v2/virtualization/tables'\n request = self.prepare_request(method='POST',\n url=url,\n headers=headers,\n data=data)\n\n response = self.send(request)\n return response\n\n\n def delete_table(self,\n virtual_schema: str,\n virtual_name: str,\n **kwargs\n ) -> DetailedResponse:\n \"\"\"\n Delete virtualized table.\n\n Removes the specified virtualized table. You must specify the schema and table\n name.\n\n :param str virtual_schema: The schema of virtualized table to be deleted.\n :param str virtual_name: The name of virtualized table to be deleted.\n :param dict headers: A `dict` containing the request headers\n :return: A `DetailedResponse` containing the result, headers and HTTP status code.\n :rtype: DetailedResponse\n \"\"\"\n\n if virtual_schema is None:\n raise ValueError('virtual_schema must be provided')\n if virtual_name is None:\n raise ValueError('virtual_name must be provided')\n headers = {}\n sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME,\n service_version='V1',\n operation_id='delete_table')\n headers.update(sdk_headers)\n\n params = {\n 'virtual_schema': virtual_schema\n }\n\n if 'headers' in kwargs:\n headers.update(kwargs.get('headers'))\n\n path_param_keys = ['virtual_name']\n path_param_values = self.encode_path_vars(virtual_name)\n path_param_dict = dict(zip(path_param_keys, path_param_values))\n url = '/v2/virtualization/tables/{virtual_name}'.format(**path_param_dict)\n request = self.prepare_request(method='DELETE',\n url=url,\n headers=headers,\n params=params)\n\n response = self.send(request)\n return response\n\n #########################\n # Primary catalog\n #########################\n\n\n def get_primary_catalog(self,\n **kwargs\n ) -> DetailedResponse:\n \"\"\"\n Get primary catalog ID.\n\n Get primary catalog ID from the table DVSYS.INSTANCE_INFO.\n\n :param dict headers: A `dict` containing the request headers\n :return: A `DetailedResponse` containing the result, headers and HTTP status code.\n :rtype: DetailedResponse with `dict` result representing a `PrimaryCatalogInfo` object\n \"\"\"\n\n headers = {}\n sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME,\n service_version='V1',\n operation_id='get_primary_catalog')\n headers.update(sdk_headers)\n\n if 'headers' in kwargs:\n headers.update(kwargs.get('headers'))\n headers['Accept'] = 'application/json'\n\n url = '/v2/catalog/primary'\n request = self.prepare_request(method='GET',\n url=url,\n headers=headers)\n\n response = self.send(request)\n return response\n\n\n def post_primary_catalog(self,\n guid: str,\n **kwargs\n ) -> DetailedResponse:\n \"\"\"\n Add primary catalog.\n\n Insert primary catalog ID into table DVSYS.INSTANCE_INFO.\n\n :param str guid:\n :param dict headers: A `dict` containing the request headers\n :return: A `DetailedResponse` containing the result, headers and HTTP status code.\n :rtype: DetailedResponse with `dict` result representing a `PostPrimaryCatalog` object\n \"\"\"\n\n if guid is None:\n raise ValueError('guid must be provided')\n headers = {}\n sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME,\n service_version='V1',\n operation_id='post_primary_catalog')\n headers.update(sdk_headers)\n\n data = {\n 'guid': guid\n }\n data = {k: v for (k, v) in data.items() if v is not None}\n data = json.dumps(data)\n headers['content-type'] = 'application/json'\n\n if 'headers' in kwargs:\n headers.update(kwargs.get('headers'))\n headers['Accept'] = 'application/json'\n\n url = '/v2/catalog/primary'\n request = self.prepare_request(method='POST',\n url=url,\n headers=headers,\n data=data)\n\n response = self.send(request)\n return response\n\n\n def delete_primary_catalog(self,\n guid: str,\n **kwargs\n ) -> DetailedResponse:\n \"\"\"\n Delete primary catalog.\n\n Delete primary catalog item in the DVSYS.INSTANCE_INFO table.\n\n :param str guid: The Data Virtualization user name, if the value is PUBLIC,\n it means revoke access privilege from all Data Virtualization users.\n :param dict headers: A `dict` containing the request headers\n :return: A `DetailedResponse` containing the result, headers and HTTP status code.\n :rtype: DetailedResponse\n \"\"\"\n\n if guid is None:\n raise ValueError('guid must be provided')\n headers = {}\n sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME,\n service_version='V1',\n operation_id='delete_primary_catalog')\n headers.update(sdk_headers)\n\n params = {\n 'guid': guid\n }\n\n if 'headers' in kwargs:\n headers.update(kwargs.get('headers'))\n\n url = '/v2/catalog/primary'\n request = self.prepare_request(method='DELETE',\n url=url,\n headers=headers,\n params=params)\n\n response = self.send(request)\n return response\n\n #########################\n # Publish objects\n #########################\n\n\n def publish_assets(self,\n catalog_id: str,\n allow_duplicates: bool,\n assets: List['PostPrimaryCatalogParametersAssetsItem'],\n **kwargs\n ) -> DetailedResponse:\n \"\"\"\n publish virtual table to WKC.\n\n publish virtual tables to WKC.\n\n :param str catalog_id:\n :param bool allow_duplicates: The type of data source that you want to add.\n :param List[PostPrimaryCatalogParametersAssetsItem] assets:\n :param dict headers: A `dict` containing the request headers\n :return: A `DetailedResponse` containing the result, headers and HTTP status code.\n :rtype: DetailedResponse with `dict` result representing a `CatalogPublishResponse` object\n \"\"\"\n\n if catalog_id is None:\n raise ValueError('catalog_id must be provided')\n if allow_duplicates is None:\n raise ValueError('allow_duplicates must be provided')\n if assets is None:\n raise ValueError('assets must be provided')\n assets = [convert_model(x) for x in assets]\n headers = {}\n sdk_headers = get_sdk_headers(service_name=self.DEFAULT_SERVICE_NAME,\n service_version='V1',\n operation_id='publish_assets')\n headers.update(sdk_headers)\n\n data = {\n 'catalog_id': catalog_id,\n 'allow_duplicates': allow_duplicates,\n 'assets': assets\n }\n data = {k: v for (k, v) in data.items() if v is not None}\n data = json.dumps(data)\n headers['content-type'] = 'application/json'\n\n if 'headers' in kwargs:\n headers.update(kwargs.get('headers'))\n headers['Accept'] = 'application/json'\n\n url = '/v2/integration/catalog/publish'\n request = self.prepare_request(method='POST',\n url=url,\n headers=headers,\n data=data)\n\n response = self.send(request)\n return response\n\n\n##############################################################################\n# Models\n##############################################################################\n\n\nclass CatalogPublishResponseDuplicateAssetsItem():\n \"\"\"\n CatalogPublishResponseDuplicateAssetsItem.\n\n :attr str schema_name: (optional)\n :attr str table_name: (optional)\n \"\"\"\n\n def __init__(self,\n *,\n schema_name: str = None,\n table_name: str = None) -> None:\n \"\"\"\n Initialize a CatalogPublishResponseDuplicateAssetsItem object.\n\n :param str schema_name: (optional)\n :param str table_name: (optional)\n \"\"\"\n self.schema_name = schema_name\n self.table_name = table_name\n\n @classmethod\n def from_dict(cls, _dict: Dict) -> 'CatalogPublishResponseDuplicateAssetsItem':\n \"\"\"Initialize a CatalogPublishResponseDuplicateAssetsItem object from a json dictionary.\"\"\"\n args = {}\n if 'schema_name' in _dict:\n args['schema_name'] = _dict.get('schema_name')\n if 'table_name' in _dict:\n args['table_name'] = _dict.get('table_name')\n return cls(**args)\n\n @classmethod\n def _from_dict(cls, _dict):\n \"\"\"Initialize a CatalogPublishResponseDuplicateAssetsItem object from a json dictionary.\"\"\"\n return cls.from_dict(_dict)\n\n def to_dict(self) -> Dict:\n \"\"\"Return a json dictionary representing this model.\"\"\"\n _dict = {}\n if hasattr(self, 'schema_name') and self.schema_name is not None:\n _dict['schema_name'] = self.schema_name\n if hasattr(self, 'table_name') and self.table_name is not None:\n _dict['table_name'] = self.table_name\n return _dict\n\n def _to_dict(self):\n \"\"\"Return a json dictionary representing this model.\"\"\"\n return self.to_dict()\n\n def __str__(self) -> str:\n \"\"\"Return a `str` version of this CatalogPublishResponseDuplicateAssetsItem object.\"\"\"\n return json.dumps(self.to_dict(), indent=2)\n\n def __eq__(self, other: 'CatalogPublishResponseDuplicateAssetsItem') -> bool:\n \"\"\"Return `true` when self and other are equal, false otherwise.\"\"\"\n if not isinstance(other, self.__class__):\n return False\n return self.__dict__ == other.__dict__\n\n def __ne__(self, other: 'CatalogPublishResponseDuplicateAssetsItem') -> bool:\n \"\"\"Return `true` when self and other are not equal, false otherwise.\"\"\"\n return not self == other\n\nclass CatalogPublishResponseFailedAssetsItem():\n \"\"\"\n CatalogPublishResponseFailedAssetsItem.\n\n :attr str error_msg: (optional)\n :attr str schema_name: (optional)\n :attr str table_name: (optional)\n \"\"\"\n\n def __init__(self,\n *,\n error_msg: str = None,\n schema_name: str = None,\n table_name: str = None) -> None:\n \"\"\"\n Initialize a CatalogPublishResponseFailedAssetsItem object.\n\n :param str error_msg: (optional)\n :param str schema_name: (optional)\n :param str table_name: (optional)\n \"\"\"\n self.error_msg = error_msg\n self.schema_name = schema_name\n self.table_name = table_name\n\n @classmethod\n def from_dict(cls, _dict: Dict) -> 'CatalogPublishResponseFailedAssetsItem':\n \"\"\"Initialize a CatalogPublishResponseFailedAssetsItem object from a json dictionary.\"\"\"\n args = {}\n if 'error_msg' in _dict:\n args['error_msg'] = _dict.get('error_msg')\n if 'schema_name' in _dict:\n args['schema_name'] = _dict.get('schema_name')\n if 'table_name' in _dict:\n args['table_name'] = _dict.get('table_name')\n return cls(**args)\n\n @classmethod\n def _from_dict(cls, _dict):\n \"\"\"Initialize a CatalogPublishResponseFailedAssetsItem object from a json dictionary.\"\"\"\n return cls.from_dict(_dict)\n\n def to_dict(self) -> Dict:\n \"\"\"Return a json dictionary representing this model.\"\"\"\n _dict = {}\n if hasattr(self, 'error_msg') and self.error_msg is not None:\n _dict['error_msg'] = self.error_msg\n if hasattr(self, 'schema_name') and self.schema_name is not None:\n _dict['schema_name'] = self.schema_name\n if hasattr(self, 'table_name') and self.table_name is not None:\n _dict['table_name'] = self.table_name\n return _dict\n\n def _to_dict(self):\n \"\"\"Return a json dictionary representing this model.\"\"\"\n return self.to_dict()\n\n def __str__(self) -> str:\n \"\"\"Return a `str` version of this CatalogPublishResponseFailedAssetsItem object.\"\"\"\n return json.dumps(self.to_dict(), indent=2)\n\n def __eq__(self, other: 'CatalogPublishResponseFailedAssetsItem') -> bool:\n \"\"\"Return `true` when self and other are equal, false otherwise.\"\"\"\n if not isinstance(other, self.__class__):\n return False\n return self.__dict__ == other.__dict__\n\n def __ne__(self, other: 'CatalogPublishResponseFailedAssetsItem') -> bool:\n \"\"\"Return `true` when self and other are not equal, false otherwise.\"\"\"\n return not self == other\n\nclass CatalogPublishResponsePublishedAssetsItem():\n \"\"\"\n CatalogPublishResponsePublishedAssetsItem.\n\n :attr str schema_name: (optional)\n :attr str table_name: (optional)\n :attr str wkc_asset_id: (optional)\n \"\"\"\n\n def __init__(self,\n *,\n schema_name: str = None,\n table_name: str = None,\n wkc_asset_id: str = None) -> None:\n \"\"\"\n Initialize a CatalogPublishResponsePublishedAssetsItem object.\n\n :param str schema_name: (optional)\n :param str table_name: (optional)\n :param str wkc_asset_id: (optional)\n \"\"\"\n self.schema_name = schema_name\n self.table_name = table_name\n self.wkc_asset_id = wkc_asset_id\n\n @classmethod\n def from_dict(cls, _dict: Dict) -> 'CatalogPublishResponsePublishedAssetsItem':\n \"\"\"Initialize a CatalogPublishResponsePublishedAssetsItem object from a json dictionary.\"\"\"\n args = {}\n if 'schema_name' in _dict:\n args['schema_name'] = _dict.get('schema_name')\n if 'table_name' in _dict:\n args['table_name'] = _dict.get('table_name')\n if 'wkc_asset_id' in _dict:\n args['wkc_asset_id'] = _dict.get('wkc_asset_id')\n return cls(**args)\n\n @classmethod\n def _from_dict(cls, _dict):\n \"\"\"Initialize a CatalogPublishResponsePublishedAssetsItem object from a json dictionary.\"\"\"\n return cls.from_dict(_dict)\n\n def to_dict(self) -> Dict:\n \"\"\"Return a json dictionary representing this model.\"\"\"\n _dict = {}\n if hasattr(self, 'schema_name') and self.schema_name is not None:\n _dict['schema_name'] = self.schema_name\n if hasattr(self, 'table_name') and self.table_name is not None:\n _dict['table_name'] = self.table_name\n if hasattr(self, 'wkc_asset_id') and self.wkc_asset_id is not None:\n _dict['wkc_asset_id'] = self.wkc_asset_id\n return _dict\n\n def _to_dict(self):\n \"\"\"Return a json dictionary representing this model.\"\"\"\n return self.to_dict()\n\n def __str__(self) -> str:\n \"\"\"Return a `str` version of this CatalogPublishResponsePublishedAssetsItem object.\"\"\"\n return json.dumps(self.to_dict(), indent=2)\n\n def __eq__(self, other: 'CatalogPublishResponsePublishedAssetsItem') -> bool:\n \"\"\"Return `true` when self and other are equal, false otherwise.\"\"\"\n if not isinstance(other, self.__class__):\n return False\n return self.__dict__ == other.__dict__\n\n def __ne__(self, other: 'CatalogPublishResponsePublishedAssetsItem') -> bool:\n \"\"\"Return `true` when self and other are not equal, false otherwise.\"\"\"\n return not self == other\n\nclass CheckPolicyStatusV2Response():\n \"\"\"\n CheckPolicyStatusV2Response.\n\n :attr str status:\n \"\"\"\n\n def __init__(self,\n status: str) -> None:\n \"\"\"\n Initialize a CheckPolicyStatusV2Response object.\n\n :param str status:\n \"\"\"\n self.status = status\n\n @classmethod\n def from_dict(cls, _dict: Dict) -> 'CheckPolicyStatusV2Response':\n \"\"\"Initialize a CheckPolicyStatusV2Response object from a json dictionary.\"\"\"\n args = {}\n if 'status' in _dict:\n args['status'] = _dict.get('status')\n else:\n raise ValueError('Required property \\'status\\' not present in CheckPolicyStatusV2Response JSON')\n return cls(**args)\n\n @classmethod\n def _from_dict(cls, _dict):\n \"\"\"Initialize a CheckPolicyStatusV2Response object from a json dictionary.\"\"\"\n return cls.from_dict(_dict)\n\n def to_dict(self) -> Dict:\n \"\"\"Return a json dictionary representing this model.\"\"\"\n _dict = {}\n if hasattr(self, 'status') and self.status is not None:\n _dict['status'] = self.status\n return _dict\n\n def _to_dict(self):\n \"\"\"Return a json dictionary representing this model.\"\"\"\n return self.to_dict()\n\n def __str__(self) -> str:\n \"\"\"Return a `str` version of this CheckPolicyStatusV2Response object.\"\"\"\n return json.dumps(self.to_dict(), indent=2)\n\n def __eq__(self, other: 'CheckPolicyStatusV2Response') -> bool:\n \"\"\"Return `true` when self and other are equal, false otherwise.\"\"\"\n if not isinstance(other, self.__class__):\n return False\n return self.__dict__ == other.__dict__\n\n def __ne__(self, other: 'CheckPolicyStatusV2Response') -> bool:\n \"\"\"Return `true` when self and other are not equal, false otherwise.\"\"\"\n return not self == other\n\nclass DatasourceConnectionsList():\n \"\"\"\n DatasourceConnectionsList.\n\n :attr List[DatasourceConnectionsListDatasourceConnectionsItem]\n datasource_connections: (optional)\n \"\"\"\n\n def __init__(self,\n *,\n datasource_connections: List['DatasourceConnectionsListDatasourceConnectionsItem'] = None) -> None:\n \"\"\"\n Initialize a DatasourceConnectionsList object.\n\n :param List[DatasourceConnectionsListDatasourceConnectionsItem]\n datasource_connections: (optional)\n \"\"\"\n self.datasource_connections = datasource_connections\n\n @classmethod\n def from_dict(cls, _dict: Dict) -> 'DatasourceConnectionsList':\n \"\"\"Initialize a DatasourceConnectionsList object from a json dictionary.\"\"\"\n args = {}\n if 'datasource_connections' in _dict:\n args['datasource_connections'] = [DatasourceConnectionsListDatasourceConnectionsItem.from_dict(x) for x in _dict.get('datasource_connections')]\n return cls(**args)\n\n @classmethod\n def _from_dict(cls, _dict):\n \"\"\"Initialize a DatasourceConnectionsList object from a json dictionary.\"\"\"\n return cls.from_dict(_dict)\n\n def to_dict(self) -> Dict:\n \"\"\"Return a json dictionary representing this model.\"\"\"\n _dict = {}\n if hasattr(self, 'datasource_connections') and self.datasource_connections is not None:\n _dict['datasource_connections'] = [x.to_dict() for x in self.datasource_connections]\n return _dict\n\n def _to_dict(self):\n \"\"\"Return a json dictionary representing this model.\"\"\"\n return self.to_dict()\n\n def __str__(self) -> str:\n \"\"\"Return a `str` version of this DatasourceConnectionsList object.\"\"\"\n return json.dumps(self.to_dict(), indent=2)\n\n def __eq__(self, other: 'DatasourceConnectionsList') -> bool:\n \"\"\"Return `true` when self and other are equal, false otherwise.\"\"\"\n if not isinstance(other, self.__class__):\n return False\n return self.__dict__ == other.__dict__\n\n def __ne__(self, other: 'DatasourceConnectionsList') -> bool:\n \"\"\"Return `true` when self and other are not equal, false otherwise.\"\"\"\n return not self == other\n\nclass DatasourceConnectionsListDatasourceConnectionsItem():\n \"\"\"\n DatasourceConnectionsListDatasourceConnectionsItem.\n\n :attr str node_name: (optional) The name of the node that a datasource\n connection associates.\n :attr str node_description: (optional) The description of the node that a\n datasource connection associates.\n :attr str agent_class: (optional) The type of connector, for example, H stands\n for Hosted, ie running within the cluster, F means Fenced Mode Process, ie\n direct within Data Virtualization instance.\n :attr str hostname: (optional) The hostname or IP address that is used to access\n the connection.\n :attr str port: (optional) The port number that is used to access the\n connection.\n :attr str os_user: (optional)\n :attr str is_docker: (optional) Determines whether the data source uses Docker.\n :attr str dscount: (optional) The number of data sources.\n :attr List[DatasourceConnectionsListDatasourceConnectionsItemDataSourcesItem]\n data_sources: (optional)\n \"\"\"\n\n def __init__(self,\n *,\n node_name: str = None,\n node_description: str = None,\n agent_class: str = None,\n hostname: str = None,\n port: str = None,\n os_user: str = None,\n is_docker: str = None,\n dscount: str = None,\n data_sources: List['DatasourceConnectionsListDatasourceConnectionsItemDataSourcesItem'] = None) -> None:\n \"\"\"\n Initialize a DatasourceConnectionsListDatasourceConnectionsItem object.\n\n :param str node_name: (optional) The name of the node that a datasource\n connection associates.\n :param str node_description: (optional) The description of the node that a\n datasource connection associates.\n :param str agent_class: (optional) The type of connector, for example, H\n stands for Hosted, ie running within the cluster, F means Fenced Mode\n Process, ie direct within Data Virtualization instance.\n :param str hostname: (optional) The hostname or IP address that is used to\n access the connection.\n :param str port: (optional) The port number that is used to access the\n connection.\n :param str os_user: (optional)\n :param str is_docker: (optional) Determines whether the data source uses\n Docker.\n :param str dscount: (optional) The number of data sources.\n :param\n List[DatasourceConnectionsListDatasourceConnectionsItemDataSourcesItem]\n data_sources: (optional)\n \"\"\"\n self.node_name = node_name\n self.node_description = node_description\n self.agent_class = agent_class\n self.hostname = hostname\n self.port = port\n self.os_user = os_user\n self.is_docker = is_docker\n self.dscount = dscount\n self.data_sources = data_sources\n\n @classmethod\n def from_dict(cls, _dict: Dict) -> 'DatasourceConnectionsListDatasourceConnectionsItem':\n \"\"\"Initialize a DatasourceConnectionsListDatasourceConnectionsItem object from a json dictionary.\"\"\"\n args = {}\n if 'node_name' in _dict:\n args['node_name'] = _dict.get('node_name')\n if 'node_description' in _dict:\n args['node_description'] = _dict.get('node_description')\n if 'agent_class' in _dict:\n args['agent_class'] = _dict.get('agent_class')\n if 'hostname' in _dict:\n args['hostname'] = _dict.get('hostname')\n if 'port' in _dict:\n args['port'] = _dict.get('port')\n if 'os_user' in _dict:\n args['os_user'] = _dict.get('os_user')\n if 'is_docker' in _dict:\n args['is_docker'] = _dict.get('is_docker')\n if 'dscount' in _dict:\n args['dscount'] = _dict.get('dscount')\n if 'data_sources' in _dict:\n args['data_sources'] = [DatasourceConnectionsListDatasourceConnectionsItemDataSourcesItem.from_dict(x) for x in _dict.get('data_sources')]\n return cls(**args)\n\n @classmethod\n def _from_dict(cls, _dict):\n \"\"\"Initialize a DatasourceConnectionsListDatasourceConnectionsItem object from a json dictionary.\"\"\"\n return cls.from_dict(_dict)\n\n def to_dict(self) -> Dict:\n \"\"\"Return a json dictionary representing this model.\"\"\"\n _dict = {}\n if hasattr(self, 'node_name') and self.node_name is not None:\n _dict['node_name'] = self.node_name\n if hasattr(self, 'node_description') and self.node_description is not None:\n _dict['node_description'] = self.node_description\n if hasattr(self, 'agent_class') and self.agent_class is not None:\n _dict['agent_class'] = self.agent_class\n if hasattr(self, 'hostname') and self.hostname is not None:\n _dict['hostname'] = self.hostname\n if hasattr(self, 'port') and self.port is not None:\n _dict['port'] = self.port\n if hasattr(self, 'os_user') and self.os_user is not None:\n _dict['os_user'] = self.os_user\n if hasattr(self, 'is_docker') and self.is_docker is not None:\n _dict['is_docker'] = self.is_docker\n if hasattr(self, 'dscount') and self.dscount is not None:\n _dict['dscount'] = self.dscount\n if hasattr(self, 'data_sources') and self.data_sources is not None:\n _dict['data_sources'] = [x.to_dict() for x in self.data_sources]\n return _dict\n\n def _to_dict(self):\n \"\"\"Return a json dictionary representing this model.\"\"\"\n return self.to_dict()\n\n def __str__(self) -> str:\n \"\"\"Return a `str` version of this DatasourceConnectionsListDatasourceConnectionsItem object.\"\"\"\n return json.dumps(self.to_dict(), indent=2)\n\n def __eq__(self, other: 'DatasourceConnectionsListDatasourceConnectionsItem') -> bool:\n \"\"\"Return `true` when self and other are equal, false otherwise.\"\"\"\n if not isinstance(other, self.__class__):\n return False\n return self.__dict__ == other.__dict__\n\n def __ne__(self, other: 'DatasourceConnectionsListDatasourceConnectionsItem') -> bool:\n \"\"\"Return `true` when self and other are not equal, false otherwise.\"\"\"\n return not self == other\n\nclass DatasourceConnectionsListDatasourceConnectionsItemDataSourcesItem():\n \"\"\"\n DatasourceConnectionsListDatasourceConnectionsItemDataSourcesItem.\n\n :attr str cid: (optional) The identifier of the connection for the Data\n Virtualization.\n :attr str dbname: (optional) The name of the database.\n :attr str connection_id: (optional) The connection identifier for the platform.\n :attr str srchostname: (optional) The hostname or IP address of the data source.\n :attr str srcport: (optional) The port number of the data source.\n :attr str srctype: (optional) The type of the data source.\n :attr str usr: (optional) The user that has access to the data source.\n :attr str uri: (optional) The URI of the data source.\n :attr str status: (optional) The status of the data source.\n :attr str connection_name: (optional) The name of the connection.\n \"\"\"\n\n def __init__(self,\n *,\n cid: str = None,\n dbname: str = None,\n connection_id: str = None,\n srchostname: str = None,\n srcport: str = None,\n srctype: str = None,\n usr: str = None,\n uri: str = None,\n status: str = None,\n connection_name: str = None) -> None:\n \"\"\"\n Initialize a DatasourceConnectionsListDatasourceConnectionsItemDataSourcesItem object.\n\n :param str cid: (optional) The identifier of the connection for the Data\n Virtualization.\n :param str dbname: (optional) The name of the database.\n :param str connection_id: (optional) The connection identifier for the\n platform.\n :param str srchostname: (optional) The hostname or IP address of the data\n source.\n :param str srcport: (optional) The port number of the data source.\n :param str srctype: (optional) The type of the data source.\n :param str usr: (optional) The user that has access to the data source.\n :param str uri: (optional) The URI of the data source.\n :param str status: (optional) The status of the data source.\n :param str connection_name: (optional) The name of the connection.\n \"\"\"\n self.cid = cid\n self.dbname = dbname\n self.connection_id = connection_id\n self.srchostname = srchostname\n self.srcport = srcport\n self.srctype = srctype\n self.usr = usr\n self.uri = uri\n self.status = status\n self.connection_name = connection_name\n\n @classmethod\n def from_dict(cls, _dict: Dict) -> 'DatasourceConnectionsListDatasourceConnectionsItemDataSourcesItem':\n \"\"\"Initialize a DatasourceConnectionsListDatasourceConnectionsItemDataSourcesItem object from a json dictionary.\"\"\"\n args = {}\n if 'cid' in _dict:\n args['cid'] = _dict.get('cid')\n if 'dbname' in _dict:\n args['dbname'] = _dict.get('dbname')\n if 'connection_id' in _dict:\n args['connection_id'] = _dict.get('connection_id')\n if 'srchostname' in _dict:\n args['srchostname'] = _dict.get('srchostname')\n if 'srcport' in _dict:\n args['srcport'] = _dict.get('srcport')\n if 'srctype' in _dict:\n args['srctype'] = _dict.get('srctype')\n if 'usr' in _dict:\n args['usr'] = _dict.get('usr')\n if 'uri' in _dict:\n args['uri'] = _dict.get('uri')\n if 'status' in _dict:\n args['status'] = _dict.get('status')\n if 'connection_name' in _dict:\n args['connection_name'] = _dict.get('connection_name')\n return cls(**args)\n\n @classmethod\n def _from_dict(cls, _dict):\n \"\"\"Initialize a DatasourceConnectionsListDatasourceConnectionsItemDataSourcesItem object from a json dictionary.\"\"\"\n return cls.from_dict(_dict)\n\n def to_dict(self) -> Dict:\n \"\"\"Return a json dictionary representing this model.\"\"\"\n _dict = {}\n if hasattr(self, 'cid') and self.cid is not None:\n _dict['cid'] = self.cid\n if hasattr(self, 'dbname') and self.dbname is not None:\n _dict['dbname'] = self.dbname\n if hasattr(self, 'connection_id') and self.connection_id is not None:\n _dict['connection_id'] = self.connection_id\n if hasattr(self, 'srchostname') and self.srchostname is not None:\n _dict['srchostname'] = self.srchostname\n if hasattr(self, 'srcport') and self.srcport is not None:\n _dict['srcport'] = self.srcport\n if hasattr(self, 'srctype') and self.srctype is not None:\n _dict['srctype'] = self.srctype\n if hasattr(self, 'usr') and self.usr is not None:\n _dict['usr'] = self.usr\n if hasattr(self, 'uri') and self.uri is not None:\n _dict['uri'] = self.uri\n if hasattr(self, 'status') and self.status is not None:\n _dict['status'] = self.status\n if hasattr(self, 'connection_name') and self.connection_name is not None:\n _dict['connection_name'] = self.connection_name\n return _dict\n\n def _to_dict(self):\n \"\"\"Return a json dictionary representing this model.\"\"\"\n return self.to_dict()\n\n def __str__(self) -> str:\n \"\"\"Return a `str` version of this DatasourceConnectionsListDatasourceConnectionsItemDataSourcesItem object.\"\"\"\n return json.dumps(self.to_dict(), indent=2)\n\n def __eq__(self, other: 'DatasourceConnectionsListDatasourceConnectionsItemDataSourcesItem') -> bool:\n \"\"\"Return `true` when self and other are equal, false otherwise.\"\"\"\n if not isinstance(other, self.__class__):\n return False\n return self.__dict__ == other.__dict__\n\n def __ne__(self, other: 'DatasourceConnectionsListDatasourceConnectionsItemDataSourcesItem') -> bool:\n \"\"\"Return `true` when self and other are not equal, false otherwise.\"\"\"\n return not self == other\n\nclass PostDatasourceConnection():\n \"\"\"\n PostDatasourceConnection.\n\n :attr str connection_id: The identifier of data source connection.\n :attr str datasource_type: The type of data source that you want to add.\n :attr str name: The name of data source.\n \"\"\"\n\n def __init__(self,\n connection_id: str,\n datasource_type: str,\n name: str) -> None:\n \"\"\"\n Initialize a PostDatasourceConnection object.\n\n :param str connection_id: The identifier of data source connection.\n :param str datasource_type: The type of data source that you want to add.\n :param str name: The name of data source.\n \"\"\"\n self.connection_id = connection_id\n self.datasource_type = datasource_type\n self.name = name\n\n @classmethod\n def from_dict(cls, _dict: Dict) -> 'PostDatasourceConnection':\n \"\"\"Initialize a PostDatasourceConnection object from a json dictionary.\"\"\"\n args = {}\n if 'connection_id' in _dict:\n args['connection_id'] = _dict.get('connection_id')\n else:\n raise ValueError('Required property \\'connection_id\\' not present in PostDatasourceConnection JSON')\n if 'datasource_type' in _dict:\n args['datasource_type'] = _dict.get('datasource_type')\n else:\n raise ValueError('Required property \\'datasource_type\\' not present in PostDatasourceConnection JSON')\n if 'name' in _dict:\n args['name'] = _dict.get('name')\n else:\n raise ValueError('Required property \\'name\\' not present in PostDatasourceConnection JSON')\n return cls(**args)\n\n @classmethod\n def _from_dict(cls, _dict):\n \"\"\"Initialize a PostDatasourceConnection object from a json dictionary.\"\"\"\n return cls.from_dict(_dict)\n\n def to_dict(self) -> Dict:\n \"\"\"Return a json dictionary representing this model.\"\"\"\n _dict = {}\n if hasattr(self, 'connection_id') and self.connection_id is not None:\n _dict['connection_id'] = self.connection_id\n if hasattr(self, 'datasource_type') and self.datasource_type is not None:\n _dict['datasource_type'] = self.datasource_type\n if hasattr(self, 'name') and self.name is not None:\n _dict['name'] = self.name\n return _dict\n\n def _to_dict(self):\n \"\"\"Return a json dictionary representing this model.\"\"\"\n return self.to_dict()\n\n def __str__(self) -> str:\n \"\"\"Return a `str` version of this PostDatasourceConnection object.\"\"\"\n return json.dumps(self.to_dict(), indent=2)\n\n def __eq__(self, other: 'PostDatasourceConnection') -> bool:\n \"\"\"Return `true` when self and other are equal, false otherwise.\"\"\"\n if not isinstance(other, self.__class__):\n return False\n return self.__dict__ == other.__dict__\n\n def __ne__(self, other: 'PostDatasourceConnection') -> bool:\n \"\"\"Return `true` when self and other are not equal, false otherwise.\"\"\"\n return not self == other\n\nclass PostDatasourceConnectionParametersProperties():\n \"\"\"\n PostDatasourceConnectionParametersProperties.\n\n :attr str access_token: (optional)\n :attr str account_name: (optional)\n :attr str api_key: (optional)\n :attr str auth_type: (optional)\n :attr str client_id: (optional)\n :attr str client_secret: (optional)\n :attr str collection: (optional)\n :attr str credentials: (optional)\n :attr str database: (optional)\n :attr str host: (optional)\n :attr str http_path: (optional)\n :attr str jar_uris: (optional)\n :attr str jdbc_driver: (optional)\n :attr str jdbc_url: (optional)\n :attr str password: (optional)\n :attr str port: (optional)\n :attr str project_id: (optional)\n :attr str properties: (optional)\n :attr str refresh_token: (optional)\n :attr str role: (optional)\n :attr str sap_gateway_url: (optional)\n :attr str server: (optional)\n :attr str service_name: (optional)\n :attr str sid: (optional)\n :attr str ssl: (optional)\n :attr str ssl_certificate: (optional)\n :attr str ssl_certificate_host: (optional)\n :attr str ssl_certificate_validation: (optional)\n :attr str username: (optional)\n :attr str warehouse: (optional)\n \"\"\"\n\n def __init__(self,\n *,\n access_token: str = None,\n account_name: str = None,\n api_key: str = None,\n auth_type: str = None,\n client_id: str = None,\n client_secret: str = None,\n collection: str = None,\n credentials: str = None,\n database: str = None,\n host: str = None,\n http_path: str = None,\n jar_uris: str = None,\n jdbc_driver: str = None,\n jdbc_url: str = None,\n password: str = None,\n port: str = None,\n project_id: str = None,\n properties: str = None,\n refresh_token: str = None,\n role: str = None,\n sap_gateway_url: str = None,\n server: str = None,\n service_name: str = None,\n sid: str = None,\n ssl: str = None,\n ssl_certificate: str = None,\n ssl_certificate_host: str = None,\n ssl_certificate_validation: str = None,\n username: str = None,\n warehouse: str = None) -> None:\n \"\"\"\n Initialize a PostDatasourceConnectionParametersProperties object.\n\n :param str access_token: (optional)\n :param str account_name: (optional)\n :param str api_key: (optional)\n :param str auth_type: (optional)\n :param str client_id: (optional)\n :param str client_secret: (optional)\n :param str collection: (optional)\n :param str credentials: (optional)\n :param str database: (optional)\n :param str host: (optional)\n :param str http_path: (optional)\n :param str jar_uris: (optional)\n :param str jdbc_driver: (optional)\n :param str jdbc_url: (optional)\n :param str password: (optional)\n :param str port: (optional)\n :param str project_id: (optional)\n :param str properties: (optional)\n :param str refresh_token: (optional)\n :param str role: (optional)\n :param str sap_gateway_url: (optional)\n :param str server: (optional)\n :param str service_name: (optional)\n :param str sid: (optional)\n :param str ssl: (optional)\n :param str ssl_certificate: (optional)\n :param str ssl_certificate_host: (optional)\n :param str ssl_certificate_validation: (optional)\n :param str username: (optional)\n :param str warehouse: (optional)\n \"\"\"\n self.access_token = access_token\n self.account_name = account_name\n self.api_key = api_key\n self.auth_type = auth_type\n self.client_id = client_id\n self.client_secret = client_secret\n self.collection = collection\n self.credentials = credentials\n self.database = database\n self.host = host\n self.http_path = http_path\n self.jar_uris = jar_uris\n self.jdbc_driver = jdbc_driver\n self.jdbc_url = jdbc_url\n self.password = password\n self.port = port\n self.project_id = project_id\n self.properties = properties\n self.refresh_token = refresh_token\n self.role = role\n self.sap_gateway_url = sap_gateway_url\n self.server = server\n self.service_name = service_name\n self.sid = sid\n self.ssl = ssl\n self.ssl_certificate = ssl_certificate\n self.ssl_certificate_host = ssl_certificate_host\n self.ssl_certificate_validation = ssl_certificate_validation\n self.username = username\n self.warehouse = warehouse\n\n @classmethod\n def from_dict(cls, _dict: Dict) -> 'PostDatasourceConnectionParametersProperties':\n \"\"\"Initialize a PostDatasourceConnectionParametersProperties object from a json dictionary.\"\"\"\n args = {}\n if 'access_token' in _dict:\n args['access_token'] = _dict.get('access_token')\n if 'account_name' in _dict:\n args['account_name'] = _dict.get('account_name')\n if 'api_key' in _dict:\n args['api_key'] = _dict.get('api_key')\n if 'auth_type' in _dict:\n args['auth_type'] = _dict.get('auth_type')\n if 'client_id' in _dict:\n args['client_id'] = _dict.get('client_id')\n if 'client_secret' in _dict:\n args['client_secret'] = _dict.get('client_secret')\n if 'collection' in _dict:\n args['collection'] = _dict.get('collection')\n if 'credentials' in _dict:\n args['credentials'] = _dict.get('credentials')\n if 'database' in _dict:\n args['database'] = _dict.get('database')\n if 'host' in _dict:\n args['host'] = _dict.get('host')\n if 'http_path' in _dict:\n args['http_path'] = _dict.get('http_path')\n if 'jar_uris' in _dict:\n args['jar_uris'] = _dict.get('jar_uris')\n if 'jdbc_driver' in _dict:\n args['jdbc_driver'] = _dict.get('jdbc_driver')\n if 'jdbc_url' in _dict:\n args['jdbc_url'] = _dict.get('jdbc_url')\n if 'password' in _dict:\n args['password'] = _dict.get('password')\n if 'port' in _dict:\n args['port'] = _dict.get('port')\n if 'project_id' in _dict:\n args['project_id'] = _dict.get('project_id')\n if 'properties' in _dict:\n args['properties'] = _dict.get('properties')\n if 'refresh_token' in _dict:\n args['refresh_token'] = _dict.get('refresh_token')\n if 'role' in _dict:\n args['role'] = _dict.get('role')\n if 'sap_gateway_url' in _dict:\n args['sap_gateway_url'] = _dict.get('sap_gateway_url')\n if 'server' in _dict:\n args['server'] = _dict.get('server')\n if 'service_name' in _dict:\n args['service_name'] = _dict.get('service_name')\n if 'sid' in _dict:\n args['sid'] = _dict.get('sid')\n if 'ssl' in _dict:\n args['ssl'] = _dict.get('ssl')\n if 'ssl_certificate' in _dict:\n args['ssl_certificate'] = _dict.get('ssl_certificate')\n if 'ssl_certificate_host' in _dict:\n args['ssl_certificate_host'] = _dict.get('ssl_certificate_host')\n if 'ssl_certificate_validation' in _dict:\n args['ssl_certificate_validation'] = _dict.get('ssl_certificate_validation')\n if 'username' in _dict:\n args['username'] = _dict.get('username')\n if 'warehouse' in _dict:\n args['warehouse'] = _dict.get('warehouse')\n return cls(**args)\n\n @classmethod\n def _from_dict(cls, _dict):\n \"\"\"Initialize a PostDatasourceConnectionParametersProperties object from a json dictionary.\"\"\"\n return cls.from_dict(_dict)\n\n def to_dict(self) -> Dict:\n \"\"\"Return a json dictionary representing this model.\"\"\"\n _dict = {}\n if hasattr(self, 'access_token') and self.access_token is not None:\n _dict['access_token'] = self.access_token\n if hasattr(self, 'account_name') and self.account_name is not None:\n _dict['account_name'] = self.account_name\n if hasattr(self, 'api_key') and self.api_key is not None:\n _dict['api_key'] = self.api_key\n if hasattr(self, 'auth_type') and self.auth_type is not None:\n _dict['auth_type'] = self.auth_type\n if hasattr(self, 'client_id') and self.client_id is not None:\n _dict['client_id'] = self.client_id\n if hasattr(self, 'client_secret') and self.client_secret is not None:\n _dict['client_secret'] = self.client_secret\n if hasattr(self, 'collection') and self.collection is not None:\n _dict['collection'] = self.collection\n if hasattr(self, 'credentials') and self.credentials is not None:\n _dict['credentials'] = self.credentials\n if hasattr(self, 'database') and self.database is not None:\n _dict['database'] = self.database\n if hasattr(self, 'host') and self.host is not None:\n _dict['host'] = self.host\n if hasattr(self, 'http_path') and self.http_path is not None:\n _dict['http_path'] = self.http_path\n if hasattr(self, 'jar_uris') and self.jar_uris is not None:\n _dict['jar_uris'] = self.jar_uris\n if hasattr(self, 'jdbc_driver') and self.jdbc_driver is not None:\n _dict['jdbc_driver'] = self.jdbc_driver\n if hasattr(self, 'jdbc_url') and self.jdbc_url is not None:\n _dict['jdbc_url'] = self.jdbc_url\n if hasattr(self, 'password') and self.password is not None:\n _dict['password'] = self.password\n if hasattr(self, 'port') and self.port is not None:\n _dict['port'] = self.port\n if hasattr(self, 'project_id') and self.project_id is not None:\n _dict['project_id'] = self.project_id\n if hasattr(self, 'properties') and self.properties is not None:\n _dict['properties'] = self.properties\n if hasattr(self, 'refresh_token') and self.refresh_token is not None:\n _dict['refresh_token'] = self.refresh_token\n if hasattr(self, 'role') and self.role is not None:\n _dict['role'] = self.role\n if hasattr(self, 'sap_gateway_url') and self.sap_gateway_url is not None:\n _dict['sap_gateway_url'] = self.sap_gateway_url\n if hasattr(self, 'server') and self.server is not None:\n _dict['server'] = self.server\n if hasattr(self, 'service_name') and self.service_name is not None:\n _dict['service_name'] = self.service_name\n if hasattr(self, 'sid') and self.sid is not None:\n _dict['sid'] = self.sid\n if hasattr(self, 'ssl') and self.ssl is not None:\n _dict['ssl'] = self.ssl\n if hasattr(self, 'ssl_certificate') and self.ssl_certificate is not None:\n _dict['ssl_certificate'] = self.ssl_certificate\n if hasattr(self, 'ssl_certificate_host') and self.ssl_certificate_host is not None:\n _dict['ssl_certificate_host'] = self.ssl_certificate_host\n if hasattr(self, 'ssl_certificate_validation') and self.ssl_certificate_validation is not None:\n _dict['ssl_certificate_validation'] = self.ssl_certificate_validation\n if hasattr(self, 'username') and self.username is not None:\n _dict['username'] = self.username\n if hasattr(self, 'warehouse') and self.warehouse is not None:\n _dict['warehouse'] = self.warehouse\n return _dict\n\n def _to_dict(self):\n \"\"\"Return a json dictionary representing this model.\"\"\"\n return self.to_dict()\n\n def __str__(self) -> str:\n \"\"\"Return a `str` version of this PostDatasourceConnectionParametersProperties object.\"\"\"\n return json.dumps(self.to_dict(), indent=2)\n\n def __eq__(self, other: 'PostDatasourceConnectionParametersProperties') -> bool:\n \"\"\"Return `true` when self and other are equal, false otherwise.\"\"\"\n if not isinstance(other, self.__class__):\n return False\n return self.__dict__ == other.__dict__\n\n def __ne__(self, other: 'PostDatasourceConnectionParametersProperties') -> bool:\n \"\"\"Return `true` when self and other are not equal, false otherwise.\"\"\"\n return not self == other\n\nclass PostPrimaryCatalogParametersAssetsItem():\n \"\"\"\n PostPrimaryCatalogParametersAssetsItem.\n\n :attr str schema:\n :attr str table:\n \"\"\"\n\n def __init__(self,\n schema: str,\n table: str) -> None:\n \"\"\"\n Initialize a PostPrimaryCatalogParametersAssetsItem object.\n\n :param str schema:\n :param str table:\n \"\"\"\n self.schema = schema\n self.table = table\n\n @classmethod\n def from_dict(cls, _dict: Dict) -> 'PostPrimaryCatalogParametersAssetsItem':\n \"\"\"Initialize a PostPrimaryCatalogParametersAssetsItem object from a json dictionary.\"\"\"\n args = {}\n if 'schema' in _dict:\n args['schema'] = _dict.get('schema')\n else:\n raise ValueError('Required property \\'schema\\' not present in PostPrimaryCatalogParametersAssetsItem JSON')\n if 'table' in _dict:\n args['table'] = _dict.get('table')\n else:\n raise ValueError('Required property \\'table\\' not present in PostPrimaryCatalogParametersAssetsItem JSON')\n return cls(**args)\n\n @classmethod\n def _from_dict(cls, _dict):\n \"\"\"Initialize a PostPrimaryCatalogParametersAssetsItem object from a json dictionary.\"\"\"\n return cls.from_dict(_dict)\n\n def to_dict(self) -> Dict:\n \"\"\"Return a json dictionary representing this model.\"\"\"\n _dict = {}\n if hasattr(self, 'schema') and self.schema is not None:\n _dict['schema'] = self.schema\n if hasattr(self, 'table') and self.table is not None:\n _dict['table'] = self.table\n return _dict\n\n def _to_dict(self):\n \"\"\"Return a json dictionary representing this model.\"\"\"\n return self.to_dict()\n\n def __str__(self) -> str:\n \"\"\"Return a `str` version of this PostPrimaryCatalogParametersAssetsItem object.\"\"\"\n return json.dumps(self.to_dict(), indent=2)\n\n def __eq__(self, other: 'PostPrimaryCatalogParametersAssetsItem') -> bool:\n \"\"\"Return `true` when self and other are equal, false otherwise.\"\"\"\n if not isinstance(other, self.__class__):\n return False\n return self.__dict__ == other.__dict__\n\n def __ne__(self, other: 'PostPrimaryCatalogParametersAssetsItem') -> bool:\n \"\"\"Return `true` when self and other are not equal, false otherwise.\"\"\"\n return not self == other\n\nclass PrimaryCatalogInfoEntity():\n \"\"\"\n PrimaryCatalogInfoEntity.\n\n :attr bool auto_profiling: (optional)\n :attr str bss_account_id: (optional)\n :attr int capacity_limit: (optional)\n :attr str description: (optional)\n :attr str generator: (optional)\n :attr bool is_governed: (optional)\n :attr str name: (optional)\n \"\"\"\n\n def __init__(self,\n *,\n auto_profiling: bool = None,\n bss_account_id: str = None,\n capacity_limit: int = None,\n description: str = None,\n generator: str = None,\n is_governed: bool = None,\n name: str = None) -> None:\n \"\"\"\n Initialize a PrimaryCatalogInfoEntity object.\n\n :param bool auto_profiling: (optional)\n :param str bss_account_id: (optional)\n :param int capacity_limit: (optional)\n :param str description: (optional)\n :param str generator: (optional)\n :param bool is_governed: (optional)\n :param str name: (optional)\n \"\"\"\n self.auto_profiling = auto_profiling\n self.bss_account_id = bss_account_id\n self.capacity_limit = capacity_limit\n self.description = description\n self.generator = generator\n self.is_governed = is_governed\n self.name = name\n\n @classmethod\n def from_dict(cls, _dict: Dict) -> 'PrimaryCatalogInfoEntity':\n \"\"\"Initialize a PrimaryCatalogInfoEntity object from a json dictionary.\"\"\"\n args = {}\n if 'auto_profiling' in _dict:\n args['auto_profiling'] = _dict.get('auto_profiling')\n if 'bss_account_id' in _dict:\n args['bss_account_id'] = _dict.get('bss_account_id')\n if 'capacity_limit' in _dict:\n args['capacity_limit'] = _dict.get('capacity_limit')\n if 'description' in _dict:\n args['description'] = _dict.get('description')\n if 'generator' in _dict:\n args['generator'] = _dict.get('generator')\n if 'is_governed' in _dict:\n args['is_governed'] = _dict.get('is_governed')\n if 'name' in _dict:\n args['name'] = _dict.get('name')\n return cls(**args)\n\n @classmethod\n def _from_dict(cls, _dict):\n \"\"\"Initialize a PrimaryCatalogInfoEntity object from a json dictionary.\"\"\"\n return cls.from_dict(_dict)\n\n def to_dict(self) -> Dict:\n \"\"\"Return a json dictionary representing this model.\"\"\"\n _dict = {}\n if hasattr(self, 'auto_profiling') and self.auto_profiling is not None:\n _dict['auto_profiling'] = self.auto_profiling\n if hasattr(self, 'bss_account_id') and self.bss_account_id is not None:\n _dict['bss_account_id'] = self.bss_account_id\n if hasattr(self, 'capacity_limit') and self.capacity_limit is not None:\n _dict['capacity_limit'] = self.capacity_limit\n if hasattr(self, 'description') and self.description is not None:\n _dict['description'] = self.description\n if hasattr(self, 'generator') and self.generator is not None:\n _dict['generator'] = self.generator\n if hasattr(self, 'is_governed') and self.is_governed is not None:\n _dict['is_governed'] = self.is_governed\n if hasattr(self, 'name') and self.name is not None:\n _dict['name'] = self.name\n return _dict\n\n def _to_dict(self):\n \"\"\"Return a json dictionary representing this model.\"\"\"\n return self.to_dict()\n\n def __str__(self) -> str:\n \"\"\"Return a `str` version of this PrimaryCatalogInfoEntity object.\"\"\"\n return json.dumps(self.to_dict(), indent=2)\n\n def __eq__(self, other: 'PrimaryCatalogInfoEntity') -> bool:\n \"\"\"Return `true` when self and other are equal, false otherwise.\"\"\"\n if not isinstance(other, self.__class__):\n return False\n return self.__dict__ == other.__dict__\n\n def __ne__(self, other: 'PrimaryCatalogInfoEntity') -> bool:\n \"\"\"Return `true` when self and other are not equal, false otherwise.\"\"\"\n return not self == other\n\nclass PrimaryCatalogInfoMetadata():\n \"\"\"\n PrimaryCatalogInfoMetadata.\n\n :attr str create_time: (optional)\n :attr str creator_id: (optional)\n :attr str guid: (optional)\n :attr str url: (optional)\n \"\"\"\n\n def __init__(self,\n *,\n create_time: str = None,\n creator_id: str = None,\n guid: str = None,\n url: str = None) -> None:\n \"\"\"\n Initialize a PrimaryCatalogInfoMetadata object.\n\n :param str create_time: (optional)\n :param str creator_id: (optional)\n :param str guid: (optional)\n :param str url: (optional)\n \"\"\"\n self.create_time = create_time\n self.creator_id = creator_id\n self.guid = guid\n self.url = url\n\n @classmethod\n def from_dict(cls, _dict: Dict) -> 'PrimaryCatalogInfoMetadata':\n \"\"\"Initialize a PrimaryCatalogInfoMetadata object from a json dictionary.\"\"\"\n args = {}\n if 'create_time' in _dict:\n args['create_time'] = _dict.get('create_time')\n if 'creator_id' in _dict:\n args['creator_id'] = _dict.get('creator_id')\n if 'guid' in _dict:\n args['guid'] = _dict.get('guid')\n if 'url' in _dict:\n args['url'] = _dict.get('url')\n return cls(**args)\n\n @classmethod\n def _from_dict(cls, _dict):\n \"\"\"Initialize a PrimaryCatalogInfoMetadata object from a json dictionary.\"\"\"\n return cls.from_dict(_dict)\n\n def to_dict(self) -> Dict:\n \"\"\"Return a json dictionary representing this model.\"\"\"\n _dict = {}\n if hasattr(self, 'create_time') and self.create_time is not None:\n _dict['create_time'] = self.create_time\n if hasattr(self, 'creator_id') and self.creator_id is not None:\n _dict['creator_id'] = self.creator_id\n if hasattr(self, 'guid') and self.guid is not None:\n _dict['guid'] = self.guid\n if hasattr(self, 'url') and self.url is not None:\n _dict['url'] = self.url\n return _dict\n\n def _to_dict(self):\n \"\"\"Return a json dictionary representing this model.\"\"\"\n return self.to_dict()\n\n def __str__(self) -> str:\n \"\"\"Return a `str` version of this PrimaryCatalogInfoMetadata object.\"\"\"\n return json.dumps(self.to_dict(), indent=2)\n\n def __eq__(self, other: 'PrimaryCatalogInfoMetadata') -> bool:\n \"\"\"Return `true` when self and other are equal, false otherwise.\"\"\"\n if not isinstance(other, self.__class__):\n return False\n return self.__dict__ == other.__dict__\n\n def __ne__(self, other: 'PrimaryCatalogInfoMetadata') -> bool:\n \"\"\"Return `true` when self and other are not equal, false otherwise.\"\"\"\n return not self == other\n\nclass TablesForRoleResponse():\n \"\"\"\n TablesForRoleResponse.\n\n :attr List[TablesForRoleResponseObjectsItem] objects: (optional)\n \"\"\"\n\n def __init__(self,\n *,\n objects: List['TablesForRoleResponseObjectsItem'] = None) -> None:\n \"\"\"\n Initialize a TablesForRoleResponse object.\n\n :param List[TablesForRoleResponseObjectsItem] objects: (optional)\n \"\"\"\n self.objects = objects\n\n @classmethod\n def from_dict(cls, _dict: Dict) -> 'TablesForRoleResponse':\n \"\"\"Initialize a TablesForRoleResponse object from a json dictionary.\"\"\"\n args = {}\n if 'objects' in _dict:\n args['objects'] = [TablesForRoleResponseObjectsItem.from_dict(x) for x in _dict.get('objects')]\n return cls(**args)\n\n @classmethod\n def _from_dict(cls, _dict):\n \"\"\"Initialize a TablesForRoleResponse object from a json dictionary.\"\"\"\n return cls.from_dict(_dict)\n\n def to_dict(self) -> Dict:\n \"\"\"Return a json dictionary representing this model.\"\"\"\n _dict = {}\n if hasattr(self, 'objects') and self.objects is not None:\n _dict['objects'] = [x.to_dict() for x in self.objects]\n return _dict\n\n def _to_dict(self):\n \"\"\"Return a json dictionary representing this model.\"\"\"\n return self.to_dict()\n\n def __str__(self) -> str:\n \"\"\"Return a `str` version of this TablesForRoleResponse object.\"\"\"\n return json.dumps(self.to_dict(), indent=2)\n\n def __eq__(self, other: 'TablesForRoleResponse') -> bool:\n \"\"\"Return `true` when self and other are equal, false otherwise.\"\"\"\n if not isinstance(other, self.__class__):\n return False\n return self.__dict__ == other.__dict__\n\n def __ne__(self, other: 'TablesForRoleResponse') -> bool:\n \"\"\"Return `true` when self and other are not equal, false otherwise.\"\"\"\n return not self == other\n\nclass TablesForRoleResponseObjectsItem():\n \"\"\"\n TablesForRoleResponseObjectsItem.\n\n :attr str table_name: (optional) The virtualized table name that is granted\n access to role ROLENAME.\n :attr str table_schema: (optional) The SCHEMA of virtualized table that is\n granted access to role ROLENAME.\n \"\"\"\n\n def __init__(self,\n *,\n table_name: str = None,\n table_schema: str = None) -> None:\n \"\"\"\n Initialize a TablesForRoleResponseObjectsItem object.\n\n :param str table_name: (optional) The virtualized table name that is\n granted access to role ROLENAME.\n :param str table_schema: (optional) The SCHEMA of virtualized table that is\n granted access to role ROLENAME.\n \"\"\"\n self.table_name = table_name\n self.table_schema = table_schema\n\n @classmethod\n def from_dict(cls, _dict: Dict) -> 'TablesForRoleResponseObjectsItem':\n \"\"\"Initialize a TablesForRoleResponseObjectsItem object from a json dictionary.\"\"\"\n args = {}\n if 'table_name' in _dict:\n args['table_name'] = _dict.get('table_name')\n if 'table_schema' in _dict:\n args['table_schema'] = _dict.get('table_schema')\n return cls(**args)\n\n @classmethod\n def _from_dict(cls, _dict):\n \"\"\"Initialize a TablesForRoleResponseObjectsItem object from a json dictionary.\"\"\"\n return cls.from_dict(_dict)\n\n def to_dict(self) -> Dict:\n \"\"\"Return a json dictionary representing this model.\"\"\"\n _dict = {}\n if hasattr(self, 'table_name') and self.table_name is not None:\n _dict['table_name'] = self.table_name\n if hasattr(self, 'table_schema') and self.table_schema is not None:\n _dict['table_schema'] = self.table_schema\n return _dict\n\n def _to_dict(self):\n \"\"\"Return a json dictionary representing this model.\"\"\"\n return self.to_dict()\n\n def __str__(self) -> str:\n \"\"\"Return a `str` version of this TablesForRoleResponseObjectsItem object.\"\"\"\n return json.dumps(self.to_dict(), indent=2)\n\n def __eq__(self, other: 'TablesForRoleResponseObjectsItem') -> bool:\n \"\"\"Return `true` when self and other are equal, false otherwise.\"\"\"\n if not isinstance(other, self.__class__):\n return False\n return self.__dict__ == other.__dict__\n\n def __ne__(self, other: 'TablesForRoleResponseObjectsItem') -> bool:\n \"\"\"Return `true` when self and other are not equal, false otherwise.\"\"\"\n return not self == other\n\nclass TurnOnPolicyV2Response():\n \"\"\"\n TurnOnPolicyV2Response.\n\n :attr str status:\n \"\"\"\n\n def __init__(self,\n status: str) -> None:\n \"\"\"\n Initialize a TurnOnPolicyV2Response object.\n\n :param str status:\n \"\"\"\n self.status = status\n\n @classmethod\n def from_dict(cls, _dict: Dict) -> 'TurnOnPolicyV2Response':\n \"\"\"Initialize a TurnOnPolicyV2Response object from a json dictionary.\"\"\"\n args = {}\n if 'status' in _dict:\n args['status'] = _dict.get('status')\n else:\n raise ValueError('Required property \\'status\\' not present in TurnOnPolicyV2Response JSON')\n return cls(**args)\n\n @classmethod\n def _from_dict(cls, _dict):\n \"\"\"Initialize a TurnOnPolicyV2Response object from a json dictionary.\"\"\"\n return cls.from_dict(_dict)\n\n def to_dict(self) -> Dict:\n \"\"\"Return a json dictionary representing this model.\"\"\"\n _dict = {}\n if hasattr(self, 'status') and self.status is not None:\n _dict['status'] = self.status\n return _dict\n\n def _to_dict(self):\n \"\"\"Return a json dictionary representing this model.\"\"\"\n return self.to_dict()\n\n def __str__(self) -> str:\n \"\"\"Return a `str` version of this TurnOnPolicyV2Response object.\"\"\"\n return json.dumps(self.to_dict(), indent=2)\n\n def __eq__(self, other: 'TurnOnPolicyV2Response') -> bool:\n \"\"\"Return `true` when self and other are equal, false otherwise.\"\"\"\n if not isinstance(other, self.__class__):\n return False\n return self.__dict__ == other.__dict__\n\n def __ne__(self, other: 'TurnOnPolicyV2Response') -> bool:\n \"\"\"Return `true` when self and other are not equal, false otherwise.\"\"\"\n return not self == other\n\nclass VirtualizeTableParameterSourceTableDefItem():\n \"\"\"\n VirtualizeTableParameterSourceTableDefItem.\n\n :attr str column_name: The name of the column.\n :attr str column_type: The type of the column.\n \"\"\"\n\n def __init__(self,\n column_name: str,\n column_type: str) -> None:\n \"\"\"\n Initialize a VirtualizeTableParameterSourceTableDefItem object.\n\n :param str column_name: The name of the column.\n :param str column_type: The type of the column.\n \"\"\"\n self.column_name = column_name\n self.column_type = column_type\n\n @classmethod\n def from_dict(cls, _dict: Dict) -> 'VirtualizeTableParameterSourceTableDefItem':\n \"\"\"Initialize a VirtualizeTableParameterSourceTableDefItem object from a json dictionary.\"\"\"\n args = {}\n if 'column_name' in _dict:\n args['column_name'] = _dict.get('column_name')\n else:\n raise ValueError('Required property \\'column_name\\' not present in VirtualizeTableParameterSourceTableDefItem JSON')\n if 'column_type' in _dict:\n args['column_type'] = _dict.get('column_type')\n else:\n raise ValueError('Required property \\'column_type\\' not present in VirtualizeTableParameterSourceTableDefItem JSON')\n return cls(**args)\n\n @classmethod\n def _from_dict(cls, _dict):\n \"\"\"Initialize a VirtualizeTableParameterSourceTableDefItem object from a json dictionary.\"\"\"\n return cls.from_dict(_dict)\n\n def to_dict(self) -> Dict:\n \"\"\"Return a json dictionary representing this model.\"\"\"\n _dict = {}\n if hasattr(self, 'column_name') and self.column_name is not None:\n _dict['column_name'] = self.column_name\n if hasattr(self, 'column_type') and self.column_type is not None:\n _dict['column_type'] = self.column_type\n return _dict\n\n def _to_dict(self):\n \"\"\"Return a json dictionary representing this model.\"\"\"\n return self.to_dict()\n\n def __str__(self) -> str:\n \"\"\"Return a `str` version of this VirtualizeTableParameterSourceTableDefItem object.\"\"\"\n return json.dumps(self.to_dict(), indent=2)\n\n def __eq__(self, other: 'VirtualizeTableParameterSourceTableDefItem') -> bool:\n \"\"\"Return `true` when self and other are equal, false otherwise.\"\"\"\n if not isinstance(other, self.__class__):\n return False\n return self.__dict__ == other.__dict__\n\n def __ne__(self, other: 'VirtualizeTableParameterSourceTableDefItem') -> bool:\n \"\"\"Return `true` when self and other are not equal, false otherwise.\"\"\"\n return not self == other\n\nclass VirtualizeTableParameterVirtualTableDefItem():\n \"\"\"\n VirtualizeTableParameterVirtualTableDefItem.\n\n :attr str column_name: The name of the column.\n :attr str column_type: The type of the column.\n \"\"\"\n\n def __init__(self,\n column_name: str,\n column_type: str) -> None:\n \"\"\"\n Initialize a VirtualizeTableParameterVirtualTableDefItem object.\n\n :param str column_name: The name of the column.\n :param str column_type: The type of the column.\n \"\"\"\n self.column_name = column_name\n self.column_type = column_type\n\n @classmethod\n def from_dict(cls, _dict: Dict) -> 'VirtualizeTableParameterVirtualTableDefItem':\n \"\"\"Initialize a VirtualizeTableParameterVirtualTableDefItem object from a json dictionary.\"\"\"\n args = {}\n if 'column_name' in _dict:\n args['column_name'] = _dict.get('column_name')\n else:\n raise ValueError('Required property \\'column_name\\' not present in VirtualizeTableParameterVirtualTableDefItem JSON')\n if 'column_type' in _dict:\n args['column_type'] = _dict.get('column_type')\n else:\n raise ValueError('Required property \\'column_type\\' not present in VirtualizeTableParameterVirtualTableDefItem JSON')\n return cls(**args)\n\n @classmethod\n def _from_dict(cls, _dict):\n \"\"\"Initialize a VirtualizeTableParameterVirtualTableDefItem object from a json dictionary.\"\"\"\n return cls.from_dict(_dict)\n\n def to_dict(self) -> Dict:\n \"\"\"Return a json dictionary representing this model.\"\"\"\n _dict = {}\n if hasattr(self, 'column_name') and self.column_name is not None:\n _dict['column_name'] = self.column_name\n if hasattr(self, 'column_type') and self.column_type is not None:\n _dict['column_type'] = self.column_type\n return _dict\n\n def _to_dict(self):\n \"\"\"Return a json dictionary representing this model.\"\"\"\n return self.to_dict()\n\n def __str__(self) -> str:\n \"\"\"Return a `str` version of this VirtualizeTableParameterVirtualTableDefItem object.\"\"\"\n return json.dumps(self.to_dict(), indent=2)\n\n def __eq__(self, other: 'VirtualizeTableParameterVirtualTableDefItem') -> bool:\n \"\"\"Return `true` when self and other are equal, false otherwise.\"\"\"\n if not isinstance(other, self.__class__):\n return False\n return self.__dict__ == other.__dict__\n\n def __ne__(self, other: 'VirtualizeTableParameterVirtualTableDefItem') -> bool:\n \"\"\"Return `true` when self and other are not equal, false otherwise.\"\"\"\n return not self == other\n\nclass VirtualizeTableResponse():\n \"\"\"\n VirtualizeTableResponse.\n\n :attr str table_name: The name of the table that is virtualized.\n :attr str schema_name: The schema of the table that is virtualized.\n \"\"\"\n\n def __init__(self,\n table_name: str,\n schema_name: str) -> None:\n \"\"\"\n Initialize a VirtualizeTableResponse object.\n\n :param str table_name: The name of the table that is virtualized.\n :param str schema_name: The schema of the table that is virtualized.\n \"\"\"\n self.table_name = table_name\n self.schema_name = schema_name\n\n @classmethod\n def from_dict(cls, _dict: Dict) -> 'VirtualizeTableResponse':\n \"\"\"Initialize a VirtualizeTableResponse object from a json dictionary.\"\"\"\n args = {}\n if 'table_name' in _dict:\n args['table_name'] = _dict.get('table_name')\n else:\n raise ValueError('Required property \\'table_name\\' not present in VirtualizeTableResponse JSON')\n if 'schema_name' in _dict:\n args['schema_name'] = _dict.get('schema_name')\n else:\n raise ValueError('Required property \\'schema_name\\' not present in VirtualizeTableResponse JSON')\n return cls(**args)\n\n @classmethod\n def _from_dict(cls, _dict):\n \"\"\"Initialize a VirtualizeTableResponse object from a json dictionary.\"\"\"\n return cls.from_dict(_dict)\n\n def to_dict(self) -> Dict:\n \"\"\"Return a json dictionary representing this model.\"\"\"\n _dict = {}\n if hasattr(self, 'table_name') and self.table_name is not None:\n _dict['table_name'] = self.table_name\n if hasattr(self, 'schema_name') and self.schema_name is not None:\n _dict['schema_name'] = self.schema_name\n return _dict\n\n def _to_dict(self):\n \"\"\"Return a json dictionary representing this model.\"\"\"\n return self.to_dict()\n\n def __str__(self) -> str:\n \"\"\"Return a `str` version of this VirtualizeTableResponse object.\"\"\"\n return json.dumps(self.to_dict(), indent=2)\n\n def __eq__(self, other: 'VirtualizeTableResponse') -> bool:\n \"\"\"Return `true` when self and other are equal, false otherwise.\"\"\"\n if not isinstance(other, self.__class__):\n return False\n return self.__dict__ == other.__dict__\n\n def __ne__(self, other: 'VirtualizeTableResponse') -> bool:\n \"\"\"Return `true` when self and other are not equal, false otherwise.\"\"\"\n return not self == other\n\nclass CatalogPublishResponse():\n \"\"\"\n CatalogPublishResponse.\n\n :attr List[CatalogPublishResponseDuplicateAssetsItem] duplicate_assets:\n (optional)\n :attr List[CatalogPublishResponseFailedAssetsItem] failed_assets: (optional)\n :attr List[CatalogPublishResponsePublishedAssetsItem] published_assets:\n (optional)\n \"\"\"\n\n def __init__(self,\n *,\n duplicate_assets: List['CatalogPublishResponseDuplicateAssetsItem'] = None,\n failed_assets: List['CatalogPublishResponseFailedAssetsItem'] = None,\n published_assets: List['CatalogPublishResponsePublishedAssetsItem'] = None) -> None:\n \"\"\"\n Initialize a CatalogPublishResponse object.\n\n :param List[CatalogPublishResponseDuplicateAssetsItem] duplicate_assets:\n (optional)\n :param List[CatalogPublishResponseFailedAssetsItem] failed_assets:\n (optional)\n :param List[CatalogPublishResponsePublishedAssetsItem] published_assets:\n (optional)\n \"\"\"\n self.duplicate_assets = duplicate_assets\n self.failed_assets = failed_assets\n self.published_assets = published_assets\n\n @classmethod\n def from_dict(cls, _dict: Dict) -> 'CatalogPublishResponse':\n \"\"\"Initialize a CatalogPublishResponse object from a json dictionary.\"\"\"\n args = {}\n if 'duplicate_assets' in _dict:\n args['duplicate_assets'] = [CatalogPublishResponseDuplicateAssetsItem.from_dict(x) for x in _dict.get('duplicate_assets')]\n if 'failed_assets' in _dict:\n args['failed_assets'] = [CatalogPublishResponseFailedAssetsItem.from_dict(x) for x in _dict.get('failed_assets')]\n if 'published_assets' in _dict:\n args['published_assets'] = [CatalogPublishResponsePublishedAssetsItem.from_dict(x) for x in _dict.get('published_assets')]\n return cls(**args)\n\n @classmethod\n def _from_dict(cls, _dict):\n \"\"\"Initialize a CatalogPublishResponse object from a json dictionary.\"\"\"\n return cls.from_dict(_dict)\n\n def to_dict(self) -> Dict:\n \"\"\"Return a json dictionary representing this model.\"\"\"\n _dict = {}\n if hasattr(self, 'duplicate_assets') and self.duplicate_assets is not None:\n _dict['duplicate_assets'] = [x.to_dict() for x in self.duplicate_assets]\n if hasattr(self, 'failed_assets') and self.failed_assets is not None:\n _dict['failed_assets'] = [x.to_dict() for x in self.failed_assets]\n if hasattr(self, 'published_assets') and self.published_assets is not None:\n _dict['published_assets'] = [x.to_dict() for x in self.published_assets]\n return _dict\n\n def _to_dict(self):\n \"\"\"Return a json dictionary representing this model.\"\"\"\n return self.to_dict()\n\n def __str__(self) -> str:\n \"\"\"Return a `str` version of this CatalogPublishResponse object.\"\"\"\n return json.dumps(self.to_dict(), indent=2)\n\n def __eq__(self, other: 'CatalogPublishResponse') -> bool:\n \"\"\"Return `true` when self and other are equal, false otherwise.\"\"\"\n if not isinstance(other, self.__class__):\n return False\n return self.__dict__ == other.__dict__\n\n def __ne__(self, other: 'CatalogPublishResponse') -> bool:\n \"\"\"Return `true` when self and other are not equal, false otherwise.\"\"\"\n return not self == other\n\nclass PostPrimaryCatalog():\n \"\"\"\n PostPrimaryCatalog.\n\n :attr str guid:\n :attr str name:\n :attr str description:\n \"\"\"\n\n def __init__(self,\n guid: str,\n name: str,\n description: str) -> None:\n \"\"\"\n Initialize a PostPrimaryCatalog object.\n\n :param str guid:\n :param str name:\n :param str description:\n \"\"\"\n self.guid = guid\n self.name = name\n self.description = description\n\n @classmethod\n def from_dict(cls, _dict: Dict) -> 'PostPrimaryCatalog':\n \"\"\"Initialize a PostPrimaryCatalog object from a json dictionary.\"\"\"\n args = {}\n if 'guid' in _dict:\n args['guid'] = _dict.get('guid')\n else:\n raise ValueError('Required property \\'guid\\' not present in PostPrimaryCatalog JSON')\n if 'name' in _dict:\n args['name'] = _dict.get('name')\n else:\n raise ValueError('Required property \\'name\\' not present in PostPrimaryCatalog JSON')\n if 'description' in _dict:\n args['description'] = _dict.get('description')\n else:\n raise ValueError('Required property \\'description\\' not present in PostPrimaryCatalog JSON')\n return cls(**args)\n\n @classmethod\n def _from_dict(cls, _dict):\n \"\"\"Initialize a PostPrimaryCatalog object from a json dictionary.\"\"\"\n return cls.from_dict(_dict)\n\n def to_dict(self) -> Dict:\n \"\"\"Return a json dictionary representing this model.\"\"\"\n _dict = {}\n if hasattr(self, 'guid') and self.guid is not None:\n _dict['guid'] = self.guid\n if hasattr(self, 'name') and self.name is not None:\n _dict['name'] = self.name\n if hasattr(self, 'description') and self.description is not None:\n _dict['description'] = self.description\n return _dict\n\n def _to_dict(self):\n \"\"\"Return a json dictionary representing this model.\"\"\"\n return self.to_dict()\n\n def __str__(self) -> str:\n \"\"\"Return a `str` version of this PostPrimaryCatalog object.\"\"\"\n return json.dumps(self.to_dict(), indent=2)\n\n def __eq__(self, other: 'PostPrimaryCatalog') -> bool:\n \"\"\"Return `true` when self and other are equal, false otherwise.\"\"\"\n if not isinstance(other, self.__class__):\n return False\n return self.__dict__ == other.__dict__\n\n def __ne__(self, other: 'PostPrimaryCatalog') -> bool:\n \"\"\"Return `true` when self and other are not equal, false otherwise.\"\"\"\n return not self == other\n\nclass PrimaryCatalogInfo():\n \"\"\"\n PrimaryCatalogInfo.\n\n :attr PrimaryCatalogInfoEntity entity: (optional)\n :attr str href: (optional)\n :attr PrimaryCatalogInfoMetadata metadata: (optional)\n \"\"\"\n\n def __init__(self,\n *,\n entity: 'PrimaryCatalogInfoEntity' = None,\n href: str = None,\n metadata: 'PrimaryCatalogInfoMetadata' = None) -> None:\n \"\"\"\n Initialize a PrimaryCatalogInfo object.\n\n :param PrimaryCatalogInfoEntity entity: (optional)\n :param str href: (optional)\n :param PrimaryCatalogInfoMetadata metadata: (optional)\n \"\"\"\n self.entity = entity\n self.href = href\n self.metadata = metadata\n\n @classmethod\n def from_dict(cls, _dict: Dict) -> 'PrimaryCatalogInfo':\n \"\"\"Initialize a PrimaryCatalogInfo object from a json dictionary.\"\"\"\n args = {}\n if 'entity' in _dict:\n args['entity'] = PrimaryCatalogInfoEntity.from_dict(_dict.get('entity'))\n if 'href' in _dict:\n args['href'] = _dict.get('href')\n if 'metadata' in _dict:\n args['metadata'] = PrimaryCatalogInfoMetadata.from_dict(_dict.get('metadata'))\n return cls(**args)\n\n @classmethod\n def _from_dict(cls, _dict):\n \"\"\"Initialize a PrimaryCatalogInfo object from a json dictionary.\"\"\"\n return cls.from_dict(_dict)\n\n def to_dict(self) -> Dict:\n \"\"\"Return a json dictionary representing this model.\"\"\"\n _dict = {}\n if hasattr(self, 'entity') and self.entity is not None:\n _dict['entity'] = self.entity.to_dict()\n if hasattr(self, 'href') and self.href is not None:\n _dict['href'] = self.href\n if hasattr(self, 'metadata') and self.metadata is not None:\n _dict['metadata'] = self.metadata.to_dict()\n return _dict\n\n def _to_dict(self):\n \"\"\"Return a json dictionary representing this model.\"\"\"\n return self.to_dict()\n\n def __str__(self) -> str:\n \"\"\"Return a `str` version of this PrimaryCatalogInfo object.\"\"\"\n return json.dumps(self.to_dict(), indent=2)\n\n def __eq__(self, other: 'PrimaryCatalogInfo') -> bool:\n \"\"\"Return `true` when self and other are equal, false otherwise.\"\"\"\n if not isinstance(other, self.__class__):\n return False\n return self.__dict__ == other.__dict__\n\n def __ne__(self, other: 'PrimaryCatalogInfo') -> bool:\n \"\"\"Return `true` when self and other are not equal, false otherwise.\"\"\"\n return not self == other\n","sub_path":"ibm_cloud/data_virtualization_v1.py","file_name":"data_virtualization_v1.py","file_ext":"py","file_size_in_byte":104942,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"626617554","text":"import numpy as np\nimport pandas as pd\n\ndef get_baskets(): \n datasets_path = lambda file_name: f'/Users/stijnvanleeuwen/Desktop/codes/EUR/Ass2/datasets/{file_name}.parquet'\n return pd.read_parquet(datasets_path('baskets')).astype({'week':'uint8', 'customer':'uint','product':'category', 'price':'uint16'}) \n\ndef get_coupons():\n datasets_path = lambda file_name: f'/Users/stijnvanleeuwen/Desktop/codes/EUR/Ass2/datasets/{file_name}.parquet'\n return pd.read_parquet(datasets_path('coupons')).astype({'week':'uint8', 'customer':'uint','product':'category', 'discount':'uint8'})\n \ndef get_prediction_index():\n datasets_path = lambda file_name: f'/Users/stijnvanleeuwen/Desktop/codes/EUR/Ass2/datasets/{file_name}.parquet' \n return pd.read_parquet(datasets_path('prediction_index')).astype({'week':'uint8', 'customer':'category','product':'category'}) \n\ndef get_3_files():\n \"\"\"\n Returns baskets, coupons, prediction_index\n \"\"\"\n return get_baskets(), get_coupons(), get_prediction_index()\n \ndef split_4_way(base, target_col, unkwown_week=89):\n train = base[base['week']!=unkwown_week]\n test = base[base['week']==unkwown_week]\n x_train, x_test = train.drop(target_col,axis=1), test.drop(target_col,axis=1)\n y_train, y_test = train[target_col], test[target_col]\n return x_train, y_train, x_test, y_test \n\n\n# ALLLLLL\n\ndef create_base(weeks=range(90), customers=range(2000)):\n products = range(250)\n n_weeks, n_customers, n_products = len(weeks), len(customers), len(products)\n\n base = pd.DataFrame({\n 'week': np.array([[x] * n_products * n_customers for x in weeks]).flatten(),\n 'customer': np.array([[x] * n_products for x in customers] * n_weeks).flatten(),\n 'product': list(range(n_products)) * n_customers * n_weeks\n })\n \n return base\n\n\ndef add_basket_info(base, baskets):\n base = pd.merge(base, baskets, on=['week', 'customer','product'], how='left')\n base['price'] = base['price'].fillna(0).astype(int)\n base['isBought'] = (base['price'] > 0)\n base['basket'] = base['week'].astype(str) + '_' + base['customer'].astype(str)\n return base\n\ndef add_coupon_info(base, baskets, coupons):\n base = pd.merge(base, coupons, on=['week', 'customer','product'], how='left')\n base['discount'] = base['discount'].fillna(0).astype(int)\n base = base.rename(columns={\"discount\": \"dGiven\"})\n base['isGiven'] = (base['dGiven'] > 0)\n\n normal_prices = baskets.groupby('product')['price'].max().values\n base['highestPrice'] = base['product'].apply(lambda x: normal_prices[x])\n base['isUsed'] = ((base['price'] != base['highestPrice']) & (base['price']!=0))\n base.drop('highestPrice', axis=1, inplace=True)\n return base\n\ndef add_categories(base):\n base['category'] = (base['product'] / 10).astype(int)\n return base\n\ndef add_frequencies(base, baskets):\n \n baskets.loc[:,'category'] = (baskets['product'].astype(int) / 10).astype(int)\n n_weeks = baskets['week'].nunique()\n \n prod_probs_df = (\n baskets.groupby(['customer','product'])['week'].count() / n_weeks) \\\n .reset_index() \\\n .rename(columns={'week':'probability'})\n\n cat_probs_df = (\n baskets.groupby(['customer','category'])['week'].count() / n_weeks) \\\n .reset_index() \\\n .rename(columns={'week':'probability'})\n \n base = pd.merge(base, prod_probs_df, on=['customer','product'] ,how='left')\n base = pd.merge(base, cat_probs_df, on=['customer','category'] ,how='left')\n \n base.rename(columns={'probability_x':'p_prod', 'probability_y':'p_cat'},inplace=True)\n \n base[['p_prod','p_cat']] = base[['p_prod','p_cat']].fillna(0)\n \n return base\n\ndef get_rolling_frequencies(base, n_weeks=5, category=False):\n \n rolling_df = pd.DataFrame()\n \n for week_nr in range(n_weeks,89+1):\n\n start = week_nr - n_weeks - 1\n end = week_nr\n\n single_week = (\n base[(start < base['week']) & (base['week'] < end)] \n .groupby(['customer',f\"{'category' if category else 'product'}\"]) \n .agg({'week':'last','isBought':'sum'}) \n .reset_index()\n )\n \n single_week['week'] = single_week['week'] + 1\n single_week['isBought'] = single_week['isBought'] / n_weeks\n rolling_df = pd.concat([rolling_df, single_week])\n \n return rolling_df\n\ndef add_rolling_frequencies(base):\n \n values = [5,10,30]\n prod_names = [f'roll_prod_{value}' for value in values]\n cat_names = [f'roll_cat_{value}' for value in values]\n\n for i, name in enumerate(prod_names):\n rolled = get_rolling_frequencies(base,n_weeks=values[i]).rename(columns={'isBought':name})\n base = pd.merge(base, rolled, on=['week','customer','product'],how='left')\n\n for i, name in enumerate(cat_names):\n rolled = get_rolling_frequencies(base, n_weeks=values[i], category=True).rename(columns={'isBought':name})\n base2 = pd.merge(base, rolled, on=['week','customer','category'],how='left') \n \n base.loc[:,prod_names[0]:] = base2.loc[:,prod_names[0]:].fillna(0) \n \n return base\n\ndef buy_weeks_to_ago(buy_weeks):\n weeks_past = 90\n val = []\n bought = False\n\n for i in range(90):\n if i in buy_weeks:\n weeks_past = 0\n val.append(weeks_past)\n bought = True\n elif(bought==True): \n weeks_past += 1 \n val.append(weeks_past)\n else:\n val.append(90)\n return val\n\n\ndef add_weeks_ago(base):\n \n only_bought = base[base['isBought']==1]\n pairs = only_bought.groupby(['customer','product']).size().reset_index(inplace=False)\n\n all_pairs = pd.DataFrame()\n\n for i in range(len(pairs)):\n customer = pairs.iloc[i,0]\n product = pairs.iloc[i,1]\n \n df = pd.DataFrame({\n 'week':range(90),\n 'customer':customer, \n 'product':product, \n })\n \n buy_weeks = list(only_bought[(only_bought['product']==product) & (only_bought['customer']==customer)]['week'])\n df['weeks_ago'] = buy_weeks_to_ago(buy_weeks)\n all_pairs = pd.concat([all_pairs,df])\n \n base = pd.merge(base, all_pairs, on=['week','customer','product'],how='left').fillna(90)\n \n return base\n\n","sub_path":"code/functions.py","file_name":"functions.py","file_ext":"py","file_size_in_byte":6310,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"178282086","text":"import sys, os\r\nimport numpy as np\r\nimport pdb\r\nimport warnings\r\n\r\ndef load_one_label_seq(path):\r\n npy = np.load(path)\r\n return npy\r\n\r\n\r\ndef load_label_seqs(path, mode, index):#index are generated by gen_index\r\n labels=[]\r\n for i in range(len(index)): #eg index = [(lab,1),(lab,2),(lab,3),...]\r\n loc = index[i][0] #eg lab office house\r\n idx = index[i][1] #eg 1,2,3\r\n labelnpy = os.path.join(path,loc,mode+\"_left\"+str(idx)+'.npy')\r\n labels.append(load_one_label_seq(labelnpy))\r\n #labelnpy = os.path.join(path,loc,mode+\"_right\"+str(idx)+'.npy')\r\n #labels.append(load_one_label_seq(labelnpy))\r\n for i in range(len(index)):\r\n loc = index[i][0]\r\n idx = index[i][1]\r\n #labelnpy = os.path.join(path,loc,mode+\"_left\"+str(idx)+'.npy')\r\n #labels.append(load_one_label_seq(labelnpy))\r\n labelnpy = os.path.join(path,loc,mode+\"_right\"+str(idx)+'.npy')\r\n labels.append(load_one_label_seq(labelnpy))\r\n return labels #left1~3 right1~3\r\n\r\ndef gen_index(setting_index):\r\n train_index=[]\r\n test_index =[]\r\n if setting_index == 0:\r\n #order: \r\n #train : lab1~4 off1~3 house1~3\r\n #test : lab5~8 off4~6 house4~6\r\n for i in range(1,7):\r\n if i <= 3:\r\n train_index.append(('house',i))\r\n else:\r\n test_index.append(('house',i))\r\n for i in range(1,9):\r\n if i <= 4:\r\n train_index.append(('lab',i))\r\n else:\r\n test_index.append(('lab',i))\r\n for i in range(1,7):\r\n if i <= 3:\r\n train_index.append(('office',i))\r\n else:\r\n test_index.append(('office',i))\r\n\r\n elif setting_index == 1:\r\n for i in range(1,9):\r\n train_index.append(('lab',i))\r\n for i in range(1,7):\r\n train_index.append(('office',i))\r\n for i in range(1,7):\r\n test_index.append(('house',i))\r\n else:\r\n raise ValueError ('error setting index')\r\n\r\n return train_index, test_index\r\n\r\n\r\n\r\ndef gen_index_process(index=None, setting_index=None):\r\n if index == None:\r\n if setting_index==None:\r\n raise ValueError('Setting index can not be none')\r\n else:\r\n train_index, test_index = gen_index(setting_index)\r\n return train_index, test_index\r\n \r\n\r\ndef load_train_labels(path, mode, index=None, setting_index=None):\r\n if index == None:\r\n index,_ = gen_index_process(index,setting_index)\r\n else:\r\n if setting_index != None:\r\n warnings.warn('setting_index has no effect when given particular index')\r\n labels = load_label_seqs(path, mode, index)\r\n return labels\r\n\r\ndef load_test_labels(path, mode, index=None, setting_index=None):\r\n if index == None:\r\n _,index = gen_index_process(index,setting_index)\r\n else:\r\n if setting_index != None:\r\n warnings.warn('setting_index has no effect when given particular index')\r\n labels = load_label_seqs(path, mode, index)\r\n return labels\r\n\r\n\r\ndef load_all_labels(path, mode, setting_index):\r\n train_index, test_index = gen_index(setting_index)\r\n train_labels = load_train_labels(path, mode,train_index)\r\n test_labels = load_train_labels(path, mode,test_index)\r\n return train_labels, test_labels","sub_path":"data.py","file_name":"data.py","file_ext":"py","file_size_in_byte":3367,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"154564138","text":"# The merger allows you to combine multiple JSON objects into one while maintaining a valid JSON structure.\nimport os\nimport json\n\n# Set global variables.\ninputFiles = []\ntweets = []\n\n# Get an array of all file names in a certain directory.\nfor f in os.listdir(os.getcwd() + '/test-data'):\n inputFiles.append('test-data/' + f)\n\n# Open each file path from the array and store the files contents in a variable (loads).\nfor eachFile in inputFiles:\n with open(eachFile, encoding='UTF-8') as inputData:\n tweets = json.loads(inputData.read())\n\n # Append JSON to a file (dumps) and add a comma to make it valid JSON.\n with open('test-data.json', 'a+') as outputFile:\n for eachTweet in tweets:\n outputFile.write(json.dumps(eachTweet, indent=2))\n outputFile.write(',')\n\n# After this is done, add opening and closing brackets to the entire file. \n","sub_path":"twitter-merger-v3.py","file_name":"twitter-merger-v3.py","file_ext":"py","file_size_in_byte":885,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"148097865","text":"import webapp2\n\nurl = 'http://grooveshark.com'\nhtml5_url = 'http://html5.grooveshark.com'\nimport urllib2\n\n\nclass MainHandler(webapp2.RequestHandler):\n def get(self):\n #if not self.request.headers.get('Origin'):\n # return self.response.out.write('')\n self.response.headers['Access-Control-Allow-Origin'] = '*'\n self.response.headers['Access-Control-Allow-Headers'] = 'Content-Type'\n \n #proxy = urllib2.ProxyHandler({'http': 'IP:PORT'})\n #opener = urllib2.build_opener(proxy)\n \n opener = urllib2.build_opener()\n urllib2.install_opener(opener)\n \n # submit the client headers, so that the request isn't denied\n for h in ['User-Agent', 'Accept-Language', 'Accept']:\n opener.addheaders = [(h, str(self.request.headers[h]))]\n\n conn = urllib2.urlopen(html5_url if self.request.get('html5') == \"true\" else url)\n html = conn.read()\n\n self.response.out.write(html)\n","sub_path":"gae/handlers.py","file_name":"handlers.py","file_ext":"py","file_size_in_byte":983,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"363774321","text":"import numpy as np\nimport scipy.misc as smp\n\ndata = np.zeros( (512, 512, 3), dtype=np.uint8)\n\ndata[254,254] = [254,0,0]\ndata[254,255] = [0,0,255]\n\nimg = smp.toimage( data )\n\nimg.show()\n\n","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":186,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"79033571","text":"#-*- coding:utf-8 -*-\r\nclass zz91news:\r\n def __init__ (self):\r\n self.dbn=dbn\r\n #获得新闻栏目id列表\r\n def getcolumnid(self):\r\n sql='select id,typename,keywords from dede_arctype where reid=184 order by sortrank limit 0,20'\r\n resultlist=self.dbn.fetchalldb(sql)\r\n listall=[]\r\n for result in resultlist:\r\n listall.append(result[0])\r\n return listall\r\n def delnews(self,id):\r\n sql='delete from dede_arctiny where id=%s'\r\n self.dbn.updatetodb(sql,id)\r\n sql='delete from dede_archives where id=%s'\r\n self.dbn.updatetodb(sql,id)\r\n sql='delete from dede_addonarticle where aid=%s'\r\n self.dbn.updatetodb(sql,id)\r\n def delnewstype(self,id):\r\n sql='delete from dede_arctype where id=%s'\r\n self.dbn.updatetodb(sql,id)\r\n def updatetype(self,typename,sortrank,typeid):\r\n sql='update dede_arctype set typename=%s,sortrank=%s where id=%s'\r\n self.dbn.updatetodb(sql,[typename,sortrank,typeid])\r\n def addtype(self,typename,sortrank,reid,topid):\r\n sql='insert into dede_arctype(typename,sortrank,reid,topid) values(%s,%s,%s,%s)'\r\n self.dbn.updatetodb(sql,[typename,sortrank,reid,topid])\r\n def updatenews(self,title,shorttitle,litpic,click,writer,typeid,typeid2,body,id):\r\n sql='update dede_archives set title=%s,shorttitle=%s,litpic=%s,click=%s,writer=%s,typeid=%s,typeid2=%s where id=%s'\r\n self.dbn.updatetodb(sql,[title,shorttitle,litpic,click,writer,typeid,typeid2,id])\r\n sql1='update dede_addonarticle set body=%s where aid=%s'\r\n self.dbn.updatetodb(sql1,[body,id])\r\n def quickupdate(self,strattlist,title,keywords,shorttitle,id):\r\n sql='update dede_archives set flag=%s,title=%s,keywords=%s,shorttitle=%s where id=%s'\r\n self.dbn.updatetodb(sql,[strattlist,title,keywords,shorttitle,id])\r\n def addnews(self,title,shorttitle,litpic,click,writer,typeid,typeid2,body,pubdate):\r\n sortrank=int(time.time())\r\n sql='insert into dede_arctiny(typeid,typeid2,mid,senddate,sortrank) values(%s,%s,%s,%s,%s)'\r\n self.dbn.updatetodb(sql,[typeid,typeid2,1,sortrank,sortrank])\r\n sql2='select id from dede_arctiny where sortrank=%s'\r\n result=self.dbn.fetchonedb(sql2,sortrank)\r\n if result:\r\n id=result[0]\r\n sql3='insert into dede_archives(id,title,shorttitle,litpic,click,writer,typeid,typeid2,pubdate,sortrank) values(%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)'\r\n self.dbn.updatetodb(sql3,[id,title,shorttitle,litpic,click,writer,typeid,typeid2,pubdate,sortrank])\r\n sql4='insert into dede_addonarticle(aid,body) values(%s,%s)'\r\n self.dbn.updatetodb(sql4,[id,body])\r\n \r\n #----资讯列表(搜索引擎)\r\n def getnewslist(self,keywords=\"\",frompageCount=\"\",limitNum=\"\",typeid=\"\",typeid2=\"\",allnum=\"\",arg='',flag='',type='',MATCH=\"\",num=\"\",has_txt=\"\",sortby='',company_id='',hot=''):\r\n# if keywords:\r\n# keywords=keywords.upper()\r\n# if '%' in keywords:\r\n# keywords=keywords.replace('%','%%')\r\n news=SPHINXCONFIG['name']['news']['name']\r\n serverid=SPHINXCONFIG['name']['news']['serverid']\r\n port=SPHINXCONFIG['name']['news']['port']\r\n cl = SphinxClient()\r\n cl.SetServer ( serverid, port )\r\n if MATCH!=\"\":\r\n cl.SetMatchMode ( SPH_MATCH_ANY )\r\n else:\r\n cl.SetMatchMode ( SPH_MATCH_BOOLEAN )\r\n cl.SetFilter('typeid',[392],exclude=1)\r\n if company_id:\r\n #我的关注\r\n myguanzhu=self.getmyguanzhu(company_id)\r\n if myguanzhu:\r\n typeid=[]\r\n for l in myguanzhu:\r\n typeid.append(l['typeid'])\r\n cl.SetFilter('typeid',typeid)\r\n else:\r\n if typeid:\r\n cl.SetFilter('typeid',typeid)\r\n if typeid2 and typeid2!=\"\" and typeid2!=[]:\r\n cl.SetFilter('typeid2',typeid2)\r\n flag=1\r\n cl.SetSortMode( SPH_SORT_EXTENDED ,\"click desc\" )\r\n else:\r\n if typeid:\r\n cl.SetFilter('typeid',typeid)\r\n if typeid2 and typeid2!=\"\" and typeid2!=[]:\r\n cl.SetFilter('typeid2',typeid2)\r\n cl.SetFilter('deleted',[0])\r\n if hot:\r\n #一个月内容的热门资讯\r\n today=datetime.date.today() \r\n oneday=datetime.timedelta(days=7) \r\n day7=today-oneday\r\n cl.SetFilterRange('pubdate',date_to_int(day7),date_to_int(today))\r\n if MATCH!=\"\":\r\n cl.SetSortMode( SPH_SORT_EXTENDED ,'@weight DESC,pubdate desc' )\r\n else:\r\n if sortby:\r\n cl.SetSortMode( SPH_SORT_EXTENDED ,sortby )\r\n else:\r\n cl.SetSortMode( SPH_SORT_ATTR_DESC ,'pubdate' )\r\n if num:\r\n cl.SetLimits (0,num,num)\r\n else:\r\n if (allnum):\r\n cl.SetLimits (frompageCount,limitNum,allnum)\r\n else:\r\n cl.SetLimits (frompageCount,limitNum)\r\n if (keywords):\r\n if flag:\r\n res = cl.Query ('@(title,description,typename,typename1) '+keywords+'&@(flag) \"p\"',news)\r\n else:\r\n if arg==1:\r\n res = cl.Query ('@(title,description,typename,typename1) '+keywords,news)\r\n else:\r\n res = cl.Query ('@(title,typename,typename1) '+keywords,news)\r\n else:\r\n if flag:\r\n res = cl.Query ('@(flag) \"p\"',news)\r\n else:\r\n res = cl.Query ('',news)\r\n listall_news=[]\r\n listcount_news=0\r\n numb=0\r\n if res:\r\n if res.has_key('matches'):\r\n tagslist=res['matches']\r\n for match in tagslist:\r\n id=match['id']\r\n content=''\r\n contentall=''\r\n if has_txt:\r\n content=self.getnewcontent(id)\r\n contentall=content\r\n content=subString(filter_tags(content),200)\r\n \r\n attrs=match['attrs']\r\n title=attrs['ptitle']\r\n click=attrs['click']\r\n pubdate=attrs['pubdate']\r\n litpic=attrs['litpic']\r\n goodpost=attrs['goodpost']\r\n typeid=attrs['typeid']\r\n newsurl=self.get_newstype(typeid=typeid)\r\n weburl=\"\"\r\n if newsurl:\r\n weburl=\"/news/\"+newsurl[\"url\"]+\"/\"+str(id)+\".html\"\r\n else:\r\n weburl=\"/news/search/\"+str(id)+\".html\"\r\n imgurl=''\r\n litpic=None\r\n if not litpic:\r\n imgurl=self.get_img_url(contentall)\r\n if imgurl:\r\n litpic=imgurl[0]\r\n if litpic:\r\n if \"zz91.com\" not in litpic and \"http\" not in litpic:\r\n litpic=litpic.replace(\"uploads/uploads/\",\"\")\r\n litpic=\"http://imgnews.zz91.com\"+litpic\r\n if litpic:\r\n has_pic=1\r\n else: \r\n litpic=\"http://img0.zz91.com/front/images/global/noimage.gif\"\r\n has_pic=''\r\n #litpic=''\r\n pubdate1=time.strftime('%m-%d', time.localtime(pubdate))\r\n pubdate2=time.strftime('%Y-%m-%d', time.localtime(pubdate))\r\n title=title.replace(' ','')\r\n numb+=1\r\n #收藏数\r\n favoritecount=self.getfavoritecount(id)\r\n dianzhancount=self.getzhancount(id)\r\n list1={'typeid':typeid,'favoritecount':favoritecount,'title':title,'click':click,'id':id,'pubdate1':pubdate1,'pubdate':pubdate2,'weburl':weburl,'litpic':litpic,'has_pic':has_pic,'content':content,'goodpost':dianzhancount}\r\n if keywords:\r\n listall_news.append(list1)\r\n if keywords.upper() in title.upper() or arg==1 or arg==2:\r\n title=search_strong(keywords,title)\r\n list1['title']=title\r\n else:\r\n listall_news.append(list1)\r\n if limitNum==1 or num==1:\r\n return list1\r\n listcount_news=res['total_found']\r\n if num:\r\n return listall_news\r\n else:\r\n return {'list':listall_news,'count':listcount_news}\r\n def getsubcontent(self,id,len):\r\n sql='select description from dede_archives where id=%s'\r\n result=self.dbn.fetchonedb(sql,[id])\r\n if result:\r\n body=result[0]\r\n return body[:len]\r\n #是否收藏\r\n def isfavorite(self,content_id,favorite_type_code,company_id):\r\n if content_id and favorite_type_code and company_id:\r\n sql=\"select id from myfavorite where favorite_type_code=%s and content_id=%s and company_id=%s\"\r\n clist=dbc.fetchonedb(sql,[favorite_type_code,content_id,company_id])\r\n if clist:\r\n return 1\r\n else:\r\n return 0\r\n else:\r\n return 0\r\n #我的收藏夹\r\n def myfavorite(self,company_id,frompageCount=\"\",limitNum=\"\"):\r\n sql=\"select content_id from myfavorite where company_id=%s and favorite_type_code=%s order by gmt_created desc limit \"+str(frompageCount)+','+str(limitNum)\r\n mlist=dbc.fetchalldb(sql,[company_id,'10091012'])\r\n listall=[]\r\n for list in mlist:\r\n id=list[0]\r\n list=self.getnewsdetail(id)\r\n list['body']=''\r\n list['content']=list['minbody']\r\n list['isfavorite']=1\r\n #ll={'id':list['id'],'conent':list['minbody'],'title':list['title'],'weburl':list['weburl']}\r\n listall.append(list)\r\n return listall\r\n #----获取资讯url\r\n def get_newstype(self,id='',typeid=''):\r\n \r\n if id:\r\n #catelist=cache.get(\"newstype\"+str(id))\r\n #if catelist:\r\n # return catelist\r\n sql='select typeid,typeid2 from dede_archives where id=%s'\r\n result=self.dbn.fetchonedb(sql,[id])\r\n if result:\r\n typeid=result[0]\r\n typeid2=result[1]\r\n else:\r\n typeid2=\"0\"\r\n sql2='select typename,keywords from dede_arctype where id=%s'\r\n result2=self.dbn.fetchonedb(sql2,[typeid])\r\n if result2:\r\n url1=result2[1]\r\n \r\n if url1==\"guonei\":\r\n url1=\"cjxw\"\r\n if url1==\"guoji\":\r\n url1=\"cjxw\"\r\n if url1==\"hangye\":\r\n url1=\"hydt\"\r\n if url1==\"pinlun\":\r\n url1=\"hydt\"\r\n list={'typename':result2[0],'url':url1,'typeid':typeid,'typeid2':typeid2,'url2':'','typename2':''}\r\n if typeid2!='0':\r\n sql3='select keywords,typename from dede_arctype where id=%s'\r\n result3=self.dbn.fetchonedb(sql3,[typeid2])\r\n if result3:\r\n list['url2']=result3[0]\r\n list['typename2']=result3[1]\r\n #cache.set(\"newstype\"+str(id),list,60*60)\r\n return list\r\n #类别名称\r\n def gettypenameid(self,keywords):\r\n sql='select id,typename from dede_arctype where keywords=%s'\r\n result=dbn.fetchonedb(sql,[keywords])\r\n if result:\r\n id=result[0]\r\n typename=result[1]\r\n list={'id':id,'typename':typename}\r\n return list\r\n def get_typetags(self,url):\r\n listall=cache.get(\"news_typetags\"+str(url))\r\n if not catelist:\r\n sql1='select typename from dede_arctype where keywords=%s'\r\n result=self.dbn.fetchonedb(sql1,[url])\r\n listall=[]\r\n if result:\r\n keywords=result[0]\r\n sql='select id,typename from dede_arctype where keywords=%s'\r\n resultlist=self.dbn.fetchalldb(sql,[keywords])\r\n if resultlist:\r\n for result in resultlist:\r\n typename=result[1]\r\n list={'id':result[0],'typename':typename,'typename_hex':getjiami(typename),}\r\n listall.append(list)\r\n cache.set(\"news_typetags\"+str(url),listall,60*60)\r\n return listall\r\n def gettypelist(self,frompageCount,limitNum,reid='',keywords='',has_news='',fromnews='',has_txt='',typeid='',typeid2=''):\r\n #获得缓存\r\n zz91news_gettypelist=cache.get(\"zz91news_gettypelist\"+str(reid)+str(keywords)+str(has_news))\r\n if zz91news_gettypelist:\r\n return zz91news_gettypelist \r\n listall=[]\r\n argument=[]\r\n sqlarg=' from dede_arctype '\r\n if reid:\r\n if 'where' in sqlarg:\r\n sqlarg+=' and reid=%s'\r\n else:\r\n sqlarg+=' where reid=%s'\r\n argument.append(reid)\r\n if keywords:\r\n if 'where' in sqlarg:\r\n sqlarg+=' and keywords=%s'\r\n else:\r\n sqlarg+=' where keywords=%s'\r\n argument.append(keywords)\r\n sql='select id,typename,sortrank,keywords'+sqlarg\r\n sql+=' order by sortrank,id limit '+str(frompageCount)+','+str(limitNum)\r\n resultlist=self.dbn.fetchalldb(sql,argument)\r\n for result in resultlist:\r\n id=result[0]\r\n nexttype=self.getnexttype(id)\r\n typename=result[1]\r\n typename_hex=''\r\n if typename:\r\n typename_hex=getjiami(typename)\r\n sortrank=result[2]\r\n keywords=result[3]\r\n newslist=[]\r\n if has_news:\r\n if reid==183:\r\n typeid=typeid\r\n typeid2=id\r\n# typeid=[]\r\n else:\r\n typeid=id\r\n typeid2=typeid2\r\n if fromnews:\r\n newslist=self.get_news_all(frompageCount=fromnews,limitNum=has_news,typeid=typeid,typeid2=typeid2,has_txt=has_txt)['list']\r\n else:\r\n newslist=self.get_news_all(frompageCount=0,limitNum=has_news,typeid=typeid,typeid2=typeid2,has_txt=has_txt)\r\n list={'id':result[0],'typename':typename,'typename_hex':typename_hex,'sortrank':sortrank,'nexttype':nexttype,'keywords':keywords,'newslist':newslist}\r\n listall.append(list)\r\n #设置缓存\r\n cache.set(\"zz91news_gettypelist\"+str(reid)+str(keywords)+str(has_news),listall,60*10) \r\n return listall\r\n def getnexttype(self,reid):\r\n listall=[]\r\n sql='select id,typename,sortrank from dede_arctype where reid=%s order by sortrank'\r\n resultlist=self.dbn.fetchalldb(sql,[reid])\r\n if resultlist:\r\n for result in resultlist:\r\n typename=result[1]\r\n sortrank=result[2]\r\n list={'id':result[0],'typename':typename,'sortrank':sortrank}\r\n listall.append(list)\r\n return listall\r\n def gettypedetail(self,id):\r\n sql='select id,typename,sortrank from dede_arctype where id=%s'\r\n result=self.dbn.fetchone(sql,[id])\r\n if result:\r\n list={'id':result[0],'typename':result[1],'sortrank':result[2]}\r\n return list\r\n #----资讯列表(数据库)\r\n def get_news_all(self,frompageCount,limitNum,pubdate='',pubdate2='',flag='',title='',typeid='',typeid2='',has_txt='',kwd=''):\r\n #获得缓存\r\n zz91news_get_news_all=cache.get(\"zz91news_get_news_all\"+str(pubdate2)+str(flag)+str(typeid))\r\n zz91news_get_news_all=None\r\n if zz91news_get_news_all:\r\n return zz91news_get_news_all \r\n argument=[]\r\n sql1='select count(0) from dede_archives where id>0'\r\n sql='select id,title,sortrank,click,writer,shorttitle,keywords,litpic,filename,description from dede_archives where id>0'\r\n if pubdate:\r\n argument.append(pubdate)\r\n sql1=sql1+' and senddate>=%s'\r\n sql=sql+' and senddate>=%s'\r\n if pubdate2:\r\n argument.append(pubdate2)\r\n sql1=sql1+' and senddate<=%s'\r\n sql=sql+' and senddate<=%s'\r\n if flag:\r\n if ',' in flag:\r\n sql1=sql1+' and flag=%s'\r\n sql=sql+' and flag=%s'\r\n else:\r\n sql1=sql1+' and find_in_set(%s,flag)'\r\n sql=sql+' and find_in_set(%s,flag)'\r\n argument.append(flag)\r\n if typeid:\r\n argument.append(typeid)\r\n sql1=sql1+' and typeid=%s'\r\n sql=sql+' and typeid=%s'\r\n if typeid2:\r\n argument.append(typeid2)\r\n sql1=sql1+' and typeid2=%s'\r\n sql=sql+' and typeid2=%s'\r\n if title:\r\n# argument.append(title)\r\n sql1=sql1+' and title like \"%'+title+'%\"'\r\n sql=sql+' and title like \"%'+title+'%\"'\r\n sql=sql+' order by id desc'\r\n if limitNum:\r\n sql=sql+' limit '+str(frompageCount)+','+str(limitNum)\r\n count=self.dbn.fetchnumberdb(sql1,argument)\r\n resultlist=self.dbn.fetchalldb(sql,argument)\r\n listall=[]\r\n if resultlist:\r\n js=0\r\n for result in resultlist:\r\n id=result[0]\r\n title=result[1]\r\n title12=title[:12]\r\n title15=title[:15]\r\n title16=title[:16]\r\n title20=title[:20]\r\n intdate=result[2]\r\n click=result[3]\r\n writer=result[4]\r\n shorttitle=result[5]\r\n keywords=result[6]\r\n litpic=result[7]\r\n filename=result[8]\r\n description=result[9]\r\n kwds=''\r\n kwds_hex=''\r\n if kwd and keywords:\r\n kwdslist=keywords.split(',')[:kwd]\r\n if kwd>1:\r\n kwds=','.join(kwdslist)\r\n else:\r\n kwds=kwdslist[0]\r\n kwds_hex=getjiami(kwds)\r\n pubdate=intdate\r\n# pubdate=int_to_str(intdate)\r\n pubdate1=time.strftime('%m-%d', time.localtime(pubdate))\r\n pubdate2=time.strftime('%Y-%m-%d', time.localtime(pubdate))\r\n newsurl=self.get_newstype(id=id)\r\n weburl=\"\"\r\n weburl=\"http://news.zz91.com\"\r\n typeid=''\r\n typeid2=''\r\n typename=''\r\n typename2=''\r\n if newsurl:\r\n typeid=newsurl['typeid']\r\n typename=newsurl['typename']\r\n typeid2=newsurl['typeid2']\r\n if newsurl[\"url2\"]:\r\n typename2=newsurl['typename2']\r\n #weburl+=\"/\"+newsurl[\"url2\"]\r\n #weburl+=\"/\"+newsurl[\"url\"]+\"/newsdetail1\"+str(id)+\".htm\"\r\n weburl=\"/\"+newsurl[\"url\"]+\"/\"+str(id)+\".html\"\r\n content=''\r\n if has_txt:\r\n if description:\r\n content=filter_tags(description)\r\n content=subString(str(content),has_txt)\r\n #content=self.getnewsbody(id,has_txt)\r\n list={'id':id,'intdate':intdate,'pubdate':pubdate,'pubdate1':pubdate1,'pubdate2':pubdate2,'title':title,'title12':title12,'title15':title15,'title16':title16,'title20':title20,'weburl':weburl,'click':click,'writer':writer,'flaglist':'','flagnamestr':'','js':js,'typeid':typeid,'typeid2':typeid2,'typename':typename,'typename2':typename2,'shorttitle':shorttitle,'keywords':keywords,'litpic':litpic,'content':content,'kwds':kwds,'kwds_hex':kwds_hex,'filename':filename}\r\n #if flag:\r\n #list['flaglist']=flaglist\r\n #list['flagnamestr']=flagnamestr\r\n if limitNum==1:\r\n return list\r\n listall.append(list)\r\n js=js+1\r\n #设置缓存\r\n cache.set(\"zz91news_get_news_all\"+str(pubdate2)+str(flag)+str(typeid),listall,60*10) \r\n return {'list':listall,'count':count}\r\n #新闻内容\r\n def getnewsbody(self,id,has_txt):\r\n sql='select description from dede_archives where id=%s'\r\n resultlist=self.dbn.fetchonedb(sql,id)\r\n if resultlist:\r\n content=resultlist[0]\r\n if content:\r\n content=content[:has_txt]\r\n return content\r\n #收藏数\r\n def getfavoritecount(self,id):\r\n sql=\"select count(0) from myfavorite where content_id=%s and favorite_type_code='10091012'\"\r\n result=dbc.fetchonedb(sql,[id])\r\n return result[0]\r\n #点赞数\r\n def getzhancount(self,id):\r\n sql=\"select count(0) from dianzhan where aid=%s\"\r\n result=dbn.fetchonedb(sql,[id])\r\n return result[0]\r\n def getattlist(self):\r\n catelist=cache.get(\"news_attlist\")\r\n if catelist:\r\n return catelist\r\n sql='select sortid,att,attname from dede_arcatt order by sortid'\r\n resultlist=self.dbn.fetchalldb(sql)\r\n listall=[]\r\n if resultlist:\r\n for result in resultlist:\r\n list={'id':result[0],'att':result[1],'attname':result[2]}\r\n listall.append(list)\r\n cache.set(\"news_attlist\",listall,60*60000)\r\n return listall\r\n def getflagname(self,att):\r\n sql='select attname from dede_arcatt where att=%s'\r\n result=self.dbn.fetchonedb(sql,att)\r\n if result:\r\n return result[0]\r\n #新闻内容\r\n def getnewcontent(self,id,nohtml=''):\r\n sql='select body from dede_addonarticle where aid=%s'\r\n result1=self.dbn.fetchonedb(sql,id)\r\n if result1:\r\n body=result1[0]\r\n if nohtml:\r\n body=filter_tags(body)\r\n return body\r\n def getnewsdetail(self,id):\r\n #获得缓存\r\n #zz91news_getnewsdetail=cache.get(\"zz91news_getnewsdetail\"+str(id))\r\n #if zz91news_getnewsdetail:\r\n #return zz91news_getnewsdetail \r\n sql='select body,redirecturl from dede_addonarticle where aid=%s'\r\n result1=self.dbn.fetchonedb(sql,id)\r\n if result1:\r\n body=result1[0]\r\n redirecturl=result1[1]\r\n if redirecturl:\r\n list={'redirecturl':redirecturl}\r\n return list\r\n minbody=filter_tags(body)\r\n minbody=minbody.replace(\" \",\"\").strip().lstrip().rstrip().replace(\" \",\"\")\r\n minbody=subString(minbody,200)\r\n \r\n else:\r\n return ''\r\n sql='select title,typeid,typeid2,flag,litpic,writer,click,shorttitle,pubdate,keywords,goodpost from dede_archives where id=%s'\r\n result=self.dbn.fetchonedb(sql,id)\r\n if result:\r\n title=result[0]\r\n typeid=result[1]\r\n typename=self.gettypename(typeid)\r\n typeid2=str(result[2])\r\n typename2=''\r\n if not typeid2:\r\n typeid2=\"0\"\r\n if typeid2!='0':\r\n typename2=self.gettypename(typeid2)\r\n flag=result[3]\r\n litpic=result[4]\r\n #图片替换url\r\n imgurl=self.get_img_url(body)\r\n if imgurl:\r\n litpic=imgurl[0]\r\n for pp in imgurl:\r\n if \"zz91.com\" not in pp and \"http\" not in pp:\r\n pic=pp.replace(\"uploads/uploads/\",\"\")\r\n pic=\"http://imgnews.zz91.com\"+pic\r\n body=body.replace(pp,pic)\r\n \r\n \r\n if litpic:\r\n if \"zz91.com\" not in litpic and \"http\" not in litpic:\r\n litpic=litpic.replace(\"uploads/uploads/\",\"\")\r\n litpic=\"http://imgnews.zz91.com\"+litpic\r\n if litpic!=\"\" and litpic:\r\n has_pic=1\r\n else: \r\n has_pic=''\r\n writer=result[5]\r\n click=result[6]\r\n shorttitle=result[7]\r\n pubdate=int_to_strall(result[8])\r\n keywords=result[9]\r\n goodpost=result[10]\r\n kwdlist=[]\r\n newsurl=self.get_newstype(typeid=typeid)\r\n weburl=\"\"\r\n if newsurl:\r\n weburl=\"/news/\"+newsurl[\"url\"]+\"/\"+str(id)+\".html\"\r\n else:\r\n weburl=\"/news/search/\"+str(id)+\".html\"\r\n if keywords:\r\n if ',' in keywords:\r\n keywordlist=keywords.split(',')\r\n for kwd in keywordlist:\r\n kwd_hex=getjiami(kwd)\r\n listdir={'kwd_hex':kwd_hex,'kwd_name':kwd}\r\n kwdlist.append(listdir)\r\n else:\r\n kwd_hex=getjiami(keywords)\r\n listdir={'kwd_hex':kwd_hex,'kwd_name':keywords}\r\n kwdlist.append(listdir)\r\n #收藏数\r\n favoritecount=self.getfavoritecount(id)\r\n dianzhancount=self.getzhancount(id)\r\n list={'body':body,'favoritecount':favoritecount,'title':title,'typeid':typeid,'typename':typename,'typeid2':typeid2,'typename2':typename2,'flag':flag,'litpic':litpic,'writer':writer,'click':click,'shorttitle':shorttitle,'pubdate':pubdate,'kwdlist':kwdlist,'goodpost':dianzhancount,'minbody':minbody,'has_pic':has_pic,'weburl':weburl,'id':id,'keywords':keywords}\r\n #设置缓存\r\n cache.set(\"zz91news_getnewsdetail\"+str(id),list,60*10)\r\n return list\r\n def gettypename(self,id):\r\n sql='select typename from dede_arctype where id=%s'\r\n result=self.dbn.fetchonedb(sql,id)\r\n if result:\r\n return result[0]\r\n def gettypenameurl(self,id):\r\n sql='select typename,keywords from dede_arctype where id=%s'\r\n result=self.dbn.fetchonedb(sql,[id])\r\n if result:\r\n listdir={'typename':result[0],'keywords':result[1]}\r\n return listdir\r\n #新闻最终页上一篇下一篇(一期)\r\n def getarticalup(self,id,typeid,typeid2,detail_url):\r\n #获得缓存\r\n zz91news_getarticalup=cache.get(\"zz91news_getarticalup\"+str(id)+str(typeid)+str(typeid2)+str(detail_url))\r\n if zz91news_getarticalup:\r\n return zz91news_getarticalup \r\n sqlt=\"select id,title from dede_archives where typeid=%s and typeid2=%s and id>%s order by id limit 0,1\"\r\n resultu = self.dbn.fetchonedb(sqlt,[typeid,typeid2,id])\r\n if resultu:\r\n idu=resultu[0]\r\n titleu=resultu[1]\r\n titleu=titleu.replace(\" \",\"\")\r\n titleu=titleu[:20]\r\n newsurl=self.get_newstype(idu)\r\n weburl='/'+detail_url+'/newsdetail1'+str(idu)+'.htm'\r\n list={'idu':idu,'titleu':titleu,'weburl':weburl}\r\n #设置缓存\r\n cache.set(\"zz91news_getarticalup\"+str(id)+str(typeid)+str(typeid2)+str(detail_url),list,60*10)\r\n return list\r\n def getarticalnx(self,id,typeid,typeid2,detail_url):\r\n #获得缓存\r\n zz91news_getarticalnx=cache.get(\"zz91news_getarticalnx\"+str(id)+str(typeid)+str(typeid2)+str(detail_url))\r\n if zz91news_getarticalnx:\r\n return zz91news_getarticalnx \r\n sqlt=\"select id,title from dede_archives where typeid=%s and typeid2=%s and id<%s order by id desc limit 0,1\"\r\n resultn = self.dbn.fetchonedb(sqlt,[typeid,typeid2,id])\r\n if resultn:\r\n idn=resultn[0]\r\n titlen=resultn[1]\r\n titlen=titlen.replace(\" \",\"\")\r\n titlen=titlen[:20]\r\n newsurl=self.get_newstype(idn)\r\n weburl='/'+detail_url+'/newsdetail1'+str(idn)+'.htm'\r\n list={'idn':idn,'titlen':titlen,'weburl':weburl}\r\n #设置缓存\r\n cache.set(\"zz91news_getarticalnx\"+str(id)+str(typeid)+str(typeid2)+str(detail_url),list,60*10)\r\n return list\r\n #订阅类别\r\n def getguanzhu(self,company_id=\"\"):\r\n sql=\"select id,typename,typedir from dede_arctype where isdefault=0\"\r\n resultlist=self.dbn.fetchalldb(sql)\r\n listall=[]\r\n for list in resultlist:\r\n id=list[0]\r\n typename=list[1]\r\n typedir=list[2]\r\n myflag=None\r\n if company_id:\r\n sqld=\"select id from myguanzhu where company_id=%s and typeid=%s\"\r\n resultd=self.dbn.fetchonedb(sqld,[company_id,id])\r\n if resultd:\r\n myflag=1\r\n l={'id':id,'typename':typename,'myflag':myflag,'typedir':typedir}\r\n listall.append(l)\r\n if company_id:\r\n sql=\"select id,tags from myguanzhu where typeid=0 and company_id=%s\"\r\n result=self.dbn.fetchalldb(sql,[company_id])\r\n if result:\r\n myflag=1\r\n for list in result:\r\n id=list[0]\r\n typename=list[1]\r\n l={'id':id,'typename':typename,'myflag':myflag,'typedir':''}\r\n listall.append(l)\r\n return listall\r\n #我的关注\r\n def getmyguanzhu(self,company_id=\"\"):\r\n listall=[]\r\n if company_id:\r\n sql=\"select tags,typeid from myguanzhu where company_id=%s order by id asc\"\r\n resultlist=self.dbn.fetchalldb(sql,company_id)\r\n if resultlist:\r\n listall=[]\r\n for result in resultlist:\r\n typename=result[0]\r\n typeid=result[1]\r\n list={'typename':typename,'typeid':typeid}\r\n listall.append(list)\r\n return listall\r\n #微门户关键词\r\n def getcplist(self,keywords,limitcount):\r\n cl = SphinxClient()\r\n cl.SetServer ( SPHINXCONFIG['serverid'], SPHINXCONFIG['port'] )\r\n cl.SetMatchMode ( SPH_MATCH_BOOLEAN )\r\n cl.SetSortMode( SPH_SORT_EXTENDED,\"showcount desc\" )\r\n cl.SetLimits (0,limitcount,limitcount)\r\n keywords=''\r\n if keywords=='':\r\n res = cl.Query ('','daohangkeywords')\r\n else:\r\n res = cl.Query ('@(label) '+keywords,'daohangkeywords')\r\n listall=[]\r\n if res:\r\n if res.has_key('matches'):\r\n tagslist=res['matches']\r\n listall_news=[]\r\n i=1\r\n for match in tagslist:\r\n id=match['id']\r\n attrs=match['attrs']\r\n label=attrs['plabel']\r\n pingyin=attrs['ppinyin']\r\n if pingyin!=\"\":\r\n list={'label':label,'pingyin':pingyin,'i':i}\r\n listall.append(list)\r\n if (i>=4):\r\n i=1\r\n i=i+1\r\n if listall==[]:\r\n res = cl.Query ('','daohangkeywords')\r\n if res:\r\n if res.has_key('matches'):\r\n tagslist=res['matches']\r\n listall_news=[]\r\n for match in tagslist:\r\n id=match['id']\r\n attrs=match['attrs']\r\n label=attrs['plabel']\r\n pingyin=attrs['ppinyin']\r\n if pingyin!=\"\":\r\n list={'label':label,'pingyin':pingyin}\r\n listall.append(list)\r\n return listall\r\n #展会列表\r\n def getzhlist(self,frompageCount,limitNum,searchlist=\"\"):\r\n sqlarg=' from exhibit as a left outer join category as b on a.plate_category_code=b.code left outer join category as c on c.code=a.exhibit_category_code left outer join category as d on a.area_code=d.code where a.id>0'\r\n argument=[]\r\n if searchlist.has_key(\"area_code\"):\r\n area_code=searchlist['area_code']\r\n sqlarg+=' and a.area_code=%s'\r\n argument.append(area_code)\r\n if searchlist.has_key(\"name\"):\r\n name=searchlist['name']\r\n sqlarg+=' and a.name like %s'\r\n argument.append('%'+name+'%')\r\n if searchlist.has_key(\"area\"):\r\n area=searchlist['area']\r\n sqlarg+=' and a.area like %s'\r\n argument.append('%'+area+'%')\r\n if searchlist.has_key(\"plate_category_code\"):\r\n plate_category_code=searchlist['plate_category_code']\r\n sqlarg+=' and a.plate_category_code=%s'\r\n argument.append(plate_category_code)\r\n if searchlist.has_key(\"exhibit_category_code\"):\r\n exhibit_category_code=searchlist['exhibit_category_code']\r\n sqlarg+=' and a.exhibit_category_code=%s'\r\n argument.append(exhibit_category_code)\r\n if searchlist.has_key(\"noexpress\"):\r\n noexpress=searchlist['noexpress']\r\n sqlarg+=' and DATEDIFF(CURDATE(),a.start_time)<=0'\r\n if searchlist.get(\"top\"):\r\n sqlarg+=' and a.hz_categorylist like \"%20121002%\"'\r\n sql1='select count(0)'+sqlarg\r\n sql='select a.id,a.name,a.area_code,a.area,a.start_time,a.end_time,a.plate_category_code,a.exhibit_category_code,a.gmt_created,a.checked,a.tags,b.label as bktypename,c.label as hytypename,d.label as area_name,a.tags,a.allzhuban,a.photo_cover,a.content,a.redircturl '+sqlarg\r\n if searchlist.has_key(\"noexpress\"):\r\n sql+=' order by a.start_time asc limit '+str(frompageCount)+','+str(limitNum)\r\n else:\r\n sql+=' order by a.start_time desc limit '+str(frompageCount)+','+str(limitNum)\r\n if argument:\r\n count=dbc.fetchnumberdb(sql1,argument)\r\n resultlist=dbc.fetchalldb(sql,argument)\r\n else:\r\n count=dbc.fetchnumberdb(sql1)\r\n resultlist=dbc.fetchalldb(sql)\r\n listall=[]\r\n i=1\r\n for result in resultlist:\r\n id=result[0]\r\n name=result[1]\r\n area_code=result[2]\r\n area=result[3]\r\n start_time=formattime(result[4],1)\r\n intstarttime=date_to_int(result[4])\r\n nowint=date_to_int(datetime.datetime.now())\r\n haveday=0\r\n if intstarttime>nowint:\r\n haveday=(intstarttime-nowint)/(3600*24)\r\n end_time=formattime(result[5],1)\r\n plate_category_code=result[6]\r\n exhibit_category_code=result[7]\r\n gmt_created=formattime(result[8],0)\r\n checked=result[9]\r\n bktypename=result[11]\r\n hytypename=result[12]\r\n area_name=result[13]\r\n tags=result[14]\r\n allzhuban=result[15]\r\n photo_cover=result[16]\r\n redircturl=result[18]\r\n imgurl=''\r\n if not photo_cover:\r\n imgurl=self.get_img_url(result[17])\r\n if imgurl:\r\n photo_cover=imgurl[0]\r\n if not photo_cover:\r\n photo_cover='http://img0.zz91.com/front/images/global/noimage.gif'\r\n if area:\r\n area_name=area\r\n if checked==1:\r\n checkvalue='已审'\r\n else:\r\n checkvalue='未审'\r\n hnum=i % 2\r\n i+=1\r\n list={'id':id,'name':name,'area_code':area_code,'area_name':area_name,'tags':tags,'allzhuban':allzhuban,'area':area,'start_time':start_time,'end_time':end_time,'bktypename':bktypename,'hytypename':hytypename,'gmt_created':gmt_created,'checkvalue':checkvalue,'hnum':hnum,'photo_cover':photo_cover,'haveday':haveday,'redircturl':redircturl}\r\n listall.append(list)\r\n return {'list':listall,'count':count}\r\n #获取内容图片\r\n def get_img_url(self,html):#获得图片url\r\n #html=html.lower()\r\n if html:\r\n html=html.replace(\"data-original=\",\"src=\").replace(\"IMG\",'img').replace(\"SRC\",'src').replace(\"data-src\",\"src\")\r\n re_py3=r''\r\n urls_pat3=re.compile(re_py3)\r\n img_url3=re.findall(urls_pat3,html)\r\n if img_url3:\r\n return img_url3\r\n re_py3=r\"\"\r\n urls_pat3=re.compile(re_py3)\r\n img_url3=re.findall(urls_pat3,html)\r\n if img_url3:\r\n return img_url3\r\n re_py3=r''\r\n urls_pat3=re.compile(re_py3)\r\n img_url3=re.findall(urls_pat3,html)\r\n if img_url3:\r\n return img_url3\r\n def getcategorylabel(self,code):\r\n sql=\"select label from category where code=%s\"\r\n result=dbc.fetchonedb(sql,[code])\r\n if result:\r\n return result[0]\r\n else:\r\n return ''","sub_path":"mobile/mobile/func/news_function.py","file_name":"news_function.py","file_ext":"py","file_size_in_byte":37250,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"178110013","text":"#pip install requests-html\n\nfrom requests_html import HTMLSession\nsession = HTMLSession()\n\nurl = \"https://gamingph.com/2019/09/chess-rush-patch-review-new-hero-headreaper-and-guild-system/\"\n\nwith session.get(url) as r:\n\n selector=\"#post-21527 > div.entry\"\n post = r.html.find(selector, first=True)\n\n text = post.text\n text = text.splitlines(True)\n\n text = text[1:-5]\n\n with open(\"python-data-stories.txt\",\"a\") as f:\n f.writelines(text)\n","sub_path":"src/download_sej_article.py","file_name":"download_sej_article.py","file_ext":"py","file_size_in_byte":447,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"515651144","text":"from collections import defaultdict\nfrom utilities import operations as op\n\nR = defaultdict(int)\n\nmodify = {'inc': op['+'], 'dec': op['-']}\n\n\nmax_reg = -float('inf')\n\nfor line in open('data/day8.txt'):\n splited = line.split()\n reg, _p, val, _c = splited[0], splited[1], splited[2], splited[4:]\n if op[_c[1]](R[_c[0]], int(_c[2])): R[reg] = modify[_p](R[reg], int(val))\n \n max_reg = max(max_reg, R[reg])\n\n\n\nprint(max(R.items(), key=lambda x: x[1]))\nprint('max ever : {}'.format(max_reg))\n","sub_path":"day8.py","file_name":"day8.py","file_ext":"py","file_size_in_byte":503,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"496384899","text":"'''\n@name: 2_visualizing_raw_data.py\n@description: Ploting data points on the 2D coordinate\n@author: VPi\n@date: 9th - August - 2017\n'''\n\nimport csv\nimport matplotlib.pyplot as plt\n\n# Variables to store data\nmans_monthly_income = []\ntotal_number_of_gfs = []\n\n# Read data from csv file\nwith open('funny_dataset.csv') as mycsvfile:\n datasets = csv.reader(mycsvfile, delimiter=',')\n \n for data in datasets:\n mans_monthly_income.append(float(data[0]))\n total_number_of_gfs.append(float(data[1]))\n\nplt.figure(1)\nplt.xlim([0, 10500])\nplt.ylim([0, 10])\nplt.xlabel('Monthly income ($)')\nplt.ylabel('The number of girl friends')\nplt.plot(mans_monthly_income, total_number_of_gfs, 'o')\nplt.show()\n","sub_path":"linear_regression/2_visualizing_raw_data.py","file_name":"2_visualizing_raw_data.py","file_ext":"py","file_size_in_byte":709,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"322533741","text":"from pico2d import *\nimport numpy as np\n\nimport game_framework\n\n\nTIME_PER_ACTION = 0.5\nACTION_PER_TIME = 1.0 / TIME_PER_ACTION\n\nFRAMES_PER_ACTION = 7\ndef draw_Map(image, map_x, map_y, Map_type):\n\n x, y = 0, 0\n type = Map_type\n while type > 16:\n type = type - 16\n y += 1\n while type > 1:\n type = type - 1\n x += 1\n image.clip_draw(x * 20, y * 20, 20, 20, map_x * 20, map_y * 20)\n\nclass Grass:\n def __init__(self):\n self.image = load_image('Mdesert.png')\n self.castle_hp_image = load_image('ui\\\\castle_hp.png')\n self.castle_hp = 300\n self.hp_frame = 0\n\n with open('Map.txt', 'r') as self.file:\n self.line = np.loadtxt('Map.txt', delimiter=' ')\n\n def draw(self):\n map_x, map_y = 0, 0\n for i in self.line:\n for j in i:\n draw_Map(self.image, map_x, map_y, j)\n map_x = map_x + 1\n map_x = 0\n map_y = map_y +1\n self.castle_hp_image.clip_draw(int(self.hp_frame) * 393, 0, 393, 90,\n 600 + (300 - self.castle_hp)/2, 20, self.castle_hp, 20)\n\n def update(self):\n self.hp_frame = self.hp_frame + FRAMES_PER_ACTION * ACTION_PER_TIME * game_framework.frame_time\n self.hp_frame = self.hp_frame % 7\n pass\n\n def attacked(self):\n self.castle_hp -= 5\n\n","sub_path":"grass.py","file_name":"grass.py","file_ext":"py","file_size_in_byte":1396,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"236582642","text":"# -*- coding: utf-8 -*-\r\n\r\nimport psutil\r\ndef get_nets():\r\n return psutil.net_io_counters(pernic=True).keys() # 获取网卡名称\r\n\r\ndef get_nets_io(nets=None):\r\n if not nets:\r\n key_info = get_nets() # 获取网卡名称\r\n recv = {}\r\n sent = {}\r\n for key in key_info:\r\n recv.setdefault(key, psutil.net_io_counters(pernic=True).get(key).bytes_recv) # 各网卡接收的字节数\r\n sent.setdefault(key, psutil.net_io_counters(pernic=True).get(key).bytes_sent) # 各网卡发送的字节数\r\n return key_info, recv, sent\r\n\r\ndef get_nets_io_rate(func):\r\n import time\r\n\r\n key_info, old_recv, old_sent = func() # 上一秒收集的数据\r\n\r\n time.sleep(1)\r\n\r\n key_info, now_recv, now_sent = func() # 当前所收集的数据\r\n\r\n net_in = {}\r\n net_out = {}\r\n\r\n for key in key_info:\r\n net_in.setdefault(key, now_recv.get(key) - old_recv.get(key)) # 每秒接收速率\r\n net_out.setdefault(key, now_sent.get(key) - old_sent.get(key)) # 每秒发送速率\r\n # net_in.setdefault(key, round(((now_recv.get(key) - old_recv.get(key)) / 1024), 2)) # 每秒接收速率\r\n # net_out.setdefault(key, round(((now_sent.get(key) - old_sent.get(key)) / 1024), 2)) # 每秒发送速率\r\n\r\n return key_info, net_in, net_out\r\n\r\ndef trans_io(num, unit=1024, places=2):\r\n return round( float(num) / float(unit), places )\r\n\r\nif __name__ == \"__main__\":\r\n key_info, net_in, net_out = get_nets_io_rate(get_nets_io)\r\n # print('-----------------------', key_info, net_in, net_out)\r\n # ['vethed8bd96', 'veth07d0c4d', 'docker0', 'veth22fa1dd', 'veth1e14688', 'ens160', 'veth03abfca', 'vethaf7fd5b',\r\n # 'veth63f726b', 'lo', 'veth88bc1b4', 'br-ed615a0f409e']\r\n # {'vethed8bd96': 0.0, 'veth07d0c4d': 3.0, 'docker0': 0.0,\r\n # 'veth22fa1dd': 1.0, 'veth1e14688': 0.0, 'ens160': 6.0,\r\n # 'veth03abfca': 0.0, 'vethaf7fd5b': 0.0,\r\n # 'veth63f726b': 0.0, 'lo': 0.0, 'veth88bc1b4': 0.0,\r\n # 'br-ed615a0f409e': 0.0}\r\n # {'vethed8bd96': 0.0,\r\n # 'veth07d0c4d': 1.0,\r\n # 'docker0': 0.0,\r\n # 'veth22fa1dd': 3.0,\r\n # 'veth1e14688': 0.0,\r\n # 'ens160': 3.0,\r\n # 'veth03abfca': 0.0,\r\n # 'vethaf7fd5b': 0.0,\r\n # 'veth63f726b': 0.0, 'lo': 0.0,\r\n # 'veth88bc1b4': 0.0,\r\n # 'br-ed615a0f409e': 0.0}\r\n # while 1:\r\n # try:\r\n # key_info, net_in, net_out = get_nets_io_rate(get_nets_io)\r\n #\r\n # for key in key_info:\r\n # print('%s\\nInput:\\t %-5sKB/s\\nOutput:\\t %-5sKB/s\\n' % (key, net_in.get(key), net_out.get(key)))\r\n # except KeyboardInterrupt:\r\n # exit()","sub_path":"app/utils/network.py","file_name":"network.py","file_ext":"py","file_size_in_byte":2642,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"600603762","text":"import json\nfrom copy import copy\n\nfrom flask import current_app\n\nfrom hubserver.app import db, celery_beat_scheduler\nfrom hubserver.app.servers.models import Server\n\n\nclass Job(Server):\n __tablename__ = 'jobs'\n\n STATUS_CACHE_PREFIX = 'job_server_status_'\n\n server_id = db.Column(\n db.Integer,\n db.ForeignKey('servers.id'),\n primary_key=True\n )\n script = db.Column(\n db.String(255),\n nullable=False\n )\n method = db.Column(\n db.String(50),\n nullable=True\n )\n schedule = db.Column(\n db.String(20),\n nullable=True\n )\n auto_restart = db.Column(\n db.Boolean,\n default=True\n )\n\n __mapper_args__ = {\n 'polymorphic_identity': 'j',\n }\n\n def __str__(self):\n return self.name\n\n @property\n def crontab(self):\n return dict(zip(['minute', 'hour', 'day_of_month', 'month_of_year', 'day_of_week'], self.schedule.split()))\n\n @property\n def task_key(self):\n from hubserver.app.tasks import start_server_task\n task_name = start_server_task.name\n return '{0}{1}:{2}'.format(\n current_app.config.get('CELERY_REDIS_SCHEDULER_KEY_PREFIX'),\n task_name, self.hashid\n )\n\n def start(self):\n self.status = self.LAUNCHING\n from hubserver.app.tasks import start_server_task\n task_name = start_server_task.name\n task = {\n 'name': 'schedule job',\n 'enabled': True,\n 'task': task_name,\n 'schedule': self.crontab,\n 'args': [\n self.hashid\n ],\n 'kwargs': {\n 'command': self.environment_type.cmd.format(job=self, script_name_len=len(self.script.split('.')[0])),\n 'restart': {\"Name\": \"on-failure\", \"MaximumRetryCount\": 2} if self.auto_restart else None\n }\n }\n celery_beat_scheduler.set(self.task_key, json.dumps(task))\n self.status = self.RUNNING\n\n def stop(self):\n task = json.loads(celery_beat_scheduler.get(self.task_key).decode('utf8'))\n task['enabled'] = False\n celery_beat_scheduler.set(self.task_key, json.dumps(task))\n self.status = self.STOPPED\n\n def terminate(self):\n task_key = copy(self.task_key)\n super().terminate()\n celery_beat_scheduler.delete(task_key)\n\n def restart(self):\n celery_beat_scheduler.delete(self.task_key)\n self.start()\n","sub_path":"hubserver/app/servers/jobs/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":2474,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"410915218","text":"# Definition for a binary tree node.\n# class TreeNode:\n# def __init__(self, x):\n# self.val = x\n# self.left = None\n# self.right = None\n\nclass Solution:\n def levelOrder(self, root: TreeNode) -> List[List[int]]:\n if not root:\n return []\n\n def helper(out, root, level=0):\n if root is None:\n return out\n if len(out) - 1 < level:\n out.append([])\n out = helper(out, root.left, level + 1)\n out = helper(out, root.right, level + 1)\n out[level].append(root.val)\n return out\n\n return helper([[]], root)","sub_path":"python/leetcode/2019/trees/levelOrder.py","file_name":"levelOrder.py","file_ext":"py","file_size_in_byte":650,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"562263501","text":"# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import, division, print_function\n\nfrom marshmallow import Schema, fields, post_load\n\nfrom polyaxon_schemas.base import BaseConfig, BaseMultiSchema\n\n\nclass BaseOptimizerSchema(Schema):\n learning_rate = fields.Float(allow_none=True)\n decay_type = fields.Str(allow_none=True)\n decay_rate = fields.Float(allow_none=True)\n decay_steps = fields.Int(allow_none=True)\n start_decay_at = fields.Int(allow_none=True)\n stop_decay_at = fields.Int(allow_none=True)\n min_learning_rate = fields.Float(allow_none=True)\n staircase = fields.Bool(allow_none=True)\n global_step = fields.Str(allow_none=True)\n use_locking = fields.Bool(allow_none=True)\n name = fields.Str(allow_none=True)\n\n\nclass BaseOptimizerConfig(BaseConfig):\n REDUCED_ATTRIBUTES = ['name']\n\n def __init__(self,\n learning_rate=0.001,\n decay_type=\"\",\n decay_rate=0.,\n decay_steps=100,\n start_decay_at=0,\n stop_decay_at=1e10,\n min_learning_rate=1e-12,\n staircase=False,\n global_step=None,\n use_locking=False,\n name='optimizer'):\n self.learning_rate = learning_rate\n self.decay_type = decay_type\n self.decay_rate = decay_rate\n self.decay_steps = decay_steps\n self.start_decay_at = start_decay_at\n self.stop_decay_at = stop_decay_at\n self.min_learning_rate = min_learning_rate\n self.staircase = staircase\n self.global_step = global_step\n self.use_locking = use_locking\n self.name = name\n\n\nclass SGDSchema(BaseOptimizerSchema):\n class Meta:\n ordered = True\n\n @post_load\n def make_load(self, data):\n return SGDConfig(**data)\n\n\nclass SGDConfig(BaseOptimizerConfig):\n IDENTIFIER = 'SGD'\n SCHEMA = SGDSchema\n\n def __init__(self, # pylint: disable=useless-super-delegation\n learning_rate=0.01,\n decay_type=\"\",\n decay_rate=0.,\n decay_steps=100,\n start_decay_at=0,\n stop_decay_at=1e10,\n min_learning_rate=1e-12,\n staircase=False,\n global_step=None,\n use_locking=False,\n name='SGD'):\n super(SGDConfig, self).__init__(learning_rate, decay_type, decay_rate, decay_steps,\n start_decay_at, stop_decay_at, min_learning_rate,\n staircase, global_step, use_locking, name)\n\n\nclass MomentumSchema(BaseOptimizerSchema):\n momentum = fields.Float(allow_none=True)\n\n class Meta:\n ordered = True\n\n @post_load\n def make_load(self, data):\n return MomentumConfig(**data)\n\n\nclass MomentumConfig(BaseOptimizerConfig):\n IDENTIFIER = 'Momentum'\n SCHEMA = MomentumSchema\n\n def __init__(self,\n learning_rate=0.001,\n momentum=0.9,\n decay_type=\"\",\n decay_rate=0.,\n decay_steps=10000,\n start_decay_at=0,\n stop_decay_at=1e10,\n min_learning_rate=1e-12,\n staircase=False,\n global_step=None,\n use_locking=False,\n name='Momentum'):\n self.momentum = momentum\n super(MomentumConfig, self).__init__(learning_rate, decay_type, decay_rate, decay_steps,\n start_decay_at, stop_decay_at, min_learning_rate,\n staircase, global_step, use_locking, name)\n\n\nclass NestrovSchema(BaseOptimizerSchema):\n momentum = fields.Float(allow_none=True)\n\n class Meta:\n ordered = True\n\n @post_load\n def make_load(self, data):\n return NestrovConfig(**data)\n\n\nclass NestrovConfig(BaseOptimizerConfig):\n IDENTIFIER = 'Nestrov'\n SCHEMA = NestrovSchema\n\n def __init__(self,\n learning_rate=0.001,\n momentum=0.9,\n decay_type=\"\",\n decay_rate=0.,\n decay_steps=10000,\n start_decay_at=0,\n stop_decay_at=1e10,\n min_learning_rate=1e-12,\n staircase=False,\n use_locking=False,\n global_step=None,\n name='Nestrov'):\n self.momentum = momentum\n super(NestrovConfig, self).__init__(learning_rate, decay_type, decay_rate, decay_steps,\n start_decay_at, stop_decay_at, min_learning_rate,\n staircase, global_step, use_locking, name)\n\n\nclass RMSPropSchema(BaseOptimizerSchema):\n decay = fields.Float(allow_none=True)\n momentum = fields.Float(allow_none=True)\n epsilon = fields.Float(allow_none=True)\n\n class Meta:\n ordered = True\n\n @post_load\n def make_load(self, data):\n return RMSPropConfig(**data)\n\n\nclass RMSPropConfig(BaseOptimizerConfig):\n IDENTIFIER = 'RMSProp'\n SCHEMA = RMSPropSchema\n\n def __init__(self,\n learning_rate=0.001,\n decay=0.9,\n momentum=0.0,\n epsilon=1e-10,\n decay_type=\"\",\n decay_rate=0.,\n decay_steps=10000,\n start_decay_at=0,\n stop_decay_at=1e10,\n min_learning_rate=1e-12,\n staircase=False,\n global_step=None,\n use_locking=False,\n name='RMSProp'):\n self.decay = decay\n self.momentum = momentum\n self.epsilon = epsilon\n super(RMSPropConfig, self).__init__(learning_rate, decay_type, decay_rate, decay_steps,\n start_decay_at, stop_decay_at, min_learning_rate,\n staircase, global_step, use_locking, name)\n\n\nclass AdamSchema(BaseOptimizerSchema):\n beta1 = fields.Float(allow_none=True)\n beta2 = fields.Float(allow_none=True)\n epsilon = fields.Float(allow_none=True)\n\n class Meta:\n ordered = True\n\n @post_load\n def make_load(self, data):\n return AdamConfig(**data)\n\n\nclass AdamConfig(BaseOptimizerConfig):\n IDENTIFIER = 'Adam'\n SCHEMA = AdamSchema\n\n def __init__(self,\n learning_rate=0.001,\n beta1=0.9,\n beta2=0.999,\n epsilon=1e-8,\n decay_type=\"\",\n decay_rate=0.,\n decay_steps=10000,\n start_decay_at=0,\n stop_decay_at=1e10,\n min_learning_rate=1e-12,\n staircase=False,\n global_step=None,\n use_locking=False,\n name='Adam'):\n self.beta1 = beta1\n self.beta2 = beta2\n self.epsilon = epsilon\n super(AdamConfig, self).__init__(learning_rate, decay_type, decay_rate, decay_steps,\n start_decay_at, stop_decay_at, min_learning_rate,\n staircase, global_step, use_locking, name)\n\n\nclass AdagradSchema(BaseOptimizerSchema):\n initial_accumulator_value = fields.Float(allow_none=True)\n\n class Meta:\n ordered = True\n\n @post_load\n def make_load(self, data):\n return AdagradConfig(**data)\n\n\nclass AdagradConfig(BaseOptimizerConfig):\n IDENTIFIER = 'Adagrad'\n SCHEMA = AdagradSchema\n\n def __init__(self,\n learning_rate=0.01,\n initial_accumulator_value=0.1,\n decay_type=\"\",\n decay_rate=0.,\n decay_steps=10000,\n start_decay_at=0,\n stop_decay_at=1e10,\n min_learning_rate=1e-12,\n staircase=False,\n global_step=None,\n use_locking=False,\n name='Adagrad'):\n self.initial_accumulator_value = initial_accumulator_value\n super(AdagradConfig, self).__init__(learning_rate, decay_type, decay_rate, decay_steps,\n start_decay_at, stop_decay_at, min_learning_rate,\n staircase, global_step, use_locking, name)\n\n\nclass AdadeltaSchema(BaseOptimizerSchema):\n rho = fields.Float(allow_none=True)\n epsilon = fields.Float(allow_none=True)\n\n class Meta:\n ordered = True\n\n @post_load\n def make_load(self, data):\n return AdadeltaConfig(**data)\n\n\nclass AdadeltaConfig(BaseOptimizerConfig):\n IDENTIFIER = 'Adadelta'\n SCHEMA = AdadeltaSchema\n\n def __init__(self,\n learning_rate=0.99,\n rho=0.95,\n epsilon=1e-08,\n decay_type=\"\",\n decay_rate=0.,\n decay_steps=10000,\n start_decay_at=0,\n stop_decay_at=1e10,\n min_learning_rate=1e-12,\n staircase=False,\n global_step=None,\n use_locking=False,\n name='Adadelta'):\n self.rho = rho\n self.epsilon = epsilon\n super(AdadeltaConfig, self).__init__(learning_rate, decay_type, decay_rate, decay_steps,\n start_decay_at, stop_decay_at, min_learning_rate,\n staircase, global_step, use_locking, name)\n\n\nclass FtrlSchema(BaseOptimizerSchema):\n learning_rate_power = fields.Float(allow_none=True)\n initial_accumulator_value = fields.Float(allow_none=True)\n l1_regularization_strength = fields.Float(allow_none=True)\n l2_regularization_strength = fields.Float(allow_none=True)\n\n class Meta:\n ordered = True\n\n @post_load\n def make_load(self, data):\n return FtrlConfig(**data)\n\n\nclass FtrlConfig(BaseOptimizerConfig):\n IDENTIFIER = 'Ftrl'\n SCHEMA = FtrlSchema\n\n def __init__(self,\n learning_rate=3.0,\n learning_rate_power=-0.5,\n initial_accumulator_value=0.1,\n l1_regularization_strength=0.0,\n l2_regularization_strength=0.0,\n decay_type=\"\",\n decay_rate=0.,\n decay_steps=10000,\n start_decay_at=0,\n stop_decay_at=1e10,\n min_learning_rate=1e-12,\n staircase=False,\n global_step=None,\n use_locking=False,\n name='Ftrl'):\n self.learning_rate_power = learning_rate_power\n self.initial_accumulator_value = initial_accumulator_value\n self.l1_regularization_strength = l1_regularization_strength\n self.l2_regularization_strength = l2_regularization_strength\n super(FtrlConfig, self).__init__(learning_rate, decay_type, decay_rate, decay_steps,\n start_decay_at, stop_decay_at, min_learning_rate,\n staircase, global_step, use_locking, name)\n\n\nclass OptimizerSchema(BaseMultiSchema):\n __multi_schema_name__ = 'optimizer'\n __configs__ = {\n SGDConfig.IDENTIFIER: SGDConfig,\n MomentumConfig.IDENTIFIER: MomentumConfig,\n NestrovConfig.IDENTIFIER: NestrovConfig,\n RMSPropConfig.IDENTIFIER: RMSPropConfig,\n AdamConfig.IDENTIFIER: AdamConfig,\n AdagradConfig.IDENTIFIER: AdagradConfig,\n AdadeltaConfig.IDENTIFIER: AdadeltaConfig,\n FtrlConfig.IDENTIFIER: FtrlConfig,\n }\n","sub_path":"polyaxon_schemas/optimizers.py","file_name":"optimizers.py","file_ext":"py","file_size_in_byte":11691,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"324684126","text":"from dateutil.relativedelta import relativedelta\nfrom datetime import datetime\n\ndef compute_age_from_dates(dob, deceased=False, dod=\"\"):\n today = datetime.today().date()\n if dob:\n start = datetime.strptime(str(dob), '%Y-%m-%d')\n end = datetime.strptime(str(today),'%Y-%m-%d')\n if deceased:\n end = datetime.strptime(\n str(dod), '%Y-%m-%d %H:%M')\n\n rdelta = relativedelta(end, start)\n\n years = rdelta.years\n months= rdelta.months\n days= rdelta.days\n\n if months==0 and days==0 and years !=0:\n age = str(years) + \"yr\"\n elif years==0 and days==0 and months !=0:\n age = str(months) + 'm'\n elif years==0 and months==0 and days !=0:\n age = str(days) + 'd'\n elif years !=0 and months !=0 and days ==0:\n age = str(years) + \"yr \" + str(months) + \"m\"\n elif years !=0 and months ==0 and int(days) !=0:\n age = str(years) + \"yr \" + str(days) + 'd'\n elif years ==0 and months !=0 and days !=0:\n age = str(months) + \"m \" + str(days) + 'd'\n elif years !=0 and months !=0 and int(days)!=0:\n age = str(years) + \"yr \" +str(months) + 'm ' + str(days) + 'd'\n elif years==0 and months==0 and days==0:\n age= \"New born\"\n else:\n age=\"Unable to compute age\"\n\n return age\n\nif __name__ == '__main__':\n print(compute_age_from_dates(\"2018-3-9\"))","sub_path":"features.py","file_name":"features.py","file_ext":"py","file_size_in_byte":1476,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"471096532","text":"# -*- coding:utf-8 -*-\nimport pygame\n\n\nclass Ship():\n \"\"\"control the ships in AI games\"\"\"\n\n def __init__(self, screen):\n self.screen = screen\n\n self.image = pygame.image.load('images/ship1.bmp')\n self.rect = self.image.get_rect()\n self.screen_rect = screen.get_rect()\n\n self.rect.centerx = self.screen_rect.centerx\n self.rect.bottom = self.screen_rect.bottom\n\n self.move_right = False\n self.move_left = False\n\n def bliteme(self):\n self.screen.blit(self.image, self.rect)\n\n def ship_motion_update(self):\n if self.move_right:\n self.rect.centerx += 1\n elif self.move_left:\n self.rect.centerx -= 1\n\n","sub_path":"AI/ship.py","file_name":"ship.py","file_ext":"py","file_size_in_byte":706,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"578020522","text":"# Licensed to the Apache Software Foundation (ASF) under one or more\n# contributor license agreements. See the NOTICE file distributed with\n# this work for additional information regarding copyright ownership.\n# The ASF licenses this file to You under the Apache License, Version 2.0\n# (the \"License\"); you may not use this file except in compliance with\n# the License. You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport requests\nimport unittest\nimport sys\n\ntry:\n from lxml import etree\nexcept ImportError:\n etree = None\n\nimport mock\nimport requests_mock\n\nfrom libcloud.common.base import LazyObject\nfrom libcloud.common.base import XmlResponse\nfrom libcloud.common.types import MalformedResponseError\nfrom libcloud.test import LibcloudTestCase\n\n\nclass LazyObjectTest(LibcloudTestCase):\n class A(LazyObject):\n def __init__(self, x, y=None):\n self.x = x\n self.y = y\n\n def test_lazy_init(self):\n # Test normal init\n a = self.A(1, y=2)\n self.assertTrue(isinstance(a, self.A))\n\n # Test lazy init\n with mock.patch.object(self.A,\n '__init__', return_value=None) as mock_init:\n a = self.A.lazy(3, y=4)\n self.assertTrue(isinstance(a, self.A)) # Proxy is a subclass of A\n mock_init.assert_not_called()\n\n # Since we have a mock init, an A object doesn't actually get\n # created. But, we can still call __dict__ on the proxy, which will\n # init the lazy object.\n self.assertEqual(a.__dict__, {})\n mock_init.assert_called_once_with(3, y=4)\n\n def test_setattr(self):\n a = self.A.lazy('foo', y='bar')\n a.z = 'baz'\n wrapped_lazy_obj = object.__getattribute__(a, '_lazy_obj')\n self.assertEqual(a.z, 'baz')\n self.assertEqual(wrapped_lazy_obj.z, 'baz')\n\n\nclass XmlResponseTest(unittest.TestCase):\n def test_lxml_from_unicode_with_encoding_declaration(self):\n if etree is None:\n return\n connection = mock.Mock()\n response_text = u'\\n' \\\n 'InvalidSnapshot.NotFound' \\\n 'Snapshot does not exist' \\\n 'd65ede94-44d9-40c4-992b-23aafd611797'\n with requests_mock.Mocker() as m:\n m.get('https://127.0.0.1',\n text=response_text,\n headers={'content-type': 'application/xml'})\n response = XmlResponse(requests.get('https://127.0.0.1'),\n connection)\n body = response.parse_body()\n self.assertIsNotNone(body)\n self.assertIsInstance(body, etree._Element)\n\n def test_parse_error_raises_exception_on_empty_body(self):\n if etree is None:\n return\n connection = mock.Mock()\n response_text = ''\n with requests_mock.Mocker() as m:\n m.get('https://127.0.0.1',\n text=response_text,\n headers={'content-type': 'application/xml'})\n response = XmlResponse(requests.get('https://127.0.0.1'),\n connection)\n response.parse_zero_length_body = True\n\n with self.assertRaises(MalformedResponseError):\n response.parse_error()\n\n\nif __name__ == '__main__':\n sys.exit(unittest.main())\n","sub_path":"libcloud/test/common/test_base.py","file_name":"test_base.py","file_ext":"py","file_size_in_byte":3881,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"504809880","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\nimport logging;logging.basicConfig(level=logging.INFO)\nimport asyncio,os,json,time\nfrom datetime import datetime\nfrom aiohttp import web\n\nasync def index(request):\n await asyncio.sleep(0.5)\n return web.Response(body=b'

Index

',content_type='text/html')\n\nasync def hello(request):\n await asyncio.sleep(0.5)\n text = '

你好,%s!

' % request.match_info['name']\n return web.Response(body=text.encode('utf-8'),content_type='text/html')\n #return web.Response(body=text.encode('GB2312'),content_type='text/html')\n\nasync def init(loop):\n app = web.Application(loop=loop)\n app.router.add_route('GET','/',index)\n app.router.add_route('GET','/hello/{name}',hello)\n srv = await loop.create_server(app.make_handler(),'127.0.0.1',9000)\n print('Server statrted at http://127.0.0.1:9000...')\n return srv\nloop = asyncio.get_event_loop()\nloop.run_until_complete(init(loop))\nloop.run_forever()","sub_path":"www/app1.py","file_name":"app1.py","file_ext":"py","file_size_in_byte":971,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"36621500","text":"# -*- encoding: utf-8 -*-\nfrom setuptools import setup, find_packages\n\ninstall_requires = [\n]\n\n\nif __name__ == '__main__':\n setup(\n name='logtest',\n version='0.1',\n description='Log Test',\n url='https://github.com/socek/logtest',\n license='Apache License 2.0',\n packages=find_packages('src'),\n package_dir={'': 'src'},\n install_requires=install_requires,\n entry_points={\n\n }\n )\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":454,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"591857996","text":"import json\nimport os\nimport sys\nimport requests\nfrom math import sqrt\n\nfrom flask import Flask, request\nfrom flask_sqlalchemy import SQLAlchemy\nfrom flask_login import LoginManager\n\n# SQLite URI compatible\nWIN = sys.platform.startswith('win')\nif WIN:\n prefix = 'sqlite:///'\nelse:\n prefix = 'sqlite:////'\n\napp = Flask(__name__)\napp.config['SECRET_KEY'] = \"You can NEVER guess this LOL\"\napp.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False\napp.config['SQLALCHEMY_DATABASE_URI'] = prefix + os.path.join(os.path.dirname(app.root_path), 'wlysCraft\\\\data.db')\napp.config['UPLOAD_FOLDER'] = os.path.join(os.path.dirname(app.root_path), 'wlysCraft\\\\uploadfiles')\n\nif not os.path.exists(app.config['UPLOAD_FOLDER']):\n os.mkdir(app.config['UPLOAD_FOLDER'])\n\ndb = SQLAlchemy(app)\n\nlogin_manager = LoginManager(app) # 实例化扩展类\nlogin_manager.login_view = 'login'\n\n@login_manager.user_loader\ndef load_user(user_id): # 创建用户加载回调函数,接受用户 ID 作为参数\n from wlysCraft.models import User\n user = User.query.get(int(user_id)) # 用 ID 作为 User 模型的主键查询对应的用户\n return user # 返回用户对象\n\n@app.route('/programs/zspd', methods=['POST'])\ndef zspd():\n try:\n num = int(request.form['num'])\n except:\n return json.dumps({'zsjg': ''}, ensure_ascii=False)\n if len(str(num)) > 10:\n return json.dumps({'zsjg': '太大了'}, ensure_ascii=False)\n if num > 1:\n if num == 2:\n return json.dumps({'zsjg': '是质数'}, ensure_ascii=False)\n if num % 2 == 0:\n return json.dumps({'zsjg': '是合数'}, ensure_ascii=False)\n\n for x in range(3, int(sqrt(num) + 1), 2):\n if num % x == 0:\n return json.dumps({'zsjg': '是合数'}, ensure_ascii=False)\n return json.dumps({'zsjg': '是质数'}, ensure_ascii=False)\n return json.dumps({'zsjg': '不是有效数字'}, ensure_ascii=False)\n\n\n@app.route('/index/weather', methods=['POST'])\ndef weather():\n my_params = {'location': 'auto_ip',\n 'key': '216168dcbeeb4a9ba1dd70f153ac4463'}\n requesturl = \"https://itsflicker.github.io/requestsAPI.html\"\n url = \"https://free-api.heweather.net/s6/weather/now\"\n resn = requests.get(requesturl, params=my_params)\n url2 = \"https://free-api.heweather.net/s6/weather/forecast\"\n resf = requests.get(url2, my_params)\n messages = {'weathern': resn.json(), 'weatherf': resf.json()}\n return json.dumps(messages, ensure_ascii=False)\n\n\nfrom wlysCraft import views, errors, commands\n\nif __name__ == '__main__':\n app.run(debug=False, port=80, host=\"192.168.0.100\")\n","sub_path":"wlysCraft/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":2643,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"569746153","text":"#\n# This source file is part of the EdgeDB open source project.\n#\n# Copyright 2016-present MagicStack Inc. and the EdgeDB authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n#\n\n\nimport time\nimport typing\n\nimport immutables\n\nfrom edb.server import defines\nfrom edb.lang.common import lru\n\nfrom . import dbstate\n\n\n__all__ = ('DatabaseIndex', 'DatabaseConnectionView')\n\n\nclass Database:\n\n # Global LRU cache of compiled anonymous queries\n _eql_to_compiled: typing.Mapping[bytes, dbstate.QueryUnit]\n\n def __init__(self, name):\n self._name = name\n self._dbver = time.monotonic_ns()\n\n self._eql_to_compiled = lru.LRUMapping(\n maxsize=defines._MAX_QUERIES_CACHE)\n\n def _signal_ddl(self):\n self._dbver = time.monotonic_ns() # Advance the version\n self._invalidate_caches()\n\n def _invalidate_caches(self):\n self._eql_to_compiled.clear()\n\n def _cache_compiled_query(self, eql: bytes, json_mode: bool,\n compiled: dbstate.QueryUnit):\n assert compiled.is_preparable()\n key = (eql, json_mode)\n existing = self._eql_to_compiled.get(key)\n if existing is not None and existing.dbver > compiled.dbver:\n # We already have a cached query for a more recent DB version.\n return\n\n self._eql_to_compiled[key] = compiled\n\n def _new_view(self, *, user):\n return DatabaseConnectionView(self, user=user)\n\n\nclass DatabaseConnectionView:\n\n _eql_to_compiled: typing.Mapping[bytes, dbstate.QueryUnit]\n\n def __init__(self, db: Database, *, user):\n self._db = db\n\n self._user = user\n\n self._config = immutables.Map()\n self._modaliases = immutables.Map({None: 'default'})\n\n # Whenever we are in a transaction that had executed a\n # DDL command, we use this cache for compiled queries.\n self._eql_to_compiled = lru.LRUMapping(\n maxsize=defines._MAX_QUERIES_CACHE)\n\n self._new_tx_state()\n\n def _invalidate_local_cache(self):\n self._eql_to_compiled.clear()\n\n def _new_tx_state(self):\n self._txid = None\n self._in_tx = False\n self._in_tx_with_ddl = False\n self._tx_error = False\n\n def rollback(self):\n self._new_tx_state()\n\n @property\n def config(self):\n return self._config\n\n @property\n def modaliases(self):\n return self._modaliases\n\n @property\n def txid(self):\n return self._txid\n\n @property\n def in_tx(self):\n return self._in_tx\n\n @property\n def user(self):\n return self._user\n\n @property\n def dbver(self):\n return self._db._dbver\n\n @property\n def dbname(self):\n return self._db._name\n\n def cache_compiled_query(self, eql: bytes,\n json_mode: bool,\n compiled: dbstate.QueryUnit):\n if self._in_tx_with_ddl:\n self._eql_to_compiled[(eql, json_mode)] = compiled\n else:\n self._db._cache_compiled_query(eql, json_mode, compiled)\n\n def lookup_compiled_query(\n self, eql: bytes,\n json_mode: bool) -> typing.Optional[dbstate.QueryUnit]:\n\n compiled: dbstate.QueryUnit\n key = (eql, json_mode)\n\n if self._in_tx_with_ddl:\n compiled = self._eql_to_compiled.get(key)\n else:\n compiled = self._db._eql_to_compiled.get(key)\n if compiled is not None and compiled.dbver != self.dbver:\n compiled = None\n\n return compiled\n\n def tx_error(self):\n if self._in_tx:\n self._tx_error = True\n\n def start(self, qu: dbstate.QueryUnit):\n self._txid = qu.txid\n if qu.starts_tx:\n self._in_tx = True\n if qu.has_ddl:\n self._in_tx_with_ddl\n\n def on_error(self, qu: dbstate.QueryUnit):\n self.tx_error()\n\n def on_success(self, qu: dbstate.QueryUnit):\n if not self._in_tx and qu.has_ddl:\n self._db._signal_ddl()\n\n if qu.commits_tx:\n assert self._in_tx\n if self._in_tx_with_ddl:\n self._db._signal_ddl()\n self._new_tx_state()\n\n elif qu.rollbacks_tx:\n assert self._in_tx\n self._new_tx_state()\n\n if qu.config:\n self._config = qu.config\n\n if qu.modaliases:\n self._modaliases = qu.modaliases\n\n\nclass DatabaseIndex:\n\n def __init__(self):\n self._dbs = {}\n\n def new_view(self, dbname: str, *, user: str) -> DatabaseConnectionView:\n try:\n db = self._dbs[dbname]\n except KeyError:\n db = Database(dbname)\n self._dbs[dbname] = db\n\n return db._new_view(user=user)\n","sub_path":"edb/server2/backend/dbview.py","file_name":"dbview.py","file_ext":"py","file_size_in_byte":5255,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"79884290","text":"from scrapy import Spider\nfrom selenium import webdriver\nfrom scrapy.http import HtmlResponse\n\nfrom selenium.webdriver.chrome.options import Options\nfrom selenium.webdriver.support.ui import WebDriverWait\nfrom selenium.webdriver.support import expected_conditions as EC\nfrom selenium.webdriver.common.by import By\nfrom selenium.common.exceptions import NoSuchElementException\nfrom selenium.common.exceptions import InvalidSessionIdException\n\nfrom time import sleep\n\nclass SaasMagCrawl(Spider):\n name = 'saas'\n allowed_domains = ['www.saasmag.com']\n\n start_urls = ['https://www.saasmag.com/saas-1000-2019/']\n\n def __init__(self):\n # any options to add for chrome\n chromeOptions = Options()\n chromeOptions.headless = False\n chromeOptions.add_argument('--enable-javascript')\n\n # chrome driver path\n chromeDriverPath = \"/home/sihamsharif/driver/chromedriver\"\n self.driver = webdriver.Chrome(executable_path=chromeDriverPath, options=chromeOptions)\n\n def parse(self, response):\n self.driver.get(response.url)\n while True:\n try:\n # sel = Selector(text=self.driver.page_source)\n print(response.url)\n body = self.driver.page_source\n response = HtmlResponse(self.driver.current_url, body=body, encoding='utf-8', request=response.url)\n\n presence_checker_element = WebDriverWait(self.driver, 100).until(\n EC.presence_of_all_elements_located((By.CLASS_NAME,\n \"col_leadinvestor\"))\n )\n\n tableRow = response.xpath(\"//tbody/tr[@role='row']\")\n # http://doc.scrapy.org/en/latest/topics/selectors.html#working-with-relative-xpaths\n for row in tableRow:\n ranking = row.xpath(\".//td[@class=' col_CurrentRanking mynumcol']/text()\").extract_first()\n company_name = row.xpath(\".//td[@class=' col_company_name']/a/text()\").extract_first()\n city = row.xpath(\".//td[@class=' col_city']/text()\").extract_first()\n state = row.xpath(\".//td[@class=' col_state']/text()\").extract_first()\n employess = row.xpath(\n \".//td[@class='col_may_2017_employees mynumcol green']/text()\").extract_first()\n six_month_growth = row.xpath(\".//td[@class=' col_6_month_growth mynumcol']/text()\").extract_first()\n investor = row.xpath(\".//td[@class=' col_leadinvestor mynumcol']/text()\").extract_first()\n\n yield {\n 'ranking': ranking,\n 'company_name': company_name,\n 'city': city,\n 'state': state,\n 'employess': employess,\n 'six_month_growth': six_month_growth,\n 'investor': investor,\n }\n\n sleep(2)\n self.logger.info('sleep for 2 sec')\n\n next_page_number = self.driver.find_element_by_xpath(\"//*[@class='paginate_button current']/following-sibling::a\")\n next_page_number.click()\n\n except NoSuchElementException:\n\n body = self.driver.page_source\n response = HtmlResponse(self.driver.current_url, body=body, encoding='utf-8', request=response.url)\n\n presence_checker_element = WebDriverWait(self.driver, 100).until(\n EC.presence_of_all_elements_located((By.CLASS_NAME,\n \"col_leadinvestor\"))\n )\n\n tableRow = response.xpath(\"//tbody/tr[@role='row']\")\n # http://doc.scrapy.org/en/latest/topics/selectors.html#working-with-relative-xpaths\n for row in tableRow:\n ranking = row.xpath(\".//td[@class=' col_CurrentRanking mynumcol']/text()\").extract_first()\n company_name = row.xpath(\".//td[@class=' col_company_name']/a/text()\").extract_first()\n city = row.xpath(\".//td[@class=' col_city']/text()\").extract_first()\n state = row.xpath(\".//td[@class=' col_state']/text()\").extract_first()\n employess = row.xpath(\n \".//td[@class='col_may_2017_employees mynumcol green']/text()\").extract_first()\n six_month_growth = row.xpath(\".//td[@class=' col_6_month_growth mynumcol']/text()\").extract_first()\n investor = row.xpath(\".//td[@class=' col_leadinvestor mynumcol']/text()\").extract_first()\n\n yield {\n 'ranking': ranking,\n 'company_name': company_name,\n 'city': city,\n 'state': state,\n 'employess': employess,\n 'six_month_growth': six_month_growth,\n 'investor': investor,\n }\n\n self.logger.info('No more pages')\n self.driver.close()\n self.driver.quit()\n\n except InvalidSessionIdException:\n self.logger.info(\"Invalid Session Exception\")\n self.driver.quit()","sub_path":"SaaSrankingSites/SaaSrankingSites/spiders/SaaSsiteSpider.py","file_name":"SaaSsiteSpider.py","file_ext":"py","file_size_in_byte":5332,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"465791786","text":"\ndef clean_data(DataFrame):\n dimensions = [dimension for dimension in DataFrame.columns]\n\n for dimension in dimensions:\n indexes = DataFrame[DataFrame[dimension] == '?'].index\n DataFrame.drop(indexes , inplace=True)\n return DataFrame\n\ndef delete_dimension(DataFrame, index):\n indexes = list(range(len(DataFrame.columns)))\n del indexes[index]\n DataFrame = DataFrame.iloc[:, indexes]\n return DataFrame\n","sub_path":"cleaning.py","file_name":"cleaning.py","file_ext":"py","file_size_in_byte":435,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"504112873","text":"\"\"\"An only semi-dumb DBM.\n\nThis module is an attempt to do slightly better than the\nstandard library's dumbdbm. It keeps a similar design\nto dumbdbm while improving and fixing some of dumbdbm's\nproblems.\n\n\"\"\"\nimport os\nimport sys\nimport mmap\nfrom binascii import crc32\nimport struct\ntry:\n import __builtin__\nexcept ImportError:\n import builtins as __builtin__\ntry:\n _str_type = unicode\nexcept NameError:\n # Python 3.x.\n _str_type = str\n\n__version__ = '0.4.0'\n# Major, Minor version.\nFILE_FORMAT_VERSION = (1, 1)\nFILE_IDENTIFIER = b'\\x53\\x45\\x4d\\x49'\n\n\n_open = __builtin__.open\n_DELETED = -1\n_MAPPED_LOAD_PAGES = 300\n_WRITE_OPEN_FLAGS = None\n_DATA_OPEN_FLAGS = os.O_RDWR|os.O_CREAT|os.O_APPEND\nif sys.platform.startswith('win'):\n # On windows we need to specify that we should be\n # reading the file as a binary file so it doesn't\n # change any line ending characters.\n _DATA_OPEN_FLAGS = _DATA_OPEN_FLAGS|os.O_BINARY\n\n\nclass DBMError(Exception):\n pass\n\n\nclass DBMLoadError(DBMError):\n pass\n\n\nclass DBMChecksumError(DBMError):\n pass\n\n\nclass _SemiDBM(object):\n \"\"\"\n\n :param dbdir: The directory containing the dbm files. If the directory\n does not exist it will be created.\n\n \"\"\"\n def __init__(self, dbdir, renamer=None, verify_checksums=False):\n if renamer is None:\n self._renamer = _Renamer()\n else:\n self._renamer = renamer\n self._dbdir = dbdir\n self._data_filename = os.path.join(dbdir, 'data')\n # The in memory index, mapping of key to (offset, size).\n self._index = None\n self._data_fd = None\n self._verify_checksums = verify_checksums\n self._current_offset = 0\n self._load_db()\n\n def _create_db_dir(self):\n if not os.path.exists(self._dbdir):\n os.makedirs(self._dbdir)\n\n def _load_db(self):\n self._create_db_dir()\n self._index = self._load_index(self._data_filename)\n self._data_fd = os.open(self._data_filename, _DATA_OPEN_FLAGS)\n self._current_offset = os.lseek(self._data_fd, 0, os.SEEK_END)\n\n def _load_index(self, filename):\n # This method is only used upon instantiation to populate\n # the in memory index.\n if not os.path.exists(filename):\n self._write_headers(filename)\n return {}\n try:\n return self._load_index_from_fileobj(filename)\n except ValueError as e:\n raise DBMLoadError(\"Bad index file %s: %s\" % (filename, e))\n\n def _write_headers(self, filename):\n with _open(filename, 'wb') as f:\n # Magic number identifier.\n f.write(FILE_IDENTIFIER)\n # File version format.\n f.write(struct.pack('!HH', *FILE_FORMAT_VERSION))\n\n def _load_index_from_fileobj(self, filename):\n index = {}\n for key_name, offset, size in self._read_index(filename):\n size = int(size)\n offset = int(offset)\n if size == _DELETED:\n # This is a deleted item so we need to make sure that this\n # value is not in the index. We know that the key is already\n # in the index, because a delete is only written to the index\n # if the key already exists in the db.\n del index[key_name]\n else:\n if key_name in index:\n index[key_name] = (offset, size)\n else:\n index[key_name] = (offset, size)\n return index\n\n def _read_index(self, filename):\n # yields keyname, offset, size\n f = _open(filename, 'rb')\n header = f.read(8)\n self._verify_header(header)\n contents = mmap.mmap(f.fileno(), 0, access=mmap.ACCESS_READ)\n remap_size = mmap.ALLOCATIONGRANULARITY * _MAPPED_LOAD_PAGES\n # We need to track the max_index to use as the upper bound\n # in the .find() calls to be compatible with python 2.6.\n # There's a bug in python 2.6 where if an offset is specified\n # along with a size of 0, then the size for mmap() is the size\n # of the file instead of the size of the file - offset. To\n # fix this, we track this ourself and make sure we never go passed\n # max_index. If we don't do this, python2.6 will crash with\n # a bus error (python2.7 works fine without this workaround).\n # See http://bugs.python.org/issue10916 for more info.\n max_index = os.path.getsize(filename)\n file_size_bytes = max_index\n num_resizes = 0\n current = 8\n try:\n while current != max_index:\n key_size, val_size = struct.unpack(\n '!ii', contents[current:current+8])\n key = contents[current+8:current+8+key_size]\n offset = (remap_size * num_resizes) + current + 8 + key_size\n if offset + val_size > file_size_bytes:\n # If this happens then the index is telling us\n # to read past the end of the file. What we need\n # to do is stop reading from the index.\n return\n yield (key, offset, val_size)\n if val_size == _DELETED:\n val_size = 0\n # Also need to skip past the 4 byte checksum, hence\n # the '+ 4' at the end\n current = current + 8 + key_size + val_size + 4\n if current >= remap_size:\n contents.close()\n num_resizes += 1\n offset = num_resizes * remap_size\n # Windows python2.6 bug. You can't specify a length of\n # 0 with an offset, otherwise you get a WindowsError, not\n # enough storage is available to process this command.\n # Couldn't find an issue for this, but the workaround\n # is to specify the actual length of the mmap'd region\n # which is the total size minus the offset we want.\n contents = mmap.mmap(f.fileno(), file_size_bytes - offset,\n access=mmap.ACCESS_READ,\n offset=offset)\n current -= remap_size\n max_index -= remap_size\n finally:\n contents.close()\n f.close()\n\n def _verify_header(self, header):\n sig = header[:4]\n if sig != FILE_IDENTIFIER:\n raise DBMLoadError(\"File is not a semibdm db file.\")\n major, minor = struct.unpack('!HH', header[4:])\n if major != FILE_FORMAT_VERSION[0]:\n raise DBMLoadError(\n 'Incompatible file version (got: v%s, can handle: v%s)' % (\n (major, FILE_FORMAT_VERSION[0])))\n\n def __getitem__(self, key, read=os.read, lseek=os.lseek,\n seek_set=os.SEEK_SET, str_type=_str_type,\n isinstance=isinstance):\n if isinstance(key, str_type):\n key = key.encode('utf-8')\n offset, size = self._index[key]\n lseek(self._data_fd, offset, seek_set)\n if not self._verify_checksums:\n return read(self._data_fd, size)\n else:\n # Checksum is at the end of the value.\n data = read(self._data_fd, size + 4)\n return self._verify_checksum_data(key, data)\n\n def _verify_checksum_data(self, key, data):\n # key is the bytes of the key,\n # data is the bytes of the value + 4 byte checksum at the end.\n value = data[:-4]\n expected = struct.unpack('!I', data[-4:])[0]\n actual = crc32(key)\n actual = crc32(value, actual)\n if actual & 0xffffffff != expected:\n raise DBMChecksumError(\n \"Corrupt data detected: invalid checksum for key %s\" % key)\n return value\n\n def __setitem__(self, key, value, len=len, crc32=crc32, write=os.write,\n str_type=_str_type, pack=struct.pack, bytearray=bytearray,\n isinstance=isinstance):\n if isinstance(key, str_type):\n key = key.encode('utf-8')\n if isinstance(value, str_type):\n value = value.encode('utf-8')\n # Write the new data out at the end of the file.\n # Format is\n # 4 bytes 4bytes 4bytes\n # \n # Everything except for the actual checksum + value\n key_size = len(key)\n val_size = len(value)\n blob = bytearray(pack('!ii', key_size, val_size))\n keyval = bytes(key + value)\n blob.extend(keyval)\n blob.extend(pack('!I', crc32(keyval) & 0xffffffff))\n\n write(self._data_fd, blob)\n # Update the in memory index.\n self._index[key] = (self._current_offset + 8 + key_size,\n val_size)\n self._current_offset += len(blob)\n\n def __contains__(self, key):\n return key in self._index\n\n def __delitem__(self, key, len=len, write=os.write, deleted=_DELETED,\n str_type=_str_type, isinstance=isinstance,\n bytearray=bytearray, crc32=crc32, pack=struct.pack):\n if isinstance(key, str_type):\n key = key.encode('utf-8')\n blob = bytearray(pack('!ii', len(key), _DELETED))\n blob.extend(key)\n crc = pack('!I', crc32(key) & 0xffffffff)\n blob.extend(crc)\n\n write(self._data_fd, blob)\n del self._index[key]\n self._current_offset += len(blob)\n\n def __iter__(self):\n for key in self._index:\n yield key\n\n def keys(self):\n \"\"\"Return all they keys in the db.\n\n The keys are returned in an arbitrary order.\n\n \"\"\"\n return self._index.keys()\n\n def values(self):\n return [self[key] for key in self._index]\n\n def close(self, compact=False):\n \"\"\"Close the db.\n\n The data is synced to disk and the db is closed.\n Once the db has been closed, no further reads or writes\n are allowed.\n\n :param compact: Indicate whether or not to compact the db\n before closing the db.\n\n \"\"\"\n if compact:\n self.compact()\n self.sync()\n os.close(self._data_fd)\n\n def sync(self):\n \"\"\"Sync the db to disk.\n\n This will flush any of the existing buffers and\n fsync the data to disk.\n\n You should call this method to guarantee that the data\n is written to disk. This method is also called whenever\n the dbm is `close()`'d.\n\n \"\"\"\n # The files are opened unbuffered so we don't technically\n # need to flush the file objects.\n os.fsync(self._data_fd)\n\n def compact(self):\n \"\"\"Compact the db to reduce space.\n\n This method will compact the data file and the index file.\n This is needed because of the append only nature of the index\n and data files. This method will read the index and data file\n and write out smaller but equivalent versions of these files.\n\n As a general rule of thumb, the more non read updates you do,\n the more space you'll save when you compact.\n\n \"\"\"\n # Basically, compaction works by opening a new db, writing\n # all the keys from this db to the new db, renaming the\n # new db to the filenames associated with this db, and\n # reopening the files associated with this db. This\n # implementation can certainly be more efficient, but compaction\n # is really slow anyways.\n new_db = self.__class__(os.path.join(self._dbdir, 'compact'))\n for key in self._index:\n new_db[key] = self[key]\n new_db.sync()\n new_db.close()\n os.close(self._data_fd)\n self._renamer(new_db._data_filename, self._data_filename)\n os.rmdir(new_db._dbdir)\n # The index is already compacted so we don't need to compact it.\n self._load_db()\n\n\nclass _SemiDBMReadOnly(_SemiDBM):\n def __delitem__(self, key):\n self._method_not_allowed('delitem')\n\n def __setitem__(self, key, value):\n self._method_not_allowed('setitem')\n\n def sync(self):\n self._method_not_allowed('sync')\n\n def compact(self):\n self._method_not_allowed('compact')\n\n def _method_not_allowed(self, method_name):\n raise DBMError(\"Can't %s: db opened in read only mode.\" % method_name)\n\n def close(self, compact=False):\n os.close(self._data_fd)\n\n\nclass _SemiDBMReadOnlyMMap(_SemiDBMReadOnly):\n def __init__(self, dbdir, **kwargs):\n self._data_map = None\n super(_SemiDBMReadOnlyMMap, self).__init__(dbdir, **kwargs)\n\n def _load_db(self):\n self._create_db_dir()\n self._index = self._load_index(self._data_filename)\n self._data_fd = os.open(self._data_filename, os.O_RDONLY|os.O_CREAT)\n if os.path.getsize(self._data_filename) > 0:\n self._data_map = mmap.mmap(self._data_fd, 0,\n access=mmap.ACCESS_READ)\n\n def __getitem__(self, key, str_type=_str_type, isinstance=isinstance):\n if isinstance(key, str_type):\n key = key.encode('utf-8')\n offset, size = self._index[key]\n if not self._verify_checksums:\n return self._data_map[offset:offset+size]\n else:\n data = self._data_map[offset:offset+size+4]\n return self._verify_checksum_data(key, data)\n\n def close(self, compact=False):\n super(_SemiDBMReadOnlyMMap, self).close()\n if self._data_map is not None:\n self._data_map.close()\n\n\nclass _SemiDBMReadWrite(_SemiDBM):\n def _load_db(self):\n if not os.path.isfile(self._data_filename):\n raise DBMError(\"Not a file: %s\" % self._data_filename)\n\n super(_SemiDBMReadWrite, self)._load_db()\n\n\nclass _SemiDBMNew(_SemiDBM):\n def _load_db(self):\n self._create_db_dir()\n self._remove_files_in_dbdir()\n super(_SemiDBMNew, self)._load_db()\n\n def _remove_files_in_dbdir(self):\n # We want to create a new DB so we need to remove\n # any of the existing files in the dbdir.\n if os.path.exists(self._data_filename):\n os.remove(self._data_filename)\n\n\n# These renamer classes are needed because windows\n# doesn't support atomic renames, and I won't want\n# non-window clients to suffer for this. If you're on\n# windows, you don't get atomic renames.\nclass _Renamer(object):\n \"\"\"An object that can rename files.\"\"\"\n def __call__(self, from_file, to_file):\n os.rename(from_file, to_file)\n\n\n# Note that this also works on posix platforms as well.\nclass _WindowsRenamer(object):\n def __call__(self, from_file, to_file):\n # os.rename(from_, to) will fail is the to file exists,\n # so in order to accommodate this, the to_file is renamed,\n # then from_file -> to_file, and then to_file is removed.\n os.rename(to_file, to_file + os.extsep + 'tmprename')\n os.rename(from_file, to_file)\n os.remove(to_file + os.extsep + 'tmprename')\n\n\n# The \"dbm\" interface is:\n#\n# open(filename, flag='r', mode=0o666)\n#\n# All the other args after this should have default values\n# so that this function remains compatible with the dbm interface.\ndef open(filename, flag='r', mode=0o666, verify_checksums=False):\n \"\"\"Open a semidbm database.\n\n :param filename: The name of the db. Note that for semidbm,\n this is actually a directory name. The argument is named\n `filename` to be compatible with the dbm interface.\n\n :param flag: Specifies how the db should be opened. `flag` can be any of these values\n\n +---------+-------------------------------------------+\n | Value | Meaning |\n +=========+===========================================+\n | ``'r'`` | Open existing database for reading only |\n | | (default) |\n +---------+-------------------------------------------+\n | ``'w'`` | Open existing database for reading and |\n | | writing |\n +---------+-------------------------------------------+\n | ``'c'`` | Open database for reading and writing, |\n | | creating it if it doesn't exist |\n +---------+-------------------------------------------+\n | ``'n'`` | Always create a new, empty database, open |\n | | for reading and writing |\n +---------+-------------------------------------------+\n\n :param mode: Not currently used (provided to be compatible with\n the dbm interface).\n\n :param verify_checksums: Verify the checksums for each value\n are correct on every __getitem__ call (defaults to False).\n\n \"\"\"\n if sys.platform.startswith('win'):\n renamer = _WindowsRenamer()\n else:\n renamer = _Renamer()\n kwargs = {'renamer': renamer, 'verify_checksums': verify_checksums}\n if flag == 'r':\n return _SemiDBMReadOnly(filename, **kwargs)\n elif flag == 'c':\n return _SemiDBM(filename, **kwargs)\n elif flag == 'w':\n return _SemiDBMReadWrite(filename, **kwargs)\n elif flag == 'n':\n return _SemiDBMNew(filename, **kwargs)\n else:\n raise ValueError(\"flag argument must be 'r', 'c', 'w', or 'n'\")\n","sub_path":"semidbm/db.py","file_name":"db.py","file_ext":"py","file_size_in_byte":17494,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"213724211","text":"# Orca\n#\n# Copyright 2004-2008 Sun Microsystems Inc.\n#\n# This library is free software; you can redistribute it and/or\n# modify it under the terms of the GNU Library General Public\n# License as published by the Free Software Foundation; either\n# version 2 of the License, or (at your option) any later version.\n#\n# This library is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n# Library General Public License for more details.\n#\n# You should have received a copy of the GNU Library General Public\n# License along with this library; if not, write to the\n# Free Software Foundation, Inc., Franklin Street, Fifth Floor,\n# Boston MA 02110-1301 USA.\n\n\"\"\" Custom script for gnome-panel\n\"\"\"\n\n__id__ = \"$Id: gnome-panel.py 4221 2008-09-15 08:11:23Z wwalker $\"\n__version__ = \"$Revision: 4221 $\"\n__date__ = \"$Date: 2008-09-15 04:11:23 -0400 (Mon, 15 Sep 2008) $\"\n__copyright__ = \"Copyright (c) 2005-2008 Sun Microsystems Inc.\"\n__license__ = \"LGPL\"\n\nimport orca.default as default\nimport orca.debug as debug\nimport orca.braille as braille\nimport orca.speech as speech\nimport pyatspi\n\n########################################################################\n# #\n# The gnome-panel script class. #\n# #\n########################################################################\n\nclass Script(default.Script):\n\n def __init__(self, app):\n \"\"\"Creates a new script for gnome-panel\n\n Arguments:\n - app: the application to create a script for.\n \"\"\"\n\n # Set the debug level for all the methods in this script.\n #\n self.debugLevel = debug.LEVEL_FINEST\n\n self._debug(\"__init__\")\n default.Script.__init__(self, app)\n\n def _debug(self, msg):\n \"\"\" Convenience method for printing debug messages\n \"\"\"\n debug.println(self.debugLevel, \"gnome-panel.py: \"+msg)\n\n def getListeners(self):\n \"\"\"Sets up the AT-SPI event listeners for this script.\n \"\"\"\n listeners = default.Script.getListeners(self)\n \n listeners[\"object:state-changed:focused\"] = \\\n self.onStateChanged\n listeners[\"object:state-changed:showing\"] = \\\n self.onStateChanged\n \n return listeners\n\n def onStateChanged(self, event):\n \"\"\"Called whenever an object's state changes.\n\n Arguments:\n - event: the Event\n \"\"\"\n obj = event.source\n\n self._debug(\"onStateChanged: '%s' %s (%d, %d)\" % \\\n (obj.name, event.type, event.detail1, event.detail2))\n\n # Handle tooltip popups.\n #\n if obj.getRole() == pyatspi.ROLE_TOOL_TIP:\n if event.type.startswith(\"object:state-changed:showing\") and \\\n event.detail1 == 1:\n braille.displayMessage(obj.name)\n speech.speak(obj.name)\n\n # If focus moves to something within a panel and focus was not\n # already in the containing panel, the panel will issue its\n # own state-changed:focused event with detail1 == 1 after the\n # event for the item with focus. The panel is not focused,\n # plus the extraneous event results in unnecessary chattiness\n # and updates the braille display to \"panel.\"\n #\n elif obj.getRole() == pyatspi.ROLE_PANEL and \\\n event.type.startswith(\"object:state-changed:focused\") and \\\n event.detail1 == 1 and not \\\n event.source.getState().contains(pyatspi.STATE_FOCUSED):\n return\n\n else:\n default.Script.onStateChanged(self, event)\n","sub_path":"usr/share/python-support/gnome-orca/orca/scripts/apps/gnome-panel.py","file_name":"gnome-panel.py","file_ext":"py","file_size_in_byte":3886,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"408507588","text":"# Funksjonen som utfører bubble sort algoritmen som tar inn en liste.\r\ndef bubble_sort(list):\r\n # Sier at lengden av løkka vi skal ha senere er lengden av lista minus 1\r\n length = len(list)-1\r\n\r\n #Vi setter at lista ikke er sortert til å begynne med.\r\n sorted = False\r\n\r\n # Setter igang en while-løkke som kjører mens lista ikke er sortert.\r\n while not sorted:\r\n # Setter sorted til True slik at om if-setningen i forløkka under\r\n # ikke utføres så er lista sortert.\r\n sorted = True\r\n\r\n # Lager en forløkke for alle elementene i lista\r\n for i in range(length):\r\n # Sier at dersom det nåværende leddet i lista er større enn\r\n # det neste leddet i rekka, så skal vi utførez if-setningen inne i\r\n # løkka.\r\n if list[i] > list[i+1]:\r\n # Om dette er tilfelle så er lista ikke sortert,\r\n # så vi setter dermed sorted til false igjen.\r\n sorted = False\r\n\r\n # Bytter så om på plassene til i og i+1 i lista\r\n list[i], list[i+1] = list[i+1], list[i]\r\n\r\n # Returnerer dermed lista.\r\n return(list)\r\n\r\n# Dette er den andre funksjonen\r\ndef selection_sort(list):\r\n # Lager en ny liste som skal være den sorterte listen\r\n sorted_list=[]\r\n\r\n # Sier at lengden er lik listas lengde. Ikke helt nødvendig, men litt ryddig\r\n length = len(list)\r\n\r\n # Lager en forløkke i range til lengden til lista\r\n for n in range(length):\r\n # Definerer en variabel x som det største tallet i lista\r\n x = max(list)\r\n # Fjerner dette fra lista\r\n list.remove(x)\r\n # Legger det til i den nye lista\r\n sorted_list.append(x)\r\n # Returnerer den sorterte lista.\r\n return sorted_list\r\n\r\nliste = [4,3,2,1,5]\r\nliste2 = [7,2,6,12,8]\r\nprint(bubble_sort(liste))\r\nprint(selection_sort(liste2))\r\n","sub_path":"Øving 7/oving7_sortering.py","file_name":"oving7_sortering.py","file_ext":"py","file_size_in_byte":1910,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"554220862","text":"# -*- coding: utf-8 -*-\n\nimport csv\nimport math\n\n# Formats the csv file that is the coppy of the xls file and returns an other csv\n\n\n# Reads and formats the data form all_data csv file\ndef read_data(file_name=\"All_data.csv\"):\n all_data = []\n \n # reads the data into all_data list\n with open(file_name) as file:\n data = csv.reader(file)\n for line in data:\n all_data.append(line)\n file.close()\n \n # get the data for each of the 3 planes form all_data (i forgot what prp is supposed to be) \n prp = [[float(y) for y in x] for x in all_data[45:55]]\n \n # creat a dictionary for the planes and thir charachteristics\n ac = {}\n for i in range(3):\n ac[i+1] = {\"speed\":prp[0][i], \"seats\":prp[1][i], \"TAT\":prp[2][i],\n \"range\":prp[3][i], \"rwr\":prp[4][i], \"lease\":prp[5][i],\n \"fixed_o_c\":prp[6][i], \"time_c\":prp[7][i], \"fuel_c\":prp[8][i],\n \"fleet\":prp[9][i]}\n \n # get the demand form A1 and dist values from the all_data list\n demand = [[int(y[:-2]) for y in x] for x in all_data[0:20]]\n dist = [[int(y) for y in x] for x in all_data[24:44]]\n \n # creat a dictionary that has the runway lengths and the hourly demand\n loc = {}\n for i in range(20):\n loc[i] = {\"rwl\":int(all_data[22][i][:-2])}\n \n for i in range(56,76):\n loc[i-56].update({\"h_d\":[float(x) for x in all_data[i][1:]]})\n \n # creat a compliance matrix that shows how long it take a plane to go form airport to airport\n # It appends 1 for cases where it stays (as opposed to 0 for flights it cannot make)\n ac_comp = []\n for ac_type in range(1,4):\n ac_m = []\n for loc1 in range(20):\n row = []\n for loc2 in range(20):\n if ac[ac_type][\"rwr\"] <= loc[loc1][\"rwl\"] and ac[ac_type][\"rwr\"] <= loc[loc2][\"rwl\"] and \\\n ac[ac_type][\"range\"] > dist[loc1][loc2] and loc1 != loc2:\n # the time it flies x 10 (as this time is given in hours) + the TAT /6 as tat is given in min\n # + half an hour from the assigment 30 / 6 = 5\n time = (dist[loc1][loc2]/ac[ac_type][\"speed\"])*10 + ac[ac_type][\"TAT\"]/6 + 5 \n row.append(math.ceil(time))\n elif loc1 == loc2:\n row.append(1)\n else:\n row.append(0)\n ac_m.append(row)\n ac_comp.append(ac_m)\n \n # Creats a matrix for each plane where the possible profit for each route is added\n ac_profit = []\n for ac_type in range(1,4):\n ac_m = []\n for loc1 in range(20):\n row = []\n for loc2 in range(20):\n if ac[ac_type][\"rwr\"] <= loc[loc1][\"rwl\"] and ac[ac_type][\"rwr\"] <= loc[loc2][\"rwl\"] and \\\n ac[ac_type][\"range\"] > dist[loc1][loc2] and loc1 != loc2:\n # check the function to see what it returns\n row.append(profit(ac_type,loc1,loc2,dist,ac))\n else:\n row.append(0)\n ac_m.append(row)\n ac_profit.append(ac_m)\n \n # returns the demand from A1, a dictionary with runway lengts and hourly demand,\n # compliance matrix for each plane that gives how long it takes to get form one place to another,\n # a matrix that gives the profit for each ac, and a dictionary for each ac\n return demand, loc, ac_comp, ac_profit, ac, dist\n\n\n# converts the given hourly demand float and the demand form A1 to hourly demands\ndef h_demands(demand,loc):\n tot_demands = []\n \n for t in range(24):\n time = []\n for i in range(20):\n row = []\n for j in range(20):\n dem = loc[i][\"h_d\"][t]\n \n row.append(int(dem*demand[i][j]))\n time.append(row)\n tot_demands.append(time)\n \n return tot_demands\n\n# takes the hourly demand and takes into account the +1,0,-1,-2 hours demand that is captured\n# for each hour, so it gives the maximum number of people that are willing to fly at that time\ndef tot_h_dems(h_demand):\n tot_demands = []\n \n for t in range(24):\n time = []\n for i in range(20):\n row = []\n for j in range(20):\n if i == 0 or j == 0:\n dem = h_demand[t][i][j] # take current hour into account\n if t >= 2 and t <= 24:\n dem += h_demand[t-2][i][j] # take hour -2 into account\n if t >= 1 and t <= 24:\n dem += h_demand[t-1][i][j] # take hour -1 into account\n if t <= 22:\n dem += h_demand[t+1][i][j] # take hour +1 into account\n else:\n dem = 0\n \n row.append(int(dem))\n time.append(row)\n tot_demands.append(time)\n \n return tot_demands\n\n \n# returns a tuple with the revenue and the cost (the revenue is per passenger)\ndef profit(ac_type,loc1,loc2,dist,ac):\n # as london is our hub (which is 1st in the list) the 1st item is 0.7 which is the \n # 30% cost decrease from assigment one\n cost = [0.7] + [1]*19\n # cost of flying is given by the fixed cost, time cost and fuel cost times 0.7 for hub and 1 for non-hub\n c = (ac[ac_type][\"fixed_o_c\"] + (dist[loc1][loc2] / ac[ac_type][\"speed\"]) * ac[ac_type][\"time_c\"] +\n dist[loc1][loc2]*ac[ac_type][\"fuel_c\"]*(1.42/1.5))*cost[loc1]*cost[loc2]\n r = (5.9*(dist[loc1][loc2]**(-0.76))+0.043)*dist[loc1][loc2]\n# if r * ac[ac_type][\"seats\"] - c < 0:\n# return 0\n return [round(r,2),round(c,2)]\n\n# returns an hourly profit matrix for an ac type for each possible route\ndef h_profits(h_demand,ac_profit,ac_type,ac):\n prof = []\n for i in range(len(h_demand)):\n lst = []\n for o in range(20):\n row = []\n for j in range(20):\n # get the profit, cost tuple\n x = ac_profit[ac_type-1][o][j]\n # get the total demand for that hour\n dem = h_demand[i][o][j]\n # if demand is larger than the capacity then demand is set to the number of seats\n if dem >= ac[ac_type][\"seats\"]:\n dem = ac[ac_type][\"seats\"]\n # if profit tuple isnt 0 (so its profitable) then set revenue to the\n # number of seats used * profit/passenger - cost\n if x:\n revenue = round(x[0]*dem - x[1],2)\n # return 0 if not profitable (could also mean staying in place)\n else:\n revenue = 0.0\n # if the number of people is not enough to make it profitable return empty string\n # gives slight performance improvement (if commented then unprofitable routes are also considered)\n# if revenue < 0:\n# revenue = \"\"\n row.append(revenue)\n lst.append(row)\n prof.append(lst)\n return prof\n \n# find the next possible destinations and how long it will take to get there\ndef find_next(current,comp,ac_type):\n # -1 is needed because then comp list starts at 0 but first ac starts at 1\n lst = comp[ac_type-1]\n options = []\n # if the hub then all possible locations are available\n if current == 0: \n for o in range(len(lst[current])):\n if lst[current][o]:\n # destination, time to destination\n options.append((o,lst[current][o]))\n # if not the hub the only destination is the hub\n else:\n options.append((0,lst[current][0]))\n return options\n \n# simple function that gets the profit of a route given the current location, destination and time\ndef get_prof(h_profit, dtime, current, destination):\n dtime = int(dtime/10)\n return h_profit[dtime][current][destination]\n\n# turns the hourly profits into per 6 min profits \ndef tot_profits(h_profit):\n \n all_nodes = []\n for t in range(240):\n matrix = []\n for i in range(20):\n row = []\n for o in range(20):\n x = get_prof(h_profit, t, i, o)\n row.append(x)\n matrix.append(row)\n all_nodes.append(matrix)\n \n return all_nodes\n\n# update the hourly demand (not tot)\ndef update_demand(h_demand, path, comp, ac, ac_type):\n # get the flight schedule (fs) for the best path\n fs = []\n past = 0\n t = -1\n for i in path:\n # if the current location is the same as the past step then it did not move\n # so add one to the time (still on the 6 min intervall)\n if i == past:\n t += 1\n else:\n fs.append([t,past,i])\n t += comp[ac_type-1][past][i]\n past = i\n \n # using the flight schedule substract the number of people flying on a route\n # taking into account the +1,0,-1,-2 demands\n ts = [0,-1,1,-2]\n for i in fs:\n removed = 0\n seats = ac[ac_type][\"seats\"]\n t = int(i[0]/10)\n for o in ts:\n # if the number of seats still availabe is larger than the demand\n # remove the demand from that hour and decrease the available seats\n if seats >= h_demand[t+o][i[1]][i[2]]:\n seats -= h_demand[t+o][i[1]][i[2]]\n removed += h_demand[t+o][i[1]][i[2]]\n h_demand[t+o][i[1]][i[2]] = 0\n # if the demand is more than the number of seats \n # substract the last availabe seats from the demand and stop\n else:\n h_demand[t+o][i[1]][i[2]] -= int(seats)\n removed += int(seats)\n break\n i.append(removed)\n \n #retunr the new hourly demand after the best flight and the flight schedule of it\n return h_demand, fs\n\n# get the block time that the ac spends in the air because of the (min 6 hour requirement)\ndef block_time(paths,comp,ac_type,ac):\n flight_t = 0\n past = 0\n for i in paths[239][0][\"path\"]:\n if i != past:\n flight_t += comp[ac_type-1][past][i] - math.ceil(ac[ac_type][\"TAT\"]/6)# include this if part c is part of block time + 5)\n past = i\n return flight_t\n\n# helper function for the plotting\ndef plot_help(path, comp, ac_type):\n \n times = [0]\n pos = [0]\n past = 0\n t = -1\n for i in path:\n # if the current location is the same as the past step then it did not move\n # so add one to the time (still on the 6 min intervall)\n if i == past:\n t += 1\n else:\n if times[-1]+1 != t: \n times.append(t)\n pos.append(past)\n t += comp[ac_type-1][past][i]\n times.append(t)\n pos.append(i)\n past = i\n times.append(239)\n pos.append(0)\n return times, pos\n\ndef kpis(final_paths, ac, dist, ac_prof):\n ask, rpk, num_p, num_s, tot_c, tot_p = 0, 0, 0, 0, 0, 0\n for i in final_paths:\n for o in i[\"fs\"]:\n d = dist[o[1]][o[2]]\n seats = ac[i[\"ac\"]][\"seats\"]\n used = o[3]\n ask += d*seats\n rpk += d*used\n num_p += used\n num_s += seats\n tot_c += ac_prof[i[\"ac\"]-1][o[1]][o[2]][1]\n tot_c += ac[i[\"ac\"]][\"lease\"]\n tot_p += i[\"prof\"]\n cask = tot_c/ask\n rask = (tot_p+tot_c)/ask\n rrpk = (tot_p+tot_c)/rpk\n \n return ask,rpk,num_p/num_s,cask,round(rask,4),round(rrpk,4)\n \n \n \n \n\n\n\n\n\n\n\n\n","sub_path":"Dynamic-Programing/functions.py","file_name":"functions.py","file_ext":"py","file_size_in_byte":11643,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"457872053","text":"from flask import Flask, request, Response\nimport sys\nfrom ufal.morphodita import *\n\ndef encode_entities(text):\n return text.replace('&', '&').replace('<', '<').replace('>', '>').replace('\"', '"')\n\ntagger_file = \"czech-morfflex-pdt-161115.tagger\"\nsys.stderr.write('Loading tagger: ')\ntagger = Tagger.load(tagger_file)\nif not tagger:\n sys.stderr.write(\"Cannot load tagger from file '%s'\\n\" % sys.argv[1])\n sys.exit(1)\nsys.stderr.write('done\\n')\n\nforms = Forms()\nlemmas = TaggedLemmas()\ntokens = TokenRanges()\ntokenizer = tagger.newTokenizer()\nif tokenizer is None:\n sys.stderr.write(\"No tokenizer is defined for the supplied model!\")\n sys.exit(1)\n\n\napp = Flask(__name__)\n\n@app.route(\"/\", methods=['GET'])\ndef tag():\n text = request.args.get('text')\n tokenizer.setText(text)\n t = 0\n out = \"\"\n\n while tokenizer.nextSentence(forms, tokens):\n tagger.tag(forms, lemmas)\n for i in range(len(lemmas)):\n lemma = lemmas[i]\n token = tokens[i]\n out = out + ('%s%s%s%s' % (\n encode_entities(text[t : token.start]),\n \"\" if i == 0 else \"\",\n encode_entities(lemma.lemma),\n encode_entities(lemma.tag),\n encode_entities(text[token.start : token.start + token.length]),\n \"\" if i + 1 == len(lemmas) else \"\",\n ))\n t = token.start + token.length\n #print(encode_entities(text[t : ]))\n\n #print(out)\n # html = \"{tagged_output}\"\n return Response(out, mimetype='text/xml')\n #return html.format(tagged_output=out)\n\nif __name__ == \"__main__\":\n app.run(host='0.0.0.0', port=80)\n","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1706,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"35073740","text":"#!/usr/bin/python\n# coding:utf-8\n\n\"\"\"\n@author: yyhaker\n@contact: 572176750@qq.com\n@file: 3.求一个整数数组的最长上升子序列的个数.py\n@time: 2019/8/18 19:14\n\"\"\"\n\"\"\"\nleetcode 300: 求一个整数数组的最长上升子序列的个数\n思路:动态规划+二分法\n\"\"\"\nclass Solution(object):\n def lengthOfLIS(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: int\n \"\"\"\n # 思路1:动态规划,令d[i]表示以nums[i]结尾的最长递增子序列的长度, 则有\n # d[i] = max_{0<=j d[i]:\n d[i] = d[j] + 1\n if d[i] > max_res:\n max_res = d[i]\n return max_res\n\nclass Solution2(object):\n def lengthOfLIS(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: int\n \"\"\"\n # 思路二:二分查找,维护一个序列L,序列L的长度即为遍历到数组第i个元素时的最长递增子序列的长度,\n # 维护的L中每个元素都是当前最小的,新来的元素如果大于nums[len-1], 直接添加;否则直接二分查找插入即可\n # 时间复杂度为O(nlogn), 空间复杂度为O(n)\n # (注意二分查找:在一个数组中查找大于target中的最小数字)\n if len(nums) == 0:\n return 0\n L = [nums[0]]\n for i in range(1, len(nums)):\n if nums[i] > L[len(L) - 1]:\n L.append(nums[i])\n else:\n # 二分查找加入,替换掉大于等于nums[i]的最小整数\n l, r = 0, len(L) - 1\n while l <= r:\n mid = (l + r) // 2\n if nums[i] <= L[mid]:\n r = mid - 1\n else:\n l = mid + 1\n # l 即为插入替换的位置\n L[l] = nums[i]\n return len(L)\n\n\nclass Solution3(object):\n def lengthOfLIS(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: int\n \"\"\"\n # (方法一:动态规划)\n # max_len = 0\n # # L[i]表示以nums[i]结尾的最长递增子序列的长度)O(n^2)\n # L = [1] * len(nums)\n # for i in range(len(nums)):\n # # 表示最大的L[j]\n # t = 0\n # for j in range(i):\n # if nums[i] > nums[j] and L[j] > t:\n # t = L[j]\n # L[i] = t + 1\n # # 更新当前的最大值\n # if L[i] > max_len:\n # max_len = L[i]\n # return max_len\n\n # (方法二)\n # O(nlogn)\n # 维护一个序列L,序列L的长度即为遍历到数组第i个元素时的最长递增子序列的长度,\n # 维护的L中每个元素都是当前最小的,新来的元素如果大于nums[len-1], 直接添加;否则直接二分查找插入即可\n # 时间复杂度为O(nlogn), 空间复杂度为O(n)\n if len(nums) == 0:\n return 0\n L = [nums[0]]\n for i in range(1, len(nums)):\n if nums[i] > L[len(L) - 1]:\n L.append(nums[i])\n else:\n # 二分查找替换掉L中大于等于nums[i]的最小的数字\n left = 0\n right = len(L) - 1\n while left <= right:\n mid = (left + right) // 2\n if nums[i] < L[mid]:\n right = mid - 1\n elif nums[i] > L[mid]:\n left = mid + 1\n else:\n left = mid\n break\n # 替换\n L[left] = nums[i]\n return len(L)\n\n\nsolution = Solution2()\nnums = [10,9,2,5,3,7,101,18]\nres = solution.lengthOfLIS(nums)\nprint(res)\n\n# 二分查找\n# def binary_search(nums, target):\n# l, r = 0, len(nums)-1\n# while l <= r:\n# mid = (l + r) // 2\n# if target <= nums[mid]:\n# r = mid - 1\n# else:\n# l = mid + 1\n# return l\n#\n# nums = [1, 2, 3, 5, 6]\n# nums2 = [1, 2, 3, 6]\n# nums3 = [5]\n# target = 4\n# res = binary_search(nums3, target)\n# print(res)","sub_path":"algorithms/常见面试编程题(剑指offer&leetcode)/动态规划dp/3.求一个整数数组的最长上升子序列的个数.py","file_name":"3.求一个整数数组的最长上升子序列的个数.py","file_ext":"py","file_size_in_byte":4491,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"134437938","text":"'''\nGiven a string s, return the longest palindromic substring in s.\n\n \n\nExample 1:\n\nInput: s = \"babad\"\nOutput: \"bab\"\nExplanation: \"aba\" is also a valid answer.\nExample 2:\n\nInput: s = \"cbbd\"\nOutput: \"bb\"\n \n\nConstraints:\n\n1 <= s.length <= 1000\ns consist of only digits and English letters.\n'''\nclass Solution:\n # O(N^2) find longest palindrome from inner to outer\n # j, k are middle index\n def longestPalindrome(self, s: str) -> str:\n def longest(s, j, k):\n while j>=0 and k.\n#\n# All Rights Reserved. V-Ray(R) is a registered trademark of Chaos Software.\n#\n\nimport bpy\n\nimport TexCommonParams3dsMax\n\n\nTYPE = 'TEXTURE'\nID = 'TexFalloff'\nNAME = 'Falloff'\nDESC = \"\"\n\nPluginParams = list(TexCommonParams3dsMax.PluginParams)\n\nPluginParams.extend([\n {\n 'attr' : 'color1',\n 'desc' : \"First color\",\n 'type' : 'TEXTURE',\n 'default' : (1, 1, 1),\n },\n {\n 'attr' : 'color2',\n 'desc' : \"Second color\",\n 'type' : 'TEXTURE',\n 'default' : (0, 0, 0),\n },\n\n {\n 'attr' : 'type',\n 'desc' : \"Type\",\n 'type' : 'ENUM',\n 'items' : (\n ('0', \"Towards / Away\", \"\"),\n ('1', \"Perpendicular / Parallel\", \"\"),\n ('2', \"Fresnel\", \"\"),\n ('3', \"Shadow / Light\", \"\"),\n ('4', \"Distance Blend\", \"\")\n ),\n 'default' : '0',\n },\n {\n 'attr' : 'direction_type',\n 'desc' : \"Direction type\",\n 'type' : 'ENUM',\n 'items' : (\n ('0', \"View Z\", \"\"),\n ('1', \"View X\", \"\"),\n ('2', \"View Y\", \"\"),\n ('3', \"Explicit\", \"\"),\n ('4', \"Local X\", \"\"),\n ('5', \"Local Y\", \"\"),\n ('6', \"Local Z\", \"\"),\n ('7', \"World X\", \"\"),\n ('8', \"World Y\", \"\"),\n ('9', \"World Z\", \"\")\n ),\n 'default' : '0',\n },\n {\n 'attr' : 'fresnel_ior',\n 'desc' : \"IOR for the Fresnel falloff type\",\n 'type' : 'FLOAT',\n 'default' : 1.6,\n },\n {\n 'attr' : 'dist_extrapolate',\n 'desc' : \"Extrapolate for the distance blend falloff type\",\n 'type' : 'BOOL',\n 'default' : False,\n },\n {\n 'attr' : 'dist_near',\n 'desc' : \"Near distance for the distance blend falloff type\",\n 'type' : 'FLOAT',\n 'default' : 0,\n },\n {\n 'attr' : 'dist_far',\n 'desc' : \"Far distance for the distance blend falloff type\",\n 'type' : 'FLOAT',\n 'default' : 100,\n },\n {\n 'attr' : 'explicit_dir',\n 'desc' : \"Direction for the explicit direction type\",\n 'type' : 'VECTOR',\n 'default' : (0, 0, 1),\n },\n {\n 'attr' : 'use_blend_input',\n 'desc' : \"\",\n 'type' : 'BOOL',\n 'default' : False,\n },\n {\n 'attr' : 'blend_input',\n 'desc' : \"If specified and 'Use Blend Input' is true, the final blending amount will be taken from this texture\",\n 'type' : 'FLOAT_TEXTURE',\n 'default' : 0.5,\n },\n {\n 'attr' : 'blend_output',\n 'desc' : \"The blending amount, based on the parameters\",\n 'type' : 'OUTPUT_FLOAT_TEXTURE',\n 'default' : 1.0,\n },\n])\n\nPluginWidget = \"\"\"\n{ \"widgets\": [\n { \"layout\" : \"COLUMN\",\n \"attrs\" : [\n { \"name\" : \"type\" },\n { \"name\" : \"direction_type\" }\n ]\n },\n\n { \"layout\" : \"SEPARATOR\" },\n\n { \"layout\" : \"SPLIT\",\n \"splits\" : [\n { \"layout\" : \"COLUMN\",\n \"align\" : true,\n \"attrs\" : [\n { \"name\" : \"fresnel_ior\" }\n ]\n },\n { \"layout\" : \"COLUMN\",\n \"align\" : true,\n \"attrs\" : [\n { \"name\" : \"dist_near\" },\n { \"name\" : \"dist_far\" },\n { \"name\" : \"dist_extrapolate\" }\n ]\n }\n ]\n },\n\n {TEX_COMMON}\n]}\n\"\"\"\nPluginWidget = PluginWidget.replace('{TEX_COMMON}', TexCommonParams3dsMax.PluginWidget)\n\n\ndef nodeDraw(context, layout, propGroup):\n layout.prop(propGroup, 'use_blend_input')\n","sub_path":"plugins/texture/TexFalloff.py","file_name":"TexFalloff.py","file_ext":"py","file_size_in_byte":4418,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"147932529","text":"\"\"\"\nSilverline declassification module.\n\"\"\"\nimport socket\nimport time\n\n# Module ID, for OFX internal reference.\nMODULEID = 0x20\n\n\n# dependencies for this module\ndependencies = ['uthash.h']\n\n# message type definitions for this module. \nENABLEDECLASSIFIER = 0x01 # enable the declassifier.\nADDFLOWPERMISSION = 0x02 # enable permissions for the flow.\n\ndataPathPort = 44444 # port that the dp agent listens on.\n\n\nclass ControllerComponent(object):\n \"\"\"\n The component that gets loaded by the controller.\n This provides an interface for control programs to use this module.\n \"\"\"\n MODULEID = 0x20\n def __init__(self, ofxControllerInterface):\n self.permissionCt = 0\n\n self.ofxSys = ofxControllerInterface\n self.mainHandler = self.handleModuleMessage\n def enableDeclassifier(self, sendToSwitch):\n \"\"\"\n Tells the switch to enable the declassifier.\n For all udp traffic. But this can be for a certain flow \n in the future.\n \"\"\"\n data = \"no_data\"\n msg = self.ofxSys.buildModuleMessage(self.MODULEID, ENABLEDECLASSIFIER, data)\n sendToSwitch(msg)\n def addFlowPermission(self, sendToSwitch, flowPermissionBin):\n \"\"\"\n Adds a flow permission to a switch.\n \"\"\"\n self.permissionCt += 1\n if (self.permissionCt % 1000) == 0:\n print (\"%s permissions added (in OFX controller component)\"%self.permissionCt)\n\n data = flowPermissionBin\n msg = self.ofxSys.buildModuleMessage(self.MODULEID, ADDFLOWPERMISSION, data)\n sendToSwitch(msg)\n def handleModuleMessage(self, data, datapathSendFcn):\n \"\"\"\n handle message from the switch.\n \"\"\"\n print (\"handler not implemented in silverline.\")\n\nclass SwitchComponent(object):\n \"\"\"\n The component that gets loaded by the OFX agent on the switch.\n \"\"\"\n MODULEID = 0x20\n # messages that this module wants to handle on the switch.\n def __init__(self, ofxAgent):\n # the OpenFlow messages this module wants to intercept.\n self.OFInterceptors = {}\n # self.OFInterceptors = {'ofp_packet_in':self.handlePacketInMessage}\n # the handler for messages directed to this module.\n self.mainHandler = self.handleModuleMessage\n # handler for messages from the data path component to the \n # switch management component.\n self.dpHandler = self.handleDpMessage\n\n # the agent running on the switch that interfaces with the switch and controller.\n self.ofxAgent = ofxAgent\n # methods provided by the switch agent to send to the controller and switch.\n self.sendToSwitchFcn = ofxAgent.injectToSwitch\n self.sendToControllerFcn = ofxAgent.injectToController\n self.permissionCt = 0\n self.time = time.time()\n\n\n def handleDpMessage(self, msgType, data):\n \"\"\"\n Handles messages from the data path component.\n \"\"\"\n print (\"silverline module got a message from the data path.(len = %s)\"%len(data))\n print (\"this shouldn't happen?\")\n return\n\n def handleModuleMessage(self, data):\n \"\"\"\n Handles messages directed to this module.\n \"\"\"\n # print (\"got a message in silverline module.\")\n (messageType, content) = self.ofxAgent.unpackModuleMessage(data)\n # print \"\\tmessage type: %s\"%messageType\n if messageType == ENABLEDECLASSIFIER:\n self.enableDeclassifier()\n elif messageType == ADDFLOWPERMISSION:\n self.addFlowPermission(content)\n\n def enableDeclassifier(self):\n \"\"\"\n Enables the declassifier.\n 1) redirect packets to the data path component.\n 2) Open Socket to data path component.\n \"\"\"\n # redirect to data path component.\n print (\"enabling silverline declassifier\")\n print (\"adding low priority rule to redirect udp packets to declassifier.\")\n matchPatternIn = \"priority=1, dl_type=0x0800, ip_proto=17\"\n self.ofxAgent.redirectToDpAgent(matchPatternIn, self.MODULEID)\n print (\"adding default output rule to flood packets.\")\n # bug in pica8 if you try to match udp packets here, it doesn't work.\n matchPatternOut = \"priority=2, dl_type=0x0800\"\n actionOut = \"FLOOD\"\n self.ofxAgent.redirectFromDpAgent(matchPatternOut, actionOut, self.MODULEID)\n\n def addFlowPermission(self, msgContent):\n \"\"\"\n add permissions for the flow.\n (forward the message to the socket to the data path component.)\n \"\"\"\n self.permissionCt += 1\n if (self.permissionCt % 1000) == 0:\n compTime = time.time() - self.time\n self.time = time.time()\n print (\"%s permissions added (in OFX manager) (%s sec)\"%(self.permissionCt, compTime))\n self.ofxAgent.sendToDp(self.MODULEID, ADDFLOWPERMISSION, msgContent)\n\n\n","sub_path":"src/ofx/ofx/exampleApps/silverline/silverlineModule.py","file_name":"silverlineModule.py","file_ext":"py","file_size_in_byte":4895,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"153045133","text":"import cv2\r\nimport pytesseract\r\nimport numpy as np\r\nfrom PIL import ImageGrab\r\nimport time\r\n\r\npytesseract.pytesseract.tesseract_cmd = 'C:\\\\Users\\\\dell\\\\Tesseract-OCR\\\\tesseract.exe'\r\nimg = cv2.imread('image.png')\r\nimg = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)\r\n#print(pytesseract.image_to_string(img))\r\n\r\n#Detecting Words\r\nhImg, wImg,_ = img.shape\r\nboxes = pytesseract.image_to_data(img)\r\nprint(boxes)\r\nboxes = pytesseract.image_to_data(img)\r\nfor a,b in enumerate(boxes.splitlines()):\r\n #print(b)\r\n if a!=0:\r\n b = b.split()\r\n if len(b)==12:\r\n x,y,w,h = int(b[6]),int(b[7]),int(b[8]),int(b[9])\r\n cv2.putText(img,b[11],(x,y-5),cv2.FONT_HERSHEY_SIMPLEX,1,(0,0,255),2)\r\n cv2.rectangle(img, (x,y), (x+w, y+h), (50, 50, 255), 1)\r\n\r\ncv2.imshow(\"Result\",img)\r\ncv2.waitKey(0)\r\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":846,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"414930090","text":"import sqlalchemy as db\nfrom sqlalchemy.orm import relationship\nfrom sqlalchemy.ext.declarative import declarative_base\n\nfrom Interface_API_Alchemy.Model_Alchemy.pokemon_model import PokemonModel\n\nBaseAlchemy = declarative_base()\n\n\nclass TreinadorModel(BaseAlchemy):\n\t__tablename__ = \"TREINADOR\"\n\n\tid = db.Column(db.Integer, primary_key=True)\n\tnome = db.Column(db.String(length=100))\n\tsobrenome = db.Column(db.String(length=100))\n\tidade = db.Column(db.Integer)\n\tcidade = db.Column(db.String(length=100))\n\tpokemon_id = db.Column(db.Integer, db.ForeignKey(\"POKEMON.id\"))\n\n\tdef __init__(self, nome, sobrenome, idade, cidade,\n\t\t\t\t pokemon_id=None, id=0):\n\t\tself.id = id\n\t\tself.nome = nome\n\t\tself.sobrenome = sobrenome\n\t\tself.idade = idade\n\t\tself.cidade = cidade\n\t\tself.pokemon_id = pokemon_id\n\n\tdef serialize(self):\n\t\treturn {\"id\": self.id, \"nome\": self.nome,\n\t\t\t\t\"sobrenome\": self.sobrenome,\n\t\t\t\t\"idade\": self.idade,\n\t\t\t\t\"cidade\": self.cidade,\n\t\t\t\t\"pokemon_id\": self.pokemon_id\n\t\t\t\t}\n\n\tdef __str__(self):\n\t\treturn f\"\"\"Codigo: {self.id}\nNome: {self.nome}\nSobrenome: {self.sobrenome}\nIdade: {int(self.idade)}\nCidade: {self.cidade}\nPokemon Inicial ID: {self.id_pokemon}\"\"\"\n","sub_path":"Interface_API_Alchemy/Model_Alchemy/treinador_model.py","file_name":"treinador_model.py","file_ext":"py","file_size_in_byte":1167,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"148959423","text":"import shortuuid\nfrom django.db import models\nfrom django.shortcuts import reverse\nfrom meta.views import Meta\nfrom stencila.schema.util import node_type as schema_node_type\n\nfrom projects.models.projects import Project\nfrom projects.models.sources import Source\nfrom users.models import User, get_name\n\n\ndef generate_node_key():\n \"\"\"\n Generate a unique, and very difficult to guess, key to access the node.\n \"\"\"\n return shortuuid.ShortUUID().random(length=32)\n\n\n# Applications known to create nodes\n# For these provide further details in HTML views of nodes\nAPPS = {\n \"api\": (\"API\", \"https://hub.stenci.la/api\"),\n \"encoda\": (\"Encoda\", \"https://github.com/stencila/encoda#readme\"),\n \"gsuita\": (\n \"Google Workspace\",\n \"https://workspace.google.com/marketplace/app/stencila/110435422451\",\n ),\n}\n\n\nclass Node(models.Model):\n \"\"\"\n A Stencila Schema node.\n\n Could be any type of node e.g. a `CodeChunk`, `CreativeWork`, `Number` within\n some larger document, or a complete `Article` or `Review`.\n\n The `project` field allows the node to be associated with a project.\n This field is not required; this allows apps to create nodes in documents (e.g. GSuita)\n or to or to convert documents (e.g. Encoda) without having to associate them with a project.\n If the `project` is deleted then so are any associated nodes. This is primarily\n a housekeeping consideration to avoid many nodes associated with temporary projects.\n\n The `source` field allows the node to be associated with a project source.\n Storing this allows us to change the node's project if the source is moved\n from one project to another (e.g. from a temporary project to an existing project).\n Because a `source` is always associated with a project, to avoid conflicts (e.g.\n if a source is moved from one project to another), if `source` is set\n then `project` will be set to `None`.\n\n Each node is created by an `app`. This string is primarily used when generating\n HTML representations of the node to provide links back to that app.\n\n This `host` is a URL (often the URL of the `source`) which is primarily used\n when generating HTML representations of the node to provide links back to the\n document.\n\n The `json` of the node is also immutable. It is returned to requests with\n `Accept: application/json` (if authorized).\n\n Each node has a unique `key` generated at the time of creation. This\n is the only way to retreive a node. The `key` should be treated as a secret.\n \"\"\"\n\n class Meta:\n unique_together = (\n \"project\",\n \"key\",\n )\n\n creator = models.ForeignKey(\n User,\n null=True, # Should only be null if the creator is deleted\n blank=True,\n on_delete=models.SET_NULL,\n related_name=\"nodes_created\",\n help_text=\"User who created the project.\",\n )\n\n created = models.DateTimeField(\n auto_now_add=True, help_text=\"When the project was created.\"\n )\n\n project = models.ForeignKey(\n Project,\n null=True,\n blank=True,\n on_delete=models.CASCADE,\n related_name=\"nodes\",\n help_text=\"The project this node is associated with (if any).\",\n )\n\n source = models.ForeignKey(\n Source,\n null=True,\n blank=True,\n on_delete=models.CASCADE,\n related_name=\"nodes\",\n help_text=\"The source this node is associated with (if any).\",\n )\n\n app = models.TextField(\n null=True,\n blank=True,\n help_text=\"An identifier for the app that created the node.\",\n )\n\n host = models.URLField(\n null=True,\n blank=True,\n help_text=\"URL of the host document within which the node was created.\",\n )\n\n key = models.CharField(\n unique=True,\n default=generate_node_key,\n max_length=64,\n help_text=\"A unique, and very difficult to guess, key to access this node if it is not public.\",\n )\n\n json = models.JSONField(help_text=\"The JSON content of node.\")\n\n def get_absolute_url(self):\n \"\"\"Get the URL of this node.\"\"\"\n return reverse(\"api-nodes-detail\", kwargs={\"key\": self.key})\n\n def get_app(self):\n \"\"\"Get name and URL of the creator app.\"\"\"\n return APPS.get(self.app.lower(), (self.app, None))\n\n def get_meta(self) -> Meta:\n \"\"\"Get the metadata to include in the head of the node's page.\"\"\"\n json = self.json\n node_type = schema_node_type(json)\n if node_type in (\"CodeChunk\", \"CodeExpression\"):\n lang = json.get(\"programmingLanguage\", \"\")\n kind = \"code chunk\" if node_type == \"CodeChunk\" else \"code expression\"\n title = f\"{lang.title()} {kind}\"\n elif node_type in (\"MathBlock\", \"MathFragment\"):\n lang = json.get(\"mathLanguage\", \"\")\n kind = \"math block\" if node_type == \"MathBlock\" else \"math fragment\"\n title = f\"{lang.title()} {kind}\"\n else:\n title = node_type + \" node\"\n\n description = \"Created\"\n if self.creator:\n description += f\" by { get_name(self.creator) }\"\n\n app_name, app_url = self.get_app()\n if app_name:\n description += f\" using { app_name }\"\n\n if self.created:\n description += f\" at { self.created } UTC\"\n return Meta(object_type=\"article\", title=title, description=description,)\n","sub_path":"manager/projects/models/nodes.py","file_name":"nodes.py","file_ext":"py","file_size_in_byte":5446,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"198996830","text":"import time\nfrom selenium import webdriver\nfrom selenium.common.exceptions import TimeoutException\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.common.keys import Keys\nfrom selenium.webdriver.support.wait import WebDriverWait\nfrom selenium.webdriver.support import expected_conditions as EC\nfrom util import logger, Utils\nfrom settings import IS_OLINE\n\n\nclass QutoutiaoUpload(object):\n\n driver_path = \"./driver/chromedriver.exe\"\n\n def __init__(self, account, password, video_type, video_path, image_path, title, content, tags, id):\n self.id = id\n self.tags = tags\n self.account = account\n self.password = password\n if IS_OLINE:\n self.video_path = video_path\n self.image_path = image_path\n else:\n self.video_path = '\\\\\\\\192.168.200.249' + video_path[2:]\n self.image_path = '\\\\\\\\192.168.200.249' + image_path[2:]\n self.title = title\n self.content = content\n self.msg = ''\n self.status = False\n self.aid = ''\n self.vid = ''\n self.browser = self.init_browser()\n\n def init_browser(self):\n option = webdriver.ChromeOptions()\n option.add_experimental_option('excludeSwitches', ['enable-automation'])\n browser = webdriver.Chrome(executable_path=self.driver_path, chrome_options=option)\n return browser\n\n def build_tag(self, tags):\n for tag in tags:\n self.browser.find_element_by_xpath(\"//div[@class='content-tag']//input\").send_keys(tag)\n self.browser.find_element_by_xpath(\"//div[@class='content-tag']//input\").send_keys(Keys.ENTER)\n time.sleep(0.5)\n\n def run(self):\n try:\n self.go()\n except Exception as e:\n logger.error(\"头条上传失败 任务id:{} error=>{}\".format(self.id, e))\n self.msg = \"上传未知失败 请检查上传日志 error:{}\".format(e)\n self.browser.close()\n return self.status, self.aid, self.vid, self.msg\n\n def go(self):\n self.browser.get(\"https://mp.qutoutiao.net/login\")\n # 登录开始\n WebDriverWait(self.browser, 10).until(\n EC.presence_of_element_located(\n (By.XPATH, \"//i[@class='login-icon']/following-sibling::input[1]\"))).send_keys(self.account)\n WebDriverWait(self.browser, 10).until(\n EC.presence_of_element_located((By.XPATH, \"//i[@class='pwd-icon']/following-sibling::input[1]\"))).send_keys(\n self.password)\n WebDriverWait(self.browser, 10).until(\n EC.presence_of_element_located((By.XPATH, \"//button[@id='submit-login']\"))).click()\n # 登录结束\n time.sleep(2)\n self.browser.maximize_window()\n\n # 跳转发布开始\n WebDriverWait(self.browser, 10).until(\n EC.presence_of_element_located((By.XPATH, \"//span[contains(string(), '发布内容')]\"))).click()\n WebDriverWait(self.browser, 10).until(\n EC.presence_of_element_located((By.XPATH, \"//p[contains(string(), '发布视频')]\"))).click()\n # *** 处理发文规范弹窗 ***\n WebDriverWait(self.browser, 10).until(\n EC.presence_of_element_located((By.XPATH, \"//i[@class='el-message-box__close el-icon-close']\"))).click()\n time.sleep(1)\n # 跳转发布结束\n\n # 开始发视频\n WebDriverWait(self.browser, 10).until(\n EC.presence_of_element_located((By.XPATH, \"//input[@id='inp-video-file']\"))).click()\n time.sleep(1) # 等待上传框体加载\n Utils.upload(self.video_path)\n WebDriverWait(self.browser, 100).until(\n EC.presence_of_element_located((By.XPATH, \"//span[contains(string(), '上传成功')]\")))\n WebDriverWait(self.browser, 10).until(\n EC.presence_of_element_located(\n (By.XPATH, \"//form[@class='el-form el-form--label-left']/div[1]//input\"))).send_keys(\n [Keys.BACKSPACE for i in range(1, 100)] + [i for i in self.title]) # 发送标题\n WebDriverWait(self.browser, 10).until(\n EC.presence_of_element_located((By.XPATH, \"//textarea[@class='el-textarea__inner']\"))).send_keys(\n self.content) # 发送描述\n WebDriverWait(self.browser, 10).until(\n EC.presence_of_element_located((By.XPATH, \"//input[@placeholder='请选择分类']\"))).click()\n time.sleep(1) # 等待分类加载\n WebDriverWait(self.browser, 10).until(\n EC.presence_of_element_located((By.XPATH, \"//dd[contains(string(), '{}')]\".format(self.video_type)))).click()\n time.sleep(1)\n self.build_tag(self.tags)\n time.sleep(0.5)\n # -- 选择封面开始\n WebDriverWait(self.browser, 10).until(\n EC.presence_of_element_located((By.XPATH, \"//div[@class='el-upload']\"))).click()\n time.sleep(1) # 等待封面框体加载\n WebDriverWait(self.browser, 10).until(\n EC.presence_of_element_located((By.XPATH, \"//p[contains(string(), '自定义封面')]\"))).click()\n WebDriverWait(self.browser, 10).until(\n EC.presence_of_element_located((By.XPATH, \"//span[contains(string(), '选择图片')]\"))).click()\n time.sleep(1) # 等待上传框体加载\n Utils.upload(self.image_path)\n time.sleep(3) # 等待图片上传完成 # TODO 待处理\n WebDriverWait(self.browser, 10).until(\n EC.presence_of_element_located((By.XPATH,\n \"//div[@class='el-dialog__wrapper dialog-img-cropper']//span[contains(string(), '确 定')]\")))\n time.sleep(1)\n self.browser.find_element_by_xpath(\"//div[@class='el-dialog__wrapper dialog-img-cropper']//span[contains(string(), '确 定')]\").click()\n # 封面选择结束\n # 视频信息构造结束\n time.sleep(3)\n WebDriverWait(self.browser, 10).until(\n EC.presence_of_element_located(\n (By.XPATH, \"//button[@class='el-button el-button--primary']//span[contains(string(), '发布')]\"))).click()\n try:\n WebDriverWait(self.browser, 3).until(\n EC.presence_of_element_located((By.XPATH, \"//div[@class='el-message-box__message']\")))\n time.sleep(2)\n self.msg = self.browser.find_element_by_xpath(\"//div[@class='el-message-box__message']\").text\n if self.msg:\n return\n except TimeoutException:\n pass\n WebDriverWait(self.browser, 10).until(EC.presence_of_element_located((By.XPATH, \"//button[@class='el-button el-button--primary el-button--medium']//span[contains(string(), '确认发布')]\"))) # TODO\n time.sleep(1)\n self.browser.find_element_by_xpath(\"//button[@class='el-button el-button--primary el-button--medium']//span[contains(string(), '确认发布')]\").click()\n time.sleep(2)\n self.status = True\n # TODO 确认发布\n","sub_path":"qutoutiao/qutoutiao.py","file_name":"qutoutiao.py","file_ext":"py","file_size_in_byte":6964,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"133912805","text":"# 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 getIntersectionNode(self, headA, headB):\n \"\"\"\n :type head1, head1: ListNode\n :rtype: ListNode\n \"\"\"\n '''2 pointer, find out the max len between the 2 \n and move one pointer till equidistant \n then check until they become same'''\n lenA = 0\n lenB = 0\n curr = headA\n while(curr != None):\n curr = curr.next\n lenA += 1\n curr = headB\n while(curr != None):\n curr = curr.next\n lenB += 1\n \n while(lenA > lenB):\n headA = headA.next\n lenA -= 1\n \n while(lenB > lenA):\n headB = headB.next\n lenB -= 1\n \n while(headA != headB):\n headA = headA.next\n headB = headB.next\n \n if headA != headB:\n return None\n \n return headA #return either","sub_path":"160-Intersection2LinkedList.py","file_name":"160-Intersection2LinkedList.py","file_ext":"py","file_size_in_byte":1086,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"348199524","text":"import torch\nimport torch.nn as nn\nfrom torch.autograd import Function, Variable\n\nfrom functools import reduce\nfrom torch.legacy.nn.Module import Module as LegacyModule\nfrom torch.legacy.nn.utils import clear\nfrom torch.nn._functions.thnn.normalization import CrossMapLRN2d\n\nimport numpy as np\nfrom pdb import set_trace as st\n\nclass Render4CNN(nn.Module):\n def __init__(self, finetune=False, weights = None, weights_path = None, num_classes = 12):\n super().__init__()\n\n # Normalization layers\n # norm1 = Lambda(lambda x,lrn=SpatialCrossMapLRN_temp(*(5, 0.0001, 0.75, 1)): Variable(lrn.forward(x.data)))\n # norm2 = Lambda(lambda x,lrn=SpatialCrossMapLRN_temp(*(5, 0.0001, 0.75, 1)): Variable(lrn.forward(x.data)))\n norm1 = nn.LocalResponseNorm(5, 0.0001, 0.75, 1)\n norm2 = nn.LocalResponseNorm(5, 0.0001, 0.75, 1)\n\n # conv layers\n conv1 = nn.Conv2d(3, 96, (11, 11), (4,4))\n relu1 = nn.ReLU()\n pool1 = nn.MaxPool2d( (3,3), (2,2), (0,0), ceil_mode=True)\n\n conv2 = nn.Conv2d(96, 256, (5, 5), (1,1), (2,2), 1,2)\n relu2 = nn.ReLU()\n pool2 = nn.MaxPool2d( (3,3), (2,2), (0,0), ceil_mode=True)\n\n conv3 = nn.Conv2d(256,384,(3, 3),(1, 1),(1, 1))\n relu3 = nn.ReLU()\n\n conv4 = nn.Conv2d(384,384,(3, 3),(1, 1),(1, 1),1,2)\n relu4 = nn.ReLU()\n\n conv5 = nn.Conv2d(384,256,(3, 3),(1, 1),(1, 1),1,2)\n relu5 = nn.ReLU()\n pool5 = nn.MaxPool2d((3, 3),(2, 2),(0, 0),ceil_mode=True)\n\n\n # inference layers\n fc6 = nn.Linear(9216,4096)\n relu6 = nn.ReLU()\n\n fc7 = nn.Linear(4096,4096)\n relu7 = nn.ReLU()\n\n drop6 = nn.Dropout(0.5)\n drop7 = nn.Dropout(0.5)\n\n azim = nn.Linear(4096,num_classes * 360)\n elev = nn.Linear(4096,num_classes * 360)\n tilt = nn.Linear(4096,num_classes * 360)\n\n\n if weights == 'lua':\n\n state_dict = torch.load(weights_path)\n\n conv1.weight.data.copy_(state_dict['0.weight'])\n conv1.bias.data.copy_(state_dict['0.bias'])\n conv2.weight.data.copy_(state_dict['4.weight'])\n conv2.bias.data.copy_(state_dict['4.bias'])\n conv3.weight.data.copy_(state_dict['8.weight'])\n conv3.bias.data.copy_(state_dict['8.bias'])\n conv4.weight.data.copy_(state_dict['10.weight'])\n conv4.bias.data.copy_(state_dict['10.bias'])\n\n conv5.weight.data.copy_(state_dict['12.weight'])\n conv5.bias.data.copy_(state_dict['12.bias'])\n fc6.weight.data.copy_(state_dict['16.1.weight'])\n fc6.bias.data.copy_(state_dict['16.1.bias'])\n fc7.weight.data.copy_(state_dict['19.1.weight'])\n fc7.bias.data.copy_(state_dict['19.1.bias'])\n\n if num_classes == 3 and (state_dict['22.1.weight'].size()[0] > 360*3):\n azim.weight.data.copy_( torch.cat([ state_dict['22.1.weight'][360*4:360*5, :], state_dict['22.1.weight'][360*5:360*6, :], state_dict['22.1.weight'][360*8:360*9, :] ], dim = 0) )\n elev.weight.data.copy_( torch.cat([ state_dict['24.1.weight'][360*4:360*5, :], state_dict['24.1.weight'][360*5:360*6, :], state_dict['24.1.weight'][360*8:360*9, :] ], dim = 0) )\n tilt.weight.data.copy_( torch.cat([ state_dict['26.1.weight'][360*4:360*5, :], state_dict['26.1.weight'][360*5:360*6, :], state_dict['26.1.weight'][360*8:360*9, :] ], dim = 0) )\n\n azim.bias.data.copy_( torch.cat([ state_dict['22.1.bias'][360*4:360*5], state_dict['22.1.bias'][360*5:360*6], state_dict['22.1.bias'][360*8:360*9] ], dim = 0) )\n elev.bias.data.copy_( torch.cat([ state_dict['24.1.bias'][360*4:360*5], state_dict['24.1.bias'][360*5:360*6], state_dict['24.1.bias'][360*8:360*9] ], dim = 0) )\n tilt.bias.data.copy_( torch.cat([ state_dict['26.1.bias'][360*4:360*5], state_dict['26.1.bias'][360*5:360*6], state_dict['26.1.bias'][360*8:360*9] ], dim = 0) )\n else:\n azim.weight.data.copy_(state_dict['22.1.weight'])\n elev.weight.data.copy_(state_dict['24.1.weight'])\n tilt.weight.data.copy_(state_dict['26.1.weight'])\n azim.bias.data.copy_(state_dict['22.1.bias'])\n elev.bias.data.copy_(state_dict['24.1.bias'])\n tilt.bias.data.copy_(state_dict['26.1.bias'])\n\n elif weights == 'npy':\n state_dict = np.load(weights_path).item()\n\n # Convert parameters to torch tensors\n for key in state_dict.keys():\n state_dict[key]['weight'] = torch.from_numpy(state_dict[key]['weight'])\n state_dict[key]['bias'] = torch.from_numpy(state_dict[key]['bias'])\n\n\n conv1.weight.data.copy_(state_dict['conv1']['weight'])\n conv1.bias.data.copy_(state_dict['conv1']['bias'])\n conv2.weight.data.copy_(state_dict['conv2']['weight'])\n conv2.bias.data.copy_(state_dict['conv2']['bias'])\n conv3.weight.data.copy_(state_dict['conv3']['weight'])\n conv3.bias.data.copy_(state_dict['conv3']['bias'])\n conv4.weight.data.copy_(state_dict['conv4']['weight'])\n conv4.bias.data.copy_(state_dict['conv4']['bias'])\n\n conv5.weight.data.copy_(state_dict['conv5']['weight'])\n conv5.bias.data.copy_(state_dict['conv5']['bias'])\n fc6.weight.data.copy_(state_dict['fc6']['weight'])\n fc6.bias.data.copy_(state_dict['fc6']['bias'])\n fc7.weight.data.copy_(state_dict['fc7']['weight'])\n fc7.bias.data.copy_(state_dict['fc7']['bias'])\n\n if num_classes == 3:\n azim.weight.data.copy_( torch.cat([ state_dict['pred_azimuth'][ 'weight'][360*4:360*5, :], state_dict['pred_azimuth'][ 'weight'][360*5:360*6, :], state_dict['pred_azimuth'][ 'weight'][360*8:360*9, :] ], dim = 0) )\n elev.weight.data.copy_( torch.cat([ state_dict['pred_elevation']['weight'][360*4:360*5, :], state_dict['pred_elevation']['weight'][360*5:360*6, :], state_dict['pred_elevation']['weight'][360*8:360*9, :] ], dim = 0) )\n tilt.weight.data.copy_( torch.cat([ state_dict['pred_tilt'][ 'weight'][360*4:360*5, :], state_dict['pred_tilt'][ 'weight'][360*5:360*6, :], state_dict['pred_tilt'][ 'weight'][360*8:360*9, :] ], dim = 0) )\n\n azim.bias.data.copy_( torch.cat([ state_dict['pred_azimuth']['bias'][360*4:360*5], state_dict['pred_azimuth']['bias'][360*5:360*6], state_dict['pred_azimuth']['bias'][360*8:360*9] ], dim = 0) )\n elev.bias.data.copy_( torch.cat([ state_dict['pred_elevation']['bias'][360*4:360*5], state_dict['pred_elevation']['bias'][360*5:360*6], state_dict['pred_elevation']['bias'][360*8:360*9] ], dim = 0) )\n tilt.bias.data.copy_( torch.cat([ state_dict['pred_tilt']['bias'][360*4:360*5], state_dict['pred_tilt']['bias'][360*5:360*6], state_dict['pred_tilt']['bias'][360*8:360*9] ], dim = 0) )\n else:\n azim.weight.data.copy_(state_dict['fc-azimuth']['weight'])\n elev.weight.data.copy_(state_dict['fc-elevation']['weight'])\n tilt.weight.data.copy_(state_dict['fc-tilt']['weight'])\n azim.bias.data.copy_(state_dict['fc-azimuth']['bias'])\n elev.bias.data.copy_(state_dict['fc-elevation']['bias'])\n tilt.bias.data.copy_(state_dict['fc-tilt']['bias'])\n\n # Define Network\n self.conv4 = nn.Sequential( conv1, relu1, pool1, norm1,\n conv2, relu2, pool2, norm2,\n conv3, relu3,\n conv4, relu4)\n\n # self.conv4 = nn.Sequential( conv1, relu1, pool1,\n # conv2, relu2, pool2,\n # conv3, relu3,\n # conv4, relu4)\n\n self.conv5 = nn.Sequential( conv5, relu5, pool5)\n\n self.infer = nn.Sequential( fc6, relu6, drop6,\n fc7, relu7, drop7)\n\n if finetune:\n self.conv4.requires_grad = False\n self.conv5.requires_grad = False\n\n\n self.azim = nn.Sequential( azim )\n self.elev = nn.Sequential( elev )\n self.tilt = nn.Sequential( tilt )\n\n def forward(self, images):\n # tmp = torch.zeros(images.size(), requires_grad=True)\n # tmp = images\n # features = self.conv4(tmp)\n features = self.conv4(images)\n features = self.conv5(features)\n features = features.view(features.size(0), 9216)\n features = self.infer(features)\n # loss = torch.sum(features)\n # loss.backward()\n # print(torch.sum(tmp.grad))\n # st()\n azim = self.azim(features)\n elev = self.elev(features)\n tilt = self.tilt(features)\n\n return azim, elev, tilt\n\n\n# class SpatialCrossMapLRN_temp(LegacyModule):\n\n# def __init__(self, size, alpha=1e-4, beta=0.75, k=1, gpuDevice=0):\n# super(SpatialCrossMapLRN_temp, self).__init__()\n\n# self.size = size\n# self.alpha = alpha\n# self.beta = beta\n# self.k = k\n# self.scale = None\n# self.paddedRatio = None\n# self.accumRatio = None\n# self.gpuDevice = gpuDevice\n\n# def updateOutput(self, input):\n# assert input.dim() == 4\n\n# if self.scale is None:\n# self.scale = input.new()\n\n# if self.output is None:\n# self.output = input.new()\n\n# batchSize = input.size(0)\n# channels = input.size(1)\n# inputHeight = input.size(2)\n# inputWidth = input.size(3)\n\n# if input.is_cuda:\n# self.output = self.output.cuda(self.gpuDevice)\n# self.scale = self.scale.cuda(self.gpuDevice)\n\n# self.output.resize_as_(input)\n# self.scale.resize_as_(input)\n\n# # use output storage as temporary buffer\n# inputSquare = self.output\n# torch.pow(input, 2, out=inputSquare)\n\n# prePad = int((self.size - 1) / 2 + 1)\n# prePadCrop = channels if prePad > channels else prePad\n\n# scaleFirst = self.scale.select(1, 0)\n# scaleFirst.zero_()\n# # compute first feature map normalization\n# for c in range(prePadCrop):\n# scaleFirst.add_(inputSquare.select(1, c))\n\n# # reuse computations for next feature maps normalization\n# # by adding the next feature map and removing the previous\n# for c in range(1, channels):\n# scalePrevious = self.scale.select(1, c - 1)\n# scaleCurrent = self.scale.select(1, c)\n# scaleCurrent.copy_(scalePrevious)\n# if c < channels - prePad + 1:\n# squareNext = inputSquare.select(1, c + prePad - 1)\n# scaleCurrent.add_(1, squareNext)\n\n# if c > prePad:\n# squarePrevious = inputSquare.select(1, c - prePad)\n# scaleCurrent.add_(-1, squarePrevious)\n\n# self.scale.mul_(self.alpha / self.size).add_(self.k)\n\n# torch.pow(self.scale, -self.beta, out=self.output)\n# self.output.mul_(input)\n\n# return self.output\n\n# def updateGradInput(self, input, gradOutput):\n# assert input.dim() == 4\n\n# batchSize = input.size(0)\n# channels = input.size(1)\n# inputHeight = input.size(2)\n# inputWidth = input.size(3)\n\n# if self.paddedRatio is None:\n# self.paddedRatio = input.new()\n# if self.accumRatio is None:\n# self.accumRatio = input.new()\n# self.paddedRatio.resize_(channels + self.size - 1, inputHeight, inputWidth)\n# self.accumRatio.resize_(inputHeight, inputWidth)\n\n# cacheRatioValue = 2 * self.alpha * self.beta / self.size\n# inversePrePad = int(self.size - (self.size - 1) / 2)\n\n# self.gradInput.resize_as_(input)\n# torch.pow(self.scale, -self.beta, out=self.gradInput).mul_(gradOutput)\n\n# self.paddedRatio.zero_()\n# paddedRatioCenter = self.paddedRatio.narrow(0, inversePrePad, channels)\n# for n in range(batchSize):\n# torch.mul(gradOutput[n], self.output[n], out=paddedRatioCenter)\n# paddedRatioCenter.div_(self.scale[n])\n# torch.sum(self.paddedRatio.narrow(0, 0, self.size - 1), 0, out=self.accumRatio)\n# for c in range(channels):\n# self.accumRatio.add_(self.paddedRatio[c + self.size - 1])\n# self.gradInput[n][c].addcmul_(-cacheRatioValue, input[n][c], self.accumRatio)\n# self.accumRatio.add_(-1, self.paddedRatio[c])\n\n# return self.gradInput\n\n# def clearState(self):\n# clear(self, 'scale', 'paddedRatio', 'accumRatio')\n# return super(SpatialCrossMapLRN_temp, self).clearState()\n\n# class SpatialCrossMapLRNFunc(Function):\n# def __init__(self, size, alpha=1e-4, beta=0.75, k=1):\n# self.size = size\n# self.alpha = alpha\n# self.beta = beta\n# self.k = k\n\n# def forward(self, input):\n# self.save_for_backward(input)\n# self.lrn = SpatialCrossMapLRNOld(self.size, self.alpha, self.beta, self.k)\n# self.lrn.type(input.type())\n# return self.lrn.forward(input)\n\n# def backward(self, grad_output):\n# input, = self.saved_tensors\n# return self.lrn.backward(input, grad_output)\n\n# class SpatialCrossMapLRN(nn.Module):\n# def __init__(self, size, alpha=1e-4, beta=0.75, k=1):\n# super(SpatialCrossMapLRN, self).__init__()\n# self.size = size\n# self.alpha = alpha\n# self.beta = beta\n# self.k = k\n\n# def forward(self, input):\n# return CrossMapLRN2d(self.size, alpha = self.alpha, beta = self.beta, k = self.k)(input)\n# # return SpatialCrossMapLRNFunc(self.size, alpha = self.alpha, beta = self.beta, k = self.k)(input)\n\n# class LambdaBase(nn.Sequential):\n# def __init__(self, fn, *args):\n# super(LambdaBase, self).__init__(*args)\n# self.lambda_func = fn\n\n# def forward_prepare(self, input):\n# output = []\n# for module in self._modules.values():\n# output.append(module(input))\n# return output if output else input\n\n# class Lambda(LambdaBase):\n# def forward(self, input):\n# return self.lambda_func(self.forward_prepare(input))\n\n# class LambdaMap(LambdaBase):\n# def forward(self, input):\n# return list(map(self.lambda_func,self.forward_prepare(input)))\n\n# class LambdaReduce(LambdaBase):\n# def forward(self, input):\n# return reduce(self.lambda_func,self.forward_prepare(input))","sub_path":"pytorch/models/render4cnn.py","file_name":"render4cnn.py","file_ext":"py","file_size_in_byte":14857,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"321460339","text":"#!/usr/bin/env python\n#-*- coding:utf-8 -*-\nfrom pyomo.environ import *\nfrom pyomo.dae import *\nimport matplotlib.pyplot as plt\nimport copy\nimport re\nimport load_initials\n\ndifferetial_var = [\"x[*,0]\",\"x[*,1]\",\"x[*,2]\",\"x[*,3]\"]\nderivatives = [\"dxdt[*,0]\",\"dxdt[*,1]\",\"dxdt[*,2]\",\"dxdt[*,3]\"]\nalgebraic_var = [\"y[*,0]\",\"y[*,1]\"]\nre_expression_name = r'^(.*)\\['\nre_expression_index = r'\\[(.*)\\]'\n\ninit_result = {}\nfor i in differetial_var:\n name = re.search(re_expression_name, i).group(1)\n if name not in init_result:\n init_result[name] = {}\nfor i in derivatives:\n name = re.search(re_expression_name, i).group(1)\n if name not in init_result:\n init_result[name] = {}\nfor i in algebraic_var:\n name = re.search(re_expression_name, i).group(1)\n if name not in init_result:\n init_result[name] = {}\n\ndifferetial_var_value = [0,0,0,0]\nalgebraic_var_value = [0,0]\nsolver=SolverFactory('ipopt')\nh=0.2\nstart_time = 0\ntime = []\n\ny1 = []\ny2 = []\n\nfor k in range(100):\n try:\n a_model\n except NameError:\n pass\n else:\n del a_model\n from algebraic_part import model as a_model\n a_model = copy.deepcopy(a_model)\n for i in range(len(differetial_var_value)):\n setattr(a_model,\"ICON_\"+str(i),Constraint(expr=eval(\"a_model.\"+differetial_var[i].replace('*','0')+\"==\"+str(differetial_var_value[i]))))\n results = solver.solve(a_model,tee=False)\n for i in range(len(algebraic_var_value)):\n algebraic_var_value[i] =eval(\" value(a_model.\"+algebraic_var[i].replace('*','0')+\")\\n\")\n init_result[re.search(re_expression_name, algebraic_var[i]).group(1)]\\\n [eval(\"(\"+re.search(re_expression_index, algebraic_var[i]).group(1).replace('*',str(start_time))+\")\")] = algebraic_var_value[i]\n\n #print(algebraic_var_value)\n y1.append(algebraic_var_value[0])\n y2.append(algebraic_var_value[1])\n\n try:\n d_model\n except NameError:\n pass\n else:\n del d_model\n from differential_part import model as d_model\n d_model = copy.deepcopy(d_model)\n for i in range(len(algebraic_var_value)):\n setattr(d_model,\"ICON_A0_\"+str(i),Constraint(expr=eval(\"d_model.\"+algebraic_var[i].replace('*','0')+\"==\"+str(algebraic_var_value[i]))))\n setattr(d_model, \"ICON_A1_\" + str(i),Constraint(expr=eval(\"d_model.\" + algebraic_var[i].replace('*', '1') + \"==\" + str(algebraic_var_value[i]))))\n for i in range(len(differetial_var_value)):\n setattr(d_model,\"ICON_D0_\"+str(i),Constraint(expr=eval(\"d_model.\"+differetial_var[i].replace('*','0')+\"==\"+\\\n str(differetial_var_value[i])+\"+0.25*\"+\"d_model.\"+derivatives[i].replace('*','0')+\"*\"+str(h)+ \\\n \"+(3+2*(3**0.5))/12*\" + \"d_model.\" + derivatives[i].replace('*', '1')+\"*\" + str(h))))\n setattr(d_model, \"ICON_D1_\" + str(i), Constraint(expr=eval(\"d_model.\" + differetial_var[i].replace('*', '1') + \"==\" + \\\n str(differetial_var_value[i]) + \"+(3-2*(3**0.5))/12*\" + \"d_model.\" + derivatives[i].replace('*', '0')+\"*\"+ str(h) + \\\n \"+0.25*\" + \"d_model.\" + derivatives[i].replace('*', '1') + \"*\" + str(h))))\n results = solver.solve(d_model,tee=False)\n for i in range(len(differetial_var_value)):\n differetial_var_value[i] +=h/2*(eval(\" value(d_model.\"+derivatives[i].replace('*','0')+\")\\n\")+ \\\n eval(\" value(d_model.\" + derivatives[i].replace('*', '1') + \")\\n\"))\n init_result[re.search(re_expression_name, differetial_var[i]).group(1)]\\\n [eval(\"(\"+re.search(re_expression_index, differetial_var[i]).group(1).replace('*',str(start_time))+\")\")] = differetial_var_value[i]\n for i in range(len(differetial_var_value)):\n init_result[re.search(re_expression_name, derivatives[i]).group(1)]\\\n [eval(\"(\"+re.search(re_expression_index, derivatives[i]).group(1).replace('*',str(start_time))+\")\")] = \\\n eval(\" value(d_model.\" + derivatives[i].replace('*', '1') + \")\\n\")\n\n #print(differetial_var_value)\n time.append(start_time)\n start_time += h\n\n#-------------------------------------------\n# Save Result\n#-------------------------------------------\nf = open('RK_Init_Result.py', 'w')\nf.write(\"RK_Init_For_Control_System = \"+str(init_result).replace(', (',',\\n(').replace(' {','\\n{'))\nf.write('\\n')\nf.write(\"old_time = \"+str(time))\nf.close()\n#-------------------------------------------\n# Show Result\n#-------------------------------------------\nfig, axes = plt.subplots(1,2)\naxes[0].plot(time,y1, label = 'y1',c='b')\naxes[1].plot(time,y2, label = 'y2',c='b')\n\nfrom use_direct_disc_method import time as direct_disc_time,y1 as direct_disc_y1,y2 as direct_disc_y2\naxes[0].plot(direct_disc_time,direct_disc_y1, label = 'y1',c='r')\naxes[1].plot(direct_disc_time,direct_disc_y2, label = 'y2',c='r')\nfor ax in axes:\n ax.legend(loc=\"best\") #set legend location\nplt.show()\n\n\n\n\n","sub_path":"rk_ini_value/solve_using_RK.py","file_name":"solve_using_RK.py","file_ext":"py","file_size_in_byte":4907,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"15500899","text":"# -*- coding: utf-8 -*-\n\n\nfrom openerp.osv import osv, fields\n\n\nclass flight_control_skydiver(osv.Model):\n _name = 'flight.control.skydiver'\n\n def __fullname(self, cr, uid, ids, field, arg, context=None):\n for skydiver in self.browse(cr, uid, ids):\n fullname = ''.join([skydiver.surname,skydiver.name,skydiver.patronymic])\n return fullname\n return ''\n\n\n def __check_full_name(self,cr,uid,ids):\n for skydiver in self.browse(cr, uid, ids):\n fullname = ''.join([skydiver.surname,skydiver.name,skydiver.patronymic])\n if fullname== '':\n return False # Fullname is empty\n return True\n\n\n _columns = {\n 'surname' : fields.char('Surname', size=64, select=True, help='Surname'),\n 'name' : fields.char('Name', size=64, select=True, help='name' ),\n 'patronymic' : fields.char('Patronymic', size=64, select=True, help='Patronymic'),\n 'status' : fields.selection([('student','Student'),\n ('sportsmen','Sportsmen'), ('coach','Coach')],'State',required=True, select=True),\n # 'fullname' : fields.function(__fullname, type='text', help='Fullname')\n }\n\n _defaults = {\n 'status': 'student',\n }\n\n _description = 'Skydiver info'\n\n _sql_constraints = [('fullname_uniq','unique(surname, name, patronymic)', 'Fullname must be unique!')]\n\n _constraints = [(__check_full_name, 'Fullname is empty !', ['name','surname','patronymic'])]\n\n\nflight_control_skydiver()\n\n\n","sub_path":"flight_control/flight_control_skydiver.py","file_name":"flight_control_skydiver.py","file_ext":"py","file_size_in_byte":1508,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"49385143","text":"class mergesort:\r\n def __init__(self):\r\n self.listOfLists = []\r\n def mergeSortAlgorithm(self,x):\r\n\r\n for i in range(len(x)):\r\n temp = [x[i]]\r\n self.listOfLists.append(temp)\r\n while(len(self.listOfLists) != 1):\r\n j = 0\r\n while(j < len(self.listOfLists)-1):\r\n tempList = self.merge(self.listOfLists[j], self.listOfLists[j+1])\r\n self.listOfLists[j] = tempList\r\n del self.listOfLists[j+1]\r\n print(self.listOfLists[0], \"is sorted!\")\r\n\r\n def merge(self,a, b):\r\n newList = []\r\n count1, count2 = 0, 0\r\n while((count1 < len(a)) and (count2 < len(b))):\r\n if(a[count1] > b[count2]):\r\n newList.append(b[count2])\r\n count2 = count2 + 1\r\n\r\n elif(a[count1] < b[count2]):\r\n newList.append(a[count1])\r\n count1 = count1 + 1\r\n\r\n elif(a[count1] == b[count2]):\r\n newList.append(a[count1])\r\n newList.append(b[count2])\r\n count1, count2 = count1 + 1, count2 + 1\r\n\r\n if(count1 < len(a)):\r\n for f in range(count1, len(a)):\r\n newList.append(a[f])\r\n elif(count2 < len(b)):\r\n for k in range(count2, len(b)):\r\n newList.append(b[k])\r\n\r\n return newList\r\nn=int(input(\"enter length of list:\"))\r\narr=[]\r\nfor i in range(0,n):\r\n arr.append(int(input()))\r\nm=mergesort()\r\nm.mergeSortAlgorithm(arr)\r\n","sub_path":"algo-prakash/mergesort.py","file_name":"mergesort.py","file_ext":"py","file_size_in_byte":1447,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"535896564","text":"import json\n\n\"\"\"\nThis class is for the reading ranges.\n\"\"\"\n\n\nclass ReadingRanges:\n min_temperature = 20\n max_temperature = 30\n min_humidity = 50\n max_humidity = 60\n\n \"\"\"\n Method to create custom instance\n \"\"\"\n def __init__(\n self,\n min_temperature,\n max_temperature,\n min_humidity,\n max_humidity\n ):\n self.min_temperature = min_temperature\n self.max_temperature = max_temperature\n self.min_humidity = min_humidity\n self.max_humidity = max_humidity\n\n \"\"\"\n This method updates the ranges from a json file\n Params: file path for json file\n \"\"\"\n @classmethod\n def update_defaults_from_json(cls, json_file_path):\n with open(json_file_path) as json_file:\n data = json.load(json_file)\n ReadingRanges.validate_range_json(data)\n cls.min_temperature = data[\"min_temperature\"]\n cls.max_temperature = data[\"max_temperature\"]\n cls.min_humidity = data[\"min_humidity\"]\n cls.max_humidity = data[\"max_humidity\"]\n print(\"Updated Defaults from {}\".format(json_file_path))\n\n \"\"\"\n This creates a ranges instance from a json file\n Params: file path for json file\n \"\"\"\n @classmethod\n def from_json(cls, json_file_path):\n with open(jsonFilePath) as json_file:\n data = json.load(json_file)\n ReadingRanges.validate_range_json(data)\n cls(\n data[\"min_temperature\"],\n data[\"max_temperature\"],\n data[\"min_humidity\"],\n data[\"max_humidity\"]\n )\n\n \"\"\"\n This method validates the json object\n \"\"\"\n @staticmethod\n def validate_range_json(data):\n if 'min_temperature' in data and \\\n 'max_temperature' in data and \\\n 'min_humidity' in data and \\\n 'max_humidity' in data:\n return True\n raise Exception('JSON Range file is not valid!')\n","sub_path":"readingRanges.py","file_name":"readingRanges.py","file_ext":"py","file_size_in_byte":2003,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"109765038","text":"\"\"\"\nfile format conversion utility functions\n\"\"\"\nimport pysam\nfrom bcbio.utils import (file_exists, replace_suffix)\nfrom bcbio.distributed.transaction import file_transaction\nimport os\n\ndef expects(fmt):\n \"\"\"\n decorates a function with a file format checker. for example if your function\n foo only excepts bam files:\n\n @expects(\"bam\")\n def foo(in_file):\n return \"bam\"\n\n foo(\"in.bam\") -> \"bam\"\n foo(\"in.sam\") -> ValueError exception thrown\n\n requires two things:\n 1) in_file is the first argument or your function takes a keyword argument in_file\n 2) you have implemented an is_fmt predicate (for example is_bam) that returns True\n if in_file is the right format\n \"\"\"\n def decorator(fn):\n def wrapped(*args, **kwargs):\n in_file = kwargs.get(\"in_file\", None)\n if not in_file:\n in_file = args[0]\n id_fun_string = \"is_\" + fmt\n id_fun = globals().get(id_fun_string)\n if not id_fun:\n _format_detector_not_found(id_fun_string)\n if not id_fun(in_file):\n _wrong_input_file_format(fn, fmt, in_file)\n return fn(*args, **kwargs)\n return wrapped\n return decorator\n\ndef _format_detector_not_found(id_fun_string):\n error_string = \"The file format detector {0} does not exist.\"\n raise ValueError(error_string.format(id_fun_string))\n\ndef _wrong_input_file_format(fn, fmt, in_file):\n error_string = \"{0} expects {1} but {2} is not of that format.\"\n raise ValueError(error_string.format(fn, fmt, in_file))\n\n@expects(\"bam\")\ndef bam2sam(in_file):\n \"\"\"\n converts a bam file to a sam file\n bam2sam(\"file.bam\") -> \"file.sam\"\n \"\"\"\n out_file = replace_suffix(in_file, \".sam\")\n if file_exists(out_file):\n return out_file\n with file_transaction(out_file) as tmp_out_file:\n pysam.view(\"-h\", \"-o\" + tmp_out_file, in_file)\n return out_file\n\n@expects(\"bam\")\ndef bam2sizes(in_file):\n \"\"\"\n converts a bam file to a chromosome sizes file\n chromosome sizes has the format:\n CHROM\tSIZE\n\n For example:\n chr1\t249250621\n chr2\t243199373\n\n bam2sizes(\"in.bam\") -> \"in.sizes\"\n \"\"\"\n base, _ = os.path.splitext(in_file)\n out_file = base + \".sizes\"\n if file_exists(out_file):\n return out_file\n\n header = pysam.Samfile(in_file, 'rb').header\n with file_transaction(out_file) as tmp_out_file:\n with open(tmp_out_file, 'w') as out_handle:\n for line in header['SQ']:\n out_handle.write(\"\\t\".join([line['SN'], str(line['LN'])]) + \"\\n\")\n return out_file\n\n@expects(\"bam\")\ndef bam2freec_len(in_file):\n \"\"\"\n converts a bam file to a chromosome length file for the use with\n Control-FREEC:\n http://bioinfo-out.curie.fr/projects/freec/\n the length file has the format:\n INDEX\tCHROM\tSIZE\n\n For example:\n 1\tchr1\t249250621\n 2\tchr2\t243199373\n\n bam2freec_len(\"in.bam\") -> \"in.len\"\n \"\"\"\n base, _ = os.path.splitext(in_file)\n out_file = base + \".len\"\n if file_exists(out_file):\n return out_file\n\n header = pysam.Samfile(in_file, 'rb').header\n with file_transaction(out_file) as tmp_out_file:\n with open(tmp_out_file, 'w') as out_handle:\n count = 1\n for line in header['SQ']:\n out_handle.write(\"\\t\".join([str(count), line['SN'],\n str(line['LN'])]) + \"\\n\")\n count += 1\n return out_file\n\n\ndef is_sam(in_file):\n _, ext = os.path.splitext(in_file)\n if ext == \".sam\":\n return True\n else:\n return False\n\ndef is_bam(in_file):\n _, ext = os.path.splitext(in_file)\n if ext == \".bam\":\n return True\n else:\n return False\n","sub_path":"bcbio/convert.py","file_name":"convert.py","file_ext":"py","file_size_in_byte":3766,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"132929715","text":"from crudlfap import crudlfap\n\nimport django_tables2 as tables\n\nfrom .views import (\n MRSRequestRejectView,\n MRSRequestProgressView,\n MRSRequestValidateView,\n)\nfrom .models import MRSRequest\n\n\nclass MRSRequestListView(crudlfap.FilterTables2ListView):\n filter_fields = (\n 'status',\n 'institution',\n 'caisse',\n )\n\n table_columns = dict( # our extra columns\n first_name=tables.Column(\n accessor='insured.first_name',\n verbose_name='Prénom',\n order_by=['insured__first_name'],\n ),\n last_name=tables.Column(\n accessor='insured.last_name',\n verbose_name='Nom',\n order_by=['insured__last_name'],\n ),\n nir=tables.Column(\n accessor='insured.nir',\n verbose_name='NIR',\n order_by=['insured__nir'],\n ),\n )\n\n table_sequence = (\n 'creation_datetime',\n 'display_id',\n 'first_name',\n 'last_name',\n 'nir',\n 'status',\n 'institution',\n 'caisse',\n )\n\n search_fields = (\n 'insured__first_name',\n 'insured__last_name',\n 'insured__email',\n 'insured__nir',\n 'institution__finess',\n 'display_id',\n 'caisse__name',\n 'caisse__number',\n 'caisse__code',\n )\n\n def get_queryset(self):\n qs = super().get_queryset()\n qs = qs.select_related('caisse', 'insured')\n return qs\n\n\nclass MRSRequestRouter(crudlfap.Router):\n model = MRSRequest\n material_icon = 'insert_drive_file'\n views = [\n crudlfap.DeleteView,\n crudlfap.DetailView.clone(locks=True),\n MRSRequestValidateView,\n MRSRequestRejectView,\n MRSRequestProgressView,\n MRSRequestListView,\n ]\n\n def allowed(self, view):\n user = view.request.user\n\n if not (user.is_staff or user.is_superuser):\n return False\n\n if view.urlname == 'delete':\n return user.is_superuser\n\n if getattr(view, 'object', None):\n if user.is_superuser:\n return True\n return view.object.caisse in user.caisses.all()\n\n if view.urlname == 'list':\n return True\n\n def get_objects_for_user(self, user, perms):\n if not (user.is_staff or user.is_superuser):\n return self.model.objects.none()\n\n if user.is_superuser:\n return self.model.objects.all()\n\n return self.model.objects.filter(caisse__in=user.caisses.all())\n\nMRSRequestRouter(namespace='mrsrequestrouter').register()\n","sub_path":"src/mrsrequest/crudlfap.py","file_name":"crudlfap.py","file_ext":"py","file_size_in_byte":2600,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"633183532","text":"#!/usr/bin/env python3\n\"\"\"\nServer module\n\n:author: Angelo Cutaia, Claudio Tancredi\n:copyright: Copyright 2020, Angelo Cutaia, Claudio Tancredi\n..\n\n Copyright 2020 Angelo Cutaia\n\n Licensed under the Apache License, Version 2.0 (the \"License\");\n you may not use this file except in compliance with the License.\n You may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\n Unless required by applicable law or agreed to in writing, software\n distributed under the License is distributed on an \"AS IS\" BASIS,\n WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n See the License for the specific language governing permissions and\n limitations under the License.\n\"\"\"\n# Third Party\nimport cherrypy\n\n# Internal\nfrom .catalog.root import Catalog\nfrom .catalog.database import DataBase\nfrom .catalog.mqtt.mqttcherrypy import MqttPlugin, save_device\n\n# Setting\nfrom .catalog.settings import CATALOG_CONFIG, NO_AUTORELOAD\n\n# -----------------------------------------------------------------------------\n\nperiodic_task = cherrypy.process.plugins.BackgroundTask(60, DataBase.delete_old_entries)\n\n\ndef setup():\n DataBase.setup_database()\n DataBase.delete_old_entries()\n periodic_task.start()\n\n\ndef start():\n \"\"\"\n Start the REST server\n \"\"\"\n\n # Mount the Endpoints\n cherrypy.tree.mount(Catalog(), \"/catalog\", CATALOG_CONFIG)\n\n # Update Server Config\n cherrypy.config.update(NO_AUTORELOAD)\n cherrypy.config.update({\"server.socket_host\": \"0.0.0.0\"})\n cherrypy.config.update({\"server.socket_port\": 8080})\n cherrypy.config.update({\"request.show_tracebacks\": False})\n\n # Start the Server\n cherrypy.engine.subscribe(\"start\", setup())\n cherrypy.engine.subscribe(\"stop\", periodic_task.cancel)\n MqttPlugin(\n cherrypy.engine, \"test.mosquitto.org\", 1883, \"catalog/devices\"\n ).subscribe()\n cherrypy.engine.subscribe(\"catalog/devices\", save_device)\n cherrypy.engine.signals.subscribe()\n cherrypy.engine.start()\n cherrypy.engine.block()\n","sub_path":"SW_lab/sw_lab_part2/exercise5/app/server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":2064,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"566707156","text":"# \n# Copyright (c) 2020 Minato Sato\n# All rights reserved.\n#\n# This source code is licensed under the license found in the\n# LICENSE file in the root directory of this source tree.\n#\n\nimport cymf\n\nimport argparse\nparser = argparse.ArgumentParser(description='')\nparser.add_argument('--max_epochs', type=int, default=300)\nparser.add_argument('--num_components', type=int, default=20)\nparser.add_argument('--learning_rate', type=float, default=1e-2)\nparser.add_argument('--weight_decay', type=float, default=1e-2)\nparser.add_argument('--num_threads', type=int, default=8)\n\n\nargs = parser.parse_args()\n\ndataset = cymf.dataset.MovieLens(\"ml-100k\")\n\nvalid_evaluator = cymf.evaluator.AverageOverAllEvaluator(dataset.valid, dataset.train, metrics=[\"DCG\"], k=5)\ntest_evaluator = cymf.evaluator.AverageOverAllEvaluator(dataset.test, dataset.train, k=5)\nmodel = cymf.BPR(num_components=args.num_components, learning_rate=args.learning_rate, weight_decay=args.weight_decay)\nmodel.fit(dataset.train, num_epochs=args.max_epochs, num_threads=args.num_threads, valid_evaluator=valid_evaluator, early_stopping=True)\nprint(test_evaluator.evaluate(model.W, model.H))\n\n","sub_path":"examples/implicit-recsys/bpr_example.py","file_name":"bpr_example.py","file_ext":"py","file_size_in_byte":1150,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"51652820","text":"import re, string\n\n\ndef solve09():\n word = open('inputs/day09.txt').read()\n print('Task 1:', len(decompress(word, False)))\n print('Task 2:', len(decompress(word, True)))\n\n\ndef decompress(word, rec):\n pos = 0\n ret = ''\n while pos < len(word):\n if word[pos] != '(':\n ret += word[pos]\n pos += 1\n else:\n index = word.find(')', pos)\n values = [int(i) for i in re.findall('[0-9]+', word[pos + 1:index])]\n pos = index + 1\n if rec:\n ret += decompress(word[pos:pos + values[0]], True) * values[1]\n else:\n ret += word[pos:pos + values[0]] * values[1]\n pos += values[0]\n return ret\n","sub_path":"AOC2016/day09.py","file_name":"day09.py","file_ext":"py","file_size_in_byte":724,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"552181820","text":"import os\nimport csv\nimport cv2\nimport numpy as np\nimport keras\nfrom keras.models import Sequential\nfrom keras.layers import Flatten, Dense, Lambda, Dropout, ELU\nfrom keras.layers.convolutional import Convolution2D, Cropping2D\nfrom keras.layers.pooling import MaxPooling2D\nfrom keras.optimizers import Adam\nfrom keras import backend as K\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.utils import shuffle\n\ndir_path = os.path.dirname(os.path.realpath(__file__))\nudacity_csv = 'udacity_data/driving_log.csv'\n# trained_csv = 'trained_data/left_track/driving_log.csv'\n# trained_reverse_csv = 'trained_data/left_track_reverse/driving_log.csv'\n# corrections_csv = 'trained_data/corrections/driving_log.csv'\n\n\n############################################\n# Step 1: Read the CSV File\n############################################\nlines = []\nwith open(udacity_csv) as f:\n reader = csv.reader(f)\n for line in reader:\n lines.append(line)\n\ntrain_samples, validation_samples = train_test_split(lines, test_size=0.2)\n\n\n############################################\n# Step 2: Helper Methods for Images, Pass through Generators\n############################################\ndef get_image_and_angle(batch_sample):\n \"\"\"\n :param batch_sample: Row from CSV\n :return: String (path, angle are strings from row)\n \"\"\"\n # Image\n random = np.random.randint(3)\n path = batch_sample[random].strip()\n if path.split('/')[0] == 'IMG':\n path = dir_path + '/udacity_data/' + path\n\n # Angle\n angle = float(batch_sample[3])\n if random == 1:\n angle = angle + 0.22\n if random == 2:\n angle = angle - 0.22\n\n return path, angle\n\ndef shift_img(image, angle):\n \"\"\"\n Random Shift Image\n Inspiration for this Edition:\n source: https://github.com/windowsub0406/Behavior-Cloning/blob/master/model.py\n\n :param image: Numpy Array\n :param angle: Float\n :return: Numpy Array, Float (Altered)\n \"\"\"\n max_shift = 55\n max_ang = 0.14 # ang_per_pixel = 0.0025\n\n rows, cols, _ = image.shape\n\n random_x = np.random.randint(-max_shift, max_shift + 1)\n steer = angle + (random_x / max_shift) * max_ang\n if abs(steer) > 1:\n dst_steer = -1 if (steer < 0) else 1\n\n mat = np.float32([[1, 0, random_x], [0, 1, 0]])\n dst_img = cv2.warpAffine(image, mat, (cols, rows))\n return dst_img, steer\n\ndef flip_image(image, angle):\n \"\"\"\n :param image: Numpy Array\n :param angle: Float\n :return: Numpy Array, Float (Altered)\n \"\"\"\n flip_image = image.copy()\n flip_angle = angle\n num = np.random.randint(2)\n if num == 0:\n flip_image, flip_angle = cv2.flip(image, 1), -angle\n\n return flip_image, flip_angle\n\ndef augment_brightness(image):\n \"\"\"\n :param image: Numpy Array\n :return: Numpy Array, (Altered)\n \"\"\"\n hsv_img = cv2.cvtColor(image, cv2.COLOR_RGB2HSV)\n random = np.random.randint(2)\n\n if random == 0:\n random_bright = 0.2 + np.random.uniform(0.2, 0.6)\n hsv_img[:,:,2] = hsv_img[:,:,2] * random_bright\n hsv_img = cv2.cvtColor(hsv_img, cv2.COLOR_HSV2RGB)\n\n return hsv_img\n\ndef preprocess(image, angle):\n \"\"\"\n :param image: Numpy Array\n :param angle: Float\n :return: Numpy Array, Float (Altered)\n \"\"\"\n image, angle = shift_img(image, angle)\n image, angle = flip_image(image, angle)\n image = augment_brightness(image)\n\n return image, angle\n\ndef train_generator(samples, batch_size=32):\n \"\"\"\n Generators can be a great way to work with large amounts of data.\n Instead of storing the preprocessed data in memory all at once,\n using a generator you can pull pieces of the data and process them\n on the fly only when you need them, which is much more memory-efficient.\n\n :param samples: Array\n :param batch_size: Integer\n :return: Numpy Array (Images and Steering)\n \"\"\"\n num_samples = len(samples)\n while 1:\n shuffle(samples)\n for offset in range(0, num_samples, batch_size):\n batch_samples = samples[offset:offset + batch_size]\n\n images = []\n steering_angles = []\n for batch_sample in batch_samples:\n image, angle = get_image_and_angle(batch_sample)\n image = cv2.imread(image)\n\n image, angle = preprocess(image, angle)\n images.append(image)\n steering_angles.append(angle)\n\n X_train = np.array(images)\n y_train = np.array(steering_angles)\n yield shuffle(X_train, y_train)\n\ndef valid_generator(samples, batch_size=32):\n \"\"\"\n :param samples: Array\n :param batch_size: Integer\n :return: Numpy Array (Images and Steering\n \"\"\"\n image_set = np.zeros((len(validation_samples), 160, 320, 3))\n angles_set = np.zeros(len(validation_samples))\n\n for i in range(len(samples)):\n # Image\n sample = samples[i]\n path = sample[0].strip()\n if path.split('/')[0] == 'IMG':\n path = dir_path + '/udacity_data/' + path\n image = cv2.imread(path)\n # img = image[60:136,0:image.shape[1],:]\n image_set[i] = image\n\n # Angle\n angles_set[i] = float(sample[3])\n\n return image_set, angles_set\n\ntrain_generator = train_generator(train_samples, batch_size=32)\nvalid_generator = valid_generator(validation_samples, batch_size=32)\n\n\n############################################\n# Step 3: Build Models and Execute\n############################################\n\nmodel = Sequential()\n\n# normalization\nmodel.add(Lambda(lambda x: x / 255.0 - 0.5, input_shape=(160, 320, 3)))\nmodel.add(Cropping2D(cropping=((72,25),(0,0))))\n\n# NVIDIA Inspiration\nmodel.add(Convolution2D(24,5,5,subsample=(2,2),activation='relu', name=\"conv0\"))\nmodel.add(MaxPooling2D(pool_size=(2, 2), strides=(1,1)))\n\nmodel.add(Convolution2D(36,5,5,subsample=(2,2),activation='relu', name=\"conv1\"))\nmodel.add(MaxPooling2D(pool_size=(2, 2), strides=(1,1), border_mode='same'))\n\nmodel.add(Convolution2D(48,5,5,subsample=(2,2),activation='relu', name=\"conv2\"))\nmodel.add(MaxPooling2D(pool_size=(2, 2), strides=(1,1), border_mode='same'))\n\nmodel.add(Convolution2D(64,3,3,activation='relu', name=\"conv3\"))\nmodel.add(MaxPooling2D(pool_size=(2, 2), strides=(1,1), border_mode='same'))\n\nmodel.add(Convolution2D(64,3,3, activation='relu', name=\"conv4\"))\nmodel.add(MaxPooling2D(pool_size=(2, 2), strides=(1,1), border_mode='same'))\n\nmodel.add(Flatten())\nmodel.add(Dropout(0.2))\nmodel.add(Dense(1164, activation='relu'))\nmodel.add(Dropout(0.2))\nmodel.add(Dense(100, activation='relu'))\nmodel.add(Dropout(0.2))\nmodel.add(Dense(50, activation='relu'))\nmodel.add(Dropout(0.2))\nmodel.add(Dense(10, activation='relu'))\nmodel.add(Dropout(0.2))\nmodel.add(Dense(1))\n\nadam = Adam(lr=1e-4, beta_1=0.9, beta_2=0.999, epsilon=1e-08, decay=0.0)\nmodel.compile(optimizer=adam, loss='mse')\n\nhistory_object = model.fit_generator(\n train_generator,\n samples_per_epoch=len(train_samples),\n validation_data=valid_generator,\n nb_epoch=5,\n verbose=1)\n\nmodel.save('model.h5')\nK.clear_session()","sub_path":"model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":7075,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"199068412","text":"\"\"\"Base class for integration tests\"\"\"\n\nfrom Products.Five import zcml\nfrom Products.Five import fiveconfigure\nfrom Products.PloneTestCase import PloneTestCase\nfrom Products.PloneTestCase.layer import onsetup\nfrom Products.CMFCore.utils import getToolByName\nfrom Testing import ZopeTestCase\n\nfrom Products.psuauthz.tests.mocks import monkeypatch, unmonkeypatch\n\n@onsetup\ndef setup_umgplugin():\n # Load the ZCML configuration\n fiveconfigure.debug_mode = True\n import Products.psuauthz\n zcml.load_config('configure.zcml', Products.psuauthz)\n fiveconfigure.debug_mode = False\n\n # Tell the testing framework the package is available\n ZopeTestCase.installPackage('Products.psuauthz')\n\nsetup_umgplugin()\nPloneTestCase.setupPloneSite(products=['Products.psuauthz'])\n\n\nclass BaseIntegrationTestCase(PloneTestCase.PloneTestCase):\n\n plugin_id = 'plugin'\n plugin_host = 'host'\n\n def makeOne(self):\n raise NotImplementedError(\"You much define how to make a plugin.\")\n\n def destroyOne(self):\n self._acl_users.manage_delObjects(self.plugin_id)\n\n def beforeTearDown(self):\n self._acl_users.manage_delObjects(self.plugin_id)\n from Products.psuauthz.tests.mocks import unmonkeypatch\n from Products.psuauthz.umg import UserManagedGroupsPlugin\n unmonkeypatch(UserManagedGroupsPlugin)\n\n @property\n def _acl_users(self):\n \"\"\"Return the acl_users folder in the Plone site.\"\"\"\n return getToolByName(self.portal, 'acl_users')\n\n @property\n def _plugin(self):\n return self._acl_users[self.plugin_id]\n\n\nclass BaseUMGIntegrationTestCase(BaseIntegrationTestCase):\n\n plugin_id = 'umg_plugin'\n plugin_host = u'ldap.psu.edu'\n plugin_email_domain = u'psu.edu'\n _items = (\n (u'umg/up.tlt.tltstaff', ('Group',),), # lots of people\n (u'umg/up.weblion.clubsites.admins', ('Group',),), # few people\n (u'umg/up.weblion.clubsites.interns', ('Group',),), # doens't exist\n )\n\n def makeOne(self):\n # Install an umgplugin plugin:\n acl_users = self._acl_users\n # http://wiki.zope.org/zope2/ObjectManager\n constructors = acl_users.manage_addProduct['Products.psuauthz']\n constructors.manage_addUMGPlugin(self.plugin_id, self.plugin_host)\n\n # Activate it:\n # plugins is a PluginRegistry\n plugins = acl_users['plugins']\n from Products.psuauthz.umg import implementedInterfaces\n for interface in implementedInterfaces:\n plugins.activatePlugin(interface, self.plugin_id)\n\n def afterSetUp(self):\n from Products.psuauthz.umg import UserManagedGroupsPlugin\n monkeypatch(UserManagedGroupsPlugin)\n self.makeOne()\n\n def beforeTearDown(self):\n self.destroyOne()\n from Products.psuauthz.umg import UserManagedGroupsPlugin\n unmonkeypatch(UserManagedGroupsPlugin)\n\n\nclass BaseAffilIntegrationTestCase(BaseIntegrationTestCase):\n\n plugin_id = 'affil_plugin'\n plugin_host = u'ldap.psu.edu'\n\n def makeOne(self):\n # Install an umgplugin plugin:\n acl_users = self._acl_users\n # http://wiki.zope.org/zope2/ObjectManager\n constructors = acl_users.manage_addProduct['Products.psuauthz']\n constructors.manage_addAffiliationPlugin(self.plugin_id, self.plugin_host)\n\n # Activate it:\n # plugins is a PluginRegistry\n plugins = acl_users['plugins']\n from Products.psuauthz.affiliation import implementedInterfaces\n for interface in implementedInterfaces:\n plugins.activatePlugin(interface, self.plugin_id)\n\n def afterSetUp(self):\n from Products.psuauthz.affiliation import UserAffiliationPlugin\n monkeypatch(UserAffiliationPlugin)\n self.makeOne()\n\n def beforeTearDown(self):\n self.destroyOne()\n from Products.psuauthz.affiliation import UserAffiliationPlugin\n unmonkeypatch(UserAffiliationPlugin)\n","sub_path":"Products/psuumg/tests/base_integration.py","file_name":"base_integration.py","file_ext":"py","file_size_in_byte":3943,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"112688857","text":"#3.\tTính tổng các số CHẴN nằm trong đoạn từ 0 đến N\r\nn= int(input('nhap n = '))\r\nchan=0\r\nfor i in range (0,n+1):\r\n if( i % 2 ==0 ):\r\n chan += i\r\n print (i) \r\n else:\r\n print()\r\nprint(\"tong cac so chan \", chan)\r\n","sub_path":"Buổi 2/BT3.py.py","file_name":"BT3.py.py","file_ext":"py","file_size_in_byte":256,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"538875765","text":"#coding: UTF-8\n\"\"\"html_render_refactor.py\"\"\"\n\nimport pdb\n\n#Step 1: create Element\n\nclass Element(object):\n \"\"\"docstring for Element\"\"\"\n tag = u'html'\n indent = u' '\n\n def __init__(self, content=None):\n if not content:\n self.content = []\n else:\n self.content = [content]\n\n def append(self, s):\n \"\"\"append method for element\"\"\"\n self.content.append(s)\n\n def render(self, file_out, current_ind=u''):\n file_out.write(current_ind + u'<' + self.tag + u'>\\n')\n\n try:\n for s in self.content:\n file_out.write(current_ind + self.indent + s + u'\\n')\n except TypeError:\n for s in self.content:\n # pdb.set_trace()\n s.render(file_out, current_ind + self.indent)\n\n file_out.write(current_ind + u'\\n')\n\n# Step 2 create subclasses for body and p\nclass Html(Element):\n tag = 'Html'\n\nclass Body(Element):\n tag='body'\n\nclass P(Element):\n tag = 'p'\n\n\n","sub_path":"Students/ebuer/session_06/render/html_render_refactor.py","file_name":"html_render_refactor.py","file_ext":"py","file_size_in_byte":1025,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"382985583","text":"from subprocess import call\nimport numpy as np\nimport sys, glob\nimport stacking_utilities\nimport readmytupledata as rmd\nimport netcdf_read_write as rwr\nimport nsbas\nimport dem_error_correction\nimport sentinel_utilities\n\n\n# LET'S GET A VELOCITY FIELD\ndef drive_velocity_gmtsar(intf_files, nsbas_min_intfs, smoothing, wavelength, rowref, colref, outdir,\n signal_spread_file, baseline_file=None, coh_files=None):\n # GMTSAR DRIVING VELOCITIES\n signal_spread_file = outdir + \"/\" + signal_spread_file; \n intf_tuple = rmd.reader(intf_files);\n coh_tuple = None;\n if coh_files is not None:\n coh_tuple = rmd.reader(coh_files);\n signal_spread_data = rwr.read_grd(signal_spread_file);\n velocities = nsbas.Velocities(intf_tuple, nsbas_min_intfs, smoothing, wavelength, rowref, colref,\n signal_spread_data, baseline_file=baseline_file, coh_tuple=coh_tuple);\n rwr.produce_output_netcdf(intf_tuple.xvalues, intf_tuple.yvalues, velocities, 'mm/yr', outdir + '/velo_nsbas.grd');\n rwr.produce_output_plot(outdir + '/velo_nsbas.grd', 'LOS Velocity', outdir + '/velo_nsbas.png', 'velocity (mm/yr)');\n return;\n\n\n# LET'S GET SOME PIXELS AND OUTPUT THEIR TS. \ndef drive_point_ts_gmtsar(intf_files, ts_points_file, smoothing, wavelength, rowref, colref, outdir,\n baseline_file=None, coh_files=None, geocoded_flag=0):\n # For general use, please provide a file with [lon, lat, row, col, name]\n lons, lats, names, rows, cols = stacking_utilities.drive_cache_ts_points(ts_points_file, intf_files[0], geocoded_flag);\n if lons is None:\n return;\n outdir = outdir + \"/ts\";\n print(\"TS OUTPUT DIR IS: \" + outdir);\n call(['mkdir', '-p', outdir], shell=False);\n print(\"Computing TS for %d pixels\" % len(lons));\n intf_tuple = rmd.reader(intf_files);\n coh_tuple = None; \n coh_value = None;\n if coh_files is not None:\n coh_tuple = rmd.reader(coh_files);\n datestrs, x_dts, x_axis_days = nsbas.get_TS_dates(intf_tuple.date_pairs_julian);\n reference_pixel_vector = intf_tuple.zvalues[:, rowref, colref];\n\n for i in range(len(rows)):\n pixel_value = intf_tuple.zvalues[:, rows[i], cols[i]];\n pixel_value = np.subtract(pixel_value, reference_pixel_vector); # with respect to the reference pixel. \n if coh_tuple is not None:\n coh_value = coh_tuple.zvalues[:, rows[i], cols[i]];\n stacking_utilities.write_testing_pixel(intf_tuple, pixel_value, coh_value, outdir+'/testing_pixel_'+str(i)+'.txt');\n m_cumulative = nsbas.do_nsbas_pixel(pixel_value, intf_tuple.date_pairs_julian, smoothing, wavelength, datestrs,\n coh_value=coh_value);\n\n # If we're using DEM error, then we pass in the baseline table.\n if baseline_file is not None:\n m_cumulative = dem_error_correction.driver(m_cumulative, datestrs, baseline_file);\n\n nsbas.nsbas_ts_points_outputs(x_dts, m_cumulative, rows[i], cols[i], names[i], lons[i], lats[i], outdir);\n return;\n\n\n# LET'S GET THE FULL TS FOR EVERY PIXEL\ndef drive_full_TS_gmtsar(intf_files, nsbas_min_intfs, sbas_smoothing, wavelength, rowref, colref, outdir, \n signal_spread_file, baseline_file=None, coh_files=None):\n # SETUP. \n start_index = 0;\n end_index = 7000000;\n signal_spread_file = outdir + \"/\" + signal_spread_file;\n\n intf_tuple = rmd.reader(intf_files);\n coh_tuple = None;\n if coh_files is not None:\n coh_tuple = rmd.reader(coh_files);\n xdates = stacking_utilities.get_xdates_from_intf_tuple(intf_tuple);\n signal_spread_data = rwr.read_grd(signal_spread_file);\n\n # TIME SERIES\n TS = nsbas.Full_TS(intf_tuple, nsbas_min_intfs, sbas_smoothing, wavelength, rowref, colref, signal_spread_data,\n start_index=start_index, end_index=end_index, baseline_file=baseline_file, coh_tuple=coh_tuple);\n rwr.produce_output_TS_grids(intf_tuple.xvalues, intf_tuple.yvalues, TS, xdates, 'mm', outdir);\n return;\n\n\ndef make_vels_from_ts_grids(ts_dir, geocoded=False):\n if geocoded:\n filelist = glob.glob(ts_dir + \"/publish/*_ll.grd\");\n mydata = rmd.reader_from_ts(filelist, \"lon\", \"lat\", \"z\"); # put these if using geocoded values\n else:\n filelist = glob.glob(ts_dir + \"/????????.grd\");\n mydata = rmd.reader_from_ts(filelist);\n vel = nsbas.Velocities_from_TS(mydata);\n rwr.produce_output_netcdf(mydata.xvalues, mydata.yvalues, vel, 'mm/yr', ts_dir + '/velo_nsbas.grd');\n rwr.produce_output_plot(ts_dir + '/velo_nsbas.grd', 'LOS Velocity', ts_dir + '/velo_nsbas.png', 'velocity (mm/yr)');\n return;\n\n\n# LET'S GET THE FULL TS FOR UAVSAR/ISCE FILES.\ndef drive_full_TS_isce(intf_files, nsbas_min_intfs, sbas_smoothing, wavelength, rowref, colref, outdir,\n baseline_file=None, coh_files=None):\n # SETUP. \n signal_spread_file = outdir + \"/signalspread_cut.nc\"\n intf_tuple = rmd.reader_isce(intf_files);\n coh_tuple = None;\n if coh_files is not None:\n coh_tuple = rmd.reader_isce(coh_files);\n xdates = stacking_utilities.get_xdates_from_intf_tuple(intf_tuple);\n signal_spread_data = rwr.read_grd(signal_spread_file);\n\n # TIME SERIES\n TS = nsbas.Full_TS(intf_tuple, nsbas_min_intfs, sbas_smoothing, wavelength, rowref, colref, signal_spread_data,\n baseline_file=baseline_file, coh_tuple=coh_tuple);\n\n # OUTPUTS\n TS_NC_file = outdir + \"/TS.nc\";\n TS_image_file = outdir + \"/TS.png\";\n rwr.produce_output_timeseries(intf_tuple.xvalues, intf_tuple.yvalues, TS, xdates, 'mm', TS_NC_file);\n stacking_utilities.plot_full_timeseries(TS_NC_file, xdates, TS_image_file, vmin=-50, vmax=200, aspect=1 / 8);\n return;\n\n\n","sub_path":"stacking_tools/nsbas_accessing.py","file_name":"nsbas_accessing.py","file_ext":"py","file_size_in_byte":5793,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"438446082","text":"# Line Styles and Widths\nimport pylab\n\nif __name__ == '__main__':\n\tax = pylab.linspace(0.1, 1., 100)\n\tayi = 1. / ax\n\taye = 10. * pylab.exp(-2. * ax)\n\t\n\tpylab.plot(ax, ayi, color='r', linestyle=':', linewidth=4.)\n\tpylab.plot(ax, aye, color='m', linestyle='--', linewidth=2.)\n\tpylab.show()\n","sub_path":"Scientific-Programming/Learning Scientific Programming With Python/Chp03 - Plotting With Pylab/plotlinestyles.py","file_name":"plotlinestyles.py","file_ext":"py","file_size_in_byte":288,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"123790121","text":"import numpy as np\r\nimport csv\r\nimport sys\r\nimport os\r\nimport json\r\nimport keras\r\nfrom keras.layers import Input, Conv2D, UpSampling2D, Lambda, SpatialDropout2D, Dense, Layer, Activation, BatchNormalization, MaxPool2D, concatenate, LocallyConnected2D\r\nfrom keras.models import Model, Sequential\r\nfrom keras.models import model_from_json, load_model\r\nfrom keras.utils import multi_gpu_model\r\nfrom keras.utils.np_utils import to_categorical\r\nimport keras.backend as K\r\nfrom keras.callbacks import TensorBoard, TerminateOnNaN, ModelCheckpoint\r\nfrom keras.callbacks import Callback as CallbackBase\r\nfrom keras.preprocessing.image import ImageDataGenerator as oldImageDataGenerator\r\nfrom keras.initializers import Constant\r\nfrom optparse import OptionParser # TODO update to ArgParser (python2 --> python3)\r\nimport nibabel as nib\r\nfrom scipy import ndimage\r\nfrom sklearn.model_selection import KFold\r\nimport skimage.transform\r\nimport tensorflow as tf\r\nimport matplotlib as mptlib\r\n#mptlib.use('TkAgg')\r\nimport matplotlib.pyplot as plt\r\n\r\n\r\nimport settings \r\n#from tweaked_ImageGenerator_v2 import ImageDataGenerator\r\nfrom generator import customImageDataGenerator as ImageDataGenerator\r\n\r\n\r\n###\r\n### Training: build NN model from anonymized data\r\n###\r\ndef TrainModel(idfold=0):\r\n\r\n from setupmodel import GetSetupKfolds, GetCallbacks, GetOptimizer, GetLoss\r\n from buildmodel import get_unet, thick_slices\r\n\r\n ###\r\n ### load data\r\n ###\r\n\r\n kfolds = settings.options.kfolds\r\n\r\n print('loading memory map db for large dataset')\r\n numpydatabase = np.load(settings._globalnpfile)\r\n (train_index,test_index) = GetSetupKfolds(settings.options.dbfile, kfolds, idfold)\r\n\r\n print('copy data subsets into memory...')\r\n axialbounds = numpydatabase['axialtumorbounds']\r\n dataidarray = numpydatabase['dataid']\r\n dbtrainindex= np.isin(dataidarray, train_index )\r\n dbtestindex = np.isin(dataidarray, test_index )\r\n subsetidx_train = np.all( np.vstack((axialbounds , dbtrainindex)) , axis=0 )\r\n subsetidx_test = np.all( np.vstack((axialbounds , dbtestindex )) , axis=0 )\r\n if np.sum(subsetidx_train) + np.sum(subsetidx_test) != min(np.sum(axialbounds ),np.sum(dbtrainindex )) :\r\n raise(\"data error: slice numbers dont match\")\r\n\r\n print('copy memory map from disk to RAM...')\r\n trainingsubset = numpydatabase[subsetidx_train]\r\n\r\n np.random.seed(seed=0)\r\n np.random.shuffle(trainingsubset)\r\n totnslice = len(trainingsubset)\r\n\r\n if settings.options.D3:\r\n x_data = trainingsubset['imagedata']\r\n y_data = trainingsubset['truthdata']\r\n \r\n x_train = thick_slices(x_data, settings.options.thickness)\r\n y_train = thick_slices(y_data, settings.options.thickness)\r\n else: \r\n x_train=trainingsubset['imagedata']\r\n y_train=trainingsubset['truthdata']\r\n \r\n\r\n slicesplit = int(0.9 * totnslice)\r\n TRAINING_SLICES = slice( 0, slicesplit)\r\n VALIDATION_SLICES = slice(slicesplit, totnslice )\r\n\r\n print(\"\\nkfolds : \", kfolds)\r\n print(\"idfold : \", idfold)\r\n print(\"slices in kfold : \", totnslice)\r\n print(\"slices training : \", slicesplit)\r\n print(\"slices validation : \", totnslice - slicesplit)\r\n try:\r\n print(\"slices testing : \", len(numpydatabase[subsetidx_test]))\r\n except:\r\n print(\"slices testing : 0\")\r\n\r\n\r\n ###\r\n ### data preprocessing : applying liver mask\r\n ###\r\n y_train_typed = y_train.astype(settings.SEG_DTYPE)\r\n\r\n liver_idx = y_train_typed > 0\r\n y_train_liver = np.zeros_like(y_train_typed)\r\n y_train_liver[liver_idx] = 1\r\n\r\n tumor_idx = y_train_typed > 1\r\n y_train_tumor = np.zeros_like(y_train_typed)\r\n y_train_tumor[tumor_idx] = 1\r\n\r\n x_masked = x_train * y_train_liver - 100.0*(1.0 - y_train_liver)\r\n x_masked = x_masked.astype(settings.IMG_DTYPE)\r\n\r\n\r\n ###\r\n ### set up output, logging, and callbacks\r\n ###\r\n logfileoutputdir= '%s/%03d/%03d' % (settings.options.outdir, kfolds, idfold)\r\n os.system ('mkdir -p ' + logfileoutputdir)\r\n os.system ('mkdir -p ' + logfileoutputdir + '/nii')\r\n os.system ('mkdir -p ' + logfileoutputdir + '/tumor')\r\n print(\"Output to\\t\", logfileoutputdir)\r\n\r\n\r\n\r\n ###\r\n ### create and run model\r\n ###\r\n opt = GetOptimizer()\r\n callbacks, modelloc = GetCallbacks(logfileoutputdir, \"tumor\")\r\n lss, met = GetLoss()\r\n model = get_unet()\r\n model.compile(loss = lss,\r\n metrics = met,\r\n optimizer = opt)\r\n\r\n print(\"\\n\\n\\tlivermask training...\\tModel parameters: {0:,}\".format(model.count_params()))\r\n\r\n if settings.options.augment:\r\n train_datagen = ImageDataGenerator(\r\n brightness_range=[0.95,1.05],\r\n width_shift_range=[-0.1,0.1],\r\n height_shift_range=[-0.1,0.1],\r\n horizontal_flip=True,\r\n vertical_flip=True,\r\n zoom_range=0.1,\r\n fill_mode='nearest',\r\n )\r\n test_datagen = ImageDataGenerator()\r\n else:\r\n train_datagen = oldImageDataGenerator()\r\n test_datagen = oldImageDataGenerator()\r\n \r\n\r\n if settings.options.D3: \r\n train_generator = train_datagen.flow(x=x_masked[TRAINING_SLICES,:,:,:, np.newaxis],\r\n y=y_train_tumor[TRAINING_SLICES,:,:,:, np.newaxis],\r\n batch_size=settings.options.trainingbatch)\r\n test_generator = test_datagen.flow(x=x_masked[TRAINING_SLICES,:,:,:, np.newaxis],\r\n y=y_train_tumor[TRAINING_SLICES,:,:,:, np.newaxis],\r\n batch_size=settings.options.validationbatch)\r\n else: \r\n train_generator = train_datagen.flow(x=x_masked[TRAINING_SLICES,:,:,np.newaxis],\r\n y=y_train_tumor[TRAINING_SLICES,:,:,np.newaxis],\r\n batch_size=settings.options.trainingbatch)\r\n test_generator = test_datagen.flow(x=x_masked[VALIDATION_SLICES,:,:,np.newaxis],\r\n y=y_train_tumor[VALIDATION_SLICES,:,:,np.newaxis],\r\n batch_size=settings.options.validationbatch)\r\n \r\n history_liver = model.fit_generator(\r\n train_generator,\r\n steps_per_epoch= slicesplit // settings.options.trainingbatch,\r\n validation_steps = (totnslice - slicesplit) // settings.options.validationbatch,\r\n epochs=settings.options.numepochs,\r\n validation_data=test_generator,\r\n callbacks=callbacks)\r\n\r\n\r\n\r\n ###\r\n ### make predicions on validation set\r\n ###\r\n print(\"\\n\\n\\tapplying models...\")\r\n if settings.options.D3:\r\n y_pred_float = model.predict( x_masked[VALIDATION_SLICES,:,:,:,np.newaxis] )\r\n else: \r\n y_pred_float = model.predict( x_masked[VALIDATION_SLICES,:,:,np.newaxis] )\r\n \r\n y_pred_seg = (y_pred_float[...,0] >= settings.options.segthreshold).astype(settings.SEG_DTYPE)\r\n\r\n print(\"\\tsaving to file...\")\r\n \r\n if settings.options.D3:\r\n trueinnii = nib.Nifti1Image(x_train [VALIDATION_SLICES,:,:,:] , None )\r\n truesegnii = nib.Nifti1Image(y_train [VALIDATION_SLICES,:,:,:] , None )\r\n truelivernii = nib.Nifti1Image(y_train_liver[VALIDATION_SLICES,:,:,:] , None )\r\n truetumornii = nib.Nifti1Image(y_train_tumor[VALIDATION_SLICES,:,:,:] , None )\r\n else: \r\n trueinnii = nib.Nifti1Image(x_train [VALIDATION_SLICES,:,:] , None )\r\n truesegnii = nib.Nifti1Image(y_train [VALIDATION_SLICES,:,:] , None )\r\n truelivernii = nib.Nifti1Image(y_train_liver[VALIDATION_SLICES,:,:] , None )\r\n truetumornii = nib.Nifti1Image(y_train_tumor[VALIDATION_SLICES,:,:] , None )\r\n \r\n\r\n \r\n predsegnii = nib.Nifti1Image(y_pred_seg, None )\r\n predfloatnii = nib.Nifti1Image(y_pred_float, None)\r\n \r\n trueinnii.to_filename( logfileoutputdir+'/nii/trueimg.nii.gz')\r\n truesegnii.to_filename( logfileoutputdir+'/nii/truseg.nii.gz')\r\n truelivernii.to_filename( logfileoutputdir+'/nii/trueliver.nii.gz')\r\n truetumornii.to_filename( logfileoutputdir+'/nii/truetumor.nii.gz')\r\n predsegnii.to_filename( logfileoutputdir+'/nii/predtumorseg.nii.gz')\r\n predfloatnii.to_filename( logfileoutputdir+'/nii/predtumorfloat.nii.gz')\r\n\r\n print(\"\\done saving.\")\r\n return modelloc\r\n\r\n\r\n","sub_path":"tumorcode_aws/trainmodel.py","file_name":"trainmodel.py","file_ext":"py","file_size_in_byte":8198,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"27127744","text":"from __future__ import print_function\nimport xarray as xr\nimport os\nimport numpy as np\nimport sys\nimport glob\nimport timeit\nimport warnings\nwarnings.simplefilter(action='ignore')\nfrom calendar import monthrange\nfrom datetime import date\nfrom functions import get_lat_lon_lwp_iwp_from_hdf\n\ndef gridding_data():\n for i in range(nlats):\n for j in range(nlons):\n slat = bd_lats[i]\n nlat = bd_lats[i+1]\n llon = bd_lons[j]\n rlon = bd_lons[j+1]\n\n ind = (lats>=slat) & (lats<=nlat) & (lons>=llon) & (lons<=rlon)\n if np.sum(ind)>0:\n lwp_grid_dt[i,j] = np.nansum([ lwp_grid_dt[i,j], np.nanmean(lwp[ind]) ])\n iwp_grid_dt[i,j] = np.nansum([ iwp_grid_dt[i,j], np.nanmean(iwp[ind]) ])\n visit_dt[i,j] = visit_dt[i,j] + 1\n else:\n lwp_grid_dt[i,j] = np.nansum([lwp_grid_dt[i,j], np.nan])\n iwp_grid_dt[i,j] = np.nansum([iwp_grid_dt[i,j], np.nan])\n\nif __name__ == '__main__':\n P = os.path.join\n saved_dir = './output_data/lwp_iwp_year_dt_flip_lon_t42_2015_2016'\n if not os.path.exists(saved_dir):\n os.makedirs(saved_dir)\n\n ## Read t42 lat lon boundary and lat lons from dataset\n t42_fn = 'atmos_monthly.nc'\n ds_t42 = xr.open_dataset(t42_fn, decode_times=False)\n bd_lats = ds_t42.latb.values\n bd_lons = ds_t42.lonb.values\n lats1 = ds_t42.lat.values\n lons1 = ds_t42.lon.values\n nlats = len(lats1)\n nlons = len(lons1)\n\n '''\n bd_lats = np.arange(-90, 91, 1)\n bd_lons = np.arange(-180, 181, 1)\n nlats = len(bd_lats)-1\n nlons = len(bd_lons)-1\n lats1 = (bd_lats[0:-1]+bd_lats[1:]) / 2.0\n lons1 = (bd_lons[0:-1]+bd_lons[1:]) / 2.0\n '''\n lwp_grid_dt_year = np.zeros((12, nlats, nlons))\n iwp_grid_dt_year = np.zeros((12, nlats, nlons))\n visit_dt_year = np.zeros((12, nlats, nlons))\n\n basedir = 'ftp.cloudsat.cira.colostate.edu/2B-CWC-RO.P1_R05/'\n\n # input year from command line\n year = int(sys.argv[1]) #2016\n\n start = timeit.default_timer()\n for mm, mon in enumerate(range(12)): \n i_mon = mon+1\n print('Year, mon ', year, i_mon)\n\n # save data each month\n lwp_grid_dt = np.zeros((nlats, nlons))\n iwp_grid_dt = np.zeros((nlats, nlons))\n visit_dt = np.zeros((nlats, nlons))\n\n days_in_mon = monthrange(year, i_mon)[1]\n for d in range(days_in_mon):\n day = (date(year, i_mon, d+1) - date(year, 1, 1)).days + 1\n day_str = str(day).zfill(3)\n print('day = ', day)\n\n start_d = timeit.default_timer()\n\n fns = sorted(glob.glob(P(basedir, str(year), day_str, '*.hdf')))\n for kk, fn in enumerate(fns):\n start1 = timeit.default_timer()\n print(os.path.basename(fn))\n\n lats, lons, lwp, iwp = get_lat_lon_lwp_iwp_from_hdf(fn)\n print('mean lwp/iwp:', np.nanmean(lwp), np.nanmean(iwp))\n\n gridding_data()\n\n stop = timeit.default_timer()\n print(kk, ' Time has passed: ', stop - start1)\n\n stop = timeit.default_timer()\n print('Day ', day, ' Time has passed: ', stop - start_d)\n print('Day ', day, ' Total time has passed: ', stop - start)\n print('')\n\n lwp_grid_dt_year[mm,] = lwp_grid_dt\n iwp_grid_dt_year[mm,] = iwp_grid_dt\n visit_dt_year[mm,] = visit_dt\n\n stop = timeit.default_timer()\n print('month ', i_mon, 'Total time has passed: ', stop - start)\n\n # ====================== save data sets ====================== \n visit_dt = xr.DataArray(visit_dt, dims=('lat', 'lon'), coords=(lats1, lons1))\n lwp_grid_dt = xr.DataArray(lwp_grid_dt, dims=('lat', 'lon'), coords=(lats1, lons1))\n iwp_grid_dt = xr.DataArray(iwp_grid_dt, dims=('lat', 'lon'), coords=(lats1, lons1))\n\n coords = {'lat': lats1, 'lon': lons1}\n mon_str = str(i_mon).zfill(2)\n\n visit_ds = xr.Dataset({'visit_num':visit_dt}, coords=coords)\n visit_ds.to_netcdf(P(saved_dir, 'visit_num_'+str(year)+mon_str+'.nc'), format='NETCDF4_CLASSIC', mode='w')\n\n lwp_ds = xr.Dataset({'lwp_sum':lwp_grid_dt}, coords=coords)\n lwp_ds.to_netcdf(P(saved_dir, 'lwp_sum_'+str(year)+mon_str+'.nc'), format='NETCDF4_CLASSIC', mode='w')\n\n iwp_ds = xr.Dataset({'iwp_sum':iwp_grid_dt}, coords=coords)\n iwp_ds.to_netcdf(P(saved_dir, 'iwp_sum_'+str(year)+mon_str+'.nc'), format='NETCDF4_CLASSIC', mode='w')\n\n print('monthly dataset saved...')\n\n # ====================== save yearly data set====================== \n mons = np.arange(1, 13, 1) \n visit_dt_year = xr.DataArray(visit_dt_year, dims=('month', 'lat', 'lon'), coords=(mons, lats1, lons1))\n lwp_grid_dt_year = xr.DataArray(lwp_grid_dt_year, dims=('month', 'lat', 'lon'), coords=(mons, lats1, lons1))\n iwp_grid_dt_year = xr.DataArray(iwp_grid_dt_year, dims=('month', 'lat', 'lon'), coords=(mons, lats1, lons1))\n\n coords = {'month': mons, 'lat': lats1, 'lon': lons1}\n visit_yr_ds = xr.Dataset({'visit_num':visit_dt_year}, coords=coords)\n visit_yr_ds.to_netcdf(P(saved_dir, 'visit_num_'+str(year)+'.nc'), format='NETCDF4_CLASSIC', mode='w')\n\n lwp_yr_ds = xr.Dataset({'lwp_sum':lwp_grid_dt_year}, coords=coords)\n lwp_yr_ds.to_netcdf(P(saved_dir, 'lwp_sum_'+str(year)+'.nc'), format='NETCDF4_CLASSIC', mode='w')\n\n iwp_yr_ds = xr.Dataset({'iwp_sum':iwp_grid_dt_year}, coords=coords)\n iwp_yr_ds.to_netcdf(P(saved_dir, 'iwp_sum_'+str(year)+'.nc'), format='NETCDF4_CLASSIC', mode='w')\n print('yearly dataset saved...')\n","sub_path":"get_accumulated_gridded_data_mon.py","file_name":"get_accumulated_gridded_data_mon.py","file_ext":"py","file_size_in_byte":5646,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"376031012","text":"import sqlite3\n\ndb = sqlite3.connect(\"default_v2.sqlite\")\ncursor = db.cursor()\n\n# open the dicationary txt file\nfile = open(\"query_dictionary.txt\", 'r')\n# per line in file, add to db\nline = file.readline()\nwhile line != '':\n\tif line != '\\n':\n\t\tcursor.execute('INSERT INTO triggers (trigger) VALUES (?)', (line.strip(),))\n\tline = file.readline()\nfile.close()\n\n# open the order dictionary txt file\nfile = open(\"order_dictionary.txt\", 'r')\n# per line in file, add to db\nline = file.readline()\nwhile line != '':\n\tif line != '\\n':\n\t\tcursor.execute('INSERT INTO orders (name) VALUES (?)', (line.strip(),))\n\tline = file.readline()\nfile.close()\n\ndb.commit()\ndb.close()","sub_path":"ersim/extra/database_loader.py","file_name":"database_loader.py","file_ext":"py","file_size_in_byte":660,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"367075394","text":"#!/usr/bin/python3\nimport sys\nimport json\nfrom os import path, _exit\nfrom functools import wraps\n\nimport flask\nimport bcrypt\nfrom watchdog.observers import Observer\nfrom watchdog.events import FileSystemEventHandler\n\nsys.path.append(path.join(path.dirname(__file__), '../command_line'))\nfrom owo import add_file, add_user, add_comment, \\\n rm_comment, mark_user, mark_task, \\\n update_avatar, take_task, reject_task, \\\n authorize\nfrom common import get_db_connection, \\\n assert_ok_dbname\n\ngame_id = None # Must be replaced when executing\n\napp = flask.Flask(__name__)\n\ndef _parse_mysql_vomit(vomit:list) -> list:\n \"\"\"Takes mysql's cursor's fetchall() result and returns it beautified\n if there was one field in SELECT, otherwise raises a ValueError\n Parameters:\n vomit(list[tuple[X]]): A mysql's cursor's fetchall() result\n Returns:\n list[X]: The beautified result as a map object (see examples below)\n Examples:\n list(_parse_mysql_vomit([(1,), (2,), (\"x\",)])) == [1, 2, \"x\"]\n list(_parse_mysql_vomit([(1, 2), (3, 4)])) -> ValueError\n \"\"\"\n if not all(map(lambda x: len(x) == 1, vomit)):\n raise ValueError(\"Only one field must be requested in the sql query\")\n return map(lambda x: x[0], vomit)\n\ndef get_user_info(user_id:str) -> dict:\n \"\"\"Returns the user info like a dict\n Parameters:\n user_id(str): The user identifier\n Returns:\n dict: A dict with the following keys:\n login(str) - the user login\n is_captain(bool) - if the user is a captain\n avatar(str or NoneType) - the avatar file id\n solving(list[str]) - ids of tasks took by the user\n\n If the user doesn't exist, the returned dict will be:\n {'login': 'DELETED', 'is_captain': False, 'avatar': None,\n 'solving': []}\n \"\"\"\n assert_ok_dbname(game_id)\n db = get_db_connection()\n c = db.cursor()\n c.execute('USE OvO_' + game_id)\n c.execute('SELECT is_captain, avatar FROM users WHERE login=(%s)',\n (user_id,))\n user_info = c.fetchone()\n if user_info is None:\n return {'login': 'DELETED', 'is_captain': False, 'avatar': None, 'solving': []}\n else:\n c.execute('SELECT task_id FROM solvings WHERE user_id=(%s)', (user_id,))\n return {'login': user_id, 'is_captain': (True if user_info[0] == 'Y' else False),\n 'avatar': user_info[1], 'solving': list(_parse_mysql_vomit(c.fetchall()))}\n\ndef get_task_info(task_id:str) -> dict:\n \"\"\"Returns the task info like a dict\n Parameters:\n task_id(str): The task identifier\n Returns:\n dict: A dict with the following keys:\n id(str) - The task identifier\n name(str) - The task name\n is_solved(bool) - If the task solved or not\n original_link(str or NoneType) - The link to the task on the main platform\n original_id(str or NoneType) - The task identifier on main platform\n text(str or NoneType) - The task text\n solvers(list[str]) - ids of users, who took the task\n \"\"\"\n assert_ok_dbname(game_id)\n db = get_db_connection()\n c = db.cursor()\n c.execute('USE OvO_' + game_id)\n c.execute('SELECT * FROM tasks WHERE id=(%s)', (task_id,))\n ans = dict(zip(['id', 'name', 'is_solved', 'original_link', 'original_id', 'text'],\n c.fetchone()))\n ans['is_solved'] = True if ans['is_solved'] == 'Y' else False\n c.execute('SELECT user_id FROM solvings WHERE task_id=(%s)', (task_id,))\n ans['solvers'] = list(_parse_mysql_vomit(c.fetchall()))\n return ans\n\ndef get_comment_info(comment_id:str) -> dict:\n \"\"\"Returns the comment info like a dict\n Parameters:\n comment_id(str): The comment identifier\n Returns:\n dict: A dict with the following keys:\n id(str) - The comment identifier\n task_id(str) - The identifier of the task the comment attached to\n user_id(str) - The comment's author identifier\n text(str or NoneType) - The comment text\n attached_files(list[str]) - A list of ids of files attached to the comment\n \"\"\"\n assert_ok_dbname(game_id)\n db = get_db_connection()\n c = db.cursor()\n c.execute('USE OvO_' + game_id)\n c.execute('SELECT * FROM comments WHERE id=(%s)', (comment_id,))\n ans = dict(zip(['id', 'task_id', 'user_id', 'text', 'attached_files'], c.fetchone()))\n ans['attached_files'] = json.loads(ans['attached_files'])\n return ans\n\ndef get_game_info() -> dict:\n \"\"\"Returns the game info as a dict\n Returns:\n dict: A dict with the following keys:\n port(int) - The network port to run web interface on\n files_folder(str) - A path to the folder for game files\n register_pass(str) - A password, required for registration (bcrypt)\n captain_pass(str) - A password, required for registering as\n a captain (bcrypt)\n judge_url(str or NoneType) - The main platform URL\n judge_login(str or NoneType) - A username for the main platform\n judge_pass(str or NoneType) - A password for the main platform\n \"\"\"\n assert_ok_dbname(game_id)\n db = get_db_connection()\n c = db.cursor()\n c.execute('USE OvO_' + game_id)\n c.execute('SELECT * FROM game_info')\n ans = dict(zip(['port', 'files_folder', 'register_pass', 'captain_pass', \\\n 'judge_url', 'judge_login', 'judge_pass'], c.fetchone()))\n return ans\n\ndef get_user_info_s(session_id:str) -> dict:\n \"\"\"Returns the user info by his session id\n Parameters:\n session_id(str): The session identifier\n Returns:\n dict: User info (got from `get_user_info`)\n\n Raises ValueError if the session id doesn't exist\n \"\"\"\n assert_ok_dbname(game_id)\n db = get_db_connection()\n c = db.cursor()\n c.execute('USE OvO_' + game_id)\n c.execute('SELECT user_id FROM session_data WHERE session_id=(%s)',\n (session_id,))\n tmp = c.fetchone()\n if tmp is None:\n raise ValueError(\"Invalid session id\")\n return get_user_info(tmp[0])\n\ndef assert_is_authorized(func):\n \"\"\"A decorator for flask route functions.\n Interrupts with 403 status code if\n the request came from an unauthorized\n user\n \"\"\"\n @wraps(func)\n def ans(*args, **kwargs):\n try:\n get_user_info_s(flask.request.cookies['session_id'])\n except (KeyError, ValueError):\n return flask.abort(403)\n\n return func(*args, **kwargs)\n\n return ans\n\ndef check_given_params(required_params:set,\n all_params:set, given_params:set) -> bool:\n \"\"\"Checks if all the required params where given\n and all the given params are valid\n Parameters:\n required_params(set): The set of params keys\n required for the method\n all_params(set): The set of valid params keys\n for the method\n given_params(set): The set of given params keys\n Returns:\n bool: True, if the given params are correct,\n otherwise False\n \"\"\"\n if len(required_params.intersection(given_params)) < \\\n len(required_params):\n return False\n if len(given_params - all_params) > 0:\n return False\n return True\n\ndef assert_ok_params(required:set, positional:set):\n \"\"\"Returns a decorator for flask route functions.\n Interrupts with 400 status code if the request\n parameters are not correct\n Parameters:\n required(set): A set of parameters required for\n the api method\n positional(set): A set of poistional parameters for\n the api method\n\n The result function aborts if not all the required arguments\n were specified\n The result function aborts if unknown arguments were specified\n \"\"\"\n def decorator(func):\n @wraps(func)\n def ans(*args, **kwargs):\n if check_given_params(\n required,\n required.union(positional),\n set(flask.request.form.keys())\n ):\n return func(*args, **kwargs)\n else:\n return flask.abort(400)\n\n return ans\n\n return decorator\n\n# UI:\npass\n\n# API:\n# ------ BEGIN NON-CONST API METHODS ------\n@app.route('/api/authorize', methods=['POST'])\n@assert_ok_params({'login', 'password'}, set())\ndef web_authorize():\n try:\n session_id = authorize(game_id, **flask.request.form)\n resp = app.make_response(\n json.dumps(session_id)\n )\n resp.set_cookie('session_id', session_id)\n return resp\n except ValueError:\n return flask.abort(401)\n\n@app.route('/api/add_file', methods=['POST'])\n@assert_ok_params({'name'}, set())\n@assert_is_authorized\ndef web_add_file():\n if set(flask.request.files.keys()) != {'file'}:\n return flask.abort(400)\n f = flask.request.files['file']\n file_id = add_file(game_id, flask.request.form.get('name', f.filename), silent=True)\n f.save(path.join(get_game_info()['files_folder'], file_id))\n return json.dumps(file_id)\n\n@app.route('/api/add_user', methods=['POST'])\n@assert_ok_params({'login', 'password', 'register_pass'},\n {'captain_pass', 'avatar'})\ndef web_add_user():\n if not bcrypt.checkpw(\n flask.request.form['register_pass'].encode('utf-8'),\n get_game_info()['register_pass'].encode('utf-8')\n ):\n return flaks.abort(403)\n args = {k: v for k, v in flask.request.form.items() if k in {'login', \\\n 'password', 'avatar'}}\n is_captain = False\n if 'captain_pass' in flask.request.form.keys():\n if bcrypt.checkpw(\n flask.request.form['captain_pass'].encode('utf-8'),\n get_game_info()['captain_pass'].encode('utf-8')\n ):\n is_captain = True\n else:\n return flask.abort(403)\n add_user(game_id, **args, is_captain=is_captain)\n return ''\n\n@app.route('/api/add_comment', methods=['POST'])\n@assert_ok_params({'task_id'}, {'text', 'files_ids'})\n@assert_is_authorized\ndef web_add_comment():\n user_id = get_user_info_s(flask.request.cookies['session_id'])['login']\n args = {k: v for k, v in flask.request.form.items() if k != 'files_ids'}\n args['files_ids'] = flask.request.form.getlist('files_ids')\n return json.dumps(add_comment(game_id, user_id, **args))\n\n@app.route('/api/rm_comment', methods=['POST'])\n@assert_ok_params({'id'}, set())\n@assert_is_authorized\ndef web_rm_comment():\n user_info = get_user_info_s(flask.request.cookies['session_id'])\n comment_info = get_comment_info(flask.request.form['id'])\n if user_info['is_captain'] or (user_info['login'] == comment_info['user_id']):\n return json.dumps(rm_comment(game_id, flask.request.form['id']))\n else:\n return flask.abort(403)\n\n@app.route('/api/mark_user', methods=['POST'])\n@assert_ok_params({'login', 'new_type'}, set())\n@assert_is_authorized\ndef web_mark_user():\n if not get_user_info_s(flask.request.cookies['session_id'])['is_captain']:\n return flask.abort(403)\n mark_user(game_id, *(flask.request.form[i] for i in ['login', 'new_type']))\n return ''\n\n@app.route('/api/mark_task', methods=['POST'])\n@assert_ok_params({'id', 'new_type'}, set())\n@assert_is_authorized\ndef web_mark_task():\n mark_task(game_id, *(flask.request.form[i] for i in ['id', 'new_type']))\n return ''\n\n@app.route('/api/update_avatar', methods=['POST'])\n@assert_ok_params({'avatar'}, set())\n@assert_is_authorized\ndef web_update_avatar():\n user_id = get_user_info_s(flask.request.cookies['session_id'])['login']\n update_avatar(game_id, user_id, flask.request.form['avatar'])\n return ''\n\n@app.route('/api/take_task', methods=['POST'])\n@assert_ok_params({'task_id', 'user_id'}, set())\n@assert_is_authorized\ndef web_take_task():\n user_info = get_user_info_s(flask.request.cookies['session_id'])\n if user_info['is_captain'] or (user_info['login'] == flask.request.form['user_id']):\n take_task(game_id, **flask.request.form)\n return ''\n else:\n return flask.abort(403)\n\n@app.route('/api/reject_task', methods=['POST'])\n@assert_ok_params({'task_id', 'user_id'}, set())\n@assert_is_authorized\ndef web_reject_task():\n user_info = get_user_info_s(flask.request.cookies['session_id'])\n if user_info['is_captain'] or (user_info['login'] == flask.request.form['user_id']):\n reject_task(game_id, **flask.request.form)\n return ''\n else:\n return flask.abort(403)\n# ------ END NON-CONST API METHODS ------\n\n\ndef file_path_and_name(file_id:str) -> tuple:\n \"\"\"Returns a path to the file and it's original name, if exists\n Parameters:\n file_id(str): The file identifier\n Returns:\n tuple: (path_to_file, original_filename) if the file exists, (None, None) otherwise\n \"\"\"\n assert_ok_dbname(game_id)\n db = get_db_connection()\n c = db.cursor()\n c.execute('USE OvO_' + game_id)\n c.execute('SELECT name FROM files WHERE id=(%s)', (file_id,))\n name = c.fetchone()\n if name is None:\n return (None, None)\n else:\n return (path.join(get_game_info()['files_folder'], file_id), name[0])\n\n# ------ BEGIN CONST API METHODS ------\n@app.route('/api/get_file/')\n@assert_is_authorized\ndef web_get_file(file_id):\n path, name = file_path_and_name(file_id)\n if path is None:\n return flask.abort(404)\n return flask.send_file(path)\n\n@app.route('/api/download_file/')\n@assert_is_authorized\ndef web_download_file(file_id):\n path, name = file_path_and_name(file_id)\n if path is None:\n return flask.abort(404)\n return flask.send_file(path, as_attachment=True, attachment_filename=name)\n\n@app.route('/api/get_user_info/')\n@assert_is_authorized\ndef web_get_user_info(user_id):\n return json.dumps(get_user_info(user_id))\n\n@app.route('/api/get_users')\n@assert_is_authorized\ndef web_get_users():\n assert_ok_dbname(game_id)\n db = get_db_connection()\n c = db.cursor()\n c.execute('USE OvO_' + game_id)\n c.execute('SELECT login FROM users')\n return json.dumps(\n [get_user_info(uid) for uid in _parse_mysql_vomit(c.fetchall())]\n )\n\n@app.route('/api/get_task_info/')\n@assert_is_authorized\ndef web_get_task_info(task_id):\n return json.dumps(get_task_info(task_id))\n\n@app.route('/api/get_tasks')\n@assert_is_authorized\ndef web_get_tasks():\n assert_ok_dbname(game_id)\n db = get_db_connection()\n c = db.cursor()\n c.execute('USE OvO_' + game_id)\n c.execute('SELECT id FROM tasks')\n return json.dumps(\n [get_task_info(tid) for tid in _parse_mysql_vomit(c.fetchall())]\n )\n\n@app.route('/api/get_solvings')\n@assert_is_authorized\ndef web_get_solvings():\n assert_ok_dbname(game_id)\n db = get_db_connection()\n c = db.cursor()\n c.execute('USE OvO_' + game_id)\n c.execute('SELECT * FROM solvings')\n return json.dumps(\n [dict(zip(['user_id', 'task_id'], i)) for i in c.fetchall()]\n )\n\n@app.route('/api/get_file_name/')\n@assert_is_authorized\ndef web_get_file_info(file_id):\n return json.dumps(file_path_and_name(file_id)[1])\n\n@app.route('/api/get_files')\n@assert_is_authorized\ndef web_get_files():\n assert_ok_dbname(game_id)\n db = get_db_connection()\n c = db.cursor()\n c.execute('USE OvO_' + game_id)\n c.execute('SELECT * FROM files')\n return json.dumps(\n [dict(zip(['id', 'name'], i)) for i in c.fetchall()]\n )\n\n@app.route('/api/get_comment_info/')\n@assert_is_authorized\ndef web_get_comment_info(comment_id):\n return json.dumps(get_comment_info(comment_id))\n\n@app.route('/api/get_comments')\n@assert_is_authorized\ndef web_get_comments():\n assert_ok_dbname(game_id)\n db = get_db_connection()\n c = db.cursor()\n c.execute('USE OvO_' + game_id)\n c.execute('SELECT id FROM comments')\n return json.dumps(\n [get_comment_info(cid) for cid in _parse_mysql_vomit(c.fetchall())]\n )\n# ------ END CONST API METHODS ------\n\nclass WaitForExit(FileSystemEventHandler):\n def on_created(self, event):\n if(not event.is_directory) and (event.src_path.split('/')[-1] == 'exit'):\n _exit(0)\n\nif __name__ == \"__main__\":\n game_id = sys.argv[1]\n game_info = get_game_info()\n observer = Observer()\n observer.schedule(WaitForExit(), path=game_info['files_folder'])\n observer.start()\n app.run('0.0.0.0', port=game_info['port'])\n","sub_path":"src/web/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":16567,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"328685670","text":"def answer_one():\r\n return pd.Series(df[df.Gold == max(df.Gold)].index)[0]\r\nanswer_one()\r\n\r\ndef answer_two():\r\n df1 = df\r\n df1['Maxdiff'] = abs (df1['Gold']-df1['Gold.1'])\r\n return pd.Series(df1[ df1.Maxdiff == max(df1.Maxdiff) ].index)[0]\r\nanswer_two()\r\n\r\ndef answer_three():\r\n df1 = df[(df.Gold > 0) & (df['Gold.1'] > 0) ]\r\n df1['Maxdiff'] = abs ((df1['Gold']-df1['Gold.1'])/(df1['Gold']+df1['Gold.1']))\r\n return pd.Series(df1[ df1.Maxdiff == max(df1.Maxdiff) ].index)[0]\r\nanswer_three()\r\n\r\n\r\ndef answer_four():\r\n df1 = df\r\n df1['Points'] = df1['Gold.2']*3 + df1['Silver.2']*2 + df1['Bronze.2']\r\n return df1['Points']\r\nanswer_four()\r\n\r\n\r\ndef answer_five():\r\n df1 = census_df[census_df.SUMLEV == 50]\r\n df1 = df1[['STNAME','CTYNAME']].groupby('STNAME',as_index=False).count()\r\n return df1[df1.CTYNAME == max(df1.CTYNAME)].iloc[0,0]\r\nanswer_five()\r\n\r\ndef answer_six():\r\n df1 = census_df[census_df.SUMLEV == 50]\r\n df1 = df1[['STNAME','CTYNAME', 'CENSUS2010POP']]\r\n df1 = df1.sort(['STNAME', 'CENSUS2010POP'], ascending=[1, 0]).reset_index()\r\n df1 = df1.groupby('STNAME').head(3)[['STNAME','CENSUS2010POP']].groupby('STNAME', as_index = False).sum()\r\n df1 = df1.sort('CENSUS2010POP', ascending= False).head(3).iloc[:,0]\r\n df1 = list(df1)\r\n return df1\r\nanswer_six()\r\n\r\ndef answer_seven():\r\n df1 = census_df[census_df.SUMLEV == 50]\r\n df1 = df1[['CTYNAME','POPESTIMATE2010','POPESTIMATE2011','POPESTIMATE2012','POPESTIMATE2013','POPESTIMATE2014']].drop_duplicates()\r\n df1 = df1.groupby('CTYNAME', as_index= False).sum()\r\n df1['MaxPop'] = df1[['POPESTIMATE2010','POPESTIMATE2011','POPESTIMATE2012','POPESTIMATE2013','POPESTIMATE2014']].max(axis=1)\r\n df1['MinPop'] = df1[['POPESTIMATE2010','POPESTIMATE2011','POPESTIMATE2012','POPESTIMATE2013','POPESTIMATE2014']].min(axis=1)\r\n df1['MaxChange'] = df1['MaxPop'] - df1['MinPop']\r\n return df1[df1.MaxChange == max(df1.MaxChange)].iloc[0,0]\r\nanswer_seven()\r\n\r\n\r\ndef answer_eight():\r\n df1 = census_df[census_df.SUMLEV == 50]\r\n df1 = df1[(census_df.CTYNAME.str.startswith(\"Washington\") ) & (census_df.POPESTIMATE2015 > census_df.POPESTIMATE2014) & ((census_df.REGION == 1) | (census_df.REGION == 2 ))]\r\n df1 = df1[['STNAME', 'CTYNAME']]\r\n df1.index.rename('ID', inplace=True)\r\n return df1\r\nanswer_eight()","sub_path":"Python work/Coursera/Assignments/week2.py","file_name":"week2.py","file_ext":"py","file_size_in_byte":2338,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"63824816","text":"# -*- coding: utf-8 -*-\nimport requests\nimport sqlite3\nfrom bs4 import BeautifulSoup\nimport re\nfrom pprint import pprint\n\nm = {\n '基金全称': 'name',\n '基金简称': 'name2',\n '基金类型': 'type',\n '基金经理人': 'mgr',\n '基金管理人': 'com',\n '发行日期': 'st',\n '跟踪标的': 'trace',\n}\n\n# fn = '1.htm'\n# soup = BeautifulSoup(open(fn), 'html.parser')\n\nprint(\"Read funds info from web, please wait...\")\nf = requests.get('http://fund.eastmoney.com/allfund.html')\ntry:\n f.raise_for_status()\nexcept Exception as exc:\n print('There was a problem: %s' % exc)\n exit(1)\n\nprint(\"Read OK\")\nsoup = BeautifulSoup(f.text, 'html.parser')\n\nr = re.compile(r'\\d{6}')\nuls = soup.find_all('ul', class_='num_right')\ncodes = []\nfor i in range(len(uls)):\n lis = uls[i].find_all('li', class_='b')\n for j in range(len(lis)):\n c = r.search(lis[j].getText())\n if c:\n # test\n # print(c.group())\n codes.append(c.group())\n\nprint('read', len(codes), 'codes')\n\ncon = sqlite3.connect('c:/rou/db/abc.db')\n\n# for i in range(100):\nfor i in range(len(codes)):\n # test\n # print(codes[i])\n print(\"Read fund (\", codes[i], \") info from web, please wait...\")\n url = \"http://fund.eastmoney.com/f10/\" + codes[i] + \".html\"\n # print(\"url=\", url)\n f = requests.get(url)\n try:\n f.raise_for_status()\n except Exception as exc:\n print('There was a problem: %s' % exc)\n exit(1)\n\n print(\"Read OK\")\n soup = BeautifulSoup(f.text, 'lxml')\n tb = soup.find_all('table', class_='info w790')\n if len(tb) == 0:\n continue\n trs = tb[0].find_all('tr')\n # print('trs=', len(trs))\n d = {'code': codes[i]}\n for j in range(len(trs)):\n # pprint(trs[j])\n ths = trs[j].find_all('th')\n tds = trs[j].find_all('td')\n # pprint(ths)\n # pprint(tds)\n if len(ths) != len(tds):\n continue\n for k in range(len(ths)):\n th = ths[k].getText()\n td = tds[k].getText()\n if th not in m.keys():\n continue\n d[m[th]] = td\n # test\n d['key'] = d['code'] + ' ' + d['mgr']\n pprint(d)\n keys = ','.join(d.keys())\n question_marks = ','.join(list('?' * len(d)))\n values = tuple(d.values())\n # print('INSERT OR REPLACE INTO fund_b (' + keys + ') VALUES (' + question_marks + ')', values)\n con.execute('INSERT OR REPLACE INTO fund_b (' + keys + ') VALUES (' + question_marks + ')', values)\n\ncon.commit()\n\n'''\ncon.execute(\"\"\"\nCREATE TABLE fund_b\n(\n key NVARCHAR2 PRIMARY KEY,\n code TEXT NOT NULL,\n name NVARCHAR2,\n name2 NVARCHAR2,\n type NVARCHAR2,\n mgr NVARCHAR2,\n com NVARCHAR2,\n st NVARCHAR2,\n trace NVARCHAR2\n)\n\"\"\")\n'''\n","sub_path":"prj/lang/fx/lang_getfundinfo.py","file_name":"lang_getfundinfo.py","file_ext":"py","file_size_in_byte":2827,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"418898301","text":" \nimport socket\nimport traceback\nimport threading\nimport struct\nfrom .sensorDataProcessing import * \nfrom ThingBoardConection.client import ThingBoardUser\nimport logging\nfrom logging.handlers import RotatingFileHandler\nfrom properties.PropertiesReader import ConfParams\nfrom collections import defaultdict\nimport time\nimport decimal\nfrom TcpServer.PlcCalculatedParams import PlcCalculatedParams\n \n\n\n\nclass TcpServSensor: \n instance = None\n \n class __TcpServer:\n params=ConfParams()\n get_status = b'\\x12\\x01\\x01'\n\n begin_of_packet =b'UUUU'\n user = ThingBoardUser()\n \n plcCalculatedParams= PlcCalculatedParams()\n function_process_data_to_view = None\n update_conected_sensors = None\n update_cmd_view=None\n bind_ip = '0.0.0.0'\n bind_port = int( params.getParam(\"GATEWAY_PORT\"))\n dict_allSensor_by_id = {}\n # dict_allSockets_by_sensor_id={}\n prevPacket=None \n prevPacketType=None \n errorLoggers={} \n lastPackets={}\n lostPacketsCounter={}\n nextDeviceIdIndexToProcess=0\n generalLogger= None \n do_update_sensor_server_print_Consol=False\n threadData = threading.local()\n #dataPerSensor={}\n dataPerSensor=defaultdict(dict)\n def getLogger(self,sensor_id):\n logger=None\n if(sensor_id in self.errorLoggers):\n logger=self.errorLoggers[sensor_id]\n \n if(logger != None):\n return logger\n logger = logging.getLogger(sensor_id)\n handler = RotatingFileHandler('../logs/'+sensor_id+'.log', maxBytes=20000000, backupCount=20)\n formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')\n handler.setFormatter(formatter)\n \n logger.addHandler(handler) \n logger.setLevel(logging.DEBUG)\n self.errorLoggers[sensor_id]=logger\n return logger\n \n \n def update_sensors_server (self,sensor_id ,key,value):\n if key==\"get_debug_buffer\":\n \n self.dataPerSensor[sensor_id][\"get_debug_buffer\"]=value\n \n elif key==\"update_view_with_first_raw_data_packet\":\n #self.dataPerSensor[sensor_id]=\"update_view_with_first_raw_data_packet\"\n self.dataPerSensor[sensor_id][\"update_view_with_first_raw_data_packet\"]=value\n #self.threadData.update_view_with_first_raw_data_packet=value\n elif key==\"print_incoming_packets_info_to_console\":\n self.do_update_sensor_server_print_Consol=value \n else : \n self.dataPerSensor[sensor_id][key]=value\n \n \n def recv_data(self, client_socket,processData):\n #value=client_socket.recv(100)\n #print(\"first 100 bytes : \", str(value))\n global prevPacket\n global prevPacketType\n \n value=None \n foundPacketPrefix=False\n # value=client_socket.recv(2000)\n # print(\"out of reading sync , next 2000: \", value ) \n #value=client_socket.recv(20000)\n #in case out of reading sync, clearing the socket buffer\n outOfReadingSync=''\n while (not foundPacketPrefix):\n while(value!=b'U'):\n if(value!= None):\n outOfReadingSync=outOfReadingSync+str(value)\n \n value=client_socket.recv(1)\n #if(value== b''):\n #processData.connection_terminated=True\n #return\n #print(\"out of reading sync , next 200: \", str(value)) \n value=client_socket.recv(4)\n #if(value== b''):\n #processData.connection_terminated=True\n #return\n if (value == self.begin_of_packet):\n foundPacketPrefix=True\n if(outOfReadingSync!='' and self.do_update_sensor_server_print_Consol):\n print(\"out of reading sync\")#: \", str(outOfReadingSync))\n outOfReadingSync=''\n \n else:\n value=None \n \n \n value=client_socket.recv( processData.headersProcess.LENGTH_HEADERS)\n #print(\"headers : \", str(value))\n value_length=len(value)\n while value_length < processData.headersProcess.LENGTH_HEADERS :\n self.generalLogger.warn (\"in value.length < processData.headersProcess.len_data loop , length requred\"+str(processData.headersProcess.LENGTH_HEADERS)+\" and , value \"+ str(value))\n\n value +=client_socket.recv( processData.headersProcess.LENGTH_HEADERS-value_length)\n value_length=len(value)\n \n #if(value== b''):\n #processData.connection_terminated=True\n #return\n \n valueAll=value\n processData.headersProcess.headers = value\n #print(\"headers : \", str(value))\n \n value = client_socket.recv(processData.headersProcess.len_data)\n value_length=len(value)\n while value_length < processData.headersProcess.len_data :\n if self.do_update_sensor_server_print_Consol:\n self.generalLogger.warning(\"in value.length < processData.headersProcess.len_data loop , length requred\"+str(processData.headersProcess.len_data)+\" and , value \"+ str(value))\n value +=client_socket.recv( processData.headersProcess.len_data-value_length)\n value_length=len(value)\n \n # if(value== b''):\n # processData.connection_terminated=True\n # return\n \n processData.headersProcess.data = value\n \n \n \n \n valueAll=valueAll+value;\n if processData.headersProcess.isRawData ==True :\n print(\"Raw Data :\"+str(value))\n logger= self.getLogger(str(processData.headersProcess.headers[0]))\n \n if self.do_update_sensor_server_print_Consol:\n print(\"PfS :\"+str(processData.headersProcess.headers[0])+ \" ,SqN : \"+ str(processData.headersProcess.headers[4])+\" ,Packet Type :\", processData.headersProcess.type_data )\n \n if( processData.headersProcess.is_debuge_buffer ):\n print(\"packet data: \"+ processData.get_data_as_decimals(2))\n\n if processData.headersProcess.is_vz_param :\n \n index = str(processData.headersProcess.data[0])\n #print('\\nReceived index:', index)\n #print(self.dataPerSensor['command'])\n param_type=int(self.dataPerSensor['command'][index])\n #print('param_type: ', param_type)\n #print('Received data bytes ', str(processData.headersProcess.data))\n \n if param_type == 1: # boolean\n value = struct.unpack('<4B', processData.headersProcess.data[1:])\n elif param_type == 2: # uint\n (value,) = struct.unpack('13 or processData.headersProcess.headers[0]<0):\n msg= \"sensor ID \"+str(processData.headersProcess.headers[0]) +\" is not valid, packet content: :\"+ str(valueAll) \n print(msg)\n self.generalLogger.error(msg)\n raise Exception(msg)\n \n lastPacket=None\n sSensorID=str(processData.headersProcess.headers[0])\n if (sSensorID in self.lastPackets):\n lastPacket=self.lastPackets[sSensorID]\n \n if(lastPacket != None):\n currentSeqNumber=processData.headersProcess.headers[4]\n \n lastPackeSeqNumber=lastPacket.headersProcess.headers[4]\n if( currentSeqNumber!=(lastPackeSeqNumber+1) and currentSeqNumber!=0 and lastPackeSeqNumber!=255 ):\n lostCounter=0\n if (sSensorID in self.lostPacketsCounter):\n lostCounter=self.lostPacketsCounter[sSensorID]\n \n lostCounter=lostCounter+(currentSeqNumber-lastPackeSeqNumber)\n self.lostPacketsCounter[sSensorID] =lostCounter \n \n \n logger.error(\"lost packets , current seq id : \"+ str(currentSeqNumber) + ' , prev seq ID : '+str(lastPackeSeqNumber))\n logger.error(\"lost packets Counter : \"+str(lostCounter))\n logger.error(\"current packet content : \"+ str(valueAll ))\n logger.error(\"prev packet content : \"+ str(processData.headersProcess.headers)+str(processData.headersProcess.data) )\n \n #valdation of algo_2_demo , value --8\n if( processData.headersProcess.headers[3]==25 and processData.headersProcess.data[1]!=8):\n logger.error(\"validation of algo_2_demo value==8 failed, actual value : \"+ processData.headersProcess.data[1])\n logger.error(\" packet content : \"+ str(valueAll ))\n \n \n self.lastPackets[sSensorID]=processData\n #print(\"current Packet data length :\", str(processData.headersProcess.len_data))\n #print(\"current Packet input :\", valueAll )\n prevPacket=valueAll\n prevPacketType=processData.headersProcess.type_data\n \n sensor_id=str(processData.headersProcess.headers[0])\n \n if sensor_id in self.dataPerSensor and \"update_view_with_first_raw_data_packet\" in self.dataPerSensor[sensor_id] and self.dataPerSensor[sensor_id][\"update_view_with_first_raw_data_packet\"]==True :#and processData.headersProcess.type_data in ['velocity','distance'] :\n self.update_cmd_view(\"raw_data_packet\",valueAll)\n self.dataPerSensor[sensor_id][\"update_view_with_first_raw_data_packet\"]=False\n\n def handle_client_connection(self, client_socket):\n \n \n self.threadData.update_view_with_first_raw_data_packet=False\n time.sleep(5)\n\n client_socket.send(self.get_status)\n\n \n while True:\n try:\n processData = SensorDataProcess()\n self.recv_data(client_socket,processData)\n if(processData.connection_terminated):\n temp_id=None\n temp_id=processData.headersProcess.id_sensor\n if id==None:\n temp_id=\"\" \n print(\"connection is terminated \"+ str(temp_id))\n self.generalLogger.error(\"connection is terminated \"+ str(temp_id))\n if(temp_id!=\"\" and temp_id in self.dict_allSensor_by_id):\n del self.dict_allSensor_by_id[temp_id]\n self.update_conected_sensors(self.dict_allSensor_by_id) \n return \n \n ts = {\"ts\":int(round(time.time() * 1000))}\n # if(processData.headersProcess.id_sensor in self.dict_allSensor_by_id):\n # del self.dict_allSockets_by_sensor_id[self.dict_allSensor_by_id[processData.headersProcess.id_sensor]]\n self.dict_allSensor_by_id[processData.headersProcess.id_sensor] = client_socket\n # self.dict_allSockets_by_sensor_id[client_socket] = processData.headersProcess.id_sensor \n self.update_conected_sensors(self.dict_allSensor_by_id)\n if( processData.headersProcess.is_debuge_buffer or processData.headersProcess.is_vz_param):\n continue\n if processData.headersProcess.is_plc_data or processData.headersProcess.isRawData :#or self.headersProcess.type_data == \"end_of_pac\":\n \n id_socket, data = processData.process_data(ts)\n \n \n \n try:\n \n do_send_is_alive_ping=(processData.headersProcess.isRawData and processData.headersProcess.pack_seq_number%100==0)\n self.user.send_telemetry(id_socket, data, processData.headersProcess.isRawData,processData.headersProcess.data,processData.headersProcess.type_data,do_send_is_alive_ping )\n \n except Exception as e:\n print(\"error sending data serv \" + str(e))\n self.generalLogger.error(\"error sending data serv \" + str(e))\n else:\n fer = self.function_process_data_to_view(processData)\n \n except Exception as e:\n #ConnectionResetError: [WinError 10054] An existing connection was forcibly closed by the remote host\n msg=str(e)\n print(\"general error \" + msg)\n self.generalLogger.error(msg)\n \n \n print( traceback.format_exc())\n \n self.generalLogger.error(\"general error \" + str(e)+\" processData.headersProcess._headers: \"+ str(processData.headersProcess._headers))\n self.generalLogger.error(\"general error processData.headersProcess._headers: \"+ str(processData.headersProcess._headers))\n self.generalLogger.error(\"general error processData.headersProcess._headers: \"+ str(processData.headersProcess.data))\n self.generalLogger.error( traceback.format_exc())\n if( \"closed\" in msg):\n return\n \n# \n# def handle_client_connections(self):\n# \n# \n# \n# while True:\n# sensor_ids=self.dict_allSensor_by_id.keys()\n# for sensor_id in sensor_ids:\n# try:\n# client_socket=self.dict_allSensor_by_id[sensor_id]\n# self.handle_client_connection(client_socket)\n# except Exception as e:\n# print(\"error sending data serv\" + str(e))\n# self.generalLogger.error(\"error sending data serv\" + str(e))\n \n\n def send_to_sensor(self, ids_sensor: list, data: str ):\n# if read_sensor_raw_data_in_secods:\n# for i in ids_sensor:\n# if i not in self.list_sensors_send_coomend_read_raw_data:\n# self.list_sensors_send_coomend_read_raw_data[i] = read_sensor_raw_data_in_secods\n for i in ids_sensor:\n if i not in self.dict_allSensor_by_id:\n return 'error id sensor ' + str(i)\n try:\n print(\"send to sensor \"+str(i)+\" : \"+str(data))\n self.dict_allSensor_by_id.get(i).send(data)\n except Exception as e:\n print(e)\n self.generalLogger.error(\"error sending data sensor\" + str(e))\n return ''\n\n def run(self):\n if(self.generalLogger==None):\n self.generalLogger=self.getLogger ('generalSensorsGateway')\n \n server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n #server = socket.socket(socket.AF_INET, socket.SOCK_RAW )\n \n server.bind((self.bind_ip, self.bind_port))\n server.listen(8) # max backlog of connections\n # print('Listening on {}:{}'.format(self.bind_ip, self.bind_port))\n while True:\n print('Waiting for Sensors connection')\n client_sock, address = server.accept()\n client_sock.setsockopt(socket.SOL_SOCKET, socket.SO_RCVBUF,\n 10000)\n print('Accepted connection from {}:{}'.format(address[0], address[1]))\n client_handler = threading.Thread(\n target=self.handle_client_connection,\n args=(client_sock,))\n client_handler.start()\n\n def __new__(cls) -> __TcpServer: # __new__ always a classmethod\n\n if not TcpServSensor.instance:\n TcpServSensor.instance = TcpServSensor.__TcpServer()\n return TcpServSensor.instance\n","sub_path":"pepsiN/TcpServer/TcpServSensor.py","file_name":"TcpServSensor.py","file_ext":"py","file_size_in_byte":17617,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"288609868","text":"# 队列的实现,基于列表\nclass Queue:\n def __init__(self, *args):\n self._queue = []\n for i in args:\n self._queue.insert(0, i) # 列表右边是队头\n\n def size(self):\n return len(self._queue)\n\n def is_empty(self):\n if self.size() == 0:\n return True\n \n def enqueue(self, *args): # 入队\n for i in args:\n self._queue.insert(0, i)\n \n def dequeue(self): # 出队\n if self.size() > 0:\n return self._queue.pop()\n else:\n print(\"empty queue\")\n\n\n# 约瑟夫环,用循环队列解决\nnames = input('plz input the names(with blank betwwwn them):')\njudge = int(input('plz input the judge number:'))\nflag = 1\nqueue = Queue()\nfor i in names.split(\" \"):\n queue.enqueue(i)\nwhile queue.size() != 1:\n if flag != judge:\n queue.enqueue(queue.dequeue())\n flag += 1\n else:\n queue.dequeue()\n flag = 1\n# 求出最后剩下的人\nprint(queue._queue)\n\n \n \n","sub_path":"python数据结构/队列queue.py","file_name":"队列queue.py","file_ext":"py","file_size_in_byte":1019,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"301937769","text":"\n\n#calss header\nclass _REPTILIAN():\n\tdef __init__(self,): \n\t\tself.name = \"REPTILIAN\"\n\t\tself.definitions = [u'belonging to or like a reptile: ', u'used to describe an unpleasantly strange and unfriendly person or type of behaviour: ']\n\n\t\tself.parents = []\n\t\tself.childen = []\n\t\tself.properties = []\n\t\tself.jsondata = {}\n\n\n\t\tself.specie = 'adjectives'\n\n\n\tdef run(self, obj1, obj2):\n\t\tself.jsondata[obj2] = {}\n\t\tself.jsondata[obj2]['properties'] = self.name.lower()\n\t\treturn self.jsondata\n","sub_path":"xai/brain/wordbase/adjectives/_reptilian.py","file_name":"_reptilian.py","file_ext":"py","file_size_in_byte":486,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"221009902","text":"from flask import Flask,jsonify,request,make_response,abort\nfrom flask_cors import CORS\n\nfrom tf_idf_model import Similarity\ns=Similarity()\napp = Flask(__name__)\nCORS(app, resources=r'/*')\n\n\n#get\n@app.route('/sendquery',methods=['GET'])\ndef get_task():\n if not 'query' in request.args.to_dict():\n abort(404)\n result=s.send_query(request.args.to_dict()['query'])\n return result\n\n#404处理\n@app.errorhandler(404)\ndef not_found(error):\n return make_response(jsonify({'error':'Not found'}),404)\n\nif __name__ == '__main__':\n app.run(port=5000)\n","sub_path":"api.py","file_name":"api.py","file_ext":"py","file_size_in_byte":562,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"496174234","text":"from sys import exit\n\n\n# Test File\n# this file has the classes that make testing nice and easy ;)\n# this stuff is used in the tests.py file.\n\n\nclass Test():\n def __init__(self,function,requires=[]):\n self.function = function\n self.requires = requires\n self.completed = False\n\n\n def __getattr__(self,key):\n if key == \"name\":\n return self.function.__name__+\" test\"\n elif key == \"function_name\":\n return self.function.__name__\n\n\n\n def __call__(self):\n if self.completed:\n return False\n\n ret = self.function()\n if ret == False:\n self.completed = True\n return ret\n\n\nclass Tests():\n def __init__(self):\n self.completed = []\n self.tests = []\n\n\n def new(self,function,func_requires=[]):\n requires = []\n\n for req in func_requires:\n for test in self.tests:\n if test.function == test:\n requires.append(test)\n self.tests.append(Test(function,requires))\n\n\n def run_test(self,test):\n for req in test.requires:\n if not isinstance(req,Test):\n raise Exception(test.name+\" requires a non-test \",req)\n self.run_test(req)\n\n ret = test()\n if ret == False:\n print(\"\\033[92m\"+test.name+\" passed\\033[0m\")\n test.completed = True\n elif ret == None:\n print(\"\\033[90m\"+test.name+\" has no test\\033[0m\")\n else:\n print(\"\\033[91m\"+test.name+\" failed\\033[0m\")\n exit(2)\n\n\n def __call__(self):\n for test in self.tests:\n self.run_test(test)","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":1459,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"421355905","text":"#! /usr/bin/env python\n# -*- coding:utf-8 -*-\n\nfrom bs4 import CData,BeautifulSoup\nmarkup = \"\"\nsoup = BeautifulSoup(markup,'lxml')\ncomment = soup.b.string\ncdata = CData('A CDATA block')\ncomment.replace_with(cdata)\nprint(soup.b)","sub_path":"beautifulsoup/cdatd.py","file_name":"cdatd.py","file_ext":"py","file_size_in_byte":279,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"330648132","text":"'''\nAs we have mentioned, this approach is very unskilful. What if we have to change the size or the thickness of the star? We have to change all the points manually, which is of course an error-prone and tedious task to do. So, we present a new version of the previous script which involves more \"programming\" and programming skills. First, we put the creation of the star in a function, and we use an origin point and two lengths p and t to create the star:\nOur new improved program looks like this now:\n'''\n\nfrom tkinter import *\n\ncanvas_width = 400\ncanvas_height =400\npython_green = \"#476042\"\n\ndef polygon_star(canvas, x,y,p,t, outline=python_green, fill='yellow', width = 1):\n points = []\n for i in (1,-1):\n points.extend((x,\t y + i*p))\n points.extend((x + i*t, y + i*t))\n points.extend((x + i*p, y))\n points.extend((x + i*t, y - i * t))\n\n print(points)\n\n canvas.create_polygon(points, outline=outline,\n fill=fill, width=width)\n\nmaster = Tk()\n\nw = Canvas(master,\n width=canvas_width,\n height=canvas_height)\nw.pack()\n\np = 50\nt = 15\n\nnsteps = 10\nstep_x = int(canvas_width / nsteps)\nstep_y = int(canvas_height / nsteps)\n\nfor i in range(1, nsteps):\n polygon_star(w,i*step_x,i*step_y,p,t,outline='red',fill='gold', width=3)\n polygon_star(w,i*step_x,canvas_height - i*step_y,p,t,outline='red',fill='gold', width=3)\n\nmainloop()\n\n'''\nThe result looks even more like Xmas and we are sure that nobody doubts that it would be hell to define the polygon points directly, as we did in our first star example:\n'''\n","sub_path":"GUIs/demoCanvas8_star.py","file_name":"demoCanvas8_star.py","file_ext":"py","file_size_in_byte":1586,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"192022291","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Mon Jul 8 20:12:22 2019\r\n\r\n@author: h34sh00ters4m\r\n\"\"\"\r\n\r\nimport pandas as pd\r\nimport numpy as np\r\nimport csv\r\nimport matplotlib.pylab as plt\r\nimport collections\r\n\r\n\r\nlist2 = [[22], [38], [39], [15], [34], [31], [30], [29],[28],\r\n [27], [24], [21], [20], [19], [9], [12], \r\n [13], [14], [15], [16], [17], [18]]\r\nlistDict = []\r\n \r\nfor param in list2:\r\n \r\n with open('D:\\DATA\\Automobile\\Collisions.csv') as csv_file:\r\n csv_reader = csv.reader(csv_file, delimiter=',')\r\n lcount = 0\r\n for item1 in csv_reader:\r\n #print(item[22], item[38], item[39], item[15], item[34], item[31], item[30], item[29],\r\n # item[28], item[27], item[24], item[21], item[20], item[19], item[9], item[12]\r\n # , item[13], item[14], item[15], item[16], item[17], item[18])\r\n \r\n \r\n #-------------------------------------------\r\n # COUNT FREQUENCY OF Parameter\r\n # -------------------------------------------\r\n \r\n lcount = 0\r\n print(param)\r\n FatalityCount_Dict = {}\r\n for item in csv_reader:\r\n data = item[param[0]]\r\n #print(\"----------||||||-----\")\r\n #print(\"-----------\\n-----------\\n-------\") \r\n if data not in FatalityCount_Dict:\r\n FatalityCount_Dict[data] = 1\r\n else:\r\n FatalityCount_Dict[data] += 1\r\n \r\n \r\n #lcount += 1\r\n #if(lcount == 100):\r\n # break\r\n \r\n listDict.append((item1[param[0]], FatalityCount_Dict))\r\n \r\n print(\"xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx\\n\\n\\n\\n\")\r\n \r\n \r\nprint(listDict)\r\ncount = 0\r\nwith open('masterList.txt', 'w') as f:\r\n for item in listDict:\r\n f.write(\"\\nXXXXXXXXXXXXXXXXXXXX\\n\")\r\n f.write(\"\\n%d\\n\" % count)\r\n for tup in item:\r\n \r\n f.write(\"%s\\n\" % str(tup))\r\n f.write(\"\\n-----------------------------------------------\\n\")\r\n count +=1\r\n \r\n#Light Conditions {'Daylight': 112856, 'Dark - Street Lights On': 47677, 'Unknown': 13317, 'Dusk': 5784, '': 25209, 'Dark - Street Lights Off': 1191, 'Dawn': 2451, 'Other': 224, 'Dark - No Street Lights': 1491}\r\n#FATALITIES {0: 209881, 1: 304, 2: 11, 4: 1, 3: 2, 5: 1}\r\n#[['Othr', 224], ['DrkStrt Lits O', 1191], ['Drk-NStrtLits', 1491], ['Dawn', 2451], ['Dsk', 5784], ['Unkn', 13317], ['', 25209], ['DkStrtLitsO', 47677], ['Dlight', 112856]]\r\n#\r\n#\r\n#\r\n\"\"\"\r\n \r\n\r\nPersonCount_Dict = {12: 33, 2: 112456, 3: 34712, 6: 2671, 0: 24119, 4: 14307, 1: 13218, 8: 528, 5: 6467, 16: 8, 7: 1130, 9: 219, 17: 11, 11: 58, 13: 21, 26: 4, 22: 5, 10: 127, 37: 3, 28: 3, 36: 2, 14: 22, 53: 1, 19: 6, 30: 2, 29: 4, 23: 3, 44: 5, 15: 11, 32: 3, 21: 2, 20: 6, 27: 3, 41: 1, 35: 1, 43: 1, 81: 1, 18: 6, 48: 1, 25: 5, 24: 2, 34: 3, 57: 1, 39: 1, 47: 3, 31: 2, 54: 1, 93: 1}\r\n \r\n\r\n lists = sorted(PersonCount_Dict.items()) # sorted by key, return a list of tuples\r\n \r\n x, y = zip(*lists) # unpack a list of pairs into two tuples\r\n \r\n plt.plot(x, y, marker=\"v\", color='green', linestyle = 'dashed', linewidth='0.8', \r\n markeredgecolor = 'purple', markersize = 5)\r\n plt.grid(True)\r\n plt.xlabel(\"----- Number of Persons -----\")\r\n plt.ylabel(\"Frequency\")\r\n plt.title(\"Frequency vs. Accident Person Count\")\r\n plt.axis([0, 10, 0, 125000])\r\n plt.savefig(\"collisions_PersonCount_Frequency1.PNG\", dpi=388, bbox_inches = 'tight')\r\n plt.show()\r\n\r\n\r\n\r\n\r\n\"\"\"\r\n \r\n \r\n\"\"\"\r\nlightingConditions = {'Dlight': 112856, 'DkStrtLitsO': 47677, 'Unkn': 13317, 'Dsk': 5784, '': 25209, 'DrkStrt Lits O': 1191, 'Dawn': 2451, 'Othr': 224, 'Drk-NStrtLits': 1491}\r\n\r\nlist1 = []\r\nfor item in lightingConditions:\r\n list1.append([item, lightingConditions[item]])\r\nprint(sorted(list1, key=lambda x: x[1]))\r\nlists = sorted(lightingConditions.items()) # sorted by key, return a list of tuples\r\n\r\nx, y = zip(*lists) # unpack a list of pairs into two tuples\r\n\r\nplt.plot(x, y, marker=\"v\", color='green', linestyle = 'dashed', linewidth='0.8', \r\n markeredgecolor = 'purple', markersize = 5)\r\nplt.grid(True)\r\nplt.xlabel(\"----- Number of Persons -----\")\r\nplt.ylabel(\"Frequency\")\r\nplt.title(\"Frequency vs. Accident Person Count\")\r\nplt.axis([0, 10, 0, 125000])\r\nplt.savefig(\"Frequency1.PNG\", dpi=388, bbox_inches = 'tight')\r\nplt.show()\r\n\"\"\"","sub_path":"collisions.py","file_name":"collisions.py","file_ext":"py","file_size_in_byte":4561,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"582638438","text":"# conflicts with isort because of local non-relative import\n# pylint: disable=wrong-import-order\nimport unittest\n\nfrom fastapi.testclient import TestClient\nfrom models.tortoise_models.fleet import Fleet, Robot\nfrom models.tortoise_models.fleet_state import FleetState, RobotStateEnum\nfrom rest_server.app import get_app\nfrom rest_server.repositories.report.fleet_state import get_fleet_state\nfrom rest_server.test_utils import start_test_database\nfrom tortoise import Tortoise\n\napp = get_app()\n\n\nclass TestReportFleetState(unittest.IsolatedAsyncioTestCase):\n async def asyncSetUp(self):\n await start_test_database()\n self.client = TestClient(app)\n\n robot = await Robot.create(name=\"Robot 1\")\n fleet = await Fleet.create(name=\"Fleet 1\")\n\n await FleetState.create(\n fleet=fleet,\n robot=robot,\n robot_battery_percent=\"100\",\n robot_location=\"1\",\n robot_mode=RobotStateEnum.MODE_WAITING,\n robot_seq=1,\n robot_task_id=\"test\",\n )\n await FleetState.create(\n fleet=fleet,\n robot=robot,\n robot_battery_percent=\"100\",\n robot_location=\"1\",\n robot_mode=RobotStateEnum.MODE_WAITING,\n robot_seq=2,\n robot_task_id=\"test\",\n )\n\n async def asyncTearDown(self):\n await Tortoise.close_connections()\n\n async def test_get_fleet_states(self):\n fleet_list = await get_fleet_state(0, 10)\n self.assertEqual(len(fleet_list), 2)\n","sub_path":"packages/reporting-server/rest_server/repositories/report/test_fleet_state.py","file_name":"test_fleet_state.py","file_ext":"py","file_size_in_byte":1540,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"514747444","text":"\"\"\"\nhttps://leetcode.com/problems/n-th-tribonacci-number/\n\"\"\"\nclass Solution:\n def tribonacci(self, n: int) -> int:\n a, b, c = 0, 1, 1\n if n == 0:\n return 0\n elif n == 1 or n == 2:\n return 1\n else:\n n -= 3\n while n >= 0:\n new_c = a + b + c\n a, b = b, c\n c = new_c\n n -= 1\n return c\n\nsol = Solution()\nassert sol.tribonacci(4) == 4\nassert sol.tribonacci(25) == 1389537\n","sub_path":"1137_NthTribonacciNumber.py","file_name":"1137_NthTribonacciNumber.py","file_ext":"py","file_size_in_byte":513,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"585563801","text":"from collections import defaultdict\nimport MySQLdb\nfrom Classes.SearchResults import SearchResults\nimport database\n\n\nclass RubyInterfacer():\n\n def FormatForRuby(self, pythonResult):\n\n result = defaultdict(list)\n\n # Analyzing old code, these were all possible dictionary keys:\n # \"neurons in the same region\" XXX\n # \"neurons from the same region\" ***\n # \"neurons with the same neurotransmitter\"\n # \"similar neurons\"\n #\n # XXX - duplicate\n # *** - actually seen used on website\n\n # Get NeuroML model IDs from mysql db\n rows = self.GetNeuroMLids(pythonResult)\n\n # Build a NeuroLexUri -> ModelDBids dictionary\n models = {}\n for row in rows:\n if row[1] not in models:\n models[row[1]] = [row[0]]\n else:\n # Each uri can have more than one model\n models[row[1]].append(row[0])\n\n result[\"Gap Relationships\"] = self.PopulateHeading(\n pythonResult.Relationships.GapRelationships,\n \"gapObjectId\",\n models\n )\n\n result[\"Direct Relationship Analogues\"] = self.PopulateHeading(\n pythonResult.DirectRelationshipAnalogues,\n \"id\",\n models\n )\n\n result[\"Keyword Relations\"] = self.PopulateHeading(\n pythonResult.KeywordRelations,\n \"id\",\n models\n )\n\n # # Fill out these\n # # result[\"neurons from the same region\"]\n # # result[\"neurons with the same neurotransmitter\"\n #\n # sameRegion = []\n # sameNeuroTrans = []\n # for analogue in pythonResult.DirectRelationshipAnalogues:\n #\n # if analogue[\"id\"] in models:\n #\n # if analogue[\"relationship\"].endswith(\"Located_in\"):\n # sameRegion.append(models[analogue[\"id\"]])\n #\n # elif analogue[\"relationship\"].endswith(\"Neurotransmitter\"):\n # sameNeuroTrans.append(models[analogue[\"id\"]])\n #\n # for keyword in pythonResult.KeywordRelations:\n #\n # if keyword[\"id\"] in models:\n #\n # if keyword[\"relationship\"].endswith(\"Located_in\"):\n # sameRegion.append(models[keyword[\"id\"]])\n #\n # elif keyword[\"relationship\"].endswith(\"Neurotransmitter\"):\n # sameNeuroTrans.append(models[keyword[\"id\"]])\n #\n # if len(sameRegion) > 0:\n # result[\"neurons from the same region\"] = sameRegion\n #\n # if len(sameNeuroTrans) > 0:\n # result[\"neurons with the same neurotransmitter\"] = sameNeuroTrans\n #\n # # Fill out this one\n # # result[\"similar neurons\"]\n # similar = []\n # for gap in pythonResult.GapRelationships:\n # if gap[\"gapObjectId\"] in models:\n # similar.append(models[gap[\"gapObjectId\"]])\n #\n # if len(similar) > 0:\n # result[\"similar neurons\"] = similar\n\n return result\n\n def PopulateHeading(self, source, idProperty, models):\n\n result = []\n for line in source:\n if line[idProperty] in models:\n line[\"ModelIds\"] = models[line[idProperty]]\n result.append(line)\n\n return result\n\n def GetNeuroMLids(self, pythonResult):\n\n connection = MySQLdb.connect(\"localhost\", database.connection['user'], database.connection['password'], database.connection['db'])\n connection.autocommit(True)\n cursor = connection.cursor()\n\n with open(\"Queries/GetNeuroMLmodels.sql\") as queryFile:\n query = queryFile.read()\n\n # Insert keyword ids into query\n query = query.replace(\"[NeuroLexUris]\", self.GetNeuroLexUris(pythonResult))\n\n cursor.execute(query)\n result = cursor.fetchall()\n\n connection.commit()\n connection.close()\n\n return result\n\n\n def GetNeuroLexUris(self, pythonResult):\n\n uris = pythonResult.GetNeuroLexUris()\n\n # Surround with quotes\n result = []\n for uri in uris:\n result.append('\"' + uri + '\"')\n\n # CSV and line separate\n result = \"\\n , \\n\".join(result)\n\n return result\n","sub_path":"www/NeuroML-DB.org_Ontology/Classes/RubyInterfacer.py","file_name":"RubyInterfacer.py","file_ext":"py","file_size_in_byte":4315,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"463927075","text":"import json\n\nwith open(\"./../data/season.json\") as data:\n season = json.load(data)\n\nfor game in season:\n game['gameType'] = \"R\"\n\nwith open(\"./../data/modified.json\", \"w\") as outfile:\n json.dump(season, outfile, indent=4)","sub_path":"pylib/changedata.py","file_name":"changedata.py","file_ext":"py","file_size_in_byte":229,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"401945526","text":"import random\nfrom math import ceil\nimport numpy as np\nclass JOB:\n def __init__(self):\n self.processing_time = 0\n self.index = 0\n self.release_date = 0\n self.pieces = 0\n self.weight = 0\n self.Mj = []\n self.Temperature = 0\n self.WP = 0\n self.Machine_Assigned = 0\n self.starting_time = 0\n self.is_processed = False\n self.due_date = None\n #normalized data\n self.processing_time_n = None\n self.pieces_n = None\n self.weight_n = None\n self.Mj_n = None\n self.due_date_n = None\n self.release_date_n = None\n #priority of be chosen\n self.priority = None\n def __repr__(self):\n return(\"Job index : %d \\t release date : %d \\t processing time : %d \" % (self.index,self.release_date, self.processing_time))\n\n def Generating_Data(self,p_range = (15.94,4.23), w_range = (5,25) , m_range = (3,20),v_mean = 1):\n # Processing_time\n\n p = random.gauss(p_range[0],p_range[1])\n self.pieces = random.randint(w_range[0],w_range[1])\n self.processing_time = round(p) if p > 1 else random.randint(1,int(p_range[0] + p_range[1]))\n # threshold = random.randint(1, 100)\n # if threshold <= 70:\n # self.processing_time = round(p)\n # self.pieces = 25\n # else:\n # self.pieces = w = random.randint(15, 25)\n # self.processing_time = round((p / 25) * w)\n\n # Weight\n self.weight = np.random.poisson(v_mean)\n if self.weight <= 0 : self.weight = 1\n\n # threshold = random.randint(1, 100)\n # if threshold <= 50:\n # self.weight = 1\n # elif threshold <= 80:\n # self.weight = 2\n # elif threshold < 95:\n # self.weight = 3\n # else:\n # self.weight = 4\n\n # Set Mj\n threshold = random.randint(m_range[0], m_range[1])\n data = [i for i in range(1, 26)]\n random.shuffle(data)\n self.Mj = data[:threshold]\n self.Mj.sort()\n # Set temperature\n self.Temperature = random.randint(100, 201)\n\n def set_release_date(self,index,sums,r):\n self.release_date = round(index / 25 * sums * r)\n # self.release_date = random.randint(0, 1440)\n def set_due_date(self,sums):\n alpha = [i for i in np.arange(-0.2, 1, 0.1)]\n beta = [i for i in np.arange(0.7, 1.9, 0.1)]\n a = random.choice(alpha)\n b = random.choice(beta)\n if b >= a: b = random.choice([i for i in np.arange(1, 1.9, 0.1)])\n\n self.due_date = int(max(random.randint(5,10),round(random.uniform(sums / 20 * a, sums / 20 * b))) + self.release_date + self.processing_time)\n def transfer_time(self,curr_temp):\n setup = 5 + abs(self.Temperature - curr_temp) * (0.1)\n setup = int(ceil(setup))\n return setup\n # def __lt__(self, other):\n # return self.processing_time < other.processing_time\n","sub_path":"Job.py","file_name":"Job.py","file_ext":"py","file_size_in_byte":2976,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"101396858","text":"# coding: utf-8\n\n'''\nCopyright (c) 2015 Paulo Sérgio Borges de Oliveira Filho\nCheck LICENSE for details.\n'''\n\nimport unittest\nfrom time import sleep\nfrom datetime import datetime, timedelta\n\nfrom synchronizer.runner import Runner\nfrom fixtures import *\n\nclass TestSync(unittest.TestCase):\n def setUp(self):\n self.runner = Runner(**{\n '--interval': 60,\n '--elasticsearch': 'localhost:9200',\n '--cassandra': 'localhost:9042'\n })\n\n self.runner.eraseAll()\n sleep(1)\n\n def tearDown(self):\n self.runner.eraseAll()\n sleep(1)\n\n def test_iterate(self):\n self.runner.cassandra.cql([\n KEYSPACE_FIRST,\n TABLE_DOCUMENTS,\n ]);\n\n # Add documents\n self.runner.cassandra.bulkInsert(CA_DOCUMENTS)\n self.runner.elastic.bulkIndex(ES_DOCUMENTS)\n sleep(1)\n\n # Retrieve changes in the timestamp interval\n now = datetime.utcnow()\n before = now - timedelta(seconds=self.runner.interval)\n elastic, cassandra = self.runner.retrieve_changes(before, now)\n\n # Assert changes lists\n self.assertEqual(len(cassandra), len([d for d in CA_DOCUMENTS\n if d['ts'] <= now and d['ts'] > before]))\n self.assertEqual(len(elastic), len([d for d in ES_DOCUMENTS\n if d['timestamp'] <= now and d['timestamp'] > before]))\n\n for _id, elem in cassandra.iteritems():\n self.assertEqual(elem['db'], 'first')\n self.assertEqual(elem['col'], 'documents')\n\n other = next((o for o in CA_DOCUMENTS if str(o['id']) == _id), None)\n self.assertIsNotNone(other)\n self.assertEqual(elem['obj'], other['row'])\n\n for _id, elem in elastic.iteritems():\n self.assertEqual(elem['db'], 'first')\n self.assertEqual(elem['col'], 'documents')\n\n other = next((o for o in ES_DOCUMENTS if str(o['id']) == _id), None)\n self.assertIsNotNone(other)\n self.assertEqual(elem['obj'], other['body'])\n\n # Build diffs\n es_diff, ca_diff = self.runner.diff_changes(elastic, cassandra)\n\n # Assert diffs\n self.assertEqual(len(ca_diff), 2)\n self.assertEqual(len(es_diff), 2)\n\n self.assertEqual(\n set([e['obj']['title'] for e in ca_diff]),\n set(['Document B (new)', 'Document E'])\n )\n\n self.assertEqual(\n set([e['obj']['title'] for e in es_diff]),\n set(['Document A (new)', 'Document D'])\n )\n\n # Apply diffs\n self.runner.apply_changes(es_diff, ca_diff)\n sleep(1)\n\n ca_final = self.runner.cassandra.select('first', 'documents')\n es_final = self.runner.elastic.search(index='first',\n doc_type='documents')\n\n # Assert new insertions\n self.assertEqual(len(ca_final), 6)\n self.assertEqual(len(es_final), 6)\n\n self.assertEqual(CA_FINAL,\n set([e['obj']['title'] for e in ca_final.values()]))\n\n self.assertEqual(ES_FINAL,\n set([e['obj']['title'] for e in es_final.values()]))\n","sub_path":"tests/tests.py","file_name":"tests.py","file_ext":"py","file_size_in_byte":3145,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"354736298","text":"#encoding: UTF-8\r\n#Autor: Eduardo Roberto Müller Romero, A01745219\r\n#Escribe un programa que calcule el pago a un trabajador\r\n\r\ndef main():\r\n horasextras = int(input(\"Horas Extras Trabajadas: \"))\r\n horasnormales = int(input(\"Horas Normales Trabajadas: \"))\r\n pago = int(input(\"pago por hora: \"))\r\n pagonormal = calcularpagodehorasnormales(horasnormales, pago)\r\n pagoextra = calcularpagoporhorasextras(horasextras, pago)\r\n pago = pagonormal + pagoextra\r\n print(\"pago por hora:\", pago)\r\n print(\"horas normales trabajadas:\", horasnormales)\r\n print(\"horas extras trabajadas:\", horasextras)\r\n print(\"pago por horas normales:\", pagonormal)\r\n print(\"pago por horas extras:\", pagoextra)\r\n print(\"total a pagar:\", pago)\r\n\r\n#multiplica las horas normales por el pago por hora\r\ndef calcularpagodehorasnormales(horasnormales, pago):\r\n pagoporhora = horasnormales * (pago)\r\n return pagoporhora\r\n\r\n#multiplica el pago por hora por 1.5 y luego por las horas extras laboradas\r\ndef calcularpagoporhorasextras(horasextras, pago):\r\n pagoporhorasextras = horasextras * (pago * 1.5)\r\n return pagoporhorasextras\r\n\r\nmain()","sub_path":"pago_al_trabajador.py","file_name":"pago_al_trabajador.py","file_ext":"py","file_size_in_byte":1147,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"585568387","text":"import pandas as pd\nimport bitdotio\nimport psycopg2\nfrom getpass import getpass\nimport os, io\n\n\"\"\"This module provides a wrapper class to integrate bit.io with common Pandas dataframe operations.\"\"\"\n\nclass BitDotIOPandas:\n \"\"\"Wrapper class for Pandas and bit.io to make working with bit.io similar to local files.\n \n Attributes:\n api_key (str): A bit.io API key. Can be passed to constructor, read from ENV \"BITDOTIO_API_KEY\",\n or passed into the CLI, in that order of priority.\n username (str): Optional username to set. If not set, username must be specified for dependent op's.\n repo (str): Optional repo to set. If not set, repo must be specified for dependent op's.\n \"\"\"\n # TODO(doss): Clean up propogation of exceptions through the stack and improve messages\n # TODO(doss): Write unittests once we have an API we agree on\n # TODO(doss): Add info messages to confirm successful DB write operations.\n \n # TODO: Handle more data types like time-zones, periods, half-precision, etc.\n DTYPE_MAP = {\n 'object':'TEXT',\n 'int16': 'INTEGER',\n 'int32': 'INTEGER',\n 'int64': 'INTEGER',\n 'float16': 'REAL',\n 'float32': 'REAL',\n 'float64': 'REAL',\n 'bool': 'BOOLEAN',\n 'datetime64[ns]': 'TIMESTAMP WITHOUT TIME ZONE',\n 'datetime64[ns, UTC]': 'TIMESTAMP WITH TIME ZONE',\n 'datetime64[ns, US/Eastern]': 'TIMESTAMP WITH TIME ZONE'\n }\n \n def __init__(self, api_key=None, username=None, repo=None):\n if not api_key:\n api_key = self._get_api_key()\n # Test API key and raise exception if invalid\n try:\n self._b = bitdotio.bitdotio(api_key)\n self._connect()\n except Exception as e:\n raise ValueError(\"Unable to connect to bit.io with the provided API key.\")\n \n # username and repo are optional at init\n self.username = username\n self.repo = repo\n \n def set_username(self, username):\n '''Sets repo username'''\n self.username = username\n \n def set_repo(self, repo):\n '''Sets repo'''\n self.repo = repo\n \n def list_tables(self, repo=None, username=None):\n '''Lists tables in a specified repo'''\n # TODO(doss): Add info about permissions, like ls -la\n username, repo = self._get_username_and_repo(username, repo)\n return [table.current_name for table in self._b.list_tables(username, repo)]\n \n def list_repos(self, username=None):\n '''Lists tables in a specified repo'''\n # TODO(doss): Add info about permissions, like ls -la\n username, _ = self._get_username_and_repo(username, None)\n return [table.name for table in self._b.list_repos(username)]\n \n def read_sql(self, sql):\n '''Query bit.io with SQL and return a pandas dataframe'''\n try:\n # Connect to bit.io\n conn = self._connect()\n # Execute sql\n return pd.read_sql(sql, conn)\n except Exception as e:\n print(error)\n finally:\n if conn is not None:\n conn.close()\n \n def read_head(self, table, repo=None, username=None, limit=5):\n '''Get first \"limit\" rows from a table'''\n return self._read_table(table, repo, username, limit=limit)\n \n def read_table(self, table, repo=None, username=None, chunksize=None):\n '''Reads a table with optional pagination through a generator.\n \n Args:\n table (str): The table name in bit.io. If not provided, must be set in object.\n repo (str): The repo name in bit.io. If not provided, must be set in object.\n username (str): The username in bit.io. If not provided, must be set in object.\n chunksize (int): The maximum chunk size per download. If not provided the entire table\n is downloaded.\n Returns:\n A pandas DataFrame if no chunksize provided, else a generator that yields pandas\n DataFrames with a maximum of chunksize rows until all rows have been downloaded.\n '''\n if not chunksize:\n return self._read_table(table, repo, username)\n else:\n max_row = self._get_max_row(table, repo, username)\n n_chunks = (max_row // chunksize) + 1\n \n def table_chunk_gen():\n i = 0\n while i < n_chunks:\n yield self._read_table(table, repo, username, limit=chunksize, offset=i * chunksize)\n i += 1\n return table_chunk_gen()\n \n def delete_table(self, table, repo=None, username=None, limit=5):\n '''Deletes a table'''\n username, repo = self._get_username_and_repo(username, repo)\n self._validate_repo_and_table(repo, username, table)\n fully_qualified = self._get_fully_qualified(username, repo, table)\n self.sql(f'DROP TABLE {fully_qualified};')\n \n def sql(self, sql):\n '''Run arbitrary SQL statements on bitdotio'''\n try:\n # Connect to bit.io\n conn = self._connect()\n # Open cursor with bit.io server\n cur = conn.cursor()\n # Execute sql\n cur.execute(sql)\n # Close cursor\n cur.close()\n # Commit the changes (only relevent for write ops)\n conn.commit()\n except Exception as e:\n print(e)\n finally:\n if conn is not None:\n conn.close()\n\n def to_table(self, df, table, repo=None, username=None, append=True, chunksize=None):\n '''Write a dataframe to a bitdotio table, creating the table if necessary.\n\n One difference from a typical Pandas file operation is that we default to append,\n as a safer operation than truncate and insert (requires non-default argument).\n\n Args:\n df (Pandas DataFrame): The dataframe to upload.\n table (str): The table name in bit.io. If not provided, must be set in object.\n repo (str): The repo name in bit.io. If not provided, must be set in object.\n username (str): The username in bit.io. If not provided, must be set in object.\n append (str): Whether to append (default) or truncate and then insert. Optional.\n chunksize (int): Optional chunksize for uploading large tables, default None.\n '''\n # TODO(doss): This is a very naive implementation, maybe can use SQLAlchemy or our own ingestor \n # TODO(doss): This should also support chunking for \"big data\" uploads\n username, repo = self._get_username_and_repo(username, repo)\n self._validate_repo(repo, username)\n fully_qualified = self._get_fully_qualified(username, repo, table)\n\n # Create table if needed\n if table not in self.list_tables(repo, username):\n self._create_table(username, repo, table, df)\n\n # Truncate if needed\n if not append:\n self.sql(f\"DELETE FROM {fully_qualified};\")\n # TODO(doss): look into more robust/performant implementation - SQLAlchemy?\n # TODO(doss): this implementation lacks integrity control for partial insert with chunking\n if chunksize is None:\n chunksize = df.shape[0]\n i = 0\n while i * chunksize < df.shape[0]:\n chunk_start, chunk_end = i * chunksize, (i + 1) * chunksize\n buffer = io.StringIO()\n df.iloc[chunk_start:chunk_end, :].to_csv(buffer, index=False, header=False, na_rep=\"null\", line_terminator=\"\\r\\n\")\n buffer.seek(0)\n try:\n conn = self._connect()\n cursor = conn.cursor()\n cursor.copy_expert(f\"COPY {fully_qualified} FROM STDIN delimiter ',' null as 'null' csv;\", buffer)\n conn.commit()\n except (Exception, psycopg2.DatabaseError) as e:\n print(e)\n conn.rollback()\n finally:\n if conn is not None:\n conn.close()\n i += 1\n \n def __repr__(self):\n return f'BitDotIOPandas Object: username= {self.username}, repo= {self.repo}'\n \n def _get_username_and_repo(self, username, repo):\n '''Retrieves set username and repo if no arguments passed.'''\n username = username if username else self.username\n if not username:\n raise ValueError('Repo username must be initialized or provided as an argument.')\n repo = repo if repo else self.repo\n if not repo:\n raise ValueError('Repo name must be either initialized or provided as an argument.')\n return username, repo\n \n def _get_fully_qualified(self, username, repo, table):\n '''Constructs fully qualified table name from parts'''\n return f'\"{username}/{repo}\".\"{table}\"'\n\n def _get_api_key(self):\n '''Retrieves API key from ENV or username CLI input, in that order'''\n if os.getenv(\"BITDOTIO_API_KEY\"):\n api_key = os.getenv(\"BITDOTIO_API_KEY\")\n else:\n api_key = getpass(\"Please enter your bitdotio API key\")\n return api_key\n \n def _connect(self):\n '''Gets a psycopg2 connection to bit.io'''\n # Get psycopg2 connection\n return self._b.get_connection()\n \n\n def _validate_repo(self, repo, username):\n '''Checks for repo'''\n # TODO: make this handle different permission levels later\n if repo not in self.list_repos(username):\n raise ValueError('Repo not found or not visible with your permissions. Try bpd.list_repos(repo, username).')\n \n def _validate_table(self, repo, username, table):\n '''Checks for repo'''\n # TODO: make this handle different permission levels later\n if table not in self.list_tables(repo, username):\n raise ValueError('Table not found or not visible with your permissions. Try bpd.list_tables(username).')\n \n def _validate_repo_and_table(self, repo, username, table):\n '''Validates repo and table'''\n self._validate_repo(repo, username)\n self._validate_table(repo, username, table)\n \n def _get_max_row(self, table, repo, username):\n '''Get maximum row number for a table'''\n username, repo = self._get_username_and_repo(username, repo)\n self._validate_repo_and_table(repo, username, table)\n fully_qualified = self._get_fully_qualified(username, repo, table)\n sql = f'SELECT COUNT(1) FROM {fully_qualified};'\n return self.read_sql(sql).values[0][0]\n \n def _read_table(self, table, repo=None, username=None, limit=None, offset=None):\n '''Download from a table from bitdotio with optional limit and offset'''\n username, repo = self._get_username_and_repo(username, repo)\n self._validate_repo_and_table(repo, username, table)\n fully_qualified = self._get_fully_qualified(username, repo, table)\n sql = f'SELECT * FROM {fully_qualified};'\n # TODO: look into whether if full qualification and helper and int casting\n # are sufficient for secure use of this helper\n if limit:\n sql = sql[:-1] + f' LIMIT {int(limit)};'\n if offset:\n sql = sql[:-1] + f' OFFSET {int(offset)};'\n return self.read_sql(sql)\n \n def _create_table(self, username, repo, table, df):\n '''Automated table creation from a dataframe with limited type handling'''\n fully_qualified = self._get_fully_qualified(username, repo, table)\n sql = f'CREATE TABLE {fully_qualified} ('\n col_types = []\n breakpoint()\n for col, dtype in dict(df.dtypes).items():\n col_types.append(f'{col} {BitDotIOPandas.DTYPE_MAP.get(str(dtype), \"TEXT\")}')\n sql += ', '.join(col_types)\n sql += ')'\n self.sql(sql)\n return None","sub_path":"summer_reading/bitdotio_pandas.py","file_name":"bitdotio_pandas.py","file_ext":"py","file_size_in_byte":12036,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"402478426","text":"# -*- coding: utf-8 -*-\n'''Public section, including homepage and signup.'''\nfrom flask import (Blueprint, request, render_template, flash, url_for,\n redirect, session, abort, send_from_directory, jsonify)\nfrom flask.ext.login import login_user, login_required, logout_user, current_user\n\nfrom wooey.extensions import login_manager\nfrom wooey.user.models import User\nfrom wooey.public.forms import LoginForm\nfrom wooey.user.forms import RegisterForm\nfrom wooey.utils import flash_errors\nfrom wooey.database import db\n\nfrom werkzeug import secure_filename\n\nfrom collections import defaultdict\n\nimport tempfile\n\nimport json\nimport os\nimport base64\nimport mistune\n\nimport zipfile, tarfile\n\nfrom .models import Script, Job, STATUS_COMPLETE\n\nblueprint = Blueprint('public', __name__, static_folder=\"../static\")\n\n\n@login_manager.user_loader\ndef load_user(id):\n return User.get_by_id(int(id))\n\n\n@blueprint.route(\"/\", methods=[\"GET\", \"POST\"])\ndef home():\n form = LoginForm(request.form)\n # Handle logging in\n if request.method == 'POST':\n if form.validate_on_submit():\n login_user(form.user)\n flash(\"You are logged in.\", 'success')\n redirect_url = request.args.get(\"next\") or url_for(\"user.members\")\n return redirect(redirect_url)\n else:\n flash_errors(form)\n\n scripts = Script.query.order_by(Script.name)\n return render_template(\"public/home.html\", login_form=form, scripts=scripts)\n\n\n@blueprint.route('/logout/')\n@login_required\ndef logout():\n logout_user()\n flash('You are logged out.', 'info')\n return redirect(url_for('public.home'))\n\n\n@blueprint.route(\"/register/\", methods=['GET', 'POST'])\ndef register():\n form = RegisterForm(request.form, csrf_enabled=False)\n if form.validate_on_submit():\n new_user = User.create(username=form.username.data,\n email=form.email.data,\n password=form.password.data,\n active=True)\n flash(\"Thank you for registering. You can now log in.\", 'success')\n return redirect(url_for('public.home'))\n else:\n flash_errors(form)\n return render_template('public/register.html', form=form)\n\n\n@blueprint.route(\"/about/\")\ndef about():\n form = LoginForm(request.form)\n return render_template(\"public/about.html\", form=form)\n\n\n@blueprint.route(\"/scripts/\")\ndef scripts():\n scripts = Script.query.order_by(Script.name)\n return render_template(\"public/scripts.html\", scripts=scripts)\n\n\n@blueprint.route(\"/jobs/create//\", methods=[\"GET\", \"POST\"])\ndef create_job(script_id):\n '''\n Create a new job from the given script.\n\n GET request results in rendering the form\n POST accepts the form, creates the job and redirects to the job view\n\n This function handles the conversion of POSTed data into a command line arg sequence for\n subsequent running as a job object.\n\n :param script_id:\n :return:\n '''\n\n # Get the script object from the database\n script = Script.query.get(script_id)\n\n if request.method == 'GET':\n # Find the documentation and parse it using markdown\n documentation = script.load_docs()\n if documentation:\n documentation = mistune.markdown(documentation)\n\n # Render the script view\n return render_template(\"public/job.html\", script=script, metadata=script.load_config(),\n documentation=documentation)\n\n elif request.method == 'POST':\n # Handle the form submission to generate the arguments for the script\n metadata = script.load_config()\n\n args = []\n tempdir = tempfile.mkdtemp()\n\n for l in ['required', 'optional']:\n for a in metadata[l]:\n # Positional arguments\n name = a['name']\n\n if (name in request.form and request.form[name]) or \\\n (name in request.files and request.files[name]):\n\n # Add the command switch if defined\n if a['commands']:\n args.append(a['commands'][0])\n\n if name in request.form:\n\n # Required arguments are positional; so plot it into place\n # FIXME: Probably a better check to do here, might require additional data from the parser\n if a['widget'] not in [\"CheckBox\"]:\n if 'nargs' in a and ( a['nargs'] == '+' or a['nargs'] == '*' ):\n args.extend(request.form[name].split(\" \"))\n else:\n args.append(request.form[name])\n\n elif name in request.files:\n # FIXME: Should account for the EXCLUDED UPLOAD in settings.py\n # Process file upload. We need to copy to a temporary file and update the dictionary\n file = request.files[name]\n fname = os.path.join(tempdir, secure_filename(file.filename))\n file.save(fname)\n args.append(fname)\n\n # Create the job\n # FIXME: Priority should be calculated from the higest value of the script and the user\n # e.g. a user with priority 10 running a priority 1 script, will get a priority 10 job\n\n if current_user.is_anonymous():\n # Allow non-logged in users to submit public jobs\n user = None\n else:\n user = current_user\n\n job = Job(script=script, user=user, path=tempdir, config=json.dumps({'args': args}), priority=script.priority)\n db.session.commit()\n\n return redirect(url_for('public.job', job_id=job.id))\n\n\ndef build_display_objects(files):\n\n display = defaultdict(list)\n\n for filename in sorted(files):\n\n name, ext = os.path.splitext(os.path.basename(filename))\n\n if ext in ['.png', '.jpg', '.jpeg', '.tif', '.tiff']:\n with open(filename, 'r') as f:\n src = ''\n size = f.tell()\n\n display['Images'].append({\n 'name': name,\n 'src': src,\n 'icon': 'file-image-o',\n 'metadata': [\"%dkB\" % (size / 1024), 'image/%s' % ext[1:]]\n })\n\n elif ext in ['.svg']:\n with open(filename, 'r') as f:\n src = f.read().decode('utf8')\n size = f.tell()\n\n display['Images'].append({\n 'name': name,\n 'src': src,\n 'icon': 'file-image-o',\n 'metadata': [\"%dkB\" % (size / 1024), 'image/%s' % ext[1:]]\n })\n\n elif ext in ['.htm', '.html']:\n with open(filename, 'r') as f:\n src = f.read().decode('utf8')\n size = f.tell()\n\n display['Html'].append({\n 'name': name,\n 'src': '' % src,\n 'icon': 'file-text-o',\n 'metadata': [\"%dkB\" % (size / 1024), 'text/%s' % ext[1:]]\n })\n\n\n else: # Miscellaneous files\n size = os.path.getsize(filename)\n display['Other'].append({\n 'name': name,\n 'src': \"\",\n 'icon': 'file-o',\n 'metadata': [\"%dkB\" % (size / 1024), ext[1:].upper()]\n })\n\n return display\n\n\n@blueprint.route(\"/jobs//\")\ndef job(job_id):\n '''\n View a single job (any status) with AJAX callback to update elements, e.g.\n - STDOUT/STDERR\n - File outputs (figures, etc.), intelligent render handling\n - Download link for all files\n\n\n :param job_id:\n :return:\n '''\n\n # Get the job object from the database\n job = Job.query.get(job_id)\n script = job.script\n display = {}\n\n cwd = os.path.join(job.path, 'output') # Excution path of the job\n if os.path.isdir(cwd): # Execution has begun/finished\n\n files = job.get_output_files()\n display = build_display_objects(files)\n\n documentation = script.load_docs()\n if documentation:\n documentation = mistune.markdown(documentation)\n\n return render_template(\"public/job.html\", script=script, job=job, metadata=script.load_config(), display=display,\n documentation=documentation)\n\n\n@blueprint.route(\"/jobs/.json\")\ndef job_json(job_id):\n '''\n Get the current job status information by AJAX, sufficient to update the current view with output.\n\n This will be polled every 5s on running jobs.\n\n :param job_id:\n :return:\n '''\n\n job = Job.query.get(job_id)\n\n files = job.get_output_files()\n displayo = build_display_objects(files)\n\n display = {}\n for section, oo in displayo.items():\n display[section] = {\n 'count': len(oo),\n 'content': render_template(\"public/job_content.html\", section=section, oo=sorted(oo)),\n }\n\n data = {\n 'status': job.status,\n 'updated_at': job.updated_at,\n 'started_at': job.started_at,\n 'stopped_at': job.stopped_at,\n 'priority': job.priority,\n 'console': job.console, # Might be a bit heavy on disk access\n 'has_output': job.has_output, # Might be a bit heavy on disk access\n 'display': display,\n 'progress': job.progress,\n }\n\n return jsonify(**data)\n\n\ndef make_zipdir(zipf, path):\n for root, dirs, files in os.walk(path):\n for file in files:\n fn = os.path.join(root, file)\n zipf.write(fn, os.path.relpath(fn, path))\n\n\n@blueprint.route(\"/jobs//download\")\ndef download_job_output(job_id, format):\n if format not in ['.zip', '.tgz', '.tar.gz']:\n abort(404)\n\n job = Job.query.get(job_id)\n\n if job.stopped_at is None:\n # Don't return (or generate) a download until the job is stopped (error or complete)\n abort(404)\n\n fn = secure_filename(\"%s_%d%s\" % (job.script.name, job.id, format))\n path_fn = os.path.join(job.path, fn)\n\n # Check for existence of pre-zipped files\n if not os.path.exists(path_fn):\n\n # Target folder to zip\n folder = os.path.join(job.path, 'output')\n\n if format == '.zip':\n with zipfile.ZipFile(path_fn, 'w', zipfile.ZIP_DEFLATED) as zipf:\n make_zipdir(zipf, folder)\n\n elif format in ['.tar.gz', '.tgz']:\n\n with tarfile.open(path_fn, \"w:gz\") as tarzf:\n tarzf.add(folder, arcname=\"\")\n\n # Return the download\n return send_from_directory(job.path, fn, as_attachment=True)\n\n\n@blueprint.route(\"/queue/\")\ndef queue():\n jobs = Job.query.order_by(Job.created_at.desc())\n return render_template(\"public/queue.html\", jobs=jobs)\n\n\n@blueprint.context_processor\ndef inject_login_form():\n return {\n 'login_form': LoginForm(request.form),\n }","sub_path":"wooey/public/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":11049,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"270195591","text":"from scipy import stats\nimport numpy as np\nimport pandas as pd\n\ndef filter_outlier_value_range(dt, filter_columns=\"all\", threshold_zscore=3, threshold_iqr=1.5):\n\n\tdata = dt.copy()\n\t\n\tif not isinstance(dt, pd.DataFrame):\n\t\tdata = pd.DataFrame(dt, columns=['temp'])\n\t\tfilter_columns = ['temp']\n\t\t\n\tif filter_columns == \"all\":\n\t\tfilter_columns = data.columns\n\t\tfilter_df = data\n\telse:\n\t\tfilter_df = data[filter_columns]\n\t\t\n\tz = np.abs(stats.zscore(filter_df))\n\tfilter_df = filter_df[(z < threshold_zscore).all(axis=1)]\n\n\tQ1 = filter_df.quantile(0.25)\n\tQ3 = filter_df.quantile(0.75)\n\tIQR = Q3 - Q1\n\tfilter_df = filter_df[~((filter_df < (Q1 - threshold_iqr * IQR)) |(filter_df > (Q3 + threshold_iqr * IQR))).any(axis=1)]\n\n\tfiltered_df = data\n\tfiltered_df[filter_columns] = filter_df\n\tfiltered_df = filtered_df.dropna()\n\n\tif not isinstance(dt, pd.DataFrame):\n\t\treturn filtered_df['temp'].values\n\telse:\n\t\treturn filtered_df\n\n\ndef filter_outlier_category(df, category_column=None, threshold_category=0.7):\n\n df_count = df.groupby(category_column, as_index=False).count()\n index = np.where(df.columns != category_column)[0][0]\n column_name = df.columns[index]\n df_count = df_count.rename(columns={column_name:'count'})\n df_count = df_count[[category_column, 'count']]\n \n z = stats.zscore(df_count['count'])\n df_count['z'] = z\n df_count = df_count[df_count['z']>-threshold_category]\n \n df_category = pd.DataFrame(df_count[category_column])\n filtered_df = df.merge(df_category, on=category_column, how='right' )\n\n return filtered_df","sub_path":"Final_project-Horse racing prediction/api/common/filter_outlier.py","file_name":"filter_outlier.py","file_ext":"py","file_size_in_byte":1561,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"581717762","text":"#!/eecs/research/asr/mingbin/python-workspace/hopeless/bin/python\n\n\"\"\"\nAuthor : Mingbin Xu (mingbin.xu@gmail.com)\nFilename : kbp-ed-trainer.py\nLast Update : Jul 26, 2016\nDescription : N/A\nWebsite : https://wiki.eecs.yorku.ca/lab/MLL/\n\nCopyright (c) 2016 iNCML (author: Mingbin Xu)\nLicense: MIT License (see ../LICENSE)\n\"\"\"\n\nimport argparse, logging, time\nfrom itertools import product, chain\n\n\nif __name__ == '__main__':\n\n parser = argparse.ArgumentParser()\n\n parser.add_argument( 'word_embedding', type = str, \n help = 'word_embedding.{-case-insensitive, -case-sensitive}.word2vec are assumed' )\n parser.add_argument( 'data_path', type = str, \n help = 'path to ed-eng-{train,eval} of KBP2015' )\n\n # training-related arguments\n parser.add_argument( '--n_char_embedding', type = int, default = 32,\n help = 'char embedding dimension' )\n parser.add_argument( '--n_ner_embedding', type = int, default = 32,\n help = 'ner embedding dimension' )\n parser.add_argument( '--n_char', type = int, default = 128,\n help = 'character set size. since ascii is used; 128 is assumed' )\n parser.add_argument( '--layer_size', type = str, default = '512,512,512',\n help = 'size of fully connected layers after projection' )\n parser.add_argument( '--n_batch_size', type = int, default = 512,\n help = 'mini batch size; the last one may be smaller' )\n parser.add_argument( '--learning_rate', type = float, default = 0.1024,\n help = 'global initial learning rate' )\n parser.add_argument( '--momentum', type = float, default = 0.9,\n help = 'momentum value when MomentumOptimizer is used' )\n parser.add_argument( '--max_iter', type = int, default = 64,\n help = 'maximum number of iterations' )\n parser.add_argument( '--feature_choice', type = int, default = 767,\n help = 'the features used are pick with a bit mask. They are ' + \n '1) case-insensitive/character-level bfofe with candidate word(s), ' +\n '2) case-insensitive/character-level bfofe without candidate word(s), ' + \n '3) case-insensitive/character-level bag-of-words, ' + \n '4) case-sensitive/word-level bfofe with candidate word(s), ' +\n '5) case-sensitive/word-level bfofe without candidate word(s), ' + \n '6) case-sensitive/word-level bag-of-words, ' + \n '7) char-level bfofe of candidate word(s), ' + \n '8) char-level bfofe of candidate initial, ' + \n '9) gazetteer exact match, ' +\n '10) character-convolution'\n 'e.g. if choice is 0b000111111, feature 1 to 6 are used' )\n parser.add_argument( '--overlap_rate', type = float, default = 0.08,\n help = 'what percentage of overlap examples is used during training' )\n parser.add_argument( '--disjoint_rate', type = float, default = 0.016,\n help = 'what percentage of disjoint example is used during training' )\n parser.add_argument( '--dropout', action = 'store_true', default = False,\n help = 'whether to use dropout or not' )\n parser.add_argument( '--char_alpha', type = float, default = 0.8,\n help = 'char-level forgetting factor' )\n parser.add_argument( '--word_alpha', type = float, default = 0.5,\n help = 'word-level forgetting factor' )\n parser.add_argument( '--share_word_embedding', action = 'store_true', default = False,\n help = 'whether or not bow and context share a same word embedding' )\n parser.add_argument( '--n_window', type = int, default = 7,\n help = 'maximum length of NER candidate' )\n parser.add_argument( '--strictly_one_hot', action = 'store_true', default = False,\n help = 'when gazetteer is used, True if 7-bit match or False 5-bit match' )\n parser.add_argument( '--hope_out', type = int, default = 0,\n help = 'dimension of z in the HOPE paper; 0 means not used' )\n parser.add_argument( '--n_label_type', type = int, default = 10,\n help = 'By default, PER, LOC, ORG and MISC are assumed' )\n parser.add_argument( '--kernel_height', type = str, default = '2,3,4,5,6,7,8,9' )\n parser.add_argument( '--kernel_depth', type = str, default = ','.join( ['16'] * 8 ) )\n parser.add_argument( '--enable_distant_supervision', action = 'store_true', default = False ) \n parser.add_argument( '--initialize_method', type = str, default = 'uniform',\n choices = [ 'uniform', 'gaussian' ] )\n parser.add_argument( '--model', type = str, default = 'kbp2016' )\n parser.add_argument( '--iflytek', action = 'store_true', default = False )\n parser.add_argument( '--language', type = str, choices = ['eng', 'cmn', 'spa'], default = 'eng' )\n parser.add_argument( '--average', action = 'store_true', default = False,\n help = 'word embedding is averaged on number of characters ' + \\\n 'when word level feature is used in Chinese' )\n\n ########################################################################\n\n # set a logging file at DEBUG level, TODO: windows doesn't allow \":\" appear in a file name\n logging.basicConfig( format = '%(asctime)s : %(levelname)s : %(message)s', \n level= logging.DEBUG,\n filename = ('log/kbp ' + time.ctime() + '.log').replace(' ', '-'), \n filemode = 'w' )\n\n # direct the INFO-level logging to the screen\n console = logging.StreamHandler()\n console.setLevel( logging.INFO )\n console.setFormatter( logging.Formatter( '%(asctime)s : %(levelname)s : %(message)s' ) )\n logging.getLogger().addHandler( console )\n\n logger = logging.getLogger()\n\n ########################################################################\n\n args = parser.parse_args()\n logger.info( str(args) + '\\n' )\n\n ########################################################################\n\n from fofe_mention_net import *\n config = mention_config( args )\n\n ########################################################################\n\n mention_net = fofe_mention_net( config )\n mention_net.tofile( args.model )\n\n ########################################################################\n\n # there are 2 sets of vocabulary, case-insensitive and case sensitive\n # for simplicity, same forgetting factor is used at character level\n if config.language != 'cmn':\n numericizer1 = vocabulary( config.word_embedding + '-case-insensitive.wordlist', \n config.char_alpha, False )\n numericizer2 = vocabulary( config.word_embedding + '-case-sensitive.wordlist', \n config.char_alpha, True )\n else:\n numericizer1 = chinese_word_vocab( config.word_embedding + '-char.wordlist' )\n numericizer2 = chinese_word_vocab( config.word_embedding + \\\n ('-avg.wordlist' if config.average else '-word.wordlist') )\n \n # it's assumed that there are exactly 2 files in 'data_path'\n # namely 'ed-eng-train' and 'ed-eng-eval'\n kbp_gazetteer = gazetteer( config.data_path + '/kbp-gazetteer', mode = 'KBP' )\n\n source = imap( lambda x: x[:4],\n LoadED( config.data_path + '/%s-train-parsed' % config.language ) ) \n\n if args.iflytek:\n source = chain( source,\n imap( lambda x: x[:4], \n LoadED( 'iflytek-clean-%s' % config.language ) ) )\n human = batch_constructor( source,\n numericizer1, numericizer2, gazetteer = kbp_gazetteer, \n alpha = config.word_alpha, window = config.n_window, \n n_label_type = config.n_label_type,\n language = config.language )\n logger.info( 'human: ' + str(human) )\n \n valid = batch_constructor( # KBP2015( data_path + '/ed-eng-eval' ), \n imap( lambda x: x[:4], LoadED( config.data_path + '/%s-eval-parsed' % config.language ) ), \n numericizer1, numericizer2, gazetteer = kbp_gazetteer, \n alpha = config.word_alpha, window = config.n_window, \n n_label_type = config.n_label_type,\n language = config.language )\n logger.info( 'valid: ' + str(valid) )\n \n test = batch_constructor( # KBP2015( data_path + '/ed-eng-train' ), \n imap( lambda x: x[:4], LoadED( config.data_path + '/%s-train-parsed' % config.language ) ),\n numericizer1, numericizer2, gazetteer = kbp_gazetteer, \n alpha = config.word_alpha, window = config.n_window, \n n_label_type = config.n_label_type,\n language = config.language )\n logger.info( 'test: ' + str(test) )\n\n logger.info( 'data set loaded' )\n\n\n ################### let's compute ####################\n\n prev_cost, decay_started = 2054, False\n\n infinite_human = human.infinite_mini_batch_multi_thread( \n config.n_batch_size, \n True, \n config.overlap_rate, \n config.disjoint_rate, \n config.feature_choice, \n True )\n\n for n_epoch in xrange( config.max_iter ):\n\n if not os.path.exists( 'kbp-result' ):\n os.makedirs( 'kbp-result' )\n\n valid_predicted_file = 'kbp-result/kbp-valid-%s.predicted' % args.model \n test_predicted_file = 'kbp-result/kbp-test-%s.predicted' % args.model\n valid_predicted = open( valid_predicted_file, 'wb' )\n test_predicted = open( test_predicted_file, 'wb' )\n\n #############################################\n ########## go through training set ##########\n #############################################\n\n if config.enable_distant_supervision:\n dsp = distant_supervision_parser( \n '/local/scratch/mingbin/distant-supervision/sentences-v2',\n '/local/scratch/mingbin/distant-supervision/joint-labels-v2',\n n_epoch, None, 128 )\n train = batch_constructor( dsp, numericizer1, numericizer2, \n gazetteer = kbp_gazetteer, \n alpha = config.word_alpha, \n window = config.n_window, \n n_label_type = config.n_label_type,\n language = config.language )\n logger.info( 'train: ' + str(train) )\n else:\n train = human\n\n # phar is used to observe training progress\n logger.info( 'epoch %2d, learning-rate: %f' % \\\n (n_epoch + 1, mention_net.config.learning_rate) )\n pbar = tqdm( total = len(train.positive) + \n int(len(train.overlap) * config.overlap_rate) +\n int(len(train.disjoint) * config.disjoint_rate) )\n\n cost, cnt = 0, 0\n \n for x in ifilter( lambda x : x[-1].shape[0] == config.n_batch_size,\n train.mini_batch_multi_thread( config.n_batch_size, \n True, \n config.overlap_rate, \n config.disjoint_rate, \n config.feature_choice ) ):\n if config.enable_distant_supervision:\n x = [ x, infinite_human.next() ]\n if choice( [ True, False ] ):\n x.append( infinite_human.next() )\n else:\n x = [ x ]\n\n for example in x:\n c = mention_net.train( example )\n\n cost += c * example[-1].shape[0]\n cnt += example[-1].shape[0]\n pbar.update( example[-1].shape[0] )\n\n pbar.close()\n train_cost = cost / cnt \n logger.info( 'training set iterated, %f' % train_cost )\n\n ########################################################################\n\n if n_epoch + 1 == config.max_iter:\n # if config.enable_distant_supervision or \\\n # n_epoch + 1 == config.max_iter or \\\n # (n_epoch + 1) % min(16, config.max_iter / 16) == 0:\n ###############################################\n ########## go through validation set ##########\n ###############################################\n\n cost, cnt = 0, 0\n for example in valid.mini_batch_multi_thread( \n 256 if config.feature_choice & (1 << 9 ) > 0 else 1024, \n False, 1, 1, config.feature_choice ):\n\n c, pi, pv = mention_net.eval( example )\n\n cost += c * example[-1].shape[0]\n cnt += example[-1].shape[0]\n for expected, estimate, probability in zip( example[-1], pi, pv ):\n print >> valid_predicted, '%d %d %s' % \\\n (expected, estimate, ' '.join( [('%f' % x) for x in probability.tolist()] ))\n\n valid_cost = cost / cnt \n valid_predicted.close()\n\n #########################################\n ########## go through test set ##########\n #########################################\n\n cost, cnt = 0, 0\n for example in test.mini_batch_multi_thread( \n 256 if config.feature_choice & (1 << 9 ) > 0 else 1024, \n False, 1, 1, config.feature_choice ):\n\n c, pi, pv = mention_net.eval( example )\n\n cost += c * example[-1].shape[0]\n cnt += example[-1].shape[0]\n for expected, estimate, probability in zip( example[-1], pi, pv ):\n print >> test_predicted, '%d %d %s' % \\\n (expected, estimate, ' '.join( [('%f' % x) for x in probability.tolist()] ))\n\n test_cost = cost / cnt \n test_predicted.close()\n\n ###################################################################################\n ########## exhaustively iterate 3 decodding algrithms with 0.x cut-off ############\n ###################################################################################\n\n # logger.info( 'cost: %f (train), %f (valid), %f (test)', train_cost, valid_cost, test_cost )\n logger.info( 'cost: %f (train), %f (valid), %f (test)', train_cost, valid_cost, test_cost )\n\n # algo_list = ['highest-first', 'longest-first', 'subsumption-removal']\n idx2algo = { 1: 'highest-first', 2: 'longest-first', 3:'subsumption-removal' }\n algo2idx = { 'highest-first': 1, 'longest-first': 2, 'subsumption-removal': 3 }\n\n best_dev_fb1, best_threshold, best_algorithm = 0, [0.5, 0.5], [1, 1]\n\n if n_epoch >= config.max_iter / 2:\n pp = [ p for p in PredictionParser( # KBP2015( data_path + '/ed-eng-eval' ), \n imap( lambda x: x[:4], LoadED( config.data_path + '/%s-eval-parsed' % config.language ) ),\n valid_predicted_file, config.n_window,\n n_label_type = config.n_label_type ) ]\n\n for algorithm in product( [1, 2], repeat = 2 ):\n algorithm = list( algorithm )\n name = [ idx2algo[i] for i in algorithm ]\n for threshold in product( [ 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9 ], repeat = 2 ):\n threshold = list( threshold )\n\n precision, recall, f1, _ = evaluation( pp, threshold, algorithm, True,\n n_label_type = config.n_label_type )\n # logger.debug( ('cut-off: %f, algorithm: %-20s' % (threshold, name)) + \n # (', validation -- precision: %f, recall: %f, fb1: %f' % (precision, recall, f1)) )\n if f1 > best_dev_fb1:\n best_dev_fb1, best_threshold, best_algorithm = f1, threshold, algorithm\n best_precision, best_recall = precision, recall\n mention_net.config.algorithm = best_algorithm\n mention_net.config.threshold = best_threshold\n mention_net.tofile( args.model )\n\n logger.info( 'cut-off: %s, algorithm: %-20s' % \\\n (str(best_threshold), str([ idx2algo[i] for i in best_algorithm ])) )\n\n precision, recall, f1, info = evaluation( PredictionParser( # KBP2015( data_path + '/ed-eng-eval' ),\n imap( lambda x: x[:4], LoadED( config.data_path + '/%s-eval-parsed' % config.language ) ),\n valid_predicted_file, config.n_window,\n n_label_type = config.n_label_type ), \n best_threshold, best_algorithm, True,\n analysis = None, #analysis,\n n_label_type = config.n_label_type )\n logger.info( '%s\\n%s' % ('validation', info) ) \n\n precision, recall, f1, info = evaluation( PredictionParser( # KBP2015( data_path + '/ed-eng-train' ),\n imap( lambda x: x[:4], LoadED( config.data_path + '/%s-train-parsed' % config.language ) ),\n test_predicted_file, config.n_window,\n n_label_type = config.n_label_type ), \n best_threshold, best_algorithm, True,\n analysis = None, #analysis,\n n_label_type = config.n_label_type )\n logger.info( '%s\\n%s' % ('test', info) ) \n\n mention_net.config.learning_rate *= 0.5 ** ((4./ config.max_iter) if config.drop_rate > 0 else (1./ 2))\n mention_net.config.drop_rate *= 0.5 ** (2./ config.max_iter)\n\n logger.info( 'results are written in kbp-result/kbp-{valid,test}.predicted' )\n","sub_path":"kbp-ed-trainer.py","file_name":"kbp-ed-trainer.py","file_ext":"py","file_size_in_byte":19525,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"14703196","text":"\n\n#calss header\nclass _TIMBRE():\n\tdef __init__(self,): \n\t\tself.name = \"TIMBRE\"\n\t\tself.definitions = [u'a quality of sound that makes voices or musical instruments sound different from each other: ']\n\n\t\tself.parents = []\n\t\tself.childen = []\n\t\tself.properties = []\n\t\tself.jsondata = {}\n\n\n\t\tself.specie = 'nouns'\n\n\n\tdef run(self, obj1 = [], obj2 = []):\n\t\treturn self.jsondata\n","sub_path":"xai/brain/wordbase/nouns/_timbre.py","file_name":"_timbre.py","file_ext":"py","file_size_in_byte":373,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"203399790","text":"\nfrom typing import List\n\n\"\"\"\nhttps://leetcode-cn.com/problems/rotate-matrix-lcci/\n矩阵 旋转 90度\n\n\nGiven an image represented by an N x N matrix, \nwhere each pixel in the image is 4 bytes, \nwrite a method to rotate the image by 90 degrees. \nCan you do this in place?\n\n \n\nExample 1:\n\nGiven matrix = \n[\n [1,2,3],\n [4,5,6],\n [7,8,9]\n],\n\nRotate the matrix in place. It becomes:\n[\n [7,4,1],\n [8,5,2],\n [9,6,3]\n]\nExample 2:\n\nGiven matrix =\n[\n [ 5, 1, 9,11],\n [ 2, 4, 8,10],\n [13, 3, 6, 7],\n [15,14,12,16]\n], \n\nRotate the matrix in place. It becomes:\n[\n [15,13, 2, 5],\n [14, 3, 4, 1],\n [12, 6, 8, 9],\n [16, 7,10,11]\n]\n\n\n方案1:\n找出 第 i 圈,观察 4个角移动的特点和关系。\n\n方案2:\n矩阵 沿 左上-右下 对角反转\n再沿 左右翻转\n\n\"\"\"\nclass Solution:\n def rotate(self, matrix: List[List[int]]) -> None:\n \"\"\"\n Do not return anything, modify matrix in-place instead.\n \"\"\"\n n = len(matrix)\n for level in range(0, n - 1):\n \"\"\"\n 第 i 层,从 i,i -> i,n-1-i -> n-1-i,n-1-i -> n-1-i,i\n 左上 每向右移动一\n -> 右上 向下移动一\n -> 右下 向左 移动一\n -> 左下 向上 移动一\n \"\"\"\n for j in range(level, (n - 1 - level)):\n x1 = level\n y1 = j\n x2 = j\n y2 = n - 1 - level\n x3 = n - 1 - level\n y3 = n - 1 - j\n x4 = n - 1 - j\n y4 = level\n\n matrix[x1][y1], matrix[x2][y2], matrix[x3][y3], matrix[x4][y4], = matrix[x4][y4], matrix[x1][y1], \\\n matrix[x2][y2], matrix[x3][y3],\n","sub_path":"leetcode/array/rotate-matrix-lcci.py","file_name":"rotate-matrix-lcci.py","file_ext":"py","file_size_in_byte":1772,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"8267498","text":"import numpy as np\n\n\nclass NaiveBayes:\n def _create_vocabulary(self, data):\n vocab_set = set()\n for record in data:\n vocab_set = vocab_set | set(record)\n\n return list(vocab_set)\n\n def _words_to_vec(self, vocabulary, record):\n vec = np.zeros(len(vocabulary))\n for word in record:\n if word in vocabulary:\n vec[vocabulary.index(word)] = 1\n else:\n print('The word {} is not in vocabulary.'.format(word))\n\n return vec\n\n def _create_matrix(self, vocabulary, data):\n mat = np.zeros((len(data), len(vocabulary)))\n for i, record in enumerate(data):\n mat[i, :] = self._words_to_vec(vocabulary, record)\n\n return mat\n\n def fit(self, data, label):\n unique_label = list(set(label))\n num_classes = len(unique_label)\n vocabulary = self._create_vocabulary(data)\n\n train_matrix = self._create_matrix(vocabulary, data)\n num_records, num_words = train_matrix.shape\n prob_matrix = np.ones((num_classes, num_words))\n prob_class = np.zeros(num_classes)\n words_num = np.ones(num_classes) + 1.0\n for i in range(num_records):\n label_idx = unique_label.index(label[i])\n prob_class[label_idx] += 1\n prob_matrix[label_idx, :] += train_matrix[i]\n words_num[label_idx] += np.sum(train_matrix[i])\n\n for i in range(num_classes):\n prob_matrix[i, :] /= words_num[i]\n prob_class /= num_records\n prob_matrix = np.log(prob_matrix)\n\n self.unique_label = unique_label\n self.prob_class = prob_class\n self.prob_matrix = prob_matrix\n self.vocabulary = vocabulary\n\n def predict(self, data):\n num_classes = len(self.unique_label)\n prob_vec = np.zeros(num_classes)\n test_matrix = self._create_matrix(self.vocabulary, data)\n\n for record in data:\n for i in range(num_classes):\n pass","sub_path":"NaiveBayes/bayes.py","file_name":"bayes.py","file_ext":"py","file_size_in_byte":2007,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"194678002","text":"__author__ = 'Hanh'\n# Constructor Critter\n\nclass Critter(object):\n \"\"\"A virtual pet\"\"\"\n \"\"\"Structure of class\"\"\"\n # Track of the total number of Critter objects instantiated.\n total_critter = 0\n \"\"\"Methods of class\"\"\"\n @staticmethod\n def status():\n print(\"\\nThe total number of critters is \",Critter.total_critter)\n # Constructors\n def __init__(self):\n print(\"A new critter has been born!\")\n self.name = \"Newbie\"\n Critter.total_critter += 1\n\n def __init__(self,name):\n print(\"A new critter has been born!\")\n if name == '' or name is None:\n self.name = \"Newbie\"\n else:\n self.name = name;\n Critter.total_critter += 1\n\n # Utilities\n def talk(self):\n print(\"Hi. I'm\", self.name, \"\\n\")\n\n def __str__(self):\n rep = \"Critter object\\n\"\n rep += \"name: \" + self.name + \"\\n\"\n return rep\n\n# Main test\ncritter1 = Critter(\"Steve\")\ncritter1.talk()\n\ncritter2 = Critter(\"Rechie\")\ncritter2.talk()\n\ncritter3 = Critter(\"\")\ncritter3.talk()\n\nCritter.status()\n\ninput(\"\\n\\nPress the enter key to exit.\")\n","sub_path":"Critter.py","file_name":"Critter.py","file_ext":"py","file_size_in_byte":1125,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"228972082","text":"import glob\nimport os\nimport sys\n\ntry:\n sys.path.append(glob.glob('../../carla/dist/carla-*%d.%d-%s.egg' % (\n sys.version_info.major,\n sys.version_info.minor,\n 'win-amd64' if os.name == 'nt' else 'linux-x86_64'))[0])\n\nexcept IndexError:\n pass\n\nimport carla\n\nimport time\nimport math\nimport keyboard\nimport warnings\nwarnings.filterwarnings(\"ignore\")\nimport cvxpy\nimport random\n\nimport numpy as np\n\nsys.path.append(r\"../../\")\nfrom fhdo_casestudy.cs_utils import dictionaries as dic\nfrom fhdo_casestudy.cs_utils import sensor_util as su\nfrom fhdo_casestudy.cs_utils import tools as to\nfrom fhdo_casestudy.cs_utils import module_p2\nfrom fhdo_casestudy.mpc import cubic_spline_planner as cubic_spline_planner\n\nfrom queue import Queue\nfrom queue import Empty\n\nnp.random.seed(2)\n\n# -- VARIABLE INITIALIZATION --\n# Specify the wanted map\ntown_dic = dic.town02\n\nmap_name, \\\n weather_type, \\\n current_town, \\\n gps_intersection_csv, \\\n waypoints_csv, \\\n spawn_csv, \\\n carla_intersection_csv, \\\n road_segments_file = to.paths_initialization(town_dic)\n\n\ndef update_carla_state(vehicle):\n control = vehicle.get_control()\n throttle, brake, steer = control.throttle, control.brake, control.steer\n\n # get location\n location = vehicle.get_location()\n loc_x, loc_y = location.x, location.y\n\n # get rotation\n yaw = vehicle.get_transform().rotation.yaw\n yaw = np.deg2rad(yaw)\n\n # get velocity\n v = vehicle.get_velocity()\n ms = math.sqrt(v.x ** 2 + v.y ** 2 + v.z ** 2)\n kmh = int(3.6 * ms)\n\n\ndef carla_world_plot(world, path, z=1.0, lt=0.0):\n debug = world.debug\n for x, y in path:\n location = carla.Location(x=x, y=y, z=z)\n debug.draw_point(\n location,\n size=0.1,\n life_time=lt,\n persistent_lines=False,\n color=carla.Color(0, 255, 0))\n\n\ndef sensor_callback(sensor_data, sensor_queue, sensor_name):\n sensor_queue.put((sensor_data, sensor_name))\n\n\ndef game_loop(reload=True, hp=False, cp=False): # hp: Horizon plot - cp: Course plot\n client = carla.Client('localhost', 2000)\n client.set_timeout(10.0)\n\n # List initialization\n actor_list, sensor_list = [], []\n gnss_list, zgnss_list = [], []\n imu_list, zimu_list = [], []\n loc_data = []\n sensor_queue = Queue()\n\n try:\n if reload:\n print(\"Loading world...\")\n world = client.load_world(town_dic['name'])\n else:\n world = client.get_world()\n\n settings = world.get_settings()\n settings.synchronous_mode = True\n world.apply_settings(settings)\n traffic_manager = client.get_trafficmanager()\n\n # Spectator\n spectator = world.get_spectator()\n transform = carla.Transform(carla.Location(x=town_dic['x'], y=town_dic['y'], z=town_dic['z']),\n carla.Rotation(pitch=town_dic['pitch'], yaw=town_dic['yaw']))\n spectator.set_transform(transform)\n\n # World setting\n world.set_weather(getattr(carla.WeatherParameters, town_dic['weather'])) # set weather\n blueprint_library = world.get_blueprint_library() # get blueprint library\n\n # Vehicle\n vehicle_model = \"mercedesccc\" # \"model3\"/\"lincoln\"/\"mercedesccc\"\n vehicle_color = dic.petronas_color\n vehicle = su.spawn_vehicle(world, blueprint_library, vehicle_model, vehicle_color)\n actor_list.append(vehicle)\n\n # == GNSS: zero noise\n zgnss = su.spawn_gnss(world, blueprint_library, vehicle, dic.gnss)\n zgnss.listen(lambda zgnss_event: sensor_callback(zgnss_event, sensor_queue, 0))\n sensor_list.append(zgnss)\n\n # == GNSS\n gnss = su.spawn_gnss(world, blueprint_library, vehicle, dic.gnss_noise)\n gnss.listen(lambda gnss_event: sensor_callback(gnss_event, sensor_queue, 1))\n sensor_list.append(gnss)\n\n # == IMU: zero noise\n zimu = su.spawn_imu(world, blueprint_library, vehicle, dic.imu)\n zimu.listen(lambda zimu_event: sensor_callback(zimu_event, sensor_queue, 2))\n sensor_list.append(zimu)\n\n # == IMU:\n imu = su.spawn_imu(world, blueprint_library, vehicle, dic.imu_noise)\n imu.listen(lambda imu_event: sensor_callback(imu_event, sensor_queue, 3))\n sensor_list.append(imu)\n\n # == Camera: Spectator\n cam_spectate = su.spawn_camera_rgb(world, blueprint_library, vehicle, dic.cam_spectate_1)\n cam_spectate.listen(lambda data: sensor_callback(data, sensor_queue, 4))\n sensor_list.append(cam_spectate)\n\n # Sensor listening\n print(\"Stage: listening to sensor\")\n while True:\n world.tick()\n try:\n ms, kmh = su.speed_estimation(vehicle)\n\n # speed of autopilot\n traffic_manager.global_percentage_speed_difference(0)\n\n degree = vehicle.get_transform().rotation.yaw\n rad = np.deg2rad(degree)\n\n location = vehicle.get_location()\n loc_x = location.x\n loc_y = location.y\n\n vehicle.set_autopilot(True)\n su.passing_trafficlight(vehicle)\n\n for _ in range(len(sensor_list)):\n s_frame = sensor_queue.get(True, 1.0)\n if s_frame[1] == 0:\n xz, yz = su.gnss_function(s_frame[0], gnss_list)\n elif s_frame[1] == 1:\n x, y = su.gnss_function(s_frame[0], gnss_list)\n elif s_frame[1] == 2:\n gyroscopez = su.imu_function(s_frame[0], imu_list)\n elif s_frame[1] == 3:\n gyroscope = su.imu_function(s_frame[0], imu_list)\n else:\n su.live_cam(s_frame[0], dic.cam_spectate_1)\n\n xTrue = [xz, yz, ms, rad]\n xDR = [x, y, ms, rad]\n zTrue = [xz, yz]\n z = [x, y]\n u = [ms, gyroscopez[2]]\n ud = [ms, gyroscope[2]]\n\n data2 = [loc_x, loc_y, gyroscope[2], gyroscopez[2], ms, rad]\n loc_data.append(data2)\n\n # Stopping key\n if keyboard.is_pressed(\"q\"):\n print(\"Simulation stopped\")\n break\n\n except Empty:\n print(\"- Some of the sensor information is missed\")\n\n finally:\n print(\"Finally...\")\n # Switch back to synchronous mode\n settings.synchronous_mode = False\n world.apply_settings(settings)\n to.export_csv(\"dataset_04.csv\", loc_data)\n\n try:\n # Destroying actors\n print(\"Destroying {} actor(s)\".format(len(actor_list)))\n client.apply_batch([carla.command.DestroyActor(x) for x in actor_list])\n\n except Exception as e:\n print(\"Final Exception: \", e)\n\n\ndef main():\n game_loop(reload=True, hp=True, cp=False)\n time.sleep(0.5)\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"localization/data_collection.py","file_name":"data_collection.py","file_ext":"py","file_size_in_byte":7044,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"634271616","text":"# Pull PMIDs from the GWAS downloads script so that\n# GWAS sumstats folders can be paired with the appropriate\n# files. This depends on the GWAS download script following\n# a few basic conventions:\n# - pmid listed before \"mkdir\" command in one of the formats described in this script\n# - folder specified using mkdir command\n#\n# PMID and mkdir command do not need to be directly adjacent, as long as they are not\n# separated by other PMID or mkdir lines.\n# \nwith open(\"gwas_pmids.txt\", \"w\") as w:\n w.write(\"study\\tpmid\\n\")\n with open(\"../gwas_downloads.sh\") as f:\n last_pmid = None\n for line in f:\n if \"/pubmed/\" in line:\n # Example lines\n # https://www.ncbi.nlm.nih.gov/pubmed/25231870\n # https://www.ncbi.nlm.nih.gov/pubmed/25282103?dopt=Citation\n # https://www.ncbi.nlm.nih.gov/pubmed/?term=28800628\n last_pmid = line.strip().split(\"/pubmed/\")[1].replace(\"?term=\", \"\").replace(\"?dopt=Citation\", \"\")\n if \"PMID\" in line:\n # Example line:\n # PMID: 22479202 PMCID: PMC3315470\n last_pmid = line.strip().split(\"PMID: \")[1].split()[0]\n if \"mkdir\" in line:\n # Example line:\n # mkdir -p Statin-Efficacy_Barber_2010\n study = line.strip().replace(\"-p\", \"\").split()[1]\n if not last_pmid is None:\n # We only associate one folder with each PMID. This avoids\n # false pairings but also will miss some folders if there\n # are more than one folder associated with same PMID. Need\n # to go back and fix this.\n w.write(\"{0}\\t{1}\\n\".format(study, last_pmid))\n last_pmid = None\n\n\n\n\n\n","sub_path":"download/annotations/get_pmids.py","file_name":"get_pmids.py","file_ext":"py","file_size_in_byte":1812,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"302172168","text":"#!/usr/bin/env python\n\nfrom load import ROOT as R\nfrom matplotlib import pyplot as P\nimport numpy as N\nfrom gna.env import env\nfrom gna.labelfmt import formatter as L\nfrom mpl_tools.helpers import savefig, plot_hist, add_colorbar\nfrom scipy.stats import norm\nfrom gna.converters import convert\nfrom argparse import ArgumentParser\nimport gna.constructors as C\nfrom gna.parameters.printer import print_parameters\n\nparser = ArgumentParser()\nparser.add_argument( '-o', '--output' )\nparser.add_argument( '-s', '--show', action='store_true' )\nopts = parser.parse_args()\n\ndef axes( title, ylabel='' ):\n fig = P.figure()\n ax = P.subplot( 111 )\n ax.minorticks_on()\n ax.grid()\n ax.set_xlabel( L.u('evis') )\n ax.set_ylabel( ylabel )\n ax.set_title( title )\n return ax\n\ndef singularities( values, edges ):\n indices = N.digitize( values, edges )-1\n phist = N.zeros( edges.size-1 )\n phist[indices] = 1.0\n return phist\n\n#\n# Define the parameters in the current namespace\n#\npercent = 0.01\nenv.defparameter( 'Eres_a', central=0.016, relsigma=30*percent )\nenv.defparameter( 'Eres_b', central=0.081, relsigma=30*percent )\nenv.defparameter( 'Eres_c', central=0.026, relsigma=30*percent )\nprint_parameters( env.globalns )\n\n#\n# Define bin edges\n#\nbinwidth=0.05\nedges = N.arange( 0.0, 12.0001, binwidth )\nefine = N.arange( edges[0], edges[-1]+1.e-5, 0.005 )\n\nfor eset in [\n [ [1.025], [3.025], [6.025], [9.025] ],\n [ [ 1.025, 5.025, 9.025 ] ],\n [ [ 6.025, 7.025, 8.025, 8.825 ] ],\n ]:\n ax = axes( 'Energy resolution impact' )\n for i, e in enumerate(eset):\n phist = singularities( e, edges )\n\n hist = C.Histogram( edges, phist )\n eres = R.EnergyResolutionC()\n eres.smear.Nrec( hist.hist )\n\n smeared = eres.smear.Nrec.data()\n print( 'Sum check for {} (diff): {}'.format( e, phist.sum()-smeared.sum() ) )\n\n # bars = P.bar( edges[:-1], phist, binwidth, align='edge' )\n lines = plot_hist( edges, smeared )\n color = lines[0].get_color()\n ax.vlines( e, 0.0, smeared.max(), linestyle='--', color=color )\n\n if len(e)>1:\n color='green'\n for e in e:\n ax.plot( efine, binwidth*norm.pdf( efine, loc=e, scale=eres.relativeSigma(e)*e ), linestyle='--', color=color )\n\n savefig( opts.output, suffix='_test_%i'%i )\n\nax = axes( 'Relative energy uncertainty', ylabel=L.u('eres_sigma_rel') )\nx = N.arange( 0.5, 12.0, 0.01 )\nfcn = N.frompyfunc( eres.relativeSigma, 1, 1 )\ny = fcn( x )\n\nax.plot( x, y*100. )\nsavefig( opts.output, suffix='_sigma' )\n\nfig = P.figure()\nax = P.subplot( 111 )\nax.minorticks_on()\nax.grid()\nax.set_xlabel( '' )\nax.set_ylabel( '' )\nax.set_title( 'Energy resolution convertsion matrix' )\n\nmat = convert(eres.getDenseMatrix(), 'matrix')\nmat = N.ma.array( mat, mask= mat==0.0 )\nc = ax.matshow( mat, extent=[ edges[0], edges[-1], edges[-1], edges[0] ] )\nadd_colorbar( c )\n\nsavefig( opts.output, suffix='_mat' )\n\nif opts.show:\n P.show()\n\n","sub_path":"tests/detector/test_eresc.py","file_name":"test_eresc.py","file_ext":"py","file_size_in_byte":2982,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"515997853","text":"import csv\nfrom classes.moveClass import *\n\nclass Pokemon:\n def __init__(self, pkmn, lv, ev, moves, isFainted, statChanges, statusConditions,\n isActive = False):\n pkmnAttributes = []\n file = \"classes/spreadsheets/pokemon.csv\"\n pkmnList = open(file)\n csvReader = csv.reader(pkmnList, delimiter = \",\")\n for line in csvReader:\n if line[0] == pkmn:\n pkmnAttributes = line\n break\n pkmnList.close()\n \n # ATTRIBUTES\n self.pkmnName = pkmn # str\n if pkmnAttributes[2] == \"\":\n self.pkmnType = [pkmnAttributes[1]]\n else:\n self.pkmnType = [pkmnAttributes[1]] + [pkmnAttributes[2]]\n self.baseStats = []\n for stat in range(3, 9):\n attr = int(pkmnAttributes[stat])\n self.baseStats.append(attr)\n self.ev = ev # [hp, atk, def, sp. atk, sp. def, spd] int (max 252 per stat, max 510 overall)\n self.moves = moves # [move1, move2, move3, move4] Move objects\n self.level = lv # int\n self.isFainted = isFainted\n self.statChanges = statChanges\n self.ppChanges = [0, 0, 0, 0]\n self.statusConditions = statusConditions # [burn, para, poison, sleep, freeze]\n self.isActive = isActive\n self.stagesDict = {-6: 0.25, -5: 0.28, -4: 0.33, -3: 0.2, -2: 0.5, -1: 0.66, 0: 1, 1: 1.5, 2: 2, 3: 2.5, 4: 3, 5: 3.5, 6: 4}\n \n def __repr__(self):\n return \"%s\" % self.pkmnName\n \n # change to active\n def activeTrue(self):\n self.isActive = True\n\n def activeFalse(self):\n self.isActive = False\n\n def getIsActive(self):\n return self.isActive\n\n # get pkmn name\n def getName(self):\n if self.pkmnName == \"Nidoran-F\":\n return \"Nidoran (F)\"\n elif self.pkmnName == \"Nidoran-M\":\n return \"Nidoran (M)\"\n return self.pkmnName\n\n # get pkmn type\n def getType(self):\n return self.pkmnType\n \n # get pkmn level\n def getLevel(self):\n return self.level\n\n # change pkmn level\n def changeLevel(self, newLvl):\n self.level = newLvl\n \n # get base stats\n def getBaseStats(self):\n return self.baseStats\n\n # get BATTLE pkmn stats (NOT base stats! these are dependent on level and EVs)\n # assume 31 IVs for each stat bc why would you do anything else\n # formulae retrieved from https://bulbapedia.bulbagarden.net/wiki/Statistic#In_Generation_III_onward\n def getBattleStats(self):\n iv = 31\n evDivisor = 4\n hpFormula = int((((2 * self.baseStats[0] + iv + self.ev[0]/evDivisor) * \\\n self.level) / 100) + self.level + 10)\n adjStats = [hpFormula]\n for stat in range(1, len(self.baseStats)): # atk, def, sp. atk, sp. def, spd\n base = int((((2 * self.baseStats[stat] + iv + \\\n self.ev[stat]/evDivisor) * self.level) / 100) + 5)\n formula = int(base * self.stagesDict[self.statChanges[stat]])\n adjStats.append(formula)\n return adjStats\n \n def changeMoves(self, index, move):\n self.moves[index] = move\n\n def changeEVs(self, index, ev):\n self.ev[index] = ev\n\n # get pkmn moves\n def getMoves(self):\n return self.moves\n\n def getMoveNames(self):\n moveNames = set()\n for move in self.moves:\n if move != None:\n moveNames.add(move.getMoveName())\n else:\n moveNames.add(None)\n return moveNames\n \n # use a move\n def useMove(self, usedMove):\n return \"%s used %s.\" % (self.pkmnName, usedMove)\n\n def changeToFainted(self):\n self.isFainted = True\n\n def changeNotFainted(self):\n self.isFainted = False\n\n # get is fainted\n def getIsFainted(self):\n return self.isFainted\n\n # get stat changes\n def getStatChanges(self):\n return self.statChanges\n\n def changeHP(self, amount):\n self.statChanges[0] += amount\n\n # change stats\n def changeStats(self, stat, stage):\n if stat == 0: # ATTACK\n self.statChanges[1] += stage\n elif stat == 1: # DEFENSE\n self.statChanges[2] += stage\n elif stat == 2: # SPECIAL ATTACK\n self.statChanges[3] += stage\n elif stat == 3: # SPECIAL DEFENSE\n self.statChanges[4] += stage\n elif stat == 4: # SPEED\n self.statChanges[5] += stage\n elif stat == 5: # ACCURACY\n self.statChanges[6] += stage\n elif stat == 6: # EVASION\n self.statChanges[7] += stage\n\n def getPPChanges(self):\n return self.ppChanges\n\n # reset stats\n def resetStatConds(self):\n self.statChanges = [0, 0, 0, 0, 0, 0, 0, 0]\n self.statusConditions = [False, False, False, False, False]\n\n # get status: [burn, para, poison, sleep, freeze]\n def getConditions(self):\n return self.statusConditions\n\n def changeConditions(self, cond):\n if cond == 0:\n self.statusConditions[0] = True\n elif cond == 1:\n self.statusConditions[1] = True\n elif cond == 2:\n self.statusConditions[2] = True\n elif cond == 3:\n self.statusConditions[3] = True\n elif cond == 4:\n self.statusConditions[4] = True\n\n def changeConditionsFalse(self, cond):\n if cond == 0:\n self.statusConditions[0] = False\n elif cond == 1:\n self.statusConditions[1] = False\n elif cond == 2:\n self.statusConditions[2] = False\n elif cond == 3:\n self.statusConditions[3] = False\n elif cond == 4:\n self.statusConditions[4] = False","sub_path":"classes/pokemonClass.py","file_name":"pokemonClass.py","file_ext":"py","file_size_in_byte":5740,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"141459648","text":"#!/usr/bin/env python3\r\n'''animal_file_generator.py\r\n\r\nA script designed for batch prosessing with a 'for' loop.\r\n\r\nWritten by Seppo Karvinen on 25.09.2016 [DDMMYYYY]\r\nwith some peer support by Hanna.\r\n\r\nUsage: ./animal_file_generator.py\r\n'''\r\n\r\nbasename = 'Animal'\r\nfilenames = ''\r\n\r\nfor i in range(31):\r\n print (basename + '_' + str(i))\r\n \r\nfor i in range(31):\r\n filenames = (basename + '_' + str(i) + '.shp')\r\n print (filenames)","sub_path":"animal_file_generator.py","file_name":"animal_file_generator.py","file_ext":"py","file_size_in_byte":443,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"652265647","text":"from setuptools import setup, find_packages\n\n\ninstall_required = [l.strip() for l in open('requestments.txt', 'r')]\n\n\nmetadata = {\n 'name': '',\n 'version': '0.1',\n 'packages': find_packages(),\n 'author': 'shonenada',\n 'author_email': 'shonenada@gmail.com',\n 'install_requires': install_required,\n}\n\nsetup(**metadata)\n","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":335,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"570243469","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import migrations, models\nfrom django.conf import settings\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n migrations.swappable_dependency(settings.AUTH_USER_MODEL),\n ]\n\n operations = [\n migrations.CreateModel(\n name='BaseModel',\n fields=[\n ('id', models.AutoField(primary_key=True, verbose_name='ID', serialize=False, auto_created=True)),\n ('last_updated', models.DateTimeField(auto_now_add=True)),\n ('created', models.DateTimeField()),\n ],\n ),\n migrations.CreateModel(\n name='Address',\n fields=[\n ('basemodel_ptr', models.OneToOneField(to='api.BaseModel', primary_key=True, parent_link=True, serialize=False, auto_created=True)),\n ('address_name', models.CharField(max_length=50)),\n ('street', models.CharField(blank=True, null=True, max_length=150)),\n ('line_2', models.CharField(blank=True, null=True, max_length=150)),\n ('city', models.CharField(max_length=100)),\n ('state', models.CharField(max_length=100)),\n ('zip_code', models.CharField(blank=True, null=True, max_length=15)),\n ],\n bases=('api.basemodel',),\n ),\n migrations.CreateModel(\n name='Certification',\n fields=[\n ('basemodel_ptr', models.OneToOneField(to='api.BaseModel', primary_key=True, parent_link=True, serialize=False, auto_created=True)),\n ('name', models.CharField(max_length=150)),\n ('date_earned', models.DateField(null=True)),\n ],\n bases=('api.basemodel',),\n ),\n migrations.CreateModel(\n name='Company',\n fields=[\n ('basemodel_ptr', models.OneToOneField(to='api.BaseModel', primary_key=True, parent_link=True, serialize=False, auto_created=True)),\n ('name', models.CharField(max_length=150)),\n ('title', models.CharField(blank=True, null=True, max_length=150)),\n ('position', models.CharField(blank=True, null=True, max_length=150)),\n ('from_date', models.DateField()),\n ('to_date', models.DateField(null=True)),\n ('address', models.OneToOneField(to='api.Address')),\n ],\n bases=('api.basemodel',),\n ),\n migrations.CreateModel(\n name='Email',\n fields=[\n ('basemodel_ptr', models.OneToOneField(to='api.BaseModel', primary_key=True, parent_link=True, serialize=False, auto_created=True)),\n ('email', models.CharField(max_length=150)),\n ],\n bases=('api.basemodel',),\n ),\n migrations.CreateModel(\n name='Headline',\n fields=[\n ('basemodel_ptr', models.OneToOneField(to='api.BaseModel', primary_key=True, parent_link=True, serialize=False, auto_created=True)),\n ('description', models.CharField(max_length=250)),\n ],\n bases=('api.basemodel',),\n ),\n migrations.CreateModel(\n name='Profile',\n fields=[\n ('basemodel_ptr', models.OneToOneField(to='api.BaseModel', primary_key=True, parent_link=True, serialize=False, auto_created=True)),\n ('home_phone', models.CharField(blank=True, null=True, max_length=15)),\n ('mobile_phone', models.CharField(blank=True, null=True, max_length=15)),\n ('business_phone', models.CharField(blank=True, null=True, max_length=15)),\n ('fax', models.CharField(blank=True, null=True, max_length=15)),\n ('url', models.CharField(blank=True, null=True, max_length=150)),\n ('addresses', models.ManyToManyField(to='api.Address')),\n ('emails', models.ManyToManyField(to='api.Email')),\n ],\n bases=('api.basemodel',),\n ),\n migrations.CreateModel(\n name='Project',\n fields=[\n ('basemodel_ptr', models.OneToOneField(to='api.BaseModel', primary_key=True, parent_link=True, serialize=False, auto_created=True)),\n ('description', models.TextField()),\n ],\n bases=('api.basemodel',),\n ),\n migrations.CreateModel(\n name='Resume',\n fields=[\n ('basemodel_ptr', models.OneToOneField(to='api.BaseModel', primary_key=True, parent_link=True, serialize=False, auto_created=True)),\n ('objective', models.CharField(blank=True, null=True, max_length=300)),\n ('address', models.ForeignKey(to='api.Address')),\n ('companies', models.ManyToManyField(to='api.Company')),\n ('email', models.ForeignKey(to='api.Email')),\n ('headlines', models.ManyToManyField(to='api.Headline', null=True)),\n ('profile', models.ForeignKey(to='api.Profile')),\n ],\n bases=('api.basemodel',),\n ),\n migrations.CreateModel(\n name='School',\n fields=[\n ('basemodel_ptr', models.OneToOneField(to='api.BaseModel', primary_key=True, parent_link=True, serialize=False, auto_created=True)),\n ('name', models.CharField(max_length=150)),\n ('program', models.CharField(blank=True, null=True, max_length=150)),\n ('degree', models.CharField(blank=True, null=True, max_length=150)),\n ('gpa', models.CharField(blank=True, null=True, max_length=5)),\n ('from_date', models.DateField()),\n ('to_date', models.DateField(null=True)),\n ('address', models.OneToOneField(to='api.Address')),\n ('projects', models.ManyToManyField(to='api.Project', null=True)),\n ],\n bases=('api.basemodel',),\n ),\n migrations.CreateModel(\n name='Skill',\n fields=[\n ('basemodel_ptr', models.OneToOneField(to='api.BaseModel', primary_key=True, parent_link=True, serialize=False, auto_created=True)),\n ('name', models.CharField(max_length=150)),\n ('level', models.IntegerField(default=5)),\n ('years_experience', models.IntegerField(default=0)),\n ],\n bases=('api.basemodel',),\n ),\n migrations.CreateModel(\n name='Tag',\n fields=[\n ('basemodel_ptr', models.OneToOneField(to='api.BaseModel', primary_key=True, parent_link=True, serialize=False, auto_created=True)),\n ('name', models.CharField(max_length=100)),\n ],\n bases=('api.basemodel',),\n ),\n migrations.AddField(\n model_name='basemodel',\n name='user',\n field=models.ForeignKey(to=settings.AUTH_USER_MODEL),\n ),\n migrations.AddField(\n model_name='skill',\n name='tag',\n field=models.OneToOneField(to='api.Tag', null=True),\n ),\n migrations.AddField(\n model_name='resume',\n name='schools',\n field=models.ManyToManyField(to='api.School'),\n ),\n migrations.AddField(\n model_name='resume',\n name='skills',\n field=models.ManyToManyField(to='api.Skill'),\n ),\n migrations.AddField(\n model_name='project',\n name='tag',\n field=models.OneToOneField(to='api.Tag', null=True),\n ),\n migrations.AddField(\n model_name='headline',\n name='tag',\n field=models.OneToOneField(to='api.Tag', null=True),\n ),\n migrations.AddField(\n model_name='company',\n name='projects',\n field=models.ManyToManyField(to='api.Project', null=True),\n ),\n ]\n","sub_path":"api/migrations/0001_initial.py","file_name":"0001_initial.py","file_ext":"py","file_size_in_byte":8022,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"345300858","text":"import matplotlib.pyplot as plt\nimport numpy as np\n\nimport torch\nimport torch.optim as optim\nimport torch.nn as nn\nimport torch.nn.functional as F\n\nimport os.path\nimport sys, time, math\n\nfrom torch.autograd import Variable\nfrom torch.utils.data import DataLoader\nfrom torchvision import datasets, transforms\nfrom dataset import SoundDataset\n\n# import torchvision.models as torchvision_models\n\n# from networks import smallNet, vgg9, VGG9_idx, vgg11, VGG11_idx, vgg19, VGG19_idx\nfrom signal_networks import VGG11_idx\ndef time_since(since):\n s = time.time() - since\n m = math.floor(s / 60)\n s -= m * 60\n return '%dm %ds' % (m, s)\n\ndef visualize_weights(weights):\n values = weights.data.numpy()\n plt.imshow(values)\n plt.show()\n\ndef train(epoch, print_every):\n all_losses = []\n sum_loss_training = 0.0\n criterion = nn.CrossEntropyLoss()\n start = time.time()\n\n model.train() # set the model in \"training mode\"\n\n for batch_idx, (data, target) in enumerate(train_loader):\n\n # Add dimension for depth\n data = data.reshape(data.shape[0], 1, data.shape[1], data.shape[2])\n data, target = data.to(device), target.to(device)\n\n # Zero gradients\n optimizer.zero_grad()\n\n # Make prediction\n output = model(data)#.unsqueeze_(0))\n\n # Calculate loss\n loss = criterion(output, target)\n all_losses.append(loss)\n sum_loss_training += loss.item()\n\n # Backpropagation\n loss.backward()\n\n optimizer.step()\n if batch_idx % print_every == 0:\n print('[%s Batch: (%d %d%%) Loss: %.4f]' % (time_since(start), batch_idx, batch_idx / len(train_loader) * 100, loss))\n\n # Saves losses over time\n f= open('../data/losses/' + \"all_train_losses_\" + model.mname + \".txt\",\"a\")\n\n for i in range(len(all_losses)):\n f.write(str(all_losses[i].detach().cpu().numpy()) + ',')\n\n f.write(\"\\n\")\n\n print(\"\\nAverage training loss: %.4f\" % sum_loss_training)\n\ndef test(epoch):\n model.eval() # set the model in \"testing mode\"\n\n all_losses = []\n\n test_loss = 0\n correct = 0\n criterion = nn.CrossEntropyLoss()\n\n # Do not update model during test\n with torch.no_grad():\n for data, target in test_loader:\n\n # Add dimension for depth\n data = data.reshape(data.shape[0], 1, data.shape[1], data.shape[2])\n data, target = data.to(device), target.to(device)\n\n output = model(data)\n\n test_loss += criterion(output, target).data #fsize_average=False to sum, instead of average losses\n pred = output.data.max(1, keepdim=True)[1]\n correct+= pred.eq(target.data.view_as(pred)).cpu().sum() # to operate on variables they need to be on the CPU again\n\n test_dat_len = len(test_loader.dataset)\n test_loss /= test_dat_len\n accuracy = 100. * correct / test_dat_len\n\n # print the test accuracy\n print('\\nTest set: Average loss: {:.4f}, Accuracy: {}/{} ({:.2f}%)\\n'.format(\n test_loss, correct, test_dat_len, accuracy))\n\n # Saves losses over time\n\n f = open('../data/losses/' + \"all_test_losses_\" + model.mname + \".txt\",\"a\")\n\n f.write(str(test_loss.detach().cpu().numpy()))\n f.write(\"\\n\")\n\n # Save accuracies\n\n f = open('../data/losses/' + \"accuracies_\" + model.mname + \".txt\",\"a\")\n f.write(str(accuracy.detach().cpu().numpy()))\n f.write(\"\\n\")\n\nif __name__ == '__main__':\n model_name = sys.argv[1] # VGG11_idx\n dataset_name = sys.argv[2] # 5class1000\n learning_rate = sys.argv[3]\n momentum = sys.argv[4]\n weight_decay = sys.argv[5]\n n_epochs = sys.argv[6] # amount of epochs we'll train in one job (1 2 or 5 or so)\n m_epochs = sys.argv[7] # amount of epochs we'll train in total (100 or 1000?)\n s_epoch = sys.argv[8] # epoch whose pkl we need to load in. We pick up here; where we left off\n # a call to this file might look like:\n # srun --gres=gpu:1 -p fatq python -u train_epochs.py VGG11_idx 5_class_1000 0.0001 0.9 0.05 2 100 32\n # make a bash script that looks like so\n\n device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n\n # Setup network\n assert model_name == \"VGG11_idx_renamed\", \"you're loading something with a different name than how you'll save it\"\n model = VGG11_idx(num_classes=5, init_weights=True).to(device)\n\n model.mname = model_name+\"_\"+dataset_name+\"_adam_lr\"+learning_rate+\"_mom\"+momentum+\"_wd\"+weight_decay+\"_mxepch\"+m_epochs\n loadname = model.mname+\"_epoch\"+s_epoch+\".pkl\"\n end_epoch = int(s_epoch) + int(n_epochs) # get epochs\n savename = loadname.replace(\"epoch\" + s_epoch + \".pkl\", \"epoch\" + str(end_epoch) + \".pkl\") # replace with current epoch + .pkl\n\n if int(s_epoch) == 0:\n # Reset loss files\n f = open('../data/losses/' + \"all_test_losses_\" + model.mname + \".txt\",\"w\")\n f.write(\"\")\n f = open('../data/losses/' + \"all_train_losses_\" + model.mname + \".txt\",\"w\")\n f.write(\"\")\n f = open('../data/losses/' + \"accuracies_\" + model.mname + \".txt\",\"w\")\n f.write(\"\")\n\n # # Set starting epoch, change if\n # s_epoch = 1\n\n weightdir = '/var/scratch/prai1811/data/models/'\n\n # Load weights if they exist\n if os.path.exists(weightdir+loadname):\n model.load_state_dict(torch.load(weightdir+loadname))\n print('Loaded model: %s' % (loadname))\n # model.load_state_dict(torch.load(loadname))\n\n # Select optimizer\n optimizer = optim.Adam(model.parameters(), lr=float(learning_rate), weight_decay=float(weight_decay))\n\n # Load data\n batch_size = 8\n\n train_dataset = SoundDataset('/var/scratch/prai1811/data/spectrograms/'+dataset_name+'/train/', '../data/dictionaries/'+dataset_name+'.pkl')\n val_dataset = SoundDataset('/var/scratch/prai1811/data/spectrograms/'+dataset_name+'/val/', '../data/dictionaries/'+dataset_name+'.pkl')\n # val instead of test?!\n\n # train_dataset = SoundDataset('../data/spectrograms/'+dataset_name+'/train/', '../data/dictionaries/'+dataset_name+'.pkl')\n # val_dataset = SoundDataset('../data/spectrograms/'+dataset_name+'/test/', '../data/dictionaries/'+dataset_name+'.pkl')\n\n # batch the data for the training and test datasets\n train_loader = DataLoader(dataset=train_dataset, batch_size=batch_size, shuffle=True)\n test_loader = DataLoader(dataset=val_dataset, batch_size=batch_size, shuffle=True)\n\n print(len(train_dataset.spectrograms), 'train samples')\n print(len(val_dataset.spectrograms), 'test samples\\n')\n\n for epoch in range(int(s_epoch), end_epoch):\n\n train(epoch, print_every=5)\n test(epoch)\n print(\"------------\")\n\n torch.save(model.state_dict(), weightdir+savename)\n print(\"Model saved: %s\" % (savename))\n","sub_path":"src/old/train_epochs0.py","file_name":"train_epochs0.py","file_ext":"py","file_size_in_byte":6746,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"395717703","text":"# -*- coding: utf-8 -*- \r\nclass Pager(object):\r\n \r\n list = None\r\n total = 0 # 总数\r\n limit = 4 # 每页条目\r\n pages = 1 # 总页数\r\n pageNumber = 1 # 当前页\r\n \r\n navigatePages = 5\r\n navigatePageNumbers = []\r\n \r\n isFirstPage = False; # 是否为第一页\r\n isLastPage = False; # 是否为最后一页\r\n hasPreviousPage = False; # 是否有前一页\r\n hasNextPage = False; # 是否有下一页\r\n \r\n def __init__(self, pageNumber, total, limit):\r\n self.navigatePageNumbers = []\r\n \r\n self.total = total\r\n self.limit = limit\r\n \r\n self.pages = (self.total - 1) / self.limit + 1;\r\n \r\n self.pageNumber = pageNumber\r\n self.calcNavigatePageNumbers()\r\n self.judgePageBoudary()\r\n \r\n def calcNavigatePageNumbers(self):\r\n # 当总页数小于或等于导航页码数时\r\n if self.pages <= self.navigatePages:\r\n for i in range(0, self.pages):\r\n self.navigatePageNumbers.append(i + 1)\r\n # 当总页数大于导航页码数时\r\n else :\r\n startNum = self.pageNumber - self.navigatePages / 2\r\n endNum = self.pageNumber + self.navigatePages / 2\r\n# print 'startNum:' + str(startNum)\r\n# print 'endNum:' + str(endNum)\r\n if startNum < 1:\r\n startNum = 1\r\n # (最前navigatePages页\r\n for i in range(0, self.navigatePages):\r\n self.navigatePageNumbers.append(startNum)\r\n startNum += 1\r\n elif endNum > self.pages:\r\n endNum = self.pages\r\n # 最后navigatePages页\r\n for i in range(0,self.navigatePages):\r\n self.navigatePageNumbers.append((endNum-i));\r\n self.navigatePageNumbers.reverse()\r\n else:\r\n # 所有中间页\r\n for i in range(0, self.navigatePages):\r\n self.navigatePageNumbers.append(startNum)\r\n startNum += 1\r\n\r\n def judgePageBoudary(self):\r\n self.isFirstPage = self.pageNumber == 1;\r\n self.isLastPage = self.pageNumber == self.pages & self.pageNumber != 1;\r\n self.hasPreviousPage = self.pageNumber > 1;\r\n self.hasNextPage = self.pageNumber < self.pages;\r\n\r\n# test \r\n# p = Pager(pageNumber=1, total=19, limit=4)\r\n# print p.navigatePageNumbers","sub_path":"pager.py","file_name":"pager.py","file_ext":"py","file_size_in_byte":2608,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"39065966","text":"#Slide and Pin Joint Demo\n\nimport pymunk\n\ndef add_ball(space):\n mass = 1\n radius = 14\n moment = pymunk.moment_for_circle(mass, 0, radius) # 1\n body = pymunk.Body(mass, moment) # 2\n x = random.randint(120, 380)\n body.position = x, 550 # 3\n shape = pymunk.Circle(body, radius) # 4\n space.add(body, shape) # 5\n return shape\n","sub_path":"Slide-PintJoint.py","file_name":"Slide-PintJoint.py","file_ext":"py","file_size_in_byte":348,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"522354736","text":"from tensorflow.keras.models import Sequential\nfrom tensorflow.keras.layers import Dense, LSTM, RepeatVector, TimeDistributed, Conv1D, Flatten, MaxPooling1D\nfrom tensorflow import keras\nfrom tensorflow.keras.utils import plot_model\nimport keras as K\n\nclass CNN_LSTM_Autoencoder:\n def __init__(self, X_train, y_train, X_test, y_test):\n self.model = self.create_model()\n\n @staticmethod\n def create_model(time_window_size=30, n_features=1):\n model_CNNLSTM = Sequential()\n model_CNNLSTM.add(Conv1D(filters=64, kernel_size=1, activation='relu', input_shape=(time_window_size, n_features)))\n model_CNNLSTM.add((MaxPooling1D(pool_size=2)))\n model_CNNLSTM.add(Flatten())\n model_CNNLSTM.add(RepeatVector(time_window_size))\n model_CNNLSTM.add(TimeDistributed(Dense(n_features, activation=\"linear\")))\n model_CNNLSTM.summary()\n plot_model(model_CNNLSTM, to_file=\"/home/takara/Desktop/Masters/BR_Conference/images/CNN.png\", show_shapes=True, show_layer_names=True)\n model_CNNLSTM.compile(optimizer='adam', loss=\"MAPE\")\n\n\n return model_CNNLSTM\n\n def train(self, X_train, y_train, epochs=60, batch_size=32, validation_split=0.1, shuffle=False):\n history = self.model.fit(x=X_train, y=y_train, epochs=epochs, batch_size=batch_size,\n validation_split=validation_split, shuffle=shuffle)\n return history\n\n def predict(self, X_train):\n X_train_pred = self.model.predict(X_train)\n return X_train_pred\n\n def evaluate(self, X_test, y_test):\n mae = self.model.evaluate(X_test, y_test)\n return mae\n","sub_path":"models_architecture/CNNLSTM_Autoencoder.py","file_name":"CNNLSTM_Autoencoder.py","file_ext":"py","file_size_in_byte":1643,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"638052675","text":"#\n# Unregister info is for installers or external uninstallers.\n# The WISE installer, for example firstly registers the COM server,\n# then queries for the Unregister info, appending it to its\n# install log. Uninstalling the package will the uninstall the server\ndef UnregisterInfoClasses(*classes, **flags):\n ret = []\n for cls in classes:\n clsid = cls._reg_clsid_\n progID = _get(cls, '_reg_progid_')\n verProgID = _get(cls, '_reg_verprogid_')\n customKeys = _get(cls, '_reg_remove_keys_')\n ret = ret + GetUnregisterServerKeys(clsid, progID, verProgID, customKeys)\n return ret\n","sub_path":"test_segment_base/register_0.py","file_name":"register_0.py","file_ext":"py","file_size_in_byte":593,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"42173569","text":"from flask import Flask, render_template\napp = Flask(__name__)\n\n@app.route('/')\ndef home_page():\n\tfav_players = [\"Leonil Messi\",\"Waseem Lawen\",\"Laith Husseini\"]\n\treturn render_template(\"index.html\", players=fav_players, likes_same_sport=True)\n\t\n\nif __name__ == '__main__':\n app.run(debug = True)","sub_path":"exercises/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":297,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"591560039","text":"from datetime import datetime\nfrom typing import List\n\nfrom bson.objectid import ObjectId\n\nfrom finance_telebot.entity import Transaction\n\n\nclass TransactionError(Exception):\n pass\n\n\nclass TransationFilter:\n def __init__(self):\n self.a = ''\n self.b = ''\n\n\nclass TransactionRepository:\n col_name = 'transactions'\n\n def __init__(self, db: dict):\n self._table = db[self.col_name]\n\n def get(self, tid: str) -> Transaction:\n trx = self._table.find_one({'_id': tid})\n if not trx:\n raise TransactionError('Transaction not found')\n tr = Transaction.from_json(trx)\n return tr\n\n def find(self, filter: TransationFilter) -> List[Transaction]:\n return [Transaction.from_json({})]\n\n def save(self, trx: Transaction):\n now = datetime.now()\n trx.id = str(ObjectId())\n trx.created_at = now\n trx.updated_at = now\n try:\n self._table.insert_one(trx.as_json)\n except Exception as e:\n raise TransactionError(e)\n\n def update(self, trx: Transaction):\n now = datetime.now()\n trx.updated_at = now\n try:\n res = self._table.update_one(\n {'_id': trx.id},\n {'$set': trx.as_json}\n )\n except Exception as e:\n raise TransactionError(e)\n\n if res.modified_count != 1:\n raise TransactionError('Transaction not updated')\n","sub_path":"finance_telebot/repository/transaction.py","file_name":"transaction.py","file_ext":"py","file_size_in_byte":1449,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"37701083","text":"from Monte_Carlo_Value_Estimation.Grid import Grid\n\n\nclass Agent(object):\n def __init__(self, numRows, numColumns, listOfTStates, discountFactor, Policy, transitionProb, numEpisodes):\n self.numRows = numRows\n self.numColumns = numColumns\n self.numEpisodes = numEpisodes\n self.listOfTStates = listOfTStates\n self.discountFactor = discountFactor\n self.Policy = Policy\n self.transitionProb = transitionProb\n self.totalReturn = []\n self.numStateVisit = []\n self.avgValue = []\n\n\n def initializePlay(self):\n self.totalReturn = [[0 for i in range(self.numColumns)] for j in range(self.numRows)]\n self.numStateVisit = [[0 for i in range(self.numColumns)] for j in range(self.numRows)]\n self.avgValue = [[0 for i in range(self.numColumns)] for j in range(self.numRows)]\n\n def addMatrix(self, matrixA, matrixB):\n rows = len(matrixA)\n columns = len(matrixA[0])\n sum = [[0 for i in range(columns)] for j in range(rows)]\n for i in range(rows):\n for j in range(columns):\n sum[i][j] = matrixA[i][j] + matrixB[i][j]\n\n return sum\n\n def playFirstVisit(self):\n self.initializePlay()\n for i in range(self.numEpisodes):\n grid = Grid(self.numRows, self.numColumns, self.listOfTStates, self.discountFactor, self.Policy,\n self.transitionProb)\n result = grid.createEpisodeFirstVisit()\n self.totalReturn = self.addMatrix(self.totalReturn, result[0])\n self.numStateVisit = self.addMatrix(self.numStateVisit, result[1])\n\n for i in range(self.numRows):\n for j in range(self.numColumns):\n if self.numStateVisit[i][j] != 0:\n self.avgValue[i][j] = self.totalReturn[i][j] / self.numStateVisit[i][j]\n\n return self.avgValue\n\n def playEveryVisit(self):\n self.initializePlay()\n for i in range(self.numEpisodes):\n grid = Grid(self.numRows, self.numColumns, self.listOfTStates, self.discountFactor, self.Policy,\n self.transitionProb)\n result = grid.createEpisodeEveryVisit()\n self.totalReturn = self.addMatrix(self.totalReturn, result[0])\n self.numStateVisit = self.addMatrix(self.numStateVisit, result[1])\n\n for i in range(self.numRows):\n for j in range(self.numColumns):\n if self.numStateVisit[i][j] != 0:\n self.avgValue[i][j] = self.totalReturn[i][j] / self.numStateVisit[i][j]\n\n return self.avgValue\n\n\ndef main():\n numRows = 4\n numColumns = 4\n terminalStates = [[0, 0], [3, 3]]\n discountFactor = 1\n policyFileName = \"Policy\"\n transitionProbabilities = [0.7, 0.1, 0.1, 0.1]\n numIterations = 4\n\n agent = Agent(numRows, numColumns, terminalStates, discountFactor, policyFileName, transitionProbabilities,\n numIterations)\n print(agent.playFirstVisit())\n print(agent.playEveryVisit())\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"src/Monte_Carlo_Value_Estimation/Agent.py","file_name":"Agent.py","file_ext":"py","file_size_in_byte":3079,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"67726620","text":"\"\"\"empty message\n\nRevision ID: bef45169c904\nRevises: f1318346a431\nCreate Date: 2016-01-30 16:53:34.058084\n\n\"\"\"\n\n# revision identifiers, used by Alembic.\nrevision = 'bef45169c904'\ndown_revision = 'f1318346a431'\n\nfrom alembic import op\nimport sqlalchemy as sa\nfrom sqlalchemy.dialects import mysql\n\ndef upgrade():\n ### commands auto generated by Alembic - please adjust! ###\n op.create_table('user_table',\n sa.Column('id', sa.Integer(), nullable=False),\n sa.Column('date_created', sa.DateTime(), nullable=True),\n sa.Column('date_modified', sa.DateTime(), nullable=True),\n sa.Column('user_id', sa.String(length=30), nullable=True),\n sa.Column('user_pw', sa.String(length=255), nullable=True),\n sa.Column('permission', sa.SMALLINT(), nullable=True),\n sa.PrimaryKeyConstraint('id')\n )\n op.drop_table('t_gdg_help_desk')\n ### end Alembic commands ###\n\n\ndef downgrade():\n ### commands auto generated by Alembic - please adjust! ###\n op.create_table('t_gdg_help_desk',\n sa.Column('id', mysql.INTEGER(display_width=11), nullable=False),\n sa.Column('date_created', mysql.DATETIME(), nullable=True),\n sa.Column('date_modified', mysql.DATETIME(), nullable=True),\n sa.Column('help_title', mysql.VARCHAR(length=200), nullable=True),\n sa.Column('help_content', mysql.TEXT(), nullable=True),\n sa.Column('author_address', mysql.VARCHAR(length=15), nullable=True),\n sa.PrimaryKeyConstraint('id'),\n mysql_default_charset='utf8',\n mysql_engine='InnoDB'\n )\n op.drop_table('user_table')\n ### end Alembic commands ###\n","sub_path":"migrations/versions/bef45169c904_.py","file_name":"bef45169c904_.py","file_ext":"py","file_size_in_byte":1572,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"66049434","text":"#!/usr/bin/python3\r\n\r\nimport tkinter\r\n\r\ndef destroyChild(widget):\r\n for child in widget.winfo_children(): child.destroy()\r\n\r\nclass Condition():\r\n def __init__(self, function, message):\r\n self.function = function\r\n self.message = message\r\n\r\nclass Widget():\r\n gridLen = 0\r\n widgets = []\r\n def __init__(self, name, path, *childs, **kwargs):\r\n self.id = len(self.widgets)\r\n self.widgets += [self]\r\n self.name = name\r\n self.path = path\r\n self.childs = childs\r\n self.conditions = kwargs.get(\"conditions\", [])\r\n self.description = kwargs.get(\"description\", \"\")\r\nclass Label(str): gridLen = 1\r\nclass View(Widget): gridLen = 1\r\nclass Entry(Widget): gridLen = 2\r\nclass Text(Widget): gridLen = 2\r\n\r\nclass TKFrame(tkinter.Frame):\r\n\r\n def back(self):\r\n if len(self.viewStack) > 1: self.viewStack = self.viewStack[:-1]\r\n self.update()\r\n\r\n def changeView(self, view):\r\n self.viewStack += [view]\r\n self.update()\r\n\r\n def getChildPath(self, child):\r\n return sum([view.path for view in self.viewStack] + [child.path], [])\r\n\r\n def savePage(self):\r\n for widget, getMethod in self.savable:\r\n for condition in widget.conditions:\r\n if not condition.function(getMethod()):\r\n text = \"'{}' got an error : {}\".format(widget.name, condition.message)\r\n self.errorLabel.config(text=text)\r\n return\r\n self.errorLabel.config(text=\"\")\r\n for widget, getMethod in self.savable:\r\n self.database.set(getMethod(), *self.getChildPath(widget))\r\n\r\n def setView(self):\r\n destroyChild(self)\r\n self.savable = []\r\n pathFrame = tkinter.Frame(self)\r\n canBack = len(self.viewStack) > 1\r\n back = tkinter.Button(pathFrame, text=\"<==\", font=('Courrier', 12, 'bold' if canBack else ''),\r\n state=\"normal\" if canBack else \"disabled\", command=self.back)\r\n back.grid(row=0, column=0)\r\n label = tkinter.Label(pathFrame, text=\" / \".join(view.name for view in self.viewStack),\r\n font=('Courrier', 12))\r\n label.grid(row=0, column=1, padx=20)\r\n view = self.viewStack[-1]\r\n titleFrame = tkinter.Frame(self)\r\n font = ('Courrier', 12, 'bold')\r\n textFont = ('Courrier', 12)\r\n titleFont = ('Courrier', 20, 'bold')\r\n save = tkinter.Button(titleFrame, text=\"Save\", font=textFont, command=self.savePage)\r\n save.pack(side=tkinter.RIGHT, padx=30)\r\n tkinter.Label(titleFrame, text=view.name, font=titleFont).pack()\r\n childFrame = None\r\n childFrameType = Widget\r\n pathFrame.pack(anchor=tkinter.W)\r\n titleFrame.pack(pady=30)\r\n self.errorLabel = tkinter.Label(self, font=font, fg=\"red\")\r\n self.errorLabel.pack(pady=30)\r\n row=0\r\n for child in view.childs:\r\n if type(child).gridLen != childFrameType.gridLen:\r\n childFrame = tkinter.Frame(self)\r\n childFrame.pack()\r\n childFrameType = type(child)\r\n if type(child) == Label:\r\n for line in child.split('\\n'):\r\n tkinter.Label(childFrame, text=line, font=font).grid(row=row, column=1, pady=10)\r\n row+=1\r\n elif type(child) == Entry:\r\n tkinter.Label(childFrame, text=child.name + ' :', font=font).grid(row=row, column=0, pady=10)\r\n entry = tkinter.Entry(childFrame, font=textFont, width=40)\r\n text = self.database.get(*self.getChildPath(child), allowNone=True)\r\n if text: entry.insert(tkinter.END, text)\r\n entry.grid(row=row, column=1, pady=10)\r\n self.savable += [(child, lambda entry=entry: entry.get())]\r\n row+=1\r\n elif type(child) == Text:\r\n tkinter.Label(childFrame, text=child.name + ' :', font=font).grid(row=row, column=0, pady=10)\r\n entry = tkinter.Text(childFrame, font=textFont, width=40, height=5)\r\n text = self.database.get(*self.getChildPath(child), allowNone=True)\r\n if text: entry.insert(tkinter.END, text)\r\n entry.grid(row=row, column=1, pady=10)\r\n self.savable += [(child, lambda entry=entry: entry.get(\"1.0\", tkinter.END))]\r\n row+=1\r\n elif type(child) == View:\r\n btn = tkinter.Button(childFrame, text=child.name, font=textFont,\r\n command=lambda child=child: self.changeView(child))\r\n btn.bind(\"\", lambda event, btn=btn: btn.invoke())\r\n btn.grid(row=row, column=1, pady=10)\r\n row+=1\r\n for line in view.description.split('\\n')[::-1]:\r\n tkinter.Label(self, text=line, font=('Courrier', 12, 'italic')).pack(side=tkinter.BOTTOM)\r\n self.savePage()\r\n\r\n def update(self):\r\n self.setView()\r\n super().update()\r\n\r\n def __init__(self, master, database, view, *args, **kwargs):\r\n super().__init__(master, *args, **kwargs)\r\n self.database = database\r\n self.viewStack = [view]\r\n self.setView()\r\n","sub_path":"BunnyLib/Database/GUI.py","file_name":"GUI.py","file_ext":"py","file_size_in_byte":5279,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"472783999","text":"from connections.connectionFactory import ConnectionFactory\n\nclass CurriculoDAO:\n\n def __init__(self, candidato_id = None, curriculo_id = None):\n self.candidato_id = candidato_id\n self.curriculo_id = curriculo_id\n\n def remover_idiomas(self):\n query = f'DELETE FROM curriculo_idioma WHERE curriculo_id = {self.curriculo_id}'\n ConnectionFactory.execute(query)\n \n\n def remover_experiencias_anteriores(self):\n query = f'DELETE FROM curriculo_experiencia WHERE curriculo_id = {self.curriculo_id}'\n ConnectionFactory.execute(query)\n\n def remover_curso_extra_curricular(self):\n query = f'DELETE FROM curriculo_curso_extracurricular WHERE curriculo_id = {self.curriculo_id}'\n ConnectionFactory.execute(query)\n\n def remover_endereco(self):\n query = f'DELETE FROM curriculo_idioma WHERE curriculo_id = {self.curriculo_id}'\n ConnectionFactory.execute(query)\n\n def remover(self):\n query = f'DELETE FROM curriculo WHERE curriculo_id = {self.curriculo_id}'\n ConnectionFactory.execute(query)\n\n def buscar(self):\n query = f'SELECT nome, idade, email, realocar, telefone_residencial, telefone_celular FROM candidato c WHERE c.candidato_id = {self.candidato_id}'\n connection = ConnectionFactory.get_connection()\n cursor = connection.cursor(dictionary=True,buffered=True)\n cursor.execute(query)\n dados = cursor.fetchone()\n return dados\n\n def buscar_endereco(self):\n query = f'SELECT uf, cidade, rua, numero, cep FROM endereco e INNER JOIN candidato c ON c.endereco_id = e.endereco_id WHERE c.candidato_id = {self.candidato_id}'\n connection = ConnectionFactory.get_connection()\n cursor = connection.cursor(dictionary=True,buffered=True)\n cursor.execute(query)\n dados = cursor.fetchone()\n return dados\n\n def buscar_curso_extra_curricular(self):\n query = f'SELECT * FROM curso_extra_curricular ce INNER JOIN curriculo_curso_extracurricular cce ON cce.curso_extracurricular_id = ce.curso_extra_id INNER JOIN curriculo c ON c.curriculo_id = cce.curriculo_id WHERE c.candidato_id = {self.candidato_id}'\n connection = ConnectionFactory.get_connection()\n cursor = connection.cursor(dictionary=True,buffered=True)\n cursor.execute(query)\n dados = cursor.fetchone()\n return dados\n \n def buscar_experiencias_anteriores(self):\n query = f'SELECT * FROM experiencia_anterior ea INNER JOIN curriculo_experiencia ce ON ce.experiencia_id = ea.experiencia_id INNER JOIN curriculo c ON ce.curriculo_id = c.curriculo_id WHERE c.candidato_id = {self.candidato_id}'\n connection = ConnectionFactory.get_connection()\n cursor = connection.cursor(dictionary=True,buffered=True)\n cursor.execute(query)\n dados = cursor.fetchone()\n return dados\n\n def buscar_formacao_academica(self):\n query = f'SELECT * FROM formacao_academica fa INNER JOIN curriculo_formacao cfa ON cfa.formacao_id = fa.formacao_id INNER JOIN curriculo c ON c.curriculo_id = cfa.curriculo_id WHERE c.candidato_id = {self.candidato_id}'\n connection = ConnectionFactory.get_connection()\n cursor = connection.cursor(dictionary=True,buffered=True)\n cursor.execute(query)\n dados = cursor.fetchone()\n return dados\n\n def buscar_idiomas(self):\n query = f'SELECT * FROM idioma i INNER JOIN curriculo_idioma ci ON ci.idioma_id = ci.idioma_id INNER JOIN curriculo c ON c.curriculo_id = ci.curriculo_id WHERE c.candidato_id = {self.candidato_id}'\n connection = ConnectionFactory.get_connection()\n cursor = connection.cursor(dictionary=True,buffered=True)\n cursor.execute(query)\n dados = cursor.fetchone()\n return dados","sub_path":"services/curriculoService/DAOs/curriculoDAO.py","file_name":"curriculoDAO.py","file_ext":"py","file_size_in_byte":3808,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"269902566","text":"import pickle\r\nimport cv2\r\nimport os\r\nimport time\r\nimport numpy as np\r\nimport pytesseract\r\nfrom image_handlers import read_table\r\nfrom constants.path_manager import IMAGE_TEXT_DATA_PATH, IMAGE_OUTPUT_PATH\r\nfrom image_handlers.image_utilities import get_binary, find_table, find_text_region, intersection_lines_detection\r\n\r\n# from utilities.file_utilities import get_file_name, get_extension\r\nfrom utilities.path import root\r\n\r\n\r\nclass TableTextReader:\r\n def __init__(self, image_path):\r\n self.image_path = image_path\r\n self.image = cv2.imread(image_path)\r\n self.image_original_coo = list(self.image.shape[:2])\r\n self.image_height = self.image_original_coo[0]\r\n self.image_width = self.image_original_coo[1]\r\n self.blank_image = np.zeros(list(self.image.shape), self.image.dtype)\r\n self.soft_margin = 10\r\n\r\n def no_intersection_tables_ocr(self, table, table_coo, table_num, highlight_readable_paras):\r\n represent_point = table_coo[table_num][:2]\r\n # represent_point_ratio = (np.divide(represent_point, self.image_original_coo)).tolist()\r\n width = abs(table_coo[table_num][0] - table_coo[table_num][2])\r\n height = abs(table_coo[table_num][1] - table_coo[table_num][3])\r\n represent_point.append(width)\r\n represent_point.append(height)\r\n # relative_width = width / self.image_width\r\n # relative_height = height / self.image_height\r\n # represent_point_ratio.append(relative_width)\r\n # represent_point_ratio.append(relative_height)\r\n text = pytesseract.image_to_string(table, lang='chi_sim+eng') # 'chi_sim+eng'\r\n # table_dict[tuple(represent_point_ratio)] = text\r\n table_num += 1\r\n return represent_point, text\r\n\r\n def intersection_tables_ocr(self, table_coo, table_num, highlight_readable_paras):\r\n print('I am working on intersection table OCR')\r\n bin_table = get_binary(self.image)\r\n table_lines = find_table(bin_table)\r\n region = find_text_region(table_lines, cv2.RETR_TREE)\r\n # read text of table into dictionary\r\n text_dict = {}\r\n for table in region[1:]:\r\n # get the coordinate order\r\n # use the minimum coordination as the represent point of each small table\r\n represent_point = sorted(table.tolist())[0]\r\n width = abs(table[1] - table[2])[0]\r\n height = abs(table[0] - table[1])[1]\r\n table_region = self.image[represent_point[1]:(represent_point[1] + height),\r\n represent_point[0]:(represent_point[0] + width)]\r\n # relative_coo_point = [relative_x_value, relative_y_value, relative_rec_width, relative_rec_height]\r\n relative_width = width / self.image_width\r\n relative_height = height / self.image_height\r\n o_coo_point = (np.add(represent_point, table_coo[table_num][:2])).tolist()\r\n relative_coo_point = (np.divide(o_coo_point, self.image_original_coo)).tolist()\r\n relative_coo_point.append(relative_width)\r\n relative_coo_point.append(relative_height)\r\n # get text from table\r\n small_table_height, small_table_width, dim = table_region.shape\r\n if small_table_height == 0 and small_table_width == 0:\r\n continue\r\n elif 2 * width * height > self.image_height * self.image_width:\r\n continue\r\n elif height + self.soft_margin > self.image_height or width + self.soft_margin > self.image_width:\r\n continue\r\n # print('table_region:{}'.format(table_region.shape))\r\n text = pytesseract.image_to_string(table_region)\r\n text_dict[tuple(relative_coo_point)] = text\r\n if text and highlight_readable_paras:\r\n # highlight img\r\n cv2.rectangle(self.blank_image, (o_coo_point[0] + self.soft_margin, o_coo_point[1] + self.soft_margin),\r\n (o_coo_point[0] + width - self.soft_margin, o_coo_point[1] + height - self.soft_margin),\r\n (0, 0, 255), thickness=2)\r\n table_num += 1\r\n cv2.imwrite('blank_image.png', self.blank_image)\r\n # table_dicts.append(text_dict)\r\n return text_dict\r\n\r\n def get_table_text_dict(self, save_dict_path=None, save_dict=False, highlight_readable_paras=None):\r\n \"\"\"\r\n save table text dict in a list\r\n\r\n \"\"\"\r\n print('I am working on extracting table information dictionary')\r\n table_num = 0\r\n table_dict = {}\r\n table_keys_list = []\r\n table_dicts_group = []\r\n # adjust contrast\r\n contrast_img = cv2.addWeighted(self.image, 1.3, self.blank_image, 1 - 1.3, 5)\r\n imgs, table_coo = read_table.extract_table_from_img(self.image_path)\r\n highlight_step_1 = self.blank_image.copy()\r\n pure_table_image = np.zeros([self.image_height + self.soft_margin, self.image_width + self.soft_margin, 3],\r\n self.image.dtype)\r\n print('I am working on OCR')\r\n for table in imgs:\r\n # print('working on region {}'.format(table_num))\r\n if not intersection_lines_detection(table):\r\n table_key, table_value = self.no_intersection_tables_ocr(table, table_coo, table_num,\r\n highlight_readable_paras)\r\n cv2.rectangle(pure_table_image, (table_key[0], table_key[1]),\r\n (table_key[0] + table_key[2], table_key[1] + table_key[3]),\r\n (0, 0, 255), thickness=4)\r\n table_dict[tuple(table_key)] = table_value\r\n table_keys_list.append(table_key)\r\n table_num += 1\r\n else:\r\n table_num += 1\r\n continue\r\n # image_copy = self.image.copy()\r\n binary_table_region = get_binary(pure_table_image)\r\n table_edge_condition, table_region_contours = find_text_region(binary_table_region, cv2.RETR_EXTERNAL)\r\n # cv2.drawContours(image_copy, table_region_contours, -1, (0, 255, 0), 12)\r\n # cv2.imwrite('pure_table_region.png', image_copy)\r\n # cv2.imshow('pure table region', pure_table_image)\r\n # cv2.waitKey(0)\r\n # cv2.destroyAllWindows()\r\n # group the discrete small tables in a table\r\n # table_edge_condition = get_iso_table_condition(table_keys_list)\r\n # print('return table text information dictionary')\r\n for edge_condition in table_edge_condition:\r\n represent_min_point = sorted(edge_condition.tolist())[0]\r\n represent_max_point = sorted(edge_condition.tolist())[-1]\r\n min_edge_x, min_edge_y = represent_min_point\r\n max_edge_x, max_edge_y = represent_max_point\r\n iso_table_dict = {}\r\n for key in table_keys_list:\r\n if min_edge_x <= key[0] < max_edge_x and min_edge_y <= key[1] < max_edge_y:\r\n iso_table_dict[tuple(key)] = table_dict[tuple(key)]\r\n table_dicts_group.append(iso_table_dict)\r\n if save_dict:\r\n # save table dictionary in pkl file\r\n file = open(save_dict_path, 'wb')\r\n pickle.dump(table_dict, file)\r\n file.close()\r\n if highlight_readable_paras:\r\n print('highlight step 1')\r\n highlight_step_1 = cv2.addWeighted(contrast_img, 0.8, self.blank_image, 0.2, 3)\r\n # f_name = get_file_name(save_highlight_path)\r\n # f_extension = get_extension(save_highlight_path)\r\n # cv2.imwrite('test_highlight_step1_marked.png', highlight_step_1)\r\n return table_dicts_group, highlight_step_1\r\n\r\n\r\nif __name__ == '__main__':\r\n # path = IMAGE_TEXT_DATA_PATH # GERBER_IMG_DATAPATH\r\n # # file_name = 'middle_black.pdf-output-0.png' # '(0.24平米) 04-28 20 4S7HQ08GA0/drill_drawing.pho.png'\r\n # file_name = 'i_test4.png'\r\n # input_file = os.path.join(path, file_name)\r\n # out_file = os.path.join(IMAGE_OUTPUT_PATH, file_name)\r\n\r\n pdf_test_path = os.path.join(root, 'image_handlers', 'data', 'image4experiment')\r\n pdf_output_path = os.path.join(root, 'image_handlers', 'data', 'output4experiment')\r\n file_name = 'pdf_image.png'\r\n input_file = os.path.join(pdf_test_path, file_name)\r\n output_file = os.path.join(pdf_output_path, file_name)\r\n\r\n image = cv2.imread(input_file)\r\n print(image.shape)\r\n\r\n # dict_path = os.path.join(IMAGE_OUTPUT_PATH, 'pdf_text_dict.pkl')\r\n # start_time = time.time()\r\n # table_reader = TableTextReader(input_file)\r\n # text_dict_list, highlight = table_reader.get_table_text_dict(save_dict_path=dict_path,\r\n # save_dict=True, highlight_readable_paras=True)\r\n # print(len(text_dict_list))\r\n # # print(text_dict_list)\r\n # for l in text_dict_list:\r\n # print(l)\r\n # print(\"--- %s seconds ---\" % (time.time() - start_time))\r\n # print(text_dict_list)\r\n","sub_path":"image_handlers/no_merge.py","file_name":"no_merge.py","file_ext":"py","file_size_in_byte":9105,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"639052022","text":"# uncompyle6 version 3.7.4\n# Python bytecode 2.7 (62211)\n# Decompiled from: Python 3.6.9 (default, Apr 18 2020, 01:56:04) \n# [GCC 8.4.0]\n# Embedded file name: /Users/Dani/Documents/Projects/Golismero_2.0/src_github/thirdparty_libs/requests_ntlm/ntlm/des.py\n# Compiled at: 2013-08-26 10:52:44\nimport des_c\n\nclass DES:\n des_c_obj = None\n\n def __init__(self, key_str):\n \"\"\"\"\"\"\n k = str_to_key56(key_str)\n k = key56_to_key64(k)\n key_str = ''\n for i in k:\n key_str += chr(i & 255)\n\n self.des_c_obj = des_c.DES(key_str)\n\n def encrypt(self, plain_text):\n \"\"\"\"\"\"\n return self.des_c_obj.encrypt(plain_text)\n\n def decrypt(self, crypted_text):\n \"\"\"\"\"\"\n return self.des_c_obj.decrypt(crypted_text)\n\n\nDESException = 'DESException'\n\ndef str_to_key56(key_str):\n \"\"\"\"\"\"\n if type(key_str) != type(''):\n pass\n if len(key_str) < 7:\n key_str = key_str + '\\x00\\x00\\x00\\x00\\x00\\x00\\x00'[:7 - len(key_str)]\n key_56 = []\n for i in key_str[:7]:\n key_56.append(ord(i))\n\n return key_56\n\n\ndef key56_to_key64(key_56):\n \"\"\"\"\"\"\n key = []\n for i in range(8):\n key.append(0)\n\n key[0] = key_56[0]\n key[1] = key_56[0] << 7 & 255 | key_56[1] >> 1\n key[2] = key_56[1] << 6 & 255 | key_56[2] >> 2\n key[3] = key_56[2] << 5 & 255 | key_56[3] >> 3\n key[4] = key_56[3] << 4 & 255 | key_56[4] >> 4\n key[5] = key_56[4] << 3 & 255 | key_56[5] >> 5\n key[6] = key_56[5] << 2 & 255 | key_56[6] >> 6\n key[7] = key_56[6] << 1 & 255\n key = set_key_odd_parity(key)\n return key\n\n\ndef set_key_odd_parity(key):\n \"\"\"\"\"\"\n for i in range(len(key)):\n for k in range(7):\n bit = 0\n t = key[i] >> k\n bit = (t ^ bit) & 1\n\n key[i] = key[i] & 254 | bit\n\n return key","sub_path":"pycfiles/golismero-2.0.3-1.tar/des.py","file_name":"des.py","file_ext":"py","file_size_in_byte":1834,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"320898620","text":"from ete3 import NCBITaxa\nimport argparse\nfrom utils import *\n\nparser = argparse.ArgumentParser(description=\n \"Filter fasta files based on taxonomy and accession types\"\n )\nparser.add_argument('-i',\n dest='fasta_in',\n help=\"Input file to filter\",\n required=True\n )\nparser.add_argument('-o',\n dest=\"fasta_out\",\n help=\"Fasta ouput file. Depending on extensions can be gzipped or not\",\n required=True)\nparser.add_argument('--include-taxa',\n dest='taxa_in',\n help=\"A comma separated list of taxa to be filtered\",\n required=False\n )\nparser.add_argument('--exclude-taxa',\n dest='taxa_ex',\n help='Taxa to be excluded',\n required=False\n )\nparser.add_argument('--include-accessions',\n dest='acc_in',\n help='List of accession types to be included',\n required=False\n )\nparser.add_argument('--exclude-accessions',\n dest='acc_ex',\n help='List of accession types to be excluded',\n required=False\n )\nparser.add_argument('-j',\n dest='json_fp',\n help='JSON file with the mapping of taxonomy ids to accessions',\n required=True\n )\nparser.add_argument('--include-accessions-from-file',\n dest='acc_in_file',\n help=\"A file containing accessions to be included, one per line\",\n required=False)\nparser.add_argument('--exclude-accessions-from-file',\n dest='acc_ex_file',\n help=\"A file containing accessions to be excluded, one per line\",\n required=False)\nparser.add_argument(\"--dbfile\",\n dest=\"dbfile\",\n help=\"Path to instantiated ete3 sqlite db\",\n required=False)\n\n\nrefseq_genomic_prefixes = {\"NC\", \"NW\", \"NG\", \"NT\", \"NZ_CP\", \"NZ_CM\", \"NZ\", \"AC\"}\n\n\nclass FastaFilterer:\n \"\"\"\n An object that filters sequences from a given fasta file, based on given taxonomic identifiers\n or accession prefixes.\n \"\"\"\n\n def __init__(self, fp_in, fp_out,\n include_taxa, exclude_taxa,\n include_accessions, exclude_accessions,\n accessions_infile, accessions_exfile,\n acc2taxid_json, dbfile):\n\n self.fp_in = fp_in\n self.fp_out = fp_out\n\n # Load the taxonomy info if taxa based filtering is defined\n if include_taxa or exclude_taxa:\n self.taxonomy_filtering = True\n print(\"Loading taxonomy information\")\n self.acc2taxid = get_acc2taxid_map(acc2taxid_json)\n self.ncbiTree = NCBITaxa(dbfile=dbfile)\n if include_taxa and exclude_taxa:\n self.tmode = \"both\"\n taxa_in = set(create_full_taxa_list(include_taxa, self.ncbiTree, include_parent=True))\n taxa_ex = set(create_full_taxa_list(exclude_taxa, self.ncbiTree, include_parent=True))\n if taxa_ex.issuperset(taxa_in):\n self.final_taxa_list = list(taxa_in)\n else:\n self.final_taxa_list = list(taxa_in - taxa_ex)\n\n elif include_taxa and not exclude_taxa:\n self.tmode = \"inclusive_only\"\n self.final_taxa_list = create_full_taxa_list(include_taxa, self.ncbiTree, include_parent=True)\n elif exclude_taxa and not include_taxa:\n self.tmode = \"exclusive_only\"\n self.final_taxa_list = create_full_taxa_list(exclude_taxa, self.ncbiTree, include_parent=True)\n else:\n self.final_taxa_list = None\n self.taxonomy_filtering = None\n\n if include_accessions or exclude_accessions:\n self.accession_prefix_filtering = True\n if include_accessions and exclude_accessions:\n self.pmode = \"both\"\n self.acc_prefixes = list(set(include_accessions) - set(exclude_accessions))\n elif include_accessions and not exclude_accessions:\n self.pmode = \"inclusive_only\"\n self.acc_prefixes = include_accessions\n elif exclude_accessions and not include_accessions:\n self.pmode = \"exclusive_only\"\n self.acc_prefixes = refseq_genomic_prefixes - set(exclude_accessions)\n else:\n self.acc_prefixes = None\n self.accession_prefix_filtering = None\n\n if accessions_infile or accessions_exfile:\n self.accession_file_filtering = True\n if accessions_infile and accessions_exfile:\n self.amode = \"both\"\n faccessions_in = set(single_column_file_to_list(accessions_infile))\n faccessions_ex = set(single_column_file_to_list(accessions_exfile))\n self.pre_accessions = faccessions_in - faccessions_ex\n elif accessions_infile and not accessions_exfile:\n self.amode = \"inclusive_only\"\n self.pre_accessions = set(single_column_file_to_list(accessions_infile))\n elif accessions_exfile and not accessions_infile:\n self.amode = \"exclusive_only\"\n self.pre_accessions = set(single_column_file_to_list(accessions_exfile))\n else:\n self.pre_accessions = None\n self.accession_file_filtering = None\n\n def create_taxonomy_accessions_set(self):\n accessions = []\n for taxid in self.final_taxa_list:\n tmp_ac = self.acc2taxid.get(str(taxid), None)\n if tmp_ac is not None:\n accessions += [list(tmp_ac.keys())]\n accessions_flat = [accession for sublist in accessions for accession in sublist]\n taxonomy_accessions = filter_accession_list_on_prefix(accessions_flat, self.acc_prefixes)\n return set(taxonomy_accessions)\n\n def get_fasta_accessions_set(self):\n seq_iterator = SeqIO.parse(optionally_compressed_handle(self.fp_in, 'r'), format=\"fasta\")\n fasta_accessions = {record.id for record in seq_iterator}\n return fasta_accessions\n\n def create_final_accessions_set(self):\n fasta_accessions = self.get_fasta_accessions_set()\n # 1. ALL FILTERS ENABLED\n # FIX ME\n # The self.amode is not covered here...\n if self.taxonomy_filtering \\\n and self.accession_prefix_filtering \\\n and self.accession_file_filtering:\n\n taxonomy_accessions = self.create_taxonomy_accessions_set()\n if self.tmode in [\"both\", \"inclusive_only\"]:\n tmp_accessions = fasta_accessions.intersection(taxonomy_accessions)\n\n if self.pmode in [\"both\", \"inclusive_only\"]:\n final_accessions = filter_accession_list_on_prefix(tmp_accessions,\n self.acc_prefixes,\n exclusive=False)\n elif self.pmode == \"exclusive_only\":\n final_accessions = filter_accession_list_on_prefix(tmp_accessions,\n self.acc_prefixes,\n exclusive=True)\n else:\n print(\"Why am I here...?\")\n\n elif self.tmode == \"exclusive_only\":\n tmp_accessions = fasta_accessions.difference(taxonomy_accessions)\n if self.pmode in [\"both\", \"inclusive_only\"]:\n final_accessions = filter_accession_list_on_prefix(tmp_accessions,\n self.acc_prefixes,\n exclusive=False)\n elif self.pmode == \"exclusive_only\":\n print(\"excluding prefixes\")\n final_accessions = filter_accession_list_on_prefix(tmp_accessions,\n self.acc_prefixes,\n exclusive=True)\n else:\n print(\"Why am I here\")\n\n # 2. FILE AND PREFIX\n elif self.accession_file_filtering \\\n and self.accession_prefix_filtering \\\n and not self.taxonomy_filtering:\n\n if self.amode in [\"both\", \"inclusive_only\"]:\n tmp_accessions = fasta_accessions.intersection(self.pre_accessions)\n if self.pmode in [\"both\", \"inclusive_only\"]:\n print(\"including prefixes\")\n final_accessions = filter_accession_list_on_prefix(tmp_accessions,\n self.acc_prefixes,\n exclusive=False)\n elif self.pmode == \"exclusive_only\":\n print(\"excluding prefixes\")\n final_accessions = filter_accession_list_on_prefix(tmp_accessions,\n self.acc_prefixes,\n exclusive=True)\n else:\n print(\"Why am I here\")\n elif self.amode == \"exclusive_only\":\n tmp_accessions = fasta_accessions.difference(self.pre_accessions)\n if self.pmode in [\"both\", \"inclusive_only\"]:\n final_accessions = filter_accession_list_on_prefix(tmp_accessions,\n self.acc_prefixes,\n exclusive=False)\n elif self.pmode == \"exclusive_only\":\n print(\"excluding prefixes\")\n final_accessions = filter_accession_list_on_prefix(tmp_accessions,\n self.acc_prefixes,\n exclusive=True)\n else:\n print(\"Why am I here...\")\n\n # 3. FILE ONLY\n elif self.accession_file_filtering \\\n and not self.accession_prefix_filtering \\\n and not self.taxonomy_filtering:\n\n if self.amode in [\"both\", \"inclusive_only\"]:\n final_accessions = fasta_accessions.union(self.pre_accessions)\n elif self.amode == \"exclusive_only\":\n final_accessions = fasta_accessions.difference(self.pre_accessions)\n\n # 4. PREFIX ONLY\n elif self.accession_prefix_filtering \\\n and not self.accession_file_filtering \\\n and not self.taxonomy_filtering:\n\n if self.pmode in [\"both\", \"inclusive_only\"]:\n final_accessions = filter_accession_list_on_prefix(fasta_accessions,\n self.acc_prefixes,\n exclusive=False)\n elif self.pmode == \"exclusive_only\":\n final_accessions = filter_accession_list_on_prefix(fasta_accessions,\n self.acc_prefixes,\n exclusive=True)\n\n # 5. TAXONOMY AND PREFIX\n elif self.taxonomy_filtering \\\n and self.accession_prefix_filtering \\\n and not self.accession_file_filtering:\n\n taxonomy_accessions = self.create_taxonomy_accessions_set()\n if self.tmode in [\"both\", \"inclusive_only\"]:\n tmp_accessions = fasta_accessions.intersection(taxonomy_accessions)\n elif self.tmode == \"exclusive_only\":\n tmp_accessions = fasta_accessions.difference(taxonomy_accessions)\n else:\n tmp_accessions = set()\n\n if self.pmode in [\"both\", \"inclusive_only\"]:\n final_accessions = filter_accession_list_on_prefix(tmp_accessions,\n self.acc_prefixes,\n exclusive=False)\n elif self.pmode == \"exclusive_only\":\n final_accessions = filter_accession_list_on_prefix(tmp_accessions,\n self.acc_prefixes,\n exclusive=True)\n\n # 6. TAXONOMY AND ACCESSION FILE\n elif self.taxonomy_filtering \\\n and self.accession_file_filtering \\\n and not self.accession_prefix_filtering:\n\n taxonomy_accessions = self.create_taxonomy_accessions_set()\n if self.tmode in [\"both\", \"inclusive_only\"]:\n tmp_accessions = fasta_accessions.intersection(taxonomy_accessions)\n if self.amode in [\"both\", \"inclusive_only\"]:\n final_accessions = tmp_accessions.intersection(self.pre_accessions)\n elif self.amode == \"exclusive_only\":\n final_accessions = tmp_accessions.difference(self.pre_accessions)\n\n else:\n print(\"Case not covered\")\n\n return set(final_accessions)\n\n def write_accessions_to_file(self, fp_in, fp_out, accessions):\n out_counter, in_counter = 0, 0\n with optionally_compressed_handle(fp_out, 'w') as fout, optionally_compressed_handle(fp_in, 'r') as fin:\n input_seq_iterator = SeqIO.parse(fin, format=\"fasta\")\n for record in input_seq_iterator:\n in_counter += 1\n if record.id in accessions:\n out_counter += 1\n SeqIO.write(record, fout, format=\"fasta\")\n return fp_in, in_counter, fp_out, out_counter\n\n\nif __name__ == '__main__':\n args = parser.parse_args()\n\n if args.taxa_in:\n taxa_in = [taxid.strip() for taxid in args.taxa_in.split(',')]\n else:\n taxa_in = None\n\n if args.taxa_ex:\n taxa_ex = [taxid.strip() for taxid in args.taxa_ex.split(',')]\n else:\n taxa_ex = None\n\n if args.acc_in:\n acc_in = [acc.strip() for acc in args.acc_in.split(',')]\n else:\n acc_in = ['AC', 'NG', 'NC', 'NW', 'NZ', 'NZ_CP', 'NZ_CM', 'NT']\n\n if args.acc_ex:\n acc_ex = [acc.strip() for acc in args.acc_ex.split(',')]\n else:\n acc_ex = None\n\n if args.acc_in_file:\n acc_in_file = args.acc_in_file\n else:\n acc_in_file = None\n\n if args.acc_ex_file:\n acc_ex_file = args.acc_ex_file\n else:\n acc_ex_file = None\n\n filterObj = FastaFilterer(fp_in=args.fasta_in, fp_out=args.fasta_out,\n acc2taxid_json=args.json_fp,\n include_taxa=taxa_in, exclude_taxa=taxa_ex,\n include_accessions=acc_in, exclude_accessions=acc_ex,\n accessions_infile=acc_in_file, accessions_exfile=acc_ex_file,\n dbfile=args.dbfile\n )\n\n # Create the set of fasta accessions\n fasta_accessions = filterObj.get_fasta_accessions_set()\n # Filter the accessions based on input criteria\n final_accessions = filterObj.create_final_accessions_set()\n # if filtering didn't change the original set\n if final_accessions == fasta_accessions:\n # For now just rename the file - mark as processed\n fp_in, seqs_in, fp_out, seqs_out = filterObj.write_accessions_to_file(filterObj.fp_in,\n filterObj.fp_out,\n final_accessions)\n print(\"{}\\t(copied)\\t{}\\t{}\\t{}\".format(filterObj.fp_in,\n len(fasta_accessions),\n filterObj.fp_out,\n len(final_accessions)))\n elif len(final_accessions) == 0:\n print(\"{}\\t(untouched)\\t{}\\tNA\\t0\".format(filterObj.fp_in, len(fasta_accessions)))\n else:\n fp_in, seqs_in, fp_out, seqs_out = filterObj.write_accessions_to_file(filterObj.fp_in,\n filterObj.fp_out,\n final_accessions)\n print(\"{}\\t(new)\\t{}\\t{}\\t{}\".format(fp_in, seqs_in, fp_out, seqs_out))\n\n print(\"Done!\")\n","sub_path":"filter_fasta.py","file_name":"filter_fasta.py","file_ext":"py","file_size_in_byte":17120,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"276223890","text":"import tkinter\nimport sqlite3\n\ndef convert(out_breed, enter_rank):\n \"\"\" Find the rank in Sqlite3 dogs89.db table Dog_Licc and return the breed. \"\"\"\n num = enter_rank.get()\n num_tup=(num,)\n con = sqlite3.connect('dogs89.db')\n cur = con.cursor()\n cur.execute('''SELECT Breed FROM Dog_Licc WHERE Rank = ?''',num_tup)\n output=cur.fetchone()\n output = output[0]\n out_breed.set(output)\n \nwindow = tkinter.Tk()\nframe = tkinter.Frame(window)\nframe.pack()\n\nout_breed = tkinter.StringVar()\nenter_rank = tkinter.IntVar()\n\ntkinter.Label(frame, text='Enter Breed Rank 1-10').pack()\n\nenter_rank = tkinter.StringVar()\ntext = tkinter.Entry(frame, textvar=enter_rank, justify='center')\ntext.pack()\n\nout_breed = tkinter.StringVar()\nlabel = tkinter.Label(frame, textvar=out_breed)\nlabel.pack()\n\nbutton = tkinter.Button(frame, text='Find Breed', command=lambda: convert(out_breed, enter_rank))\nbutton.pack()\n\nbutton2 = tkinter.Button(frame, text='Quit', command=lambda: window.destroy())\nbutton2.pack()\n\nwindow.mainloop()\n","sub_path":"GUI dogs_DEMO.py","file_name":"GUI dogs_DEMO.py","file_ext":"py","file_size_in_byte":1037,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"379493017","text":"from pprint import pprint\nimport csv\nimport re\n\nwith open(\"phonebook_raw.csv\", encoding='utf-8') as f:\n rows = csv.reader(f, delimiter=\",\")\n contacts_list = list(rows)\n #pprint(contacts_list)\n\ndef name_normalization(rows):\n result = [' '.join(employee[0:3]).split(' ')[0:3] + employee[3:7] for employee in rows]\n\n return result\n\ndef remove_duplicates(correct_name_list):\n no_duplicates = []\n for compared in correct_name_list:\n for employee in correct_name_list:\n if compared[0:2] == employee[0:2]:\n list_employee = compared\n compared = list_employee[0:2]\n for i in range(2, 7):\n if list_employee[i] == '':\n compared.append(employee[i])\n else:\n compared.append(list_employee[i])\n if compared not in no_duplicates:\n no_duplicates.append(compared)\n\n return no_duplicates\n\ndef updating_phone_numbers(rows, regular, new):\n phonebook = []\n pattern = re.compile(regular)\n phonebook = [[pattern.sub(new, string) for string in strings] for strings in rows]\n\n return phonebook\n\ncorrect_name_list = name_normalization(contacts_list)\nno_duplicates_list = remove_duplicates(correct_name_list)\nregular = r'(\\+7|8)+[\\s(]*(\\d{3,3})[\\s)-]*(\\d{3})[\\s-]*(\\d{2})[\\s-]*(\\d{2})'\ncorrect_list = updating_phone_numbers(no_duplicates_list, regular, r'+7(\\2)\\3-\\4-\\5')\nregular_2 = r'(\\+7|8)+[\\s(]*(\\d{3,3})[\\s)-]*(\\d{3})[\\s-]*(\\d{2})[\\s-]*(\\d{2})[\\s]*[(доб.\\s]*(\\d+)[)]*'\ncorrect_phonebook = updating_phone_numbers(correct_list, regular_2, r'+7(\\2)\\3-\\4-\\5 доб.\\6')\n\nwith open(\"phonebook.csv\", \"w\", encoding='utf-8') as f:\n datawriter = csv.writer(f, delimiter=',')\n datawriter.writerows(correct_phonebook)","sub_path":"phonebook_app.py","file_name":"phonebook_app.py","file_ext":"py","file_size_in_byte":1790,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"368834967","text":"\n# coding: utf-8\n\n# In[ ]:\n\n\n# -*- coding: utf-8 -*-\nimport sys\nimport codecs\nsys.stdout = codecs.getwriter('utf_8')(sys.stdout)\nfrom selenium import webdriver\nfrom selenium.common.exceptions import WebDriverException\n#ActionChainsクラスは通常のクリック処理や値の設定以外にもShiftを押しながら入力という処理やF1やF3など特殊なキー操作を行うことができる\nfrom selenium.webdriver.common.action_chains import ActionChains\nimport time\nimport random\n\n\n# In[ ]:\n\n\n#loginする関数\ndef login():\n browser.get('https://www.instagram.com/accounts/login/?source=auth_switcher')\n f=open('insta.txt','a',encoding='utf-8')\n f.write(\"instagramにアクセスしました\\n\")\n f.close()\n time.sleep(random.randint(5,10))\n\n #メアドとパスワードを入力\n \"\"\"\n browser.find_element_by_name('username').send_keys('')#ユーザー名を入力してください\n time.sleep(5)\n browser.find_element_by_name('password').send_keys('')#パスワードを入力してください\n time.sleep(5)\n \"\"\"\n browser.find_element_by_name('username').send_keys('')#ユーザー名を入力してください\n time.sleep(random.randint(5,10))\n browser.find_element_by_name('password').send_keys('')#パスワードを入力してください\n time.sleep(random.randint(5,10))\n #ログインボタンを押す\n browser.find_element_by_class_name('L3NKy ').click()\n time.sleep(random.randint(7,12))\n f=open('insta.txt','a',encoding='utf-8')\n f.write(\"instagramにログインしました\\n\")\n f.close()\n time.sleep(random.randint(5,10))\n\n\n# In[ ]:\n\n\n#指定したtagで検索する関数\ndef tagsearch(tag):\n #指定したtagのページへ移動\n instaurl='https://www.instagram.com/explore/tags/'\n browser.get(instaurl+tag)\n time.sleep(random.randint(2,10))\n f=open('insta.txt','a')\n f.write(\"listtagより、\"+tag+\"で検索を行いました\\n\")\n f.close()\n time.sleep(random.randint(5,10))\n\n\n# In[ ]:\n\n\n#いいねとフォローをする関数\ndef clicknice_follow():\n target=browser.find_elements_by_class_name('_9AhH0')[10]#写真のtag\n actions=ActionChains(browser)\n actions.move_to_element(target)#ターゲット要素(target)にマウスカーソル移動\n actions.perform()#実行\n f=open('insta.txt','a')\n f.write(\"最新の投稿まで画面を移動しました\\n\")\n f.close()\n time.sleep(random.randint(5,10))\n \n try:\n browser.find_elements_by_class_name('_9AhH0')[9].click()#写真のtag\n time.sleep(random.randint(2,10))\n f=open('insta.txt','a')\n f.write('投稿をクリックしました\\n')\n f.close()\n time.sleep(1)\n browser.find_element_by_class_name('fr66n').click()#いいねのtag\n time.sleep(random.randint(2,10))\n f=open('insta.txt','a')\n f.write(\"投稿をいいねしました\\n\")\n f.close()\n time.sleep(random.randint(5,10))\n browser.find_element_by_class_name('bY2yH').click()#フォローのtag\n f=open('insta.txt','a')\n f.write(\"フォローしました\\n\")\n f.close()\n time.sleep(random.randint(5,10))\n\n except webDriverException:\n f=open('insta.txt','a')\n f.write(\"エラーが発生しました\\n\")\n f.close()\n return\n \n for i in range(random.randint(5,10)):\n try:\n browser.find_element_by_class_name('coreSpriteRightPaginationArrow').click()#次の写真へ移動するtag\n f = open('insta.txt','a')\n f.write(\"次の投稿へ移動しました\\n\")\n f.close()\n time.sleep(random.randint(random.randint(2, 5), random.randint(10, 15)))\n \n browser.find_element_by_class_name('fr66n').click()#いいねのtag\n f = open('insta.txt','a')\n f.write(\"投稿をいいねしました\\n\")\n f.close()\n time.sleep(random.randint(random.randint(2, 5), random.randint(10, 15)))\n \n browser.find_element_by_class_name('bY2yH').click()#フォローのtag\n f=open('insta.txt','a')\n f.write(\"フォローしました\\n\")\n f.close()\n time.sleep(random.randint(5,10))\n \n except WebDriverException:\n f = open('insta.txt','a')\n f.write(\"2つ目以降でエラーが発生しました\\n\")\n f.close()\n break\n \n\n\n# In[ ]:\n\n\nif __name__ == '__main__':#おまじない\n#いいね、フォローをしたいtagを入力\n taglist = ['animal', 'animals', 'reptile', 'animalcute','animallovers','animalcrossing','fish','animali','cat','dog']\n while True:\n browser = webdriver.Chrome()#指定の位置にwebdriverのpathを書いてください 例)/Users/ユーザー名/chromedriver\n time.sleep(random.randint(5,10))\n login()\n \n tagsearch(random.choice(taglist))#ランダムにtagを選択\n \n clicknice_follow()\n \n browser.close()\n\n abc = random.randint(random.randint(3000,5000 ), random.randint(6000, 12000))\n #encoding = \"utf-8\"\n f = open('insta.txt','a')\n f.write(str(abc)+\"秒待機します\\n\")\n f.close()\n\n time.sleep(abc) \n\n","sub_path":"instagram/instagram.py","file_name":"instagram.py","file_ext":"py","file_size_in_byte":5391,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"209271960","text":"'''\r\nGiven a list of words and two words word1 and word2, return the shortest distance between these two words in the list.\r\n\r\nExample:\r\nAssume that words = [\"practice\", \"makes\", \"perfect\", \"coding\", \"makes\"].\r\n\r\nInput: word1 = “coding”, word2 = “practice”\r\nOutput: 3\r\nInput: word1 = \"makes\", word2 = \"coding\"\r\nOutput: 1\r\nNote:\r\nYou may assume that word1 does not equal to word2, and word1 and word2 are both in the list.\r\n'''\r\n\r\nclass Solution:\r\n def shortestDistance(self, words, word1, word2):\r\n \"\"\"\r\n :type words: List[str]\r\n :type word1: str\r\n :type word2: str\r\n :rtype: int\r\n \"\"\"\r\n index1=[i for i in range(len(words)) if words[i]==word1]\r\n index2=[i for i in range(len(words)) if words[i]==word2]\r\n ret_min=float('inf')\r\n i=0\r\n while i}; however, pickle's main goal\nseems to be efficiency (both in space and time); jelly's main goals are\nsecurity, human readability, and portability to other environments.\n\nThis is how Jelly converts various objects to s-expressions.\n\nBoolean::\n True --> ['boolean', 'true']\n\nInteger::\n 1 --> 1\n\nList::\n [1, 2] --> ['list', 1, 2]\n\nString::\n \\\"hello\\\" --> \\\"hello\\\"\n\nFloat::\n 2.3 --> 2.3\n\nDictionary::\n {'a': 1, 'b': 'c'} --> ['dictionary', ['b', 'c'], ['a', 1]]\n\nModule::\n UserString --> ['module', 'UserString']\n\nClass::\n UserString.UserString --> ['class', ['module', 'UserString'], 'UserString']\n\nFunction::\n string.join --> ['function', 'join', ['module', 'string']]\n\nInstance: s is an instance of UserString.UserString, with a __dict__\n{'data': 'hello'}::\n [\\\"UserString.UserString\\\", ['dictionary', ['data', 'hello']]]\n\nClass Method: UserString.UserString.center::\n ['method', 'center', ['None'], ['class', ['module', 'UserString'],\n 'UserString']]\n\nInstance Method: s.center, where s is an instance of UserString.UserString::\n ['method', 'center', ['instance', ['reference', 1, ['class',\n ['module', 'UserString'], 'UserString']], ['dictionary', ['data', 'd']]],\n ['dereference', 1]]\n\nThe C{set} builtin and the C{sets.Set} class are serialized to the same\nthing, and unserialized to C{set} if available, else to C{sets.Set}. It means\nthat there's a possibility of type switching in the serialization process. The\nsolution is to always use C{set} if possible, and only use C{sets.Set} under\nPython 2.3; this can be accomplished by using L{twisted.python.compat.set}.\n\nThe same rule applies for C{frozenset} and C{sets.ImmutableSet}.\n\n@author: Glyph Lefkowitz\n\"\"\"\n\n# System Imports\nimport pickle\nimport types\nimport warnings\nfrom types import StringType\nfrom types import UnicodeType\nfrom types import IntType\nfrom types import TupleType\nfrom types import ListType\nfrom types import LongType\nfrom types import FloatType\nfrom types import FunctionType\nfrom types import MethodType\nfrom types import ModuleType\nfrom types import DictionaryType\nfrom types import InstanceType\nfrom types import NoneType\nfrom types import ClassType\nimport copy\n\nimport datetime\nfrom types import BooleanType\n\ntry:\n import decimal\nexcept ImportError:\n decimal = None\n\ntry:\n _set = set\nexcept NameError:\n _set = None\n\ntry:\n # Filter out deprecation warning for Python >= 2.6\n warnings.filterwarnings(\"ignore\", category=DeprecationWarning,\n message=\"the sets module is deprecated\", append=True)\n import sets as _sets\nfinally:\n warnings.filters.pop()\n\n\nfrom new import instance\nfrom new import instancemethod\nfrom zope.interface import implements\n\n# Twisted Imports\nfrom twisted.python.reflect import namedObject, qual\nfrom twisted.persisted.crefutil import NotKnown, _Tuple, _InstanceMethod\nfrom twisted.persisted.crefutil import _DictKeyAndValue, _Dereference\nfrom twisted.persisted.crefutil import _Container\nfrom twisted.python.compat import reduce\n\nfrom twisted.spread.interfaces import IJellyable, IUnjellyable\n\nDictTypes = (DictionaryType,)\n\nNone_atom = \"None\" # N\n# code\nclass_atom = \"class\" # c\nmodule_atom = \"module\" # m\nfunction_atom = \"function\" # f\n\n# references\ndereference_atom = 'dereference' # D\npersistent_atom = 'persistent' # p\nreference_atom = 'reference' # r\n\n# mutable collections\ndictionary_atom = \"dictionary\" # d\nlist_atom = 'list' # l\nset_atom = 'set'\n\n# immutable collections\n# (assignment to __dict__ and __class__ still might go away!)\ntuple_atom = \"tuple\" # t\ninstance_atom = 'instance' # i\nfrozenset_atom = 'frozenset'\n\n\n# errors\nunpersistable_atom = \"unpersistable\"# u\nunjellyableRegistry = {}\nunjellyableFactoryRegistry = {}\n\n_NO_STATE = object()\n\ndef _newInstance(cls, state=_NO_STATE):\n \"\"\"\n Make a new instance of a class without calling its __init__ method. \n Supports both new- and old-style classes.\n\n @param state: A C{dict} used to update C{inst.__dict__} or C{_NO_STATE}\n to skip this part of initialization.\n\n @return: A new instance of C{cls}.\n \"\"\"\n if not isinstance(cls, types.ClassType):\n # new-style\n inst = cls.__new__(cls)\n\n if state is not _NO_STATE:\n inst.__dict__.update(state) # Copy 'instance' behaviour\n else:\n if state is not _NO_STATE:\n inst = instance(cls, state)\n else: \n inst = instance(cls)\n return inst\n\n\n\ndef _maybeClass(classnamep):\n try:\n object\n except NameError:\n isObject = 0\n else:\n isObject = isinstance(classnamep, type)\n if isinstance(classnamep, ClassType) or isObject:\n return qual(classnamep)\n return classnamep\n\n\n\ndef setUnjellyableForClass(classname, unjellyable):\n \"\"\"\n Set which local class will represent a remote type.\n\n If you have written a Copyable class that you expect your client to be\n receiving, write a local \"copy\" class to represent it, then call::\n\n jellier.setUnjellyableForClass('module.package.Class', MyCopier).\n\n Call this at the module level immediately after its class\n definition. MyCopier should be a subclass of RemoteCopy.\n\n The classname may be a special tag returned by\n 'Copyable.getTypeToCopyFor' rather than an actual classname.\n\n This call is also for cached classes, since there will be no\n overlap. The rules are the same.\n \"\"\"\n\n global unjellyableRegistry\n classname = _maybeClass(classname)\n unjellyableRegistry[classname] = unjellyable\n globalSecurity.allowTypes(classname)\n\n\n\ndef setUnjellyableFactoryForClass(classname, copyFactory):\n \"\"\"\n Set the factory to construct a remote instance of a type::\n\n jellier.setUnjellyableFactoryForClass('module.package.Class', MyFactory)\n\n Call this at the module level immediately after its class definition.\n C{copyFactory} should return an instance or subclass of\n L{RemoteCopy}.\n\n Similar to L{setUnjellyableForClass} except it uses a factory instead\n of creating an instance.\n \"\"\"\n\n global unjellyableFactoryRegistry\n classname = _maybeClass(classname)\n unjellyableFactoryRegistry[classname] = copyFactory\n globalSecurity.allowTypes(classname)\n\n\n\ndef setUnjellyableForClassTree(module, baseClass, prefix=None):\n \"\"\"\n Set all classes in a module derived from C{baseClass} as copiers for\n a corresponding remote class.\n\n When you have a heirarchy of Copyable (or Cacheable) classes on one\n side, and a mirror structure of Copied (or RemoteCache) classes on the\n other, use this to setUnjellyableForClass all your Copieds for the\n Copyables.\n\n Each copyTag (the \\\"classname\\\" argument to getTypeToCopyFor, and\n what the Copyable's getTypeToCopyFor returns) is formed from\n adding a prefix to the Copied's class name. The prefix defaults\n to module.__name__. If you wish the copy tag to consist of solely\n the classname, pass the empty string \\'\\'.\n\n @param module: a module object from which to pull the Copied classes.\n (passing sys.modules[__name__] might be useful)\n\n @param baseClass: the base class from which all your Copied classes derive.\n\n @param prefix: the string prefixed to classnames to form the\n unjellyableRegistry.\n \"\"\"\n if prefix is None:\n prefix = module.__name__\n\n if prefix:\n prefix = \"%s.\" % prefix\n\n for i in dir(module):\n i_ = getattr(module, i)\n if type(i_) == types.ClassType:\n if issubclass(i_, baseClass):\n setUnjellyableForClass('%s%s' % (prefix, i), i_)\n\n\n\ndef getInstanceState(inst, jellier):\n \"\"\"\n Utility method to default to 'normal' state rules in serialization.\n \"\"\"\n if hasattr(inst, \"__getstate__\"):\n state = inst.__getstate__()\n else:\n state = inst.__dict__\n sxp = jellier.prepare(inst)\n sxp.extend([qual(inst.__class__), jellier.jelly(state)])\n return jellier.preserve(inst, sxp)\n\n\n\ndef setInstanceState(inst, unjellier, jellyList):\n \"\"\"\n Utility method to default to 'normal' state rules in unserialization.\n \"\"\"\n state = unjellier.unjelly(jellyList[1])\n if hasattr(inst, \"__setstate__\"):\n inst.__setstate__(state)\n else:\n inst.__dict__ = state\n return inst\n\n\n\nclass Unpersistable:\n \"\"\"\n This is an instance of a class that comes back when something couldn't be\n unpersisted.\n \"\"\"\n\n def __init__(self, reason):\n \"\"\"\n Initialize an unpersistable object with a descriptive C{reason} string.\n \"\"\"\n self.reason = reason\n\n\n def __repr__(self):\n return \"Unpersistable(%s)\" % repr(self.reason)\n\n\n\nclass Jellyable:\n \"\"\"\n Inherit from me to Jelly yourself directly with the `getStateFor'\n convenience method.\n \"\"\"\n implements(IJellyable)\n\n def getStateFor(self, jellier):\n return self.__dict__\n\n\n def jellyFor(self, jellier):\n \"\"\"\n @see: L{twisted.spread.interfaces.IJellyable.jellyFor}\n \"\"\"\n sxp = jellier.prepare(self)\n sxp.extend([\n qual(self.__class__),\n jellier.jelly(self.getStateFor(jellier))])\n return jellier.preserve(self, sxp)\n\n\n\nclass Unjellyable:\n \"\"\"\n Inherit from me to Unjelly yourself directly with the\n C{setStateFor} convenience method.\n \"\"\"\n implements(IUnjellyable)\n\n def setStateFor(self, unjellier, state):\n self.__dict__ = state\n\n\n def unjellyFor(self, unjellier, jellyList):\n \"\"\"\n Perform the inverse operation of L{Jellyable.jellyFor}.\n\n @see: L{twisted.spread.interfaces.IUnjellyable.unjellyFor}\n \"\"\"\n state = unjellier.unjelly(jellyList[1])\n self.setStateFor(unjellier, state)\n return self\n\n\n\nclass _Jellier:\n \"\"\"\n (Internal) This class manages state for a call to jelly()\n \"\"\"\n\n def __init__(self, taster, persistentStore, invoker):\n \"\"\"\n Initialize.\n \"\"\"\n self.taster = taster\n # `preserved' is a dict of previously seen instances.\n self.preserved = {}\n # `cooked' is a dict of previously backreferenced instances to their\n # `ref' lists.\n self.cooked = {}\n self.cooker = {}\n self._ref_id = 1\n self.persistentStore = persistentStore\n self.invoker = invoker\n\n\n def _cook(self, object):\n \"\"\"\n (internal) Backreference an object.\n\n Notes on this method for the hapless future maintainer: If I've already\n gone through the prepare/preserve cycle on the specified object (it is\n being referenced after the serializer is \\\"done with\\\" it, e.g. this\n reference is NOT circular), the copy-in-place of aList is relevant,\n since the list being modified is the actual, pre-existing jelly\n expression that was returned for that object. If not, it's technically\n superfluous, since the value in self.preserved didn't need to be set,\n but the invariant that self.preserved[id(object)] is a list is\n convenient because that means we don't have to test and create it or\n not create it here, creating fewer code-paths. that's why\n self.preserved is always set to a list.\n\n Sorry that this code is so hard to follow, but Python objects are\n tricky to persist correctly. -glyph\n \"\"\"\n aList = self.preserved[id(object)]\n newList = copy.copy(aList)\n # make a new reference ID\n refid = self._ref_id\n self._ref_id = self._ref_id + 1\n # replace the old list in-place, so that we don't have to track the\n # previous reference to it.\n aList[:] = [reference_atom, refid, newList]\n self.cooked[id(object)] = [dereference_atom, refid]\n return aList\n\n\n def prepare(self, object):\n \"\"\"\n (internal) Create a list for persisting an object to. This will allow\n backreferences to be made internal to the object. (circular\n references).\n\n The reason this needs to happen is that we don't generate an ID for\n every object, so we won't necessarily know which ID the object will\n have in the future. When it is 'cooked' ( see _cook ), it will be\n assigned an ID, and the temporary placeholder list created here will be\n modified in-place to create an expression that gives this object an ID:\n [reference id# [object-jelly]].\n \"\"\"\n\n # create a placeholder list to be preserved\n self.preserved[id(object)] = []\n # keep a reference to this object around, so it doesn't disappear!\n # (This isn't always necessary, but for cases where the objects are\n # dynamically generated by __getstate__ or getStateToCopyFor calls, it\n # is; id() will return the same value for a different object if it gets\n # garbage collected. This may be optimized later.)\n self.cooker[id(object)] = object\n return []\n\n\n def preserve(self, object, sexp):\n \"\"\"\n (internal) Mark an object's persistent list for later referral.\n \"\"\"\n # if I've been cooked in the meanwhile,\n if id(object) in self.cooked:\n # replace the placeholder empty list with the real one\n self.preserved[id(object)][2] = sexp\n # but give this one back.\n sexp = self.preserved[id(object)]\n else:\n self.preserved[id(object)] = sexp\n return sexp\n\n constantTypes = {types.StringType : 1, types.IntType : 1,\n types.FloatType : 1, types.LongType : 1}\n\n\n def _checkMutable(self,obj):\n objId = id(obj)\n if objId in self.cooked:\n return self.cooked[objId]\n if objId in self.preserved:\n self._cook(obj)\n return self.cooked[objId]\n\n\n def jelly(self, obj):\n if isinstance(obj, Jellyable):\n preRef = self._checkMutable(obj)\n if preRef:\n return preRef\n return obj.jellyFor(self)\n objType = type(obj)\n if self.taster.isTypeAllowed(qual(objType)):\n # \"Immutable\" Types\n if ((objType is StringType) or\n (objType is IntType) or\n (objType is LongType) or\n (objType is FloatType)):\n return obj\n elif objType is MethodType:\n return [\"method\",\n obj.im_func.__name__,\n self.jelly(obj.im_self),\n self.jelly(obj.im_class)]\n\n elif UnicodeType and objType is UnicodeType:\n return ['unicode', obj.encode('UTF-8')]\n elif objType is NoneType:\n return ['None']\n elif objType is FunctionType:\n name = obj.__name__\n return ['function', str(pickle.whichmodule(obj, obj.__name__))\n + '.' +\n name]\n elif objType is ModuleType:\n return ['module', obj.__name__]\n elif objType is BooleanType:\n return ['boolean', obj and 'true' or 'false']\n elif objType is datetime.datetime:\n if obj.tzinfo:\n raise NotImplementedError(\n \"Currently can't jelly datetime objects with tzinfo\")\n return ['datetime', '%s %s %s %s %s %s %s' % (\n obj.year, obj.month, obj.day, obj.hour,\n obj.minute, obj.second, obj.microsecond)]\n elif objType is datetime.time:\n if obj.tzinfo:\n raise NotImplementedError(\n \"Currently can't jelly datetime objects with tzinfo\")\n return ['time', '%s %s %s %s' % (obj.hour, obj.minute,\n obj.second, obj.microsecond)]\n elif objType is datetime.date:\n return ['date', '%s %s %s' % (obj.year, obj.month, obj.day)]\n elif objType is datetime.timedelta:\n return ['timedelta', '%s %s %s' % (obj.days, obj.seconds,\n obj.microseconds)]\n elif objType is ClassType or issubclass(objType, type):\n return ['class', qual(obj)]\n elif decimal is not None and objType is decimal.Decimal:\n return self.jelly_decimal(obj)\n else:\n preRef = self._checkMutable(obj)\n if preRef:\n return preRef\n # \"Mutable\" Types\n sxp = self.prepare(obj)\n if objType is ListType:\n sxp.extend(self._jellyIterable(list_atom, obj))\n elif objType is TupleType:\n sxp.extend(self._jellyIterable(tuple_atom, obj))\n elif objType in DictTypes:\n sxp.append(dictionary_atom)\n for key, val in obj.items():\n sxp.append([self.jelly(key), self.jelly(val)])\n elif (_set is not None and objType is set or\n objType is _sets.Set):\n sxp.extend(self._jellyIterable(set_atom, obj))\n elif (_set is not None and objType is frozenset or\n objType is _sets.ImmutableSet):\n sxp.extend(self._jellyIterable(frozenset_atom, obj))\n else:\n className = qual(obj.__class__)\n persistent = None\n if self.persistentStore:\n persistent = self.persistentStore(obj, self)\n if persistent is not None:\n sxp.append(persistent_atom)\n sxp.append(persistent)\n elif self.taster.isClassAllowed(obj.__class__):\n sxp.append(className)\n if hasattr(obj, \"__getstate__\"):\n state = obj.__getstate__()\n else:\n state = obj.__dict__\n sxp.append(self.jelly(state))\n else:\n self.unpersistable(\n \"instance of class %s deemed insecure\" %\n qual(obj.__class__), sxp)\n return self.preserve(obj, sxp)\n else:\n if objType is InstanceType:\n raise InsecureJelly(\"Class not allowed for instance: %s %s\" %\n (obj.__class__, obj))\n raise InsecureJelly(\"Type not allowed for object: %s %s\" %\n (objType, obj))\n\n\n def _jellyIterable(self, atom, obj):\n \"\"\"\n Jelly an iterable object.\n\n @param atom: the identifier atom of the object.\n @type atom: C{str}\n\n @param obj: any iterable object.\n @type obj: C{iterable}\n\n @return: a generator of jellied data.\n @rtype: C{generator}\n \"\"\"\n yield atom\n for item in obj:\n yield self.jelly(item)\n\n\n def jelly_decimal(self, d):\n \"\"\"\n Jelly a decimal object.\n\n @param d: a decimal object to serialize.\n @type d: C{decimal.Decimal}\n\n @return: jelly for the decimal object.\n @rtype: C{list}\n \"\"\"\n sign, guts, exponent = d.as_tuple()\n value = reduce(lambda left, right: left * 10 + right, guts)\n if sign:\n value = -value\n return ['decimal', value, exponent]\n\n\n def unpersistable(self, reason, sxp=None):\n \"\"\"\n (internal) Returns an sexp: (unpersistable \"reason\"). Utility method\n for making note that a particular object could not be serialized.\n \"\"\"\n if sxp is None:\n sxp = []\n sxp.append(unpersistable_atom)\n sxp.append(reason)\n return sxp\n\n\n\nclass _Unjellier:\n\n def __init__(self, taster, persistentLoad, invoker):\n self.taster = taster\n self.persistentLoad = persistentLoad\n self.references = {}\n self.postCallbacks = []\n self.invoker = invoker\n\n\n def unjellyFull(self, obj):\n o = self.unjelly(obj)\n for m in self.postCallbacks:\n m()\n return o\n\n\n def unjelly(self, obj):\n if type(obj) is not types.ListType:\n return obj\n jelType = obj[0]\n if not self.taster.isTypeAllowed(jelType):\n raise InsecureJelly(jelType)\n regClass = unjellyableRegistry.get(jelType)\n if regClass is not None:\n if isinstance(regClass, ClassType):\n inst = _Dummy() # XXX chomp, chomp\n inst.__class__ = regClass\n method = inst.unjellyFor\n elif isinstance(regClass, type):\n # regClass.__new__ does not call regClass.__init__\n inst = regClass.__new__(regClass)\n method = inst.unjellyFor\n else:\n method = regClass # this is how it ought to be done\n val = method(self, obj)\n if hasattr(val, 'postUnjelly'):\n self.postCallbacks.append(inst.postUnjelly)\n return val\n regFactory = unjellyableFactoryRegistry.get(jelType)\n if regFactory is not None:\n state = self.unjelly(obj[1])\n inst = regFactory(state)\n if hasattr(inst, 'postUnjelly'):\n self.postCallbacks.append(inst.postUnjelly)\n return inst\n thunk = getattr(self, '_unjelly_%s'%jelType, None)\n if thunk is not None:\n ret = thunk(obj[1:])\n else:\n nameSplit = jelType.split('.')\n modName = '.'.join(nameSplit[:-1])\n if not self.taster.isModuleAllowed(modName):\n raise InsecureJelly(\n \"Module %s not allowed (in type %s).\" % (modName, jelType))\n clz = namedObject(jelType)\n if not self.taster.isClassAllowed(clz):\n raise InsecureJelly(\"Class %s not allowed.\" % jelType)\n if hasattr(clz, \"__setstate__\"):\n ret = _newInstance(clz)\n state = self.unjelly(obj[1])\n ret.__setstate__(state)\n else:\n state = self.unjelly(obj[1])\n ret = _newInstance(clz, state)\n if hasattr(clz, 'postUnjelly'):\n self.postCallbacks.append(ret.postUnjelly)\n return ret\n\n\n def _unjelly_None(self, exp):\n return None\n\n\n def _unjelly_unicode(self, exp):\n if UnicodeType:\n return unicode(exp[0], \"UTF-8\")\n else:\n return Unpersistable(\"Could not unpersist unicode: %s\" % (exp[0],))\n\n\n def _unjelly_decimal(self, exp):\n \"\"\"\n Unjelly decimal objects, if decimal is available. If not, return a\n L{Unpersistable} object instead.\n \"\"\"\n if decimal is None:\n return Unpersistable(\n \"Could not unpersist decimal: %s\" % (exp[0] * (10**exp[1]),))\n value = exp[0]\n exponent = exp[1]\n if value < 0:\n sign = 1\n else:\n sign = 0\n guts = decimal.Decimal(value).as_tuple()[1]\n return decimal.Decimal((sign, guts, exponent))\n\n\n def _unjelly_boolean(self, exp):\n if BooleanType:\n assert exp[0] in ('true', 'false')\n return exp[0] == 'true'\n else:\n return Unpersistable(\"Could not unpersist boolean: %s\" % (exp[0],))\n\n\n def _unjelly_datetime(self, exp):\n return datetime.datetime(*map(int, exp[0].split()))\n\n\n def _unjelly_date(self, exp):\n return datetime.date(*map(int, exp[0].split()))\n\n\n def _unjelly_time(self, exp):\n return datetime.time(*map(int, exp[0].split()))\n\n\n def _unjelly_timedelta(self, exp):\n days, seconds, microseconds = map(int, exp[0].split())\n return datetime.timedelta(\n days=days, seconds=seconds, microseconds=microseconds)\n\n\n def unjellyInto(self, obj, loc, jel):\n o = self.unjelly(jel)\n if isinstance(o, NotKnown):\n o.addDependant(obj, loc)\n obj[loc] = o\n return o\n\n\n def _unjelly_dereference(self, lst):\n refid = lst[0]\n x = self.references.get(refid)\n if x is not None:\n return x\n der = _Dereference(refid)\n self.references[refid] = der\n return der\n\n\n def _unjelly_reference(self, lst):\n refid = lst[0]\n exp = lst[1]\n o = self.unjelly(exp)\n ref = self.references.get(refid)\n if (ref is None):\n self.references[refid] = o\n elif isinstance(ref, NotKnown):\n ref.resolveDependants(o)\n self.references[refid] = o\n else:\n assert 0, \"Multiple references with same ID!\"\n return o\n\n\n def _unjelly_tuple(self, lst):\n l = range(len(lst))\n finished = 1\n for elem in l:\n if isinstance(self.unjellyInto(l, elem, lst[elem]), NotKnown):\n finished = 0\n if finished:\n return tuple(l)\n else:\n return _Tuple(l)\n\n\n def _unjelly_list(self, lst):\n l = range(len(lst))\n for elem in l:\n self.unjellyInto(l, elem, lst[elem])\n return l\n\n\n def _unjellySetOrFrozenset(self, lst, containerType):\n \"\"\"\n Helper method to unjelly set or frozenset.\n\n @param lst: the content of the set.\n @type lst: C{list}\n\n @param containerType: the type of C{set} to use.\n \"\"\"\n l = range(len(lst))\n finished = True\n for elem in l:\n data = self.unjellyInto(l, elem, lst[elem])\n if isinstance(data, NotKnown):\n finished = False\n if not finished:\n return _Container(l, containerType)\n else:\n return containerType(l)\n\n\n def _unjelly_set(self, lst):\n \"\"\"\n Unjelly set using either the C{set} builtin if available, or\n C{sets.Set} as fallback.\n \"\"\"\n if _set is not None:\n containerType = set\n else:\n containerType = _sets.Set\n return self._unjellySetOrFrozenset(lst, containerType)\n\n\n def _unjelly_frozenset(self, lst):\n \"\"\"\n Unjelly frozenset using either the C{frozenset} builtin if available,\n or C{sets.ImmutableSet} as fallback.\n \"\"\"\n if _set is not None:\n containerType = frozenset\n else:\n containerType = _sets.ImmutableSet\n return self._unjellySetOrFrozenset(lst, containerType)\n\n\n def _unjelly_dictionary(self, lst):\n d = {}\n for k, v in lst:\n kvd = _DictKeyAndValue(d)\n self.unjellyInto(kvd, 0, k)\n self.unjellyInto(kvd, 1, v)\n return d\n\n\n def _unjelly_module(self, rest):\n moduleName = rest[0]\n if type(moduleName) != types.StringType:\n raise InsecureJelly(\n \"Attempted to unjelly a module with a non-string name.\")\n if not self.taster.isModuleAllowed(moduleName):\n raise InsecureJelly(\n \"Attempted to unjelly module named %r\" % (moduleName,))\n mod = __import__(moduleName, {}, {},\"x\")\n return mod\n\n\n def _unjelly_class(self, rest):\n clist = rest[0].split('.')\n modName = '.'.join(clist[:-1])\n if not self.taster.isModuleAllowed(modName):\n raise InsecureJelly(\"module %s not allowed\" % modName)\n klaus = namedObject(rest[0])\n objType = type(klaus)\n if objType not in (types.ClassType, types.TypeType):\n raise InsecureJelly(\n \"class %r unjellied to something that isn't a class: %r\" % (\n rest[0], klaus))\n if not self.taster.isClassAllowed(klaus):\n raise InsecureJelly(\"class not allowed: %s\" % qual(klaus))\n return klaus\n\n\n def _unjelly_function(self, rest):\n modSplit = rest[0].split('.')\n modName = '.'.join(modSplit[:-1])\n if not self.taster.isModuleAllowed(modName):\n raise InsecureJelly(\"Module not allowed: %s\"% modName)\n # XXX do I need an isFunctionAllowed?\n function = namedObject(rest[0])\n return function\n\n\n def _unjelly_persistent(self, rest):\n if self.persistentLoad:\n pload = self.persistentLoad(rest[0], self)\n return pload\n else:\n return Unpersistable(\"Persistent callback not found\")\n\n\n def _unjelly_instance(self, rest):\n clz = self.unjelly(rest[0])\n if type(clz) is not types.ClassType:\n raise InsecureJelly(\"Instance found with non-class class.\")\n if hasattr(clz, \"__setstate__\"):\n inst = _newInstance(clz, {})\n state = self.unjelly(rest[1])\n inst.__setstate__(state)\n else:\n state = self.unjelly(rest[1])\n inst = _newInstance(clz, state)\n if hasattr(clz, 'postUnjelly'):\n self.postCallbacks.append(inst.postUnjelly)\n return inst\n\n\n def _unjelly_unpersistable(self, rest):\n return Unpersistable(\"Unpersistable data: %s\" % (rest[0],))\n\n\n def _unjelly_method(self, rest):\n \"\"\"\n (internal) Unjelly a method.\n \"\"\"\n im_name = rest[0]\n im_self = self.unjelly(rest[1])\n im_class = self.unjelly(rest[2])\n if type(im_class) is not types.ClassType:\n raise InsecureJelly(\"Method found with non-class class.\")\n if im_name in im_class.__dict__:\n if im_self is None:\n im = getattr(im_class, im_name)\n elif isinstance(im_self, NotKnown):\n im = _InstanceMethod(im_name, im_self, im_class)\n else:\n im = instancemethod(im_class.__dict__[im_name],\n im_self,\n im_class)\n else:\n raise TypeError('instance method changed')\n return im\n\n\n\nclass _Dummy:\n \"\"\"\n (Internal) Dummy class, used for unserializing instances.\n \"\"\"\n\n\n\nclass _DummyNewStyle(object):\n \"\"\"\n (Internal) Dummy class, used for unserializing instances of new-style\n classes.\n \"\"\"\n\n\n\n#### Published Interface.\n\n\nclass InsecureJelly(Exception):\n \"\"\"\n This exception will be raised when a jelly is deemed `insecure'; e.g. it\n contains a type, class, or module disallowed by the specified `taster'\n \"\"\"\n\n\n\nclass DummySecurityOptions:\n \"\"\"\n DummySecurityOptions() -> insecure security options\n Dummy security options -- this class will allow anything.\n \"\"\"\n\n def isModuleAllowed(self, moduleName):\n \"\"\"\n DummySecurityOptions.isModuleAllowed(moduleName) -> boolean\n returns 1 if a module by that name is allowed, 0 otherwise\n \"\"\"\n return 1\n\n\n def isClassAllowed(self, klass):\n \"\"\"\n DummySecurityOptions.isClassAllowed(class) -> boolean\n Assumes the module has already been allowed. Returns 1 if the given\n class is allowed, 0 otherwise.\n \"\"\"\n return 1\n\n\n def isTypeAllowed(self, typeName):\n \"\"\"\n DummySecurityOptions.isTypeAllowed(typeName) -> boolean\n Returns 1 if the given type is allowed, 0 otherwise.\n \"\"\"\n return 1\n\n\n\nclass SecurityOptions:\n \"\"\"\n This will by default disallow everything, except for 'none'.\n \"\"\"\n\n basicTypes = [\"dictionary\", \"list\", \"tuple\",\n \"reference\", \"dereference\", \"unpersistable\",\n \"persistent\", \"long_int\", \"long\", \"dict\"]\n\n def __init__(self):\n \"\"\"\n SecurityOptions() initialize.\n \"\"\"\n # I don't believe any of these types can ever pose a security hazard,\n # except perhaps \"reference\"...\n self.allowedTypes = {\"None\": 1,\n \"bool\": 1,\n \"boolean\": 1,\n \"string\": 1,\n \"str\": 1,\n \"int\": 1,\n \"float\": 1,\n \"datetime\": 1,\n \"time\": 1,\n \"date\": 1,\n \"timedelta\": 1,\n \"NoneType\": 1}\n if hasattr(types, 'UnicodeType'):\n self.allowedTypes['unicode'] = 1\n if decimal is not None:\n self.allowedTypes['decimal'] = 1\n self.allowedTypes['set'] = 1\n self.allowedTypes['frozenset'] = 1\n self.allowedModules = {}\n self.allowedClasses = {}\n\n\n def allowBasicTypes(self):\n \"\"\"\n Allow all `basic' types. (Dictionary and list. Int, string, and float\n are implicitly allowed.)\n \"\"\"\n self.allowTypes(*self.basicTypes)\n\n\n def allowTypes(self, *types):\n \"\"\"\n SecurityOptions.allowTypes(typeString): Allow a particular type, by its\n name.\n \"\"\"\n for typ in types:\n if not isinstance(typ, str):\n typ = qual(typ)\n self.allowedTypes[typ] = 1\n\n\n def allowInstancesOf(self, *classes):\n \"\"\"\n SecurityOptions.allowInstances(klass, klass, ...): allow instances\n of the specified classes\n\n This will also allow the 'instance', 'class' (renamed 'classobj' in\n Python 2.3), and 'module' types, as well as basic types.\n \"\"\"\n self.allowBasicTypes()\n self.allowTypes(\"instance\", \"class\", \"classobj\", \"module\")\n for klass in classes:\n self.allowTypes(qual(klass))\n self.allowModules(klass.__module__)\n self.allowedClasses[klass] = 1\n\n\n def allowModules(self, *modules):\n \"\"\"\n SecurityOptions.allowModules(module, module, ...): allow modules by\n name. This will also allow the 'module' type.\n \"\"\"\n for module in modules:\n if type(module) == types.ModuleType:\n module = module.__name__\n self.allowedModules[module] = 1\n\n\n def isModuleAllowed(self, moduleName):\n \"\"\"\n SecurityOptions.isModuleAllowed(moduleName) -> boolean\n returns 1 if a module by that name is allowed, 0 otherwise\n \"\"\"\n return moduleName in self.allowedModules\n\n\n def isClassAllowed(self, klass):\n \"\"\"\n SecurityOptions.isClassAllowed(class) -> boolean\n Assumes the module has already been allowed. Returns 1 if the given\n class is allowed, 0 otherwise.\n \"\"\"\n return klass in self.allowedClasses\n\n\n def isTypeAllowed(self, typeName):\n \"\"\"\n SecurityOptions.isTypeAllowed(typeName) -> boolean\n Returns 1 if the given type is allowed, 0 otherwise.\n \"\"\"\n return (typeName in self.allowedTypes or '.' in typeName)\n\n\nglobalSecurity = SecurityOptions()\nglobalSecurity.allowBasicTypes()\n\n\n\ndef jelly(object, taster=DummySecurityOptions(), persistentStore=None,\n invoker=None):\n \"\"\"\n Serialize to s-expression.\n\n Returns a list which is the serialized representation of an object. An\n optional 'taster' argument takes a SecurityOptions and will mark any\n insecure objects as unpersistable rather than serializing them.\n \"\"\"\n return _Jellier(taster, persistentStore, invoker).jelly(object)\n\n\n\ndef unjelly(sexp, taster=DummySecurityOptions(), persistentLoad=None,\n invoker=None):\n \"\"\"\n Unserialize from s-expression.\n\n Takes an list that was the result from a call to jelly() and unserializes\n an arbitrary object from it. The optional 'taster' argument, an instance\n of SecurityOptions, will cause an InsecureJelly exception to be raised if a\n disallowed type, module, or class attempted to unserialize.\n \"\"\"\n return _Unjellier(taster, persistentLoad, invoker).unjellyFull(sexp)\n","sub_path":"python-modules/twisted/twisted/spread/jelly.py","file_name":"jelly.py","file_ext":"py","file_size_in_byte":36247,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"594486043","text":"import matplotlib.pyplot as plt\n\n# Makes a reasonable looking boxplot. Idea is to input [10,25,50,75,90] percentiles\n# to have that be the boxplot (even though the function is returning min and max instead\n# of 10th and 90th percentiles respectively).\n\ndef make_boxplot(data):\n \n # define \"figure\" and \"axes\" objects, where the \"axes\" is really my figure and\n # \"figure\" is the thing containing my figure. Annoying.\n \n fig, ax = plt.subplots()\n fig.set_size_inches(5,1)\n \n # Make the boxplot and get rid of borders I don't want.\n \n ax.boxplot(data,vert=False,widths=0.3)\n ax.spines['top'].set_visible(False)\n ax.spines['right'].set_visible(False)\n ax.spines['left'].set_visible(False)\n \n # Get rid of ticks.\n\n ax.xaxis.set_ticks_position('none')\n ax.yaxis.set_ticks_position('none')\n \n # Set scale of plot as roughly [0,(4/3)*max]\n\n upper_bound = max(data)*4/3\n \n # Scale the plot\n \n plt.xticks(range(0,upper_bound,upper_bound/7))\n \n # Maybe not necessary, but seems to make things look better for now\n \n plt.tight_layout()\n \n # Remove pointless y-axis labels in a hacky way\n \n ax.yaxis.set_ticklabels(' ')\n \n # Save the figure (untested)\n # Relevant: http://stackoverflow.com/questions/20107414/passing-a-matplotlib-figure-to-html-flask\n \n plt.savefig('figure.png',bbox_inches='tight')","sub_path":"justin/src/website/draw_boxplot.py","file_name":"draw_boxplot.py","file_ext":"py","file_size_in_byte":1401,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"195167053","text":"import sqlite3\nimport os\n\nclass Controller():\n # use this class to access the database to retrieve queries or add/update/delete entries\n \n def __init__(self, directory, database_file):\n \n self.database = os.path.join(directory, database_file)\n self.connection = sqlite3.connect(self.database)\n self.connection.row_factory = sqlite3.Row\n\n self.cursor = self.connection.cursor()\n self.cursor.execute(' PRAGMA forteign_keys=ON; ')","sub_path":"core/database/controller.py","file_name":"controller.py","file_ext":"py","file_size_in_byte":478,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"608599720","text":"# -*- coding: utf-8 -*-\nimport itertools\nimport json\nfrom presets import presets\n\n\nclass IncorrectArg(Exception):\n def __str__(self):\n return 'Argument \"' + str(self.args[0]) + \"' incorrect. \" + \\\n \"It must be in \" + str(self.args[1]) + \\\n \", but '\" + str(self.args[2]) + \"' given.\"\n\n\nclass gol(object):\n \"\"\"Create an iterated object, which returns next generation.\"\"\"\n\n def __init__(self, \n preset=None,\n first_generation=set([(3, 5), (4, 5), (5, 5), (3, 6), (4, 7)]),\n board_size=(20, 20),\n out_format='set',\n max_generation=200):\n\n #dict of the supported output formats\n self.supp_formats = {\n \"set\": lambda board: board,\n \"list\": lambda board: list(board),\n \"tuple\":lambda board: tuple(board),\n \"text\": lambda board: board.__repr__()[5:-2] + '\\n',\n \"json\": lambda board: json.dumps(list(board))\n }\n\n if preset:\n try:\n first_generation = presets[preset]['first_generation']\n board_size = presets[preset]['board_size']\n except KeyError:\n raise IncorrectArg(\"preset\", presets.keys(), preset)\n\n if isinstance(max_generation, int) and max_generation > 0:\n self.generation_counter = 1\n self.max_generation = max_generation\n\n self.last_gen = set()\n\n if not isinstance(board_size[0], int) or board_size[0] < 0 or \\\n not isinstance(board_size[1], int) or board_size[1] < 0:\n raise IncorrectArg(\"board_size\", \"natural numbers set\", board_size)\n self.max_x = board_size[0]\n self.max_y = board_size[1]\n\n for cell in first_generation:\n if not (0 <= cell[0] < board_size[0]) or \\\n not (0 <= cell[1] < board_size[1]):\n raise IncorrectArg(\"first_generation\", board_size, first_generation)\n self.current_gen = first_generation\n\n if not isinstance(out_format, basestring) or \\\n out_format not in self.supp_formats:\n raise IncorrectArg('out_format', self.supp_formats.keys(), out_format)\n self.out_format = out_format\n\n def neighbors(self, point):\n \"\"\"Returns generator object, that returns 8 neighbors of given cell\"\"\"\n x, y = point\n for i, j in itertools.product(range(-1, 2), repeat=2):\n if any((i, j)):\n neigh_x = x + i; neigh_y = y + j\n\n if (neigh_x < 0): neigh_x += self.max_x\n elif (neigh_x > self.max_x - 1): neigh_x -= self.max_x\n\n if (neigh_y < 0): neigh_y += self.max_y\n elif (neigh_y > self.max_y - 1): neigh_y -= self.max_y\n\n yield (neigh_x, neigh_y)\n\n def __iter__(self):\n return self\n\n def next(self):\n # stop after generation limit\n if (self.max_generation and self.generation_counter < self.max_generation) and \\\n (self.current_gen) and (self.current_gen != self.last_gen): # stop iteration if we have stil life\n self.last_gen = self.current_gen\n self.current_gen = set()\n\n #Calculate new generation\n recalc = self.last_gen | set(itertools.chain(*map(self.neighbors, self.last_gen)))\n for cell in recalc:\n count = sum((neigh in self.last_gen) \n for neigh in self.neighbors(cell))\n if count == 3 or (count == 2 and cell in self.last_gen):\n self.current_gen.add(cell)\n\n self.generation_counter += 1\n return self.supp_formats[self.out_format](self.current_gen) \n else:\n raise StopIteration\n","sub_path":"gol/gameoflife.py","file_name":"gameoflife.py","file_ext":"py","file_size_in_byte":3780,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"62331774","text":"import sys\nsys.path.append(\"/home/jesiner/Github/matrix/python\")\n\nfrom fitting import *\nfrom rs232 import *\n\n\n\n\n# define the function to get flow rate\ndef GetFlowRate(SER, SER_TYPE):\n # do the measurements\n print(\"\")\n intt = input(\"Please indicate how many seconds you want between each measurements:\")\n t_list, w_list = balance.GetFlowRate(SER, SER_TYPE, intt)\n # do the linear regression\n fitting = linear.linear_fit(t_list, w_list)\n print(fitting)\n","sub_path":"python/method/flow_rate_balance.py","file_name":"flow_rate_balance.py","file_ext":"py","file_size_in_byte":472,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"592888462","text":"# line_chart.py\n\nfrom openpyxl import Workbook\nfrom openpyxl.chart import LineChart, Reference\n\n\ndef create_excel_data(sheet):\n data_rows = [\n [\"Book\", \"Kindle\", \"Paperback\"],\n [1, 9.99, 25.99],\n [2, 9.99, 25.99],\n [3, 9.99, 25.99],\n [4, 4.99, 29.99],\n [5, 4.99, 29.99],\n [6, 24.99, 29.99],\n [7, 24.99, 65.00],\n [8, 24.99, 69.00],\n [9, 24.99, 69.00],\n ]\n\n for row in data_rows:\n sheet.append(row)\n\n\ndef create_line_chart(sheet):\n chart = LineChart()\n chart.title = \"Line Chart\"\n chart.style = 15\n chart.y_axis.title = 'Sales'\n chart.x_axis.title = 'Books'\n\n data = Reference(sheet, min_col=2, min_row=2, max_col=3, max_row=9)\n chart.add_data(data)\n\n sheet.add_chart(chart, \"E2\")\n\n\ndef main():\n workbook = Workbook()\n sheet = workbook.active\n create_excel_data(sheet)\n create_line_chart(sheet)\n workbook.save(\"line_chart.xlsx\")\n\n\nif __name__ == \"__main__\":\n main()","sub_path":"07_chart_types/line_chart.py","file_name":"line_chart.py","file_ext":"py","file_size_in_byte":991,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"529643634","text":"import cv2\nimport numpy as np\nimport sys\nimport os\nimport time\n\ndef genGaussiankernel(width, sigma):\n x = np.arange(-int(width/2), int(width/2)+1, 1, dtype=np.float32)\n x2d, y2d = np.meshgrid(x, x)\n kernel_2d = np.exp(-(x2d ** 2 + y2d ** 2) / (2 * sigma ** 2))\n kernel_2d = kernel_2d / np.sum(kernel_2d)\n return kernel_2d\n\ndef pyramid(im, sigma=1, prNum=6):\n height_ori, width_ori, ch = im.shape\n G = im.copy()\n pyramids = [G]\n \n # gaussian blur\n Gaus_kernel2D = genGaussiankernel(5, sigma)\n \n # downsample\n for i in range(1, prNum):\n G = cv2.filter2D(G, -1, Gaus_kernel2D)\n height, width, _ = G.shape\n G = cv2.resize(G, (int(width/2), int(height/2)))\n pyramids.append(G)\n \n \n # upsample\n for i in range(1, 6):\n curr_im = pyramids[i]\n for j in range(i):\n if j < i-1:\n im_size = (curr_im.shape[1]*2, curr_im.shape[0]*2)\n else:\n im_size = (width_ori, height_ori)\n curr_im = cv2.resize(curr_im, im_size)\n curr_im = cv2.filter2D(curr_im, -1, Gaus_kernel2D)\n pyramids[i] = curr_im\n\n return pyramids\n\ndef foveat_img(im, fixs):\n \"\"\"\n im: input image\n fixs: sequences of fixations of form [(x1, y1), (x2, y2), ...]\n \n This function outputs the foveated image with given input image and fixations.\n \"\"\"\n sigma=0.248\n prNum = 6\n As = pyramid(im, sigma, prNum)\n height, width, _ = im.shape\n \n # compute coef\n p = 1 # blur strength\n k = 3 # size of foveation\n alpha = 5 # also size?\n\n x = np.arange(0, width, 1, dtype=np.float32)\n y = np.arange(0, height, 1, dtype=np.float32)\n x2d, y2d = np.meshgrid(x, y)\n theta = np.sqrt((x2d - fixs[0][0]) ** 2 + (y2d - fixs[0][1]) ** 2) / p\n for fix in fixs[1:]:\n theta = np.minimum(theta, np.sqrt((x2d - fix[0]) ** 2 + (y2d - fix[1]) ** 2) / p)\n R = alpha / (theta + alpha)\n \n Ts = []\n for i in range(1, prNum):\n Ts.append(np.exp(-((2 ** (i-3)) * R / sigma) ** 2 * k))\n Ts.append(np.zeros_like(theta))\n\n # omega\n omega = np.zeros(prNum)\n for i in range(1, prNum):\n omega[i-1] = np.sqrt(np.log(2)/k) / (2**(i-3)) * sigma\n\n omega[omega>1] = 1\n\n # layer index\n layer_ind = np.zeros_like(R)\n for i in range(1, prNum):\n ind = np.logical_and(R >= omega[i], R <= omega[i - 1])\n layer_ind[ind] = i\n\n # B\n Bs = []\n for i in range(1, prNum):\n Bs.append((0.5 - Ts[i]) / (Ts[i-1] - Ts[i] + 1e-5))\n\n # M\n Ms = np.zeros((prNum, R.shape[0], R.shape[1]))\n\n for i in range(prNum):\n ind = layer_ind == i\n if np.sum(ind) > 0:\n if i == 0:\n Ms[i][ind] = 1\n else:\n Ms[i][ind] = 1 - Bs[i-1][ind]\n\n ind = layer_ind - 1 == i\n if np.sum(ind) > 0:\n Ms[i][ind] = Bs[i][ind]\n\n print('num of full-res pixel', np.sum(Ms[0] == 1))\n # generate periphery image\n im_fov = np.zeros_like(As[0], dtype=np.float32)\n for M, A in zip(Ms, As):\n for i in range(3):\n im_fov[:, :, i] += np.multiply(M, A[:, :, i])\n\n im_fov = im_fov.astype(np.uint8)\n return im_fov\n\n\"\"\"\nOriginal __main__\n\"\"\"\n# if __name__ == \"__main__\":\n# if len(sys.argv) != 2:\n# print(\"Wrong format: python retina_transform.py [image_path]\")\n# exit(-1)\n\n# im_path = sys.argv[1]\n# im = cv2.imread(im_path)\n# print(im)\n# # im = cv2.resize(im, (512, 320), cv2.INTER_CUBIC)\n# xc, yc = int(im.shape[1]/2), int(im.shape[0]/2)\n\n# im = foveat_img(im, [(xc, yc)])\n\n# cv2.imwrite(im_path.split('.')[0]+'_RT.jpg', im)\n\n\"\"\"\nJohan's __main__\n\"\"\" \n\n# # TODO given I use resizing and cropping no need to repeat this function for every image\n# def fill_fov(im):\n# fov_points = []\n# indices = []\n\n# # loop over the image row by row\n# for i in range(1, 10, 2):\n# for j in range(1, 10, 2):\n# indices.append((i,j))\n# fov_points.append((int(im.shape[1]*(i/10)), int(im.shape[0]*(j/10))))\n\n# # also return indices because those are needed to correctly name the output files\n# return indices, fov_points\n\n# if __name__ == \"__main__\":\n# if len(sys.argv) != 2:\n# print(\"Wrong format: python retina_transform.py [image_path]\")\n# exit(-1)\n\n# folder_path = sys.argv[1]\n# im_paths = os.listdir(folder_path) \n\n# # image transformation - parameters\n# # this is needed because otherwise foveation point outside of cropped area\n# input_size = 224\n# resize_size = int(input_size/0.875) #256 for input_size 224\n# margin = int((resize_size - input_size)/2)\n\n# for im_path in im_paths:\n# start = time.time()\n# im = cv2.imread(folder_path + '/' + im_path)\n\n# # image transformation - application\n# resized_im = cv2.resize(im, (256, 256))\n# cropped_im = resized_im[margin:-margin, margin:-margin]\n\n# dirname = folder_path + '/' + im_path.split('.')[0]\n# os.mkdir(dirname)\n\n \n\n# indices, fov_points = fill_fov(cropped_im)\n\n# for i, fov_point in enumerate(fov_points):\n# xc, yc = fov_point\n# temp = foveat_img(cropped_im, [(xc, yc)])\n# #adding a red dot so that spotting the foveation point is easier\n# #cv2.circle(temp, (xc, yc), 5, (0, 0, 255) , -1)\n\n# # TODO make sure the filenames are more robust\n# # for the specific application of a pytorch dataloader, make sure the names are getting ordered correctly.\n# cv2.imwrite(dirname + '/' + im_path.split('.')[0] + '_' + str(indices[i]) +'_RT.jpg', temp)\n\n# end = time.time()\n# print(\"done with: \" + im_path + \" in \" + str(end-start) + \" seconds.\")\n\n\"\"\"\nSecond main\n\"\"\"\n \n\nif __name__ == \"__main__\":\n if len(sys.argv) != 2:\n print(\"Wrong format: python retina_transform.py [image_path]\")\n exit(-1)\n\n folder_path = sys.argv[1]\n im_paths = os.listdir(folder_path) \n\n # image transformation - parameters\n # this is needed because otherwise foveation point outside of cropped area\n input_size = 224\n resize_size = int(input_size/0.875) #256 for input_size 224\n margin = int((resize_size - input_size)/2)\n\n # dirname = 'E:\\\\ILSVRC2017\\\\newimages\\\\notfoveated\\\\n01531178'\n dirname = 'E:\\ILSVRC2017\\multiplefoveationsTEST\\\\result'\n os.mkdir(dirname)\n\n for im_path in im_paths:\n start = time.time()\n im = cv2.imread(folder_path + '/' + im_path)\n\n # image transformation - application\n resized_im = cv2.resize(im, (256, 256))\n cropped_im = resized_im[margin:-margin, margin:-margin]\n\n # xc, yc = int(cropped_im.shape[1]/2), int(cropped_im.shape[0]/2)\n # foveated_im = foveat_img(cropped_im, [(xc, yc)])\n # cv2.imwrite(dirname + '/' + im_path.split('.')[0] + '.jpg', cropped_im)\n\n xc1, yc1 = (int(cropped_im.shape[1]*(5/10)), int(cropped_im.shape[0]*(5/10)))\n xc2, yc2 = (int(cropped_im.shape[1]*(7/10)), int(cropped_im.shape[0]*(5/10)))\n\n # foveated_im = foveat_img(cropped_im, [(xc1, yc1)])\n # cv2.circle(foveated_im, (xc1, yc1), 5, (0, 0, 255) , -1)\n # cv2.imwrite(dirname + '/' + im_path.split('.')[0] + '_1.jpg', foveated_im)\n\n # foveated_im = foveat_img(cropped_im, [(xc1, yc1), (xc2, yc2)])\n # cv2.circle(foveated_im, (xc1, yc1), 5, (0, 0, 255) , -1)\n # cv2.circle(foveated_im, (xc2, yc2), 5, (0, 0, 255) , -1)\n # cv2.imwrite(dirname + '/' + im_path.split('.')[0] + '_2.jpg', foveated_im)\n \n # cv2.imwrite(dirname + '/' + im_path.split('.')[0] + '_RT.jpg', foveated_im)\n\n\n end = time.time()\n print(\"done with: \" + im_path + \" in \" + str(end-start) + \" seconds.\")","sub_path":"retina_transform.py","file_name":"retina_transform.py","file_ext":"py","file_size_in_byte":7830,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"408759352","text":"import numpy as np\r\nimport math\r\nfrom scipy.optimize import minimize\r\n\r\n\r\ndef f(x):\r\n\tA=x[0]\r\n\tn=x[1]\r\n\tmE=x[2]\r\n\tsigma=x[3]\r\n\tT=473\r\n\tE = np.arange(10, 150, 1)\r\n\tfE = np.zeros(len(E))\r\n\tfor i in range(len(E)):\r\n\t\tfE[i] = ((1/math.sqrt(2*math.pi*sigma**2)) *math.exp(-((E[i]-mE)**2)/(2*sigma**2)))\r\n\r\n\tt = np.array([0, 15, 30, 45, 60, 120, 180, 240, 300, 596, 1200, 1800])\r\n\r\n\tzeta1 = np.zeros(t.size*E.size)\r\n\tzeta = zeta1.reshape(t.size, E.size)\r\n\r\n\tfor i in range(t.size):\r\n\t for j in range(E.size):\r\n\t zeta[i, j] = t[i]*math.exp((-(E[j]*1000)/(8.31*T)))\r\n\r\n\tzeta2 = (1-(1-n)*A*(10**8)*zeta)**(1/(1-n))\r\n\tfinal = zeta2@fE\r\n\r\n\tW1 = np.array([1, 0.775, 0.659, 0.6, 0.577, 0.472,0.418, 0.307, 0.177, 0.139, 0.082, 0])\r\n\tresult1=(W1-final)**2\r\n\tobj=result1.sum()\r\n\treturn obj\r\n\r\na=minimize(f,[30,5,70,15],method=\"Nelder-Mead\")\r\nprint(a)\r\n","sub_path":"optimization1204.py","file_name":"optimization1204.py","file_ext":"py","file_size_in_byte":841,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"176465473","text":"import json\nimport os\n\nimport requests\nfrom django.conf import settings\n\nfrom rest_framework import response, request, status, views\nfrom . import serializer, models, geocoder\n\n\nclass GeoObject(views.APIView):\n serializer_class = serializer.GeoBase\n\n def get(self, request: request.Request, geobase: models.Geobase):\n serializer_obj = self.serializer_class(data=geobase.dict())\n if not serializer_obj.is_valid():\n return response.Response(serializer_obj.errors, status=status.HTTP_400_BAD_REQUEST)\n\n return response.Response(serializer_obj.validated_data)\n\n\nclass Search(views.APIView):\n serializer_class = serializer.Search\n\n def get(self, request: request.Request):\n serializer_obj = self.serializer_class(data=request.GET)\n if not serializer_obj.is_valid():\n return response.Response(serializer_obj.errors, status=status.HTTP_400_BAD_REQUEST)\n\n result = geocoder.geo(query=serializer_obj.validated_data.get('query'))\n if result:\n return response.Response(result.dict())\n else:\n return response.Response({}, status=status.HTTP_404_NOT_FOUND)\n\n\nclass Suggestion(views.APIView):\n serializer_class = serializer.Search\n\n def get(self, request: request.Request):\n serializer_obj = self.serializer_class(data=request.GET)\n if not serializer_obj.is_valid():\n return response.Response(serializer_obj.errors, status=status.HTTP_400_BAD_REQUEST)\n\n data_key = getattr(settings, 'GEOBASE_DADATA', os.environ.get('GEOBASE_DADATA'))\n if not data_key:\n raise Exception(\"not found key GEOBASE_DADATA\")\n\n data = {\"query\": serializer_obj.validated_data.get('query'), \"count\": 10, \"restrict_value\": True}\n\n locations = []\n if serializer_obj.validated_data.get('locality') and serializer_obj.validated_data.get('street'):\n street = serializer_obj.validated_data.get('street')\n street = street.replace(\"проспект\", \"\")\n\n locations.append({\n \"city\": serializer_obj.validated_data.get('locality'),\n \"street\": street,\n })\n elif serializer_obj.validated_data.get('locality'):\n locations.append({\"city\": serializer_obj.validated_data.get('locality')})\n\n if locations:\n data.update({\"locations\": locations})\n\n res = requests.post(\n url=\"https://suggestions.dadata.ru/suggestions/api/4_1/rs/suggest/address\",\n data=json.dumps(data),\n headers={\n 'Authorization': \"Token {token}\".format(token=data_key),\n 'Content-Type': \"application/json\",\n 'Accept': \"application/json\",\n }\n )\n\n dadata = []\n if 'suggestions' in res.json():\n for item in res.json().get('suggestions'):\n\n # geo_res = []\n # if item.get('data').get('country'):\n # geo_res.append(\"{country}\".format(country=item.get('data').get('country')))\n #\n # if item.get('data').get('region'):\n # geo_res.append(\"{region}\".format(region=item.get('data').get('region')))\n #\n # if item.get('data').get('city'):\n # geo_res.append(\"{city}\".format(city=item.get('data').get('city')))\n #\n # if item.get('data').get('street'):\n # geo_res.append(\"{street}\".format(street=item.get('data').get('street')))\n #\n # if item.get('data').get('house'):\n # geo_res.append(\"{house}\".format(house=item.get('data').get('house')))\n #\n # if item.get('data').get('block_type_full'):\n # geo_res.append(\"{block_type_full}\".format(block_type_full=item.get('data').get('block_type_full')))\n #\n # if item.get('data').get('block'):\n # geo_res.append(\"{block}\".format(block=item.get('data').get('block')))\n # \", \".join(geo_res)\n\n #res = geocoder.geo(query=item.get('unrestricted_value'))\n #if res:\n #dadata.append(res.dict())\n\n #print(res.dict())\n dadata.append({\n 'value': item.get('value'),\n 'unrestricted_value': item.get('unrestricted_value'),\n 'country': item.get('data').get('country'),\n 'province': item.get('data').get('region'),\n 'locality': item.get('data').get('city'),\n 'street': item.get('data').get('street'),\n 'house': item.get('data').get('house'),\n })\n\n return response.Response({'result': dadata})\n","sub_path":"django_tasker_geobase/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":4834,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"57128973","text":"\"\"\"\n\nGeneral cube method tests against both\n- 0.4.0-style ImageCollectionClient\n- 1.0.0-style DataCube\n\n\"\"\"\n\nfrom datetime import date, datetime\n\nimport numpy as np\nimport pytest\nimport shapely\nimport shapely.geometry\n\nfrom openeo.capabilities import ComparableVersion\nfrom openeo.rest import BandMathException\nfrom openeo.rest.datacube import DataCube\nfrom openeo.rest.imagecollectionclient import ImageCollectionClient\nfrom openeo.rest.service import Service\nfrom .. import get_download_graph\nfrom ..conftest import reset_graphbuilder\nfrom .conftest import API_URL\nfrom ... import load_json_resource\n\n\ndef test_apply_dimension_temporal_cumsum(s2cube, api_version):\n cumsum = s2cube.apply_dimension('cumsum', dimension=\"t\")\n actual_graph = get_download_graph(cumsum)\n expected_graph = load_json_resource('data/{v}/apply_dimension_temporal_cumsum.json'.format(v=api_version))\n assert actual_graph == expected_graph\n\n\ndef test_apply_dimension_invalid_dimension(s2cube):\n with pytest.raises(ValueError, match=\"Invalid dimension\"):\n s2cube.apply_dimension('cumsum', dimension=\"olapola\")\n\n\ndef test_min_time(s2cube, api_version):\n min_time = s2cube.min_time()\n actual_graph = get_download_graph(min_time)\n expected_graph = load_json_resource('data/{v}/min_time.json'.format(v=api_version))\n assert actual_graph == expected_graph\n\n\ndef _get_leaf_node(cube, force_flat=True) -> dict:\n \"\"\"Get leaf node (node with result=True), supporting old and new style of graph building.\"\"\"\n if isinstance(cube, ImageCollectionClient):\n return cube.graph[cube.node_id]\n elif isinstance(cube, DataCube):\n if force_flat:\n flat_graph = cube.flat_graph()\n node, = [n for n in flat_graph.values() if n.get(\"result\")]\n return node\n else:\n return cube._pg.to_dict()\n else:\n raise ValueError(repr(cube))\n\n\ndef test_date_range_filter(s2cube):\n im = s2cube.date_range_filter(\"2016-01-01\", \"2016-03-10\")\n graph = _get_leaf_node(im)\n assert graph['process_id'] == 'filter_temporal'\n assert graph['arguments']['extent'] == [\"2016-01-01\", \"2016-03-10\"]\n\n\ndef test_filter_daterange(s2cube):\n im = s2cube.filter_daterange(extent=(\"2016-01-01\", \"2016-03-10\"))\n graph = _get_leaf_node(im)\n assert graph['process_id'] == 'filter_temporal'\n assert graph['arguments']['extent'] == [\"2016-01-01\", \"2016-03-10\"]\n\n\ndef test_filter_temporal(s2cube):\n im = s2cube.filter_temporal(\"2016-01-01\", \"2016-03-10\")\n graph = _get_leaf_node(im)\n assert graph['process_id'] == 'filter_temporal'\n assert graph['arguments']['extent'] == [\"2016-01-01\", \"2016-03-10\"]\n\n\ndef test_filter_temporal_start_end(s2cube):\n im = s2cube.filter_temporal(start_date=\"2016-01-01\", end_date=\"2016-03-10\")\n graph = _get_leaf_node(im)\n assert graph['process_id'] == 'filter_temporal'\n assert graph['arguments']['extent'] == [\"2016-01-01\", \"2016-03-10\"]\n\n\ndef test_filter_temporal_extent(s2cube):\n im = s2cube.filter_temporal(extent=(\"2016-01-01\", \"2016-03-10\"))\n graph = _get_leaf_node(im)\n assert graph['process_id'] == 'filter_temporal'\n assert graph['arguments']['extent'] == [\"2016-01-01\", \"2016-03-10\"]\n\n\n@pytest.mark.parametrize(\"args,kwargs,extent\", [\n ((), {}, [None, None]),\n ((\"2016-01-01\",), {}, [\"2016-01-01\", None]),\n ((\"2016-01-01\", \"2016-03-10\"), {}, [\"2016-01-01\", \"2016-03-10\"]),\n ((date(2016, 1, 1), date(2016, 3, 10)), {}, [\"2016-01-01\", \"2016-03-10\"]),\n ((datetime(2016, 1, 1, 12, 34), datetime(2016, 3, 10, 23, 45)), {},\n [\"2016-01-01T12:34:00Z\", \"2016-03-10T23:45:00Z\"]),\n ((), {\"start_date\": \"2016-01-01\", \"end_date\": \"2016-03-10\"}, [\"2016-01-01\", \"2016-03-10\"]),\n ((), {\"start_date\": \"2016-01-01\"}, [\"2016-01-01\", None]),\n ((), {\"end_date\": \"2016-03-10\"}, [None, \"2016-03-10\"]),\n ((), {\"start_date\": date(2016, 1, 1), \"end_date\": date(2016, 3, 10)}, [\"2016-01-01\", \"2016-03-10\"]),\n ((), {\"start_date\": datetime(2016, 1, 1, 12, 34), \"end_date\": datetime(2016, 3, 10, 23, 45)},\n [\"2016-01-01T12:34:00Z\", \"2016-03-10T23:45:00Z\"]),\n ((), {\"extent\": (\"2016-01-01\", \"2016-03-10\")}, [\"2016-01-01\", \"2016-03-10\"]),\n ((), {\"extent\": (\"2016-01-01\", None)}, [\"2016-01-01\", None]),\n ((), {\"extent\": (None, \"2016-03-10\")}, [None, \"2016-03-10\"]),\n ((), {\"extent\": (date(2016, 1, 1), date(2016, 3, 10))}, [\"2016-01-01\", \"2016-03-10\"]),\n ((), {\"extent\": (datetime(2016, 1, 1, 12, 34), datetime(2016, 3, 10, 23, 45))},\n [\"2016-01-01T12:34:00Z\", \"2016-03-10T23:45:00Z\"]),\n])\ndef test_filter_temporal_generic(s2cube, args, kwargs, extent):\n im = s2cube.filter_temporal(*args, **kwargs)\n graph = _get_leaf_node(im)\n assert graph['process_id'] == 'filter_temporal'\n assert graph['arguments']['extent'] == extent\n\n\ndef test_load_collection_bands_name(connection, api_version):\n im = connection.load_collection(\"S2\", bands=[\"B08\", \"B04\"])\n expected = load_json_resource('data/{v}/load_collection_bands.json'.format(v=api_version))\n assert im.graph == expected\n\n\ndef test_load_collection_bands_single_band(connection, api_version):\n im = connection.load_collection(\"S2\", bands=\"B08\")\n expected = load_json_resource('data/{v}/load_collection_bands.json'.format(v=api_version))\n expected[\"loadcollection1\"][\"arguments\"][\"bands\"] = [\"B08\"]\n assert im.graph == expected\n\n\ndef test_load_collection_bands_common_name(connection, api_version):\n im = connection.load_collection(\"S2\", bands=[\"nir\", \"red\"])\n expected = load_json_resource('data/{v}/load_collection_bands.json'.format(v=api_version))\n if api_version < ComparableVersion(\"1.0.0\"):\n expected[\"loadcollection1\"][\"arguments\"][\"bands\"] = [\"B08\", \"B04\"]\n else:\n expected[\"loadcollection1\"][\"arguments\"][\"bands\"] = [\"nir\", \"red\"]\n assert im.graph == expected\n\n\ndef test_load_collection_bands_band_index(connection, api_version):\n im = connection.load_collection(\"S2\", bands=[3, 2])\n expected = load_json_resource('data/{v}/load_collection_bands.json'.format(v=api_version))\n assert im.graph == expected\n\n\ndef test_load_collection_bands_and_band_math(connection, api_version):\n cube = connection.load_collection(\"S2\", bands=[\"B03\", \"B04\"])\n b4 = cube.band(\"B04\")\n b3 = cube.band(\"B03\")\n x = b4 - b3\n expected = load_json_resource('data/{v}/load_collection_bands_and_band_math.json'.format(v=api_version))\n assert x.graph == expected\n\n\ndef test_filter_bands_name(s2cube, api_version):\n im = s2cube.filter_bands([\"B08\", \"B04\"])\n expected = load_json_resource('data/{v}/filter_bands.json'.format(v=api_version))\n expected[\"filterbands1\"][\"arguments\"][\"bands\"] = [\"B08\", \"B04\"]\n assert im.graph == expected\n\n\ndef test_filter_bands_single_band(s2cube, api_version):\n im = s2cube.filter_bands(\"B08\")\n expected = load_json_resource('data/{v}/filter_bands.json'.format(v=api_version))\n expected[\"filterbands1\"][\"arguments\"][\"bands\"] = [\"B08\"]\n assert im.graph == expected\n\n\ndef test_filter_bands_common_name(s2cube, api_version):\n im = s2cube.filter_bands([\"nir\", \"red\"])\n expected = load_json_resource('data/{v}/filter_bands.json'.format(v=api_version))\n if api_version < ComparableVersion(\"1.0.0\"):\n expected[\"filterbands1\"][\"arguments\"][\"bands\"] = []\n expected[\"filterbands1\"][\"arguments\"][\"common_names\"] = [\"nir\", \"red\"]\n else:\n expected[\"filterbands1\"][\"arguments\"][\"bands\"] = [\"nir\", \"red\"]\n assert im.graph == expected\n\n\ndef test_filter_bands_index(s2cube, api_version):\n im = s2cube.filter_bands([3, 2])\n expected = load_json_resource('data/{v}/filter_bands.json'.format(v=api_version))\n expected[\"filterbands1\"][\"arguments\"][\"bands\"] = [\"B08\", \"B04\"]\n assert im.graph == expected\n\n\ndef test_pipe(s2cube, api_version):\n def ndvi_percent(cube):\n return cube.ndvi().linear_scale_range(0, 1, 0, 100)\n\n im = s2cube.pipe(ndvi_percent)\n assert im.graph == load_json_resource('data/{v}/pipe.json'.format(v=api_version))\n\n\ndef test_pipe_with_args(s2cube):\n def ndvi_scaled(cube, in_max=2, out_max=3):\n return cube.ndvi().linear_scale_range(0, in_max, 0, out_max)\n\n reset_graphbuilder()\n im = s2cube.pipe(ndvi_scaled)\n assert im.graph[\"linearscalerange1\"][\"arguments\"] == {\n 'inputMax': 2, 'inputMin': 0, 'outputMax': 3, 'outputMin': 0, 'x': {'from_node': 'ndvi1'}\n }\n reset_graphbuilder()\n im = s2cube.pipe(ndvi_scaled, 4, 5)\n assert im.graph[\"linearscalerange1\"][\"arguments\"] == {\n 'inputMax': 4, 'inputMin': 0, 'outputMax': 5, 'outputMin': 0, 'x': {'from_node': 'ndvi1'}\n }\n reset_graphbuilder()\n im = s2cube.pipe(ndvi_scaled, out_max=7)\n assert im.graph[\"linearscalerange1\"][\"arguments\"] == {\n 'inputMax': 2, 'inputMin': 0, 'outputMax': 7, 'outputMin': 0, 'x': {'from_node': 'ndvi1'}\n }\n\n\ndef test_filter_bbox(s2cube):\n im = s2cube.filter_bbox(\n west=652000, east=672000, north=5161000, south=5181000, crs=\"EPSG:32632\"\n )\n graph = _get_leaf_node(im)\n assert graph[\"process_id\"] == \"filter_bbox\"\n assert graph[\"arguments\"][\"extent\"] == {\n \"west\": 652000, \"east\": 672000, \"north\": 5161000, \"south\": 5181000, \"crs\": \"EPSG:32632\"\n }\n\n\ndef test_filter_bbox_base_height(s2cube):\n im = s2cube.filter_bbox(\n west=652000, east=672000, north=5161000, south=5181000, crs=\"EPSG:32632\",\n base=100, height=200,\n )\n graph = _get_leaf_node(im)\n assert graph[\"process_id\"] == \"filter_bbox\"\n assert graph[\"arguments\"][\"extent\"] == {\n \"west\": 652000, \"east\": 672000, \"north\": 5161000, \"south\": 5181000, \"crs\": \"EPSG:32632\",\n \"base\": 100, \"height\": 200,\n }\n\n\ndef test_bbox_filter_nsew(s2cube):\n im = s2cube.bbox_filter(\n west=652000, east=672000, north=5161000, south=5181000, crs=\"EPSG:32632\"\n )\n graph = _get_leaf_node(im)\n assert graph[\"process_id\"] == \"filter_bbox\"\n assert graph[\"arguments\"][\"extent\"] == {\n \"west\": 652000, \"east\": 672000, \"north\": 5161000, \"south\": 5181000, \"crs\": \"EPSG:32632\"\n }\n\n\ndef test_bbox_filter_tblr(s2cube):\n im = s2cube.bbox_filter(\n left=652000, right=672000, top=5161000, bottom=5181000, srs=\"EPSG:32632\"\n )\n graph = _get_leaf_node(im)\n assert graph[\"process_id\"] == \"filter_bbox\"\n assert graph[\"arguments\"][\"extent\"] == {\n \"west\": 652000, \"east\": 672000, \"north\": 5161000, \"south\": 5181000, \"crs\": \"EPSG:32632\"\n }\n\n\ndef test_bbox_filter_nsew_zero(s2cube):\n im = s2cube.bbox_filter(\n west=0, east=0, north=0, south=0, crs=\"EPSG:32632\"\n )\n graph = _get_leaf_node(im)\n assert graph[\"process_id\"] == \"filter_bbox\"\n assert graph[\"arguments\"][\"extent\"] == {\n \"west\": 0, \"east\": 0, \"north\": 0, \"south\": 0, \"crs\": \"EPSG:32632\"\n }\n\n\ndef test_max_time(s2cube, api_version):\n im = s2cube.max_time()\n graph = _get_leaf_node(im, force_flat=True)\n assert graph[\"process_id\"] == \"reduce\" if api_version == '0.4.0' else 'reduce_dimension'\n assert graph[\"arguments\"][\"data\"] == {'from_node': 'loadcollection1'}\n assert graph[\"arguments\"][\"dimension\"] == \"t\"\n if api_version == '0.4.0':\n callback = graph[\"arguments\"][\"reducer\"][\"callback\"][\"r1\"]\n assert callback == {'arguments': {'data': {'from_argument': 'data'}}, 'process_id': 'max', 'result': True}\n else:\n callback = graph[\"arguments\"][\"reducer\"][\"process_graph\"][\"max1\"]\n assert callback == {'arguments': {'data': {'from_parameter': 'data'}}, 'process_id': 'max', 'result': True}\n\n\ndef test_reduce_temporal_udf(s2cube, api_version):\n im = s2cube.reduce_temporal_udf(\"my custom code\")\n graph = _get_leaf_node(im)\n assert graph[\"process_id\"] == \"reduce\" if api_version == '0.4.0' else 'reduce_dimension'\n assert \"data\" in graph[\"arguments\"]\n assert graph[\"arguments\"][\"dimension\"] == \"t\"\n\n\ndef test_ndvi(s2cube, api_version):\n im = s2cube.ndvi()\n graph = _get_leaf_node(im)\n assert graph[\"process_id\"] == \"ndvi\"\n if api_version == '0.4.0':\n assert graph[\"arguments\"] == {'data': {'from_node': 'loadcollection1'}, 'name': 'ndvi'}\n else:\n assert graph[\"arguments\"] == {'data': {'from_node': 'loadcollection1'}}\n\n\ndef test_mask_polygon(s2cube, api_version):\n polygon = shapely.geometry.Polygon([[0, 0], [1.9, 0], [1.9, 1.9], [0, 1.9]])\n if api_version < ComparableVersion(\"1.0.0\"):\n expected_proces_id = \"mask\"\n im = s2cube.mask(polygon)\n else:\n expected_proces_id = \"mask_polygon\"\n im = s2cube.mask_polygon(mask=polygon)\n graph = _get_leaf_node(im)\n assert graph[\"process_id\"] == expected_proces_id\n assert graph[\"arguments\"] == {\n \"data\": {'from_node': 'loadcollection1'},\n \"mask\": {\n 'type': 'Polygon',\n 'coordinates': (((0.0, 0.0), (1.9, 0.0), (1.9, 1.9), (0.0, 1.9), (0.0, 0.0)),),\n }\n }\n\n\ndef test_mask_raster(s2cube, connection, api_version):\n mask = connection.load_collection(\"MASK\")\n if api_version == '0.4.0':\n im = s2cube.mask(rastermask=mask, replacement=102)\n else:\n im = s2cube.mask(mask=mask, replacement=102)\n graph = _get_leaf_node(im)\n assert graph == {\n \"process_id\": \"mask\",\n \"arguments\": {\n \"data\": {\n \"from_node\": \"loadcollection1\"\n },\n \"mask\": {\n \"from_node\": \"loadcollection3\" if api_version == '0.4.0' else \"loadcollection2\"\n },\n \"replacement\": 102\n },\n \"result\": False if api_version == '0.4.0' else True\n }\n\n\ndef test_apply_kernel(s2cube):\n kernel = [[0, 1, 0], [1, 1, 1], [0, 1, 0]]\n im = s2cube.apply_kernel(np.asarray(kernel), 3)\n graph = _get_leaf_node(im)\n assert graph[\"process_id\"] == \"apply_kernel\"\n assert graph[\"arguments\"] == {\n 'data': {'from_node': 'loadcollection1'},\n 'factor': 3,\n 'border': 0,\n 'replace_invalid': 0,\n 'kernel': [[0, 1, 0], [1, 1, 1], [0, 1, 0]]\n }\n\n\ndef test_resample_spatial(s2cube):\n im = s2cube.resample_spatial(resolution=[2.0, 3.0], projection=4578)\n graph = _get_leaf_node(im)\n assert graph[\"process_id\"] == \"resample_spatial\"\n assert \"data\" in graph[\"arguments\"]\n assert graph[\"arguments\"][\"resolution\"] == [2.0, 3.0]\n assert graph[\"arguments\"][\"projection\"] == 4578\n\n\ndef test_merge(s2cube, api_version):\n merged = s2cube.ndvi().merge(s2cube)\n expected_graph = load_json_resource('data/{v}/merge_ndvi_self.json'.format(v=api_version))\n assert merged.graph == expected_graph\n\n\ndef test_apply_absolute_str(s2cube, api_version):\n result = s2cube.apply(\"absolute\")\n expected_graph = load_json_resource('data/{v}/apply_absolute.json'.format(v=api_version))\n assert result.graph == expected_graph\n\n\ndef test_subtract_dates_ep3129(s2cube, api_version):\n \"\"\"EP-3129: band math between cubes of different time stamps is not supported (yet?)\"\"\"\n bbox = {\"west\": 5.16, \"south\": 51.23, \"east\": 5.18, \"north\": 51.25, \"crs\": \"EPSG:4326\"}\n date1 = \"2018-08-01\"\n date2 = \"2019-10-28\"\n im1 = s2cube.filter_temporal(date1, date1).filter_bbox(**bbox).band('B04')\n im2 = s2cube.filter_temporal(date2, date2).filter_bbox(**bbox).band('B04')\n\n with pytest.raises(BandMathException, match=\"between bands of different\"):\n im2.subtract(im1)\n\n\ndef test_tiled_viewing_service(s2cube, connection, requests_mock, api_version):\n expected_graph = load_json_resource('data/{v}/tiled_viewing_service.json'.format(v=api_version))\n\n def check_request(request):\n assert request.json() == expected_graph\n return True\n\n requests_mock.post(\n API_URL + \"/services\",\n status_code=201,\n text='',\n headers={'Location': API_URL + \"/services/sf00\", 'OpenEO-Identifier': 'sf00'},\n additional_matcher=check_request\n )\n\n res = s2cube.tiled_viewing_service(type=\"WMTS\", title=\"S2 Foo\", description=\"Nice!\", custom_param=45)\n assert res.service_id == 'sf00'\n\n\ndef test_apply_dimension(connection, requests_mock):\n requests_mock.get(API_URL + \"/collections/S22\", json={\n \"cube:dimensions\": {\n \"color\": {\"type\": \"bands\", \"values\": [\"cyan\", \"magenta\", \"yellow\", \"black\"]},\n \"alpha\": {\"type\": \"spatial\"},\n \"date\": {\"type\": \"temporal\"}\n }\n })\n s22 = connection.load_collection(\"S22\")\n\n for dim in [\"color\", \"alpha\", \"date\"]:\n reset_graphbuilder()\n cube = s22.apply_dimension(dimension=dim, code=\"subtract_mean\")\n assert cube.graph[\"applydimension1\"][\"process_id\"] == \"apply_dimension\"\n assert cube.graph[\"applydimension1\"][\"arguments\"][\"dimension\"] == dim\n with pytest.raises(ValueError, match=\"Invalid dimension 'wut'\"):\n s22.apply_dimension(dimension='wut', code=\"subtract_mean\")\n","sub_path":"tests/rest/datacube/test_datacube.py","file_name":"test_datacube.py","file_ext":"py","file_size_in_byte":16781,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"397755137","text":"class Solution(object):\n def findComplement(self, num):\n \"\"\"\n :type num: int\n :rtype: int\n \"\"\"\n a, result = [], 0\n while num > 0:\n a.append(0 if num & 1 == 1 else 1)\n num >>= 1\n ridx = len(a)-1\n while ridx >= 0 and a[ridx]==0: ridx-=1\n for idx in range(0,ridx+1)[::-1]: result = (result << 1) | a[idx]\n print(int(''.join([str(c) for c in a[::-1]]), 2))\n return result\n\n\nprint(Solution().findComplement(11))","sub_path":"src/cgml/leetcode/enumerated/_476e_number_complement.py","file_name":"_476e_number_complement.py","file_ext":"py","file_size_in_byte":508,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"263743483","text":"#!/usr/bin/env python\n##############################################################\n#\n# This script enables training and comparison of models on multiple GPUs.\n#\n# Usage: python scripts/automate_training.py -c path/to/config.json -p path/to/hyperparams.json -n number_of_iterations --all-combin\n#\n##############################################################\n\nimport argparse\nimport copy\nfrom functools import partial\nimport json\nimport logging\nimport os\nimport random\nimport shutil\nimport sys\nfrom itertools import product\n\nimport joblib\nimport pandas as pd\nimport torch.multiprocessing as mp\n\nfrom ivadomed import main as ivado\nfrom ivadomed import config_manager as imed_config_manager\nfrom ivadomed.utils import init_ivadomed\nfrom ivadomed.loader import utils as imed_loader_utils\nfrom ivadomed.scripts.compare_models import compute_statistics\n\nLOG_FILENAME = 'log.txt'\nlogging.basicConfig(filename=LOG_FILENAME, level=logging.DEBUG)\n\n\ndef get_parser():\n parser = argparse.ArgumentParser()\n parser.add_argument(\"-c\", \"--config\", required=True, help=\"Base config file path.\")\n parser.add_argument(\"-p\", \"--params\", required=True, help=\"JSON file where hyperparameters to experiment are \"\n \"listed.\")\n parser.add_argument(\"-n\", \"--n-iterations\", dest=\"n_iterations\", default=1,\n type=int, help=\"Number of times to run each config.\")\n parser.add_argument(\"--all-combin\", dest='all_combin', action='store_true',\n help=\"To run all combinations of config\"),\n parser.add_argument(\"-m\", \"--multi-params\", dest=\"multi_params\", action='store_true',\n help=\"To change multiple parameters at once.\")\n parser.add_argument(\"--run-test\", dest='run_test', action='store_true',\n help=\"Evaluate the trained model on the testing sub-set.\")\n parser.add_argument(\"--fixed-split\", dest='fixed_split', action='store_true',\n help=\"Keep a constant dataset split for all configs and iterations\")\n parser.add_argument(\"-l\", \"--all-logs\", dest=\"all_logs\", action='store_true',\n help=\"Keep all log directories for each iteration.\")\n parser.add_argument('-t', '--thr-increment', dest=\"thr_increment\", required=False, type=float,\n help=\"A threshold analysis is performed at the end of the training using the trained model and \"\n \"the validation sub-dataset to find the optimal binarization threshold. The specified \"\n \"value indicates the increment between 0 and 1 used during the analysis (e.g. 0.1).\")\n\n return parser\n\n\ndef train_worker(config, thr_incr):\n current = mp.current_process()\n # ID of process used to assign a GPU\n ID = int(current.name[-1]) - 1\n\n # Use GPU i from the array specified in the config file\n config[\"gpu\"] = config[\"gpu\"][ID]\n\n # Call ivado cmd_train\n try:\n # Save best validation score\n best_training_dice, best_training_loss, best_validation_dice, best_validation_loss = \\\n ivado.run_command(config, thr_increment=thr_incr)\n\n except:\n logging.exception('Got exception on main handler')\n print(\"Unexpected error:\", sys.exc_info()[0])\n raise\n\n # Save config file in log directory\n config_copy = open(config[\"log_directory\"] + \"/config_file.json\", \"w\")\n json.dump(config, config_copy, indent=4)\n\n return config[\"log_directory\"], best_training_dice, best_training_loss, best_validation_dice, best_validation_loss\n\n\ndef test_worker(config):\n # Call ivado cmd_eval\n\n current = mp.current_process()\n # ID of process used to assign a GPU\n ID = int(current.name[-1]) - 1\n\n # Use GPU i from the array specified in the config file\n config[\"gpu\"] = config[\"gpu\"][ID]\n\n try:\n # Save best test score\n config[\"command\"] = \"test\"\n df_results, test_dice = ivado.run_command(config)\n\n except:\n logging.exception('Got exception on main handler')\n print(\"Unexpected error:\", sys.exc_info()[0])\n raise\n\n return config[\"log_directory\"], test_dice, df_results\n\n\ndef make_category(base_item, keys, values, is_all_combin=False, multiple_params=False):\n items = []\n names = []\n\n if is_all_combin:\n for combination in product(*values):\n new_item = copy.deepcopy(base_item)\n name_str = \"\"\n for i in range(len(keys)):\n new_item[keys[i]] = combination[i]\n name_str += \"-\" + str(keys[i]) + \"=\" + str(combination[i]).replace(\"/\", \"_\")\n\n items.append(new_item)\n names.append(name_str)\n elif multiple_params:\n value_len = set()\n for value in values:\n value_len.add(len(value))\n if len(value_len) != 1:\n raise ValueError(\"To use flag --multi-params or -m, all hyperparameter lists need to be the same size.\")\n\n for v_idx in range(len(values[0])):\n name_str = \"\"\n new_item = copy.deepcopy(base_item)\n for k_idx, key in enumerate(keys):\n new_item[key] = values[k_idx][v_idx]\n name_str += \"-\" + str(key) + \"=\" + str(values[k_idx][v_idx]).replace(\"/\", \"_\")\n\n items.append(new_item)\n names.append(name_str)\n else:\n for value_list, key in zip(values, keys):\n for value in value_list:\n new_item = copy.deepcopy(base_item)\n new_item[key] = value\n items.append(new_item)\n # replace / by _ to avoid creating new paths\n names.append(\"-\" + str(key) + \"=\" + str(value).replace(\"/\", \"_\"))\n\n return items, names\n\n\ndef automate_training(config, param, fixed_split, all_combin, n_iterations=1, run_test=False, all_logs=False,\n thr_increment=None, multiple_params=False):\n \"\"\"Automate multiple training processes on multiple GPUs.\n\n Hyperparameter optimization of models is tedious and time-consuming. This function automatizes this optimization\n across multiple GPUs. It runs trainings, on the same training and validation datasets, by combining a given set of\n parameters and set of values for each of these parameters. Results are collected for each combination and reported\n into a dataframe to allow their comparison. The script efficiently allocates each training to one of the available\n GPUs.\n\n Usage example::\n\n ivadomed_automate_training -c config.json -p params.json -n n_iterations\n\n .. csv-table:: Example of dataframe\n :file: ../../images/detailed_results.csv\n\n Args:\n config (string): Configuration filename, which is used as skeleton to configure the training. Some of its\n parameters (defined in `param` file) are modified across experiments. Flag: ``--config``, ``-c``\n param (string): json file containing parameters configurations to compare. Parameter \"keys\" of this file\n need to match the parameter \"keys\" of `config` file. Parameter \"values\" are in a list. Flag: ``--param``, ``-p``\n\n Example::\n\n {\"default_model\": {\"depth\": [2, 3, 4]}}\n\n fixed_split (bool): If True, all the experiments are run on the same training/validation/testing subdatasets.\n Flag: ``--fixed-split``\n all_combin (bool): If True, all parameters combinations are run. Flag: ``--all-combin``\n n_iterations (int): Controls the number of time that each experiment (ie set of parameter) are run.\n Flag: ``--n-iteration``, ``-n``\n run_test (bool): If True, the trained model is also run on the testing subdataset. flag: ``--run-test``\n all_logs (bool): If True, all the log directories are kept for every iteration. Flag: ``--all-logs``, ``-l``\n thr_increment (float): A threshold analysis is performed at the end of the training using the trained model and\n the validation sub-dataset to find the optimal binarization threshold. The specified value indicates the\n increment between 0 and 1 used during the ROC analysis (e.g. 0.1). Flag: ``-t``, ``--thr-increment``\n multiple_params (bool): If True, more than one parameter will be change at the time from the hyperparameters.\n All the first elements from the hyperparameters list will be applied, then all the second, etc.\n \"\"\"\n # Load initial config\n initial_config = imed_config_manager.ConfigurationManager(config).get_config()\n\n # Hyperparameters values to experiment\n with open(param, \"r\") as fhandle:\n hyperparams = json.load(fhandle)\n param_dict, names_dict = {}, {}\n for category in hyperparams.keys():\n assert category in initial_config\n base_item = initial_config[category]\n keys = list(hyperparams[category].keys())\n values = [hyperparams[category][k] for k in keys]\n new_parameters, names = make_category(base_item, keys, values, all_combin, multiple_params)\n param_dict[category] = new_parameters\n names_dict[category] = names\n\n # Split dataset if not already done\n if fixed_split and (initial_config.get(\"split_path\") is None):\n train_lst, valid_lst, test_lst = imed_loader_utils.get_new_subject_split(\n path_folder=initial_config[\"loader_parameters\"][\"bids_path\"],\n center_test=initial_config[\"split_dataset\"][\"center_test\"],\n split_method=initial_config[\"split_dataset\"][\"method\"],\n random_seed=initial_config[\"split_dataset\"][\"random_seed\"],\n train_frac=initial_config[\"split_dataset\"][\"train_fraction\"],\n test_frac=initial_config[\"split_dataset\"][\"test_fraction\"],\n log_directory=\"./\",\n balance=initial_config[\"split_dataset\"]['balance'] if 'balance' in initial_config[\"split_dataset\"] else None)\n\n # save the subject distribution\n split_dct = {'train': train_lst, 'valid': valid_lst, 'test': test_lst}\n split_path = \"./\" + \"common_split_datasets.joblib\"\n joblib.dump(split_dct, split_path)\n initial_config[\"split_dataset\"][\"fname_split\"] = split_path\n\n config_list = []\n # Test all combinations (change multiple parameters for each test)\n if all_combin:\n\n # Cartesian product (all combinations)\n combinations = (dict(zip(param_dict.keys(), values))\n for values in product(*param_dict.values()))\n names = list(product(*names_dict.values()))\n\n for idx, combination in enumerate(combinations):\n\n new_config = copy.deepcopy(initial_config)\n\n for i, param in enumerate(combination):\n value = combination[param]\n new_config[param] = value\n new_config[\"log_directory\"] = new_config[\"log_directory\"] + names[idx][i]\n\n config_list.append(copy.deepcopy(new_config))\n elif multiple_params:\n for config_idx in range(len(names)):\n new_config = copy.deepcopy(initial_config)\n config_name = \"\"\n for param in param_dict:\n new_config[param] = param_dict[param][config_idx]\n config_name += names_dict[param][config_idx]\n new_config[\"log_directory\"] = initial_config[\"log_directory\"] + config_name\n config_list.append(copy.deepcopy(new_config))\n\n # Change a single parameter for each test\n else:\n for param in param_dict:\n new_config = copy.deepcopy(initial_config)\n for value, name in zip(param_dict[param], names_dict[param]):\n new_config[param] = value\n new_config[\"log_directory\"] = initial_config[\"log_directory\"] + name\n config_list.append(copy.deepcopy(new_config))\n\n # CUDA problem when forking process\n # https://github.com/pytorch/pytorch/issues/2517\n mp.set_start_method('spawn')\n\n # Run all configs on a separate process, with a maximum of n_gpus processes at a given time\n pool = mp.Pool(processes=len(initial_config[\"gpu\"]))\n\n results_df = pd.DataFrame()\n eval_df = pd.DataFrame()\n all_mean = pd.DataFrame()\n for i in range(n_iterations):\n if not fixed_split:\n # Set seed for iteration\n seed = random.randint(1, 10001)\n for config in config_list:\n config[\"split_dataset\"][\"random_seed\"] = seed\n if all_logs:\n if i:\n config[\"log_directory\"] = config[\"log_directory\"].replace(\"_n=\" + str(i - 1).zfill(2),\n \"_n=\" + str(i).zfill(2))\n else:\n config[\"log_directory\"] += \"_n=\" + str(i).zfill(2)\n validation_scores = pool.map(partial(train_worker, thr_incr=thr_increment), config_list)\n val_df = pd.DataFrame(validation_scores, columns=[\n 'log_directory', 'best_training_dice', 'best_training_loss', 'best_validation_dice',\n 'best_validation_loss'])\n\n if run_test:\n new_config_list = []\n for config in config_list:\n # Delete path_pred\n path_pred = os.path.join(config['log_directory'], 'pred_masks')\n if os.path.isdir(path_pred) and n_iterations > 1:\n try:\n shutil.rmtree(path_pred)\n except OSError as e:\n print(\"Error: %s - %s.\" % (e.filename, e.strerror))\n\n # Take the config file within the log_directory because binarize_prediction may have been updated\n json_path = os.path.join(config['log_directory'], 'config_file.json')\n new_config = imed_config_manager.ConfigurationManager(json_path).get_config()\n new_config[\"gpu\"] = config[\"gpu\"]\n new_config_list.append(new_config)\n\n test_results = pool.map(test_worker, new_config_list)\n\n df_lst = []\n # Merge all eval df together to have a single excel file\n for j, result in enumerate(test_results):\n df = result[-1]\n\n if i == 0:\n all_mean = df.mean(axis=0)\n std_metrics = df.std(axis=0)\n metrics = pd.concat([all_mean, std_metrics], sort=False, axis=1)\n else:\n all_mean = pd.concat([all_mean, df.mean(axis=0)], sort=False, axis=1)\n mean_metrics = all_mean.mean(axis=1)\n std_metrics = all_mean.std(axis=1)\n metrics = pd.concat([mean_metrics, std_metrics], sort=False, axis=1)\n\n metrics.rename({0: \"mean\"}, axis=1, inplace=True)\n metrics.rename({1: \"std\"}, axis=1, inplace=True)\n id = result[0].split(\"_n=\")[0]\n cols = metrics.columns.values\n for idx, col in enumerate(cols):\n metrics.rename({col: col + \"_\" + id}, axis=1, inplace=True)\n df_lst.append(metrics)\n test_results[j] = result[:2]\n\n # Init or add eval results to dataframe\n eval_df = pd.concat(df_lst, sort=False, axis=1)\n\n test_df = pd.DataFrame(test_results, columns=['log_directory', 'test_dice'])\n combined_df = val_df.set_index('log_directory').join(test_df.set_index('log_directory'))\n combined_df = combined_df.reset_index()\n\n else:\n combined_df = val_df\n\n results_df = pd.concat([results_df, combined_df])\n results_df.to_csv(\"temporary_results.csv\")\n eval_df.to_csv(\"average_eval.csv\")\n\n # Merge config and results in a df\n config_df = pd.DataFrame.from_dict(config_list)\n keep = list(param_dict.keys())\n keep.append(\"log_directory\")\n config_df = config_df[keep]\n\n results_df = config_df.set_index('log_directory').join(results_df.set_index('log_directory'))\n results_df = results_df.reset_index()\n results_df = results_df.sort_values(by=['best_validation_loss'])\n\n results_df.to_csv(\"detailed_results.csv\")\n\n print(\"Detailed results\")\n print(results_df)\n\n # Compute avg, std, p-values\n if n_iterations > 1:\n compute_statistics(results_df, n_iterations, run_test)\n\n\ndef main():\n init_ivadomed()\n\n parser = get_parser()\n args = parser.parse_args()\n\n # Get thr increment if available\n thr_increment = args.thr_increment if args.thr_increment else None\n\n # Run automate training\n automate_training(args.config, args.params, bool(args.fixed_split), bool(args.all_combin), int(args.n_iterations),\n bool(args.run_test), args.all_logs, thr_increment, bool(args.multi_params))\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"ivadomed/scripts/automate_training.py","file_name":"automate_training.py","file_ext":"py","file_size_in_byte":16869,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"465120154","text":"import math\n\nimport numpy as np\nfrom sklearn.cluster import KMeans\nfrom sklearn.datasets.samples_generator import make_blobs\nimport matplotlib.pyplot as plt\nimport scipy\n\n\ndef initialize_centroids(X, k):\n idx = np.random.randint(np.size(X, 0), size=k)\n mu_k = X[idx, :]\n return mu_k\n\n\ndef cluster_assignment(X, mu_k, k):\n c_i = [[], []]\n\n for i in range(np.size(X, 0)):\n temp = []\n for j in range(np.size(mu_k, 1)):\n temp.append((1 / np.size(X, 0)) * math.sqrt(((X[i, 0] - mu_k[j, 0]) ** 2) + ((X[i, 1] - mu_k[j, 1]) ** 2)))\n indice = temp.index(min(temp))\n c_i[indice].append(X[i, :])\n\n return c_i\n\n\ndef move_centroid(c_i, k, mu_k):\n for j in range(k):\n if not c_i[j]:\n c_i = filter(None, c_i[j])\n mu_k[j] = sum(c_i[j]) / np.size(c_i[j], 0)\n return mu_k\n\n\ndef kmeans(X, k):\n mu_k = initialize_centroids(X, k)\n converged = 0\n for n in range(10):\n _ci = cluster_assignment(X, mu_k, k)\n mu_k = move_centroid(_ci, k, mu_k)\n print(n)\n\n return _ci\n\n\ndef main():\n X, y = make_blobs(n_samples=10000, n_features=2, centers=2, random_state=0)\n number_of_clusters = 2\n clustered_data = kmeans(X, number_of_clusters)\n print(clustered_data)\n\n # y_pred = KMeans(n_clusters=2, random_state=170).fit_predict(data[0])\n\n # a = X[0, 0] - X[12, 1]\n # plt.scatter(X[0, :], X[16, :])\n # plt.show()\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"Build_structure.py","file_name":"Build_structure.py","file_ext":"py","file_size_in_byte":1462,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"43398233","text":"from datetime import datetime\nimport threading\nimport psutil\nimport myPlot\nimport myResData\n\nclass period(threading.Thread):\n cpu_percent_list = [0]*61\n on = False\n res = None\n\n def __init__(self):\n threading.Thread.__init__(self)\n self. res = myResData.Resource() # 리소스를 담을 스레드 객체 생성\n self.on = True\n self.daemon = True\n self.cpu_percent_list = [0]*61\n\n def run(self, plt, fig, ax1, ax2):\n while self.on:\n # 데이터 받음\n # cpu_percent = next(self.res.getCpu())\n cpu_percent = psutil.cpu_percent(interval=1) # blocking 상태로 cpu의 상태 리스트를 받아옴(최대길이 20)\n\n self.cpu_percent_list.pop(0)\n self.cpu_percent_list.append(cpu_percent)\n\n ax1.cla()\n ax1.set_xlim(0, 60)\n ax1.set_ylim(0, 100)\n ax1.set_title(\"CPU\")\n ax1.grid(True, linestyle='-', lw=0.2)\n\n ax1.fill_between(range(0,61), self.cpu_percent_list, y2=0, edgecolor=\"#6B66FF\", facecolors=\"#B2CCFF\", lw=2, alpha=0.7)\n ax1.tick_params(axis='x', colors='white')\n ax1.tick_params(axis='y', colors='white')\n ax1.set_xticklabels([60, 50, 40, 30, 20, 10, 0])\n\n fig.canvas.update()\n fig.canvas.flush_events()\n\n # 출력 테스트\n #print(\"%s\" % str(cpu_percent[0]))\n\n def refreshPlot(self, plt):\n pass","sub_path":"resMon/myPeriod.py","file_name":"myPeriod.py","file_ext":"py","file_size_in_byte":1468,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"545994204","text":"#!/usr/bin/env python\n# -*- coding:utf-8 -*-\nimport json\nimport tornado.web\nfrom modules.filter.filter_manage import FilterManage\n\nerrmsg = {}\n\n\nclass FilterHandler(tornado.web.RequestHandler):\n \"\"\"\n \"\"\"\n def get(self, resource):\n \"\"\"\n \"\"\"\n try:\n result = FilterManage().get(resource)\n if not result:\n self.set_status(404)\n else:\n self.write(json.dumps(result))\n except Exception as ex:\n self.write(str(ex))\n self.set_status(500)\n\n def put(self, resource):\n \"\"\"\n \"\"\"\n try:\n config = json.loads(self.request.body)\n FilterManage().update(resource, config)\n except Exception as ex:\n self.write(str(ex))\n self.set_status(500)\n\n def delete(self, resource):\n \"\"\"\n \"\"\"\n try:\n if not resource:\n self.set_status(404)\n return\n\n FilterManage().delete(resource)\n except Exception as ex:\n self.write(str(ex))\n self.set_status(500)\n\n","sub_path":"docker/container_install_script/docker-container-installer/anyrobot/etl/etl_server/handlers/filter/handler.py","file_name":"handler.py","file_ext":"py","file_size_in_byte":1121,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"604221670","text":"\nfrom django.urls import path\nfrom . import views\nurlpatterns = [\n\n path('', views.PostList.as_view(), name='home'),\n path('about/', views.about, name='about'),\n path('contact/', views.contact, name='contact'),\n path('/', views.PostDetail.as_view(), name='post_detail'),\n\n]\n","sub_path":"ft_ba/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":297,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"648096035","text":"# Copyright 2020 Google LLC\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\"\"\"Strong order 1.5 scheme for additive noise SDEs from\n\nRößler, Andreas. \"Runge–Kutta methods for the strong approximation of solutions of stochastic differential\nequations.\" SIAM Journal on Numerical Analysis 48, no. 3 (2010): 922-952.\n\"\"\"\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport math\n\nimport torch\n\nfrom torchsde._core import base_solver\nfrom torchsde._core import misc\nfrom torchsde._core.methods import utils\nfrom torchsde._core.methods.tableaus import sra1\n\nSTAGES, C0, C1, A0, B0, alpha, beta1, beta2 = (\n sra1.STAGES, sra1.C0, sra1.C1, sra1.A0, sra1.B0, sra1.alpha, sra1.beta1, sra1.beta2\n)\n\n\nclass SRKAdditive(base_solver.GenericSDESolver):\n\n def __init__(self, sde, bm, y0, dt, adaptive, rtol, atol, dt_min, options):\n super(SRKAdditive, self).__init__(\n sde=sde, bm=bm, y0=y0, dt=dt, adaptive=adaptive, rtol=rtol, atol=atol, dt_min=dt_min, options=options)\n # Trapezoidal approximation of \\int \\int \\dW_u \\ds using only `bm` allows for truly deterministic behavior.\n self.trapezoidal_approx = self.options.get('trapezoidal_approx', True)\n self.dt1_min = self.options.get('dt1_min', 0.01)\n self.dt1_div_dt = self.options.get('dt1_div_dt', 10)\n\n def step(self, t0, y0, dt):\n assert dt > 0, 'Underflow in dt {}'.format(dt)\n\n sqrt_dt = torch.sqrt(dt) if isinstance(dt, torch.Tensor) else math.sqrt(dt)\n I_k = [(bm_next - bm_cur).to(y0[0]) for bm_next, bm_cur in zip(self.bm(t0 + dt), self.bm(t0))]\n I_k0 = (\n utils.compute_trapezoidal_approx(\n self.bm, t0, y0, dt, sqrt_dt, dt1_div_dt=self.dt1_div_dt, dt1_min=self.dt1_min\n ) if self.trapezoidal_approx else [\n dt / 2. * (delta_bm_ + torch.randn_like(delta_bm_) * sqrt_dt / math.sqrt(3))\n for delta_bm_ in I_k\n ]\n )\n\n t1, y1 = t0 + dt, y0\n H0 = []\n for i in range(STAGES):\n H0i = y0\n for j in range(i):\n f_eval = self.sde.f(t0 + C0[j] * dt, H0[j])\n g_eval = self.sde.g(t0 + C1[j] * dt, y0) # The state should not affect the diffusion.\n H0i = [\n H0i_ + A0[i][j] * f_eval_ * dt + B0[i][j] * misc.batch_mvp(g_eval_, I_k0_) / dt\n for H0i_, f_eval_, g_eval_, I_k0_ in zip(H0i, f_eval, g_eval, I_k0)\n ]\n H0.append(H0i)\n\n f_eval = self.sde.f(t0 + C0[i] * dt, H0i)\n g_eval = self.sde.g(t0 + C1[i] * dt, y0)\n g_weight = [beta1[i] * I_k_ + beta2[i] * I_k0_ / dt for I_k_, I_k0_ in zip(I_k, I_k0)]\n y1 = [\n y1_ + alpha[i] * f_eval_ * dt + misc.batch_mvp(g_eval_, g_weight_)\n for y1_, f_eval_, g_eval_, g_weight_ in zip(y1, f_eval, g_eval, g_weight)\n ]\n return t1, y1\n\n @property\n def strong_order(self):\n return 1.5\n\n @property\n def weak_order(self):\n return 1.5\n","sub_path":"torchsde/_core/methods/additive/srk.py","file_name":"srk.py","file_ext":"py","file_size_in_byte":3605,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"61155859","text":"# well known n-queen problem, resolved with backtracking ofc\r\n# Nils Pinnau 20/09/2019\r\n# solved\r\n\r\nimport numpy as np\r\nimport copy\r\n\r\n# build the array of size amount * amount\r\ndef build(amount):\r\n field = np.array([[0] * amount for i in range(amount)])\r\n return field\r\n\r\n# check if the Panel is free, so a queen can be placed there\r\ndef freePanel(field, row, col):\r\n if np.count_nonzero(majorDiagonal(field, row, col) == 1) > 0:\r\n return False\r\n if np.count_nonzero(minorDiagonal(field, row, col) == 1) > 0:\r\n return False\r\n if np.count_nonzero(field[row] == 1) > 0:\r\n return False \r\n if np.count_nonzero(field[:, col] == 1) > 0:\r\n return False\r\n return True \r\n\r\n# diagonal from left top to right bottom going throught element in field[row][col]\r\ndef majorDiagonal(field, row, col):\r\n copied = copy.deepcopy(field)\r\n major = np.diagonal(copied, offset=(col - row))\r\n return major\r\n\r\n# diagonal from left bottom to right top going throught element in field[row][col]\r\ndef minorDiagonal(field, row, col):\r\n copied = copy.deepcopy(field)\r\n minor = np.diagonal(np.rot90(copied), offset=-copied.shape[1] + (row + col) + 1)\r\n return minor\r\n\r\n# set the Queens on the field recursivley, if not possible go back one step and try for next free Panel\r\ndef setQueens(field, col):\r\n # stop if all queens have been placed safely\r\n if col >= len(field):\r\n return True\r\n # try to place a queen in col, if possible then try for the next queen in the next col, if not possible then go back and set element 0 again\r\n for i in range(len(field)):\r\n if freePanel(field, i, col):\r\n field[i] [col] = 1\r\n if setQueens(field, col+1):\r\n return True\r\n field[i] [col] = 0\r\n return False\r\n\r\n# all put together\r\ndef main(amount):\r\n field = build(amount)\r\n if setQueens(field, 0):\r\n print(field)\r\n else:\r\n print('error')\r\n\r\nmain(30)\r\n","sub_path":"nQueen-problem.py","file_name":"nQueen-problem.py","file_ext":"py","file_size_in_byte":1871,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"300045014","text":"\"\"\"Snakemake wrapper for vtkdiff.\"\"\"\n\n__author__ = \"Lars Bilke\"\n__copyright__ = \"Copyright 2020, OpenGeoSys Community\"\n__license__ = \"BSD\"\n\nimport os\nfrom snakemake.shell import shell\n\nif os.path.exists(snakemake.output[0]):\n os.remove(snakemake.output[0])\n\nif snakemake.params.check_mesh:\n shell(\"vtkdiff {snakemake.input.a} {snakemake.input.b} -m > {snakemake.output[0]}\")\n\nfor field in snakemake.params.fields:\n field_a = field[0]\n offset = 0\n if len(field) == 4:\n offset = 1\n field_b = field[0 + offset]\n abs_tol = field[1 + offset]\n rel_tol = field[2 + offset]\n\n shell(\n \"\"\"\n vtkdiff {snakemake.input.a} {snakemake.input.b} \\\n -a {field_a} -b {field_b} \\\n --abs {abs_tol} --rel {rel_tol} 2>&1 | tee -a {snakemake.output[0]}\n \"\"\"\n )\n","sub_path":"scripts/snakemake/vtkdiff/wrapper.py","file_name":"wrapper.py","file_ext":"py","file_size_in_byte":813,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"363243521","text":"# coding: utf-8\n__author__ = \"nyk510\"\n\"\"\"\n人工データ・セットを作成するスクリプト\n\"\"\"\n\nimport numpy as np\n\n\ndef func1(x):\n \"\"\"\n 人工データの正しい関数例その1\n \n :param np.array x: \n :return: \n :rtype: np.array\n \"\"\"\n return x + np.sin(5 * x) - .8\n\n\ndef func2(x):\n \"\"\"\n 人口データの正しい関数その2\n :param np.ndarray x:\n :return:\n :rtype: np.ndarray\n \"\"\"\n return np.sin(5 * x) * np.abs(x)\n\n\ndef make_data(size, function_id=1, seed=1):\n \"\"\"\n 人工データの作成\n \n :param int size: \n :param int function_id: \n :param int seed: \n :return: データと正しい関数の集合\n :rtype: tuple[np.array, np.array, function]\n \"\"\"\n np.random.seed(seed)\n x = np.sort(np.random.uniform(-1.5, 1.5, size=size)).astype(np.float32).reshape(-1, 1)\n f = None\n if function_id == 1:\n f = func1\n elif function_id == 2:\n f = func2\n else:\n # 別の関数で試したい場合は適当にここで指定する\n raise ValueError\n\n y = f(x) + np.random.normal(loc=0, scale=.1, size=x.shape)\n y = y.astype(np.float32)\n return x, y, f\n","sub_path":"bnn/fetch_data/article_data.py","file_name":"article_data.py","file_ext":"py","file_size_in_byte":1185,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"54330138","text":"#!/usr/bin/env python3\n\"\"\"\nScript to run an end to end pipeline\n\"\"\"\n\nimport multiprocessing as mp\nfrom mrcnn.config import Config\nfrom argparse import ArgumentParser\nimport mrcnn.model as modellib\nfrom config import PageConfig, classes\nfrom dataset.dataset import PageDataset\nimport os\nimport subprocess\nfrom model2xml import model2xml\nfrom tqdm import tqdm\nimport shutil\nfrom utils.voc_utils import ICDAR_convert\n\n# PDF directory path\n\nparser = ArgumentParser(description=\"Run the classifier\")\nparser.add_argument('-d', \"--weightsdir\", default='weights', type=str, help=\"Path to weights dir\")\nparser.add_argument('-w', \"--weights\", type=str, help='Path to weights file', required=True)\nparser.add_argument('-t', \"--threads\", default=160, type=int, help=\"Number of threads to use\")\n\nargs = parser.parse_args()\n\nclass InferenceConfig(Config):\n NAME = \"PAGES\"\n backbone = \"resnet50\"\n GPU_COUNT = 1\n IMAGE_MIN_DIM = 1484\n IMAGE_MAX_DIM = 1920\n RPN_ANCHOR_SCALES = (64,128,256,512,768)\n NUM_CLASSES = len(classes) +1\n IMAGES_PER_GPU = 1\n\ninference_config = InferenceConfig()\nconfig = PageConfig()\nmodel = modellib.MaskRCNN(mode=\"inference\",\n config=inference_config,\n model_dir=args.weightsdir)\n#model_path = model.find_last()\n#print(\"Loading weights from \", model_path)\nmodel.load_weights(args.weights, by_name=True)\ndata_test = PageDataset('test', 'ICDAR_data_split', 0, nomask=True)\n#data_test.load_page(classes=['Figure', 'Table', 'Equation', 'Body Text'])\ndata_test.load_page(classes=classes)\ndata_test.prepare()\nimage_ids = data_test.image_ids\n\nif not os.path.exists('xml'):\n os.makedirs('xml')\n\nfor idx, image_id in enumerate(tqdm(image_ids)):\n # Load image and ground truth data\n image, image_meta, gt_class_id, gt_bbox, gt_mask = \\\n modellib.load_image_gt(data_test, inference_config,image_id, use_mini_mask=False)\n results = model.detect([image], verbose=0)\n print(results)\n r = results[0]\n info = data_test.image_info[image_id]\n zipped = zip(r[\"class_ids\"], r[\"rois\"])\n model2xml(info[\"str_id\"], 'xml', [1920, 1920], zipped, data_test.class_names, r['scores'])\n\n\n\n","sub_path":"inference/inference.py","file_name":"inference.py","file_ext":"py","file_size_in_byte":2179,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"266123223","text":"import tornado.ioloop\nimport tornado.web\nimport os.path\nimport random\n\nclass MainHandler(tornado.web.RequestHandler):\n\tdef get(self):\n\t\tself.render('index.html')\nclass WrapHandler(tornado.web.RequestHandler):\n\tdef map_by_first_letters(self,text):\n\t\tmapped = dict()\n\t\tfor line in text.split('\\r\\n'):\n\t\t\tfor word in [x for x in line.split(' ') if len(x) > 0]:\n\t\t\t\tif word[0] not in mapped: mapped[word[0]] =[]\n\t\t\t\tmapped[word[0]].append(word)\n\t\treturn mapped\n\n\tdef post(self):\n\t\tsource_text=self.get_argument(\"source\")\n\t\ttext_to_change=self.get_argument(\"change\")\n\t\tsource_map=self.map_by_first_letters(source_text)\n\t\tchange_lines=text_to_change.split('\\r\\n')\n\t\tself.render('munged.html',source_map=source_map,change_lines=change_lines,choice=random.choice)\nsettings = {\n\t'template_path':os.path.join(os.path.dirname(__file__),\"templates\"),\n\t'static_path':os.path.join(os.path.dirname(__file__),\"static\"),\n\t'debug':True,\n\t}\napplication = tornado.web.Application([\n\t(r\"/\",MainHandler),\n\t(r\"/poem\",WrapHandler),\n],**settings)\nif __name__ == \"__main__\":\n\tapplication.listen(8888)\n\ttornado.ioloop.IOLoop.instance().start()\n","sub_path":"Python/moveit/tornado/poemmaker2/tornado_test.py","file_name":"tornado_test.py","file_ext":"py","file_size_in_byte":1117,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"140211631","text":"import re\nfrom zzz.chapter03.knock20 import extract_text\n\nif __name__ == '__main__':\n filename = 'jawiki-country.json'\n text = extract_text(filename, 'イギリス')\n\n # pattern = r'ファイル:(.*?\\..*?)\\|'\n pattern = r'ファイル:(.*?\\..*?)(?:\\||\\])' # ファイル:Wembley Stadium, illuminated.jpg|thumb|220px|[[ウェンブリー・スタジアム]]\n files = re.findall(pattern, '\\n'.join(text))\n print(len(files), files)","sub_path":"zzz/chapter03/knock24.py","file_name":"knock24.py","file_ext":"py","file_size_in_byte":452,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"514700732","text":"# レクチャー59:リスト内包表記\r\n\r\nt = (1, 2, 3, 4, 5)\r\nt2 = (6, 7, 8, 9, 10)\r\n\r\nr = []\r\nfor i in t:\r\n if i % 2 == 0:\r\n r.append(i)\r\n\r\nprint(r)\r\n\r\nr = [i for i in t if i % 2 == 0]\r\nprint(r)\r\n\r\nprint('##########')\r\n\r\nr = []\r\nfor i in t:\r\n for j in t2:\r\n r.append(i * j)\r\n\r\nprint(r)\r\n\r\nr = [i * j for i in t for j in t2]\r\n\r\nprint(r)\r\nprint('-------------------------------------')\r\n\r\n# レクチャー60:辞書内包表記\r\n\r\nw = ['mon', 'tue', 'wed']\r\nf = ['coffee', 'milk', 'water']\r\n\r\nd = {}\r\nfor x, y in zip(w, f):\r\n d[x] = y\r\n\r\nprint(d)\r\n\r\nd = {x: y for x, y in zip(w, f)}\r\nprint(d)\r\nprint('-------------------------------------')\r\n\r\n# セクション61:集合内包表記\r\n\r\ns = set()\r\n\r\nfor i in range(10):\r\n if i % 2 == 0:\r\n s.add(i)\r\n\r\nprint(s)\r\n\r\ns = {i for i in range(10) if i % 2 == 0}\r\nprint(s)\r\nprint('-------------------------------------')\r\n\r\n# セク��ョン62:ジェネレーター内包表記\r\n\r\ndef g():\r\n for i in range(10):\r\n yield i\r\n\r\ng = g()\r\n\r\ng = (i for i in range(10) if i % 2 == 0)\r\n\r\nfor x in g:\r\n print(x)\r\n","sub_path":"Section5/lesson_21.py","file_name":"lesson_21.py","file_ext":"py","file_size_in_byte":1101,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"233229121","text":"#!/usr/bin/python3\n\n\n#\n# socket_probe.py - Socket Probe\n# Version 1.0\n# Created by Kevin Thomas 02/28/17\n# CC BY\n#\n\n\nimport socket\n\nmy_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n\nserver = input(\"Enter Server: \")\nport = int(input(\"Enter Port: \"))\n\nserver_ip = socket.gethostbyname(server)\nprint(server_ip)\n\nrequest = \"GET / HTTP/1.1\\nHost: \" + server + \"\\n\\n\"\n\nmy_socket.connect((server, port))\nmy_socket.send(request.encode())\nmy_result = my_socket.recv(4096)\n\nprint(my_result)\n","sub_path":"socket_probe.py","file_name":"socket_probe.py","file_ext":"py","file_size_in_byte":496,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"389137692","text":"from scipy.interpolate import griddata\r\nimport numpy as np\r\nimport random\r\nfrom timeit import default_timer as timer\r\n#import IP\r\nimport matplotlib.pyplot as plt\r\ndef im2bw(Ig,level):\r\n S=np.copy(Ig)\r\n S[Ig > level] = 1\r\n S[Ig <= level] = 0\r\n return(S)\r\ndef init(um, disp1, E, vertices, ymeas_noise_coef,Randinit,MA,scale):\r\n start = timer() \r\n N=len(E)\r\n np.random.seed(1)\r\n varibx0=ymeas_noise_coef*2#\r\n stdx0=varibx0*np.abs(E)\r\n\r\n umx=um[0::2]\r\n umy=um[1::2]\r\n x = np.array(vertices[:,0])\r\n y = np.array(vertices[:,1]) \r\n x_new = np.linspace(x.min(),x.max(),N)\r\n y_new = np.linspace(y.min(),y.max(),N)\r\n X, Y = np.meshgrid(x_new, y_new)\r\n umx_interp=np.around(griddata((x,y),np.ravel(umx),(X,Y),method='linear'),decimals=10)\r\n #umy_interp=np.around(griddata((x,y),np.ravel(umy),(X,Y),method='linear'),decimals=10)\r\n I1=im2bw(np.abs(umx_interp),0.12)\r\n xx, yy = np.indices((I1.shape[0], I1.shape[1]))\r\n x1=int(I1.shape[0]/2)\r\n y1=int(I1.shape[1]/2)\r\n dia=np.where(I1[x1,:]==0)\r\n r1=(np.max(dia[0])-np.min(dia[0])+20)/2\r\n mask_circle1 = (xx - x1) ** 2 + (yy - y1) ** 2 < r1 ** 2\r\n I3=mask_circle1*1\r\n mask=(1-I1)*I3\r\n x1=scale*mask+np.random.normal(0,stdx0,N)+0.1*np.ones(N)#++np.ravel(w)\r\n x00=np.zeros(len(E))\r\n for j in range(len(E)):\r\n idx=vertices[j,:]/30e-3*N\r\n x00[j]=x1[int(np.floor(idx[0]))-1,int(np.floor(idx[1]))-1]\r\n\r\n SNRx0=10*np.log10(np.linalg.norm(x1)**2/np.sum(stdx0**2))\r\n print('SNRx0:',SNRx0)\r\n print(\"--- %s seconds ---\" % (timer()-start)) \r\n return x00\r\n\r\n\r\n","sub_path":"init.py","file_name":"init.py","file_ext":"py","file_size_in_byte":1600,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"508789358","text":"class Solution:\n def findReplaceString(self, S, indexes, sources, targets):\n \"\"\"\n :type S: str\n :type indexes: List[int]\n :type sources: List[str]\n :type targets: List[str]\n :rtype: str\n \"\"\"\n modified = []\n pointer = 0\n for index, source, target in sorted(zip(indexes, sources, targets)):\n modified.append(S[pointer:index])\n if S[index:index + len(source)] == source:\n modified.append(target)\n else:\n modified.append(S[index:index + len(source)])\n pointer = index + len(source)\n modified.append(S[pointer:])\n return \"\".join(modified)\n","sub_path":"084/02_find_and_replace_in_string/solution_list_pointer.py","file_name":"solution_list_pointer.py","file_ext":"py","file_size_in_byte":695,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"554195797","text":"\"\"\"Nome na vertical em escada. Modifique o programa anterior de forma a mostrar o nome em formato de escada.\n\nF\nFU\nFUL\nFULA\nFULAN\nFULANO\"\"\"\n\nnome = input(\"Digite o nome: \")\n\nfor i in range(1, len(nome) + 1):\n for j in range(0, i):\n print(nome[j], end=\" \")\n print(\" \")\n","sub_path":"ExerciciosComStrings/Exe04.py","file_name":"Exe04.py","file_ext":"py","file_size_in_byte":281,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"455811770","text":"from sklearn.neural_network import MLPClassifier\nfrom sklearn.metrics import accuracy_score\nfrom sklearn.preprocessing import StandardScaler\nfrom itertools import product\nimport scipy.io as scio\nimport numpy as np \n\ntrainfilename = 'datanorm-full.mat'\ntrainmat = scio.loadmat(trainfilename)\ntraindata = np.asarray(trainmat['datanorm'])\nprint(traindata)\n\n# testfilename = 'datanorm.mat'\n# testmat = scio.loadmat(testfilename)\n# testdata = np.asarray(testmat['datanorm'])\n# testX = testdata[:, 0:20]\n# testY = testdata[:, 20]\n\ntrainX = traindata[0:40000, 0:20]\ntrainY = traindata[0:40000, 20]\n\ntestX = traindata[40000:41188, 0:20]\ntestY = traindata[40000:41188, 20]\n\n\n# training with different \n\n# parameters\n# default (100, )\nmy_hidden_layer_sizes = (3, )\n# ('identity', 'logistic', 'tanh', 'relu'), default relu\nactivations = ['identity', 'logistic', 'tanh', 'relu']\nmy_activation = 'relu'\n# {‘lbfgs’, ‘sgd’, ‘adam’}, default ‘adam’\nsolvers = ['lbfgs', 'sgd', 'adam']\nmy_solver = 'adam'\n# default 0.0001, l2 penalty\nmy_alpha = 0.0001\n# default ‘auto’, related to slover\nmy_batch_size = 'auto'\n# learning_rate : {‘constant’, ‘invscaling’, ‘adaptive’}, default ‘constant’\nlearning_rates = ['constant', 'invscaling', 'adaptive']\nmy_learning_rate = 'constant'\n# learning_rate_init : double, optional, default 0.001, only for sgd and adam solver\nmy_learning_rate_init = 0.001\n# default False\nmy_early_stopping = False\n# default 200\nmy_max_iter = 200\n\nfor my_activation in activations:\n\tfor my_solver in solvers:\n\t# my_hidden_layer_sizes = (i, )\n\t\tclf = MLPClassifier(hidden_layer_sizes=my_hidden_layer_sizes, alpha=my_alpha, \n\t\t\tactivation=my_activation, solver=my_solver,\n\t\t\tlearning_rate=my_learning_rate, learning_rate_init=my_learning_rate_init,\n\t\t\tbatch_size=my_batch_size, max_iter=my_max_iter, \n\t\t\trandom_state=1)\n\t\tclf.fit(trainX, trainY)\n\t\tpreY = clf.predict(testX)\n\t\taccu = accuracy_score(preY, testY)\n\t\tprint(\"predicting done, the parameters are: \\n my_hidden_layer_sizes: \", my_hidden_layer_sizes, \n\t\t\t\" my_activation: \", my_activation,\n\t\t\t\" my_solver: \", my_solver)\n\t\tprint(\"accuracy\", accu)\n\n\n","sub_path":"sklearn-NN.py","file_name":"sklearn-NN.py","file_ext":"py","file_size_in_byte":2140,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"241056572","text":"class Solution:\n def threeSum(self, nums: List[int]) -> List[List[int]]:\n if len(nums) < 2: return []\n HashT = defaultdict(list)\n res = set()\n for i in range(len(nums)): HashT[nums[i]].append(i)\n for i in range(len(nums)):\n for j in range(i+1, len(nums)):\n third_num = -1*(nums[i]+nums[j])\n if tuple(sorted((nums[i], nums[j], third_num))) in res: continue\n if third_num in HashT:\n for third in HashT[third_num]:\n if third != i and third != j:\n res.add(tuple(sorted((nums[i], nums[j], third_num))))\n return list(map(lambda x: list(x), list(res)))\n","sub_path":"LC15-3sum.py","file_name":"LC15-3sum.py","file_ext":"py","file_size_in_byte":716,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"524950925","text":"import os\nimport aiohttp\n\n\nclass ElasticLogger:\n\n def __init__(self, schema, host=None, index=None, user=None, pw=None):\n self.schema = schema\n self.host = host or os.getenv(\"ELASTIC_HOST\")\n self.index = index or os.getenv(\"ELASTIC_INDEX\")\n self.index_uri = \"{}/{}\".format(self.host, self.index)\n self.session = aiohttp.ClientSession(auth=aiohttp.BasicAuth(\n login=user or os.getenv(\"ELASTIC_USERID\"),\n password=pw or os.getenv(\"ELASTIC_PASSWORD\"), encoding='utf-8'))\n\n async def __call__(self, event, silent=False):\n if not silent:\n print(\"\\033[1K\\rPosting event to {}\".format(self.index))\n resp = await self.session.post(\"{}/_doc\".format(self.index_uri), json=event)\n if not silent:\n print(\"\\033[1K\\rResponse: {}\".format(resp.status))\n print(await resp.json())\n return resp\n\n async def close(self):\n await self.session.close()\n\n async def get_schema(self, silent=False):\n if not silent:\n print(\"\\033[1K\\rGetting schema of {}\".format(self.index))\n resp = await self.session.get(self.index_uri)\n if not silent:\n print(\"\\033[1K\\rResponse: {}\".format(resp.status))\n print(await resp.json())\n return resp\n\n async def init_schema(self, silent=False, deleteExisting=True):\n resp = await self.get_schema(silent=True)\n if resp.status == 200:\n if deleteExisting:\n if not silent:\n print(\n \"\\033[1K\\rIndex {} exists, deleting.\".format(self.index))\n await self.delete_index(silent=silent)\n else:\n if not silent:\n print(\n \"\\033[1K\\rIndex {} exists, not deleting.\".format(self.index))\n return False\n if not silent:\n print(\"\\033[1K\\rCreating {} schema\".format(self.index))\n resp = await self.session.put(self.index_uri, json=self.schema)\n if not silent:\n print(\"\\033[1K\\rResponse: {}\".format(resp.status))\n print(await resp.json())\n return resp\n\n async def delete_index(self, silent=False):\n if not silent:\n print(\"\\033[1K\\rDeleting index {}\".format(self.index))\n resp = await self.session.delete(self.index_uri)\n if not silent:\n print(\"\\033[1K\\rResponse: {}\".format(resp.status))\n print(await resp.json())\n return resp\n\n async def query(self, query, silent=False):\n if not silent:\n print(\"\\033[1K\\rExecuting query against {}\".format(self.index))\n resp = await self.session.get(\"{}/_search\".format(self.index_uri), json=query)\n if not silent:\n print(\"\\033[1K\\rResponse: {}\".format(resp.status))\n print(await resp.json())\n return resp\n","sub_path":"pset_x/es_logger.py","file_name":"es_logger.py","file_ext":"py","file_size_in_byte":2890,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"400120278","text":"from django.urls import path,include\nfrom . import views\n\nurlpatterns = [\n path('',views.home,name='home'),\n path('delete/',views.delete,name='delete'),\n path('uncross/',views.uncross,name='uncross'),\n path('cross_off/',views.cross_off,name='cross_off'),\n path('edit/',views.edit,name='edit'),\n]\n","sub_path":"Items/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":327,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"572442779","text":"#!/usr/bin/python\n# coding: utf8\n\nimport os\n\nfrom setuptools import setup, find_packages\nhere = os.path.abspath(os.path.dirname(__file__))\n\ntry: # for pip >= 10\n from pip._internal.req import parse_requirements\nexcept ImportError: # for pip <= 9.0.3\n from pip.req import parse_requirements\n\n# parse_requirements() returns generator of pip.req.InstallRequirement objects\ninstall_reqs = parse_requirements('requirements.txt', session=False)\n\n# reqs is a list of requirement\n# e.g. ['django==1.5.1', 'mezzanine==1.4.6']\nreqs = [str(ir.req) for ir in install_reqs]\n\nconfig = {\n 'description': 'Flask Azure Active Directory Auth',\n 'author': 'Matthias Wutte',\n 'url': '',\n 'download_url': 'https://github.com/wuttem',\n 'author_email': 'matthias.wutte@gmail.com',\n 'version': '0.7',\n 'install_requires': reqs,\n 'tests_require': reqs,\n 'packages': find_packages(),\n 'scripts': [],\n 'name': 'flask-ad-auth'\n}\n\nsetup(**config)","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":958,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"574763464","text":"# Contributor: Phuoc T. Nguyen\r\n# September 6th 2019\r\n# Language: Python 3\r\n# Program will check whether a string is palindrome or not.\r\n# Source problem: https://www.practicepython.org/exercise/2014/03/12/06-string-lists.html\r\n\r\n# write a function to check\r\ndef palindrome(word) :\r\n word = str(word)\r\n new_word = \"\"\r\n\r\n # Split each character in word\r\n for i in range(len(word)) :\r\n new_word += word[len(word) - 1 - i]\r\n return new_word\r\n\r\n# Prompt user to input a word\r\nuser_word = str(input(\"Please enter a word: \"))\r\nnew_word = palindrome(user_word)\r\n# Check palindrome or not\r\nif user_word.lower() == new_word.lower() :\r\n print(\"This is a palindrome!\")\r\nelse :\r\n print(\"This is not a palindrome!\")","sub_path":"string_List.py","file_name":"string_List.py","file_ext":"py","file_size_in_byte":730,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"419986792","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\"\"\"\n@Time : 2018/10/17\n@Author : AnNing\n\"\"\"\nimport numpy as np\n\nfrom PB.pb_time import is_day_timestamp_and_lon\n\n\ndef filter_data_by_delta_sigma(x, y, w=None, n=8):\n \"\"\"\n 过滤正负 delta + n 倍的 std 的杂点\n :param x:\n :param y:\n :param w:\n :param n:\n :return:\n \"\"\"\n c = np.polyfit(x, y, 1, w=w)\n k1 = c[0]\n k0 = c[1]\n regression_line = x * k1 + k0\n\n delta = np.abs(y - regression_line)\n delta_mean = np.nanmean(delta)\n delta_std = np.nanstd(delta)\n\n y_max = regression_line + delta_mean + delta_std * n\n y_min = regression_line - delta_mean - delta_std * n\n\n index = np.logical_and(y < y_max, y > y_min)\n\n return index\n\n\ndef filter_data_by_time(data, timestamp, longitude, time):\n index = get_time_index(timestamp, longitude, time)\n if isinstance(data, dict):\n for k, d in data.iteritems():\n data[k] = d[index]\n else:\n data = data[index]\n return data\n\n\ndef get_time_index(timestamp, longitude, time):\n \"\"\"\n 获取白天 晚上 全量的索引\n :param timestamp:\n :param longitude:\n :param time: day night all\n :return:\n \"\"\"\n time = time.lower()\n vectorize_is_day = np.vectorize(is_day_timestamp_and_lon)\n if time == 'all':\n index = np.where(timestamp)\n elif time == 'day':\n index = vectorize_is_day(timestamp, longitude)\n elif time == 'night':\n index = np.logical_not(vectorize_is_day(timestamp, longitude))\n else:\n raise KeyError('{} can not be handled.'.format(time))\n return index\n\n\ndef has_empty_data_or_not_equal_length(datas):\n\n length = set()\n\n for data in datas:\n if not data:\n return True\n else:\n length.add(len(data))\n\n if len(length) > 1:\n return True\n\n return False\n","sub_path":"lib_gsics/lib_filter.py","file_name":"lib_filter.py","file_ext":"py","file_size_in_byte":1856,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"182270091","text":"# pylint: disable=invalid-name\n# pylint: disable=missing-docstring\n\nimport numpy as np\nfrom wutils import modelling\n\n\ndef test_get_id_fold_ixs():\n np.random.seed(0)\n ids = np.array([1, 1, 1, 2, 2, 3])\n ixs = modelling.get_id_fold_ixs(ids, n_fold=2)\n expected = [\n ([3, 4, 5], [0, 1, 2]),\n ([0, 1, 2], [3, 4, 5]),\n ]\n\n for i, (trn_ixs, val_ixs) in enumerate(ixs):\n assert np.all(np.array(expected[i][0]) == trn_ixs)\n assert np.all(np.array(expected[i][1]) == val_ixs)\n","sub_path":"tests/test_modelling.py","file_name":"test_modelling.py","file_ext":"py","file_size_in_byte":513,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"506711918","text":"# -*- coding:utf-8 -*- \nimport re\nimport urllib.request\nimport requests\nfrom bs4 import BeautifulSoup\nimport os\nimport time\nglobal_download_path='/mnt/hdd/dataset/audio/lizhi/'\n\ndef get_request_fun(url):\n\n free_proxy = {'http':'39.106.223.134:80'}\n headers = {\n 'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36',\n }\n headers['User-Agent']='Mozilla/5.0 (compatible; Baiduspider/2.0; +http://www.baidu.com/search/spider.html)'\n try:\n html = requests.get(url=url,stream=True,verify=False, headers=headers,proxies=free_proxy)\n except:\n import IPython\n IPython.embed()\n html=None\n print('something goes wrong')\n return html\n\n# _ud.mp3:超高清; _hd.mp3:高清; _sd.m4a:低清\n\ndef get_music_lizhifm(url):\n id = url.rsplit('/', 1)[1]\n url = 'http://www.lizhi.fm/media/url/{}'.format(id)\n headers = {\n 'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36',\n }\n #html = requests.get(url, headers=headers).json()\n html=get_request_fun(url).json()\n\n # print(html)\n if html['data']:\n mp3_url = html['data']['url']\n return mp3_url\n else:\n print(\"!!!\"+html['msg'])\n return None\n \ndef download_each_item(article_url,mp3_save_path):\n downloadurl = get_music_lizhifm(article_url)\n urlList = []\n title=mp3_save_path.split('/')[-1]\n print(title+' is downloading')\n\n try:\n if downloadurl and not os.path.exists(mp3_save_path) :\n urllib.request.urlretrieve(downloadurl,mp3_save_path )\n except:\n print('somethnig goes wrong')\n print(title+' download is completed')\n\n\n\n\ndef download_each_page(page_url):\n userId ='1708890' #re.findall('(/[0-9]{7}/)',startUrl)[0]\n page = get_request_fun(page_url)\n bs = BeautifulSoup(page.content, features='lxml')\n all_articles=bs.find_all(\"a\", {\"class\":\"clearfix js-play-data audio-list-item\"})\n for item_inf in all_articles:\n title = item_inf[\"title\"]\n mp3_save_path=global_download_path+userId+'/'+title+'.mp3'\n if os.path.exists(mp3_save_path):\n print(mp3_save_path+' already exists')\n continue\n # import IPython\n # IPython.embed()\n article_url='https://www.lizhi.fm'+item_inf[\"href\"]\n download_each_item(article_url,mp3_save_path) \n time.sleep(5)\n\n\n\ndef downloadFromPage(startUrl):\n #page = requests.get(startUrl)\n\n userId ='1708890' #re.findall('(/[0-9]{7}/)',startUrl)[0]\n file_save_path=download_path+userId+'/'\n page = get_request_fun(startUrl)\n bs = BeautifulSoup(page.content, features='lxml')\n title = bs.select(\".audioName\")[0].text\n mp3_save_path=file_save_path+title+'.mp3'\n print(title+' is downloading')\n\n import IPython\n IPython.embed()\n\n if not os.path.exists(file_save_path):\n os.makedirs(file_save_path)\n\n downloadurl = get_music_lizhifm(startUrl)\n urlList = []\n if downloadurl and not os.path.exists(mp3_save_path) :\n urllib.request.urlretrieve(downloadurl,mp3_save_path )\n\n print(title+' download is completed')\n\n # get next url\n for link in bs.findAll('a'):\n url = link.get('href')\n downloadableUrl = re.findall('(^[0-9]{19}$)', url)\n if downloadableUrl:\n urlList.append(downloadableUrl[0])\n #import IPython\n #IPython.embed()\n time.sleep(1)\n if(len(urlList) == 2):\n nextUrl = 'https://www.lizhi.fm'+userId+urlList[1]\n print('nextUrl: ' + nextUrl)\n downloadFromPage(nextUrl)\n else:\n print('urlList length error:'+ urlList)\n #import IPython\n #IPython.embed()\n return\n\n\nif __name__ == '__main__':\n print('*' * 30 + 'ready to download' + '*' * 30)\n for page_id in range(1,100):\n url ='https://www.lizhi.fm/user/2544758401649219116/p/'+str(page_id)+'.html' #input('[请输入初始下载链接]:')\n download_each_page(url)\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3888,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"293452408","text":"import os\nfrom flask.ext.sqlalchemy import SQLAlchemy\n\nbasedir = os.path.abspath(os.path.dirname(__file__))\n\ndb_uri = 'sqlite:///' + os.path.join(basedir, 'notejam.db')\nif os.environ.get('MYSQL_HOST'):\n db_uri = 'mysql://root:password@{host}/notejam'.format(host=os.getenv('MYSQL_HOST', 'localhost'))\n\nclass Config(object):\n DEBUG = False\n TESTING = False\n SECRET_KEY = 'notejam-flask-secret-key'\n CSRF_ENABLED = True\n CSRF_SESSION_KEY = 'notejam-flask-secret-key'\n SQLALCHEMY_DATABASE_URI = db_uri\n\n\nclass ProductionConfig(Config):\n DEBUG = False\n\n\nclass DevelopmentConfig(Config):\n DEVELOPMENT = True\n DEBUG = True\n\n\nclass TestingConfig(Config):\n TESTING = True\n","sub_path":"flask/notejam/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":697,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"133396899","text":"# Definition for a binary tree node.\n# class TreeNode:\n# def __init__(self, x):\n# self.val = x\n# self.left = None\n# self.right = None\n\nclass Solution:\n def longestUnivaluePath(self, root):\n \"\"\"\n :type root: TreeNode\n :rtype: int\n \"\"\"\n self.answer = 0\n self.maxDepth(root)\n return self.answer\n \n def maxDepth(self, node):\n if node is None: \n return 0\n left = self.maxDepth(node.left)\n right = self.maxDepth(node.right)\n \n left = left + 1 if node.left and node.left.val == node.val else 0 \n right = right + 1 if node.right and node.right.val == node.val else 0\n \n # Keeps track of longest path visited so far\n self.answer = max(self.answer, left+right)\n \n return max(left,right) ","sub_path":"Leetcode/687longestUnivaluePath.py","file_name":"687longestUnivaluePath.py","file_ext":"py","file_size_in_byte":855,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"403696272","text":"#!/usr/bin/env python\nimport rospy\nimport math\nimport time\nfrom geometry_msgs.msg import Twist\nfrom std_msgs.msg import String\nfrom nav_msgs.msg import Odometry\n\nclass Pose:\n def __init__(self, x=0, y=0, theta=0):\n self.x = x\n self.y = y\n self.theta = theta\n\n def update(self, x, y, theta):\n self.x = x\n self.y = y\n self.theta = theta\n\ncurr_pose = Pose()\n\ndef publisher_node():\n global curr_pose\n\n vel_factor = 0.1\n ang_factor = 0.5\n target1 = [Pose(2, .5, 135/180*math.pi)]\n target_index = 0\n\n cmd_twist = Twist()\n\n stop_movement = Twist()\n stop_movement.linear.x = 0\n stop_movement.linear.y = 0\n stop_movement.linear.z = 0\n stop_movement.angular.x = 0\n stop_movement.angular.y = 0\n stop_movement.angular.z = 0\n \n pub = rospy.Publisher('cmd_vel', Twist, queue_size=1)\n rate = rospy.Rate(10)\n\n while not rospy.is_shutdown():\n vel_mag = min(0.26, vel_factor*((target1[target_index].x - curr_pose.x)**2 \\\n + (target1[target_index].y - curr_pose.y)**2)**0.5)\n\n ang_vel = max(-1.28, min(1.28, ang_factor*math.degrees(target1[target_index].theta - curr_pose.theta)))\n\n rospy.loginfo(ang_vel)\n\n cmd_twist.linear.x = vel_mag\n cmd_twist.angular.z = ang_vel\n\n pub.publish(cmd_twist)\n\n rate.sleep()\n\ndef get_yaw_from_quarternion(q):\n\tsiny_cosp = 2*(q.w*q.z + q.x*q.y)\n\tcosy_cosp=1-2*(q.y*q.y+q.z*q.z)\n\tyaw=math.atan(siny_cosp/cosy_cosp)\n\treturn yaw\n\ndef callback(odom_data):\n global curr_pose\n\n point = odom_data.pose.pose.position \n quart = odom_data.pose.pose.orientation \n theta = get_yaw_from_quarternion(quart)\n cur_pose = (point.x, point.y, theta) \n # rospy.loginfo(cur_pose)\n\n curr_pose.update(point.x, point.y, theta)\n\ndef main():\n try:\n rospy.init_node('lab02')\n\n rate = rospy.Rate(10) \n listen = rospy.Subscriber('odom', Odometry, callback, queue_size=1)\n\n publisher_node()\n\n rate.sleep()\n rospy.spin()\n except rospy.ROSInterruptException:\n pass\n\nif __name__ == '__main__':\n main()","sub_path":"nodes/lab02.py","file_name":"lab02.py","file_ext":"py","file_size_in_byte":2119,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"530552259","text":"# -*- coding: utf-8 -*-\nimport pandas as pd\nimport numpy as np\nfrom datetime import datetime, timedelta\nimport os\nimport sys\n\n#######Process INMET Automatic Station Data###########\n\"\"\"\nINMET Weather data is available in folders for each year, containing a csv file \nfor each automatic station available \n@author: Gabriel Marinho\n1st Task - Process an individual folder, and loop in all folders, creating a database with station\nlocation, precipitation, and date/hour information \n2nd Task - Map the station to points in the NMME moldes available from NOAA \n\"\"\"\n\"\"\"The csv files can be divided in two parts, the first 7 rows containing the station metadata\nand the rest, containing the observations.\nThe first part is following the patern below:\n \nRegion:\t(CO,N,NE,S,S)\nState_Abbr:\tXX\nStation_City:\te.g: BRASILIA\nWMO Code:\tAXXX\nLatitude:\t-15,78944444\nLongitude:\t-47,92583332\nHeight:\t1159,54\nFoundation date (YYYY-MM-DD):\tYYYY-MM-DD\n\"\"\"\n\"\"\"\nThe Second part contains the following variables in observations:\n ['DATA (YYYY-MM-DD)', 'HORA (UTC)', 'PRECIPITAÇÃO TOTAL, HORÁRIO (mm)',\n 'PRESSAO ATMOSFERICA AO NIVEL DA ESTACAO, HORARIA (mB)',\n 'PRESSÃO ATMOSFERICA MAX.NA HORA ANT. (AUT) (mB)',\n 'PRESSÃO ATMOSFERICA MIN. NA HORA ANT. (AUT) (mB)',\n 'RADIACAO GLOBAL (W/m²)',\n 'TEMPERATURA DO AR - BULBO SECO, HORARIA (°C)',\n 'TEMPERATURA DO PONTO DE ORVALHO (°C)',\n 'TEMPERATURA MÁXIMA NA HORA ANT. (AUT) (°C)',\n 'TEMPERATURA MÍNIMA NA HORA ANT. (AUT) (°C)',\n 'TEMPERATURA ORVALHO MAX. NA HORA ANT. (AUT) (°C)',\n 'TEMPERATURA ORVALHO MIN. NA HORA ANT. (AUT) (°C)',\n 'UMIDADE REL. MAX. NA HORA ANT. (AUT) (%)',\n 'UMIDADE REL. MIN. NA HORA ANT. (AUT) (%)',\n 'UMIDADE RELATIVA DO AR, HORARIA (%)',\n 'VENTO, DIREÇÃO HORARIA (gr) (° (gr))', 'VENTO, RAJADA MAXIMA (m/s)',\n 'VENTO, VELOCIDADE HORARIA (m/s)']\n\nnull values are replaced by -9999\n\nOnly the variable Total Precipitation is going to be used at the first moment\"\"\"\n\n\nparent_folder='C:/Users/mariga/OneDrive - Verisk Analytics/Projeto Final/Data/Weather/INMET'\nfor year_folder in os.listdir(parent_folder):\n if int(year_folder) < 2019:\n continue\n date_column_name = 'DATA (YYYY-MM-DD)'\n hour_column_name = 'HORA (UTC)'\n else:\n date_column_name = 'Data'\n hour_column_name = 'Hora UTC' \n year_dfs = []\n for file in os.listdir(parent_folder+'/'+year_folder):\n split = file.split(sep = '_')\n region = split[1]\n state = split[2]\n station_code = split[3]\n station_name = split[4]\n date_begin = split[5]\n if('01-01-'+str(year_folder)!=date_begin):\n full_year = False\n else:\n full_year = True\n df = pd.read_csv(parent_folder+'/'+year_folder+'/'+file, encoding='latin-1', skiprows=8, sep=';', decimal=',')\n df = df[[date_column_name, hour_column_name, 'PRECIPITAÇÃO TOTAL, HORÁRIO (mm)']]\n df['date'] = pd.to_datetime(df[date_column_name])\n df['hour'] = df[hour_column_name].apply(lambda x: int(x[:2]))\n df['day'] = df.date.dt.day\n df['month'] = df.date.dt.month\n df['year'] = df.date.dt.year\n df['precipitation'] = df['PRECIPITAÇÃO TOTAL, HORÁRIO (mm)']\n df['unit'] = 'mm'\n df.drop(columns = [date_column_name, hour_column_name, 'PRECIPITAÇÃO TOTAL, HORÁRIO (mm)','date'], inplace=True)\n df['state'] = state\n df['region'] = region\n df['station_code'] = station_code\n df['station_name'] = station_name\n df['full_year_flag'] = full_year\n year_dfs.append(df)\n year_df = pd.concat(year_dfs)\n year_df.reset_index(inplace = True, drop = True)\n year_df.to_csv(year_folder+'.csv', sep = ';', index = False, encoding='latin-1')\n","sub_path":"inmet_data.py","file_name":"inmet_data.py","file_ext":"py","file_size_in_byte":3838,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"454009217","text":"from django.urls import path\nfrom chat import views\nfrom chat.views import AllRoomsView, NewRoomView\n\napp_name = 'chat'\n\nurlpatterns = [\n path('rooms/', AllRoomsView.as_view(), name='rooms'),\n path('room/', views.room_list, name = 'room'),\n path('new_room', NewRoomView.as_view(), name = 'new_room'),\n path('send_message_images//', views.ajax_images_sending),\n\tpath('get_users//', views.ajax_get_users),\n\tpath('potential_members//', views.ajax_potential_members),\n\tpath('get_rooms/', views.ajax_get_rooms),\n\tpath('search_users/', views.ajax_search_users),\n\tpath('create_chat/', views.ajax_create_chat),\n]\n","sub_path":"chat/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":669,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"547644466","text":"#Hoja de Trabajo 10, Algoritmos y estructuras de datos\n#Consultas en Neo4j\n#------------------Integrates------------------\n# - Diego Sevilla 17348\n# - David Soto 17551\n# - Alejandro Tejada 17854\n\nfrom neo4jrestclient.client import GraphDatabase \nfrom neo4jrestclient import client\n\ndb = GraphDatabase(\"http://localhost:7474\", username=\"neo4j\", password=\"123456\")\n\n#_________Se crean las etiquetas________#\nDoctores = db.labels.create(\"Doctores\")\nPacientes = db.labels.create(\"Pacientes\")\nDrogas = db.labels.create(\"Drogas\")\n\n#_________Metodo para ingresar un doctor a la base en Neo4j________#\ndef ingresarDoctor(nombre,colegia,esp,tel):\n nuevoDoctor = db.nodes.create(name=nombre,colegiado=colegia,especialidad=esp,telefono=tel)\n Doctores.add(nuevoDoctor)\n print (\"\\nSe ha ingresado al Doctor correctamente\\n\")\n\n#_________Metodo para ingresar un paciente a la base en Neo4j________#\ndef ingresarPaciente(nombre,tel):\n nuevoPaciente = db.nodes.create(name=nombre,telefono=tel)\n Pacientes.add(nuevoPaciente)\n print (\"\\nSe ha ingresado al Paciente correctamente\\n\")\n\n#_________Metodo para ingresar la relacion de visita entre Paciente a Doctor, la prescripcion de Doctor a Medicina y de Paciente a Medicina________#\ndef relacionVisita():\n print(\"\\nEstos son los pacientes disponibles en la base de datos: \")\n q = 'MATCH (u: Pacientes) RETURN u'\n results = db.query(q, returns=(client.Node, str, client.Node))\n for r in results:\n print(\" - \" + \"%s\" % (r[0][\"name\"]))\n nomPaciente = raw_input(\"Ingrese el nombre del Paciente que desea relacionar: \")\n print(\"\\nEstos son los doctores disponibles en la base de datos: \")\n q = 'MATCH (u: Doctores) RETURN u'\n results = db.query(q, returns=(client.Node, str, client.Node))\n for r in results:\n print(\" - \" + \"%s\" % (r[0][\"name\"]))\n nomDoctor = raw_input(\"Ingrese el nombre del Doctor que desea relacionar: \")\n q = 'MATCH (u: Doctores) WHERE u.name=\"'+nomDoctor+'\" RETURN u'\n results1 = db.query(q, returns=(client.Node))\n largo1 = len(results1)\n q = 'MATCH (u: Pacientes) WHERE u.name=\"'+nomPaciente+'\" RETURN u'\n results2 = db.query(q, returns=(client.Node))\n largo2 = len(results2)\n if(largo1>0 and largo2>0):\n date = raw_input(\"Ingrese la fecha en la que el paciente visito al doctor(YYYYMMDD): \")\n med = raw_input(\"Ingrese el nombre de la medicina que el doctor prescribio: \")\n dateStart = raw_input(\"Ingrese la fecha en la cual debe iniciar el tratamoiento (YYYYMMDD): \")\n dateFinish = raw_input(\"Ingrese la fecha en la cual debe terminar el tratamoiento (YYYYMMDD): \")\n dosificacion = raw_input(\"Ingrese la dosis (cantidad y cada cuanto) que debe tomar el paciente: \")\n nuevaMed = db.nodes.create(name=med,desdeFecha=dateStart,hastaFecha=dateFinish,dosis=dosificacion)\n Drogas.add(nuevaMed)\n for r in results1:\n for i in results2:\n i[0].relationships.create(\"VISITS\",r[0],fecha=date) #el paciente visita al doctor en tal fecha\n i[0].relationships.create(\"TAKE\",nuevaMed) #el paciente toma la medicina\n r[0].relationships.create(\"PRESCRIBE\",nuevaMed) #el doctor prescribe la medicina\n #r[0].relationships.create(\"PACIENT\",i[0]) #el paciente es paciente del doctor en cuestion\n \n print(\"Se ha ingresado con exito la relacion\\n\")\n else:\n print(\"Alguno de los nombres escogidos no estaba dentro de la base de Datos\")\n\n#_________Metodo para consultar Doctores por su especialidad en la base de datos en Neo4j________#\ndef consultarEspecialidad():\n print(\"\\nEstas son las especialidades disponibles en la base de datos: \") \n q = 'MATCH (u: Doctores) RETURN u'\n results = db.query(q, returns=(client.Node, str, client.Node))\n listaEsp = []\n for r in results: \n if(len(results)>0):\n esp = r[0][\"especialidad\"]\n listaEsp.append(esp)\n imprimirSinRepetir(listaEsp) #Se imprime una lista de las especialidades que hay en la base de datos\n \n especialidadDada = raw_input(\"Ingrese el nombre de la especialidad para desplegar a los doctores en gestion: \")\n q = 'MATCH (u: Doctores) WHERE u.especialidad=\"'+especialidadDada+'\" RETURN u'\n results = db.query(q, returns=(client.Node, str, client.Node))\n for r in results:\n print(\"Se encontro al Doctor(a) %s con numero de contacto %s\" % (r[0][\"name\"],r[0][\"telefono\"]))\n if(len(results)==0):\n print(\"\\nNo se encontro ningun doctor(a) con dicha especialidad\")\n else:\n pass\n\n#_________Metodo para relacionar personas ingresadas en la base de datos en Neo4j________#\ndef relacionarPersonas():\n print(\"\\nEstas son las personas disponibles en la base de datos: \")\n \n print(\"DOCTORES: \")\n q = 'MATCH (u: Doctores) RETURN u'\n results = db.query(q, returns=(client.Node, str, client.Node))\n for r in results:\n print(\" - \" + \"%s\" % (r[0][\"name\"]))\n \n print(\"PACIENTES: \")\n q = 'MATCH (u: Pacientes) RETURN u'\n results = db.query(q, returns=(client.Node, str, client.Node))\n for r in results:\n print(\" - \" + \"%s\" % (r[0][\"name\"]))\n \n persona1 = raw_input(\"Ingrese el nombre de la persona que conoce a otra persona: \")\n persona2 = raw_input(\"Ingrese el nombre de esa otra persona: \")\n \n q = 'MATCH (u: Doctores) WHERE u.name=\"'+persona1+'\" RETURN u'\n results1 = db.query(q, returns=(client.Node))\n largo1 = len(results1)\n q = 'MATCH (u: Pacientes) WHERE u.name=\"'+persona1+'\" RETURN u'\n results2 = db.query(q, returns=(client.Node))\n largo2 = len(results2)\n q = 'MATCH (u: Pacientes) WHERE u.name=\"'+persona2+'\" RETURN u'\n results3 = db.query(q, returns=(client.Node))\n largo3 = len(results3)\n q = 'MATCH (u: Doctores) WHERE u.name=\"'+persona2+'\" RETURN u'\n results4 = db.query(q, returns=(client.Node))\n largo4 = len(results4)\n\n if(largo1>0 and largo3>0):\n anio = raw_input(\"Ingrese el anio desde que dicha persona conoce a la otra: \")\n for r in results1:\n for i in results3:\n r[0].relationships.create(\"KNOWS\",i[0],since=anio)\n print(\"La relacion fue ingresada correctamente\")\n elif(largo1>0 and largo4>0):\n anio = raw_input(\"Ingrese el anio desde que dicha persona conoce a la otra: \")\n for r in results1:\n for i in results4:\n r[0].relationships.create(\"KNOWS\",i[0],since=anio)\n print(\"La relacion fue ingresada correctamente\")\n elif(largo2>0 and largo3>0):\n anio = raw_input(\"Ingrese el anio desde que dicha persona conoce a la otra: \")\n for r in results2:\n for i in results3:\n r[0].relationships.create(\"KNOWS\",i[0],since=anio)\n print(\"La relacion fue ingresada correctamente\")\n elif(largo2>0 and largo4>0):\n anio = raw_input(\"Ingrese el anio desde que dicha persona conoce a la otra: \")\n for r in results2:\n for i in results4:\n r[0].relationships.create(\"KNOWS\",i[0],since=anio)\n print(\"La relacion fue ingresada correctamente\")\n else:\n print(\"Alguno de los nombres colocados no se encuentra en la base de datos\")\n\ndef recomendacionDadoUnPaciente():\n print(\"\\nEstos son los pacientes disponibles en la base de datos: \")\n q = 'MATCH (u: Pacientes) RETURN u'\n results = db.query(q, returns=(client.Node, str, client.Node))\n for r in results:\n print(\" - \" + \"%s\" % (r[0][\"name\"]))\n \n paciente1 = raw_input(\"Ingrese el nombre del paciente a quien se le desea recomendar un doctor: \") #Se pide el nombre del paciente dado\n q = 'MATCH (u: Pacientes)-[r:KNOWS]->(m:Pacientes) WHERE u.name=\"'+paciente1+'\" RETURN u, type(r), m' \n resultsP = db.query(q, returns=(client.Node, str, client.Node))\n ConocidosPaciente = []\n for r in resultsP: \n if(len(resultsP)>0):\n personaConocida = r[2][\"name\"]\n ConocidosPaciente.append(personaConocida) #Se construye una lista con los nombres de las personas(Pacientes) que este paciente conoce\n \n print(\"\\nEstas son las especialidades disponibles en la base de datos: \") \n q = 'MATCH (u: Doctores) RETURN u'\n results = db.query(q, returns=(client.Node, str, client.Node))\n listaEsp = []\n for r in results: \n if(len(results)>0):\n esp = r[0][\"especialidad\"]\n listaEsp.append(esp)\n imprimirSinRepetir(listaEsp) #Se imprime una lista de las especialidades que hay en la base de datos \n \n especialidadDada = raw_input(\"Ahora ingrese el nombre de la especialidad para recomendar algun doctor en gestion: \") #Se pide la especialidad del Dr que se recomendara\n q = 'MATCH (u: Doctores) WHERE u.especialidad=\"'+especialidadDada+'\" RETURN u'\n resultsD = db.query(q, returns=(client.Node, str, client.Node))\n Especialistas = []\n for r in resultsD: \n if(len(resultsD)>0):\n DrEsp = r[0][\"name\"]\n Especialistas.append(DrEsp) #Se construye una lista con los nombres de doctores que tienen la especialidad dada\n\n DrsRecomendados = []\n for i in ConocidosPaciente: #se recorre la lista de persnas(Pacientes) que el paciente dado conoce\n q = 'MATCH (u: Pacientes)-[r:VISITS]->(m:Doctores) WHERE u.name=\"'+i+'\" RETURN u, type(r), m'\n DrsVisitados = []\n results1 = db.query(q, returns=(client.Node, str, client.Node))\n for r in results1: \n if(len(results1)>0):\n DrVisitado = r[2][\"name\"]\n DrsVisitados.append(DrVisitado) #se construye una lista con los doctores visitados por el paciente conocido\n listaRepetidos = RepetidosEntreDosListas(DrsVisitados,Especialistas)\n if(len(listaRepetidos) > 0):\n for e in listaRepetidos:\n DrsRecomendados.append(e)\n if(len(DrsRecomendados) > 0): \n print(\"\\nEstos son los doctores que se le recomiendan al paciente, ya que han sido visitados por personas que el conoce.\")\n imprimirSinRepetir(DrsRecomendados)\n else:\n print(\"\\nProbablemente el paciente que ingreso no conoce a personas que hayan visitado a un medico con dicha especialidad. Intente de nuevo.\")\n \n\ndef recomendacionDadoUnDoctor():\n print(\"\\nEstos son los doctores disponibles en la base de datos: \")\n q = 'MATCH (u: Doctores) RETURN u'\n results1 = db.query(q, returns=(client.Node, str, client.Node))\n for r in results1:\n print(\" - \" + \"%s\" % (r[0][\"name\"]))\n \n doctor1 = raw_input(\"Ingrese el nombre del doctor que quiere recomendar otro doctor a un paciente: \") \n\n q = 'MATCH (u: Doctores)-[r:KNOWS]->(m:Doctores) WHERE u.name=\"'+doctor1+'\" RETURN u, type(r), m' \n results3 = db.query(q, returns=(client.Node, str, client.Node))\n ConocidosDr = []\n for r in results3:\n print (\" - \" + \"%s\" % (r[2][\"name\"]))\n if(len(results3) > 0 ):\n conocidoDelDr = r[2][\"name\"]\n ConocidosDr.append(conocidoDelDr) #se construye una lista con los doctores que este doctor conoce \n \n print(\"\\nEstas son las especialidades disponibles en la base de datos: \") \n q = 'MATCH (u: Doctores) RETURN u'\n results = db.query(q, returns=(client.Node, str, client.Node))\n listaEsp = []\n for r in results: \n if(len(results)>0):\n esp = r[0][\"especialidad\"]\n listaEsp.append(esp)\n imprimirSinRepetir(listaEsp) #Se imprime una lista de las especialidades que hay en la base de datos\n\n especialidadDada = raw_input(\"Ahora ingrese el nombre de la especialidad para recomendar algun doctor en gestion: \") #Se pide la especialidad del Dr que se recomendara\n q = 'MATCH (u: Doctores) WHERE u.especialidad=\"'+especialidadDada+'\" RETURN u'\n resultsD = db.query(q, returns=(client.Node, str, client.Node))\n Especialistas = []\n for r in resultsD: \n if(len(resultsD)>0):\n DrEsp = r[0][\"name\"]\n Especialistas.append(DrEsp) #Se construye una lista con los nombres de doctores que tienen la especialidad dada\n\n DrsRecomendados = RepetidosEntreDosListas(ConocidosDr,Especialistas) #Se construye una lista con los doctores que el doctor conoce y ademas tienen la\n #especialidad dada\n if(len(DrsRecomendados)>0):\n print (\"Los doctores recomendados son los siguientes: \")\n for i in DrsRecomendados:\n print(\" - \" + i)\n else:\n print (\"El doctor que ingreso probablemente no conoce a otros doctores con esta especialidad. Intente de nuevo.\")\n \n \n\n#---------------------------Metodos extras para impresion y despliegue de informacion---------------------------#\n#_________Metodo que elimina datos repetidos en una lista y los imprime________#\ndef imprimirSinRepetir(lista_original):\n if(len(lista_original)>0):\n lista_nueva = []\n for i in lista_original:\n if i not in lista_nueva:\n lista_nueva.append(i)\n for e in lista_nueva:\n print (\" - \" + e) \n print (\"\")\n else:\n print (\"No hay resultados\")\n \n#_________Metodo que retorna una lista con los valores repetidos entre dos listas____________#\ndef RepetidosEntreDosListas(lista1,lista2): \n if(len(lista1)>0 and len(lista2)>0):\n lista_nueva = []\n for i in lista1:\n if (i in lista2 and i not in lista_nueva):\n lista_nueva.append(i)\n return lista_nueva\n \n","sub_path":"Funciones.py","file_name":"Funciones.py","file_ext":"py","file_size_in_byte":13634,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"341663873","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Jun 21 16:09:19 2019\n\n@author: adrian.perez\n\"\"\"\n\n#Regresión polinomica\n\n# Plantilla de Preprocesado \n#Como importar las librerias\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport pandas as pd\n\n#importar el dataset\ndataset = pd.read_csv(\"Position_salaries.csv\")\n\nX=dataset.iloc[:,1:2].values #EStablece las variables independientes\ny=dataset.iloc[:, 2].values #establecer variable dependiente\n\n#Dividir el dataset en conjuto de entrenamiento y conjunto de test\n#En este caso no se dividen en sets de test y training por que hay pocos datos\n\n#from sklearn.model_selection import train_test_split\n#X_train,X_test,y_train,y_test=train_test_split(X,y,test_size=1/3,random_state=0)\n\n#Escalado de vaiables\n\"\"\"from sklearn.preprocessing import StandardScaler\nsc_X=StandardScaler()\nX_train=sc_X.fit_transform(X_train)\nX_test=sc_X.transform(X_test)\"\"\"\n#Ajustar la regresion lineal con el dataset\nfrom sklearn.linear_model import LinearRegression\nlineal_reg=LinearRegression()\nlineal_reg.fit(X,y)\n\n# Ajustar regresión polinomica con el data set\nfrom sklearn.preprocessing import PolynomialFeatures\npoly_reg=PolynomialFeatures(degree=5)\nX_poly=poly_reg.fit_transform(X)\nlin_reg_2=LinearRegression()\nlin_reg_2.fit(X_poly,y)\n\n#Visualizacion de los resultados del modelo lineal\n\nplt.scatter(X,y,color=\"red\")\nplt.plot(X,lineal_reg.predict(X),color=\"blue\")\nplt.title(\"Modelo de regresion lineal\")\nplt.xlabel(\"Posición del empleado\")\nplt.ylabel(\"Sueldo en $\")\nplt.show()\n\n#visualizacipon de los resultados del modelo polinómico\nX_grid=np.arange(min(X),max(X),0.1) # Ajustar los valores de X para un mejro calidad en la grafica(unicamente)\nX_grid=X_grid.reshape(len(X_grid),1)\nplt.scatter(X,y,color=\"red\")\n#plt.plot(X,lin_reg_2.predict(X_poly),color=\"blue\")\nplt.plot(X_grid,lin_reg_2.predict(poly_reg.fit_transform(X_grid)),color=\"blue\")\nplt.title(\"Modelo de regresion polinomica\")\nplt.xlabel(\"Posición del empleado\")\nplt.ylabel(\"Sueldo en $\")\nplt.show()\n\n\n#Predicción de los modelos\n\nlineal_reg.predict([[6.5]])\n\nlin_reg_2.predict(poly_reg.fit_transform([[6.5]]))\n\n\n\n\n\n\n","sub_path":"ML-Practicas/P2 - Linear Regresion/polinomial_regression.py","file_name":"polinomial_regression.py","file_ext":"py","file_size_in_byte":2112,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"264632764","text":"import sys, os\nsys.path.insert(0, os.path.abspath('.'))\nsys.path.insert(1, os.path.abspath('..'))\n\nfrom fhipe import ipe\nfrom timeit import default_timer as timer\n\n#Query being run is\n# SELECT * FROM a, b WHERE b.x = 3\n\ndef inner_join(a_table,b_table):\n\tret = ''\n\tcount = 0;\n\ta_enc_attributes = [];\n\tb_enc_attributes = [];\n\ta_pt_attributes = [];\n\tb_pt_attributes = [];\n\t(pp,sk, k) = ipe.setup(7);\n\n\tb_row = b_table.readline().rstrip()\n\twhile(b_row != ''):\n\t\tb_values = b_row.split(',');\n\n\t\t(ct2,tag2) = ipe.generateVectorY(b_values[0].rstrip().encode(), b_values[1].rstrip(), str(3), k, sk)\n\n\t\tb_enc_attributes.append((tag2,ct2))\n\t\tb_pt_attributes.append(b_values);\n\n\t\tb_row = b_table.readline().rstrip()\n\n\ta_row = a_table.readline().rstrip()\n\twhile(a_row != ''):\n\t\ta_values = a_row.split(',');\n\t\t(ct1,tag1) = ipe.generateVectorX(a_values[0].rstrip().encode(), 3, k, sk)\n\t\ta_pt_attributes.append(a_values);\n\t\ta_enc_attributes.append((ct1,tag1))\n\t\ta_row = a_table.readline().rstrip()\n\n\tstart = timer()\n\n\tfor x in range(0,len(a_pt_attributes)):\n\t\t(tag2, ct2) = a_enc_attributes[x];\n\t\tfor y in range(0,len(b_pt_attributes)):\n\t\t\tif((b_pt_attributes[y])[1] == str(3)):\n\t\t\t\t(tag1, ct1) = b_enc_attributes[y];\n\t\t\t\tif(ipe.decrypt(pp, tag2, ct2) == ipe.decrypt(pp, tag1, ct1)):\n\t\t\t\t\tcount=count+1;\n\tend = timer();\n\tprint(count)\n\tprint(str(end - start)+\"\\n\")\n\nopt = sys.argv\nif(len(opt) != 3):\n\tprint(\"Expecting 2 input tables\")\n\texit(-1)\n\ninner_join(open(opt[1]),open(opt[2]))","sub_path":"fhipe/join.py","file_name":"join.py","file_ext":"py","file_size_in_byte":1467,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"379120499","text":"#!/usr/bin/env python3\n# -*- coding:utf-8 -*-\n# Created by airvip on 2018/8/20 15:15.\n\n\ndef bubble_sort(nums):\n for i in range(len(nums) - 1): # 控制冒泡排序进行次数\n for j in range(len(nums) - i -1): # 控制每次比较的次数\n if nums[j] > nums[j+1]:\n nums[j], nums[j+1] = nums[j+1], nums[j]\n return nums\n\nif __name__ == \"__main__\":\n list_nums = [32, 24, 19, 55, 30, 22, 8]\n list_res = bubble_sort(list_nums)\n print(list_res)\n\n\n","sub_path":"algorithm/冒泡排序.py","file_name":"冒泡排序.py","file_ext":"py","file_size_in_byte":493,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"385732638","text":"class Machine():\n\n def __init__(self):\n self._ram = [0, 0, 0, 0, 1]\n self._ptr = 2\n\n def _allocate(self):\n if self._ptr < 0:\n self._ram.insert(0, -1)\n self._ptr += 1;\n assert self._ptr == 0\n elif self._ptr > (len(self._ram) - 1):\n self._ram.append(-1)\n assert self._ptr == len(self._ram) - 1\n\n def left(self):\n self._ptr -= 1\n self._allocate()\n\n def right(self):\n self._ptr += 1\n self._allocate()\n\n def write(self, number):\n assert number in [0, 1]\n self._ram[self._ptr] = number\n\n def show(self):\n return self._ram[self._ptr]\n\n def print(self):\n while 1:\n try:\n self._ram.remove(-1)\n except ValueError:\n break\n return self._ram\n\n\ndef run(cond1, cond2, cond3):\n\n for i in range(100):\n if machine.show() == cond1:\n machine.write(0)\n machine.left()\n machine.write(1)\n machine.left()\n\n if machine.show() == cond2:\n continue;\n else:\n pass\n\n else:\n machine.right()\n #pass\n if machine.show() != cond3:\n continue;\n else:\n machine.left()\n if machine.show() == cond2:\n continue\n else:\n pass\n\n return;\n raise RuntimeError\n\ndef check(answer):\n if answer == [1, 0, 0, 0, 0]:\n return True\n else:\n return False\n\ndef get_cond():\n cond = [-1, 0, 1]\n a = 0\n b = 0\n c = 0\n yield (cond[a], cond[b], cond[c])\n\n while 1:\n c += 1\n if c == 3:\n b += 1\n c = 0\n if b == 3:\n a += 1\n b = 0\n if a == 3:\n return\n yield (cond[a], cond[b], cond[c])\n\n\nfor cond1, cond2, cond3 in get_cond():\n machine = Machine()\n try:\n print(\"try %d, %d, %d...\" % (cond1, cond2, cond3))\n run(cond1, cond2, cond3)\n except RuntimeError:\n print(machine.print(), \"=> infinite loop!\\n\")\n continue\n\n if check(machine.print()):\n print(machine.print(), \"=> good!\")\n #print(cond1, cond2, cond3, machine.print())\n break\n else:\n print(machine.print(), \"=> wrong!\\n\")\n continue\n","sub_path":"google-turing-doodle.py","file_name":"google-turing-doodle.py","file_ext":"py","file_size_in_byte":2406,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"200456607","text":"import json\nimport unittest\n\nfrom temporencUtils.components.baseComponent import BaseComponent\nfrom temporencUtils.temporencUtils import TemporencUtils\n\n\nclass BaseComponentTest(unittest.TestCase):\n\n def setUp(self):\n BaseComponentTest.template = {\n \"s\": {\n \"precision name\": \"\",\n \"value\": \"\",\n \"_binary\": {\n \"microseconds\": \"\",\n \"milliseconds\": \"\",\n \"nanoseconds\": \"\"}\n }}\n\n BaseComponentTest.obj = TemporencUtils.packb(\n value=None, type=None, year=1983, month=None,\n day=None, hour=None, minute=None, second=None,\n millisecond=None, microsecond=None, nanosecond=None,\n tz_offset=None)\n\n\nif __name__ == \"__main__\":\n # noinspection PyUnresolvedReferences\n unittest.main()\n","sub_path":"temporencUtils/components/tests/base_component_test.py","file_name":"base_component_test.py","file_ext":"py","file_size_in_byte":864,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"535804761","text":"\r\n#make sure to install pygame and pymunk using CMD if you havent already\r\n#type pip install pygame\r\n#pip install pymunk\r\nimport pygame\r\nimport random\r\nimport os\r\nimport pymunk\r\nbg = pygame.image.load('bg.png')\r\n\r\n#these are the screen stats\r\nWIDTH = 1000\r\nHEIGHT = 585\r\nFPS = 40\r\nleft = False\r\nright = False\r\nup = False\r\ndown = False\r\nwalkcount = 0\r\nx = 500\r\ny = 400\r\nspeed = 3\r\nboost = 0\r\nbooststa = False\r\nrunning = True\r\nfolder = os.path.dirname(__file__)\r\nbg = pygame.image.load(os.path.join(folder,'bg.png'))\r\nwalkup=[pygame.image.load(os.path.join(folder,'U1.png')),pygame.image.load(os.path.join(folder,'U2.png'))]\r\nwalkdown=[pygame.image.load(os.path.join(folder,'D1.png')),pygame.image.load(os.path.join(folder,'D2.png'))]\r\nwalkleft=[pygame.image.load(os.path.join(folder,'L1.png')),pygame.image.load(os.path.join(folder,'L2.png'))]\r\nwalkright=[pygame.image.load(os.path.join(folder,'R1.png')),pygame.image.load(os.path.join(folder,'R2.png'))]\r\nchar = pygame.image.load(os.path.join(folder,'char.png'))\r\n\r\n #this are some pre requisutes\r\npygame.init()\r\npygame.mixer.init()\r\n\r\n\r\n\r\n# window properties\r\nscreen=pygame.display.set_mode((WIDTH, HEIGHT))\r\npygame.display.set_caption(\"game\")\r\nclock = pygame.time.Clock()\r\n\r\ndef Screendraw():\r\n global char\r\n global x\r\n global y\r\n global walkcount\r\n #pygame.draw.rect(screen,(0, 0, 0),(x, y, 40, 40))\r\n pygame.display.update()\r\n #screen.fill((255, 255, 255))\r\n screen.blit(bg,(0,0))\r\n #these set of commands are to set the screen to reset on the edge\r\n if x < 0:\r\n x = WIDTH\r\n\r\n if x > WIDTH:\r\n x = 0\r\n\r\n if y < 0:\r\n y = HEIGHT\r\n\r\n if y > HEIGHT:\r\n y = 0\r\n\r\nclass Player:\r\n def __init__(self,x,y):\r\n self.x=x\r\n self.y=y\r\n self.left = False\r\n self.right = False\r\n self.up = False\r\n self.down = False\r\n self.walkcount = 0\r\n self.speed = 3\r\n self.boost = 0\r\n\r\n def draw(self,screen):\r\n global walkup\r\n global walkleft\r\n global walkdown\r\n global walkright\r\n if self.walkcount>1:\r\n self.walkcount=0\r\n if self.left==True:\r\n screen.blit(walkleft[self.walkcount], (x, y))\r\n self.walkcount+=1\r\n elif self.right==True:\r\n screen.blit(walkright[self.walkcount], (x, y))\r\n self.walkcount+=1\r\n elif self.up==True:\r\n screen.blit(walkup[self.walkcount//4], (x, y))\r\n self.walkcount+=1\r\n elif self.down==True:\r\n screen.blit(walkdown[self.walkcount//4], (x, y))\r\n self.walkcount+=1\r\n else:\r\n screen.blit(char, (x, y))\r\n def Movement(self):\r\n global y\r\n global x\r\n global speed\r\n keys = pygame.key.get_pressed()\r\n #Movment keys\r\n if keys[pygame.K_LEFT]:\r\n self.left = True\r\n self.right = False\r\n x -= speed\r\n self.up = False\r\n self.down = False\r\n speed += boost\r\n elif keys[pygame.K_RIGHT]:\r\n self.left = False\r\n self.right = True\r\n x += speed\r\n self.up = False\r\n self.down = False\r\n self.speed += self.boost\r\n elif keys[pygame.K_UP]:\r\n y -= speed\r\n self.left = False\r\n self.right = False\r\n self.up = True\r\n self.down = False\r\n self.speed += self.boost\r\n elif keys[pygame.K_DOWN]:\r\n y += speed\r\n self.left = False\r\n self.right = False\r\n self.up = False\r\n self.down = True\r\n self.speed += self.boost\r\n else:\r\n self.left = False\r\n self.right = False\r\n self.up = False\r\n self.down = False\r\n self.walkcount = 0\r\n\r\nclass Enemy:\r\n pass\r\n\r\n\r\nplayer1=Player(x,y)\r\n\r\n#game loop\r\n\r\nwhile running:\r\n # to set the loop speed to the game FPS to prevent Lag\r\n #if you know a better method please do it\r\n clock.tick(FPS)\r\n #Process input (events)\r\n for event in pygame.event.get():\r\n #in case player wants to quit\r\n if event.type == pygame.QUIT:\r\n running = False\r\n #Update\r\n player1.draw(screen)\r\n player1.Movement()\r\n Screendraw()\r\n\r\n\r\n\r\n #this is the background section it is black\r\n #i dont know if you want to add background pictures\r\n\r\n#quit\r\npygame.quit()\r\n","sub_path":"Game1.py","file_name":"Game1.py","file_ext":"py","file_size_in_byte":4451,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"602368866","text":"import matplotlib as mpl\nmpl.use('pgf')\nimport matplotlib.pyplot as plt\nplt.style.use('./plots/a4.mplstyle')\nimport pickle\nimport numpy as np\n\nwith open('data/gauss_cluster_data.pickle','br') as file:\n gauss_cluster_data = pickle.load(file)\n\nx = []\ny = []\nyerr = []\n\nfor key in list(gauss_cluster_data):\n N, beta = key\n susc_mean = gauss_cluster_data[key]['susc_mean']\n susc_err = gauss_cluster_data[key]['susc_err']\n\n x.append(1./beta)\n y.append(susc_mean)\n #y.append((cluster_data[key]['charges'][100000:]**2/key[0]**2).mean())\n yerr.append(susc_err)\n\nfig, axs = plt.subplots(1,2,figsize=(4.7,3),sharey=True)\n\naxs[1].errorbar(x,y,yerr, fmt='s', markerfacecolor='none',capsize=1.5,label='Gauss cluster')\naxs[1].set_xlim(xmin=0, xmax=0.6)\naxs[1].set_ylim(ymin=0.0225)\naxs[1].legend()\naxs[1].set_xlabel(r'$\\frac{1}{\\beta}$')\naxs[1].tick_params(axis='y',direction='inout')\n\nbeta_durr, y_durr, yerr_durr = np.loadtxt('data/durr-hoelbling.dat',unpack=True)\naxs[0].errorbar(1/beta_durr,y_durr,yerr_durr, fmt='D',color='C1',markerfacecolor='none',capsize=1.5,label='Durr-Hoelbling')\naxs[0].set_xlim(xmin=0.6,xmax=0)\naxs[0].legend()\naxs[0].set_xlabel(r'$\\frac{1}{\\beta}$')\naxs[0].set_ylabel(r'$\\frac{\\chi}{g^2}$')\n\nticks = axs[0].xaxis.get_major_ticks()\nticks[0].label1.set_visible(False)\n\nfig.suptitle('Topological susceptivity: continuum limit')\nfig.subplots_adjust(wspace=0)\nfig.subplots_adjust(left=0.221)\nfig.subplots_adjust(right=0.983)\nfig.subplots_adjust(bottom=0.20)\n\nplt.savefig('gfx/susc_cont.pgf')\n\n","sub_path":"plots/susc_cont.py","file_name":"susc_cont.py","file_ext":"py","file_size_in_byte":1528,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"161207341","text":"import sys, string, codecs;\n\nMAGIC = 3078783;\nidx = 0;\n\ninf = open(sys.argv[1]);\noutf = open(sys.argv[1] + '.' + str(idx), 'w');\n\ncur_len = 0\ncur_lemma = '';\n\ndef read_line(fd): #{\n\tlemma = '';\n\trest = '';\n\n\tc = fd.read(1);\n\n\tif c == '':\n\t\treturn False;\n\n\twhile c != ';':\n\t\tlemma = lemma + c;\n\t\tc = fd.read(1);\n\t\n\twhile c != '\\n':\n\t\trest = rest + c;\n\t\tc = fd.read(1);\n\n\treturn (lemma, rest);\n#}\n\nwhile 1: #{\n\tline = read_line(inf);\n\n\tif line == False:\n\t\tbreak;\n\n\tcur_lemma = line[0];\n\n\tcur_len = cur_len + len(line[0] + line[1]);\n\n\tif cur_len > MAGIC: #{\n\t\toutline = line[0] + line[1];\n\t\toutf.write(outline + '\\n');\n\t\toutf.flush();\n\t\tprint('+ ' , sys.argv[1] + '.' + str(idx) + ':' , cur_len , ' > ' , MAGIC , ' @ ' + cur_lemma);\n\t\toverline = read_line(inf);\n\t\toutf.write(overline[0] + overline[1] + '\\n');\n\t\twhile 1: #{\n\t\t\toverline = read_line(inf);\n\t\t\tif overline[0] != cur_lemma: #{\n\t\t\t\tbreak;\n\t\t\t#}\n\t\t\toutf.write(overline[0] + overline[1] + '\\n');\n\t\t\toutf.flush();\n\t\t#}\n\t\tcur_len = 0;\n\t\tidx = idx + 1;\n\t\toutf.close();\n\t\toutf = open(sys.argv[1] + '.' + str(idx), 'w');\n\t\toutf.write(overline[0] + overline[1] + '\\n');\n\t\tcontinue;\n\t#}\n\n\toutline = line[0] + line[1];\n\toutf.write(outline + '\\n');\n\toutf.flush();\n#}\n\noutf.close();\ninf.close();\n","sub_path":"apertium-tools/speling/split-speling.py","file_name":"split-speling.py","file_ext":"py","file_size_in_byte":1242,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"582606215","text":"def max_even_seq(n):\n cntp=0\n while (n>0):\n cntl=0\n if((n%10)%2==0):\n while ((n>0) and ((n%10)%2==0)): #while the last digit is an evan number and the number is not 0\n cntl=cntl+1\n n=n//10\n if (cntl>cntp):\n cntp=cntl\n else:\n n=n//10\n return cntp\n\n\n","sub_path":"max_even_seq/subs/2017B/29.py","file_name":"29.py","file_ext":"py","file_size_in_byte":356,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"632084150","text":"###\n# Copyright (c) 2017 Nike Inc.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n###\n\nfrom io import open\nfrom troposphere import Ref, Template, Parameter, Output, GetAtt, Join, AWS_ACCOUNT_ID\nfrom troposphere.autoscaling import AutoScalingGroup, LaunchConfiguration\nfrom troposphere.cloudfront import Distribution, DefaultCacheBehavior, ForwardedValues, DistributionConfig, Origin, \\\n CustomOrigin, ViewerCertificate, Logging\nfrom troposphere.elasticloadbalancing import LoadBalancer, ConnectionDrainingPolicy, ConnectionSettings, HealthCheck, \\\n Listener, Policy\nfrom troposphere.policies import UpdatePolicy, AutoScalingRollingUpdate\nfrom troposphere.route53 import RecordSetType\nfrom troposphere.waf import WebACL, Action, Rule, SizeConstraintSet, SizeConstraint, FieldToMatch, Predicates, Rules, \\\n IPSet, SqlInjectionMatchSet, SqlInjectionMatchTuples, XssMatchSet, XssMatchTuple\nfrom troposphere.s3 import Bucket, BucketOwnerFullControl, NotificationConfiguration, LambdaConfigurations, Filter, \\\n S3Key, Rules as S3Rules, BucketPolicy\nfrom troposphere.awslambda import Function, Code, Permission\n\nfrom smaas.support.tags import CerberusTags\n\nCF_FILE = '../../src/main/resources/cloudformation/gateway-cluster.json'\nCLOUD_FRONT_PREFIX = 'cf-logs/'\n\n# Create Template\ntemplate = Template()\ntemplate.description = \"Launches the gateway cluster in the Cerberus VPC\"\ntemplate.version = '2010-09-09'\n\n###\n#\n# Inputs\n#\n###\n\ncerberus_tags = CerberusTags()\ncerberus_tags.add_tag_parameters(template)\n\ncert_public_key_param = template.add_parameter(Parameter(\n \"certPublicKey\",\n Description=\"TLS certificate public key to be used for backend authentication\",\n Type=\"String\"\n))\n\nssl_certificate_arn_param = template.add_parameter(Parameter(\n \"sslCertificateArn\",\n Description=\"TLS certificate ARN for the ELB\",\n Type=\"String\"\n))\n\nssl_certificate_id_param = template.add_parameter(Parameter(\n \"sslCertificateId\",\n Description=\"TLS certificate ID for the CloudFront distribution and ELB\",\n Type=\"String\"\n))\n\nvpc_id_param = template.add_parameter(Parameter(\n \"vpcId\",\n Description=\"The ID of the VPC\",\n Type=\"AWS::EC2::VPC::Id\"\n))\n\ninstance_profile_name_param = template.add_parameter(Parameter(\n \"instanceProfileName\",\n Description=\"The name for the instance profile\",\n Type=\"String\"\n))\n\nami_id_param = template.add_parameter(Parameter(\n \"amiId\",\n Description=\"The AMI ID for the instances\",\n Type=\"String\"\n))\n\ninstance_size_param = template.add_parameter(Parameter(\n \"instanceSize\",\n Description=\"The instance size\",\n Type=\"String\"\n))\n\ngateway_elb_sg_id_param = template.add_parameter(Parameter(\n \"gatewayElbSgId\",\n Description=\"Gateway Server ELB Security Group ID\",\n Type=\"AWS::EC2::SecurityGroup::Id\"\n))\n\ngateway_server_sg_id_param = template.add_parameter(Parameter(\n \"gatewayServerSgId\",\n Description=\"Gateway Server Security Group ID\",\n Type=\"AWS::EC2::SecurityGroup::Id\"\n))\n\ntools_ingress_sg_id_param = template.add_parameter(Parameter(\n \"toolsIngressSgId\",\n Description=\"Tools Ingress Security Group ID\",\n Type=\"AWS::EC2::SecurityGroup::Id\"\n))\n\ncloud_front_log_processor_lambda_iam_role_param = template.add_parameter(Parameter(\n \"cloudFrontLogProcessorLambdaIamRoleArn\",\n Description=\"The IAM Role Arn for the lambda\",\n Type=\"String\"\n))\n\nsubnet_id_refs = []\nfor zone_identifier in range(1, 4):\n vpc_subnet_id = template.add_parameter(Parameter(\n \"vpcSubnetIdForAz{0}\".format(zone_identifier),\n Description=\"VPC Subnet ID for Zone {0}\".format(zone_identifier),\n Type=\"String\"\n ))\n\n subnet_id_refs.append(Ref(vpc_subnet_id))\n\nkey_pair_name_param = template.add_parameter(Parameter(\n \"keyPairName\",\n Description=\"The key pair to be associated with the EC2 instances\",\n Type=\"String\",\n Default=\"cpe-cerberus\"\n))\n\ngateway_user_data_param = template.add_parameter(Parameter(\n \"userData\",\n Description=\"Gateway User Data\",\n Type=\"String\"\n))\n\nhosted_zone_id_param = template.add_parameter(Parameter(\n \"hostedZoneId\",\n Description=\"The hosted zone id to associate the CNAME record with\",\n Type=\"String\"\n))\n\nhostname_param = template.add_parameter(Parameter(\n \"hostname\",\n Description=\"The base hostname for the public facing gateway / router\",\n Type=\"String\"\n))\n\nwaf_lambda_bucket = template.add_parameter(Parameter(\n \"wafLambdaBucket\",\n Type=\"String\",\n Description=\"S3 Bucket for waf lambda function artifact\"\n))\n\nwaf_lambda_key = template.add_parameter(Parameter(\n \"wafLambdaKey\",\n Type=\"String\",\n Description=\"Key for waf lambda function artifact\"\n))\n\ndesired_instances_param = template.add_parameter(Parameter(\n \"desiredInstances\",\n Description=\"Desired Number of Auto Scaling Instances\",\n Type=\"Number\"\n))\n\nmaximum_instances_param = template.add_parameter(Parameter(\n \"maximumInstances\",\n Description=\"Maximum Number of Auto Scaling Instances\",\n Type=\"Number\"\n))\n\nminimum_instances_param = template.add_parameter(Parameter(\n \"minimumInstances\",\n Description=\"Minimum Number of Auto Scaling Instances\",\n Type=\"Number\"\n))\n\n###\n#\n# Elastic Load Balancer\n#\n###\n\ngateway_load_balancer = template.add_resource(LoadBalancer(\n \"GatewayElasticLoadBalancer\",\n ConnectionDrainingPolicy=ConnectionDrainingPolicy(\n Enabled=True,\n Timeout=10\n ),\n ConnectionSettings=ConnectionSettings(\n IdleTimeout=10\n ),\n CrossZone=True,\n HealthCheck=HealthCheck(\n HealthyThreshold=2,\n Interval=5,\n Target=\"HTTPS:443/sys/health\",\n Timeout=2,\n UnhealthyThreshold=2\n ),\n Listeners=[\n Listener(\n InstancePort=443,\n InstanceProtocol=\"HTTPS\",\n LoadBalancerPort=443,\n PolicyNames=[\n \"GatewayTLSNegotiationPolicy\"\n ],\n Protocol=\"HTTPS\",\n SSLCertificateId=Ref(ssl_certificate_arn_param)\n )\n ],\n Policies=[\n Policy(\n PolicyName=\"GatewayTLSNegotiationPolicy\",\n PolicyType=\"SSLNegotiationPolicyType\",\n Attributes=[\n {\n \"Name\": \"Reference-Security-Policy\",\n \"Value\": \"ELBSecurityPolicy-2015-05\"\n }\n ]\n ),\n Policy(\n PolicyName=\"GatewayPublicKeyPolicy\",\n PolicyType=\"PublicKeyPolicyType\",\n Attributes=[\n {\n \"Name\": \"PublicKey\",\n \"Value\": Ref(cert_public_key_param)\n }\n ]\n ),\n Policy(\n PolicyName=\"GatewayBackendServerAuthenticationPolicy\",\n PolicyType=\"BackendServerAuthenticationPolicyType\",\n Attributes=[\n {\n \"Name\": \"PublicKeyPolicyName\",\n \"Value\": \"GatewayPublicKeyPolicy\"\n }\n ],\n InstancePorts=[\n \"443\"\n ]\n )\n ],\n Scheme=\"internet-facing\",\n SecurityGroups=[\n Ref(gateway_elb_sg_id_param)\n ],\n Subnets=subnet_id_refs,\n Tags=cerberus_tags.get_tags_as_list()\n))\n\n###\n#\n# Launch Configuration and Auto Scaling Group for Gateway\n#\n###\n\ngateway_launch_config = template.add_resource(LaunchConfiguration(\n \"GatewayLaunchConfiguration\",\n AssociatePublicIpAddress=True,\n IamInstanceProfile=Ref(instance_profile_name_param),\n ImageId=Ref(ami_id_param),\n InstanceMonitoring=True,\n InstanceType=Ref(instance_size_param),\n KeyName=Ref(key_pair_name_param),\n SecurityGroups=[\n Ref(tools_ingress_sg_id_param),\n Ref(gateway_server_sg_id_param),\n ],\n UserData=Ref(gateway_user_data_param)\n))\n\ngateway_autoscaling_group = template.add_resource(AutoScalingGroup(\n \"GatewayAutoScalingGroup\",\n DesiredCapacity=Ref(desired_instances_param),\n HealthCheckGracePeriod=300,\n HealthCheckType=\"ELB\",\n LaunchConfigurationName=Ref(gateway_launch_config),\n LoadBalancerNames=[\n Ref(gateway_load_balancer)\n ],\n MaxSize=Ref(maximum_instances_param),\n MinSize=Ref(minimum_instances_param),\n UpdatePolicy=UpdatePolicy(\n AutoScalingRollingUpdate=AutoScalingRollingUpdate(\n MaxBatchSize=1,\n MinInstancesInService=2,\n PauseTime=\"PT3M\"\n )\n ),\n VPCZoneIdentifier=subnet_id_refs,\n Tags=cerberus_tags.get_autoscaling_tags_as_list()\n))\n\n###\n#\n# Record Set for public Cerberus CNAME\n#\n###\n\ngateway_record_set = template.add_resource(RecordSetType(\n \"OriginCerberusPublicRecordSet\",\n HostedZoneId=Ref(hosted_zone_id_param),\n Name=Join(\".\", [\"origin\", Ref(hostname_param), \"\"]),\n TTL=30,\n Type=\"CNAME\",\n ResourceRecords=[GetAtt(gateway_load_balancer, \"CanonicalHostedZoneName\")]\n))\n\n###\n#\n# WAF Web ACL\n#\n###\n\nxss_match_set = template.add_resource(XssMatchSet(\n \"CerberusWafXssMatchSet\",\n Name=\"CerberusWafXssMatchSet\",\n XssMatchTuples=[\n XssMatchTuple(\n \"CerberusWafXssUriMatch\",\n FieldToMatch=FieldToMatch(\n Type=\"URI\"\n ),\n TextTransformation=\"NONE\"\n ),\n XssMatchTuple(\n \"CerberusWafXssQueryStringMatch\",\n FieldToMatch=FieldToMatch(\n Type=\"QUERY_STRING\"\n ),\n TextTransformation=\"NONE\"\n ),\n XssMatchTuple(\n \"CerberusWafXssBodyMatch\",\n FieldToMatch=FieldToMatch(\n Type=\"BODY\"\n ),\n TextTransformation=\"NONE\"\n )\n ]\n))\n\nxss_rule = template.add_resource(Rule(\n \"CerberusWafXssRule\",\n Name=\"CerberusWafXssRule\",\n MetricName=\"CerberusWafXss\",\n Predicates=[\n Predicates(\n DataId=Ref(xss_match_set),\n Negated=False,\n Type=\"XssMatch\"\n )\n ]\n))\n\nsql_injection_match_set = template.add_resource(SqlInjectionMatchSet(\n \"CerberusWafSqlInjectionMatchSet\",\n Name=\"CerberusWafSqlInjectionMatchSet\",\n SqlInjectionMatchTuples=[\n SqlInjectionMatchTuples(\n \"CerberusWafSqlInjectionUriMatch\",\n FieldToMatch=FieldToMatch(\n Type=\"URI\"\n ),\n TextTransformation=\"NONE\"\n ),\n SqlInjectionMatchTuples(\n \"CerberusWafSqlInjectionQueryStringMatch\",\n FieldToMatch=FieldToMatch(\n Type=\"QUERY_STRING\"\n ),\n TextTransformation=\"NONE\"\n ),\n SqlInjectionMatchTuples(\n \"CerberusWafSqlInjectionBodyMatch\",\n FieldToMatch=FieldToMatch(\n Type=\"BODY\"\n ),\n TextTransformation=\"NONE\"\n )\n ]\n))\n\nsql_injection_rule = template.add_resource(Rule(\n \"CerberusWafSqlInjectionRule\",\n Name=\"CerberusWafSqlInjectionRule\",\n MetricName=\"CerberusWafSqlInjection\",\n Predicates=[\n Predicates(\n DataId=Ref(sql_injection_match_set),\n Negated=False,\n Type=\"SqlInjectionMatch\"\n )\n ]\n))\n\nsize_constraint_set = template.add_resource(SizeConstraintSet(\n \"CerberusWafSizeConstraintSet\",\n Name=\"CerberusWafSizeConstraintSet\",\n SizeConstraints=[\n SizeConstraint(\n \"CerberusWafSizeConstraint\",\n ComparisonOperator=\"GE\",\n FieldToMatch=FieldToMatch(\n Type=\"BODY\"\n ),\n Size=256000,\n TextTransformation=\"NONE\"\n )\n ]\n))\n\nsize_constraint_rule = template.add_resource(Rule(\n \"CerberusWafSizeConstraintRule\",\n Name=\"CerberusWafSizeConstraintRule\",\n MetricName=\"CerberusWafSizeConstraint\",\n Predicates=[\n Predicates(\n DataId=Ref(size_constraint_set),\n Negated=False,\n Type=\"SizeConstraint\"\n )\n ]\n))\n\nwaf_white_list_set = template.add_resource(IPSet(\n \"WAFWhiteListSet\",\n Name=\"White List Set\"\n))\n\nwaf_manual_block_set = template.add_resource(IPSet(\n \"WAFManualBlockSet\",\n Name=\"Manual Block Set\"\n))\n\nwaf_auto_block_set = template.add_resource(IPSet(\n \"WAFAutoBlockSet\",\n Name=\"Auto Block Set\"\n))\n\nwaf_white_list_rule = template.add_resource(Rule(\n \"WAFWhiteListRule\",\n DependsOn=\"WAFWhiteListSet\",\n Name=\"White List Rule\",\n MetricName=\"WhiteListRule\",\n Predicates=[\n Predicates(\n DataId=Ref(waf_white_list_set),\n Negated=False,\n Type=\"IPMatch\"\n )\n ]\n))\n\nwaf_manual_block_rule = template.add_resource(Rule(\n \"WAFManualBlockRule\",\n DependsOn=\"WAFManualBlockSet\",\n Name=\"Manual Block Rule\",\n MetricName=\"ManualBlockRule\",\n Predicates=[\n Predicates(\n DataId=Ref(waf_manual_block_set),\n Negated=False,\n Type=\"IPMatch\"\n )\n ]\n))\n\nwaf_auto_block_rule = template.add_resource(Rule(\n \"WAFAutoBlockRule\",\n DependsOn=\"WAFAutoBlockSet\",\n Name=\"Auto Block Rule\",\n MetricName=\"AutoBlockRule\",\n Predicates=[\n Predicates(\n DataId=Ref(waf_auto_block_set),\n Negated=False,\n Type=\"IPMatch\"\n )\n ]\n))\n\nweb_acl = template.add_resource(WebACL(\n \"CerberusWAFWebAcl\",\n DependsOn=[\"WAFManualBlockRule\", \"WAFAutoBlockRule\"],\n MetricName=\"CerberusWAF\",\n DefaultAction=Action(\n Type=\"ALLOW\"\n ),\n Name=Join(\".\", [\"waf\", Ref(hostname_param)]),\n Rules=[\n Rules(\n Action=Action(\n Type=\"BLOCK\"\n ),\n Priority=1,\n RuleId=Ref(size_constraint_rule)\n ),\n Rules(\n Action=Action(\n Type=\"BLOCK\"\n ),\n Priority=2,\n RuleId=Ref(sql_injection_rule)\n ),\n Rules(\n Action=Action(\n Type=\"BLOCK\"\n ),\n Priority=3,\n RuleId=Ref(xss_rule)\n ),\n Rules(\n Action=Action(\n Type=\"ALLOW\"\n ),\n Priority=4,\n RuleId=Ref(waf_white_list_rule)\n ),\n Rules(\n Action=Action(\n Type=\"BLOCK\"\n ),\n Priority=5,\n RuleId=Ref(waf_manual_block_rule)\n ),\n Rules(\n Action=Action(\n Type=\"BLOCK\"\n ),\n Priority=6,\n RuleId=Ref(waf_auto_block_rule)\n )\n ]\n))\n\n###\n#\n# WAF Lambda Function\n#\n###\n\nlambda_waf_blacklisting_function = template.add_resource(Function(\n \"LambdaWAFBlacklistingFunction\",\n Description=\"Function for auto black listing ips that are misbehaving\",\n Handler=\"com.nike.cerberus.lambda.waf.handler.CloudFrontLogEventHandler::handleNewS3Event\",\n Role=Ref(cloud_front_log_processor_lambda_iam_role_param),\n Code=Code(\n S3Bucket=Ref(waf_lambda_bucket),\n S3Key=Ref(waf_lambda_key)\n ),\n Runtime=\"java8\",\n MemorySize=\"512\",\n Timeout=\"60\"\n))\n\nlambda_invoke_permission = template.add_resource(Permission(\n \"LambdaInvokePermission\",\n DependsOn=\"LambdaWAFBlacklistingFunction\",\n FunctionName=GetAtt(lambda_waf_blacklisting_function, \"Arn\"),\n Action=\"lambda:*\",\n Principal=\"s3.amazonaws.com\",\n SourceAccount=Ref(AWS_ACCOUNT_ID)\n))\n\n###\n#\n# Bucket for Cloud Front Logs\n#\n###\n\ncloud_front_logs_bucket = template.add_resource(Bucket(\n \"CloudFrontBucket\",\n AccessControl=BucketOwnerFullControl,\n Tags=cerberus_tags.get_tags(),\n NotificationConfiguration=NotificationConfiguration(\n LambdaConfigurations=[LambdaConfigurations(\n Event=\"s3:ObjectCreated:*\",\n Filter=Filter(\n S3Key=S3Key(\n Rules=[S3Rules(\n Name=\"suffix\",\n Value=\"gz\"\n )]\n )\n ),\n Function=GetAtt(lambda_waf_blacklisting_function, \"Arn\")\n )]\n )\n))\n\ncloud_front_logs_bucket_policy = template.add_resource(BucketPolicy(\n \"CloudFrontLogsBucketPolicy\",\n Bucket=Ref(cloud_front_logs_bucket),\n PolicyDocument={\n \"Version\": \"2012-10-17\",\n \"Statement\": [\n {\n \"Sid\": \"Allow-CloudFront-Log-Access\",\n \"Effect\": \"Allow\",\n \"Principal\": {\n \"AWS\": [\n Ref(cloud_front_log_processor_lambda_iam_role_param)\n ]\n },\n \"Action\": [\n \"s3:*\"\n ],\n \"Resource\": [\n {\n \"Fn::Join\": [\n \"\",\n [\n \"arn:aws:s3:::\",\n Ref(cloud_front_logs_bucket),\n \"/*\"\n ]\n ]\n }\n ]\n }\n ]\n }\n\n))\n\n###\n#\n# Cloud Front for Web Application Firewall\n#\n###\n\ngateway_distribution = template.add_resource(Distribution(\n \"CerberusDistribution\",\n DistributionConfig=DistributionConfig(\n Aliases=[\n Ref(hostname_param)\n ],\n DefaultCacheBehavior=DefaultCacheBehavior(\n AllowedMethods=[\n \"GET\",\n \"PUT\",\n \"POST\",\n \"DELETE\",\n \"PATCH\",\n \"HEAD\",\n \"OPTIONS\"\n ],\n CachedMethods=[\n \"GET\",\n \"HEAD\",\n \"OPTIONS\"\n ],\n ForwardedValues=ForwardedValues(\n Headers=[\n \"*\"\n ],\n QueryString=True\n ),\n MaxTTL=0,\n MinTTL=0,\n DefaultTTL=0,\n TargetOriginId=\"CerberusGatewayOrigin\",\n ViewerProtocolPolicy=\"https-only\"\n ),\n Enabled=True,\n Origins=[\n Origin(\n Id=\"CerberusGatewayOrigin\",\n DomainName=Join(\".\", [\"origin\", Ref(hostname_param)]),\n CustomOriginConfig=CustomOrigin(\n HTTPSPort=\"443\",\n OriginProtocolPolicy=\"https-only\",\n OriginSSLProtocols=[\n \"TLSv1.2\"\n ]\n )\n )\n ],\n PriceClass=\"PriceClass_100\",\n ViewerCertificate=ViewerCertificate(\n IamCertificateId=Ref(ssl_certificate_id_param),\n MinimumProtocolVersion=\"TLSv1\",\n SslSupportMethod=\"sni-only\"\n ),\n WebACLId=Ref(web_acl),\n Logging=Logging(\n Bucket=GetAtt(cloud_front_logs_bucket, \"DomainName\")\n )\n )\n))\n\n###\n#\n# Record Set for public Cerberus Cloud Front CNAME\n#\n###\n\ncf_gateway_record_set = template.add_resource(RecordSetType(\n \"CerberusPublicRecordSet\",\n HostedZoneId=Ref(hosted_zone_id_param),\n Name=Join(\".\", [Ref(hostname_param), \"\"]),\n TTL=30,\n Type=\"CNAME\",\n ResourceRecords=[GetAtt(gateway_distribution, \"DomainName\")]\n))\n\n###\n#\n# Outputs\n#\n###\n\ntemplate.add_output(Output(\n \"autoscalingGroupLogicalId\",\n Value=Ref(gateway_autoscaling_group)\n))\n\ntemplate.add_output(Output(\n \"launchConfigurationLogicalId\",\n Value=Ref(gateway_launch_config)\n))\n\ntemplate.add_output(Output(\n \"elbLogicalId\",\n Value=Ref(gateway_load_balancer)\n))\n\ntemplate.add_output(Output(\n \"elbCanonicalHostedZoneNameId\",\n Value=GetAtt(gateway_load_balancer, \"CanonicalHostedZoneNameID\")\n))\n\ntemplate.add_output(Output(\n \"elbDnsName\",\n Value=GetAtt(gateway_load_balancer, \"DNSName\")\n))\n\ntemplate.add_output(Output(\n \"elbSourceSecurityGroupName\",\n Value=GetAtt(gateway_load_balancer, \"SourceSecurityGroup.GroupName\")\n))\n\ntemplate.add_output(Output(\n \"elbSourceSecurityGroupOwnerAlias\",\n Value=GetAtt(gateway_load_balancer, \"SourceSecurityGroup.OwnerAlias\")\n))\n\ntemplate.add_output(Output(\n \"cloudFrontDistributionId\",\n Value=Ref(gateway_distribution),\n))\n\ntemplate.add_output(Output(\n \"cloudFrontDistributionDomainName\",\n Value=GetAtt(gateway_distribution, \"DomainName\")\n))\n\ntemplate.add_output(Output(\n \"cloudFrontAccessLogBucket\",\n Value=Ref(cloud_front_logs_bucket)\n))\n\ntemplate.add_output(Output(\n \"whiteListIPSetID\",\n Value=Ref(waf_white_list_set)\n))\n\ntemplate.add_output(Output(\n \"manualBlockIPSetID\",\n Value=Ref(waf_manual_block_set)\n))\n\ntemplate.add_output(Output(\n \"autoBlockIPSetID\",\n Value=Ref(waf_auto_block_set)\n))\n\n###\n#\n# Print!\n#\n###\n\ncf_file = open(CF_FILE, 'w')\ncf_file.truncate()\ncf_file.write(template.to_json(indent=0))\ncf_file.close()\n\nprint(\"CloudFormation template written to: {0}\".format(CF_FILE))\n","sub_path":"smaas-cf/smaas/gateway-cluster.py","file_name":"gateway-cluster.py","file_ext":"py","file_size_in_byte":21150,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"6638211","text":"import jwt,sys,os\nfrom django.http import JsonResponse, HttpResponse\nfrom rest_framework.authentication import get_authorization_header\nfrom .models import PlantsList, user_details,userinfo,tokenblocklist\nimport datetime as dt\nfrom datetime import datetime, timedelta\nfrom calendar import timegm\n\n\n\ndef validation(request):\n auth = get_authorization_header(request).split()\n\n if len(auth)==0:\n return JsonResponse({'message': \"Internal server error\",'success':2} )\n if len(auth) == 1:\n msg = 'Invalid token header '\n return JsonResponse({'message': msg,'success':2})\n elif len(auth) > 2:\n msg = 'Invalid token header'\n return JsonResponse({'message': msg,'success':2})\n try:\n print('auth[0]',auth[0])\n if auth[0].decode('utf-8').lower().strip() =='token':\n token = auth[1]\n print('token in def:', token)\n if token == \"null\":\n msg = 'Null token not allowed'\n return JsonResponse({'message': msg, 'success': 2})\n return authenticate_credentials(token)\n\n except UnicodeError:\n msg = 'Invalid token header. Token string should not contain invalid characters.'\n return JsonResponse({'message': msg,'success':2})\n\ndef authenticate_credentials(token):\n # model = get_model()\n # token = bytes(token)\n # print('came to authenticate token def::', token)\n try:\n\n try:\n # payload=jwt\n payload = jwt.decode(token, \"SECRET_KEY\", )\n except jwt.InvalidSignatureError:\n return JsonResponse({'message': \"INVALID_TOKEN\",'success':2})\n except jwt.ExpiredSignatureError:\n return JsonResponse({'message': \"Session Expired ,Please login\",'success':2})\n except jwt.DecodeError:\n return JsonResponse({'message': \"INVALID_TOKEN\",'success':2})\n\n username = payload['username']\n print('username:::\\t',username)\n # email = payload['email']\n time = payload['exp']\n print('time::', type(time))\n # msg = {'Error': \"Token mismatch\", 'status': \"401\"}\n try:\n # print(userinfo.objects.get(FIRST_NAME=email, WORK_EMAIL=userid))\n\n if tokenblocklist.objects.filter(token=token).count() > 0 :\n return JsonResponse({'message': \"Session Expired ,Please login\", 'success': 2})\n else:\n \n user = userinfo.objects.filter(USERNAME=username,IS_ACTIVE=True).all()\n for obj in user:\n print('obj.USERNAME::;\\t',obj.USERNAME)\n username_db = obj.USERNAME\n \n # email_db = obj.WORK_EMAIL\n print('token in auth::',token)\n if username_db.lower() == username.lower():\n if time:\n refresh_limit = dt.timedelta(days=1)\n if isinstance(refresh_limit, timedelta):\n # refresh_limit = refresh_limit.seconds\n refresh_limit = (refresh_limit.days * 24 * 3600 + refresh_limit.seconds)\n expiration_timestamp = time + int(refresh_limit)\n now_timestamp = timegm(datetime.utcnow().utctimetuple())\n if now_timestamp > expiration_timestamp:\n msg = 'Refresh has expired.'\n # raise serializers.ValidationError(msg)\n return JsonResponse({\"msg\": msg})\n new_payload = {'username': username, 'exp': expiration_timestamp}\n new_token = jwt.encode(new_payload, key='SECRET_KEY')\n print('token in if condtions:', new_token)\n\n return JsonResponse({'token': token.decode('utf-8'), 'username': username})\n if not username:\n return JsonResponse({'message': \"INVALID_TOKEN\",'success':2})\n\n except userinfo.DoesNotExist:\n return JsonResponse({'message': \"Internal server error\",'success':2})\n except Exception as e:\n exc_type, exc_obj, exc_tb = sys.exc_info()\n fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1]\n print(exc_type, fname, exc_tb.tb_lineno)\n print(type(e)) # the exception instance\n print(e.args) # arguments stored in .args\n print(e)\n return JsonResponse({'message':'Error in create_user insertion', 'success': 0})\n\n except jwt.ExpiredSignatureError:\n return JsonResponse({'message': \"Session Expired ,Please login\",'success':2} )\n\n\n\n","sub_path":"dfp/authentication.py","file_name":"authentication.py","file_ext":"py","file_size_in_byte":4701,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"203312661","text":"# Javier Mariño\nimport matplotlib.pyplot as plt\nimport numpy as np\n\ndimt = 2500 # número de iteraciones temporales\ndeltat = 0.1; deltax = 0.5; alfa = 0.1; N = 20 # parámetros naturales de la discretización\ns = alfa*deltat/deltax**2 # calculamos la estabilidad\n\nT = np.zeros(N+1)\nT[5:9]= 5+5*np.random.sample(4) # aleatorios distribuidos en torno a 5 con desviacion 5\nT[0]=T[1]\nT[N]=T[N-1]\n\nplt.close('all')\nplt.plot(np.arange(N+1)*deltax,T,'-r'); plt.pause(0.00001)\n\nfor n in range(dimt):\n\n\tfor i in range(1,N):\n\t\tT[i] = T[i]+alfa*deltat/deltax**2*(T[i+1]-2.*T[i]+T[i-1])\n\tT[0]=T[1] # condicion de frontera de flujo nulo\n\tT[N] = T[N-1]\n\n\tif n%20==0:\n\t\tplt.plot(np.arange(N+1)*deltax,T)\n\t\tplt.pause(0.00001)\n\t\tplt.show()\n\nplt.xlabel('$x$')\nplt.ylabel('$T$')\nplt.title('FTCS con cond. de Von Neumann')","sub_path":"bol8/bol8_ex1d_Mariño_Villadamigo_Javier.py","file_name":"bol8_ex1d_Mariño_Villadamigo_Javier.py","file_ext":"py","file_size_in_byte":803,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"125029153","text":"from django.shortcuts import render,redirect,render_to_response\nfrom django.contrib.auth.decorators import login_required\nfrom . import models as mAsesor\nfrom promotor import models as mPromotor\nfrom login import models as mLogin\nfrom login import forms as fLogin\nfrom cliente import forms as fInfo\nfrom cliente import models as mCliente\nfrom django.conf import settings\nfrom . import forms as f\nimport re\nfrom django.contrib import messages\nfrom django.contrib.auth import get_user\nfrom productos import models as mProductos\nimport random\n\n# Create your views here.\n@login_required(redirect_field_name='login:login')\ndef agregarAsesor(request):\n if request.user.persona.idRol.pk == 3:\n bandera = 3\n if request.method == 'POST':\n usuario = fLogin.UserForm(request.POST)\n persona = fInfo.PersonaForm(request.POST)\n direccion = fInfo.DireccionForm(request.POST)\n contacto = fInfo.ContactoForm(request.POST)\n if usuario.is_valid() and persona.is_valid():\n user = usuario.save()\n contra = \"vvtf\"+str(random.randint(1000,9999))+request.POST.get(\"first_name\",None)[:3]\n user.set_password(contra)\n user.username = request.POST.get('email')\n try:\n user.save()\n except:\n context = {\n \"usuario\":usuario,\n \"persona\":persona,\n \"cliente\":cliente,\n \"contacto\":contacto,\n \"direccion\":direccion,\n \"bandera\":bandera,\n }\n return render(request,\"cliente/cliente_add.html\",context)\n\n rol = mLogin.Roles.objects.get(pk=2)\n fecha = request.POST.get(\"fechaDeNacimiento\",None)\n estadoCivil = request.POST.get(\"estadoCivil\",None)\n direccion = request.POST.get(\"idtipodireccion\",None)\n persona = mLogin.Persona.objects.get(user_id=user)\n nombreaux = request.POST.get(\"institucion\",None)\n if estadoCivil == \"\":\n estado = mLogin.EstadoCivil.objects.get(pk=1)\n else:\n estado = mLogin.EstadoCivil.objects.get(pk=int(estadoCivil))\n if direccion == \"\":\n tipodireccion = mLogin.CatTipodireccion.objects.get(pk=1)\n else:\n tipodireccion = mLogin.CatTipodireccion.objects.get(pk=int(direccion))\n if request.POST.get(\"clienteProspecto\",None) == \"on\":\n prospecto = True\n else:\n prospecto = False\n print(estado.nombre)\n print(tipodireccion.nombre)\n \n mLogin.Persona.objects.filter(user_id=user).update(\n estadoCivil = estado,\n fechaDeNacimiento = fecha,\n idRol = rol,\n )\n direccion = mLogin.Direccion(\n idpersona = persona,\n idtipodireccion = tipodireccion,\n calle = request.POST.get(\"calle\",None),\n colonia = request.POST.get(\"colonia\",None),\n delegacion = request.POST.get(\"delegacion\",None),\n cp = request.POST.get(\"cp\",None),\n numinterior = request.POST.get(\"numinterior\",None),\n numexterior = request.POST.get(\"numexterior\",None),\n )\n contacto = mLogin.Contacto(\n idpersona = persona,\n celular = request.POST.get(\"celular\",None),\n telcasa = request.POST.get(\"telcasa\",None),\n oficina = request.POST.get(\"oficina\",None),\n facebookid = request.POST.get(\"facebookid\",None),\n )\n promotor = mPromotor.promotorAsesor(\n idAsesor = persona,\n idPromotor = get_user(request),\n activo = True,\n )\n contacto.save()\n direccion.save()\n promotor.save()\n for insti in request.POST.getlist(\"instituciones\",None):\n institucion = mProductos.InstitucionFinanciera.objects.get(pk=int(insti))\n institucion.idPersona.add(persona)\n mail_from = settings.EMAIL_HOST_USER\n mail_to = [user.email]\n ctx = {\n 'user': user.username,\n 'pass': contra,\n 'nombre': user.first_name + \" \" + user.last_name,\n 'nombre_asesor':request.user.first_name + \" \" + request.user.last_name,\n }\n try:\n html_content = render_to_string('../templates/mails/asesor.html',ctx)\n msg = EmailMultiAlternatives(\"¡Bienvenido a vive tu futuro!\",\"\", mail_from,mail_to)\n msg.attach_alternative(html_content, \"text/html\")\n msg.send()\n messages.add_message(request, messages.SUCCESS, 'Exito - Se agregó correctamente al asesor.')\n except:\n messages.add_message(request, messages.WARNING, 'Notificacion - No se pudo mandar el correo, revisar direccion de correo.')\n else:\n messages.add_message(request, messages.ERROR, 'Error - Se produjo un error, revisa la caja de errores.')\n bandera = 0\n if request.user.pk == 1 or request.user.pk == 2:\n instituciones = mProductos.InstitucionFinanciera.objects.all()\n else:\n instituciones = mProductos.InstitucionFinanciera.objects.filter(idPersona=request.user.persona)\n \n if bandera != 0:\n if request.user.pk == 1 or request.user.pk == 2:\n instituciones = mProductos.InstitucionFinanciera.objects.all()\n else:\n instituciones = mProductos.InstitucionFinanciera.objects.filter(idPersona=request.user.persona)\n usuario = fLogin.UserForm()\n persona = fInfo.PersonaForm()\n direccion = fInfo.DireccionForm()\n contacto = fInfo.ContactoForm()\n \n context = {\n \"usuario\":usuario,\n \"persona\":persona,\n \"contacto\":contacto,\n \"direccion\":direccion,\n \"bandera\":bandera,\n \"instituciones\":instituciones\n }\n return render(request,\"asesor/asesor_add.html\",context)\n\n\n@login_required(redirect_field_name='login:login')\ndef editarAsesor(request,idAsesorPromotor):\n if request.user.persona.idRol.pk == 3:\n editar = mPromotor.promotorAsesor.objects.get(pk=idAsesorPromotor)\n if request.method == 'POST':\n usuario = fLogin.UserForm(request.POST,instance=editar.idAsesor.user)\n persona = fInfo.PersonaForm(request.POST,instance=editar.idAsesor)\n asesor = f.promotorAsesorForm(request.POST,instance=editar)\n if usuario.is_valid():\n usuario.save()\n persona.save()\n asesor.save()\n messages.add_message(request, messages.SUCCESS, 'Se ha editado a tu asesor.')\n return redirect('asesor:gestionarAsesor')\n else:\n usuario = fLogin.UserForm(instance=editar.idAsesor.user)\n persona = fInfo.PersonaForm(instance=editar.idAsesor)\n context = {\n \"usuario\":usuario,\n \"persona\":persona,\n }\n return render(request,\"asesor/asesor_editar.html\",context)\n\n else:\n return render(request,'error/404.html')\n\n@login_required(redirect_field_name='login:login')\ndef eliminarAsesor(request,idAsesorPromotor):\n if request.user.persona.idRol.pk == 3:\n eliminar = mPromotor.promotorAsesor.objects.get(pk=idAsesorPromotor)\n mPromotor.promotorAsesor.objects.filter(pk=eliminar.pk).update(\n activo = False\n )\n messages.add_message(request, messages.SUCCESS, 'Se elimino correctamente.')\n return redirect('asesor:gestionar')\n else:\n return render(request,'error/404.html')\n\n@login_required(redirect_field_name='login:login')\ndef asesor(request,idAsesorPromotor):\n if request.user.persona.idRol.pk == 3:\n promotorAsesor = mPromotor.promotorAsesor.objects.get(pk=idAsesorPromotor)\n contacto = mLogin.Contacto.objects.filter(idpersona=promotorAsesor.idAsesor)\n direccion = mLogin.Direccion.objects.filter(idpersona=promotorAsesor.idAsesor)\n context = {\n \"asesor\":promotorAsesor,\n \"contactos\":contacto,\n \"direcciones\":direccion,\n }\n return render(request,\"asesor/asesor_show.html\",context)\n else:\n return render(request,'error/404.html')\n\n\n@login_required(redirect_field_name='login:login')\ndef gestionarAsesor(request):\n if request.user.persona.idRol.pk == 3:\n promotorAsesor = mPromotor.promotorAsesor.objects.filter(idPromotor=request.user)\n salida = []\n for asesor in promotorAsesor:\n if asesor.activo == True:\n calificaciones = mCliente.AsesorCliente.objects.filter(idAsesor=asesor.idAsesor.user)\n promedio = 0\n paquete = []\n for cali in calificaciones:\n if cali.ranking:\n promedio = promedio + cali.ranking\n paquete.append(asesor)\n if len(calificaciones) == 0:\n paquete.append(promedio)\n else:\n paquete.append(promedio/len(calificaciones))\n paquete.append(len(calificaciones))\n salida.append(paquete)\n context = {\n \"promotorAsesor\":promotorAsesor,\n \"salida\":salida\n }\n\n return render(request,\"asesor/asesor_gestionar.html\",context)\n else:\n return render(request,'error/404.html')\n","sub_path":"asesor/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":10645,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"609245529","text":"# Copyright (C) 2012 Leonard Thomas\n#\n# This file is part of Dodai.\n#\n# Dodai is free software: you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation, either version 3 of the License, or\n# (at your option) any later version.\n#\n# Dodai is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with Dodai. If not, see .\n\nimport os\nimport sys\nfrom dodai.util import find\n\nclass UtilFixture(object):\n\n PROJECT = \"__test__dodai__\"\n CONFIG_FILES = ('cfg', 'connection.txt', 'databases.ini',)\n CUSTOM_CONFIG_FILES = ('test_custom_dodai', 'another_test',)\n BOGUS_FILES = ('bogus_file_one', 'bogus_file_two',)\n\n def __init__(self, directory):\n self.directory = directory\n self._filenames_ = []\n self._custom_filenames_ = []\n self._bogus_filenames_ = []\n self._all_filenames_ = []\n self._good_filenames_ = []\n\n @classmethod\n def load(cls):\n\n directory = find.home_directory(cls.PROJECT)\n obj = cls(directory)\n obj.build()\n return obj\n\n @property\n def filenames(self):\n if not self._filenames_:\n for name in self.CONFIG_FILES:\n self._filenames_.append(os.path.join(self.directory, name))\n return self._filenames_\n\n @property\n def custom_filenames(self):\n if not self._custom_filenames_:\n for name in self.CUSTOM_CONFIG_FILES:\n self._custom_filenames_.append(os.path.join(self.directory,\n name))\n return self._custom_filenames_\n\n @property\n def bogus_filenames(self):\n if not self._bogus_filenames_:\n for name in self.BOGUS_FILES:\n self._bogus_filenames_.append(os.path.join(self.directory,\n name))\n return self._bogus_filenames_\n\n @property\n def all_filenames(self):\n if not self._all_filenames_:\n self._all_filenames_ = self.filenames + self.custom_filenames +\\\n self.bogus_filenames\n return self._all_filenames_\n\n @property\n def good_filenames(self):\n if not self._good_filenames_:\n self._good_filenames_ = self.filenames + self.custom_filenames\n return self._good_filenames_\n\n def _clean_up(self):\n if os.path.exists(self.directory):\n if os.path.isdir(self.directory):\n for root, dirs, files in os.walk(self.directory,\n topdown=False):\n for name in files:\n os.remove(os.path.join(root, name))\n for name in dirs:\n os.rmdir(os.path.join(root, name))\n os.rmdir(self.directory)\n else:\n os.remove(self.directory)\n\n def build(self):\n self._clean_up()\n os.mkdir(self.directory)\n\n for path in self.all_filenames:\n with open(path, 'w') as f:\n pass\n\n def destroy(self):\n self._clean_up()\n","sub_path":"test/util/fixture.py","file_name":"fixture.py","file_ext":"py","file_size_in_byte":3464,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"503163883","text":"import http.cookiejar as cookielib\nimport os\nimport urllib\nimport re\nimport string\nfrom bs4 import BeautifulSoup\nimport requests;\nimport json;\nimport time\nimport sys\nimport logging\nimport xml.etree.ElementTree as ET\n\n\nimport MySQLdb\nconn = MySQLdb.connect(host= \"localhost\",\n user=\"root\",\n passwd=\"newpassword\",\n db=\"engy1\")\n\n\ncookie_filename = \"parser.cookies.txt\"\nlogging.basicConfig(format='%(asctime)s %(message)s', filename='scraper.log', level=logging.DEBUG)\n\nclass LinkedInParser(object):\n\n def __init__(self):\n self.opener = urllib.request.build_opener(\n urllib.request.HTTPRedirectHandler(),\n urllib.request.HTTPHandler(debuglevel=0),\n urllib.request.HTTPSHandler(debuglevel=0),\n #urllib.request.HTTPCookieProcessor(self.cj)\n )\n self.opener.addheaders = [\n ('User-agent', (\n 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/57.0.2987.133 Safari/537.36'))\n ]\n\n response = self.opener.open('https://www.amazon.com/Apple-iPad-WiFi-Space-Model/dp/B01LTIOREG/ref=as_sl_pc_tf_til?tag=fakingoodidea-20&linkCode=w00&linkId=bf7aac78bc87f9b0e46dfd92153e71d6&creativeASIN=B01LTIORC8&th=1')\n\n readed =response.read().decode(\"utf-8\");\n soup = BeautifulSoup(readed, \"html5lib\")\n\n title = soup.find(\"span\", {'id' : 'productTitle'})\n titleString = title.next;\n print(titleString);\n\n price = soup.find(\"span\", {'id': 'priceblock_ourprice'})\n priceString = price.next;\n print(priceString );\n\n\n photo = soup.find(\"li\", {'class': 'image'})\n photoString = photo.next;\n\n\n photos = soup.find(\"div\", {'id': 'altImages'})\n imgs = photos.findAll('img');\n for img in imgs:\n print(img['src'])\n src = img['src'];\n length = len(src)\n cutted = src[:length-7]\n print(cutted + '557_.jpg')\n\n\n reviews = soup.find(\"div\", {'id': 'averageCustomerReviews'})\n review = reviews.find(\"span\", {'class': 'a-icon-alt'})\n\n print(review.next)\n\n desc =soup.find(\"div\", {'id': 'productDescription'})\n descP=desc.find('p');\n print(descP.next)\n\n features = soup.find(\"div\", {'id': 'featurebullets_feature_div'})\n featuresContainer = features.find('ul');\n print(featuresContainer)\n\n\n\ninvalid_escape = re.compile(r'\\\\[0-7]{1,6}')\nparser = LinkedInParser()\n\n\n","sub_path":"Scraper.py","file_name":"Scraper.py","file_ext":"py","file_size_in_byte":2515,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"478428866","text":"import os, logging\nimport apache_beam as beam\nfrom apache_beam.io import ReadFromText\nfrom apache_beam.io import WriteToText\n\nclass ParseNameFn(beam.DoFn):\n def process(self, element):\n record = element\n name = record.get('name')\n \n split_name = name.split(' ')\n if len(split_name) > 1:\n fname = split_name[0]\n lname = split_name[1]\n else:\n fname = split_name[0]\n lname = 'None'\n \n record.pop('name', None)\n record.update({'fname' : fname})\n record.update({'lname' : lname})\n \n return [record]\n \ndef run():\n \n PROJECT_ID = 'cs327e-fa2019'\n\n # Project ID is required when using the BQ source\n options = {\n 'project': PROJECT_ID\n }\n opts = beam.pipeline.PipelineOptions(flags=[], **options)\n\n # Create beam pipeline using local runner\n p = beam.Pipeline('DirectRunner', options=opts)\n\n sql = 'SELECT name, year, category FROM oscars.Winning_Actors'\n bq_source = beam.io.BigQuerySource(query=sql, use_standard_sql=True)\n\n query_results = p | 'Read from BigQuery' >> beam.io.Read(bq_source)\n\n # apply ParDo to parse the actor's name \n parsed_pcoll = query_results | 'Parse Name' >> beam.ParDo(ParseNameFn())\n\n dataset_id = 'oscars'\n table_id = 'Winning_Actors_Beam'\n schema_id = 'fname:STRING,lname:STRING,year:INTEGER,category:STRING'\n\n # write PCollection to new BQ table\n parsed_pcoll | 'Write BQ table' >> beam.io.WriteToBigQuery(dataset=dataset_id, \n table=table_id, \n schema=schema_id,\n project=PROJECT_ID,\n create_disposition=beam.io.BigQueryDisposition.CREATE_IF_NEEDED,\n write_disposition=beam.io.BigQueryDisposition.WRITE_TRUNCATE,\n batch_size=int(500))\n result = p.run()\n result.wait_until_finish()\n\n\nif __name__ == '__main__':\n logging.getLogger().setLevel(logging.INFO)\n run()","sub_path":"oscars_Winning_Actors.py","file_name":"oscars_Winning_Actors.py","file_ext":"py","file_size_in_byte":2109,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"127433462","text":"#! usr/bin/env python3.6\n# -*- coding: utf-8 -*-\n\ninpfilename = \"../Data/cacm.all\"\noutpathname = \"../Collection/Init/\"\n\ndef ExtractionDesFichiers(infile, outpath):\n fileHandler = open(infile, \"r\")\n debut = True\n while True:\n line = fileHandler.readline()\n if not line:\n break;\n #print 'XXXXX',line[:-1]\n if line[0:2] == '.I':\n if not debut:\n f.close()\n debut = False\n a,b = line.split(\" \")\n print(\"processing file CACM-\" + b[:-1])\n f = open(outpath + \"CACM-\" + b[:-1], \"w+\")\n if line[:-1] == '.T' or line[:-1] == '.A' or line[:-1] == '.W' or line[:-1] == '.B':\n out = True\n #print 'TOTO'\n while out:\n line = fileHandler.readline()\n #print line\n if not line:\n break;\n if line[:-1] == '.N' or line[:-1] == '.X' or line[:-1] == '.K' or line[:-1] == '.I':\n out = False\n #print 'OUT',line[:-1]\n break\n elif line[:-1] != '.T' and line[:-1] != '.A' and line[:-1] != '.W' and line[:-1] != '.B':\n f.write(line[:-1] + \"\\n\")\n fileHandler.close()\n\nExtractionDesFichiers(inpfilename, outpathname)\n","sub_path":"part1/Prog/split_cacm.py","file_name":"split_cacm.py","file_ext":"py","file_size_in_byte":1315,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"99517442","text":"import sys, subprocess, traceback, os, compile, run, grade, websockets, asyncio, pickle, threading, signal\n\ndef first1023(a):\n #ensures about 1023 and a single newline at the end\n if len(a)>1023:\n return a[:1023] + \"\\r\\n\" + \"(1023 chars displayed of \"+str(len(a))+\")\" + \"\\r\\n\"\n return a.strip(\"\\r\\n\")+\"\\r\\n\"\n\nasync def submission(ws, spsName, uids, code, lang, problem, runtime, memlimit, input, expected, points, userid, subid, customrunoriginal, gid, problem_number):\n #return status, score, submission log\n ostatus = -1 # 0 is backend error, 1 is compile fail, 2 is successfully graded, 3 missed sample case (still graded test cases though)\n oscore = 0\n osublog = \"\"\n\n if ws != None:\n await ws.send(pickle.dumps({\"func\": \"live\", \"command\": \"init\", \"uid\": userid, \"subid\": subid, \"pid\": problem, \"input_len\": len(input), \"gid\": gid}))\n\n osublog += \"Submission information:\" + \"\\r\\n\"\n osublog += \"Code Length: \" + str(len(code)) + \"\\r\\n\"\n osublog += \"Code Language: \" + lang + \"\\r\\n\"\n osublog += \"Problem ID: \" + str(problem) + \"\\r\\n\"\n osublog += \"Problem number: \" + str(problem_number) + \"\\r\\n\"\n osublog += \"User ID: \" + str(userid) + \"\\r\\n\"\n osublog += \"Submission ID: \" + str(subid) + \"\\r\\n\"\n osublog += \"Submission Processing Server Name: \" + spsName + \"\\r\\n\"\n osublog += \"\\r\\n\"\n osublog += \"Compiling submission...\" + \"\\r\\n\"\n osublog += \"\\r\\n\"\n\n print(\"New Submission,\",subid)\n\n cres = compile.compileProgram(code, lang, problem_number)\n\n if cres[0] == 0:\n print(\"General Error\")\n osublog += \"General error.\" + \"\\r\\n\"\n ostatus = 0\n\n elif cres[0] == 1:\n print(\"Lang Error\")\n osublog += \"Lang error.\" + \"\\r\\n\"\n ostatus = 0\n elif cres[0] == 2:\n print(\"Compile Fail\")\n osublog += \"Compile fail.\"\n osublog += \"\\r\\n\"\n osublog += \"Compile log:\" + \"\\r\\n\"\n osublog += first1023(cres[1])\n ostatus = 1\n if ws != None:\n await ws.send(pickle.dumps({\"func\": \"live\", \"command\": \"comf\", \"uid\": userid, \"subid\": subid, \"pid\": problem, \"gid\": gid}))\n elif cres[0] == 3:\n #print(\"Compile Success\")\n\n totalScore = 0\n\n osublog += \"Compile success.\" + \"\\r\\n\"\n osublog += \"\\r\\n\"\n osublog += \"Grading submission on sample & test cases...\" + \"\\r\\n\"\n osublog += \"\\r\\n\"\n\n missedSample = False\n\n for i in range(len(input)):\n #print(\"Case \" + str(i+1) + \"/\" + str(len(input)))\n\n if ws != None:\n await ws.send(pickle.dumps({\"func\":\"live\", \"command\":\"case\", \"uid\":userid, \"subid\":subid, \"pid\":problem, \"index\":i, \"gid\": gid}))\n\n if points[i] == -1:\n osublog += \"Case \" + str(i+1) + \"/\" + str(len(input)) + \" (Sample Case)\" + \"\\r\\n\"\n else:\n osublog += \"Case \" + str(i+1) + \"/\" + str(len(input)) + \" (Worth \" + str(points[i]) + \"pts)\" + \"\\r\\n\"\n\n subprocess.call(\"rm run/* -R\", shell=True)\n inpFile = open(\"run/input.txt\", \"w\")\n inpFile.write(input[i])\n inpFile.close()\n\n block_ = asyncio.get_event_loop().create_future()\n rres = []\n signal.signal(signal.SIGALRM, run.handleTimeout)\n signal.alarm(runtime + 1)\n thr = threading.Thread(target=run.runProgram, args=(cres[1], lang, runtime, memlimit, uids, block_, rres, asyncio.get_event_loop()))\n thr.start()\n #rres = run.runProgram(cres[1], lang, runtime, memlimit, uids)\n await block_;\n thr.join()\n signal.alarm(0)\n #print(\"RRES:\", rres)\n postSample = False\n\n if len(rres[3]):\n print(\"Run Time Error\")\n osublog += \"Run Time Error.\" + \"\\r\\n\"\n postSample = True\n if ws != None:\n await ws.send(pickle.dumps({\"func\":\"live\", \"command\":\"rte\", \"uid\":userid, \"subid\":subid, \"pid\":problem, \"index\":i, \"gid\":gid}))\n elif rres[0] == 0:\n gres = grade.grade(rres[2], expected[i])\n if gres == 0:\n #print(\"Correct Output, +\"+str(points[i])+\"pts (if is not sample)\")\n if ws != None:\n await ws.send(pickle.dumps({\"func\":\"live\", \"command\":\"co\", \"uid\":userid, \"subid\":subid, \"pid\":problem, \"index\":i, \"gid\":gid}))\n if points[i] == -1:\n osublog += \"Correct Output\" + \"\\r\\n\"\n else:\n totalScore += points[i]\n osublog += \"Correct Output, +\"+str(points[i])+\"pts\" + \"\\r\\n\"\n else:\n print(\"Incorrect Output\")\n osublog += \"Incorrect Output.\" + \"\\r\\n\"\n if ws != None:\n await ws.send(pickle.dumps({\"func\":\"live\", \"command\":\"io\", \"uid\":userid, \"subid\":subid, \"pid\":problem, \"index\":i, \"gid\":gid}))\n postSample = True\n elif rres[0] == 1:\n print(\"Run Time Exceeded, Terminated\")\n osublog += \"Run Time Exceeded, Terminated.\" + \"\\r\\n\"\n if ws != None:\n await ws.send(pickle.dumps({\"func\":\"live\", \"command\":\"rtlet\", \"uid\":userid, \"subid\":subid, \"pid\":problem, \"index\":i, \"gid\":gid}))\n postSample = True\n elif rres[0] == 2:\n print(\"Memory Limit Exceeded.\")\n osublog += \"Memory Limit Exceeded.\" + \"\\r\\n\"\n if ws != None:\n await ws.send(pickle.dumps({\"func\":\"live\", \"command\":\"mlet\", \"uid\":userid, \"subid\":subid, \"pid\":problem, \"index\":i, \"gid\":gid}))\n postSample = True\n else:\n print(\"Return Error R\")\n osublog += \"Return Error r.\" + \"\\r\\n\"\n\n if (points[i] == -1 or customrunoriginal != -1) and postSample:\n missedSample = True\n if points[i] == -1:\n osublog += \"Since 'Correct Output' was not achieved, and since this is a sample case, here are the contents of the input file, output file, expected output, and error file:\" + \"\\r\\n\"\n elif customrunoriginal != -1:\n osublog += \"Since 'Correct Output' was not achieved, and since this is a custom run, here are the contents of the input file, output file, expected output, and error file:\" + \"\\r\\n\"\n\n osublog += \"Input File:\" + \"\\r\\n\"\n osublog += first1023(input[i])\n osublog += \"Output File:\" + \"\\r\\n\"\n osublog += first1023(rres[2])\n osublog += \"Expected Output:\" + \"\\r\\n\"\n osublog += first1023(expected[i])\n osublog += \"Error File:\" + \"\\r\\n\"\n osublog += first1023(rres[3])\n osublog += \"\\r\\n\"\n\n print(\"Total Score:\",totalScore)\n osublog += \"Finished grading.\" + \"\\r\\n\"\n osublog += \"Total score: \" + str(totalScore) + \"\\r\\n\"\n\n oscore = totalScore\n ostatus = 2\n if missedSample:\n ostatus = 3\n\n else:\n print(\"Return Error C\")\n osublog += \"Return Error C.\" + \"\\r\\n\"\n ostatus = 0\n\n\n if ws != None:\n await ws.send(pickle.dumps({\"func\":\"live\", \"command\":\"stop\", \"uid\":userid, \"subid\":subid, \"pid\":problem, \"gid\":gid}))\n\n print(\"Finished grading submission\")\n return ostatus, oscore, osublog\n","sub_path":"sps/submission.py","file_name":"submission.py","file_ext":"py","file_size_in_byte":7480,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"314082890","text":"# coding: utf8\nimport os\n\nfiles_list = os.listdir('.') \ninput_pattern = input('Input pattern: ')\ninput_rewrite = 'test' \npattern_files_list = []\n#print(files_list)\n\ninput()\nfor i in files_list: \n x = open(i, encoding='utf-8')\n x_read = x.read()\n x.close()\n if x_read == input_pattern:\n print('There is your pattern in file '+i)\n pattern_files_list.append(i) \n else:\n pass\n\nlen_list = len(pattern_files_list)\n\nif len_list > 0: \n #while (input_rewrite != 'no') or (input_rewrite != 'yes'):\n while not (input_rewrite == 'yes' or input_rewrite == 'no'):\n input_rewrite = input('Rewrite pattern? yes/no: ')\n print('!!!')\nelse:\n print('There is no your pattern in files!')\n\nif input_rewrite == 'yes':\n new_pattern = input('Input new pattern: ')\n for i in pattern_files_list:\n x = open(i, 'w', encoding='utf-8')\n x_write = x.write(new_pattern)\n x.close() \n print('Done!')\nelif input_rewrite == 'no':\n print('Ok') \n\ninput()\n","sub_path":"скрипты/add_user_dictionary_utility/test_utility.py","file_name":"test_utility.py","file_ext":"py","file_size_in_byte":1028,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"206986534","text":"# import necessary modules for the class\nfrom lmfit import Parameters #Please do not remove this line\nimport numpy as np\nimport sys\nimport os\nfrom scipy import special\nsys.path.append(os.path.abspath('./Functions'))\n\nclass Rod_Lipid: #Please put the class name same as the function name\n def __init__(self,x=0, E=10.0, alpha=0.1, H_lipid=20, qc=0.0217,sig=0.0,norm=1.0, qz_cen=0.0, qoff=0.0, bkg=0.0,mpar={}):\n \"\"\"\n Provides rod scan from spherical objects dispersed on a substrate\n x \t: Array of Qz values of rod scan\n E : Energy of X-ray in unit of keV\n alpha : incident angle in unit of degree\n H_lipid : height of lipids in unit of \\AA\n qc \t: Critcal wave-vector for the substrate on which sphere are aranged\n sig : relative rms fluctuation between two particles\n norm \t: Normalization constant\n qz_cen : center for the out-of-plane peak; or 0 for the in-plane peak\n qoff : qz offset in unit of \\AA^-1\n bkg \t: Constant background\n \"\"\"\n if type(x)==list:\n self.x=np.array(x)\n else:\n self.x=x\n self.E=E\n self.alpha=alpha\n self.H_lipid=H_lipid\n self.qc=qc\n self.norm=norm\n self.qz_cen=qz_cen\n self.qoff=qoff\n self.bkg=bkg\n self.sig=sig\n self.__mpar__=mpar\n self.choices={}\n self.output_params={'scaler_parameters':{}}\n\n\n def init_params(self):\n \"\"\"\n Define all the fitting parameters like\n self.param.add('sig',value=0,vary=0)\n \"\"\"\n self.params=Parameters()\n self.params.add('H_lipid',value=self.H_lipid,vary=0,min=-np.inf,max=np.inf,expr=None,brute_step=0.1)\n self.params.add('qc',value=self.qc,vary=0,min=-np.inf,max=np.inf,expr=None,brute_step=0.1)\n self.params.add('norm',value=self.norm,vary=0,min=-np.inf,max=np.inf,expr=None,brute_step=0.1)\n self.params.add('qz_cen', value=self.qz_cen, vary=0, min=-np.inf, max=np.inf, expr=None, brute_step=0.1)\n self.params.add('bkg',value=self.bkg,vary=0,min=-np.inf,max=np.inf,expr=None,brute_step=0.1)\n self.params.add('sig',value=self.sig,vary=0,min=-np.inf,max=np.inf,expr=None,brute_step=0.1)\n self.params.add('qoff', value=self.qoff, vary=0, min=-np.inf, max=np.inf, expr=None, brute_step=0.1)\n\n\n def trans(self,qz,qc):\n \"\"\"\n Calculates the transmission Coefficient\n \"\"\"\n qz = qz.clip(min=0)\n tr=2.0*qz/(qz+np.sqrt(qz**2-qc**2+0j))\n return np.abs(tr)**2\n\n def y(self):\n \"\"\"\n Define the function in terms of x to return some value\n \"\"\"\n x=self.x+self.qoff\n k0=2*np.pi*self.E/12.3984\n qbeta=x-k0*np.sin(self.alpha/180*np.pi)\n x=x-self.qz_cen\n formfac = special.spherical_jn(0,x*self.H_lipid/2)**2\n #formfac = ((np.sin(x * self.H_lipid / 2)) / (x * self.H_lipid / 2)) ** 2\n res = self.trans(qbeta, self.qc / 2) * formfac * self.norm * np.exp(-x ** 2 * self.sig ** 2) + self.bkg\n\n if not self.__fit__:\n self.output_params['scaler_parameters'] = {}\n return res\n\n\nif __name__=='__main__':\n x=np.arange(0.001,1.0,0.01)\n fun=Rod_Lipid(x=x)\n print(fun.y())\n","sub_path":"Functions/GISAXS/Rod_Lipid.py","file_name":"Rod_Lipid.py","file_ext":"py","file_size_in_byte":3301,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"225315956","text":"import tensorflow as tf\nimport tensorflow_probability as tfp\nimport treeflow.model\nimport treeflow.vi\n\ndef run_demo():\n newick_file = 'data/analysis-tree.nwk'\n fasta_file = 'data/sim-seq.fasta'\n n_iter = 10\n\n log_prob = treeflow.model.construct_model_likelihood(newick_file, fasta_file)\n q = treeflow.model.construct_surrogate_posterior(newick_file)\n res = treeflow.vi.fit_surrogate_posterior(log_prob, q, tf.optimizers.Adam(), 10)\n print(res)\n\n\n\nif __name__ == '__main__':\n run_demo()","sub_path":"script/demo.py","file_name":"demo.py","file_ext":"py","file_size_in_byte":509,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"236967906","text":"import os\nfrom PIL import Image\nfrom nose.tools import assert_equal, assert_true\nimport tempfile\nfrom practiceq.tasks.derivative_utils import _formatextension, _params_as_string, _processimage\n\n\ndef test_formatextension():\n value = _formatextension(\"JPEG\")\n assert_equal(value,\"jpg\")\n value = _formatextension(\"TIFF\")\n assert_equal(value, \"tif\")\n value = _formatextension(\"jpeg\")\n assert_equal(value,\"jpg\")\n value = _formatextension(\"jpg\")\n assert_equal(value, \"jpg\")\n\ndef test_params_as_string():\n value=_params_as_string(outformat=\"jpeg\", filter=\"\", scale=None, crop=None)\n assert_equal(value,\"jpeg_100\")\n value = _params_as_string(outformat=\"jpeg\", filter=\"\", scale=0.40, crop=None)\n assert_equal(value, \"jpeg_040\")\n value = _params_as_string(outformat=\"jpeg\", filter=\"\", scale=0.40, crop=[10,10,10,10])\n assert_equal(value, \"jpeg_040_10_10_10_10\")\n value = _params_as_string(outformat=\"jpeg\", filter=\"xyz\", scale=0.40, crop=[10, 10, 10, 10])\n assert_equal(value, \"jpeg_040_xyz_10_10_10_10\")\n\n#@patch(\"practiceq.tasks.derivative_utils.PIL.Image\")\n#16-bitcolor depth tif images.\ndef test_processimage():\n with tempfile.TemporaryDirectory() as tmpdir:\n image = Image.new(\"RGB\", size=(100,100), color=(256, 0, 0))\n image.save(tmpdir+\"/test.jpg\",\"jpeg\")\n _processimage(tmpdir+\"/test.jpg\",tmpdir+\"/test.jpg\",scale=0.40)\n assert_true(os.path.isfile(os.path.join(tmpdir, \"test.jpg\")))\n image = Image.open(tmpdir+\"/test.jpg\")\n assert_true(image.size == (40,40))\n\ndef test_processimage_1():\n with tempfile.TemporaryDirectory() as tmpdir:\n image = Image.new(\"RGB\", size=(100,100), color=(256, 0, 0))\n image.save(tmpdir+\"/test.tif\")\n _processimage(tmpdir+\"/test.tif\",tmpdir+\"/test.tif\",scale=0.40)\n assert_true(os.path.isfile(os.path.join(tmpdir, \"test.tif\")))\n image = Image.open(tmpdir+\"/test.tif\")\n assert_true(image.size == (40,40))\n\"\"\"\ndef test_processimage_2():\n with tempfile.TemporaryDirectory() as tmpdir:\n image = Image.new(\"RGB\", size=(100,100), color=(256, 0, 0))\n image.save(tmpdir+\"/test.jpg\",\"jpeg\")\n _processimage(tmpdir+\"/test.jpg\",tmpdir+\"/test.jpg\",scale=1.2)\n assert_true(os.path.isfile(os.path.join(tmpdir, \"test.jpg\")))\n image1 = Image.open(tmpdir+\"/test.jpg\")\n assert_equal(image1.size, (120,120))\n\"\"\"","sub_path":"tests/test_derivative_utils.py","file_name":"test_derivative_utils.py","file_ext":"py","file_size_in_byte":2399,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"82892049","text":"'''\n42. Trapping Rain Water\nGiven n non-negative integers representing an elevation map where the width of each bar is 1,\ncompute how much water it is able to trap after raining.\n\nThe above elevation map is represented by array [0,1,0,2,1,0,1,3,2,1,2,1].\nIn this case, 6 units of rain water (blue section) are being trapped. Thanks Marcos for contributing this image!\n\nExample:\nInput: [0,1,0,2,1,0,1,3,2,1,2,1]\nOutput: 6\n\nExample:\nInput: [3,2,1,0,4,2,3,1,5]\noutput: 12\n\nApproach: use stack,\n when p[i] < p[i-1], push\n when p[i] > p[i-1], pop and calculate sum\n\n\n'''\n\nimport sys\n\ndef trapingWater(height):\n stack = []\n bottom = 0\n bot = None\n sum = 0\n for i in range(len(height)):\n if len(stack) == 0:\n stack.append([i, height[i]])\n continue\n if height[i] <= height[i-1]:\n stack.append([i,height[i]])\n bottom = 0\n else:\n if bottom == 0:\n bot = stack.pop()\n ltop = bot\n bottom = 1\n\n rtop = height[i]\n while(len(stack) > 0 ):\n sum += (min(stack[len(stack)-1][1], rtop) - bot[1]) * (i-stack[len(stack)-1][0]-1)\n bot = stack[len(stack)-1]\n if stack[len(stack)-1][1] <= rtop:\n stack.pop()\n else:\n break\n\n stack.append([i, height[i]])\n\n\n return sum\n\n\n\nnums = [0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1]\n# nums = [3,2,1,0,4,2,3,1,5]\nprint(trapingWater(nums))","sub_path":"42_trapping_water.py","file_name":"42_trapping_water.py","file_ext":"py","file_size_in_byte":1528,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"10017432","text":"#!/usr/bin/env python3\nimport os\nimport signal\n\n__author__ = 'Trofimov Igor'\n\n\ndef handler_print(sign, frame) -> None:\n print(sign)\n\n\ndef main() -> None:\n signal.signal(signal.SIGCHLD, handler_print)\n signal.pause()\n\n\nif __name__ == '__main__':\n print('PID: {0}'.format(os.getpid()))\n main()\n","sub_path":"usignalscatcher.py","file_name":"usignalscatcher.py","file_ext":"py","file_size_in_byte":307,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"209350839","text":"from django.urls import path, include\r\nfrom . import views\r\n\r\nurlpatterns = [\r\n\tpath('', views.events_page, name='gh_crm_events_page'),\r\n\tpath('clients_page', views.clients_page, name=\"gh_crm_clients_page\"),\r\n\tpath('add_client', views.add_client, name=\"gh_crm_add_client\"),\r\n\tpath('add_event', views.add_event, name=\"gh-crm_add_event\"),\r\n\tpath('update_event', views.update_event, name=\"gh_crm_update_event\"),\r\n\tpath('update_client', views.update_client, name=\"gh_crm_update_client\"),\r\n\tpath('remove_event', views.remove_event, name=\"gh_crm_remove_event\"),\r\n\tpath('remove_client', views.remove_client, name=\"gh_crm_remove_client\"),\r\n\tpath('update_event_status', views.update_event_status, name=\"gh_crm_update_event_status\"),\r\n\tpath('update_client_status', views.update_client_status, name=\"gh_crm_update_client_status\"),\r\n\tpath('load_file', views.load_file, name=\"gh_crm_load_file\"),\r\n\tpath('del_file', views.del_file, name=\"gh_crm_del_file\"),\r\n\tpath('event_page', views.event_page, name=\"gh_crm_event_page\"),\r\n]\r\n","sub_path":"apps/gh_crm/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1013,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"331627285","text":"\"\"\"change_structure_of_tables\n\nRevision ID: 198cf3b6445b\nRevises: 12ddbf607b10\nCreate Date: 2020-08-24 11:29:36.936078\n\n\"\"\"\nfrom uuid import uuid4\n\nfrom alembic import op\nimport sqlalchemy as sa\n\n# revision identifiers, used by Alembic.\nrevision = \"198cf3b6445b\"\ndown_revision = \"\"\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n op.create_table(\n \"users\",\n sa.Column(\n \"id\", sa.Integer(), primary_key=True, autoincrement=True, nullable=False\n ),\n sa.Column(\n \"user_uuid\", sa.String(length=36), default=f\"{uuid4()}\", nullable=False\n ),\n sa.Column(\"username\", sa.String(length=50), unique=True, nullable=False),\n sa.Column(\"fullname\", sa.String(length=40), nullable=True),\n sa.Column(\"email\", sa.String(length=254), unique=True, nullable=False),\n sa.Column(\"is_active\", sa.Boolean, default=True, nullable=False),\n sa.PrimaryKeyConstraint(\"id\"),\n )\n op.create_table(\n \"service_credentials\",\n sa.Column(\n \"id\", sa.Integer(), primary_key=True, autoincrement=True, nullable=False\n ),\n # One-To-One relationship\n sa.Column(\n \"user_id\",\n sa.INTEGER,\n sa.ForeignKey(\"users.id\", ondelete=\"CASCADE\"),\n unique=True,\n ),\n sa.Column(\"music_service_name\", sa.String(length=30), nullable=False),\n sa.Column(\"access_token\", sa.String(), nullable=False),\n sa.Column(\"refresh_token\", sa.String(), nullable=False),\n sa.Column(\"product_type\", sa.String(length=30), nullable=False),\n sa.PrimaryKeyConstraint(\"id\"),\n )\n op.create_foreign_key(\n \"fk_service_creds_user\", \"service_credentials\", \"users\", [\"user_id\"], [\"id\"]\n )\n\n op.create_table(\n \"photos\",\n sa.Column(\n \"id\", sa.Integer(), primary_key=True, autoincrement=True, nullable=False\n ),\n sa.Column(\"url\", sa.String(length=255), nullable=True),\n sa.Column(\n \"user_id\",\n sa.INTEGER,\n sa.ForeignKey(\"users.id\", ondelete=\"CASCADE\"),\n unique=True,\n ),\n sa.PrimaryKeyConstraint(\"id\"),\n )\n op.create_foreign_key(\"fk_photos_user\", \"photos\", \"users\", [\"user_id\"], [\"id\"])\n\n op.create_table(\n \"followers\",\n sa.Column(\n \"id\", sa.Integer(), primary_key=True, autoincrement=True, nullable=False\n ),\n sa.Column(\"user_id\", sa.INTEGER, sa.ForeignKey(\"users.id\", ondelete=\"CASCADE\")),\n sa.Column(\n \"following_id\", sa.INTEGER, sa.ForeignKey(\"users.id\", ondelete=\"CASCADE\")\n ),\n sa.PrimaryKeyConstraint(\"id\"),\n )\n op.create_foreign_key(\n \"fk_followers_user\", \"followers\", \"users\", [\"user_id\"], [\"id\"]\n )\n op.create_foreign_key(\n \"fk_followers_following_user\", \"followers\", \"users\", [\"following_id\"], [\"id\"]\n )\n\n # op.create_foreign_key('fk_', 'from_table', 'to_table', ['column_from_table'], ['column_to_table'])\n\n\ndef downgrade():\n pass\n","sub_path":"alembic/versions/198cf3b6445b_change_structure_of_tables.py","file_name":"198cf3b6445b_change_structure_of_tables.py","file_ext":"py","file_size_in_byte":3034,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"570916302","text":"import hashlib\nimport json\nimport logging\nimport os\nfrom mlflow.utils import process\n\nfrom mlflow.exceptions import ExecutionException\n# Environment variable indicating a path to a conda installation. MLflow will default to running\n# \"conda\" if unset\nMLFLOW_CONDA_HOME = \"MLFLOW_CONDA_HOME\"\n\n_logger = logging.getLogger(__name__)\n\n\ndef _activate_conda_env_command(conda_env_name):\n activate_path = _get_conda_bin_executable(\"activate\")\n return \"source %s %s\" % (activate_path, conda_env_name)\n\n\ndef _get_conda_bin_executable(executable_name):\n \"\"\"\n Return path to the specified executable, assumed to be discoverable within the 'bin'\n subdirectory of a conda installation.\n\n The conda home directory (expected to contain a 'bin' subdirectory) is configurable via the\n ``mlflow.projects.MLFLOW_CONDA_HOME`` environment variable. If\n ``mlflow.projects.MLFLOW_CONDA_HOME`` is unspecified, this method simply returns the passed-in\n executable name.\n \"\"\"\n conda_home = os.environ.get(MLFLOW_CONDA_HOME)\n if conda_home:\n return os.path.join(conda_home, \"bin/%s\" % executable_name)\n # Use CONDA_EXE as per https://github.com/conda/conda/issues/7126\n if \"CONDA_EXE\" in os.environ:\n conda_bin_dir = os.path.dirname(os.environ[\"CONDA_EXE\"])\n return os.path.join(conda_bin_dir, executable_name)\n return executable_name\n\n\ndef _get_conda_env_name(conda_env_path, env_id=None):\n conda_env_contents = open(conda_env_path).read() if conda_env_path else \"\"\n if env_id:\n conda_env_contents += env_id\n return \"mlflow-%s\" % hashlib.sha1(conda_env_contents.encode(\"utf-8\")).hexdigest()\n\n\ndef _get_or_create_conda_env(conda_env_path, env_id=None):\n \"\"\"\n Given a `Project`, creates a conda environment containing the project's dependencies if such a\n conda environment doesn't already exist. Returns the name of the conda environment.\n :param conda_env_path: Path to a conda yaml file.\n :param env_id: Optional string that is added to the contents of the yaml file before\n calculating the hash. It can be used to distinguish environments that have the\n same conda dependencies but are supposed to be different based on the context.\n For example, when serving the model we may install additional dependencies to the\n environment after the environment has been activated.\n \"\"\"\n conda_path = _get_conda_bin_executable(\"conda\")\n try:\n process.exec_cmd([conda_path, \"--help\"], throw_on_error=False)\n except EnvironmentError:\n raise ExecutionException(\"Could not find Conda executable at {0}. \"\n \"Ensure Conda is installed as per the instructions \"\n \"at https://conda.io/docs/user-guide/install/index.html. You can \"\n \"also configure MLflow to look for a specific Conda executable \"\n \"by setting the {1} environment variable to the path of the Conda \"\n \"executable\".format(conda_path, MLFLOW_CONDA_HOME))\n # The approach here is to directly run the user's conda executable (e.g. on Databricks or other\n # environments where MLFLOW_CONDA_HOME is set), and set up the shell to detect the conda\n # bash function otherwise\n (_, stdout, _) = process.exec_cmd([conda_path, \"env\", \"list\", \"--json\"])\n env_names = [os.path.basename(env) for env in json.loads(stdout)['envs']]\n project_env_name = _get_conda_env_name(conda_env_path, env_id)\n if project_env_name not in env_names:\n _logger.info('=== Creating conda environment %s ===', project_env_name)\n if conda_env_path:\n process.exec_cmd([conda_path, \"env\", \"create\", \"-n\", project_env_name, \"--file\",\n conda_env_path], stream_output=True)\n else:\n process.exec_cmd([conda_path, \"env\", \"create\", \"-n\", project_env_name, \"python\"],\n stream_output=True)\n return project_env_name\n \n\ndef _get_conda_command(conda_env_name, direct_output_to_err=False):\n conda_path = _get_conda_bin_executable(\"conda\")\n activate_path = _get_conda_bin_executable(\"activate\")\n\n try:\n process.exec_cmd([conda_path, \"--help\"], throw_on_error=False)\n except EnvironmentError:\n raise ExecutionException(\"Could not find Conda executable at {0}. \"\n \"Ensure Conda is installed as per the instructions \"\n \"at https://conda.io/docs/user-guide/install/index.html. You can \"\n \"also configure MLflow to look for a specific Conda executable \"\n \"by setting the {1} environment variable to the path of the Conda \"\n \"executable\".format(conda_path, MLFLOW_CONDA_HOME))\n\n (_, stdout, _) = process.exec_cmd([conda_path, \"info\", \"--json\"])\n conda_env_version = json.loads(stdout)['conda_env_version']\n conda_env_version_major = int(conda_env_version.split(\".\")[0])\n conda_env_version_minor = int(conda_env_version.split(\".\")[1])\n\n output_direct = \"\"\n if direct_output_to_err:\n output_direct = \" 1>&2\"\n\n # in case os name is not 'nt', we are not running on windows. It introduces\n # bash command otherwise.\n if os.name != \"nt\" and (conda_env_version_major == 4 and conda_env_version_minor < 6):\n return [\"source %s %s%s\" % (activate_path, conda_env_name, output_direct)]\n else:\n # TODO Need to fix, getting conda.sh is not simple\n # As per https://github.com/conda/conda/issues/7126\n # Notes: \n # 1. $(dirname $CONDA_EXE)/../etc/profile.d/conda.sh will break in cases where conda and conda.sh is in expected directories, ie. /usr/bin/conda, /etc/profile.d/conda.sh\n # 2. $(dirname $CONDA_EXE)/activate will not work if activate and deactivate does not stick around.\n return [\"source /etc/profile.d/conda.sh\", \"%s activate %s%s\" % (conda_path, conda_env_name, output_direct)]\n","sub_path":"mlflow/utils/conda_utils.py","file_name":"conda_utils.py","file_ext":"py","file_size_in_byte":6104,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"219037860","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sun Oct 18 21:02:11 2020\n\n@author: Hisana\n\"\"\"\nimport pygame\nfrom random import randint\nfrom pygame import mixer\n\npygame.init()\nGD = pygame.display.set_mode((1000, 700))\nw = 1000\nh = 700\n\npygame.display.set_caption(\"S & L BY BRAIN STEAKS\")\n\n# change color if u want\nheadcolor = (255, 0, 50)\nblack = (0, 0, 0)\nwhite = (255, 255, 255)\nred = (200, 0, 0)\nb_red = (240, 0, 0)\nbg = pygame.image.load(\"blackbg.jpg\")\nGD.blit(bg, (0, 0))\nboard = pygame.image.load(\"SandL_Items/Images/Snakes-and-Ladders-Bigger.jpg\")\nGD.blit(board, (w / 2 - 250, h / 2 - 250))\ndice1 = pygame.image.load(\"SandL_Items/Images/dice1.png\")\ndice2 = pygame.image.load(\"SandL_Items/Images/dice2.gif\")\ndice3 = pygame.image.load(\"SandL_Items/Images/dice3.gif\")\ndice4 = pygame.image.load(\"SandL_Items/Images/dice4.gif\")\ndice5 = pygame.image.load(\"SandL_Items/Images/dice5.gif\")\ndice6 = pygame.image.load(\"SandL_Items/Images/dice6.gif\")\nredgoti = pygame.image.load(\"SandL_Items/Images/redgoti.png\")\n\nyellowgoti = pygame.image.load(\"SandL_Items/Images/yellowgoti.png\")\n\ngreengoti = pygame.image.load(\"SandL_Items/Images/greengoti.png\")\ngreen = (0, 200, 0)\nb_green = (0, 230, 0)\n\n\ndef button1(text, xmouse, ymouse, x, y, w, h, i, a, fs):\n # mouse pos\n\n if x + w > xmouse > x and y + h > ymouse > y:\n pygame.draw.rect(GD, a, [x - 2.5, y - 2.5, w + 5, h + 5])\n if pygame.mouse.get_pressed() == (1, 0, 0):\n return True\n\n else:\n pygame.draw.rect(GD, i, [x, y, w, h])\n message_display(text, (x + w + x) / 2, (y + h + y) / 2, fs)\n\n\ndef message_display(text, x, y, fs):\n largeText = pygame.font.Font('freesansbold.ttf', fs)\n TextSurf, TextRect = text_objects(text, largeText)\n TextRect.center = (x, y)\n GD.blit(TextSurf, TextRect)\n\n\ndef text_objects(text, font):\n textSurface = font.render(text, True, (255, 255, 255))\n return textSurface, textSurface.get_rect()\n\n\ndef message_display1(text, x, y, fs, c):\n largeText = pygame.font.Font('freesansbold.ttf', fs)\n TextSurf, TextRect = text_objects1(text, largeText)\n TextRect.center = (x, y)\n GD.blit(TextSurf, TextRect)\n\n\ndef text_objects1(text, font):\n textSurface = font.render(text, True, white)\n return textSurface, textSurface.get_rect()\n\n\ndef button(text, xmouse, ymouse, x, y, w, h, i, a, fs, b):\n if x + w > xmouse > x and y + h > ymouse > y:\n pygame.draw.rect(GD, a, [x - 2.5, y - 2.5, w + 5, h + 5])\n if pygame.mouse.get_pressed() == (1, 0, 0):\n if b == 1:\n options()\n elif b == 5:\n import frontpage\n frontpage.mainpage()\n elif b == 0:\n Quit()\n elif b == 21:\n but = mixer.Sound(\"SandL_Items/Sound/SandL_button.wav\")\n but.play()\n play(21)\n elif b == 13:\n but = mixer.Sound(\"SandL_Items/Sound/SandL_button.wav\")\n but.play()\n play(2)\n elif b == \"s\" or b == 2:\n but = mixer.Sound(\"SandL_Items/Sound/SandL_button.wav\")\n but.play()\n return b\n elif b == 7:\n options()\n else:\n return True\n\n\n\n\n\n\n else:\n pygame.draw.rect(GD, i, [x, y, w, h])\n message_display(text, (x + w + x) / 2, (y + h + y) / 2, fs)\n\n\ndef dice(a):\n if a == 1:\n a = dice1\n elif a == 2:\n a = dice2\n elif a == 3:\n a = dice3\n elif a == 4:\n a = dice4\n elif a == 5:\n a = dice5\n elif a == 6:\n a = dice6\n\n time = pygame.time.get_ticks()\n while pygame.time.get_ticks() - time < 500:\n GD.blit(a, (800, 450))\n pygame.display.update()\n\n\ndef goti(a):\n l1 = [[195, 550], [250, 550], [300, 550], [350, 550], [400, 550], [450, 550], [500, 550], [550, 550], [600, 550],\n [650, 550], [700, 550],\n [700, 500], [650, 500], [600, 500], [550, 500], [500, 500], [450, 500], [400, 500], [350, 500], [300, 500],\n [250, 500],\n [250, 450], [300, 450], [350, 450], [400, 450], [450, 450], [500, 450], [550, 450], [600, 450], [650, 450],\n [700, 450],\n [700, 400], [650, 400], [600, 400], [550, 400], [500, 400], [450, 400], [400, 400], [350, 400], [300, 400],\n [250, 400],\n [250, 350], [300, 350], [350, 350], [400, 350], [450, 350], [500, 350], [550, 350], [600, 350], [650, 350],\n [700, 350],\n [700, 300], [650, 300], [600, 300], [550, 300], [500, 300], [450, 300], [400, 300], [350, 300], [300, 300],\n [250, 300],\n [250, 250], [300, 250], [350, 250], [400, 250], [450, 250], [500, 250], [550, 250], [600, 250], [650, 250],\n [700, 250],\n [700, 200], [650, 200], [600, 200], [550, 200], [500, 200], [450, 200], [400, 200], [350, 200], [300, 200],\n [250, 200],\n [250, 150], [300, 150], [350, 150], [400, 150], [450, 150], [500, 150], [550, 150], [600, 150], [650, 150],\n [700, 150],\n [700, 100], [650, 100], [600, 100], [550, 100], [500, 100], [450, 100], [400, 100], [350, 100], [300, 100],\n [250, 100]]\n l2 = l1[a]\n x = l2[0]\n y = l2[1]\n return x, y\n\n\ndef ladders(x):\n if x == 1:\n return 38\n elif x == 4:\n return 14\n elif x == 9:\n return 31\n elif x == 28:\n return 84\n elif x == 21:\n return 42\n elif x == 51:\n return 67\n elif x == 80:\n return 99\n elif x == 72:\n return 91\n else:\n return x\n\n\ndef snakes(x):\n if x == 17:\n return 7\n elif x == 54:\n return 34\n elif x == 62:\n return 19\n elif x == 64:\n return 60\n elif x == 87:\n return 36\n elif x == 93:\n return 73\n elif x == 95:\n return 75\n elif x == 98:\n return 79\n else:\n return x\n\n\ndef Quit():\n pygame.quit()\n\n\ndef turn(score, six):\n a = randint(1, 6) # player dice roll\n if a == 6:\n six = True\n else:\n six = False\n dice(a)\n score += a\n if score <= 100:\n lad = ladders(score) # use snk and lad if you wanna use sound\n score = lad\n snk = snakes(score)\n score = snk\n else: # checks if player score is not grater than 100\n score -= a\n time = pygame.time.get_ticks()\n while pygame.time.get_ticks() - time < 1500:\n message_display1(\"Can't move!\", w / 2, 50, 35, white)\n pygame.display.update()\n\n return score, six\n\n\ndef options():\n flag = True\n while flag == True:\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n Quit()\n if event.type == pygame.KEYDOWN:\n if event.key == pygame.K_ESCAPE:\n Quit()\n\n # mouse pos\n mouse = pygame.mouse.get_pos()\n click = pygame.mouse.get_pressed()\n b1 = b2 = b3 = b4 = b5 = -1\n GD.blit(bg, (0, 0))\n # Single player button\n b1 = button(\"Single Player\", mouse[0], mouse[1], (w / 2 - 150), 250, 300, 50, (0, 17, 240), (0, 13, 210), 30,\n \"s\")\n # 2 player button\n b2 = button(\"2 Players\", mouse[0], mouse[1], (w / 2) - 150, 350, 300, 50, (0, 17, 240), (0, 13, 210), 30, 2)\n\n # Back button\n b5 = button(\"Back\", mouse[0], mouse[1], 0, 0, 200, 50, (0, 17, 240), b_red, 30, 5)\n if b5 == 5:\n but = mixer.Sound(\".SandL_Items/Sound/SandL_button.wav\")\n but.play()\n\n if b1 == \"s\":\n but = mixer.Sound(\"SandL_Items/Sound/SandL_button.wav\")\n but.play()\n play(21)\n if b2 == 2:\n but = mixer.Sound(\"SandL_Items/Sound/SandL_button.wav\")\n but.play()\n play(2)\n\n pygame.display.update()\n\n\ndef play(b):\n mixer.music.load('SandL_Items/Sound/SandL_background.mp3')\n mixer.music.play(-1)\n p1score = 0\n\n p2score = 0\n time = 3000\n t = 1\n p1score = 0\n p2score = 0\n xcr = xcy = 195\n ycr = ycy = 550\n GD.blit(bg, (0, 0))\n GD.blit(board, (w / 2 - 250, h / 2 - 250))\n GD.blit(redgoti, (195, 550))\n\n while True:\n GD.blit(bg, (0, 0))\n GD.blit(board, (w / 2 - 250, h / 2 - 250))\n mouse = pygame.mouse.get_pos()\n t = 1\n s = False\n for event in pygame.event.get():\n\n if event.type == pygame.QUIT:\n Quit()\n if event.type == pygame.KEYDOWN:\n if event.key == pygame.K_ESCAPE:\n Quit()\n if (b == 21):\n if (button1(\"Player \", mouse[0], mouse[1], 90, 400, 100, 30, red, (50, 50, 50), 20)):\n if t == 1:\n but = mixer.Sound(\"SandL_Items/Sound/SandL_button.wav\")\n but.play()\n\n p1score, s = turn(p1score, s)\n if not s:\n t = 2\n xcr, ycr = goti(p1score)\n\n pygame.display.update()\n if p1score == 100:\n mixer.music.stop()\n but = mixer.Sound(\"SandL_Items/Sound/SandL_winning.wav\")\n but.play(0)\n time = pygame.time.get_ticks()\n while pygame.time.get_ticks() - time < 2000:\n message_display1(\"Player wins\", w / 2, 50, 35, white)\n\n pygame.display.update()\n break\n\n GD.blit(redgoti, (xcr, ycr))\n pygame.time.wait(80)\n\n button(\"Reset\", mouse[0], mouse[1], 900, 0, 100, 50, (0, 17, 240), (50, 50, 50), 19, 21)\n\n mouse = pygame.mouse.get_pos()\n (button1(\"Computer\", mouse[0], mouse[1], 90, 450, 100, 30, (225, 155, 10), (50, 50, 50), 19))\n if True:\n if t == 2:\n\n p2score, s = turn(p2score, s)\n if not s:\n t = 1\n xcy, ycy = goti(p2score)\n\n pygame.display.update()\n if p2score == 100:\n but = mixer.Sound(\"SandL_Items/Sound/SandL_winning.wav\")\n but.play(0)\n time = pygame.time.get_ticks()\n while pygame.time.get_ticks() - time < 2000:\n message_display1(\"Computer wins\", w / 2, 50, 35, white)\n\n pygame.display.update()\n break\n\n GD.blit(yellowgoti, (xcy, ycy))\n\n else:\n if (button1(\"Player 1\", mouse[0], mouse[1], 90, 400, 100, 30, red, (50, 50, 50), 20)):\n if t == 1:\n but = mixer.Sound(\"SandL_Items/Sound/SandL_button.wav\")\n but.play()\n p1score, s = turn(p1score, s)\n if not s:\n t = 2\n xcr, ycr = goti(p1score)\n\n pygame.display.update()\n if p1score == 100:\n but = mixer.Sound(\"SandL_Items/Sound/SandL_winning.wav\")\n but.play(0)\n time = pygame.time.get_ticks()\n while pygame.time.get_ticks() - time < 2000:\n message_display1(\"Player 1 wins\", w / 2, 50, 35, white)\n\n pygame.display.update()\n break\n\n GD.blit(redgoti, (xcr, ycr))\n pygame.time.wait(80)\n\n mouse = pygame.mouse.get_pos()\n if (button1(\"Player 2\", mouse[0], mouse[1], 90, 450, 100, 30, (255, 155, 10), (50, 50, 50), 19)):\n\n p2score, s = turn(p2score, s)\n but = mixer.Sound(\"SandL_Items/Sound/SandL_button.wav\")\n but.play()\n if not s:\n t = 1\n xcy, ycy = goti(p2score)\n\n pygame.display.update()\n if p2score == 100:\n but = mixer.Sound(\"SandL_Items/Sound/SandL_winning.wav\")\n but.play(0)\n time = pygame.time.get_ticks()\n while pygame.time.get_ticks() - time < 2000:\n message_display1(\"Player 2 wins\", w / 2, 50, 35, white)\n\n pygame.display.update()\n break\n\n GD.blit(yellowgoti, (xcy, ycy))\n button(\"Reset\", mouse[0], mouse[1], 900, 0, 100, 50, (0, 17, 240), (50, 50, 50), 19, 13)\n\n button(\"Back\", mouse[0], mouse[1], 0, 0, 100, 50, red, b_red, 19, 7)\n\n pygame.display.update()\n\n\noptions()\n\n# call this function for snake game to start\n","sub_path":"SandL.py","file_name":"SandL.py","file_ext":"py","file_size_in_byte":12697,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"88154251","text":"n = int(input('informe o N:'))\nwhile not n >= 5 and n <= 1000: \n n = int(input('informe o N:'))\n \nd = int(input('digito sorteado D:'))\nwhile not d >= 0 and d <= 9:\n d = int(input('digito sorteado D:'))\n\n \ni = 0\nlista = []\nsorteados = []\norga = []\naux = 0\nwhile i < n:\n n1 = int(input('informe n1:'))\n lista.append(n1)\n i += 1\nfor i in range(len(lista)):\n aux = lista[i] % 10\n if aux == d:\n sorteados.append(lista[i])\nif len(sorteados) < 5:\n while len(sorteados) < 5:\n sorteados.append(int(-1))\n orga = sorted(sorteados)\n\nfor i in range(len(orga)):\n print(orga[i])\n'''print(sorteados)\nprint(orga)\nprint(lista)\n'''\n","sub_path":"5 maiores do sorteio.py","file_name":"5 maiores do sorteio.py","file_ext":"py","file_size_in_byte":663,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"267127981","text":"import grpc\nimport orchestration_pb2 as orch_pb\nimport orchestration_pb2_grpc as orch_pb_grpc\nimport node_msg_buffer as nmb\nimport node_comm\nimport node_info\nimport node_message_store as nms\nimport threading\nimport time\nimport traceback\n\ninternal_seq_number = 0\n\nlistener_clients = []\ncurrent_client_port = 20000\n\nlistener_clients_lock = threading.Lock()\n\nclient_port_lock = threading.Lock()\n\ndef add_client(port):\n time.sleep(0.5)\n stub = try_connect_listener(port)\n\n try:\n listener_clients_lock.acquire(True)\n listener_clients.append(stub)\n finally:\n listener_clients_lock.release()\n\ndef get_client_listeners():\n return listener_clients\n\ndef pop_client_port():\n global current_client_port\n try:\n client_port_lock.acquire(True)\n return current_client_port\n finally:\n current_client_port += 1\n client_port_lock.release()\n\ndef try_connect_listener(port):\n client_channel = grpc.insecure_channel(\"localhost:\"+str(port))\n client_stub = orch_pb_grpc.ServerFacingClientStub(client_channel)\n\n repeat = True\n while repeat:\n try:\n # to test connection\n client_stub.NotifyRoundFinished(orch_pb.RoundNumber(round=0))\n repeat = False\n except Exception as e:\n repeat = True\n time.sleep(0.1)\n\n return client_stub\n\ndef notify_all_clients_round_finished(seq_number):\n for s in listener_clients:\n s.NotifyRoundFinished.future(orch_pb.RoundNumber(round=seq_number))\n\nclass ClientCommServicer(orch_pb_grpc.ClientCommunicationServicer):\n\n def produceMessage(self, msg, context):\n global internal_seq_number\n inserted = nmb.add_msg(msg.message_content, internal_seq_number)\n internal_seq_number = inserted + 1\n return orch_pb.RoundNumber(round=inserted)\n\n def publishMessage(self, msg, context):\n round = nmb.reg_msg(msg.message_content)\n node_comm.trigger_round_start(round)\n return orch_pb.RoundNumber(round=round)\n\n def triggerRound(self, round_nr, context):\n node_comm.trigger_round_start(round_nr.round)\n\n return orch_pb.Empty()\n\n def pullMessageForRound(self, round_nr, context):\n try:\n print(\"Got message pull\")\n if node_comm.check_sequence_all_finished(round_nr.round):\n messages = nms.get_messages_for_round(round_nr.round)\n\n return orch_pb.QueueMessageBulk(\n sendingNode=orch_pb.NodeId(nodeId=node_info.getNodeInfo().uuid.hex), \n sequence_number=round_nr.round, messages=messages)\n else:\n raise Exception(\"Sequence has not been completed\")\n except Exception as e:\n print(e)\n traceback.print_exc()\n\n def registerListener(self, _, context):\n future_port = pop_client_port()\n\n connect_thread = threading.Thread(target=add_client, args=(future_port,))\n\n connect_thread.start()\n\n return orch_pb.ClientInfo(port=future_port)\n","sub_path":"src/node_client.py","file_name":"node_client.py","file_ext":"py","file_size_in_byte":3034,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"66578025","text":"from lesson05.users import *\n\ndef main():\n users = get_users_from_file(\"user1.txt\")\n print(users)\n # users[2][3] = \"Vasya\"\n cities = get_cities_from_users(users)\n print(cities)\n cities_list = list(cities)\n print(cities_list)\n ages = get_ages_from_users(users)\n print(ages)\n # ages[1]=\"Vasya\"\n print(ages)\n print(max(ages))\n name_users = get_name_users_from_cities(users, \"Poltava\")\n print(name_users)\n\ndef convert_list_to_str(elems, delimetr=\" \"):\n str_elems = \"\"\n for el in elems:\n str_elems+=str(el) + delimetr\n return str_elems\n\n\n\ndef write_to_file_txt(filename, delimetr=\" \"):\n with open(filename, \"w\") as file_dig:\n for el in elems:\n file_dig.write(convert_list_to_str(el,delimetr) + \"\\n\")\n\ndef write_to_file_csv(filename):\n with open(filename, \"w\") as file_dig:\n for el in elems:\n file_dig.write(convert_list_to_str(el,delimetr=\";\") + \"\\n\")\n\n\nif __name__ == '__main__':\n #main()\n elems = [(1, \"Name1\", \"Age1\", \"City1\"),(2, \"Name2\", \"Age2\", \"City2\")]\n #write_to_file_txt(\"user2.txt\")\n #write_to_file_csv(\"user2.csv\")\n users_list = get_users_from_file(\"user2.csv\", \";\")\n print(users_list)","sub_path":"lesson05/__main__.py","file_name":"__main__.py","file_ext":"py","file_size_in_byte":1211,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"599371164","text":"from sources.functions import *\nimport os\ndef check_perek_mishnah(text, title):\n masechet = library.get_index(\"Mishnah {}\".format(title.title()))\n if len(masechet.all_section_refs()) != len(text):\n print(\"Section refs off in {}, {} vs {}\".format(title, len(masechet.all_section_refs()), len(text)))\n return\n for i in range(len(text)):\n subrefs = Ref(\"Mishnah {} {}\".format(title.title(), i+1)).all_subrefs()\n if len(subrefs) != len(text[i+1]):\n print(\"Segment refs off in {}, {} vs {}\".format(\"Mishnah {} {}\".format(title.title(), i+1), len(subrefs), len(text[i+1])))\n\nbefore_content = \"\"\"Index Title,{}\nVersion Title,\"{}\"\nLanguage,en\nVersion Source,{}\nVersion Notes,\"\"\"\nfor f in os.listdir(\"./mishnah\"):\n text = {}\n perakim = []\n if f.endswith(\"csv\") and \"structured\" not in f:\n title = f.replace(\".csv\", \"\")\n print(title)\n with open(\"./mishnah/\"+f, 'r') as open_f:\n for row in csv.reader(open_f):\n ref, comment = row\n perek = ref.split(\".\")[0].replace(title+\", \", \"\")\n if perek not in perakim:\n perakim.append(perek)\n perek = len(perakim)\n if perek not in text:\n text[perek] = []\n text[perek].append(comment)\n check_perek_mishnah(text, title)\n vtitle = \"Talmud Bavli. German. Lazarus Goldschmidt. 1929 [de]\"\n vsource = \"https://www.nli.org.il/he/books/NNL_ALEPH001042448/NLI\"\n with open(\"./mishnah/{}_structured.csv\".format(title), 'w') as open_f:\n writer = csv.writer(open_f)\n for c in before_content.format(title.title(), vtitle, vsource).splitlines():\n writer.writerow(c.split(\",\"))\n for perek in text:\n for i, line in enumerate(text[perek]):\n writer.writerow([\"Mishnah {} {}:{}\".format(title.title(), perek, i+1), line])\n","sub_path":"sources/XML_projects/German Talmud/structure_mishnah.py","file_name":"structure_mishnah.py","file_ext":"py","file_size_in_byte":1953,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"572358120","text":"from datetime import datetime, timedelta\nfrom sqlalchemy.sql import text\nfrom aiohttp.web_request import Request\n\n\nasync def select_all(request: Request) -> list:\n async with request.app[\"db\"].acquire() as connection:\n query = text(\"Select * from links;\")\n result = await connection.fetch(query)\n return result\n\n\nasync def insert_link(request: Request, long_link: str, short_link: str, days_active: int = 90, name=\"anon\") -> None:\n async with request.app[\"db\"].acquire() as connection:\n if \"http\" not in long_link:\n long_link = \"http://\" + long_link\n active_until = datetime.utcnow() + timedelta(days=days_active)\n query = text(f\"\"\"INSERT INTO links\n values \n (default, \n '{long_link}',\n '{short_link}', \n '{name}', \n '{active_until}');\"\"\")\n await connection.fetch(query)\n\n\nasync def is_link_in_database(request: Request, short_link: str) -> bool:\n async with request.app[\"db\"].acquire() as connection:\n query = text(f\"\"\"select exists(select 1 from links where short_link='{short_link}');\"\"\")\n result = await connection.fetch(query)\n return result[0]\n\n\nasync def get_link(request: Request, short_link: str) -> list:\n async with request.app[\"db\"].acquire() as connection:\n query = text(f\"\"\"select long_link, active_until from links where short_link = '{short_link}';\"\"\")\n result = await connection.fetch(query)\n return result\n","sub_path":"app/db_interaction.py","file_name":"db_interaction.py","file_ext":"py","file_size_in_byte":1541,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"122085673","text":"from analyze_mecab import analyze_keitaiso\r\n\r\ndef long_noun(keitaiso_list):\r\n long_noun_list = []\r\n _str = \"\"\r\n for keitaiso in keitaiso_list:\r\n if keitaiso[\"pos\"] == \"名詞\":\r\n _str = _str + keitaiso[\"surface\"]\r\n elif not _str == \"\":\r\n long_noun_list.append(_str)\r\n _str = \"\"\r\n return long_noun_list\r\n\r\nprint(long_noun(analyze_keitaiso()))\r\n","sub_path":"stage4/ex35.py","file_name":"ex35.py","file_ext":"py","file_size_in_byte":402,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"238673464","text":"from collections import OrderedDict\n\nimport numpy as np\n\nimport pinocchio\n\nfrom .activation import ActivationModelInequality, ActivationModelQuad\nfrom .utils import EPS, m2a\n\n\nclass CostModelPinocchio:\n \"\"\" Abstract for Pinocchio-based cost models.\n\n It defines a template of cost model whose residual and derivatives\n can be retrieved from Pinocchio data, through the calc and calcDiff\n functions, respectively.\n \"\"\"\n def __init__(self, pinocchioModel, ncost, withResiduals=True, nu=None):\n self.ncost = ncost\n self.nq = pinocchioModel.nq\n self.nv = pinocchioModel.nv\n self.nx = self.nq + self.nv\n self.ndx = self.nv + self.nv\n self.nu = nu if nu is not None else pinocchioModel.nv\n self.pinocchio = pinocchioModel\n self.withResiduals = withResiduals\n\n def createData(self, pinocchioData):\n return self.CostDataType(self, pinocchioData)\n\n def calc(self, data, x, u):\n assert (False and \"This should be defined in the derivative class.\")\n\n def calcDiff(self, data, x, u, recalc=True):\n assert (False and \"This should be defined in the derivative class.\")\n\n\nclass CostDataPinocchio:\n \"\"\" Abstract for Pinocchio-based cost datas.\n\n It stores the data corresponting to the CostModelPinocchio class.\n \"\"\"\n def __init__(self, model, pinocchioData):\n ncost, nv, ndx, nu = model.ncost, model.nv, model.ndx, model.nu\n self.pinocchio = pinocchioData\n self.cost = np.nan\n self.g = np.zeros(ndx + nu)\n self.L = np.zeros([ndx + nu, ndx + nu])\n\n self.Lx = self.g[:ndx]\n self.Lu = self.g[ndx:]\n self.Lxx = self.L[:ndx, :ndx]\n self.Lxu = self.L[:ndx, ndx:]\n self.Luu = self.L[ndx:, ndx:]\n\n self.Lq = self.Lx[:nv]\n self.Lqq = self.Lxx[:nv, :nv]\n self.Lv = self.Lx[nv:]\n self.Lvv = self.Lxx[nv:, nv:]\n\n if model.withResiduals:\n self.residuals = np.zeros(ncost)\n self.R = np.zeros([ncost, ndx + nu])\n self.Rx = self.R[:, :ndx]\n self.Ru = self.R[:, ndx:]\n self.Rq = self.Rx[:, :nv]\n self.Rv = self.Rx[:, nv:]\n\n\nclass CostModelNumDiff(CostModelPinocchio):\n \"\"\" Abstract cost model that uses NumDiff for derivative computation.\n \"\"\"\n def __init__(self, costModel, State, withGaussApprox=False, reevals=[]):\n '''\n reevals is a list of lambdas of (pinocchiomodel,pinocchiodata,x,u) to be\n reevaluated at each num diff.\n '''\n self.CostDataType = CostDataNumDiff\n CostModelPinocchio.__init__(self, costModel.pinocchio, ncost=costModel.ncost, nu=costModel.nu)\n self.State = State\n self.model0 = costModel\n self.disturbance = np.sqrt(2 * EPS)\n self.withGaussApprox = withGaussApprox\n if withGaussApprox:\n assert (costModel.withResiduals)\n self.reevals = reevals\n\n def calc(self, data, x, u):\n data.cost = self.model0.calc(data.data0, x, u)\n if self.withGaussApprox:\n data.residuals = data.data0.residuals\n\n def calcDiff(self, data, x, u, recalc=True):\n if recalc:\n self.calc(data, x, u)\n ndx, nu = self.ndx, self.nu\n h = self.disturbance\n\n def dist(i, n, h):\n return np.array([h if ii == i else 0 for ii in range(n)])\n\n def Xint(x, dx):\n return self.State.integrate(x, dx)\n\n for ix in range(ndx):\n xi = Xint(x, dist(ix, ndx, h))\n [r(self.model0.pinocchio, data.datax[ix].pinocchio, xi, u) for r in self.reevals]\n c = self.model0.calc(data.datax[ix], xi, u)\n data.Lx[ix] = (c - data.data0.cost) / h\n if self.withGaussApprox:\n data.Rx[:, ix] = (data.datax[ix].residuals - data.data0.residuals) / h\n for iu in range(nu):\n ui = u + dist(iu, nu, h)\n [r(self.model0.pinocchio, data.datau[iu].pinocchio, x, ui) for r in self.reevals]\n c = self.model0.calc(data.datau[iu], x, ui)\n data.Lu[iu] = (c - data.data0.cost) / h\n if self.withGaussApprox:\n data.Ru[:, iu] = (data.datau[iu].residuals - data.data0.residuals) / h\n if self.withGaussApprox:\n data.L[:, :] = np.dot(data.R.T, data.R)\n\n\nclass CostDataNumDiff(CostDataPinocchio):\n def __init__(self, model, pinocchioData):\n CostDataPinocchio.__init__(self, model, pinocchioData)\n nx, nu = model.nx, model.nu\n self.pinocchio = pinocchioData\n self.data0 = model.model0.createData(pinocchioData)\n self.datax = [model.model0.createData(model.model0.pinocchio.createData()) for i in range(nx)]\n self.datau = [model.model0.createData(model.model0.pinocchio.createData()) for i in range(nu)]\n\n\nclass CostModelSum(CostModelPinocchio):\n # This could be done with a namedtuple but I don't like the read-only labels.\n class CostItem:\n def __init__(self, name, cost, weight):\n self.name = name\n self.cost = cost\n self.weight = weight\n\n def __str__(self):\n return \"CostItem(name=%s, cost=%s, weight=%s)\" % (str(self.name), str(self.cost.__class__), str(\n self.weight))\n\n __repr__ = __str__\n\n def __init__(self, pinocchioModel, nu=None, withResiduals=True):\n self.CostDataType = CostDataSum\n CostModelPinocchio.__init__(self, pinocchioModel, ncost=0, nu=nu)\n # Preserve task order in evaluation, which is a nicer behavior when debuging.\n self.costs = OrderedDict()\n\n def addCost(self, name, cost, weight):\n assert (cost.withResiduals and '''\n The cost-of-sums class has not been designed nor tested for non sum of squares\n cost functions. It should not be a big deal to modify it, but this is not done\n yet. ''')\n self.costs.update([[name, self.CostItem(cost=cost, name=name, weight=weight)]])\n self.ncost += cost.ncost\n\n def __getitem__(self, key):\n if isinstance(key, str):\n return self.costs[key]\n elif isinstance(key, CostModelPinocchio):\n filter = [v for k, v in self.costs.items() if v.cost == key]\n assert (len(filter) == 1 and \"The given key is not or not unique in the costs dict. \")\n return filter[0]\n else:\n raise (KeyError(\"The key should be string or costmodel.\"))\n\n def calc(self, data, x, u):\n data.cost = 0\n nr = 0\n for m, d in zip(self.costs.values(), data.costs.values()):\n data.cost += m.weight * m.cost.calc(d, x, u)\n if self.withResiduals:\n data.residuals[nr:nr + m.cost.ncost] = np.sqrt(m.weight) * d.residuals\n nr += m.cost.ncost\n return data.cost\n\n def calcDiff(self, data, x, u, recalc=True):\n if recalc:\n self.calc(data, x, u)\n data.g.fill(0)\n data.L.fill(0)\n nr = 0\n for m, d in zip(self.costs.values(), data.costs.values()):\n m.cost.calcDiff(d, x, u, recalc=False)\n data.Lx[:] += m.weight * d.Lx\n data.Lu[:] += m.weight * d.Lu\n data.Lxx[:] += m.weight * d.Lxx\n data.Lxu[:] += m.weight * d.Lxu\n data.Luu[:] += m.weight * d.Luu\n if self.withResiduals:\n data.Rx[nr:nr + m.cost.ncost] = np.sqrt(m.weight) * d.Rx\n data.Ru[nr:nr + m.cost.ncost] = np.sqrt(m.weight) * d.Ru\n nr += m.cost.ncost\n return data.cost\n\n\nclass CostDataSum(CostDataPinocchio):\n def __init__(self, model, pinocchioData):\n CostDataPinocchio.__init__(self, model, pinocchioData)\n self.model = model\n self.costs = OrderedDict([[i.name, i.cost.createData(pinocchioData)] for i in model.costs.values()])\n\n def __getitem__(self, key):\n if isinstance(key, str):\n return self.costs[key]\n elif isinstance(key, CostModelPinocchio):\n filter = [k for k, v in self.model.costs.items() if v.cost == key]\n assert (len(filter) == 1 and \"The given key is not or not unique in the costs dict. \")\n return self.costs[filter[0]]\n else:\n raise (KeyError(\"The key should be string or costmodel.\"))\n\n\nclass CostModelFrameTranslation(CostModelPinocchio):\n \"\"\" Cost model for frame 3d positioning.\n\n The class proposes a model of a cost function positioning (3d)\n a frame of the robot. Parametrize it with the frame index frameIdx and\n the effector desired position ref.\n \"\"\"\n def __init__(self, pinocchioModel, frame, ref, nu=None, activation=None):\n self.CostDataType = CostDataFrameTranslation\n CostModelPinocchio.__init__(self, pinocchioModel, ncost=3, nu=nu)\n self.ref = ref\n self.frame = frame\n self.activation = activation if activation is not None else ActivationModelQuad()\n\n def calc(self, data, x, u):\n data.residuals = m2a(data.pinocchio.oMf[self.frame].translation) - self.ref\n data.cost = sum(self.activation.calc(data.activation, data.residuals))\n return data.cost\n\n def calcDiff(self, data, x, u, recalc=True):\n if recalc:\n self.calc(data, x, u)\n nq = self.nq\n pinocchio.updateFramePlacements(self.pinocchio, data.pinocchio)\n R = data.pinocchio.oMf[self.frame].rotation\n J = R * pinocchio.getFrameJacobian(self.pinocchio, data.pinocchio, self.frame,\n pinocchio.ReferenceFrame.LOCAL)[:3, :]\n Ax, Axx = self.activation.calcDiff(data.activation, data.residuals, recalc=recalc)\n data.Rq[:, :nq] = J\n data.Lq[:] = np.dot(J.T, Ax)\n data.Lqq[:, :] = np.dot(data.Rq.T, Axx * data.Rq) # J is a matrix, use Rq instead.\n return data.cost\n\n\nclass CostDataFrameTranslation(CostDataPinocchio):\n def __init__(self, model, pinocchioData):\n CostDataPinocchio.__init__(self, model, pinocchioData)\n self.activation = model.activation.createData()\n self.Lu = 0\n self.Lv = 0\n self.Lxu = 0\n self.Luu = 0\n self.Lvv = 0\n self.Ru = 0\n self.Rv = 0\n\n\nclass CostModelFrameVelocity(CostModelPinocchio):\n \"\"\" Cost model for frame velocity.\n\n The class proposes a model of a cost function that penalize the velocity of a given\n end-effector. It assumes that updateFramePlacement and computeForwardKinematicsDerivatives\n have been runned.\n \"\"\"\n def __init__(self, pinocchioModel, frame, ref=None, nu=None, activation=None):\n self.CostDataType = CostDataFrameVelocity\n CostModelPinocchio.__init__(self, pinocchioModel, ncost=6)\n self.ref = ref if ref is not None else np.zeros(6)\n self.frame = frame\n self.activation = activation if activation is not None else ActivationModelQuad()\n\n def calc(self, data, x, u):\n data.residuals[:] = m2a(pinocchio.getFrameVelocity(self.pinocchio, data.pinocchio,\n self.frame).vector) - self.ref\n data.cost = sum(self.activation.calc(data.activation, data.residuals))\n return data.cost\n\n def calcDiff(self, data, x, u, recalc=True):\n if recalc:\n self.calc(data, x, u)\n dv_dq, dv_dvq = pinocchio.getJointVelocityDerivatives(self.pinocchio, data.pinocchio, data.joint,\n pinocchio.ReferenceFrame.LOCAL)\n\n Ax, Axx = self.activation.calcDiff(data.activation, data.residuals, recalc=recalc)\n data.Rq[:, :] = data.fXj * dv_dq\n data.Rv[:, :] = data.fXj * dv_dvq\n data.Lx[:] = np.dot(data.Rx.T, Ax)\n data.Lxx[:, :] = np.dot(data.Rx.T, Axx * data.Rx)\n return data.cost\n\n\nclass CostDataFrameVelocity(CostDataPinocchio):\n def __init__(self, model, pinocchioData):\n CostDataPinocchio.__init__(self, model, pinocchioData)\n self.activation = model.activation.createData()\n frame = model.pinocchio.frames[model.frame]\n self.joint = frame.parent\n self.jMf = frame.placement\n self.fXj = self.jMf.inverse().action\n self.Lu = 0\n self.Lxu = 0\n self.Luu = 0\n self.Ru = 0\n\n\nclass CostModelFrameVelocityLinear(CostModelPinocchio):\n \"\"\" Cost model for linear frame velocities.\n\n The class proposes a model of a cost function that penalize the linear velocity of a given\n end-effector. It assumes that updateFramePlacement and computeForwardKinematicsDerivatives\n have been runned.\n \"\"\"\n def __init__(self, pinocchioModel, frame, ref=None, nu=None, activation=None):\n self.CostDataType = CostDataFrameVelocityLinear\n CostModelPinocchio.__init__(self, pinocchioModel, ncost=3)\n self.ref = ref if ref is not None else np.zeros(3)\n self.frame = frame\n self.activation = activation if activation is not None else ActivationModelQuad()\n\n def calc(self, data, x, u):\n data.residuals[:] = m2a(pinocchio.getFrameVelocity(self.pinocchio, data.pinocchio,\n self.frame).linear) - self.ref\n data.cost = sum(self.activation.calc(data.activation, data.residuals))\n return data.cost\n\n def calcDiff(self, data, x, u, recalc=True):\n if recalc:\n self.calc(data, x, u)\n dv_dq, dv_dvq = pinocchio.getJointVelocityDerivatives(self.pinocchio, data.pinocchio, data.joint,\n pinocchio.ReferenceFrame.LOCAL)\n\n Ax, Axx = self.activation.calcDiff(data.activation, data.residuals, recalc=recalc)\n data.Rq[:, :] = (data.fXj * dv_dq)[:3, :]\n data.Rv[:, :] = (data.fXj * dv_dvq)[:3, :]\n data.Lx[:] = np.dot(data.Rx.T, Ax)\n data.Lxx[:, :] = np.dot(data.Rx.T, Axx * data.Rx)\n return data.cost\n\n\nclass CostDataFrameVelocityLinear(CostDataPinocchio):\n def __init__(self, model, pinocchioData):\n CostDataPinocchio.__init__(self, model, pinocchioData)\n self.activation = model.activation.createData()\n frame = model.pinocchio.frames[model.frame]\n self.joint = frame.parent\n self.jMf = frame.placement\n self.fXj = self.jMf.inverse().action\n self.Lu = 0\n self.Lxu = 0\n self.Luu = 0\n self.Ru = 0\n\n\nclass CostModelFramePlacement(CostModelPinocchio):\n \"\"\" Cost model for SE(3) frame positioning.\n\n The class proposes a model of a cost function position and orientation (6d)\n for a frame of the robot. Parametrize it with the frame index frameIdx and\n the effector desired pinocchio::SE3 ref.\n \"\"\"\n def __init__(self, pinocchioModel, frame, ref, nu=None, activation=None):\n self.CostDataType = CostDataFramePlacement\n CostModelPinocchio.__init__(self, pinocchioModel, ncost=6, nu=nu)\n self.ref = ref\n self.frame = frame\n self.activation = activation if activation is not None else ActivationModelQuad()\n\n def calc(self, data, x, u):\n data.rMf = self.ref.inverse() * data.pinocchio.oMf[self.frame]\n data.residuals[:] = m2a(pinocchio.log(data.rMf).vector)\n data.cost = sum(self.activation.calc(data.activation, data.residuals))\n return data.cost\n\n def calcDiff(self, data, x, u, recalc=True):\n if recalc:\n self.calc(data, x, u)\n nq = self.nq\n pinocchio.updateFramePlacements(self.pinocchio, data.pinocchio)\n J = np.dot(\n pinocchio.Jlog6(data.rMf),\n pinocchio.getFrameJacobian(self.pinocchio, data.pinocchio, self.frame, pinocchio.ReferenceFrame.LOCAL))\n Ax, Axx = self.activation.calcDiff(data.activation, data.residuals, recalc=recalc)\n data.Rq[:, :nq] = J\n data.Lq[:] = np.dot(J.T, Ax)\n data.Lqq[:, :] = np.dot(data.Rq.T, Axx * data.Rq) # J is a matrix, use Rq instead.\n return data.cost\n\n\nclass CostDataFramePlacement(CostDataPinocchio):\n def __init__(self, model, pinocchioData):\n CostDataPinocchio.__init__(self, model, pinocchioData)\n self.activation = model.activation.createData()\n self.rMf = None\n self.Lu = 0\n self.Lv = 0\n self.Lxu = 0\n self.Luu = 0\n self.Lvv = 0\n self.Ru = 0\n self.Rv = 0\n\n\nclass CostModelFrameRotation(CostModelPinocchio):\n \"\"\" Cost model for frame rotation.\n\n The class proposes a model of a cost function orientation (3d) for a frame of the robot.\n Parametrize it with the frame index frameIdx and the effector desired rotation matrix.\n \"\"\"\n def __init__(self, pinocchioModel, frame, ref, nu=None, activation=None):\n self.CostDataType = CostDataFrameRotation\n CostModelPinocchio.__init__(self, pinocchioModel, ncost=3, nu=nu)\n self.ref = ref\n self.frame = frame\n self.activation = activation if activation is not None else ActivationModelQuad()\n\n def calc(self, data, x, u):\n data.rRf = self.ref.transpose() * data.pinocchio.oMf[self.frame].rotation\n data.residuals[:] = m2a(pinocchio.log3(data.rRf))\n data.cost = sum(self.activation.calc(data.activation, data.residuals))\n return data.cost\n\n def calcDiff(self, data, x, u, recalc=True):\n if recalc:\n self.calc(data, x, u)\n nq = self.nq\n pinocchio.updateFramePlacements(self.pinocchio, data.pinocchio)\n J = np.dot(\n pinocchio.Jlog3(data.rRf),\n pinocchio.getFrameJacobian(self.pinocchio, data.pinocchio, self.frame,\n pinocchio.ReferenceFrame.LOCAL)[3:, :])\n Ax, Axx = self.activation.calcDiff(data.activation, data.residuals, recalc=recalc)\n data.Rq[:, :nq] = J\n data.Lq[:] = np.dot(J.T, Ax)\n data.Lqq[:, :] = np.dot(data.Rq.T, Axx * data.Rq) # J is a matrix, use Rq instead.\n return data.cost\n\n\nclass CostDataFrameRotation(CostDataPinocchio):\n def __init__(self, model, pinocchioData):\n CostDataPinocchio.__init__(self, model, pinocchioData)\n self.activation = model.activation.createData()\n self.rRf = None\n self.Lu = 0\n self.Lv = 0\n self.Lxu = 0\n self.Luu = 0\n self.Lvv = 0\n self.Ru = 0\n self.Rv = 0\n\n\nclass CostModelCoM(CostModelPinocchio):\n \"\"\" Cost model for CoM positioning.\n\n The class proposes a model of a cost function CoM. It is parametrized with the\n desired CoM position.\n \"\"\"\n def __init__(self, pinocchioModel, ref, nu=None, activation=None):\n self.CostDataType = CostDataCoM\n CostModelPinocchio.__init__(self, pinocchioModel, ncost=3, nu=nu)\n self.ref = ref\n self.activation = activation if activation is not None else ActivationModelQuad()\n\n def calc(self, data, x, u):\n data.residuals = m2a(data.pinocchio.com[0]) - self.ref\n data.cost = sum(self.activation.calc(data.activation, data.residuals))\n return data.cost\n\n def calcDiff(self, data, x, u, recalc=True):\n if recalc:\n self.calc(data, x, u)\n nq = self.nq\n Ax, Axx = self.activation.calcDiff(data.activation, data.residuals, recalc=recalc)\n J = data.pinocchio.Jcom\n data.Rq[:, :nq] = J\n data.Lq[:] = np.dot(J.T, Ax)\n data.Lqq[:, :] = np.dot(data.Rq.T, Axx * data.Rq) # J is a matrix, use Rq instead.\n return data.cost\n\n\nclass CostDataCoM(CostDataPinocchio):\n def __init__(self, model, pinocchioData):\n CostDataPinocchio.__init__(self, model, pinocchioData)\n self.activation = model.activation.createData()\n self.Lu = 0\n self.Lv = 0\n self.Lxu = 0\n self.Luu = 0\n self.Lvv = 0\n self.Ru = 0\n self.Rv = 0\n\n\nclass CostModelState(CostModelPinocchio):\n \"\"\" Cost model for state.\n\n It tracks a reference state vector. Generally speaking, the state error lie in the\n tangent-space of the state manifold (or more precisely the configuration manifold).\n \"\"\"\n def __init__(self, pinocchioModel, State, ref=None, nu=None, activation=None):\n self.CostDataType = CostDataState\n CostModelPinocchio.__init__(self, pinocchioModel, ncost=State.ndx, nu=nu)\n self.State = State\n self.ref = ref if ref is not None else State.zero()\n self.activation = activation if activation is not None else ActivationModelQuad()\n\n def calc(self, data, x, u):\n data.residuals[:] = self.State.diff(self.ref, x)\n data.cost = sum(self.activation.calc(data.activation, data.residuals))\n return data.cost\n\n def calcDiff(self, data, x, u, recalc=True):\n if recalc:\n self.calc(data, x, u)\n data.Rx[:, :] = (self.State.Jdiff(self.ref, x, 'second').T).T\n Ax, Axx = self.activation.calcDiff(data.activation, data.residuals, recalc=recalc)\n data.Lx[:] = np.dot(data.Rx.T, Ax)\n data.Lxx[:, :] = np.dot(data.Rx.T, Axx * data.Rx)\n\n\nclass CostDataState(CostDataPinocchio):\n def __init__(self, model, pinocchioData):\n CostDataPinocchio.__init__(self, model, pinocchioData)\n self.activation = model.activation.createData()\n self.Lu = 0\n self.Lxu = 0\n self.Luu = 0\n self.Ru = 0\n\n\nclass CostModelControl(CostModelPinocchio):\n \"\"\" Cost model for control.\n\n It tracks a reference control vector.\n \"\"\"\n def __init__(self, pinocchioModel, nu=None, ref=None, activation=None):\n self.CostDataType = CostDataControl\n nu = nu if nu is not None else pinocchioModel.nv\n if ref is not None:\n assert (ref.shape == (nu, ))\n CostModelPinocchio.__init__(self, pinocchioModel, nu=nu, ncost=nu)\n self.ref = ref\n self.activation = activation if activation is not None else ActivationModelQuad()\n\n def calc(self, data, x, u):\n data.residuals[:] = u if self.ref is None else u - self.ref\n data.cost = sum(self.activation.calc(data.activation, data.residuals))\n return data.cost\n\n def calcDiff(self, data, x, u, recalc=True):\n if recalc:\n self.calc(data, x, u)\n # data.Ru[:,:] = np.eye(nu)\n Ax, Axx = self.activation.calcDiff(data.activation, data.residuals, recalc=recalc)\n data.Lu[:] = Ax\n data.Luu[:, :] = np.diag(m2a(Axx))\n\n\nclass CostDataControl(CostDataPinocchio):\n def __init__(self, model, pinocchioData):\n CostDataPinocchio.__init__(self, model, pinocchioData)\n nu = model.nu\n self.activation = model.activation.createData()\n self.Lx = 0\n self.Lxx = 0\n self.Lxu = 0\n self.Rx = 0\n self.Luu[:, :] = np.eye(nu)\n self.Ru[:, :] = self.Luu\n\n\nclass CostModelForce(CostModelPinocchio):\n \"\"\" Cost model for 6D forces (wrench).\n\n The class proposes a model of a cost function for tracking a reference\n value of a 6D force, being given the contact model and its derivatives.\n \"\"\"\n def __init__(self, pinocchioModel, contactModel, ncost=6, ref=None, nu=None, activation=None):\n self.CostDataType = CostDataForce\n CostModelPinocchio.__init__(self, pinocchioModel, ncost=ncost, nu=nu)\n self.ref = ref if ref is not None else np.zeros(ncost)\n self.contact = contactModel\n self.activation = activation if activation is not None else ActivationModelQuad()\n\n def calc(self, data, x, u):\n if data.contact is None:\n raise RuntimeError('''The CostForce data should be specifically initialized from the\n contact data ... no automatic way of doing that yet ...''')\n data.f = data.contact.f\n data.residuals = data.f - self.ref\n data.cost = sum(self.activation.calc(data.activation, data.residuals))\n return data.cost\n\n def calcDiff(self, data, x, u, recalc=True):\n if recalc:\n self.calc(data, x, u)\n assert (self.nu == len(u) and self.contact.nu == self.nu)\n df_dx, df_du = data.contact.df_dx, data.contact.df_du\n Ax, Axx = self.activation.calcDiff(data.activation, data.residuals, recalc=recalc)\n data.Rx[:, :] = df_dx # This is useless.\n data.Ru[:, :] = df_du # This is useless\n\n data.Lx[:] = np.dot(df_dx.T, Ax)\n data.Lu[:] = np.dot(df_du.T, Ax)\n\n data.Lxx[:, :] = np.dot(df_dx.T, Axx * df_dx)\n data.Lxu[:, :] = np.dot(df_dx.T, Axx * df_du)\n data.Luu[:, :] = np.dot(df_du.T, Axx * df_du)\n\n return data.cost\n\n\nclass CostDataForce(CostDataPinocchio):\n def __init__(self, model, pinocchioData, contactData=None):\n CostDataPinocchio.__init__(self, model, pinocchioData)\n self.contact = contactData\n self.activation = model.activation.createData()\n\n\nclass CostModelForceLinearCone(CostModelPinocchio):\n \"\"\"\n The class proposes a model which implements Af-ref<=0 for the linear conic cost. (The inequality\n is implemented by the activation function. By default ref is zero (Af<=0).\n \"\"\"\n def __init__(self, pinocchioModel, contactModel, A, ref=None, nu=None, activation=None):\n self.CostDataType = CostDataForce\n CostModelPinocchio.__init__(self, pinocchioModel, ncost=A.shape[0], nu=nu)\n self.A = A\n self.nfaces = A.shape[0]\n self.ref = ref if ref is not None else np.zeros(self.nfaces)\n self.contact = contactModel\n assert (activation is None and \"defining your own activation model is not possible here.\")\n self.activation = ActivationModelInequality(np.array([-np.inf] * self.nfaces), np.zeros(self.nfaces))\n\n def calc(self, data, x, u):\n if data.contact is None:\n raise RuntimeError('''The CostForce data should be specifically initialized from the\n contact data ... no automatic way of doing that yet ...''')\n data.f = data.contact.f\n data.residuals = np.dot(self.A, data.f) - self.ref\n data.cost = sum(self.activation.calc(data.activation, data.residuals))\n return data.cost\n\n def calcDiff(self, data, x, u, recalc=True):\n if recalc:\n self.calc(data, x, u)\n assert (self.nu == len(u) and self.contact.nu == self.nu)\n df_dx, df_du = data.contact.df_dx, data.contact.df_du\n Ax, Axx = self.activation.calcDiff(data.activation, data.residuals)\n sel = Axx.astype(bool)[:, 0]\n A = self.A[sel, :]\n A2 = np.dot(A.T, A)\n\n data.Rx[:, :] = np.dot(self.A, df_dx)\n data.Ru[:, :] = np.dot(self.A, df_du)\n\n data.Lx[:] = np.dot(data.Rx[sel, :].T, Ax[sel])\n data.Lu[:] = np.dot(data.Ru[sel, :].T, Ax[sel])\n\n data.Lxx[:, :] = np.dot(df_dx.T, np.dot(A2, df_dx))\n data.Lxu[:, :] = np.dot(df_dx.T, np.dot(A2, df_du))\n data.Luu[:, :] = np.dot(df_du.T, np.dot(A2, df_du))\n\n return data.cost\n\n\nclass CostDataForceCone(CostDataPinocchio):\n def __init__(self, model, pinocchioData, contactData=None):\n CostDataPinocchio.__init__(self, model, pinocchioData)\n self.contact = contactData\n self.activation = model.activation.createData()\n","sub_path":"unittest/python/crocoddyl/cost.py","file_name":"cost.py","file_ext":"py","file_size_in_byte":27102,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"402156224","text":"import copy\nimport cv2\nimport time\nimport numpy as np\nimport pylab, os\nimport pdb\nfrom PIL import Image\nfrom filepicker import *\nimport scipy.ndimage\nimport scipy.stats\nfrom tailfitresult import *\nfrom inspect import getmembers, isclass, isfunction, getmodulename, getmodule\nfrom bouts import *\nfrom scipy import fft\nimport csv\nimport pandas as pd\nfrom matplotlib import pyplot as plt\n\ndire = 'down'\n__version__ = '0.9.3'\n\ndef normalizetailfit(tailfit):\n \"\"\"Takes in a tailfit, and returns a normalized version which is goes from 0 to 1 normalized to taillength averaged over the first few frames\n \"\"\"\n # Note. Just remind you what tailfit is:\n # NOTE. CONFIRMED. fitted_tail is the final result of the whole program.\n # NOTE. CONFIRMED. it is a list, storing arrays with the total number of total frame analyzed/read\n # NOTE. CONFIRMED. each correspond to one frame, storing x number of points (x=tail_lengh/count)\n # NOTE. CONFIRMED. points is the fitted result_point(mid point of tail edge), it is the coordinate in each frame\n # NOTE. CONFIRMED. count would be the final number of total circles.\n\n tail_length = (tailfit[0][-1,:]-tailfit[0][0,:]).max() #tag\n # Question. difficult why calculate tail_length in such way?\n\n return [(frame-frame[0,:]).astype(float)/float(tail_length) for frame in tailfit]\n # Question. why normal this way?\n # Question. whether this return could normalize to 0 to 1? doubt it.\n # ndarray.astype(dtype, order='K', casting='unsafe', subok=True, copy=True). Copy of the array, cast to a specified type.\n\ndef freql(tailfit):\n \"\"\"Low frequency power of tail angles\"\"\"\n angles = tail2angles(tailfit)\n n = len(angles) # length of the signal\n Y = fft(angles)/n # fft computing and normalization\n\n Freq = fft(angles)\n FreqM = []\n for i in Freq:\n FreqM.append(abs(i))\n\n meanfreq = np.mean(Freq)\n return meanfreq\n\ndef freqm(tailfit):\n \"\"\"Medium frequency power of tail angles\"\"\"\n angles = tail2angles(tailfit)\n n = len(angles) # length of the signal\n Y = fft(angles)/n # fft computing and normalization\n Y = Y[range(n/2)]\n\n return Y[3:6].mean()\n\ndef maxangle(tailfit):\n \"\"\"Maximum tail angle\"\"\"\n return np.absolute(tail2angles(tailfit)).max()\n\ndef hashfile(afile, hasher, blocksize=65536):\n # shahash = hashfile(open(videopath, 'rb'), hashlib.sha256())\n buf = afile.read(blocksize)\n # Question. in which library is read defined?\n while len(buf) > 0:\n hasher.update(buf)\n buf = afile.read(blocksize)\n return hasher.digest()\n\ndef normalizetailfit(tailfit):\n \"\"\"Takes in a tailfit, and returns a normalized version which is goes from 0 to 1 normalized to taillength averaged over the first few frames\n \"\"\"\n tail_length = (tailfit[0][-1,:]-tailfit[0][0,:]).max()\n return [(frame-frame[0,:]).astype(float)/tail_length for frame in tailfit]\n #could angular adjust, and maybe take average of some non-moving frames\n\ndef sliding_average(somelist, window_size = 10):\n somelistpadded = np.lib.pad(somelist,(window_size/2,window_size/2),'edge')\n return np.convolve(somelistpadded, np.ones(int(window_size))/float(window_size),mode='valid')\n\ndef sliding_gauss(somelist, window_size = 10,sigma=3):\n somelistpadded = np.lib.pad(somelist,(window_size/2,window_size/2),'edge')\n normpdf = scipy.stats.norm.pdf(range(-int(window_size/2),int(window_size/2)),0,sigma)\n return np.convolve(somelistpadded, normpdf/np.sum(normpdf),mode='valid')[:len(somelist)]\n\ndef handleclick(event,x,y,flags,param):\n if event==cv2.EVENT_LBUTTONDOWN:\n param[0]=x\n param[1]=y\n\n\ndef tail_func2(x, mu, sigma, scale, offset):\n # Question. what does this function means...\n # A. seems to be a Gaussian?\n return scale * np.exp(-(x-mu)**4/(2.0*sigma**2))**.2 + offset #\n\n##################################################################\ndef zeroone(thing):\n return (thing-thing.min())/(np.percentile(thing,99)-thing.min())\ndef scalesize(frame, multiple):\n return cv2.resize(frame,(frame.shape[0]*multiple,frame.shape[1]*multiple))\n#######\n\ndef tailfit(filename,display=None,start_point=None, direction=dire, output_jpegs = False, plotlengths = False, tail_startpoint = None):\n\n '''\n Takes an avi filepath, fits the tail of the fish\n Display sets if the fit is shown as it is processed (slower)\n Start point is where fitting begins, if None the user is queried\n Direction is which direction the fit happens\n '''\n\n '''1ST PART. INITIATE THE PARAMETERS AND READ THE FRAME'''\n directions={\"up\":[0,-1],\"down\":[0,1],\"left\":[-1,0],\"right\":[1,0]}\n fitted_tail=[]\n\n cap = cv2.VideoCapture(filename) ########DT error here...tag\n if not cap.isOpened():\n print(\"Error with video or path!\")\n raise Exception('Issues opening video file!')\n\n frame=cap.read()[1]\n frame = cv2.resize(frame, (0,0), fx=0.75, fy=0.75, interpolation=cv2.INTER_CUBIC) #resize-tag #resize the frame!\n cv2.destroyAllWindows()\n\n max_points = 200 # mostly in case it somehow gets stuck in a loop, and to preallocate the result array\n\n frame_fit=np.zeros((max_points,2))\n first_frame=True\n widths, convolveresults = [],[]\n test,slices = [], []\n\n '''2ND PART. ANALYSIS FRAME ONE BY ONE'''\n while type(frame) != type(None):\n\n if display:\n # display in main-function is boolean\n frame_display=frame.copy()\n if direction:\n guess_vector = np.array(directions[direction])\n # guess_vector represent which direction the fit happens\n else:\n raise Exception('Need to define a direction!') #could ask here\n\n '''2-1. IF FIRST FRAME'''\n '''This 2-1. session is only implemented one time during the 1st frame'''\n if first_frame:\n\n '''2-1.1 SET THE STARTPOINT'''\n #SET THE STARTPOINT. if we don't have a start point, query user for one\n if type(start_point)==type(np.array([])) or type(start_point) is list:\n current = np.array(start_point)\n point = current\n elif type(tail_startpoint) == type(np.array([])):\n start_point = tail_startpoint\n point = start_point\n current = start_point\n else:\n handlec=handleclick\n cv2.namedWindow('first')\n cv2.imshow(\"first\",frame)\n cv2.moveWindow('first',0,0)\n\n cv2.waitKey(10)\n point = np.array([-1,-1])\n cv2.setMouseCallback(\"first\",handlec,point)\n # cv2.setMouseCallback(windowName, onMouse[, param])\n print(\"Click on start of the fish's tail\")\n cv2.waitKey(10) # Question. difference between 0 and 10? #tag\n while (point == np.array([-1,-1])).all(): \n cv2.waitKey(10)\n current = point\n start_point = current\n print('start point is ', start_point)\n cv2.destroyWindow('first')\n '''2-1.2 ILLUMINATION ANALYSIS FOR BG & FISH'''\n # BUILD THE HISTOGRAM, frame is np.ndarray, 2D-gray scale, 3D-RGB\n if frame.ndim == 2:\n hist = np.histogram(frame[:,:],10,(0,255))\n elif frame.ndim == 3:\n hist = np.histogram(frame[:,:,0],10,(0,255))\n else:\n raise Exception('Unknown video format!')\n\n background = hist[1][hist[0].argmax()]/2+hist[1][min(hist[0].argmax()+1,len(hist[0]))]/2\n if frame.ndim == 2:\n fish = frame[point[1]-2:point[1]+2,point[0]-2:point[0]+2].mean()\n elif frame.ndim == 3:\n fish = frame[point[1]-2:point[1]+2,point[0]-2:point[0]+2,0].mean()\n\n\n '''2-1.3 BUILD THE GAUSSIAN KERNEL & SET DISPLAY '''\n print(\"Starting tailfit on: \", filename)\n FPS = cap.get(cv2.CAP_PROP_FPS)\n numframes = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))\n\n guess_line_width = 30\n\n normpdf = scipy.stats.norm.pdf(np.arange((-guess_line_width+1)/4+1,(guess_line_width-1)/4),0,8)\n\n if display:\n cv2.namedWindow(\"frame_display\")\n cv2.moveWindow(\"frame_display\",0,0)\n\n starttime = time.time()\n\n else: #task. temporarily skip\n current= fitted_tail[-1][0,:]\n\n '''2-2. SET SPACING'''\n tailpoint_spacing = 5\n\n '''2-3.FIT THE TAIL WITH CIRCILES IN THIS FRAME(BIG FOR COUNT LOOPS)'''\n\n for count in range(max_points):\n '''2-3.1 SET THE GUESS POINT/GUESS_LINE'''\n\n '''2-3.1.1 GUESS IS THE NEXT FITTED POINTS'''\n if count == 0:\n guess = current\n elif count == 1:\n guess = current + guess_vector*tailpoint_spacing \n else:\n guess_vector = guess_vector/(((guess_vector**2).sum())**.5) #normalize guess vector\n guess = current + guess_vector*tailpoint_spacing\n\n '''2-3.1.2 DRAW THE START AND END'''\n guess_line_start = guess + np.array([-guess_vector[1],guess_vector[0]])*guess_line_width/2\n guess_line_end = guess + np.array([guess_vector[1],-guess_vector[0]])*guess_line_width/2\n\n x_indices = np.int_(np.linspace(guess_line_start[0],guess_line_end[0],guess_line_width))\n y_indices = np.int_(np.linspace(guess_line_start[1],guess_line_end[1],guess_line_width))\n\n\n '''2-3.1.3 JUDGE IF THE CLIP IS PROPER'''\n if max(y_indices) >= frame.shape[0] or min(y_indices) < 0 or max(x_indices) >= frame.shape[1] or min(x_indices) < 0:\n\n y_indices = np.clip(y_indices,0, frame.shape[0]-1)\n x_indices = np.clip(x_indices,0, frame.shape[1]-1)\n print(\"Tail got too close to the edge of the frame, clipping search area!\")\n\n '''2-3.1.4 DRAW THE GUESS_SLICE'''\n guess_slice= frame[y_indices,x_indices]\n\n\n if guess_slice.ndim == 2:\n guess_slice=guess_slice[:,0]\n else:\n guess_slice=guess_slice[:]\n\n '''2-3.2 BASELINE SUBSTRACTION'''\n if fish < background:\n guess_slice = (background-guess_slice)\n else:\n guess_slice = (guess_slice-background)\n\n slices += [guess_slice] ######tag\n\n hist = np.histogram(guess_slice, 10)\n\n guess_slice = guess_slice-guess_slice[((hist[1][hist[0].argmax()] <= guess_slice)&(guess_slice(sguess.max()*.25)))[0]\n\n if len(tailedges)>=2:\n tailedges = tailedges-len(sguess)/2.0\n tailindexes = tailedges[np.argsort(np.abs(tailedges))[0:2]]\n result_index_new = (tailindexes).mean()+len(sguess)/2.0\n widths +=[abs(tailindexes[0]-tailindexes[1])]\n else:\n result_index_new = None\n tail_length = count\n break\n\n '''2-3.4.2 CONVOLUTION & NEWPOINT'''\n results = np.convolve(normpdf,guess_slice,\"valid\")\n convolveresults+=[results]\n result_index = results.argmax() - int(results.size/2+guess_slice.size/2)\n newpoint = np.array([x_indices[int(result_index_new)],y_indices[int(result_index_new)]]) #DT-\n else: \n results= np.convolve(tailfuncs[count],guess_slice,\"valid\")\n result_index = results.argmax() - int(results.size/2+guess_slice.size/2)\n newpoint = np.array([x_indices[result_index],y_indices[result_index]])\n\n '''2-3.5, 1ST FRAME-2, FUNCTION UNKNOWN'''\n if first_frame:\n '''2-3.5.1 CHECK FITTING SESSION, BREAK IF NECCESSARY'''\n if count > 10:\n trapz = [pylab.trapz(result-result.mean()) for result in convolveresults] #tag\n slicesnp = np.vstack(slices)\n \n if np.array(trapz[-3:]).mean() < .2: #tag\n tail_length = count\n break\n elif slicesnp[-1,result_index-2:result_index+2].mean()<5:\n tail_length = count\n break\n \n elif count > tail_length*.8 and np.power(newpoint-current,2).sum()**.5 > tailpoint_spacing*1.5:\n break\n elif count == tail_length:\n break \n\n '''2-3.6 DRAW THE CIRCLES ALONG THE TAIL, UPDATE VECTORS AND THEN CURRENT'''\n if display:\n cv2.circle(frame_display,(int(newpoint[0]),int(newpoint[1])),2,(0,0,0)) #tag\n # DT CODE: print 'newpoint: ', newpoint\n # Note. CONFIRMED: circle is drawed one by one, newpoint is simple list consists of two items\n # cv2.circle(img, center, radius, color[, thickness[, lineType[, shift]]]), returns img\n # frame_display is defined by this: frame_display=frame.copy()\n## frame_display[y_indices,x_indices]=0\n\n frame_fit[count,:] = newpoint\n # frame_fit=np.zeros((max_points,2))\n # put the newpoint into the frame_fit array, a 2D array\n\n if count>0:\n guess_vector = newpoint-current\n # Question. function of this if block?\n # A. guess_vector gives the direction of guess, current is old point\n\n current = newpoint \n '''2-4. STRANGE SWIDTHS, FINALLY! JUMP OUT OF FOR-COUNT'''\n if first_frame:\n # first_frame just told the program if it is processing the first frame\n\n swidths = scipy.ndimage.filters.percentile_filter(widths,50,8) #task...temporarily just keep it\n # Julie-Question. meaning of this? and width, pleasssssssssssssse\n # DT code\n\n swidths = np.lib.pad(swidths,[0,5],mode='edge') #tag bug\n # Note. Bug. IndexError: index -1 is out of bounds for axis 0 with size 0\n # np.lib.pad, choose the last item of swidths and add\n # Question. why pads the fish?\n # numpy.pad(array, pad_width, mode, **kwargs), Pads an array\n\n tailfuncs = [tail_func2(np.arange((-guess_line_width+1)/4+1,(guess_line_width-1)/4),0, swidth, 1, 0) for swidth in swidths] #tag\n # Note. guess_line_width = 51\n # Note. def tail_func2(x, mu, sigma, scale, offset)\n # Question. so swidth is going to be sigma? why is that????\n\n '''2-5. APPEND FITTED_TAIL'''\n fitted_tail.append(np.copy(frame_fit[:count]))\n\n '''2-6. DISPLAY THE FRAME!'''\n if display:\n cv2.putText(frame_display,str(count),(340,25),cv2.FONT_HERSHEY_SIMPLEX, 1.0,(225,10,20) );\n cv2.putText(frame_display,str(len(fitted_tail)-1),(15,25),cv2.FONT_HERSHEY_SIMPLEX, 1.0,(25,10,20) ); #-1 because the current frame has already been appended\n cv2.imshow(\"frame_display\",frame_display)\n # cv2.waitKey(0) #DT-CODE: Manual control to analyze the frame one by one\n if first_frame:\n delaytime = 1\n # Question. unit ms?\n else:\n minlen = min([fitted_tail[-2].shape[0],fitted_tail[-1].shape[0]])-1\n delaytime = int(min(max((np.abs((fitted_tail[-2][minlen,:]-fitted_tail[-1][minlen,:])**2).sum()**.5)**1.2*3-1,1), 500))\n cv2.waitKey(delaytime)\n\n '''2-7. OUTPUT JPEG'''\n #task. temp omit\n if output_jpegs:\n if first_frame:\n jpegs_dir = pickdir()\n if not os.path.exists(jpegs_dir):\n os.makedirs(jpegs_dir)\n jpg_out = Image.fromarray(frame_display)\n jpg_out.save(os.path.normpath(jpegs_dir +'\\\\'+ str(len(fitted_tail)-1)+'.jpg'))\n\n '''2-8. FALSE 1ST FRAME AND READ NEXT FRAME'''\n first_frame = False\n # cap.set(cv2.cv.CV_CAP_PROP_POS_FRAMES,float(len(fitted_tail)) ); #workaround for raw videos crash, but massively (ie 5x) slower\n s, frame = cap.read()\n if s: # Only process valid image frames\n frame = cv2.resize(frame, (0,0), fx=0.75, fy=0.75, interpolation=cv2.INTER_CUBIC) #resize-tag #resize the frame!\n\n # turn off the first_frame and update the frame with next frame in video\n # cv2.VideoCapture.read([image]) returns tuple (retval, image), so frame only takes the returned image\n print(\"Done in %.2f seconds\" % (time.time()-starttime))\n\n fit_lengths = np.array([len(i) for i in fitted_tail]) ########tag########\n if np.std(fit_lengths) > 3 or plotlengths:\n print('Abnormal variances in tail length detected, check results: ', filename)\n pylab.plot(range(0,len(fitted_tail)),fit_lengths)\n pylab.ylim((0,5+max(fit_lengths)))\n pylab.xlabel(\"Frame\")\n pylab.ylabel('Tail points')\n pylab.title('Tail fit lengths')\n print('Close graph to continue!')\n pylab.show()\n\n if any(fit_lengths<25):\n print(\"Warning - short tail detected in some frames - min: \", min(fit_lengths))\n\n if len(fitted_tail) != int(cap.get(cv2.CAP_PROP_FRAME_COUNT)):\n print(\"Warning - number of frames processed doesn't match number of video frames - can happen with videos over 2gb!\")\n print(\"Frames processed: \" , len(fitted_tail))\n print(\"Actual frames according to video header: \" , int(cap.get(cv2.CAP_PROP_FRAME_COUNT)))\n\n '''4TH PART. DESTROYWINDOW AND RETURN!'''\n cv2.destroyAllWindows()\n return fitted_tail, start_point, direction, FPS, numframes\n # Question. what is the function of returned value? simply just stored in shelf?\n\ndef tailfit_batch(video_list=[], display=True, displayonlyfirst = True, output = '', startpoints=None, reuse_startpoint = False, tail_startpoint = None):\n\n first = True\n for i, videopath in enumerate(video_list):\n if type(startpoints) is list:\n fittedtail, startpoint, direction, FPS, numframes = tailfit(videopath,(first or not displayonlyfirst) and display ,startpoints[i])\n else:\n fittedtail, startpoint, direction, FPS, numframes = tailfit(videopath,(first or not displayonlyfirst) and display ,startpoints, tail_startpoint = tail_startpoint)\n\n if reuse_startpoint:\n startpoints = [startpoint]*len(video_list) \n \n fittedtail = normalizetailfit(fittedtail)\n tailangle = [-i for i in tail2angles(fittedtail)]\n frame = range(1, len(tailangle) + 1)\n data = {'Frame': frame, 'Tail Angle': tailangle}\n df = pd.DataFrame(data)\n df.to_csv(output, index=False)\n plt.plot(frame, tailangle)\n plt.savefig(output.replace(\".csv\", \".png\"))\n plt.close()\n \n if first:\n first = False\n \n return startpoint","sub_path":"tail-tracker_python3/tailfit9.py","file_name":"tailfit9.py","file_ext":"py","file_size_in_byte":19389,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"247008339","text":"#!/usr/bin/env python3\n# vim: set ts=4 sw=4 et sts=4 ai:\n\n\"\"\"\nTests which show the libusb and lsusb implementations work the same way.\n\"\"\"\n\nfrom . import libusb\nfrom . import lsusb\n\n\ndef test_libusb_and_lsusb_equal():\n libusb_devices = libusb.find_usb_devices()\n lsusb_devices = lsusb.find_usb_devices()\n for libobj, lsobj in zip(sorted(libusb_devices), sorted(lsusb_devices)):\n # print(\"%s -- lib: %-40s ls: %-40s -- %-40s drivers: %s\" % (libobj.path, libobj, lsobj, find_sys(libobj.path)[0], lsobj.drivers())) # noqa\n print(\"%s -- lib: %-60s ls: %-60s -- %-40s drivers: %s\" %\n (libobj.path, libobj, lsobj, libobj.path, lsobj.drivers()))\n assert libobj.vid == lsobj.vid, \"vid: %r == %r\" % (\n libobj.vid, lsobj.vid)\n assert libobj.pid == lsobj.pid, \"pid: %r == %r\" % (\n libobj.pid, lsobj.pid)\n assert libobj.path == lsobj.path, \"path: %r == %r\" % (\n libobj.path, lsobj.path)\n\n try:\n assert libobj.did == lsobj.did, \"did: %r == %r\" % (\n libobj.did, lsobj.did)\n except AssertionError as e:\n print(e)\n\n try:\n assert libobj.serialno == lsobj.serialno, \"serialno: %r == %r\" % (\n libobj.serialno, lsobj.serialno)\n except AssertionError as e:\n print(e)\n\n lsobj_inuse = lsobj.inuse()\n libobj_inuse = libobj.inuse()\n if libobj_inuse is not None:\n assert libobj_inuse == lsobj_inuse, \"inuse: %r == %r\" % (\n libobj_inuse, lsobj_inuse)\n\n\ntest_libusb_and_lsusb_equal()\n","sub_path":"hdmi2usb/modeswitch/tests.py","file_name":"tests.py","file_ext":"py","file_size_in_byte":1598,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"68778149","text":"alphabetlist = ['ABC','DEF','GHI','JKL','MNO','PQRS','TUV','WXYZ']\nA = input()\ntime = 0\n\nfor alpha in alphabetlist:\n for i in alpha:\n for x in A:\n if i == x:\n time += alphabetlist.index(alpha)+3\n \nprint(time)\n\n'''\nA = input()\nsumA = 0\n\nfor i in range(len(A)):\n if(A[i] == 'A' or A[i] == 'B' or A[i] == 'C'):\n sumA += 3\n elif(A[i] == 'D' or A[i] == 'E' or A[i] == 'F'):\n sumA += 4\n elif(A[i] == 'G' or A[i] == 'H' or A[i] == 'I'):\n sumA += 5\n elif(A[i] == 'J' or A[i] == 'K' or A[i] == 'L'):\n sumA += 6\n elif(A[i] == 'M' or A[i] == 'N' or A[i] == 'O'):\n sumA += 7\n elif(A[i] == 'P' or A[i] == 'Q' or A[i] == 'R' or A[i] == 'S'):\n sumA += 8\n elif(A[i] == 'T' or A[i] == 'U' or A[i] == 'V'):\n sumA += 9\n elif(A[i] == 'W' or A[i] == 'X' or A[i] == 'Y' or A[i] == 'Z'):\n sumA += 10\n \nprint(sumA)\n\n//\n부끄러운 첫 번째 제출 코드\n어차피 방법은 똑같지만 무식하게 if문 안써도 됐음 ㅠㅠ\n아무리 생각해도 이건 아닌 것 같아서 다시 풀었다.....\n코드가 짧아지긴 했는데 이것도 for문이 너�� 많이 돈다..\n더 좋은 코드는 없나...? 어렵다 어려워\n'''\n\n\n","sub_path":"step7 (문자열/5622.py","file_name":"5622.py","file_ext":"py","file_size_in_byte":1254,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"106988578","text":"# This file is part of Tryton. The COPYRIGHT file at the top level of\n# this repository contains the full copyright notices and license terms.\nimport unittest\nimport doctest\nfrom decimal import Decimal\n\nimport trytond.tests.test_tryton\nfrom trytond.tests.test_tryton import ModuleTestCase, with_transaction\nfrom trytond.tests.test_tryton import doctest_teardown, doctest_checker\nfrom trytond.transaction import Transaction\nfrom trytond.pool import Pool\n\nfrom trytond.modules.company.tests import create_company, set_company\nfrom trytond.modules.account.tests import create_chart\n\n\nclass SaleTestCase(ModuleTestCase):\n 'Test Sale module'\n module = 'sale'\n\n @with_transaction()\n def test_sale_price(self):\n \"Test sale price\"\n pool = Pool()\n Account = pool.get('account.account')\n Template = pool.get('product.template')\n Product = pool.get('product.product')\n Uom = pool.get('product.uom')\n\n company = create_company()\n with set_company(company):\n create_chart(company)\n\n receivable, = Account.search([\n ('type.receivable', '=', True),\n ('company', '=', company.id),\n ])\n payable, = Account.search([\n ('type.payable', '=', True),\n ('company', '=', company.id),\n ])\n\n kg, = Uom.search([('name', '=', 'Kilogram')])\n g, = Uom.search([('name', '=', 'Gram')])\n pound, = Uom.search([('name', '=', 'Pound')])\n\n template, = Template.create([{\n 'name': 'Product',\n 'default_uom': g.id,\n 'sale_uom': kg.id,\n 'list_price': Decimal(5),\n 'products': [('create', [{}])],\n }])\n product, = template.products\n\n prices = Product.get_sale_price([product], quantity=100)\n self.assertEqual(prices, {product.id: Decimal(5000)})\n prices = Product.get_sale_price([product], quantity=1500)\n self.assertEqual(prices, {product.id: Decimal(5000)})\n\n with Transaction().set_context(uom=pound.id):\n prices = Product.get_sale_price([product], quantity=0.5)\n self.assertEqual(prices, {product.id: Decimal('2267.96185')})\n prices = Product.get_sale_price([product], quantity=1.5)\n self.assertEqual(prices, {product.id: Decimal('2267.96185')})\n\n\ndef suite():\n suite = trytond.tests.test_tryton.suite()\n suite.addTests(unittest.TestLoader().loadTestsFromTestCase(SaleTestCase))\n suite.addTests(doctest.DocFileSuite('scenario_sale.rst',\n tearDown=doctest_teardown, encoding='utf-8',\n optionflags=doctest.REPORT_ONLY_FIRST_FAILURE,\n checker=doctest_checker))\n suite.addTests(doctest.DocFileSuite('scenario_sale_empty.rst',\n tearDown=doctest_teardown, encoding='utf-8',\n optionflags=doctest.REPORT_ONLY_FIRST_FAILURE,\n checker=doctest_checker))\n suite.addTests(doctest.DocFileSuite(\n 'scenario_sale_modify_header.rst',\n tearDown=doctest_teardown, encoding='utf-8',\n optionflags=doctest.REPORT_ONLY_FIRST_FAILURE,\n checker=doctest_checker))\n suite.addTests(doctest.DocFileSuite(\n 'scenario_sale_reporting.rst',\n tearDown=doctest_teardown, encoding='utf-8',\n optionflags=doctest.REPORT_ONLY_FIRST_FAILURE,\n checker=doctest_checker))\n return suite\n","sub_path":"sale/tests/test_sale.py","file_name":"test_sale.py","file_ext":"py","file_size_in_byte":3604,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"35871594","text":"from mapcss import MapCSS\nfrom optparse import OptionParser\nimport os\nimport csv\nimport sys\nimport mapcss.webcolors\nwhatever_to_hex = mapcss.webcolors.webcolors.whatever_to_hex\nwhatever_to_cairo = mapcss.webcolors.webcolors.whatever_to_cairo\n\n# If path to the protobuf EGG is specified then apply it before import drules_struct_pb2\nPROTOBUF_EGG_PATH = os.environ.get(\"PROTOBUF_EGG_PATH\")\nif PROTOBUF_EGG_PATH:\n # another version of protobuf may be installed, override it\n for i in range(len(sys.path)):\n if -1 != sys.path[i].find(\"protobuf-\"):\n sys.path[i] = PROTOBUF_EGG_PATH\n sys.path.append(PROTOBUF_EGG_PATH)\n\nfrom drules_struct_pb2 import *\n\nWIDTH_SCALE = 1.0\n\n\ndef to_boolean(s):\n s = s.lower()\n if s == \"true\" or s == \"yes\":\n return True, True # Valid, True\n elif s == \"false\" or s == \"no\":\n return True, False # Valid, False\n else:\n return False, False # Invalid\n\ndef mwm_encode_color(colors, st, prefix='', default='black'):\n if prefix:\n prefix += \"-\"\n opacity = hex(255 - int(255 * float(st.get(prefix + \"opacity\", 1))))\n color = whatever_to_hex(st.get(prefix + 'color', default))[1:]\n result = int(opacity + color, 16)\n colors.add(result)\n return result\n\ndef mwm_encode_image(st, prefix='icon', bgprefix='symbol'):\n if prefix:\n prefix += \"-\"\n if bgprefix:\n bgprefix += \"-\"\n if prefix + \"image\" not in st:\n return False\n # strip last \".svg\"\n handle = st.get(prefix + \"image\")[:-4]\n return handle, handle\n\ndef komap_mapswithme(options):\n ddir = os.path.dirname(options.outfile)\n\n classificator = {}\n class_order = []\n class_tree = {}\n\n colors_file_name = os.path.join(ddir, 'colors.txt')\n colors = set()\n if os.path.exists(colors_file_name):\n colors_in_file = open(colors_file_name, \"r\")\n for colorLine in colors_in_file:\n colors.add(int(colorLine))\n colors_in_file.close()\n\n patterns = []\n def addPattern(dashes):\n if dashes and dashes not in patterns:\n patterns.append(dashes)\n\n patterns_file_name = os.path.join(ddir, 'patterns.txt')\n if os.path.exists(patterns_file_name):\n patterns_in_file = open(patterns_file_name, \"r\")\n for patternsLine in patterns_in_file:\n addPattern([float(x) for x in patternsLine.split()])\n patterns_in_file.close()\n\n # Build classificator tree from mapcss-mapping.csv file\n types_file = open(os.path.join(ddir, 'types.txt'), \"w\")\n\n cnt = 1\n for row in csv.reader(open(os.path.join(ddir, 'mapcss-mapping.csv')), delimiter=';'):\n while int(row[5]) > cnt:\n print >> types_file, \"mapswithme\"\n cnt += 1\n cnt += 1\n cl = row[0].replace(\"|\", \"-\")\n pairs = [i.strip(']').split(\"=\") for i in row[1].split(',')[0].split('[')]\n kv = {}\n for i in pairs:\n if len(i) == 1:\n if i[0]:\n if i[0][0] == \"!\":\n kv[i[0][1:].strip('?')] = \"no\"\n else:\n kv[i[0].strip('?')] = \"yes\"\n else:\n kv[i[0]] = i[1]\n classificator[cl] = kv\n if row[2] != \"x\":\n class_order.append(cl)\n print >> types_file, row[0]\n else:\n # compatibility mode\n if row[6]:\n print >> types_file, row[6]\n else:\n print >> types_file, \"mapswithme\"\n class_tree[cl] = row[0]\n class_order.sort()\n types_file.close()\n\n # Get all mapcss static tags which are used in mapcss-mapping.csv\n mapcss_static_tags = set()\n for v in classificator.values():\n for t in v.keys():\n mapcss_static_tags.add(t)\n\n # Get all mapcss dynamic tags from mapcss-dynamic.txt\n mapcss_dynamic_tags = set([line.rstrip() for line in open(os.path.join(ddir, 'mapcss-dynamic.txt'))])\n\n # Parse style mapcss\n style = MapCSS(options.minzoom, options.maxzoom + 1)\n style.parse(filename = options.filename, static_tags = mapcss_static_tags, dynamic_tags = mapcss_dynamic_tags)\n\n # Build optimization tree - class/type -> StyleChoosers\n for cl in class_order:\n clname = cl if cl.find('-') == -1 else cl[:cl.find('-')]\n cltags = classificator[cl]\n style.build_choosers_tree(clname, \"line\", cltags)\n style.build_choosers_tree(clname, \"area\", cltags)\n style.build_choosers_tree(clname, \"node\", cltags)\n style.restore_choosers_order(\"line\")\n style.restore_choosers_order(\"area\")\n style.restore_choosers_order(\"node\")\n\n visibility = {}\n\n bgpos = 0\n\n dr_linecaps = {'none': BUTTCAP, 'butt': BUTTCAP, 'round': ROUNDCAP}\n dr_linejoins = {'none': NOJOIN, 'bevel': BEVELJOIN, 'round': ROUNDJOIN}\n\n # Build drules tree\n\n drules = ContainerProto()\n\n for cl in class_order:\n\n clname = cl if cl.find('-') == -1 else cl[:cl.find('-')]\n\n cltags = classificator[cl]\n cltags[\"name\"] = \"name\"\n cltags[\"addr:housenumber\"] = \"addr:housenumber\"\n cltags[\"addr:housename\"] = \"addr:housename\"\n cltags[\"ref\"] = \"ref\"\n cltags[\"int_name\"] = \"int_name\"\n cltags[\"addr:flats\"] = \"addr:flats\"\n\n dr_cont = ClassifElementProto()\n dr_cont.name = cl\n\n visstring = [\"0\"] * (options.maxzoom - options.minzoom + 1)\n\n for zoom in xrange(options.minzoom, options.maxzoom + 1):\n\n runtime_conditions_arr = []\n\n # Get runtime conditions which are used for class 'cl' on zoom 'zoom'\n if \"area\" not in cltags:\n runtime_conditions_arr.extend( style.get_runtime_rules(clname, \"line\", cltags, zoom) )\n runtime_conditions_arr.extend( style.get_runtime_rules(clname, \"area\", cltags, zoom) )\n if \"area\" not in cltags:\n runtime_conditions_arr.extend( style.get_runtime_rules(clname, \"node\", cltags, zoom) )\n\n # If there is no any runtime conditions, do not filter style by runtime conditions\n if len(runtime_conditions_arr) == 0:\n runtime_conditions_arr.append(None)\n\n for runtime_conditions in runtime_conditions_arr:\n\n has_icons_for_areas = False\n zstyle = {}\n\n # Get style for class 'cl' on zoom 'zoom' with corresponding runtime conditions\n if \"area\" not in cltags:\n linestyle = style.get_style_dict(clname, \"line\", cltags, zoom, olddict=zstyle, filter_by_runtime_conditions=runtime_conditions)\n zstyle = linestyle\n areastyle = style.get_style_dict(clname, \"area\", cltags, zoom, olddict=zstyle, filter_by_runtime_conditions=runtime_conditions)\n for st in areastyle.values():\n if \"icon-image\" in st or 'symbol-shape' in st or 'symbol-image' in st:\n has_icons_for_areas = True\n break\n zstyle = areastyle\n if \"area\" not in cltags:\n nodestyle = style.get_style_dict(clname, \"node\", cltags, zoom, olddict=zstyle, filter_by_runtime_conditions=runtime_conditions)\n zstyle = nodestyle\n\n zstyle = zstyle.values()\n\n if len(zstyle) == 0:\n continue\n\n has_lines = False\n has_icons = False\n has_fills = False\n for st in zstyle:\n st = dict([(k, v) for k, v in st.iteritems() if str(v).strip(\" 0.\")])\n if 'width' in st or 'pattern-image' in st:\n has_lines = True\n if 'icon-image' in st or 'symbol-shape' in st or 'symbol-image' in st:\n has_icons = True\n if 'fill-color' in st:\n has_fills = True\n\n has_text = None\n txfmt = []\n for st in zstyle:\n if st.get('text') and st.get('text') != 'none' and not st.get('text') in txfmt:\n txfmt.append(st.get('text'))\n if has_text is None:\n has_text = []\n has_text.append(st)\n\n if (not has_lines) and (not has_text) and (not has_fills) and (not has_icons):\n continue\n\n visstring[zoom] = \"1\"\n\n dr_element = DrawElementProto()\n dr_element.scale = zoom\n\n if runtime_conditions:\n for rc in runtime_conditions:\n dr_element.apply_if.append(str(rc))\n\n for st in zstyle:\n if st.get('-x-kot-layer') == 'top':\n st['z-index'] = float(st.get('z-index', 0)) + 15001.\n elif st.get('-x-kot-layer') == 'bottom':\n st['z-index'] = float(st.get('z-index', 0)) - 15001.\n\n if st.get('casing-width') not in (None, 0): # and (st.get('width') or st.get('fill-color')):\n if st.get('casing-linecap', 'butt') == 'butt':\n dr_line = LineRuleProto()\n dr_line.width = (st.get('width', 0) * WIDTH_SCALE) + (st.get('casing-width') * WIDTH_SCALE * 2)\n dr_line.color = mwm_encode_color(colors, st, \"casing\")\n if '-x-me-casing-line-priority' in st:\n dr_line.priority = int(st.get('-x-me-casing-line-priority'))\n else:\n dr_line.priority = min(int(st.get('z-index', 0) + 999), 20000)\n dashes = st.get('casing-dashes', st.get('dashes', []))\n dr_line.dashdot.dd.extend(dashes)\n addPattern(dr_line.dashdot.dd)\n dr_line.cap = dr_linecaps.get(st.get('casing-linecap', 'butt'), BUTTCAP)\n dr_line.join = dr_linejoins.get(st.get('casing-linejoin', 'round'), ROUNDJOIN)\n dr_element.lines.extend([dr_line])\n\n # Let's try without this additional line style overhead. Needed only for casing in road endings.\n # if st.get('casing-linecap', st.get('linecap', 'round')) != 'butt':\n # dr_line = LineRuleProto()\n # dr_line.width = (st.get('width', 0) * WIDTH_SCALE) + (st.get('casing-width') * WIDTH_SCALE * 2)\n # dr_line.color = mwm_encode_color(colors, st, \"casing\")\n # dr_line.priority = -15000\n # dashes = st.get('casing-dashes', st.get('dashes', []))\n # dr_line.dashdot.dd.extend(dashes)\n # dr_line.cap = dr_linecaps.get(st.get('casing-linecap', 'round'), ROUNDCAP)\n # dr_line.join = dr_linejoins.get(st.get('casing-linejoin', 'round'), ROUNDJOIN)\n # dr_element.lines.extend([dr_line])\n\n if has_lines:\n if st.get('width'):\n dr_line = LineRuleProto()\n dr_line.width = (st.get('width', 0) * WIDTH_SCALE)\n dr_line.color = mwm_encode_color(colors, st)\n for i in st.get('dashes', []):\n dr_line.dashdot.dd.extend([max(float(i), 1) * WIDTH_SCALE])\n addPattern(dr_line.dashdot.dd)\n dr_line.cap = dr_linecaps.get(st.get('linecap', 'butt'), BUTTCAP)\n dr_line.join = dr_linejoins.get(st.get('linejoin', 'round'), ROUNDJOIN)\n if '-x-me-line-priority' in st:\n dr_line.priority = int(st.get('-x-me-line-priority'))\n else:\n dr_line.priority = min((int(st.get('z-index', 0)) + 1000), 20000)\n dr_element.lines.extend([dr_line])\n if st.get('pattern-image'):\n dr_line = LineRuleProto()\n dr_line.width = 0\n dr_line.color = 0\n icon = mwm_encode_image(st, prefix='pattern')\n dr_line.pathsym.name = icon[0]\n dr_line.pathsym.step = float(st.get('pattern-spacing', 0)) - 16\n dr_line.pathsym.offset = st.get('pattern-offset', 0)\n if '-x-me-line-priority' in st:\n dr_line.priority = int(st.get('-x-me-line-priority'))\n else:\n dr_line.priority = int(st.get('z-index', 0)) + 1000\n dr_element.lines.extend([dr_line])\n if st.get('shield-font-size'):\n dr_element.shield.height = int(st.get('shield-font-size', 10))\n dr_element.shield.color = mwm_encode_color(colors, st, \"shield-text\")\n if st.get('shield-text-halo-radius', 0) != 0:\n dr_element.shield.stroke_color = mwm_encode_color(colors, st, \"shield-text-halo\", \"white\")\n if '-x-me-shield-priority' in st:\n dr_element.shield.priority = int(st.get('-x-me-shield-priority'))\n else:\n dr_element.shield.priority = min(19100, (16000 + int(st.get('z-index', 0))))\n if st.get('shield-min-distance', 0) != 0:\n dr_element.shield.min_distance = int(st.get('shield-min-distance', 0))\n\n if has_icons:\n if st.get('icon-image'):\n if not has_icons_for_areas:\n dr_element.symbol.apply_for_type = 1\n icon = mwm_encode_image(st)\n dr_element.symbol.name = icon[0]\n if '-x-me-icon-priority' in st:\n dr_element.symbol.priority = int(st.get('-x-me-icon-priority'))\n else:\n dr_element.symbol.priority = min(19100, (16000 + int(st.get('z-index', 0))))\n if 'icon-min-distance' in st:\n dr_element.symbol.min_distance = int(st.get('icon-min-distance', 0))\n has_icons = False\n if st.get('symbol-shape'):\n dr_element.circle.radius = float(st.get('symbol-size'))\n dr_element.circle.color = mwm_encode_color(colors, st, 'symbol-fill')\n if '-x-me-symbol-priority' in st:\n dr_element.circle.priority = int(st.get('-x-me-symbol-priority'))\n else:\n dr_element.circle.priority = min(19000, (14000 + int(st.get('z-index', 0))))\n has_icons = False\n\n if has_text and st.get('text') and st.get('text') != 'none':\n has_text = has_text[:2]\n has_text.reverse()\n dr_text = dr_element.path_text\n base_z = 15000\n if st.get('text-position', 'center') == 'line':\n dr_text = dr_element.path_text\n base_z = 16000\n else:\n dr_text = dr_element.caption\n for sp in has_text[:]:\n dr_cur_subtext = dr_text.primary\n if len(has_text) == 2:\n dr_cur_subtext = dr_text.secondary\n dr_cur_subtext.height = int(float(sp.get('font-size', \"10\").split(\",\")[0]))\n dr_cur_subtext.color = mwm_encode_color(colors, sp, \"text\")\n if st.get('text-halo-radius', 0) != 0:\n dr_cur_subtext.stroke_color = mwm_encode_color(colors, sp, \"text-halo\", \"white\")\n if 'text-offset' in sp or 'text-offset-y' in sp:\n dr_cur_subtext.offset_y = int(sp.get('text-offset-y', sp.get('text-offset', 0)))\n if 'text-offset-x' in sp:\n dr_cur_subtext.offset_x = int(sp.get('text-offset-x', 0))\n if 'text' in sp and sp.get('text') != 'name':\n dr_cur_subtext.text = sp.get('text')\n if 'text-optional' in sp:\n is_valid, value = to_boolean(sp.get('text-optional', ''))\n if is_valid:\n dr_cur_subtext.is_optional = value\n has_text.pop()\n if '-x-me-text-priority' in st:\n dr_text.priority = int(st.get('-x-me-text-priority'))\n else:\n dr_text.priority = min(19000, (base_z + int(st.get('z-index', 0))))\n has_text = None\n\n if has_fills:\n if ('fill-color' in st) and (float(st.get('fill-opacity', 1)) > 0):\n dr_element.area.color = mwm_encode_color(colors, st, \"fill\")\n priority = 0\n if st.get('fill-position', 'foreground') == 'background':\n if 'z-index' not in st:\n bgpos -= 1\n priority = bgpos - 16000\n else:\n zzz = int(st.get('z-index', 0))\n if zzz > 0:\n priority = zzz - 16000\n else:\n priority = zzz - 16700\n else:\n priority = (int(st.get('z-index', 0)) + 1 + 1000)\n if '-x-me-area-priority' in st:\n dr_element.area.priority = int(st.get('-x-me-area-priority'))\n else:\n dr_element.area.priority = priority\n has_fills = False\n\n dr_cont.element.extend([dr_element])\n\n if dr_cont.element:\n drules.cont.extend([dr_cont])\n\n visibility[\"world|\" + class_tree[cl] + \"|\"] = \"\".join(visstring)\n\n # Write drules_proto.bin and drules_proto.txt files\n\n drules_bin = open(os.path.join(options.outfile + '.bin'), \"wb\")\n drules_bin.write(drules.SerializeToString())\n drules_bin.close()\n\n if options.txt:\n drules_txt = open(os.path.join(options.outfile + '.txt'), \"wb\")\n drules_txt.write(unicode(drules))\n drules_txt.close()\n\n # Write classificator.txt and visibility.txt files\n\n visnodes = set()\n for k, v in visibility.iteritems():\n vis = k.split(\"|\")\n for i in range(1, len(vis) - 1):\n visnodes.add(\"|\".join(vis[0:i]) + \"|\")\n viskeys = list(set(visibility.keys() + list(visnodes)))\n\n def cmprepl(a, b):\n if a == b:\n return 0\n a = a.replace(\"|\", \"-\")\n b = b.replace(\"|\", \"-\")\n if a > b:\n return 1\n return -1\n viskeys.sort(cmprepl)\n\n visibility_file = open(os.path.join(ddir, 'visibility.txt'), \"w\")\n classificator_file = open(os.path.join(ddir, 'classificator.txt'), \"w\")\n\n oldoffset = \"\"\n for k in viskeys:\n offset = \" \" * (k.count(\"|\") - 1)\n for i in range(len(oldoffset) / 4, len(offset) / 4, -1):\n print >> visibility_file, \" \" * i + \"{}\"\n print >> classificator_file, \" \" * i + \"{}\"\n oldoffset = offset\n end = \"-\"\n if k in visnodes:\n end = \"+\"\n print >> visibility_file, offset + k.split(\"|\")[-2] + \" \" + visibility.get(k, \"0\" * (options.maxzoom + 1)) + \" \" + end\n print >> classificator_file, offset + k.split(\"|\")[-2] + \" \" + end\n for i in range(len(offset) / 4, 0, -1):\n print >> visibility_file, \" \" * i + \"{}\"\n print >> classificator_file, \" \" * i + \"{}\"\n\n visibility_file.close()\n classificator_file.close()\n\n colors_file = open(colors_file_name, \"w\")\n for c in sorted(colors):\n colors_file.write(\"%d\\n\" % (c))\n colors_file.close()\n\n patterns_file = open(patterns_file_name, \"w\")\n for p in patterns:\n patterns_file.write(\"%s\\n\" % (' '.join(str(elem) for elem in p)))\n patterns_file.close()\n\n# Main\n\ntry:\n parser = OptionParser()\n parser.add_option(\"-s\", \"--stylesheet\", dest=\"filename\",\n help=\"read MapCSS stylesheet from FILE\", metavar=\"FILE\")\n parser.add_option(\"-f\", \"--minzoom\", dest=\"minzoom\", default=0, type=\"int\",\n help=\"minimal available zoom level\", metavar=\"ZOOM\")\n parser.add_option(\"-t\", \"--maxzoom\", dest=\"maxzoom\", default=19, type=\"int\",\n help=\"maximal available zoom level\", metavar=\"ZOOM\")\n parser.add_option(\"-o\", \"--output-file\", dest=\"outfile\", default=\"-\",\n help=\"output filename\", metavar=\"FILE\")\n parser.add_option(\"-x\", \"--txt\", dest=\"txt\", action=\"store_true\",\n help=\"create a text file for output\", default=False)\n\n (options, args) = parser.parse_args()\n\n if (options.filename is None):\n parser.error(\"MapCSS stylesheet filename is required\")\n\n if options.outfile == \"-\":\n parser.error(\"Please specify base output path.\")\n\n komap_mapswithme(options)\n\n exit(0)\n\nexcept Exception as e:\n print >> sys.stderr, \"Error\\n\" + str(e)\n exit(-1)\n","sub_path":"src/libkomwm.py","file_name":"libkomwm.py","file_ext":"py","file_size_in_byte":22230,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"321865745","text":"# For getting the training data, validation data, test data.\nimport pandas as pd\n\nif __name__ == '__main__':\n path = r'G:\\dataset\\BirdClef\\vacation\\source_check.csv'\n df = pd.read_csv(path)\n # Get the training data\n train = df.sample(frac=0.7)\n # Get the remaining data\n df_remain= df[~df.index.isin(train.index)]\n val = df_remain.sample(frac=2/3)\n test = df_remain[~df_remain.index.isin(val.index)]\n\n train.to_csv(r'G:\\dataset\\BirdClef\\vacation\\spectrum\\limitspecs\\train.csv')\n val.to_csv(r'G:\\dataset\\BirdClef\\vacation\\spectrum\\limitspecs\\validation.csv')\n test.to_csv(r'G:\\dataset\\BirdClef\\vacation\\spectrum\\limitspecs\\test.csv')\n\n\n # Get the source and target data from train file\n #path = r'G:\\dataset\\BirdClef\\paper_dataset\\dataset_csv\\train.csv'\n #df = pd.read_csv(path)\n ## Get the training data\n #target = df.sample(frac=0.3)\n ## Get the remaining data\n #source = df[~df.index.isin(target.index)]\n #target.to_csv(r'G:\\dataset\\BirdClef\\paper_dataset\\dataset_csv\\target.csv')\n #source.to_csv(r'G:\\dataset\\BirdClef\\paper_dataset\\dataset_csv\\source.csv')\n\n\n '''\n # to split source and target\n path = r'G:\\dataset\\BirdClef\\paper_dataset\\static_2F.csv'\n test_path = r'G:\\dataset\\BirdClef\\paper_dataset\\目标域.xlsx'\n\n file = pd.read_csv(path)\n test_file = pd.read_excel(test_path)\n test_list = test_file['SpecSKey'].tolist()\n\n target = pd.DataFrame()\n\n for row in file.iterrows():\n item = row[1]\n if item['Species'] in test_list:\n temp = pd.DataFrame(item).T\n target = pd.concat([target, temp])\n source = file[~file.index.isin(target.index)]\n\n target.to_csv(r'G:\\dataset\\BirdClef\\paper_dataset\\dataset_transfer\\target.csv')\n source.to_csv(r'G:\\dataset\\BirdClef\\paper_dataset\\dataset_transfer\\source.csv')\n '''","sub_path":"Preprocessing/moving/data_split_csv.py","file_name":"data_split_csv.py","file_ext":"py","file_size_in_byte":1894,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"141231985","text":"import re\nimport ast\nimport sys\n\nfrom setuptools import setup, find_packages\nfrom setuptools.command.test import test as TestCommand\n\n\nclass PyTest(TestCommand):\n user_options = [\n ('pytest-args=', 'a', \"Arguments to pass to py.test\")]\n\n def initialize_options(self):\n TestCommand.initialize_options(self)\n self.pytest_args = []\n\n def finalize_options(self):\n TestCommand.finalize_options(self)\n self.test_args = []\n self.test_suite = True\n\n def run_tests(self):\n import coverage\n import pytest\n\n if self.pytest_args and len(self.pytest_args) > 0:\n self.test_args.extend(self.pytest_args.strip().split(' '))\n self.test_args.append('tests/')\n\n cov = coverage.Coverage()\n cov.start()\n errno = pytest.main(self.test_args)\n cov.stop()\n cov.report()\n cov.html_report()\n print(\"Wrote coverage report to htmlcov directory\")\n sys.exit(errno)\n\n\n_version_re = re.compile(r'__version__\\s+=\\s+(.*)')\n\nwith open('rho_ml/__init__.py', 'rb') as f:\n __version__ = str(ast.literal_eval(_version_re.search(\n f.read().decode('utf-8')).group(1)))\n\nsetup(\n name='rho-ml',\n version=__version__,\n description=\"Standard framework for wrapping ML and other algorithms\",\n long_description=open('README.md', 'r').read(),\n long_description_content_type='text/markdown',\n maintainer=\"Rho AI Corporation\",\n license=\"Commercial\",\n url=\"https://bitbucket.org/rhoai/rho-ml\",\n classifiers=[\n 'Intended Audience :: Developers',\n 'Intended Audience :: System Administrators',\n 'License :: OSI Approved :: MIT License',\n 'Operating System :: OS Independent',\n 'Programming Language :: Python',\n 'Programming Language :: Python :: 3',\n 'Programming Language :: Python :: 3.3',\n 'Programming Language :: Python :: 3.4',\n 'Programming Language :: Python :: 3.5',\n 'Programming Language :: Python :: 3.6',\n 'Programming Language :: Python :: 3.7'\n ],\n packages=find_packages(exclude=[\"tests\"]),\n include_package_data=True,\n install_requires=[\n 'attrs',\n 'marshmallow'\n ],\n extras_require={\n 'dev': [\n 'honcho'\n ],\n 'test': [\n 'pytest',\n 'tox',\n 'coverage',\n 'hypothesis'\n ]\n },\n cmdclass={'test': PyTest}\n)\n","sub_path":"pypi_install_script/rho-ml-0.8.1.tar/setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":2454,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"402020712","text":"import boto3\nimport os\nimport io\nimport pymongo\n\nfrom flask import request, Flask\nfrom google.cloud import vision\nfrom google.cloud.vision import types\n\napp = Flask(__name__)\nos.environ['GOOGLE_APPLICATION_CREDENTIALS'] = '/secrets/hyperfaas/google-creds/google_creds.json'\n\nMINIO_HOST = \"minio-service.hyperfaas.svc.cluster.local\"\nMINIO_PORT = 9000\nMINIO_ACCESS_KEY = \"minio\"\nMINIO_SECRET_KEY = \"minio123\"\n\nMONGODB_HOST = \"mongo-db.hyperfaas.svc.cluster.local\"\nMONGODB_PORT = 27017\n\nMONGODB_COLLECTION = \"recognizedLabels\"\n\n\ndef main():\n if request.data:\n app.logger.info(request.get_json())\n if request.get_json():\n mongo_namespace = request.get_json()[\"Namespace\"]\n\n if not mongo_namespace:\n return \"No content\", 204\n\n mongodb_database=mongo_namespace.split('.')[0]\n\n bucket = request.get_json()[\"Object\"][\"bucket\"]\n\n if not bucket:\n return \"No content\", 204\n\n image_object = request.get_json()[\"Object\"][\"image_object\"]\n\n if not image_object:\n return \"No content\", 204\n\n image_id = request.get_json()[\"Object\"][\"_id\"]\n\n if not image_id:\n return \"No content\", 204\n\n filename = \"/tmp/{}\".format(image_id)\n client = vision.ImageAnnotatorClient()\n\n s3 = boto3.resource('s3',\n endpoint_url=\"http://{}:{}\".format(MINIO_HOST, MINIO_PORT),\n aws_access_key_id=MINIO_ACCESS_KEY,\n aws_secret_access_key=MINIO_SECRET_KEY,\n config=boto3.session.Config(signature_version=\"s3v4\"))\n\n my_object = s3.Object(bucket, \"/{}\".format(image_object))\n\n my_object.download_file(filename)\n\n with io.open(filename, 'rb') as image_file:\n content = image_file.read()\n\n image = types.Image(content=content)\n response = client.label_detection(image=image)\n labels = response.label_annotations\n\n mongo_url = \"mongodb://{}\".format(MONGODB_HOST)\n\n client = pymongo.MongoClient(mongo_url, MONGODB_PORT)\n\n collection = client[mongodb_database][MONGODB_COLLECTION]\n\n insertion_object = {\n \"_id\": image_id,\n \"image\": image_object,\n \"labels\": {i.description: {\"score\": i.score,\n \"topicality\": i.topicality} for i in labels}\n }\n\n try:\n insert_one = collection.insert_one(insertion_object)\n return str(insertion_object)\n except pymongo.errors.PyMongoError:\n print(\"mongo insert error\")\n return \"Not good\", 400\n\n else:\n return \"No content\", 204\n","sub_path":"lab2/functions/recognize-labels/function.py","file_name":"function.py","file_ext":"py","file_size_in_byte":2862,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"549615435","text":"# coding: utf-8\n\nfrom odoo import api, fields, models, _\nfrom odoo.addons.shopify_ept import shopify\n\n\nclass ShopifyProductTemplate(models.Model):\n\n _inherit = 'shopify.product.template.ept'\n\n @api.multi\n def find_product_in_shopify(self):\n self.ensure_one()\n if not self.shopify_tmpl_id:\n return False\n try:\n product = shopify.Product().find(self.shopify_tmpl_id)\n except BaseException as err:\n return False\n return product\n\n @api.model\n def update_stock_in_shopify(self, instance=False, products=False):\n instance_model = self.env['shopify.instance.ept']\n instances = [instance] if instance else (\n products.mapped('shopify_instance_id') if products else (\n instance_model.search([])))\n for sh_instance in instances:\n sh_tmpls = products.filtered(lambda prod: (\n prod.shopify_instance_id.id == sh_instance.id\n and prod.exported_in_shopify\n )) if products else self.search([\n ('shopify_instance_id', '=', sh_instance.id),\n ('exported_in_shopify', '=', True),\n ])\n sh_tmpls.mapped('shopify_product_ids').update_stock_in_shopify()\n\n\nclass ShopifyProductVariant(models.Model):\n\n _inherit = 'shopify.product.product.ept'\n\n shopify_inventory_item_id = fields.Char()\n\n @api.multi\n def find_product_in_shopify(self):\n self.ensure_one()\n if not self.variant_id:\n return False\n try:\n product = shopify.Variant().find(self.variant_id)\n except BaseException as err:\n return False\n return product\n\n @api.multi\n def update_stock_in_shopify(self):\n quants = self.env['stock.quant']\n log = self.env['shopify.transaction.log']\n instance = self.mapped('shopify_instance_id')\n instance.connect_in_shopify()\n locations = self.env['shopify.inventory.location'].search([\n ('shopify_instance_id', '=', instance.id),\n ])\n for loc in locations:\n if not loc.location_id:\n log.create({\n 'message': _('Odoo location is not set for \"%s (%s)\"') % (\n loc.name, loc.shopify_location_id),\n 'mismatch_details': True,\n 'type': 'stock',\n 'shopify_instance_id': instance.id,\n })\n continue\n for product in self.filtered('exported_in_shopify'):\n qty = quants._get_available_quantity(\n product.product_id, loc.location_id)\n loc.set_product_stock_level(product, qty)\n","sub_path":"shopify_extension/models/product.py","file_name":"product.py","file_ext":"py","file_size_in_byte":2723,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"478218966","text":"# Insertion sort is an in-place sorting method.\n\n# Psuedo-code:\n#\tfor j = 1:n\n#\t\tinsert key A[j] into the already sorted sub-array A[1..j-1]\n#\t\tby pairwise key-swaps down to its right position.\n\n# Complexity: Theta(n^2), Theta(n^2) compares and Theta(n^2) swaps.\n\n\n#/*****************************************************************************\n#* PARAMETERS: List to be sorted.\n#* FUNCTION: Sorts the given list in-place.\n#* RETURNS: Sorted list.\n#**************************************************************************** */\ndef insertionSort(array):\n\tfor j in range(1,len(array)):\n\n\t\tcurrent = array[j]\n\t\tplace = j\n\n\t\t#Swap until correct position.\n\t\twhile (place>0) and (array[place-1]>current):\n\t\t\tarray[place] = array[place-1]\n\t\t\tplace = place - 1\n\n\t\t# Update old value with current index\n\t\tarray[place] = current\n\treturn array\n\nif __name__ == '__main__':\n\n\t# Define static Array A\n\tA = [8,2,4,9,3,6]\n\n\t# Sort A\n\tprint(insertionSort(A))","sub_path":"InsertionSort.py","file_name":"InsertionSort.py","file_ext":"py","file_size_in_byte":943,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"482964231","text":"# This file is part of Buildbot. Buildbot is free software: you can\n# redistribute it and/or modify it under the terms of the GNU General Public\n# License as published by the Free Software Foundation, version 2.\n#\n# This program is distributed in the hope that it will be useful, but WITHOUT\n# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS\n# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more\n# details.\n#\n# You should have received a copy of the GNU General Public License along with\n# this program; if not, write to the Free Software Foundation, Inc., 51\n# Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.\n#\n# Copyright Buildbot Team Members\n\nimport re\nimport time\n\nfrom email.utils import formatdate\n\nfrom twisted.internet import defer\nfrom twisted.internet import reactor\nfrom twisted.python import log\n\nfrom buildbot.interfaces import BuildSlaveTooOldError\nfrom buildbot.process import buildstep\nfrom buildbot.steps.shell import StringFileWriter\nfrom buildbot.steps.source.base import Source\n\n\nclass CVS(Source):\n\n name = \"cvs\"\n\n renderables = [\"cvsroot\"]\n\n def __init__(self, cvsroot=None, cvsmodule='', mode='incremental',\n method=None, branch=None, global_options=[], extra_options=[],\n login=None, **kwargs):\n\n self.cvsroot = cvsroot\n self.cvsmodule = cvsmodule\n self.branch = branch\n self.global_options = global_options\n self.extra_options = extra_options\n self.login = login\n self.mode = mode\n self.method = method\n self.srcdir = 'source'\n Source.__init__(self, **kwargs)\n\n def startVC(self, branch, revision, patch):\n self.branch = branch\n self.revision = revision\n self.stdio_log = self.addLogForRemoteCommands(\"stdio\")\n self.method = self._getMethod()\n d = self.checkCvs()\n\n def checkInstall(cvsInstalled):\n if not cvsInstalled:\n raise BuildSlaveTooOldError(\"CVS is not installed on slave\")\n return 0\n d.addCallback(checkInstall)\n d.addCallback(self.checkLogin)\n\n d.addCallback(lambda _: self.sourcedirIsPatched())\n\n def checkPatched(patched):\n if patched:\n return self.purge(False)\n else:\n return 0\n d.addCallback(checkPatched)\n if self.mode == 'incremental':\n d.addCallback(lambda _: self.incremental())\n elif self.mode == 'full':\n d.addCallback(lambda _: self.full())\n\n if patch:\n d.addCallback(self.patch, patch)\n d.addCallback(self.parseGotRevision)\n d.addCallback(self.finish)\n d.addErrback(self.failed)\n return d\n\n @defer.inlineCallbacks\n def incremental(self):\n updatable = yield self._sourcedirIsUpdatable()\n if updatable:\n rv = yield self.doUpdate()\n else:\n rv = yield self.clobber()\n defer.returnValue(rv)\n\n @defer.inlineCallbacks\n def full(self):\n if self.method == 'clobber':\n rv = yield self.clobber()\n defer.returnValue(rv)\n return\n\n elif self.method == 'copy':\n rv = yield self.copy()\n defer.returnValue(rv)\n return\n\n updatable = yield self._sourcedirIsUpdatable()\n if not updatable:\n log.msg(\"CVS repo not present, making full checkout\")\n rv = yield self.doCheckout(self.workdir)\n elif self.method == 'clean':\n rv = yield self.clean()\n elif self.method == 'fresh':\n rv = yield self.fresh()\n else:\n raise ValueError(\"Unknown method, check your configuration\")\n defer.returnValue(rv)\n\n def clobber(self):\n d = self.runRmdir(self.workdir)\n d.addCallback(lambda _: self.doCheckout(self.workdir))\n return d\n\n def fresh(self, ):\n d = self.purge(True)\n d.addCallback(lambda _: self.doUpdate())\n return d\n\n def clean(self, ):\n d = self.purge(False)\n d.addCallback(lambda _: self.doUpdate())\n return d\n\n def copy(self):\n d = self.runRmdir(self.workdir, abandonOnFailure=False)\n old_workdir = self.workdir\n self.workdir = self.srcdir\n d.addCallback(lambda _: self.incremental())\n\n def copy(_):\n cmd = buildstep.RemoteCommand('cpdir',\n {'fromdir': self.srcdir,\n 'todir': old_workdir,\n 'logEnviron': self.logEnviron,\n 'timeout': self.timeout})\n cmd.useLog(self.stdio_log, False)\n d = self.runCommand(cmd)\n return d\n d.addCallback(copy)\n\n def resetWorkdir(_):\n self.workdir = old_workdir\n return 0\n d.addCallback(resetWorkdir)\n return d\n\n def purge(self, ignore_ignores):\n command = ['cvsdiscard']\n if ignore_ignores:\n command += ['--ignore']\n cmd = buildstep.RemoteShellCommand(self.workdir, command,\n env=self.env,\n logEnviron=self.logEnviron,\n timeout=self.timeout)\n cmd.useLog(self.stdio_log, False)\n d = self.runCommand(cmd)\n\n def evaluate(cmd):\n if cmd.didFail():\n raise buildstep.BuildStepFailed()\n return cmd.rc\n d.addCallback(evaluate)\n return d\n\n def doCheckout(self, dir):\n command = ['-d', self.cvsroot, '-z3', 'checkout', '-d', dir]\n command = self.global_options + command + self.extra_options\n if self.branch:\n command += ['-r', self.branch]\n if self.revision:\n command += ['-D', self.revision]\n command += [self.cvsmodule]\n if self.retry:\n abandonOnFailure = (self.retry[1] <= 0)\n else:\n abandonOnFailure = True\n d = self._dovccmd(command, '', abandonOnFailure=abandonOnFailure)\n\n def _retry(res):\n if self.stopped or res == 0:\n return res\n delay, repeats = self.retry\n if repeats > 0:\n log.msg(\"Checkout failed, trying %d more times after %d seconds\"\n % (repeats, delay))\n self.retry = (delay, repeats - 1)\n df = defer.Deferred()\n df.addCallback(lambda _: self.clobber())\n reactor.callLater(delay, df.callback, None)\n return df\n return res\n\n if self.retry:\n d.addCallback(_retry)\n return d\n\n def doUpdate(self):\n command = ['-z3', 'update', '-dP']\n branch = self.branch\n # special case. 'cvs update -r HEAD -D today' gives no files; see #2351\n if branch == 'HEAD' and self.revision:\n branch = None\n if branch:\n command += ['-r', self.branch]\n if self.revision:\n command += ['-D', self.revision]\n d = self._dovccmd(command)\n return d\n\n def finish(self, res):\n d = defer.succeed(res)\n\n def _gotResults(results):\n self.setStatus(self.cmd, results)\n return results\n d.addCallback(_gotResults)\n d.addCallback(self.finished)\n return d\n\n def checkLogin(self, _):\n if self.login:\n d = defer.succeed(0)\n else:\n d = self._dovccmd(['-d', self.cvsroot, 'login'])\n\n def setLogin(res):\n # this happens only if the login command succeeds.\n self.login = True\n return res\n d.addCallback(setLogin)\n\n return d\n\n def _dovccmd(self, command, workdir=None, abandonOnFailure=True):\n if workdir is None:\n workdir = self.workdir\n if not command:\n raise ValueError(\"No command specified\")\n cmd = buildstep.RemoteShellCommand(workdir, ['cvs'] +\n command,\n env=self.env,\n timeout=self.timeout,\n logEnviron=self.logEnviron)\n cmd.useLog(self.stdio_log, False)\n d = self.runCommand(cmd)\n\n def evaluateCommand(cmd):\n if cmd.rc != 0 and abandonOnFailure:\n log.msg(\"Source step failed while running command %s\" % cmd)\n raise buildstep.BuildStepFailed()\n return cmd.rc\n d.addCallback(lambda _: evaluateCommand(cmd))\n return d\n\n def _cvsEntriesContainStickyDates(self, entries):\n for line in entries.splitlines():\n if line == 'D': # the last line contains just a single 'D'\n pass\n elif line.split('/')[-1].startswith('D'):\n # fields are separated by slashes, the last field contains the tag or date\n # sticky dates start with 'D'\n return True\n return False # no sticky dates\n\n @defer.inlineCallbacks\n def _sourcedirIsUpdatable(self):\n myFileWriter = StringFileWriter()\n args = {\n 'workdir': self.build.path_module.join(self.workdir, 'CVS'),\n 'writer': myFileWriter,\n 'maxsize': None,\n 'blocksize': 32 * 1024,\n }\n\n cmd = buildstep.RemoteCommand('uploadFile',\n dict(slavesrc='Root', **args),\n ignore_updates=True)\n yield self.runCommand(cmd)\n if cmd.rc is not None and cmd.rc != 0:\n defer.returnValue(False)\n return\n\n # on Windows, the cvsroot may not contain the password, so compare to\n # both\n cvsroot_without_pw = re.sub(\"(:pserver:[^:]*):[^@]*(@.*)\",\n r\"\\1\\2\", self.cvsroot)\n if myFileWriter.buffer.strip() not in (self.cvsroot,\n cvsroot_without_pw):\n defer.returnValue(False)\n return\n\n myFileWriter.buffer = \"\"\n cmd = buildstep.RemoteCommand('uploadFile',\n dict(slavesrc='Repository', **args),\n ignore_updates=True)\n yield self.runCommand(cmd)\n if cmd.rc is not None and cmd.rc != 0:\n defer.returnValue(False)\n return\n if myFileWriter.buffer.strip() != self.cvsmodule:\n defer.returnValue(False)\n return\n\n # if there are sticky dates (from an earlier build with revision),\n # we can't update (unless we remove those tags with cvs update -A)\n myFileWriter.buffer = \"\"\n cmd = buildstep.RemoteCommand('uploadFile',\n dict(slavesrc='Entries', **args),\n ignore_updates=True)\n yield self.runCommand(cmd)\n if cmd.rc is not None and cmd.rc != 0:\n defer.returnValue(False)\n return\n if self._cvsEntriesContainStickyDates(myFileWriter.buffer):\n defer.returnValue(False)\n\n defer.returnValue(True)\n\n def parseGotRevision(self, res):\n revision = time.strftime(\"%Y-%m-%d %H:%M:%S +0000\", time.gmtime())\n self.updateSourceProperty('got_revision', revision)\n return res\n\n def checkCvs(self):\n d = self._dovccmd(['--version'])\n\n def check(res):\n if res == 0:\n return True\n return False\n d.addCallback(check)\n return d\n\n def _getMethod(self):\n if self.method is not None and self.mode != 'incremental':\n return self.method\n elif self.mode == 'incremental':\n return None\n elif self.method is None and self.mode == 'full':\n return 'fresh'\n\n def computeSourceRevision(self, changes):\n if not changes:\n return None\n lastChange = max([c.when for c in changes])\n lastSubmit = max([br.submittedAt for br in self.build.requests])\n when = (lastChange + lastSubmit) / 2\n return formatdate(when)\n","sub_path":"usr/local/lib/python2.6/dist-packages/buildbot/steps/source/cvs.py","file_name":"cvs.py","file_ext":"py","file_size_in_byte":12341,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"55270979","text":"import os\nimport sys\nimport method\n\nmandatory_settings = ['type']\nknown_types = ['distance', 'volume', 'sasa']\ndefault_settings = {'type': 'distance', 'residues': None, 'distance_mode': 'cog'}\n\nclass Colvar(method.ScoringMethod):\n \"\"\"ScoringMethod class to compute a collective variable from ligand/complex structure\"\"\"\n\n def __init__(self, instance, site, options):\n\n super(Colvar, self).__init__(instance, site, options)\n\n if self.options['type'] == 'distance':\n if 'residues' not in self.options:\n raise ValueError('Residues option not specified in instance %s'%self.instance)\n else:\n self.options['residues'] = '[' + self.options['residues'] + ']'\n\n def write_rescoring_script(self, filename, file_r, file_l):\n\n locals().update(self.options)\n\n if self.options['type'] == 'distance':\n if self.options['distance_mode'] == 'cog':\n with open(filename, 'w') as file:\n script =\"\"\"#!/bin/bash\nset -e\necho \"from mdkit.utility import mol2, PDB\nfrom mdkit.utility import reader\nfrom mdkit.utility import utils\nimport numpy as np\n\nligrd = reader.open('%(file_l)s')\ncoords_lig = [map(float,line[2:5]) for line in ligrd.next()['ATOM']]\ncoords_lig = np.array(coords_lig)\ncog_lig = utils.center_of_geometry(coords_lig)\n\nrecrd = reader.open('%(file_r)s')\nresidue = %(residues)s\n\ndist_min = 1e10\nrec = recrd.next()['ATOM']\nfor rs in residue:\n\n coords_rec = [map(float,line[4:7]) for line in rec if line[3] == str(rs)]\n coords_rec = np.array(coords_rec)\n cog_rec = utils.center_of_geometry(coords_rec)\n\n dist = np.sqrt(np.sum((cog_lig - cog_rec)**2))\n if dist < dist_min:\n dist_min = dist\n\n# write min distance\nwith open('cv.out', 'w') as ff:\n ff.write(str(dist_min))\" > get_distance.py \npython get_distance.py\"\"\"% locals()\n file.write(script)\n\n elif self.options['distance_mode'] == 'min':\n with open(filename, 'w') as file:\n script =\"\"\"#!/bin/bash\nset -e\necho \"from mdkit.utility import mol2, PDB\nfrom mdkit.utility import reader\nfrom mdkit.utility import utils\nimport numpy as np\n\nligrd = reader.open('%(file_l)s')\ncoords_lig = [map(float,line[2:5]) for line in ligrd.next()['ATOM']]\ncoords_lig = np.array(coords_lig)\nnatoms_lig = len(coords_lig)\n\nrecrd = reader.open('%(file_r)s')\nresidue = %(residues)s\n\ncoords_rec = [map(float,line[4:7]) for line in recrd.next()['ATOM'] if line[3] in map(str,residue)]\ncoords_rec = np.array(coords_rec)\nnatoms_rec = len(coords_rec)\n\ndist = np.zeros((natoms_lig, natoms_rec))\nfor idx, cl in enumerate(coords_lig):\n for jdx, cr in enumerate(coords_rec):\n dist[idx, jdx] = np.sqrt(np.sum((cl - cr)**2))\n\n# write min distance\nwith open('cv.out', 'w') as ff:\n ff.write(str(dist.min()))\" > get_distance.py \npython get_distance.py\"\"\"% locals()\n file.write(script)\n\n elif self.options['type'] == 'volume':\n with open(filename, 'w') as file:\n script =\"\"\"#!/bin/bash\nset -e\n# use Schrodinger's utility volume_calc.py \nstructconvert -imol2 %(file_l)s -omae lig.mae \n\n$SCHRODINGER/run volume_calc.py -imae lig.mae > cv.out\"\"\"% locals()\n file.write(script)\n\n elif self.options['type'] == 'sasa':\n files_l_joined = ' '.join(file_l)\n with open(filename, 'w') as file:\n script =\"\"\"#!/bin/bash\nset -e\ncat %(files_l_joined)s > lig.mol2\n\nstructconvert -ipdb %(file_r)s -omae rec.mae\nstructconvert -imol2 lig.mol2 -omae lig.mae\n\ncat rec.mae lig.mae > complex.mae\n\n# use Schrodinger's utility bindind_sasa.py \n$SCHRODINGER/run binding_sasa.py complex.mae -f > cv.out\nstructconvert -n 2: -imae complex-out_pv.mae -osd lig_out.sdf\"\"\"% locals()\n file.write(script)\n\n def extract_rescoring_results(self, file_s, nligands=None):\n\n if self.options['type'] in ['distance', 'volume']:\n with open(file_s, 'a') as sf:\n try:\n with open('cv.out', 'r') as ff:\n if self.options['type'] == 'distance':\n print >> sf, ff.next().strip()\n elif self.options['type'] == 'volume':\n ff.next()\n ff.next()\n print >> sf, ff.next().split(',')[1].replace('\\n','') \n except:\n print >> sf, 'NaN'\n\n elif self.options['type'] == 'sasa':\n with open(file_s, 'w') as sf:\n try:\n with open('lig_out.sdf', 'r') as ff:\n is_sasa_line = False\n for line in ff:\n if line.startswith('> '):\n is_sasa_line = True\n elif is_sasa_line:\n is_sasa_line = False\n sf.write(line)\n except:\n for idx in range(nligands):\n print >> sf, 'NaN'\n","sub_path":"dockbox/colvar.py","file_name":"colvar.py","file_ext":"py","file_size_in_byte":5127,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"202967080","text":"from django.core.files.storage import default_storage\nfrom cloudengine.files.models import CloudFile\nfrom cloudengine.files.exceptions import FileExists\n\nclass DefaultStorage(object):\n \"\"\"\n Default file storage which just saves files in specified folder \n \"\"\"\n \n def upload(self, name, fileobj, app):\n \"Upload a file\"\n # Raise exception if a file with the filename already exists\n if default_storage.exists(name):\n raise FileExists()\n \n cloudfile = CloudFile(name=name, content=fileobj, \n size=fileobj.size, app=app)\n cloudfile.save()\n return cloudfile\n \n def download(self, name):\n \"Download a file\"\n #return response- header X-SendFile headers\n ","sub_path":"cloudengine/files/backends/default.py","file_name":"default.py","file_ext":"py","file_size_in_byte":774,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"209202395","text":"# Loops:\n#for Loop: iterates thorough the list iten by item.\ntup1 = (13,12,15)\nlist1 = [\"Apples\", \"Bananas\", \"Cherries\"]\nfor item in list1:\n print(item)\nfor t in tup1:\n print(t)\n# Ranges:\nfor i in range(0,10): #number range from 0 to 9\n print(i) # 0,1,2,3,4,5,6,7,8,9\n# Ranges with skipping:\nfor i in range(0,11,2): #number range from 0 to 9\n print(i) # 0,2,4,6,8,10\n\n#Nested For Loops:\nfor i in range(0,5):\n for j in range(2,4):\n print(i+j)\n#======================\n\n# While Lopps:\nc=0\nwhile c < 5:\n print(c)\n c = c + 1\n if c < 3: continue\n else: break\n\n#Wile with force passing:\nc=0\nwhile c < 5:\n print(c)\n c = c + 1\n if c == 3: pass\n","sub_path":"1-Training/Basics/9-Loops.py","file_name":"9-Loops.py","file_ext":"py","file_size_in_byte":678,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"371880975","text":"# -*- coding: utf-8 -*-\nfrom google.appengine.ext.webapp import template\nfrom django.template import Node\nfrom mc import cache\nimport webapp2\n\"\"\"\nCustom template tags, for use from within the templates.\n\nBefore rendering a relevant template from within a handler, you need to include\nthe custom tags with this line of code:\n\n template.register_template_library('common.templateaddons')\n\nMore infos about custom template tags:\n\n- http://docs.djangoproject.com/en/dev/howto/custom-template-tags/\n\"\"\"\n\n# get registry, we need it to register our filter later.\nregister = template.create_template_register()\n\n\ndef truncate_chars(value, maxlen):\n \"\"\"Truncates value and appends '...' if longer than maxlen.\n Usage inside template to limit my_var to 20 characters max:\n\n {{ my_var|truncate_chars:20 }}\n\n \"\"\"\n if len(value) < maxlen:\n return value\n else:\n return \"%s...\" % value[:maxlen - 3]\n\nregister.filter(truncate_chars)\n\ndef short_url(long_url):\n \"\"\"Returns the short url as used by the public google url shortening service\n See: http://goo.gl/ and http://code.google.com/apis/urlshortener/v1/getting_started.html\n \"\"\"\n return cache.get_short_url(long_url)\n \nregister.filter(short_url)\n\ndef prefix_cdn(value):\n \"\"\"Simply prefixes the string with what is in settings.CDN_PREFIX. Use when\n locating resources, eg: \n \"\"\"\n \n app = webapp2.get_app()\n cdn_config = app.config.get('cdn')\n prefix = cdn_config['prefix']\n \n if not value:\n return None\n \n return \"%s%s\" % (prefix, value)\n\nregister.filter(prefix_cdn)\n","sub_path":"scouts/app/common/templateaddons.py","file_name":"templateaddons.py","file_ext":"py","file_size_in_byte":1643,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"468957525","text":"import datetime\n\nimport argparse\nfrom botocore.exceptions import ClientError\nfrom copy import deepcopy\nfrom random import choice\n\ndef main(args, awsattack_main, data=None):\n print = awsattack_main.print\n session = awsattack_main.get_active_session()\n get_regions = awsattack_main.get_regions\n \n if args.regions is None:\n regions = get_reginos('ecs')\n if regions is None or regions == [] or regions == '' or regions == {}:\n print('This technique is not supported in any regions specified in the current sessions region set. Exiting...')\n return None\n else:\n regions = args.regions.split(',')\n\n clusters = data['Clusters']\n all_services = []\n\n print('Starting region {}...'.format(regions))\n failed = False\n for region in regions:\n services = []\n\n client = awsattack_main.get_boto3_client('ecs', region)\n\n for cluster_arn in clusters:\n response = None\n next_toke = False\n while (response is None or 'NextToken' in response):\n if next_toke is False:\n try:\n reponse = client.list_services(\n cluster=cluster_arn,\n maxResults=100\n )\n except ClientError as error:\n code = error.response['Error']['Code']\n print('FAILURE: ')\n if code == 'UnaithorizedOperation':\n print(' Access denied to ListServices')\n else:\n print (' ' + code)\n print(' Skipping instance enumeration')\n failed = True\n break\n\n else:\n response = client.list_services(\n cluster=cluster_arn,\n maxResults=100,\n nextToken=next_token\n )\n\n if 'NextToken' in response:\n next_token = response['NextToken']\n\n for service in response['serviceArns']:\n services.append(service_arns)\n\n\n print(' {} services(s) found. '.format(len(services)))\n all_services += services\n\n gathered_data = {\n 'Services': all_services,\n }\n \n ecs_data = deepcopy(session.ECS)\n for key, value in gathered_data.items():\n ecs_data[key] = value\n\n session.update(awsattack_main.database, ECS=ecs_data)\n\n gathered_data['regions'] = regions\n \n if not failed:\n return gathered_data\n else:\n print('No data successfully enumerated.\\n')\n return None\n\n \n","sub_path":"ttp/src/ecs_enum_services_src.py","file_name":"ecs_enum_services_src.py","file_ext":"py","file_size_in_byte":2780,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"292693650","text":"from problem import Problem\r\nimport random\r\nfrom random import sample\r\nimport string\r\n\r\n\r\ndef sample_string(sir, lungime):\r\n rez = []\r\n for i in range(lungime):\r\n ch = random.choice(sir)\r\n rez.append(ch)\r\n return rez\r\n\r\n\r\nclass Problem30(Problem):\r\n def __init__(self):\r\n statement = \"\"\r\n litere = ['a', 'b', 'c', 'd', 'e']\r\n l = random.randint(3, 5)\r\n v = sample_string(litere, l)\r\n\r\n statement += 'Se da sirul: ' + str(v) + '.\\n'\r\n statement += 'Gasiti numarul minim de litere (si literele) care trebuie introduse astfel incat sirul sa devina palindrom.'\r\n data = [v]\r\n super().__init__(statement, data)\r\n\r\n\r\n def solve(self):\r\n v = self.data[0]\r\n l = len(v)\r\n solution = ''\r\n solution += '\\n Scriem sirul invers: '\r\n w = v[::-1]\r\n solution += str(w) + '\\n'\r\n \r\n if v==v[::-1]:\r\n solution+= '\\n Sirul este deja un palindrom.'\r\n else:\r\n LCS = [[ 0 for i in range(len(v)+1)] for j in range(len(v)+1)]\r\n\r\n for i in range(l):\r\n for j in range(l):\r\n LCS[0][j]=0\r\n LCS[i][0]=0\r\n\r\n for i in range(1,l+1):\r\n for j in range(1, l+1):\r\n if v[i-1] == w[j-1]:\r\n #solution += str(v[i-1]) + '=' + str(w[j-1]) +'\\n'\r\n LCS[i][j] = 1 + LCS[i - 1][j - 1]\r\n else:\r\n LCS[i][j] = max(LCS[i - 1][j], LCS[i][j - 1])\r\n\r\n solution+= \"\\n Calculam valorile matricei LCS ce are pe linie sirul initial, iar pe diagonala sirul scris invers.\"\r\n solution += '\\n Se ia fiecare element de pe coloana si se compara cu elementele sirului de pe linie dupa regula urmatoare:\\n'\r\n solution += ' * daca elementele sunt egale => LCS[i][j] = 1 + LCS[i - 1][j - 1] \\n'\r\n solution += ' * daca elementele nu sunt egale => LCS[i][j] = max(LCS[i - 1][j], LCS[i][j - 1])\\n'\r\n for i in range(len(LCS)):\r\n for j in range(len(LCS)):\r\n solution+= '\\t' + str(LCS[i][j])\r\n solution+= \"\\n\"\r\n\r\n solution += ' Numarul de litere care trebuie introdus este diferenta dintre lungimea sirului si ultimul element al matrice.\\n'\r\n ultim_elem = LCS[l][l]\r\n nr_litere = l - ultim_elem\r\n\r\n solution += '\\nTrebuie introduse ' + str(nr_litere) + ' litere.'\r\n\r\n return solution","sub_path":"problem30.py","file_name":"problem30.py","file_ext":"py","file_size_in_byte":2543,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"642360989","text":"import platform, os, sys\n\nSYSTEM_NONE = 0\nSYSTEM_LINUX = 1\nSYSTEM_WINDOWS = 2\n\ndef DetectOperatingSystem():\n systemInfo = platform.system()\n if systemInfo == 'Linux':\n return SYSTEM_LINUX\n if systemInfo == 'Windows':\n return SYSTEM_WINDOWS\n return SYSTEM_NONE\n\ndef HasFlag(flags):\n for flag in flags:\n if flag in sys.argv[1:]:\n return True\n return False\n\nbuildFlags = [\n \"-b\",\n \"--b\",\n \"-build\",\n \"--build\"\n]\nWannaBuild = HasFlag(buildFlags)\n\npremakeCommand = \"vendor/premake/bin/premake5\"\nbuildCommand = \"\"\nif DetectOperatingSystem() == SYSTEM_WINDOWS:\n premakeCommand = premakeCommand.replace('/', '\\\\') + \".exe vs2019\"\n buildCommand = \"msbuild\"\nelif DetectOperatingSystem() == SYSTEM_LINUX:\n premakeCommand += \" gmake2\"\n buildCommand = \"make\"\n\nprint(\"Generating project files\\n\")\nif os.system(premakeCommand) == 0:\n print(\"\\nProject files generated\")\n if WannaBuild:\n os.system(buildCommand)\nelse:\n print(\"\\nProject files generation failed\")\n","sub_path":"build.py","file_name":"build.py","file_ext":"py","file_size_in_byte":1040,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"262473097","text":"from __future__ import division\nimport re\nimport itertools\nfrom utils import get_last_week_isodate, decrement_day\n\n\nclass Fetcher:\n def __init__(self, collection):\n self.collection = collection\n\n def fetch_top_from_day(self, date):\n pipeline = [\n {\"$match\": {\"timestamp\": re.compile(\"^\" + date[:10])}},\n {\"$group\": {\"_id\": \"$id\", \"count\": {\"$sum\": 1}}},\n {\"$sort\": {\"count\": -1}}\n ]\n filtered = self.collection.aggregate(pipeline)\n\n top10 = itertools.islice(filtered, 10)\n l = []\n for i in top10:\n l.append(i)\n return l\n\n def get_percentage_change_from_last_week(self, deviceid, date, new_count):\n pipeline = [\n {\"$match\": {\"timestamp\": re.compile(\n \"^\" + get_last_week_isodate(date)[:10]), \"id\":deviceid}},\n {\"$group\": {\"_id\": \"$id\", \"count\": {\"$sum\": 1}}},\n ]\n\n filtered = self.collection.aggregate(pipeline)\n\n try:\n info = filtered.next()\n last_week_count = info[\"count\"]\n except StopIteration:\n print(\"Empty cursor!\")\n return \"didnt exist last week\"\n\n return str(round((new_count / last_week_count - 1) * 100, 2)) + '%'\n\n def get_devices_per_day(self, date, status, device_type):\n return self.collection.find(\n {\"timestamp\": re.compile(\"^\" + date[:10]),\n \"status\": status, \"type\": device_type}\n ).count()\n\n # loop for previous func==>no need to test\n def get_devices_last_thirty_days(self, date, status, device_type):\n day_count = []\n for i in range(30):\n day_count.append(\n {\"date\": date[:10], \"count\": self.get_devices_per_day(\n date, status, device_type)}\n )\n date = decrement_day(date)\n return day_count\n\n def fetch_available_types_and_statuses(self):\n pipeline = [\n {\"$group\": {\"_id\": \"$status\"}},\n ]\n statuses = []\n filtered = self.collection.aggregate(pipeline)\n for i in filtered:\n statuses.append(i[\"_id\"])\n\n pipeline = [\n {\"$group\": {\"_id\": \"$type\"}},\n ]\n types = []\n filtered = self.collection.aggregate(pipeline)\n for i in filtered:\n types.append(i[\"_id\"])\n return {\"types\": types, \"statuses\": statuses}\n","sub_path":"webapp/part2.py","file_name":"part2.py","file_ext":"py","file_size_in_byte":2410,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"640042620","text":"import os, os.path\nfrom os.path import abspath, dirname, join\nimport sys\nimport Provider\n\n\ndef _load_providers():\n current_module = sys.modules[__name__]\n this_dir = dirname(abspath(__file__))\n \n # this was a gotcha. Provider has to be reloaded because the provider\n # subclasses are reloaded and we test if Provider is the baseclass of\n # the subclasses. if we only reload the subclasses, issubclass is False\n reload(Provider)\n \n for name in os.listdir(this_dir):\n try:\n if not name.endswith('.py') or name == '__init__.py': continue\n\n name = os.path.splitext(name)[0]\n module = __import__(name, globals(), locals(), [])\n module = reload(module)\n\n for name, attr in module.__dict__.items():\n if not isinstance(attr, type): continue\n if not issubclass(attr, Provider.Provider): continue\n if not getattr(attr, \"textkey\", None): continue\n \n textkey = attr.textkey.replace(\".\", \"_\")\n setattr(current_module, textkey, attr) \n except:\n raise\n #logging.exception(\"Error importing plugin %s\" % name)\n continue\n\n_load_providers()","sub_path":"MainComponents/notifyengine2/plugins/providers/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":1257,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"253698079","text":"import vk_api\nfrom vk_api import VkUpload\nfrom vk_api.longpoll import VkLongPoll, VkEventType\nfrom vk_api.utils import get_random_id\nimport requests\nimport parsingLib\nimport re\nimport urllib.parse\n\n\ndef prices_soup(soup):\n price_page = soup.find(\"div\", {'class': 'cia-cs'})\n price_page = price_page.find('a').get('href')\n price_page = 'https://market.yandex.ru' + price_page\n print(price_page)\n price_soup = parsingLib.makeSoup(price_page)\n return price_soup\n\n\ndef get_price(soup):\n price_soup = prices_soup(soup)\n prices = parsingLib.allDIV(price_soup, \"price\")\n return prices\n\n\ndef get_shop(soup):\n shop_soup = prices_soup(soup)\n shops = shop_soup.findAll(\"a\", {'class': 'n-shop-logo'})\n return shops\n\n\ndef cmd_img(soup, imgs, event, vk_session):\n vk = vk_session.get_api()\n attachments = []\n main_img = soup.find(\"div\", {'class': 'img200'})\n main_img_src = \"https://www.e-katalog.ru\" + re.search(r'/jpg_zoom1/([0-9])+', str(main_img)).group(0) + \".jpg\"\n upload = VkUpload(vk_session)\n main_image = requests.get(main_img_src, stream=True)\n main_photo = upload.photo_messages(photos=main_image.raw)[0]\n attachments.append('photo{}_{}'.format(main_photo['owner_id'], main_photo['id']))\n print(main_img_src)\n for img in imgs:\n img_source = re.search(r'https://mzimg.com/big(?:[a-zA-Z]|[0-9]|[/.-_])+', str(img)).group(0)\n image = requests.get(img_source, stream=True)\n photo = upload.photo_messages(photos=image.raw)[0]\n attachments.append('photo{}_{}'.format(photo['owner_id'], photo['id']))\n vk.messages.send(\n user_id=event.user_id,\n attachment=','.join(attachments),\n message='Фото товара',\n random_id=get_random_id())\n\n\ndef cmd_price(soup, event, vk_session):\n vk = vk_session.get_api()\n vk.messages.send(user_id=event.user_id,\n message='Получаю цены',\n random_id=get_random_id())\n my_prices = get_price(soup)\n my_prices1 = []\n my_shops = get_shop(soup)\n print(my_shops)\n for my_shop in my_shops:\n print(my_shop.find('img').get('alt'))\n i = 1\n for my_price in my_prices:\n my_prices1.append('\\n' + my_price.text)\n # for my_shop in my_shops:\n # my_prices1.insert(i, my_shop.find('img').get('alt'))\n # i += 2\n\n vk.messages.send(user_id=event.user_id,\n message=my_prices1,\n random_id=get_random_id())\n\n\ndef cmd_search_get_url(event, vk_session):\n vk = vk_session.get_api()\n message_list = event.text.split()\n del message_list[0]\n word_string = \"\"\n for word in message_list:\n word_encoded = urllib.parse.quote_plus(word)\n word_string = word_string + \"+\" + word_encoded # сохраняет плюс перед первым словом\n search_url = \"https://www.e-katalog.ru/ek-list.php?search_=\" + word_string\n vk.messages.send(user_id=event.user_id,\n message=search_url,\n random_id=get_random_id())\n return search_url\n","sub_path":"cmds.py","file_name":"cmds.py","file_ext":"py","file_size_in_byte":3086,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"160919003","text":"def solution(s):\n n = len(s)\n answer = 1000\n\n for i in range(1, n + 1):\n l = []\n for j in range(0, n, i):\n temp = s[j:j + i]\n if l and l[-1][0] == temp:\n l[-1][1] += 1\n else:\n l.append([temp, 1])\n\n temp = ''\n\n for sub, num in l:\n if num > 1:\n temp += f'{num}{sub}'\n else:\n temp += sub\n\n answer = min(answer, len(temp))\n return answer\n\n\ndef compress(text, tok_len):\n words = [text[i:i + tok_len] for i in range(0, len(text), tok_len)]\n res = []\n cur_word = words[0]\n cur_cnt = 1\n for a, b in zip(words, words[1:] + ['']):\n if a == b:\n cur_cnt += 1\n else:\n res.append([cur_word, cur_cnt])\n cur_word = b\n cur_cnt = 1\n return sum(len(word) + (len(str(cnt)) if cnt > 1 else 0) for word, cnt in res)\n\n\ndef solution2(text):\n return min(compress(text, tok_len) for tok_len in list(range(1, int(len(text) / 2) + 1)) + [len(text)])\n\n\nsolution2('aabbaccc')\nsolution('ababcdcdababcdcd')\nsolution('abcabcdede')\nsolution('abcabcabcabcdededededede')\nsolution('xababcdcdababcdcd')\n","sub_path":"programmers/lv2/문자열압축.py","file_name":"문자열압축.py","file_ext":"py","file_size_in_byte":1206,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"207074963","text":"from flask import Flask, url_for, render_template, g, request, redirect\nimport os\nimport sqlite3\n\n\napp = Flask(__name__)\nDATABASE = \"vapour.db\"\n\ndef get_db():\n\tdb = getattr(g, '_database', None)\n\tif db is None:\n\t\tdb = g._database = sqlite3.connect(DATABASE)\n\t\tdb.row_factory = sqlite3.Row\n\treturn db\n\ndef query_db(query, args=(), one=False):\n\tcur = get_db().execute(query, args)\n\trv = cur.fetchall()\n\tcur.close()\n\treturn (rv[0] if rv else None) if one else rv\n\ndef change_db(query,args=()):\n\tcur = get_db().execute(query, args)\n\tget_db().commit()\n\tcur.close()\n\n@app.teardown_appcontext\ndef close_connection(exception):\n\tdb = getattr(g, '_database', None)\n\tif db is not None:\n\t\tdb.close()\n\n\n# FOR GAME TABLE\n@app.route(\"/\")\ndef index_game():\n\tgame_list = query_db(\"SELECT * FROM GAME\")\n\treturn render_template(\"index_game.html\", game_list=game_list)\n\n@app.route('/create_game', methods=['GET', 'POST'])\ndef create_game():\n\tif request.method == \"GET\":\n\t\treturn render_template(\"create.html\",GAME=None)\n\tif request.method == \"POST\":\n\t\tGAME = request.form.to_dict()\n\t\tvalues = [GAME[\"GAME_ID\"], GAME[\"GAME_NAME\"], GAME[\"PUBLISHER\"], GAME[\"SIZE\"], GAME[\"PRICE\"]]\n\t\tchange_db(\"INSERT INTO GAME (GAME_ID, GAME_NAME, PUBLISHER, SIZE, PRICE) VALUES (?, ?, ?, ?, ?)\", values)\n\t\treturn redirect(url_for(\"index\"))\n\n@app.route('/update/', methods=['GET', 'POST'])\ndef update(GAME_ID):\n\tif request.method == \"GET\":\n\t\tGAME = query_db(\"SELECT * FROM GAME WHERE GAME_ID=?\", [GAME_ID], one=True)\n\t\treturn render_template(\"update.html\", GAME=GAME)\n\tif request.method == \"POST\":\n\t\tGAME = request.form.to_dict()\n\t\tvalues = [GAME[\"GAME_ID\"], GAME[\"GAME_NAME\"], GAME[\"PUBLISHER\"], GAME[\"SIZE\"], GAME[\"PRICE\"], GAME_ID]\n\t\tchange_db(\"UPDATE GAME SET GAME_ID=?, GAME_NAME=?, PUBLISHER=?, SIZE=?, PRICE=? WHERE GAME_ID=?\", values)\n\t\treturn redirect(url_for(\"index\"))\n\n@app.route('/delete/', methods=['GET', 'POST'])\ndef delete(GAME_ID):\n\tif request.method == \"GET\":\n\t\tGAME = query_db(\"SELECT * FROM GAME WHERE GAME_ID=?\", [GAME_ID], one=True)\n\t\treturn render_template(\"delete.html\", GAME=GAME)\n\tif request.method == \"POST\":\n\t\tchange_db(\"DELETE FROM GAME where GAME_ID=?\", [GAME_ID])\n\t\treturn redirect(url_for(\"index\"))\n\n#FOR PUBLISHER TABLE\n\n@app.route(\"/PUBLISHER\")\ndef indexpub():\n\tpub_list = query_db(\"SELECT * FROM PUBLISHER\")\n\treturn render_template(\"indexpub.html\", pub_list=pub_list)\n\n@app.route('/createpub', methods=['GET', 'POST'])\ndef createpub():\n\tif request.method == \"GET\":\n\t\treturn render_template(\"createpub.html\",PUBLISHER=None)\n\tif request.method == \"POST\":\n\t\tPUBLISHER = request.form.to_dict()\n\t\tvalues = [PUBLISHER[\"PUB_ID\"], PUBLISHER[\"PUB_NAME\"], PUBLISHER[\"ADDRESS\"], PUBLISHER[\"PHONE_NO\"], PUBLISHER[\"COMMISSION\"]]\n\t\tchange_db(\"INSERT INTO PUBLISHER (PUB_ID, PUB_NAME, ADDRESS, PHONE_NO, COMMISSION) VALUES (?, ?, ?, ?, ?)\", values)\n\t\treturn redirect(url_for(\"indexpub\"))\n\n@app.route('/updatepub/', methods=['GET', 'POST'])\ndef updatepub(PUB_ID):\n\tif request.method == \"GET\":\n\t\tPUBLISHER = query_db(\"SELECT * FROM PUBLISHER WHERE PUB_ID=?\", [PUB_ID], one=True)\n\t\treturn render_template(\"updatepub.html\", PUBLISHER=PUBLISHER)\n\tif request.method == \"POST\":\n\t\tPUBLISHER = request.form.to_dict()\n\t\tvalues = [PUBLISHER[\"PUB_ID\"], PUBLISHER[\"PUB_NAME\"], PUBLISHER[\"ADDRESS\"], PUBLISHER[\"PHONE_NO\"], PUBLISHER[\"COMMISSION\"], PUB_ID]\n\t\tchange_db(\"UPDATE PUBLISHER SET PUB_ID=?, PUB_NAME=?, ADDRESS=?, PHONE_NO=?, COMMISSION=? WHERE PUB_ID=?\", values)\n\t\treturn redirect(url_for(\"indexpub\"))\n\n@app.route('/deletepub/', methods=['GET', 'POST'])\ndef deletepub(PUB_ID):\n\tif request.method == \"GET\":\n\t\tPUBLISHER = query_db(\"SELECT * FROM PUBLISHER WHERE PUB_ID=?\", [PUB_ID], one=True)\n\t\treturn render_template(\"deletepub.html\", PUBLISHER=PUBLISHER)\n\tif request.method == \"POST\":\n\t\tchange_db(\"DELETE FROM PUBLISHER where PUB_ID=?\", [PUB_ID])\n\t\treturn redirect(url_for(\"indexpub\"))\n\n\n#FOR USER TABLE\n@app.route(\"/USER\")\ndef index_user():\n\tuser_list = query_db(\"SELECT * FROM USER\")\n\treturn render_template(\"index_user.html\", user_list=user_list)\n\n@app.route('/create_user', methods=['GET', 'POST'])\ndef create_user():\n\tif request.method == \"GET\":\n\t\treturn render_template(\"create_user.html\",USER=None)\n\tif request.method == \"POST\":\n\t\tUSER = request.form.to_dict()\n\t\tvalues = [USER[\"USER_ID\"], USER[\"USER_NAME\"], USER[\"AGE\"]]\n\t\tchange_db(\"INSERT INTO USER (USER_ID, USER_NAME, AGE) VALUES (?, ?, ?)\", values)\n\t\treturn redirect(url_for(\"index_user\"))\n\n# TODO: update not updating in the form\n@app.route('/update_user/', methods=['GET', 'POST'])\ndef update_user(USER_ID):\n\tif request.method == \"GET\":\n\t\tUSER = query_db(\"SELECT * FROM USER WHERE USER_ID=?\", [USER_ID], one=True)\n\t\treturn render_template(\"update_user.html\", USER=USER_ID)\n\tif request.method == \"POST\":\n\t\tUSER = request.form.to_dict()\n\t\tvalues = [USER[\"USER_ID\"], USER[\"USER_NAME\"], USER[\"AGE\"], USER_ID]\n\t\tchange_db(\"UPDATE USER SET USER_ID=?, USER_NAME=?, AGE=? WHERE USER_ID=?\", values)\n\t\treturn redirect(url_for(\"index_user\"))\n\n@app.route('/delete_user/', methods=['GET', 'POST'])\ndef delete_user(USER_ID):\n\tif request.method == \"GET\":\n\t\tUSER = query_db(\"SELECT * FROM USER WHERE USER_ID=?\", [USER_ID], one=True)\n\t\treturn render_template(\"delete_user.html\", USER=USER)\n\tif request.method == \"POST\":\n\t\tchange_db(\"DELETE FROM USER where USER_ID=?\", [USER_ID])\n\t\treturn redirect(url_for(\"index_user\"))\n\n\n#for PAYMENT TABLE\n@app.route(\"/PAYMENT\")\ndef index_pay():\n\tpay_list = query_db(\"SELECT * FROM PAYMENT\")\n\treturn render_template(\"index_pay.html\", pay_list=pay_list)\n\n@app.route('/create_pay', methods=['GET', 'POST'])\ndef create_pay():\n\tif request.method == \"GET\":\n\t\treturn render_template(\"create_pay.html\",PAYMENT=None)\n\tif request.method == \"POST\":\n\t\tPAYMENT = request.form.to_dict()\n\t\tvalues = [PAYMENT[\"PAY_ID\"], PAYMENT[\"GAME_NAME\"], GAME[\"PUBLISHER\"], GAME[\"SIZE\"], GAME[\"PRICE\"]]\n\t\tchange_db(\"INSERT INTO GAME (GAME_ID, GAME_NAME, PUBLISHER, SIZE, PRICE) VALUES (?, ?, ?, ?, ?)\", values)\n\t\treturn redirect(url_for(\"index\"))\n\n@app.route('/update/', methods=['GET', 'POST'])\ndef update(GAME_ID):\n\tif request.method == \"GET\":\n\t\tGAME = query_db(\"SELECT * FROM GAME WHERE GAME_ID=?\", [GAME_ID], one=True)\n\t\treturn render_template(\"update.html\", GAME=GAME)\n\tif request.method == \"POST\":\n\t\tGAME = request.form.to_dict()\n\t\tvalues = [GAME[\"GAME_ID\"], GAME[\"GAME_NAME\"], GAME[\"PUBLISHER\"], GAME[\"SIZE\"], GAME[\"PRICE\"], GAME_ID]\n\t\tchange_db(\"UPDATE GAME SET GAME_ID=?, GAME_NAME=?, PUBLISHER=?, SIZE=?, PRICE=? WHERE GAME_ID=?\", values)\n\t\treturn redirect(url_for(\"index\"))\n\n@app.route('/delete/', methods=['GET', 'POST'])\ndef delete(GAME_ID):\n\tif request.method == \"GET\":\n\t\tGAME = query_db(\"SELECT * FROM GAME WHERE GAME_ID=?\", [GAME_ID], one=True)\n\t\treturn render_template(\"delete.html\", GAME=GAME)\n\tif request.method == \"POST\":\n\t\tchange_db(\"DELETE FROM GAME where GAME_ID=?\", [GAME_ID])\n\t\treturn redirect(url_for(\"index\"))\n\n\nif __name__ == '__main__':\n\tapp.run(host=\"0.0.0.0\",port=5010, debug=True)\n","sub_path":"vapour.py","file_name":"vapour.py","file_ext":"py","file_size_in_byte":7047,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"235485962","text":"\nimport collections\nfrom spira.param.field.typed_list import TypedList\n\n\nclass ElementFilterMixin(object):\n\n def add_elem_to_cell(self, elem, cellname):\n for sref in self.sref:\n if sref.ref.name == cellname:\n self += elem\n\n def get_polygons(self, layer=None, datatype=None):\n elems = ElementList()\n for ply in self.polygons:\n if layer is not None:\n if ply.gdslayer == layer:\n elems += ply\n if datatype is not None:\n if ply.gdslyaer.datatype == datatype:\n elems += ply\n return elems\n\n @property\n def polygons(self):\n from spira.gdsii.elemental.polygons import PolygonAbstract\n elems = ElementList()\n for e in self._list:\n if issubclass(type(e), PolygonAbstract):\n elems += e\n return elems\n\n @property\n def metals(self):\n from spira.rdd import get_rule_deck\n from spira.gdsii.elemental.polygons import PolygonAbstract\n RDD = get_rule_deck()\n elems = ElementList()\n for p in self.polygons:\n if p.gdslayer.number in RDD.METALS.layers:\n elems += p\n return elems\n\n @property\n def mlayers(self):\n from spira.lpe.primitives import MLayer\n elems = ElementList()\n for S in self._list:\n for Sm in S.ref.elementals.sref:\n if isinstance(Sm.ref, MLayer):\n elems += Sm\n return elems\n\n @property\n def dlayers(self):\n from spira.lpe.primitives import NLayer\n elems = ElementList()\n for S in self._list:\n for Sn in S.ref.elementals.sref:\n if isinstance(Sn.ref, NLayer):\n elems += Sn\n return elems\n\n def get_dlayer(self, layer):\n elems = ElementList()\n for S in self.dlayers:\n for p in S.ref.elementals.polygons:\n if isinstance(layer, int):\n if p.gdslayer.number == layer:\n elems += S\n else:\n if p.gdslayer == layer:\n elems += S\n return elems\n\n def get_mlayer(self, layer):\n elems = ElementList()\n for S in self.mlayers:\n for p in S.ref.elementals.polygons:\n if isinstance(layer, int):\n if p.gdslayer.number == layer:\n elems += S\n else:\n if p.gdslayer.number == layer.number:\n elems += S\n return elems\n\n @property\n def labels(self):\n from spira.gdsii.elemental.label import Label\n elems = ElementList()\n for e in self._list:\n if isinstance(e, Label):\n elems += e\n return elems\n\n @property\n def sref(self):\n from spira.gdsii.elemental.sref import SRef\n elems = ElementList()\n for e in self._list:\n if isinstance(e, SRef):\n elems += e\n return elems\n\n @property\n def mesh(self):\n from spira.lne.mesh import Mesh\n for g in self._list:\n if isinstance(g, Mesh):\n return g\n raise ValueError('No graph was generate for Cell')\n\n @property\n def graph(self):\n from spira.lne.mesh import MeshAbstract\n for e in self._list:\n if issubclass(type(e), MeshAbstract):\n return e.g\n return None\n\n @property\n def subgraphs(self):\n subgraphs = {}\n for e in self.sref:\n cell = e.ref\n if cell.graph is not None:\n subgraphs[cell.name] = cell.graph\n return subgraphs\n\n\nclass __ElementList__(TypedList, ElementFilterMixin):\n\n def __repr__(self):\n string = '\\n'.join('{}'.format(k) for k in enumerate(self._list))\n return string\n\n def __str__(self):\n return self.__repr__()\n\n def __getitem__(self, i):\n if isinstance(i, str):\n for cell_ref in self.sref:\n name = cell_ref.ref.name\n rest = name.split('-', 1)[0]\n if i == rest: return cell_ref\n elif isinstance(i, tuple):\n elems = ElementList()\n for e in self.polygons:\n if e.gdslayer.key == i:\n elems += e\n return elems\n else:\n return self._list[i]\n\n def __delitem__(self, key):\n for i in range(0, len(self._list)):\n if self._list[i] is key:\n return list.__delitem__(self._list, i)\n\n def __deepcopy__(self, memo):\n from copy import deepcopy\n L = self.__class__()\n for item in self._list:\n L.append(deepcopy(item))\n return L\n\n def __contains__(self, name):\n import spira\n for item in self._list:\n if isinstance(item, spira.Cell):\n if item.name == name:\n return True\n return False\n\n\nclass ElementList(__ElementList__):\n \"\"\"\n\n \"\"\"\n\n def dependencies(self):\n import spira\n from spira.gdsii.lists.cell_list import CellList\n\n cells = CellList()\n for e in self._list:\n cells.add(e.dependencies())\n return cells\n\n def add(self, item):\n import spira\n from spira.gdsii.lists.cell_list import CellList\n\n cells = CellList()\n for e in self._list:\n cells.add(e.dependencies())\n return cells\n\n def stretch(self, stretch_class):\n for c in self:\n c.stretch(stretch_class)\n return self\n\n def transform(self, transform):\n for c in self:\n c.transform(transform)\n return self\n\n def flat_elems(self):\n def _flatten(list_to_flatten):\n for elem in list_to_flatten:\n if isinstance(elem, (ElementList, list, tuple)):\n for x in _flatten(elem):\n yield x\n else:\n yield elem\n\n return _flatten(self._list)\n\n def flat_copy(self, level=-1, commit_to_gdspy=False):\n el = ElementList()\n for e in self._list:\n el += e.flat_copy(level, commit_to_gdspy)\n if level == -1:\n return el.flatten()\n else:\n return el\n\n def flatten(self):\n from spira.gdsii.cell import Cell\n from spira.gdsii.elemental.polygons import PolygonAbstract\n from spira.gdsii.elemental.sref import SRef\n if isinstance(self, collections.Iterable):\n flat_list = ElementList()\n for i in self._list:\n if issubclass(type(i), Cell):\n i = i.flat_copy()\n elif isinstance(i, SRef):\n i = i.flat_copy()\n for a in i.flatten():\n flat_list += a\n return flat_list\n else:\n return [self._list]\n\n def generate_cell(self, name):\n from spira.gdsii.elemental.sref import SRef\n from spira.gdsii.cell import Cell\n cc = Cell(name=name)\n for e in self._list: cc += e\n return SRef(cc)\n\n def isstored(self, pp):\n for e in self._list:\n return pp == e\n\n\n\n\n","sub_path":"spira/core/lists.py","file_name":"lists.py","file_ext":"py","file_size_in_byte":7306,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"363604957","text":"from odoo import api, fields, models,exceptions\nclass SaleOrder(models.Model):\n _inherit = \"sale.order\"\n\n cancel_done_picking = fields.Boolean(string='Cancel Done Delivery?', compute='check_cancel_done_picking')\n\n @api.model\n def check_cancel_done_picking(self):\n for order in self:\n Flag = False\n if order.company_id.cancel_done_picking and order.delivery_count > 0:\n for picking in self.picking_ids:\n if picking.state != 'cancel':\n Flag = True\n break\n order.cancel_done_picking = Flag\n \n\n @api.multi\n def cancel_picking(self):\n if len(self.picking_ids) == 1 :\n self.picking_ids.with_context({'Flag':True}).action_cancel()\n return self.action_view_picking()\n else:\n return self.action_cancel_selected_picking()\n \n @api.multi\n def action_view_picking(self):\n action = self.env.ref('stock.action_picking_tree_all').read()[0]\n picking_records = self.mapped('picking_ids')\n if picking_records:\n action['views'] = [(self.env.ref('stock.view_picking_form').id, 'form')]\n action['res_id'] = picking_records.id\n return action\n\n @api.multi\n def action_cancel_selected_picking(self):\n action = self.env.ref('stock_picking_cancel_cs.action_cancel_delivery_cft').read()[0]\n picking_obj=self.env['stock.picking']\n pickings=[]\n for picking in self.picking_ids:\n if picking.state !='cancel':\n pickings.append(picking.id)\n\n action['context'] ={ 'pickings':pickings }\n return action\n {\n 'type': 'ir.actions.act_window',\n 'res_model': 'cancel.picking.wizard',\n 'view_mode':'form',\n 'views': [(self.env.ref('stock_picking_cancel_cs.delivery_cancel_form_cft').id, 'form')],\n 'target': 'new',\n 'context': {\n 'pickings':pickings,\n },\n }\n","sub_path":"stock_picking_cancel_cs/models/sale_order.py","file_name":"sale_order.py","file_ext":"py","file_size_in_byte":2063,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"94638490","text":"import numpy as np\nfrom random import shuffle\n\ndef softmax_loss_naive(W, X, y, reg):\n \"\"\"\n Softmax loss function, naive implementation (with loops)\n\n Inputs have dimension D, there are C classes, and we operate on minibatches\n of N examples.\n\n Inputs:\n - W: A numpy array of shape (D, C) containing weights.\n - X: A numpy array of shape (N, D) containing a minibatch of data.\n - y: A numpy array of shape (N,) containing training labels; y[i] = c means\n that X[i] has label c, where 0 <= c < C.\n - reg: (float) regularization strength\n\n Returns a tuple of:\n - loss as single float\n - gradient with respect to weights W; an array of same shape as W\n \"\"\"\n # Initialize the loss and gradient to zero.\n\n\n loss = 0.0\n dW = np.zeros_like(W)\n for i in xrange(X.shape[0]):\n preLoss = X[i,:].dot(W)\n postLoss = np.zeros(preLoss.shape)\n max = -np.max(preLoss)\n expAns = np.exp(preLoss[y[i]]+max)\n expSum = np.sum(np.exp(preLoss + max))\n for score in xrange(len(preLoss)):\n expScore = np.exp(preLoss[score]+max)\n postLoss[score] = expScore/expSum\n if score != y[i]:\n dW[:,score] += expScore/expSum * X[i,:]\n else:\n dW[:,score] += -(expSum-expAns)/expSum * X[i,:]\n loss += -np.log(postLoss[y[i]])\n loss /= X.shape[0]\n dW /= X.shape[0]\n loss += 0.5*reg * np.sum(W*W)\n dW += reg * W\n\n return loss, dW\n\n\ndef softmax_loss_vectorized(W, X, y, reg):\n \"\"\"\n Softmax loss function, vectorized version.\n\n Inputs and outputs are the same as softmax_loss_naive.\n \"\"\"\n # Initialize the loss and gradient to zero.\n loss = 0.0\n dW = np.zeros_like(W)\n num_train = X.shape[0]\n preLoss = X.dot(W)\n preLoss -= np.max(preLoss,axis=1)[:,np.newaxis]\n preLoss = np.exp(preLoss)\n expSum = np.sum(preLoss,axis=1)\n preLoss = preLoss/expSum[:,np.newaxis]\n loss = np.sum(-np.log(preLoss[np.arange(len(y)),y]))\n preLoss[np.arange(len(y)),y] -= 1\n dW = X.T.dot(preLoss)\n\n\n\n loss /= num_train\n dW /= num_train\n loss += 0.5 * reg * np.sum(W * W)\n dW += reg * W\n\n return loss, dW\n\n","sub_path":"assignment1/softmax.py","file_name":"softmax.py","file_ext":"py","file_size_in_byte":2079,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"348464580","text":"import pandas as pd\nimport numpy as np\n\ndf = pd.read_csv('./master_elections.csv')\npd.set_option('display.expand_frame_repr', False)\n#df.groupby('filename').size().reset_index(name='num_of_ballots')\ncols = df.columns.difference(['Unnamed: 0','num_of_ballots', 'num_of_candidates','filename'])\ndf['num_of_ballots'] = df.groupby(['filename'])['candidate_1'].transform('count')\ndf['num_of_candidates'] = df[list(['candidate_1','candidate_2','candidate_3','candidate_4','candidate_5','candidate_6'])].count(axis=1)\ndf = df.replace(np.nan, 'yan', regex=True)\ndf = df.loc[1:].astype(str).replace('0',np.nan)\ndf['zeros'] = df.isnull().sum(axis = 1)\ndf['total_num_of_zeros'] = df.groupby(['filename'])['zeros'].transform(sum)\ndf['num_of_ballots'] = df['num_of_ballots'].astype(str).astype(int)\ndf['percentage_of_noise'] =df['total_num_of_zeros']/df['num_of_ballots']\ndf.drop(['zeros','total_num_of_zeros'],axis =1,inplace = True)\ndf.to_csv('feature_engineering_Moeid.csv')\n","sub_path":"feature_engineering.py","file_name":"feature_engineering.py","file_ext":"py","file_size_in_byte":965,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"422797975","text":"import random\n\n# Constants\nNORTH = 'n'\nEAST = 'e'\nSOUTH = 's'\nWEST = 'w'\nDIRECTIONS: list = [NORTH, EAST, SOUTH, WEST]\nLEAVER_CHOICES: list = [\"y\", \"n\"]\n\ndef move(direction, col, row):\n ''' Returns updated col, row given the direction '''\n if direction == NORTH:\n row += 1\n elif direction == SOUTH:\n row -= 1\n elif direction == EAST:\n col += 1\n elif direction == WEST:\n col -= 1\n return(col, row) \n\ndef is_victory(col, row):\n ''' Return true is player is in the victory cell '''\n return col == 3 and row == 1 # (3,1)\n\ndef print_directions(directions_str):\n print(\"You can travel: \", end='')\n first = True\n for ch in directions_str:\n if not first:\n print(\" or \", end='')\n if ch == NORTH:\n print(\"(N)orth\", end='')\n elif ch == EAST:\n print(\"(E)ast\", end='')\n elif ch == SOUTH:\n print(\"(S)outh\", end='')\n elif ch == WEST:\n print(\"(W)est\", end='')\n first = False\n print(\".\")\n \ndef find_directions(col, row):\n ''' Returns valid directions as a string given the supplied location '''\n if col == 1 and row == 1: # (1,1)\n valid_directions = NORTH\n elif col == 1 and row == 2: # (1,2)\n valid_directions = NORTH+EAST+SOUTH\n elif col == 1 and row == 3: # (1,3)\n valid_directions = EAST+SOUTH\n elif col == 2 and row == 1: # (2,1)\n valid_directions = NORTH\n elif col == 2 and row == 2: # (2,2)\n valid_directions = SOUTH+WEST\n elif col == 2 and row == 3: # (2,3)\n valid_directions = EAST+WEST\n elif col == 3 and row == 2: # (3,2)\n valid_directions = NORTH+SOUTH\n elif col == 3 and row == 3: # (3,3)\n valid_directions = SOUTH+WEST\n return valid_directions\n\ndef play_one_move(col, row, valid_directions, moves):\n ''' Plays one move of the game\n Return if victory has been obtained and updated col,row '''\n victory = False\n has_moved = False\n\n while not has_moved:\n direction = random.choice(DIRECTIONS)\n print(f\"Direction: {direction}\")\n direction = direction.lower()\n \n if not direction in valid_directions:\n print(\"Not a valid direction!\")\n print_directions(valid_directions)\n else:\n col, row = move(direction, col, row)\n victory = is_victory(col, row)\n has_moved = True\n moves += 1\n return victory, col, row, moves\n\n\ndef check_for_special_tiles(row, col, coins):\n \"\"\" Takes the row, col and coins as parameters. If the player is on one of the right \n tiles ((1,2), (2,2), (2,3) and (3,2)) the player is prompted with the choice to pull a leaver \n and if he/she pulls it he/she gets one coin \"\"\"\n special_tiles = [(1,2), (2,2), (2,3), (3,2)]\n position = (col, row)\n if position in special_tiles:\n is_leaver_pulled = random.choice(LEAVER_CHOICES)\n print(f\"Pull a lever (y/n): {is_leaver_pulled}\")\n if is_leaver_pulled.lower() == \"y\":\n coins += 1\n print(f\"You received 1 coin, your total is now {coins}.\")\n return coins\n\n\ndef play_again():\n \"\"\" Ask the user if he/she wants to play the game again and returns True if he/she wants to play again \"\"\"\n user_awnser = input(\"Play again (y/n): \")\n if user_awnser.lower() == \"y\":\n return True\n else:\n return False\n\n\ndef get_seed():\n \"\"\" Asks the user to give number (int) for random.seed \"\"\"\n seed = int(input(\"Input seed: \"))\n random.seed(seed)\n\n\n# The main program starts here\nis_playing = True\nwhile is_playing:\n victory = False\n row = 1\n col = 1\n coins = 0\n moves = 0\n\n get_seed()\n valid_directions = NORTH\n print_directions(valid_directions)\n\n while not victory:\n victory, col, row, moves = play_one_move(col, row, valid_directions, moves)\n if victory:\n print(f\"Victory! Total coins {coins}. Moves {moves}.\")\n else:\n coins = check_for_special_tiles(row, col, coins)\n valid_directions = find_directions(col, row)\n print_directions(valid_directions)\n is_playing = play_again()","sub_path":"Tímaverkefni/Assignment 13/tile_traveller2.py","file_name":"tile_traveller2.py","file_ext":"py","file_size_in_byte":4193,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"434580098","text":"\"\"\"\nThis file contains wrappers and helper functions for the technical notebook\n\"\"\"\nimport pandas as pd\nimport numpy as np\nfrom sklearn.linear_model import ElasticNet\nimport seaborn as sns\nimport matplotlib.pyplot as plt\nimport plotly.figure_factory as ff\nimport data_clean as dc\n\n\ndef import_and_clean():\n \"\"\"This function puts together a few of the cleaning functions from data_clean.py\"\"\"\n # data_import.py performs our test-train split and writes four csvs, which we read in here\n X_train_temp = pd.read_csv('./data/dirty_X_train.csv', index_col=0)\n y_train_temp = pd.read_csv('./data/dirty_y_train.csv', index_col=0)\n X_test_temp = pd.read_csv('./data/dirty_X_test.csv', index_col=0)\n y_test_temp = pd.read_csv('./data/dirty_y_test.csv', index_col=0)\n\n # These perfrom basic data cleaning\n X_train, y_train = dc.data_clean(X_train_temp, y_train_temp)\n X_test, y_test = dc.data_clean(X_test_temp, y_test_temp)\n\n # these create full sets of test and train data with FIPS county codes for plots\n X_train, X_test, full_data = dc.create_fips_df(X_train, X_test)\n y_train, y_test, full_target = dc.create_fips_df(y_train, y_test)\n\n return X_train, X_test, y_train, y_test, full_data, full_target\n\n\ndef model_selection_results(search):\n \"\"\" This is a wrapper function that turns the results of the crossvalidation into a nice\n dataframe with only relevant info \"\"\"\n cross_val = pd.DataFrame(search.cv_results_)\n cross_val2 = cross_val.sort_values('rank_test_score')\n\n nice_table = cross_val2[['rank_test_score', 'param_elastic__alpha',\n 'param_elastic__l1_ratio', 'mean_test_score', 'mean_train_score']]\n return nice_table.head()\n\n\ndef run_model(X_train, y_train, l1_ratio=.5, alpha=.5, save=None):\n \"\"\"This function takes in the optimal parameters we discovered from crossvalidation, fits a\n elastic net with those parameters to our model, and then displays a barplot of the regression\n coefficients. save is given any truthy value then also save a png of the figure\"\"\"\n reg = ElasticNet(alpha=alpha, l1_ratio=l1_ratio, max_iter=50000)\n reg.fit(X_train, y_train)\n coeffs = reg.coef_.tolist()\n coeffs_columns = X_train.columns\n coefficients = list(zip(coeffs, coeffs_columns))\n coefficients.sort()\n\n plt.figure(figsize=(15, 10))\n plt.xticks(rotation=60)\n plt.title('Effect of Features on Average Life Expectancy')\n plt.ylabel('Expected Change in ALE by Feature ')\n df2 = pd.DataFrame([coeffs_columns, coeffs])\n df_sorted = df2.T\n df_sorted = df_sorted.sort_values(1)\n sns.barplot(list(df_sorted[0]), list(df_sorted[1]), color='#0485d1')\n plt.gca().invert_yaxis()\n if save:\n plt.savefig('Regression_Results.png')\n\n return df_sorted\n\n\ndef test_model(X_test, y_test, l1_ratio=.5, alpha=.5, X_train=None, y_train=None):\n \"\"\"This Trains a model on the training data with the specified parameters and then returns\n the score for that model with the test data\"\"\"\n reg = ElasticNet(alpha=alpha, l1_ratio=l1_ratio, max_iter=50000)\n reg.fit(X_train, y_train)\n print(reg.score(X_test, y_test))\n\n return reg\n\n\ndef choropleth(full_data, column, title, reverse=None, save=None):\n \"\"\"This function takes in a data frame and a target column and makes a choropleth. We assume\n that the data frame has a FIPS column if r is any truthy value the color scheme is reveresed,\n and if save is a truthy value then the figure is saved as a png\"\"\"\n mind = full_data[column].min()\n maxd = full_data[column].max()\n\n fips = list(full_data.FIPS)\n values = list(full_data[column])\n\n bins = list(np.linspace(mind, maxd, 21))\n scale = [\"#E50059\", \"#DA025D\", \"#D00462\", \"#C50766\", \"#BB096B\", \"#B00B70\", \"#A60E74\",\n \"#9C1079\", \"#91127E\", \"#871582\", \"#7C1787\", \"#721A8C\", \"#681C90\", \"#5D1E95\",\n \"#532199\", \"#48239E\", \"#3E25A3\", \"#3428A7\", \"#292AAC\", \"#1F2CB1\", \"#142FB5\",\n \"#0A31BA\", \"#0034BF\"]\n if reverse:\n scale.reverse()\n\n fig = ff.create_choropleth(\n fips=fips, values=values, binning_endpoints=bins, legend_title=title, colorscale=scale)\n fig.layout.template = None\n\n if save:\n fig.write_image(f'{column}_counties.png')\n\n fig.write_image(\"County_LBW.png\")\n fig.show()\n","sub_path":".ipynb_checkpoints/TechBookFunctions-checkpoint.py","file_name":"TechBookFunctions-checkpoint.py","file_ext":"py","file_size_in_byte":4308,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"228868934","text":"import numpy as np\nimport cv2\nfrom matplotlib import pyplot as plt\n\ncap = cv2.VideoCapture(0)\ncap.set(3,800) # resolution\ncap.set(4,600)\npicsample = cv2.imread(\"Crop.png\")\nakaze = cv2.AKAZE_create()\nbf = cv2.BFMatcher()\n\n\nprint(\"Q - Quit\\nS - Save Image\\nP - Plot RGB Histogram\")\n\ndef pltRGBHistogram(img):\n color = ('b','g','r')\n for i,col in enumerate(color):\n histr = cv2.calcHist([img],[i],None,[256],[0,256])\n histr = histr[5:250]\n plt.plot(histr,color = col)\n plt.xlim([0,256])\n plt.show()\ndef maskImg(img,x,y,width,height): # the masked region turns black\n mask = np.zeros(img.shape[:2], np.uint8)\n mask[y:(y+height), x:(x+width)] = 255\n masked_img = cv2.bitwise_and(img,img,mask = mask)\n return masked_img\n\ndef cropBlack(img):\n crop = img[y:y+h,x:x+w]\n cv2.imshow('pocessed',crop)\n cv2.drawContours(img, contours, -1, (0,255,0), 3)\n cv2.imwrite('Cropped_img.png',crop)\n return crop\ndef drawRec(img,x,y,width,height):\n cv2.rectangle(img,(x,y),(x+width,y+height),(0,0,255),2)\n return img\ndef histNormalize(img):\n hist,bins = np.histogram(img.flatten(),256,[0,256])\n cdf = hist.cumsum()\n cdf_normalized = cdf * hist.max()/ cdf.max()\n return cdf_normalized\ndef histCompare(img1,img2):\n index = np.arange(3)\n result = []\n for i in index:\n h1 = cv2.calcHist([img1],[i],None,[256],[10,246])\n h2 = cv2.calcHist([img2],[i],None,[256],[10,246])\n h1 = h1[5:250]\n h2 = h2[5:250]\n plt.plot(h1)\n plt.plot(h2)\n result.append(cv2.compareHist(h1,h2,0))\n result = np.sum(result)/3\n print(result)\n if result < 0.9:\n return False\n return True \n\n \nwhile(True):\n ret, frame = cap.read()\n gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)\n crop = frame[0:328,0:580]\n drawRec(frame,0,0,580,328)\n cv2.imshow('frame',frame)\n key = cv2.waitKey(1) & 0xFF # & 0xFF if using 64-bit\n if key == ord('q'): \n break\n elif key == ord('c'):\n c = crop\n kp1, des1 = akaze.detectAndCompute(c, None)\n kp2, des2 = akaze.detectAndCompute(picsample, None)\n matches = bf.knnMatch(des1, des2, k=2)\n ratio = 0.5\n good = []\n for m, n in matches:\n if m.distance < ratio * n.distance:\n good.append([m])\n img3 = cv2.drawMatchesKnn(c, kp1, picsample, kp2, good, None, flags=2)\n print(len(good))\n cv2.imshow('img', img3)\n elif key == ord('s'):\n print('Capture Saved!')\n cv2.imwrite('Crop.png',crop)\n elif key == ord('p'):\n pltRGBHistogram(crop)\n elif key == ord('m'):\n maskImg(frame,0,0,580,328)\n elif key == ord('k'):\n temp = cv2.imread('sample2.jpg')\n pltRGBHistogram(temp)\n elif key == ord('o'):\n t1 = cv2.imread('t1.png')\n t2 = cv2.imread('t2.png')\n histCompare(t1,t2)\n elif key == ord('r'):\n _, frame = cap.read()\n cv2.imwrite('now.png',frame[0:328,0:580])\n now = cv2.imread('now.png')\n cz = cv2.imread('cz.png')\n zjm = cv2.imread('zjm.png')\n yz = cv2.imread('yz.png')\n if histCompare(now,cz) == True:\n print('chuzheng')\n elif histCompare(now,zjm) == True:\n print('zhujiemian')\n elif histCompare(now,yz) == True:\n print('yuanzheng')\n# When everything done, release the capture\ncap.release()\ncv2.destroyAllWindows()\n","sub_path":"Archives/ReadAndWriteVideos.py","file_name":"ReadAndWriteVideos.py","file_ext":"py","file_size_in_byte":3433,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"351209531","text":"# -*- coding: UTF-8 -*-\n\nfrom flask import Flask, render_template, Response, request\nfrom flask_bootstrap import Bootstrap\nimport cv2\nimport json\nimport mysql.connector\nimport os\nimport time\nfrom urllib import parse \nfrom urllib import request as url_request\nimport detect_people\nimport random\n\nVideoCameraObj = None\nMY_COLOR = (0, 255, 0)\n\nclass VideoCamera(object):\n def __init__(self):\n # 初始化视频\n #self.VIDEO_STREAM = \"rtsp://10.245.135.25:554/main\"\n self.VIDEO_STREAM = \"rtsp://admin:ddd123456@10.245.135.26:554\"\n self.video = cv2.VideoCapture(self.VIDEO_STREAM)\n self.people_detection = detect_people.PeopleDetection()\n\n def __del__(self):\n self.video.release()\n\n def get_frame(self):\n\n success, image = self.video.read()\n\n # 因为opencv读取的图片并非jpeg格式,因此要用motion JPEG模式需要先将图片转码成jpg格式图片\n if not success:\n print(\"Read Frame Fail.\")\n return None\n\n return image\n\napp = Flask(__name__)\napp.config['SECRET_KEY']='gmcc,st,bsc,bigdata,AI project,2017'\nbootstrap=Bootstrap(app)\n\ndef add_overlays(frame, frame_rate, boxes):\n # 全出识别人体边框(左上角+右下角:x1,y1,x2,y2)\n for box in boxes:\n cv2.rectangle(frame, (box[0], box[1]), (box[2], box[3]), MY_COLOR, thickness=3)\n\n if frame_rate is not None:\n cv2.putText(frame, str(frame_rate) + \" fps\", (20, 60),\n cv2.FONT_HERSHEY_SIMPLEX, 2, MY_COLOR,\n thickness=3, lineType=2)\n\ndef mysqlquery(visit_date_start, visit_date_end):\n temp_mysql = []\n conn = mysql.connector.connect(user='stkqj', password='Gmcc_123', database='stkqj')\n cur = conn.cursor()\n sql1 = \"select id,image_path,ID_NAME,correctName,DATE_FORMAT(Visit_tim,'%Y-%m-%d %H:%i:%S') from vb_ai_crop_visitorlist where substring(Visit_tim,1,8) between %s and %s order by Visit_tim desc limit 10\"\n data = (visit_date_start, visit_date_end,)\n cur.execute(sql1, data)\n for id, image_path, ID_NAME, correctName, Visit_tim in cur:\n temp = {'id': '%s' % (id), 'image_path': '%s' % (image_path), 'name': '%s' % (ID_NAME), 'visit_time': '%s' % (Visit_tim), 'correctName': '%s' % (correctName)}\n temp_mysql.append(temp)\n\n conn.commit()\n conn.close()\n\n return temp_mysql\n\ndef mysql_updateVistorNum(visitor_num):\n conn = mysql.connector.connect(user='stkqj', password='Gmcc_123', database='stkqj')\n cur = conn.cursor()\n sql1 = \"update tb_realtime_info set RealTimeNum= %s \"\n data = (visitor_num,)\n cur.execute(sql1, data)\n conn.commit()\n conn.close()\n\napp = Flask(__name__)\napp.config['SECRET_KEY']='gmcc,st,bsc,bigdata,AI project,2017'\nbootstrap=Bootstrap(app)\n\n@app.route('/') # 主页\ndef index():\n # jinja2模板,具体格式保存在index.html文件中\n return render_template('index.html')\n\n@app.route('/record.html') # 访客页面\ndef record():\n return render_template('record.html')\n\n@app.route('/video.html') # 访客页面(视频)\ndef video():\n return render_template('video.html')\n\n@app.route('/situation.html') # 考勤页面\ndef situation():\n return render_template('situation.html')\n\ndef gen(camera):\n start_time = time.time()\n frame_count = 0\n frame_interval = 5#15\n while True:\n #try:\n # 使用generator函数输出视频流, 每次请求输出的content类型是image/jpeg\n frame_count += 1\n if (frame_count % frame_interval) == 0:\n frame = camera.get_frame()\n \n if frame is None:\n camera.video = cv2.VideoCapture(camera.VIDEO_STREAM)\n continue\n\n # 调用图像处理API\n #time1 = time.time()\n #now_time = time.strftime('%Y%m%d%H%M%S', time.localtime(time1))\n #img_path = \"./data/srcImg/srcImg_\" + str(now_time) + str(random.randint(1,100)) + \".jpg\"\n #cv2.imwrite(img_path, frame)\n #url = \"http://127.0.0.1:9090/frameDetect\"\n #data = {\n # 'srcPath': img_path\n #}\n #data = parse.urlencode(data)\n #data = data.encode('utf-8')\n #req = url_request.Request(url, data)\n #resp = url_request.urlopen(req)\n #content = resp.read()\n #data_json = json.loads(content.decode('utf-8'))\n #if data_json[\"Code\"] == 201:\n # print(\"success.\")\n #elif data_json[\"Code\"] == 400:\n # print(\"error.\")\n \n #这里加入SSD的人体检测,人数检测\n people_num, boxes_list = camera.people_detection.detect_people(frame) \t\t\t\n mysql_updateVistorNum(people_num)\n \n #计算帧速\n #Check our current fps\n end_time = time.time()\n # 检测视频帧速\n if (end_time - start_time) > frame_interval:\n frame_rate = int(frame_count / (end_time - start_time))\n frame_rate = frame_rate\n start_time = time.time()\n frame_count = 0\n frame_rate = 12\n add_overlays(frame, frame_rate, boxes_list)\n \n image = cv2.resize(frame, (640, 480))\n cv2.putText(image, \"V8.TEST.AI.ST.GMCC.CN\", (10, 460),\n cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 255, 0),\n thickness=2, lineType=2)\n ret, jpeg = cv2.imencode('.jpg', image)\n frame = jpeg.tobytes()\n \n else:\n continue\n yield (b'--frame\\r\\n'\n b'Content-Type: image/jpeg\\r\\n\\r\\n' + frame + b'\\r\\n\\r\\n')\n time.sleep(0.01)\n #except:\n # print(\"except,something error\")\n # continue\n \n\n@app.route('/video_feed') # 这个地址返回视频流响应\ndef video_feed():\n return Response(gen(VideoCamera()),\n mimetype='multipart/x-mixed-replace; boundary=frame')\n\n@app.route('/visitor_listinfo',methods=['GET','POST'])\ndef visitor_listinfo():\n if request.method == 'POST':\n visit_date_start = request.form['visit_date_start']\n visit_date_end = request.form['visit_date_end']\n visitor_info=mysqlquery(visit_date_start, visit_date_end)\t\t\n visitor_total_count = getTotalNum(visit_date_start, visit_date_end)\n visitor_realtime_count = getRealTimeNum()\n info = {\"visitor_info\":visitor_info, \"visitor_total_count\":visitor_total_count, \"visitor_realtime_count\":visitor_realtime_count}\n info = json.dumps(info)\n return info\n else:\n return ''\n\n@app.route('/update_correctName',methods=['POST'])\ndef update_correctName():\n if request.method == 'POST':\n name = request.form['id']\n val = request.form['val']\n ID = name.split('_')[0]\t\t\n tim = name.split('_')[1]\n conn = mysql.connector.connect(user='stkqj', password='Gmcc_123', database='stkqj')\n cur = conn.cursor()\n sql1 = \"update tb_ai_vistor_listinfo set correctName= %s where ID= %s and Visit_tim= %s\"\n data = (val, ID, tim,)\n cur.execute(sql1, data)\n conn.commit()\n conn.close()\n return ''\n\n\n\ndef getRealTimeNum():\n if request.method == 'POST':\n \n end_date = time.strftime('%Y%m%d%H%M%s', time.localtime(time.time()))\n begin_date = time.strftime('%Y%m%d%H%M%s', time.localtime(time.time()))\n\n # 读取当前视频文件顺序\n conn = mysql.connector.connect(user='stkqj', password='Gmcc_123', database='stkqj')\n cur = conn.cursor()\n #sql1 = \"select max(Visit_tim) from tb_ai_vistor_listinfo\"\n #cur.execute(sql1, )\n #max_tim = '%s' % (cur.fetchone())\n\n #sql2 = \"select count(*) from tb_ai_vistor_listinfo where Visit_tim >= %s and Visit_tim < %s order by Visit_tim desc;\"\n #data = (int(max_tim)-5, int(max_tim)-4,)\n #cur.execute(sql2, data)\n sql2=\"select RealTimeNum from tb_realtime_info limit 1\"\n cur.execute(sql2,)\n count = '%s' % (cur.fetchone())\t\n #count = json.dumps(count)\n conn.close()\t\n return count\n else:\n return -1\n\t\t\ndef getTotalNum(visit_date_start, visit_date_end):\n temp_mysql = []\n conn = mysql.connector.connect(user='stkqj', password='Gmcc_123', database='stkqj')\n cur = conn.cursor()\n sql1 = \"select count(*) from (select distinct(id) from vb_ai_vistor_listinfo where substring(Visit_tim,1,8) between %s and %s ) as A\"\n data = (visit_date_start, visit_date_end)\n cur.execute(sql1, data)\n total_num = '%s' % (cur.fetchone())\n conn.close()\n\n return total_num\n\nif __name__ == '__main__':\n VideoCameraObj = VideoCamera()\n app.run(host='0.0.0.0', port = 8080, threaded=True)\n #app.run(host='0.0.0.0', port = 8080, threaded=True, debug=False)\n","sub_path":"web.py","file_name":"web.py","file_ext":"py","file_size_in_byte":8870,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"461151438","text":"import json,sys\n\nclass DFA:\n def __init__(self, states=None, letters=None, tmat=None, start=None, final=None):\n self.states = states\n self.letters = letters\n self.start = start\n self.final = final\n self.trans = tmat\n self.state_mpr1 = dict()\n self.state_mpr2 = dict()\n self.new_s = '(QS)'\n self.new_f = '(QF)'\n self.fin_tr = list()\n self.ad_details()\n\n def gts(self,in_s,out_s): # get transition state\n x = [self.trans[i][1] for i in range(len(self.trans)) if ((self.trans[i][0] == in_s) and (self.trans[i][2] == out_s))]\n return x \n\n\n def ad_details(self):\n self.all_s = [self.new_s]+self.states+[self.new_f]\n for i in range(len(self.all_s)):\n self.state_mpr1[i] = self.all_s[i]\n self.state_mpr2[self.all_s[i]] = i\n for i in self.start:\n self.trans.append([self.new_s,'$',i])\n for i in self.final:\n self.trans.append([i,'$',self.new_f])\n self.n = len(self.states)+2\n self.fin_tr = [['' for i in range(self.n)] for j in range(self.n)]\n for i in self.all_s:\n for j in self.all_s:\n ind1 ,ind2 = self.state_mpr2[i],self.state_mpr2[j]\n pttp = self.gts(i,j)\n if len(pttp) > 1:\n temp = ''\n for tss in pttp:\n temp += 'tss'\n self.fin_tr[ind1][ind2] = tss\n elif len(pttp) == 1:\n self.fin_tr[ind1][ind2] = pttp[0] \n \"\"\"\n for i in self.fin_tr:\n print(i)\n print('ddfdf')\n \"\"\"\n\n\n def endgame(self):\n ssi = self.states+[self.new_s]\n ssj = self.states+[self.new_f]\n ripped_lst = list()\n for k in self.states:\n for i in ssi:\n for j in ssj:\n ind1,ind2,ind3 = self.state_mpr2[i], self.state_mpr2[j],self.state_mpr2[k]\n ckck = (i not in ripped_lst) and (j not in ripped_lst) and (ind1!=ind3) and (ind3!=ind2)\n if ckck:\n aa1 = self.fin_tr[ind1][ind3]\n aa2 = self.fin_tr[ind3][ind3]\n aa3 = self.fin_tr[ind3][ind2]\n aa4 = self.fin_tr[ind1][ind2]\n if (len(aa1)!=0) and (len(aa3)!=0):\n upt_with = ''\n if len(aa2) !=0:\n if len(aa4)!=0: \n upt_with = '('+self.fin_tr[ind1][ind3]+')('+self.fin_tr[ind3][ind3]+')*('+self.fin_tr[ind3][ind2] + ')+('+self.fin_tr[ind1][ind2]+')'\n else:\n upt_with = '('+self.fin_tr[ind1][ind3]+')('+self.fin_tr[ind3][ind3]+')*('+self.fin_tr[ind3][ind2] + ')'\n else:\n if len(aa4)!=0: \n upt_with = '('+self.fin_tr[ind1][ind3]+')('+self.fin_tr[ind3][ind2] + ')+('+self.fin_tr[ind1][ind2]+')'\n else:\n upt_with = '('+self.fin_tr[ind1][ind3]+')('+self.fin_tr[ind3][ind2] + ')'\n self.fin_tr[ind1][ind2] = upt_with\n ripped_lst.append(k)\n for i in self.fin_tr:\n print(i)\n print()\n print(self.fin_tr[0][self.n-1],'values')\n\n\n\n\n\n\nif __name__ == '__main__':\n # print('number of args passed:',len(sys.argv))\n input_fn = sys.argv[1] # input file\n output_fn = sys.argv[2] # output file\n with open(input_fn,'r') as f:\n data = json.load(f)\n cdfa = DFA(data['states'],data['letters'],data['transition_function'],data['start_states'],data['final_states'])\n cdfa.endgame()\n\n \n \n \n \"\"\"\n with open(output_fn,'w') as f: \n json.dump(ooo, f ,indent = 4)\n \"\"\"","sub_path":"Q3/q3a.py","file_name":"q3a.py","file_ext":"py","file_size_in_byte":3953,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"569214663","text":"\"\"\"This module handles shell commands to run ack\"\"\"\n\nimport os\nfrom subprocess import getstatusoutput\n\nfrom pysyte.types import paths\n\nclass ShellError(Exception):\n def __init__(self, status, output):\n Exception.__init__(self, output)\n self.status = status\n\n\ndef _assert_perl_script(path):\n \"\"\"Raise errors if that path is not a perl script\n\n It is a perl script if it\n 1. is a file, and\n 2.a. has a '.pl' extension, or\n 2.b. mentions 'perl' in first line\n \"\"\"\n if not os.path.isfile(path):\n raise NotImplementedError('\"%s\" is not a file' % path)\n\n _stem, ext = os.path.splitext(path)\n if ext == \".pl\":\n return\n with open(path) as stream:\n if \"perl\" in stream.readline():\n return\n raise NotImplementedError(\"%s is not a perl script\" % path)\n\n\ndef shell_path() -> str:\n \"\"\"The PATH in the current shell\n\n If PATH is not raise a ShellError\n This would be exceptional and user's environment is not set correctly\n \"\"\"\n try:\n return os.environ[\"PATH\"]\n except KeyError:\n raise ShellError(1, \"Environment symbol `PATH` is not set\")\n\n\ndef run_command(command: str) -> str:\n \"\"\"Run the given command in the shell's PATH\"\"\"\n path_command = f\"PATH={shell_path()} {command}\"\n status, output = getstatusoutput(path_command)\n if status == 0:\n return output\n raise ShellError(status, output)\n\n\ndef which_ack() -> str:\n \"\"\"Get path to the ack command, given shell's path\"\"\"\n ack = paths.environ_path(\"ACK\")\n if ack.is_executable():\n return str(ack)\n if ack:\n raise ShellError(2, \"$ACK is not executable: {ack}\")\n ack = run_command(\"which ack\")\n _assert_perl_script(ack)\n return ack\n\n\ndef run_ack(args: str) -> str:\n \"\"\"Run an ack command with those args\"\"\"\n command = f\"{which_ack()} {args}\"\n return run_command(command)\n\n\ndef ack_help(help_wanted: str):\n \"\"\"Get the wanted help from ack\n\n ack provides more/less verbose help depending on what's asked\n so help_wanted can be one of \"help\", \"help-types\", \"dump\"\n \"\"\"\n if help_wanted not in (\"help\", \"help-types\", \"dump\"):\n raise ValueError(f\"Bad option for ack help: {help_wanted!r}\")\n option = f\"--{help_wanted}\"\n output = run_ack(option)\n return [_[2:] for _ in output.splitlines() if _.startswith(\" -\")]\n","sub_path":"ackvim/commands.py","file_name":"commands.py","file_ext":"py","file_size_in_byte":2373,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"442009104","text":"# Importing the libraries\nimport pandas as pd\nimport numpy as np\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.ensemble import RandomForestClassifier\nimport pickle \n\n\nDF_URL = 'https://raw.githubusercontent.com/devrepublik/data-science-course/master/data/classification/HeartDisease_Clean.csv'\nstroke_df = pd.read_csv(DF_URL)\n\n\nX_train, X_test, y_train, y_test = train_test_split(\n stroke_df.drop('target', axis=1),\n stroke_df['target'],\n test_size=0.1,\n random_state=42)\n\nregressor = RandomForestClassifier(\n n_estimators=500,\n criterion='entropy',\n max_samples=0.5,\n oob_score=True,\n random_state=42)\n\nregressor.fit(X_train, y_train);\n\npickle.dump(regressor, open('model.pkl', 'wb'))","sub_path":"model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":732,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"500902142","text":"arr = [8, 4, 2, 1, 6, 9, 7, 3, 5]\n\n# TO-DO: implement the Merge Sort function below USING RECURSION\ndef merge_sort( arr ):\n # Step 1: set up base case (if array is length of 1, should be returned)\n if len(arr) < 2:\n return arr\n # Step 2: divide the length of array by 2 (// for floor vs decimal)\n middle = len(arr) // 2\n # Step 3: assign the left integers to a separate variable and recursively call function to continue dividing\n left = merge_sort(arr[:middle])\n # Step 4: ditto for the right side integers (: in front = left, : at end = right)\n right = merge_sort(arr[middle:])\n # Step 5: feed the newly divided arrays into the helper function so they can be sorted\n return merge(left, right)\n# Note: the above steps classify as DIVIDE and below would be considered CONQUER\n\n# TO-DO: complete the helper function below to merge 2 sorted arrays\ndef merge( left, right ):\n # Step 1: set up base case (if there isn't a length, the work is done, so just return)\n if not len(left) or not len(right):\n return left or right\n # Step 2: initialize emptry array so we have somewhere to put the data as it's merged\n merged_arr = []\n # Step 3: create two placeholder indexes or we won't have any data to compare\n i = 0\n j = 0\n # Step 4: specify when work is to be done (while merged arr is smaller than the combined arrays being sorted)\n while len(merged_arr) < len(left) + len(right):\n # Step 5: if left integer is smaller than it's neighbor, place it in front, increment, and repeat\n if left[i] < right[j]:\n merged_arr.append(left[i])\n i += 1\n else:\n # Step 6: if left integer is bigger than it's neighbor, it goes behind (increment + repeat) \n merged_arr.append(right[j])\n j += 1\n # Step 7: specify what happens when we've sorted all the way down to one number\n if i == len(left) or j == len(right):\n # Step 8: place the sorted data inside the new array for this purpose\n merged_arr.extend(left[i:] or right[j:]) # sub_arr[index:]\n # Step 9: terminate the process to prevent continued operations\n break\n # Step 10: return our sorted array\n return merged_arr\n\nprint(merge_sort(arr))\n\n# QUICK SORT (everything to left of pivot smaller, everything to right larger)\ndef quick_sort(arr):\n # Step 1: set up base case (return array when 1 or less items left -- nothing left to sort)\n if len(arr) <= 1:\n return arr\n # Step 2: choose pivot (base of comparison) index and assign to a variable (-1 means last index)\n pivot = arr[-1]\n # Step 3: create empty arrays for both smaller and larger elements so they can be sorted inside\n smaller = []\n larger = []\n # Step 4: begin for loop -- remember it is typically array length minus one (account for pivot)\n for i in range(len(arr) - 1):\n # Step 5: optional -- assign index to element variable for more explicit/obvious code\n element = arr[i]\n # Step 6: if the element is smaller than pivot, append inside the smaller array\n if element < pivot:\n smaller.append(element)\n # Step 7: if the element is larger than pivot, append inside the larger array\n else:\n larger.append(element)\n # Step 8: do another quick_sort on both larger and smaller nums, repeat until sorted, add with pivot in middle\n return quick_sort(smaller) + [pivot] + quick_sort(larger) # square brackets because we're adding three arrays\n\nprint(quick_sort(arr))\n\n# STRETCH: implement an in-place merge sort algorithm\ndef merge_in_place(arr, start, mid, end):\n # TO-DO\n\n return arr\n\ndef merge_sort_in_place(arr, l, r): \n # TO-DO\n\n return arr\n\n\n# STRETCH: implement the Timsort function below\n# hint: check out https://github.com/python/cpython/blob/master/Objects/listsort.txt\ndef timsort( arr ):\n\n return arr\n","sub_path":"src/recursive_sorting/recursive_sorting.py","file_name":"recursive_sorting.py","file_ext":"py","file_size_in_byte":3941,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"292236052","text":"import tensorflow as tf\r\nfrom tensorflow.keras.models import Sequential\r\nfrom tensorflow.keras.layers import Dense,Dropout,LSTM\r\n\r\nmnist = tf.keras.datasets.mnist\r\n(x_train,y_train),(x_test,y_test)= mnist.load_data()\r\n\r\nx_train = x_train/255.0\r\nx_train = x_test/255.0 \r\n\r\n\r\nmodel.add(LSTM(128,input_shape=(x_train.shape[1:]),activation='relu',return_sequences=True))\r\nmodel.add(Dropout(0.2))\r\n\r\nmodel.add(LSTM(128,activation='relu'))\r\nmodel.add(Dropout(0.2))\r\n\r\nmodel.add(Dense(32,actiavtion='relu'))\r\nmodel.add(Dropout(0.2))\r\n\r\nmodel.add(Dense(10,actiavtion='softmax'))\r\n\r\nopt.tf.keras.optimizers.Adam(Lr=1e-3,decay=1e-5)\r\n\r\nmodel.compile(Loss='sparse_categorical_crossentropy',optimizer=opt,metrics=['accuray'])\r\n\r\nmodel.fit(x_train,y_train,epochs=3,validation_data=(x_test,y_test))\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n \r\n \r\n\r\n","sub_path":"RNN Implementation.py","file_name":"RNN Implementation.py","file_ext":"py","file_size_in_byte":877,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"168537438","text":"WORDLIST_FILENAME = \"words.txt\"\n\n\ndef loadWords():\n \"\"\"\n Returns a list of valid words. Words are strings of lowercase letters.\n\n Depending on the size of the word list, this function may\n take a while to finish.\n \"\"\"\n print(\"Loading word list from file...\")\n # inFile: file\n inFile = open(WORDLIST_FILENAME, 'r')\n # wordList: list of strings\n wordList = []\n for line in inFile:\n wordList.append(line.strip().lower())\n print(\" \", len(wordList), \"words loaded.\")\n return wordList\n\n\ndef getFrequencyDict(sequence):\n \"\"\"\n Returns a dictionary where the keys are elements of the sequence\n and the values are integer counts, for the number of times that\n an element is repeated in the sequence.\n\n sequence: string or list\n return: dictionary\n \"\"\"\n # freqs: dictionary (element_type -> int)\n freq = {}\n for x in sequence:\n freq[x] = freq.get(x, 0) + 1\n return freq\n\n\ndef flatten(aList):\n \"\"\"\n aList: The list contains other lists, strings,or ints\n returns: flattened list(eliminate the redundancy elements)\n \"\"\"\n if not aList:\n return []\n for i in aList:\n if type(i) == list:\n aList.remove(i)\n return flatten(aList) + flatten(i)\n else:\n aList.remove(i)\n return [i] + flatten(aList)\n\n\ndef isValidWord(word, hand, wordList):\n \"\"\"\n Returns True if word is in the wordList and is entirely\n composed of letters in the hand. Otherwise, returns False.\n\n Does not mutate hand or wordList.\n\n word: string\n hand: dictionary (string -> int)\n wordList: list of lowercase strings\n \"\"\"\n list1 = []\n list2 = []\n list3 = []\n for key, val in hand.items():\n list1.append(key * val)\n for i in list1:\n i = list(i)\n list2.append(i)\n list2 = flatten(list2)\n for i in word:\n if i in list2:\n list3.append(i)\n list2.remove(i)\n if len(list3) == len(word) and (word in wordList):\n return True\n else:\n return False\n\n\ndef test_isValidWord(wordList):\n \"\"\"\n Unit test for isValidWord\n \"\"\"\n failure = False\n # test 1\n word = \"hello\"\n handOrig = getFrequencyDict(word)\n handCopy = handOrig.copy()\n\n if not isValidWord(word, handCopy, wordList):\n print(\"FAILURE: test_isValidWord()\")\n print(\"\\tExpected True, but got False for word: '\" + word + \"' and hand:\", handOrig)\n\n failure = True\n\n # Test a second time to see if wordList or hand has been modified\n if not isValidWord(word, handCopy, wordList):\n print(\"FAILURE: test_isValidWord()\")\n\n if handCopy != handOrig:\n print(\"\\tTesting word\", word, \"for a second time - be sure you're not modifying hand.\")\n print(\"\\tAt this point, hand ought to be\", handOrig, \"but it is\", handCopy)\n\n else:\n print(\"\\tTesting word\", word, \"for a second time - have you modified wordList?\")\n wordInWL = word in wordList\n print(\"The word\", word, \"should be in wordList - is it?\", wordInWL)\n\n print(\"\\tExpected True, but got False for word: '\" + word + \"' and hand:\", handCopy)\n\n failure = True\n\n # test 2\n hand = {'r': 1, 'a': 3, 'p': 2, 'e': 1, 't': 1, 'u': 1}\n word = \"rapture\"\n\n if isValidWord(word, hand, wordList):\n print(\"FAILURE: test_isValidWord()\")\n print(\"\\tExpected False, but got True for word: '\" + word + \"' and hand:\", hand)\n\n failure = True\n\n # test 3\n hand = {'n': 1, 'h': 1, 'o': 1, 'y': 1, 'd': 1, 'w': 1, 'e': 2}\n word = \"honey\"\n\n if not isValidWord(word, hand, wordList):\n print(\"FAILURE: test_isValidWord()\")\n print(\"\\tExpected True, but got False for word: '\" + word + \"' and hand:\", hand)\n\n failure = True\n\n # test 4\n hand = {'r': 1, 'a': 3, 'p': 2, 't': 1, 'u': 2}\n word = \"honey\"\n\n if isValidWord(word, hand, wordList):\n print(\"FAILURE: test_isValidWord()\")\n print(\"\\tExpected False, but got True for word: '\" + word + \"' and hand:\", hand)\n\n failure = True\n\n # test 5\n hand = {'e': 1, 'v': 2, 'n': 1, 'i': 1, 'l': 2}\n word = \"evil\"\n\n if not isValidWord(word, hand, wordList):\n print(\"FAILURE: test_isValidWord()\")\n print(\"\\tExpected True, but got False for word: '\" + word + \"' and hand:\", hand)\n\n failure = True\n\n # test 6\n word = \"even\"\n\n if isValidWord(word, hand, wordList):\n print(\"FAILURE: test_isValidWord()\")\n print(\"\\tExpected False, but got True for word: '\" + word + \"' and hand:\", hand)\n print(\"\\t(If this is the only failure, make sure isValidWord() isn't mutating its inputs)\")\n\n failure = True\n\n if not failure:\n print(\"SUCCESS: test_isValidWord()\")\n\n\nwordList = loadWords()\ntest_isValidWord(wordList)\n","sub_path":"WordGame/isValidWord.py","file_name":"isValidWord.py","file_ext":"py","file_size_in_byte":4850,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"130326076","text":"class JaccardSimilarityBasedDetector:\n def measure(self, sentence1, sentence2):\n sentence1_words = set(sentence1.split())\n sentence2_words = set(sentence2.split())\n \n intersection = sentence1_words.intersection(sentence2_words)\n union = sentence1_words.union(sentence2_words)\n \n similarity = len(intersection) / len(union)\n return similarity\n","sub_path":"ml_keeker/handler/detector/jaccard.py","file_name":"jaccard.py","file_ext":"py","file_size_in_byte":401,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"243020709","text":"#!/usr/bin/python\n#-*- coding: utf-8 -*-\n\nfrom __future__ import unicode_literals, absolute_import, division, print_function\n\nfrom . import logger\n\nclass Template(object):\n def __init__(self, name):\n self.name = name\n self.args = []\n self.keywords = dict()\n \n def _value_to_string(self, value):\n value = value.replace(\"=\", \"{{=}}\")\n value = value.strip()\n return value\n\n def __unicode__(self):\n s = \"{{\" + self.name\n\n for value in self.args:\n s += \"|\" + self._value_to_string(value)\n\n for key, value in self.keywords.items():\n s += \"|\" + key + \"=\" + self._value_to_string(value)\n\n s += \"}}\"\n return s\n \n @classmethod\n def make(cls, name, *args, **keywords):\n template = cls(name)\n template.args = args\n template.keywords = keywords\n return unicode(template)\n","sub_path":"html2mediawiki/template.py","file_name":"template.py","file_ext":"py","file_size_in_byte":906,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"487355788","text":"import tensorflow as tf\nimport numpy as np \nfrom PIL import Image\nimport os\nimport random\n\nfilepath='./train_reshaped'\nlist = os.listdir(filepath)\ncurrent_index = 0\nimage_set = np.zeros((len(list),100,100,3),dtype=np.float32)\nlabel_set = np.zeros((len(list),25))\n\ncontent = open(\"train_label.txt\",\"r\")\nline = content.readlines()\nrandom.shuffle(line)\n\nfor i in range(len(line)):\n\tname,label = line[i].split(',')\n\timg = np.asarray(Image.open(filepath+\"/\"+name))\n\timage_set[i] = img\n\tlabel_set[i] = np.zeros(25)\n\tlabel_set[i][int(label)] = 1\n\nnp.savez(\"train_set.npz\",images=image_set,labels=label_set)\ncontent.close()\n\n\ntrain_set = np.load(\"train_set.npz\")\ntest_set = np.load(\"../testing.npy\").item()\n\n\nimgs = train_set[\"images\"]\nlabels = train_set[\"labels\"]\nimgs_size = imgs.shape[0]\n\ndef get_train_batch(batch_size):\n global current_index\n \n if current_index*batch_size+batch_size>imgs_size:\n batch_imgs = np.zeros((batch_size,100,100,3))\n batch_imgs[0:imgs_size-batch_size*current_index] = imgs[current_index*batch_size:imgs_size]\n y_label = np.zeros((batch_size,25))\n y_label[0:imgs_size-batch_size*current_index] = labels[current_index*batch_size:imgs_size]\n batch_imgs[imgs_size-batch_size*current_index:]=imgs[0:batch_size-imgs_size+batch_size*current_index]\n y_label[imgs_size-batch_size*current_index:] = labels[0:batch_size-imgs_size+batch_size*current_index]\n current_index=0\n return batch_imgs, y_label\n \n batch_imgs = np.array(imgs[current_index*batch_size:current_index*batch_size+batch_size])\n y_label = np.array(labels[current_index*batch_size:current_index*batch_size+batch_size])\n current_index += 1\n return batch_imgs, y_label\n \n \n\n\n\n\ndef compute_accuracy(v_xs,v_ys):\n\tglobal prediction\n\ty_pre = sess.run(prediction,feed_dict={xs:v_xs,keep_prob:1})\n\tcorrect_prediction = tf.equal(tf.argmax(y_pre,1),tf.argmax(v_ys,1))\n\taccuracy = tf.reduce_mean(tf.cast(correct_prediction,tf.float32))\n\tresult = sess.run(accuracy,feed_dict={xs:v_xs,ys:v_ys,keep_prob:1})\n\treturn result\n\n\ndef weight_variable(shape):\n\tinitial = tf.truncated_normal(shape,stddev=0.1)\n\treturn tf.Variable(initial)\n\n\ndef bias_variable(shape):\n\tinitial = tf.constant(0.1,shape=shape)\n\treturn tf.Variable(initial)\n\ndef conv2d(x,W):\n\treturn tf.nn.conv2d(x,W,strides=[1,1,1,1],padding='SAME')\n\ndef max_pool_2x2(x):\n\treturn tf.nn.max_pool(x,ksize=[1,2,2,1],strides=[1,2,2,1],padding='SAME')\n\n\n\n\nxs = tf.placeholder(tf.float32,[None,100,100,3])\nys = tf.placeholder(tf.float32,[None,25])\nkeep_prob = tf.placeholder(tf.float32)\n\nW_conv1 = weight_variable([5,5,3,32])\nb_conv1 = bias_variable([32])\nh_conv1 = tf.nn.relu(conv2d(xs,W_conv1)+b_conv1)\nh_pool1 = max_pool_2x2(h_conv1)\n\nW_conv2 = weight_variable([5,5,32,64])\nb_conv2 = bias_variable([64])\nh_conv2 = tf.nn.relu(conv2d(h_pool1,W_conv2)+b_conv2)\nh_pool2 = max_pool_2x2(h_conv2)\n\nW_conv3 = weight_variable([5,5,64,128])\nb_conv3 = bias_variable([128])\nh_conv3 = tf.nn.relu(conv2d(h_pool2,W_conv3)+b_conv3)\nh_pool3 = max_pool_2x2(h_conv3)\n\nW_fc1 = weight_variable([13*13*128,1024])\nb_fc1 = bias_variable([1024])\nh_pool3_flat = tf.reshape(h_pool3,[-1,13*13*128])\nh_fc1 = tf.nn.relu(tf.matmul(h_pool3_flat,W_fc1)+b_fc1)\nh_fc1_drop=tf.nn.dropout(h_fc1,keep_prob)\n\nW_fc2 = weight_variable([1024,25])\nb_fc2 = bias_variable([25])\nprediction = tf.nn.softmax(tf.matmul(h_fc1_drop,W_fc2)+b_fc2)\ntest_img = np.array(test_set[\"reshaped\"]).reshape(len(test_set[\"reshaped\"]),100,100,3).astype(\"uint8\")\ntest_label = np.array(test_set[\"label\"])\ntest_labels = np.zeros((250,25))\nfor i in range(250):\n test_labels[i][test_label[i]]=1\n\ncross_entropy=tf.reduce_mean(-tf.reduce_sum(ys*tf.log(prediction),reduction_indices=[1]))\n\ntrain_step = tf.train.AdamOptimizer(1e-4).minimize(cross_entropy)\n\ninit = tf.global_variables_initializer()\nsess = tf.Session()\nsess.run(init)\n\nfor i in range(2000):\n batch_xs, batch_ys = get_train_batch(50)\n sess.run(train_step,feed_dict={xs:batch_xs,ys:batch_ys,keep_prob:0.5})\n if i % 50 == 0:\n print(compute_accuracy(test_img,test_labels))\n","sub_path":"1155107961/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":4024,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"67303197","text":"from astropy.modeling.fitting import SherpaFitter\nfrom astropy.modeling.models import Gaussian1D, Gaussian2D\n\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nsfitter = SherpaFitter(statistic='chi2', optimizer='levmar', estmethod='confidence')\nsfitter.est_config['max_rstat'] = 4\nnp.random.seed(0x1337)\n\ntrue = Gaussian1D(amplitude=3, mean=0.9, stddev=0.5)\nerr = 0.8\nstep = 0.2\nx = np.arange(-3, 3, step)\ny = true(x) + err * np.random.uniform(-1, 1, size=len(x))\n\nyerrs = err * np.random.uniform(0.2, 1, size=len(x))\n# binsize=step * np.ones(x.shape) # please note these are binsize/2 not\n# true errors!\n# please note these are binsize/2 not true errors!\nbinsize = step * np.ones(x.shape)\n\nfit_model = true.copy() # ofset fit model from true\nfit_model.amplitude = 2\nfit_model.mean = 0\nfit_model.stddev = 0.2\n\nplt.plot(x, true(x), label=\"True\")\nplt.errorbar(x, y, xerr=binsize, yerr=yerrs, ls=\"\", label=\"Data\")\nplt.plot(x, fit_model(x), label=\"Starting fit model\")\nplt.legend(loc=(0.02, 0.7), frameon=False)\nplt.xlim((-3, 3))\nplt.savefig(\"_generated/example_plot_data.png\")\nplt.close('all')\n\n\nfitted_model = sfitter(fit_model, x, y, xbinsize=binsize, err=yerrs)\n\nplt.plot(x, true(x), label=\"True\")\nplt.errorbar(x, y, xerr=binsize, yerr=yerrs, ls=\"\", label=\"Data\")\nplt.plot(x, fit_model(x), label=\"Starting fit model\")\nplt.plot(x, fitted_model(x), label=\"Fitted model\")\nplt.legend(loc=(0.02, 0.6), frameon=False)\nplt.xlim((-3, 3))\nplt.savefig(\"_generated/example_plot_fitted.png\")\nplt.close('all')\n\n\nparam_errors = sfitter.est_errors(sigma=3)\nmin_model = fitted_model.copy()\nmax_model = fitted_model.copy()\n\nfor pname, pval, pmin, pmax in zip(*param_errors):\n print(pname, pval, pmin, pmax)\n getattr(min_model, pname).value = pval + pmin\n getattr(max_model, pname).value = pval + pmax\n\n\nplt.plot(x, true(x), label=\"True\")\nplt.errorbar(x, y, xerr=binsize, yerr=yerrs, ls=\"\")\nplt.plot(x, fitted_model(x), label=\"Fitted model\")\nplt.plot(x, min_model(x), label=\"min model\", ls=\"--\")\nplt.plot(x, max_model(x), label=\"max model\", ls=\"--\")\nplt.legend(loc=(0.02, 0.6), frameon=False)\n_ = plt.xlim((-3, 3))\n\nplt.savefig(\"_generated/example_plot_error.png\")\nplt.close('all')\n\nsfitter = SherpaFitter(statistic='chi2', optimizer='levmar', estmethod='confidence')\n\ndouble_gaussian = Gaussian1D(\n amplitude=10, mean=-1.5, stddev=0.5) + Gaussian1D(amplitude=1, mean=0.9,\n stddev=0.5)\n\n\ndef tiedfunc(self): # a function used for tying amplitude_1\n return 1.2 * self.amplitude_0\n\ndouble_gaussian.amplitude_1.tied = tiedfunc\ndouble_gaussian.amplitude_1.value = double_gaussian.amplitude_1.tied(\n double_gaussian)\n\n\nerr = 0.8\nstep = 0.2\nx = np.arange(-3, 3, step)\ny = double_gaussian(x) + err * np.random.uniform(-1, 1, size=len(x))\nyerrs = err * np.random.uniform(0.2, 1, size=len(x))\n# please note these are binsize/2 not true errors!\nbinsize = (step / 2) * np.ones(x.shape)\n\n\nplt.errorbar(x, y, xerr=binsize, yerr=yerrs, ls=\"\", label=\"data\")\n# once again xerrs are binsize/2 not true errors!\nplt.plot(x, double_gaussian(x), label=\"True\")\nplt.legend(loc=(0.78, 0.8), frameon=False)\n_ = plt.xlim((-3, 3))\n\n\nplt.savefig(\"_generated/example_plot_data2.png\")\nplt.close('all')\n\n\nfit_gg = double_gaussian.copy()\nfit_gg.mean_0.value = -0.5\n# sets the lower bound so we can force the parameter against it\nfit_gg.mean_0.min = -1.25\nfit_gg.mean_1.value = 0.8\nfit_gg.stddev_0.value = 0.9\nfit_gg.stddev_0.fixed = True\n\nfitted_gg = sfitter(fit_gg, x, y, xbinsize=binsize, err=yerrs)\nprint(\"##Fit with contraints\")\nprint(sfitter._fitmodel.sherpa_model)\n\nfree_gg = sfitter(double_gaussian.copy(), x, y, xbinsize=binsize, err=yerrs)\nprint()\nprint(\"##Fit without contraints\")\nprint(sfitter._fitmodel.sherpa_model)\n\nplt.figure(figsize=(10, 5))\nplt.plot(x, double_gaussian(x), label=\"True\")\nplt.errorbar(x, y, xerr=binsize, yerr=yerrs, ls=\"\", label=\"data\")\nplt.plot(x, fit_gg(x), label=\"Pre fit\")\nplt.plot(x, fitted_gg(x), label=\"Fitted\")\nplt.plot(x, free_gg(x), label=\"Free\")\nplt.subplots_adjust(right=0.8)\nplt.legend(loc=(1.01, 0.55), frameon=False)\nplt.xlim((-3, 3))\n\nplt.savefig(\"_generated/example_plot_fitted2.png\")\nplt.close('all')\n\n\nfit_gg = double_gaussian.copy()\nfit_gg.mean_0.value = -0.5\nfit_gg.mean_0.min = -1.25\nfit_gg.mean_1.value = 0.8\nfit_gg.stddev_0.value = 0.9\nfit_gg.stddev_0.fixed = True\n\nfm1, fm2 = sfitter([fit_gg, double_gaussian.copy()],\n x, y, xbinsize=binsize, err=yerrs)\n\n\nplt.figure(figsize=(10, 5))\nplt.plot(x, double_gaussian(x), label=\"True\")\nplt.errorbar(x, y, xerr=binsize, yerr=yerrs, ls=\"\", label=\"data\")\nplt.plot(x, fit_gg(x), label=\"Pre fit\")\nplt.plot(x, fm1(x), label=\"Constrained\")\nplt.plot(x, fm2(x), label=\"Free\")\nplt.subplots_adjust(right=0.8)\n\n\nplt.legend(loc=(1.01, 0.55), frameon=False)\nplt.xlim((-3, 3))\n\n\nplt.savefig(\"_generated/example_plot_simul.png\")\nplt.close(\"all\")\n\n\nfit_gg = double_gaussian.copy()\nfit_gg.mean_0 = -2.3\nfit_gg.mean_1 = 0.7\nfit_gg.amplitude_0 = 2\nfit_gg.amplitude_1 = 3\nfit_gg.stddev_0 = 0.3\nfit_gg.stddev_1 = 0.5\n\n\nsecond_gg = double_gaussian.copy()\nsecond_gg.mean_0 = -2\nsecond_gg.mean_1 = 0.5\nsecond_gg.amplitude_0 = 8\nsecond_gg.amplitude_1 = 5\nsecond_gg.stddev_0 = 0.4\nsecond_gg.stddev_1 = 0.8\nsecond_gg.amplitude_1.value = second_gg.amplitude_1.tied(second_gg)\n\n\nyy2 = second_gg(x) + err * np.random.uniform(-1, 1, size=len(x))\nyy2errs = err * np.random.uniform(0.2, 1, size=len(x))\n\nplt.errorbar(x, y, xerr=binsize, yerr=yerrs, ls=\"\", label=\"data1\")\nplt.errorbar(x, yy2, yerr=yy2errs, ls=\"\", label=\"data2\")\nplt.plot(x, fit_gg(x), label=\"Prefit\")\n\nfitted_model = sfitter(fit_gg, x=[x, x], y=[y, yy2], xbinsize=[\n binsize, None], err=[yerrs, yy2errs])\n\nplt.plot(x, fitted_model[0](x), label=\"Fitted\")\nplt.plot(x, fitted_model[1](x), label=\"Fitted\")\nplt.subplots_adjust(right=0.8)\n\n\nplt.legend(loc=(1.01, 0.55), frameon=False)\nplt.xlim((-3, 3))\n\n\nplt.savefig(\"_generated/example_plot_simul2.png\")\nplt.close(\"all\")\n\n\ncy=y.copy()\ncy[cy<0]=0\ncfitter = SherpaFitter(statistic='cstat', optimizer='levmar', estmethod='covariance')\ncmo=cfitter(fit_gg, x=x, y=cy, xbinsize=binsize, err=yerrs, bkg=y, bkg_scale=0.3)\n\nplt.errorbar(x, cy, yerr=yerrs, xerr=binsize)\nplt.plot(x, cmo(x))\nplt.savefig(\"_generated/example_plot_bkg.png\")\nplt.close(\"all\")\n\n\nnp.random.seed(123456789)\nx0low, x0high = 3000, 4000\nx1low, x1high = 4000, 4800\ndx = 15\nx1, x0 = np.mgrid[x1low:x1high:dx, x0low:x0high:dx]\nshape = x0.shape\nx0, x1 = x0.flatten(), x1.flatten()\n\n\nplt.rcParams['figure.figsize'] = (15, 5)\n\ntruth = Gaussian2D(x_mean=3512, y_mean=4418, x_stddev=150, y_stddev=150,\n theta=20, amplitude=100)\nmexp = truth(x0, x1).reshape(shape)\nmerr = abs(np.random.poisson(mexp) - mexp)\n\nplt.subplot(1, 3, 1)\nplt.imshow(mexp, origin='lower', cmap='viridis',\n extent=(x0low, x0high, x1low, x1high),\n interpolation='nearest', aspect='auto')\nplt.title(\"True\")\nplt.subplot(1, 3, 2)\nplt.imshow(merr, origin='lower', cmap='viridis',\n extent=(x0low, x0high, x1low, x1high),\n interpolation='nearest', aspect='auto')\nplt.title(\"Noise\")\nplt.subplot(1, 3, 3)\nplt.imshow((mexp + merr), origin='lower', cmap='viridis',\n extent=(x0low, x0high, x1low, x1high),\n interpolation='nearest', aspect='auto')\nplt.title(\"True+Noise\")\n\nplt.savefig(\"_generated/example_plot_2d_data.png\")\nplt.close(\"all\")\n\n\nsfit = SherpaFitter(statistic=\"chi2\")\nfitmo = truth.copy()\nfitmo.x_mean = 3650\nfitmo.y_mean = 4250\nfitmo.x_stddev = 100\nfitmo.y_stddev = 100\nfitmo.theta = 10\nfitmo.amplitude = 50\n\nfitmo = sfit(fitmo, x0.flatten(), x1.flatten(), mexp.flatten()+merr.flatten(), xbinsize=np.ones(x0.size)*dx, ybinsize=np.ones(x1.size)*dx, err=merr.flatten()+np.random.uniform(-0.5, 0.5, x0.size))\n\n\nplt.subplot(1, 2, 1)\nplt.imshow(fitmo(x0, x1).reshape(shape), origin='lower', cmap='viridis',\n extent=(x0low, x0high, x1low, x1high),\n interpolation='nearest', aspect='auto')\nplt.title(\"Fit Model\")\n\nres = (mexp + merr) - fitmo(x0, x1).reshape(shape)\nplt.subplot(1, 2, 2)\nplt.imshow(res, origin='lower', cmap='viridis',\n extent=(x0low, x0high, x1low, x1high),\n interpolation='nearest', aspect='auto')\nplt.title(\"Residuals\")\n\n\nplt.savefig(\"_generated/example_plot_2d_fit.png\")\nplt.close(\"all\")\n\nfrom astropy.modeling.models import Polynomial1D\n\nx = np.arange(0, 10, 0.1)\ny = 2+3*x**2+0.5*x\nsfit = SherpaFitter(statistic=\"Cash\")\nprint(sfit(Polynomial1D(2), x, y))\n\nsampler = sfit.get_sampler()\n\n\ndef lognorm(x):\n # center on 10^20 cm^2 with a sigma of 0.5\n sigma = 0.5\n x0 = 1\n # nH is in units of 10^-22 so convert\n dx = np.log10(x) - x0\n norm = sigma / np.sqrt(2 * np.pi)\n return norm * np.exp(-0.5*dx*dx/(sigma*sigma))\n\nsampler.set_prior(\"c0\", lognorm)\n_ = sampler(20000)\n\n\ndef plotter(xx, yy, c):\n px = []\n py = []\n for (xlo, xhi), y in zip(zip(xx[:-1], xx[1:]), yy):\n\n px.extend([xlo, xhi])\n py.extend([y, y])\n plt.plot(px, py, c=c)\n\n\ndef plot_hist(sampler, pname, nbins, c=\"b\"):\n yy, xx = np.histogram(sampler.parameters[pname][sampler.accepted], nbins)\n plotter(xx, yy, c)\n plt.axvline(sampler.parameter_map[pname].val, c=c)\n\nplt.figure(figsize=(3.2, 6))\n\n\nplt.subplot(311)\nplot_hist(sampler, 'c0', 100, 'k')\nplt.text(0.1, 350, \"c0\")\nplt.subplot(312)\nplot_hist(sampler, 'c1', 100, 'r')\nplt.text(-2.9, 350, \"c2\")\nplt.ylabel(\"Number of accepted fits\")\nplt.subplot(313)\nplot_hist(sampler, 'c2', 100, 'b')\nplt.text(2.61, 300, \"c3\")\nplt.xlabel(\"Parameter value\")\nplt.subplots_adjust(left=0.2)\nplt.savefig(\"_generated/example_plot_mcmc_hist.png\")\nplt.close(\"all\")\n\n\ndef plot_cdf(sampler, pname, nbins, c=\"b\", sigfrac=0.682689):\n y, xx = np.histogram(sampler.parameters[pname][sampler.accepted], nbins)\n cdf = [y[0]]\n for yy in y[1:]:\n cdf.append(cdf[-1]+yy)\n cdf = np.array(cdf)\n cdf = cdf / float(cdf[-1])\n\n plotter(xx, cdf, c)\n plt.axvline(sampler.parameter_map[pname].val, c=c)\n med_ind = np.argmin(abs(cdf-0.5))\n plt.axvline((xx[med_ind]+xx[med_ind+1])/2, ls=\"--\", c=c)\n siglo = (1-sigfrac)/2.0\n sighi = (1+sigfrac)/2.0\n lo_ind = np.argmin(abs(cdf-siglo))\n hi_ind = np.argmin(abs(cdf-sighi))\n plt.axvline((xx[lo_ind]+xx[lo_ind+1])/2, ls=\"--\", c=c)\n plt.axvline((xx[hi_ind]+xx[hi_ind+1])/2, ls=\"--\", c=c)\n\nplt.figure(figsize=(3, 6))\n\nplt.subplot(311)\nplot_cdf(sampler, 'c0', 100, 'k')\nplt.text(0.1, 0.89, \"c0\")\nplt.subplot(312)\nplot_cdf(sampler, 'c1', 100, 'r')\nplt.text(-2.9, 0.89, \"c1\")\nplt.ylabel(\"CDF\")\nplt.subplot(313)\nplot_cdf(sampler, 'c2', 100, 'b')\nplt.text(2.61, 0.89, \"c2\")\nplt.xlabel(\"Parameter value\")\n\nplt.subplots_adjust(left=0.2)\nplt.savefig(\"_generated/example_plot_mcmc_cdf.png\")\nplt.close(\"all\")\n\n\nprint(\"Done\")\n","sub_path":"docs/gen_plots.py","file_name":"gen_plots.py","file_ext":"py","file_size_in_byte":10738,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"301897066","text":"names=[]\r\nscores=[]\r\navg=0\r\n\r\n# 計算平均值的函式\r\ndef average(scores):\r\n total = 0\r\n n = len(scores)\r\n # average score\r\n for item in scores:\r\n total = total+item\r\n average = total/n\r\n return average\r\n\r\n# 計算最高分的函式\r\ndef highestscore(scores):\r\n highest=0\r\n n = len(scores)\r\n for i in range(n):\r\n if scores[i] > highest:\r\n highest = scores[i] \r\n highestname = names[i]\r\n person = list()\r\n person.append(highestname)\r\n person.append(highest)\r\n return person\r\n \r\n# 計算最低分的函式\r\ndef lowestscore(scores):\r\n lowest = 100\r\n n = len(scores)\r\n for i in range(n):\r\n if scores[i] < lowest:\r\n lowest = scores[i]\r\n lowestname = names[i]\r\n person = list()\r\n person.append(lowestname)\r\n person.append(lowest)\r\n return person\r\n\r\n# 主程式\r\n# 詢問班上人數\r\nn = input('How many people in this class? ')\r\nn = int(n)\r\n\r\n# 利用迴圈和input讓班上同學輸入名字和成績\r\nfor i in range(n):\r\n name = input('Please input the name: ')\r\n names.append(name)\r\n\r\n score = input('Please input the score: ')\r\n score = int(score)\r\n scores.append(score)\r\n \r\n#使用前面定義的函式直接找出最高、最低、平均\r\nave = average(scores)\r\nhigh = highestscore(scores)\r\nlow = lowestscore(scores)\r\n \r\nprint(\"The average is\", ave) \r\nprint(high[0], 'got the highest score', high[1])\r\nprint(low[0], \"got the lowest score\", low[1])\r\n","sub_path":"score_2list_function.py","file_name":"score_2list_function.py","file_ext":"py","file_size_in_byte":1510,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"648059323","text":"import os\nfrom flask import Flask, request, abort, jsonify, redirect\nfrom flask_sqlalchemy import SQLAlchemy\nfrom sqlalchemy import exc\nfrom flask_cors import CORS\n\nfrom models import setup_db, Trainer, Client, Session\nfrom auth import AuthError, requires_auth, LOGIN_URI\n\n\ndef create_app(test_config=None):\n # create and configure the app\n app = Flask(__name__)\n setup_db(app)\n CORS(app, resources={r\"/*\": {'origins': '*'}})\n\n @app.after_request\n def after_request(response):\n response.headers.add('Access-Control-Allow-Headers',\n 'Content-Type, Authorization, true')\n response.headers.add('Access-Control-Allow-Headers',\n 'GET, PATCH, POST, DELETE, OPTIONS')\n return response\n\n @app.route('/')\n def index():\n return redirect(LOGIN_URI, 302)\n \n @app.route('/welcome')\n def welcome():\n return jsonify({\n 'success': True, \n 'message': 'Login was successful, welcome!'\n })\n\n ###############################\n # trainers related end-points #\n ###############################\n @app.route('/trainers', methods=['GET'])\n @requires_auth('get:trainers')\n def get_trainers():\n if request.get_json():\n abort(405)\n\n try:\n trainers = Trainer.query.all()\n if trainers is None:\n raise AuthError({\n 'code': 'no_trainers',\n 'description': 'There are no trainers on system yet.'\n }, 404)\n except AuthError as e:\n abort(e.status_code, e.error)\n\n trainers_formatted = []\n\n for trainer in trainers:\n trainers_formatted.append(trainer.format())\n \n return jsonify({\n 'success': True,\n 'trainers': trainers_formatted\n })\n \n @app.route('/trainers', methods=['POST'])\n @requires_auth('post:trainers')\n def add_trainer():\n request_data = request.get_json()\n\n try:\n if len(request_data) > 3:\n raise AuthError({'description': 'Please include only the name, gender, and age of trainer.'}, 400)\n if not request_data['name']:\n raise AuthError({'description': 'Trainer name is missing.'}, 400)\n if not request_data['gender']:\n raise AuthError({'description': 'Trainer gender is missing.'}, 400)\n if not request_data['age']:\n raise AuthError({'description': 'Trainer age is missing.'}, 400)\n except AuthError as e:\n abort(e.status_code, e.error)\n\n new_trainer = Trainer()\n new_trainer.name = request_data['name']\n new_trainer.gender = request_data['gender']\n new_trainer.age = request_data['age']\n\n new_trainer.insert()\n \n return jsonify({\n 'success': True,\n 'new_trainer': new_trainer.format()\n })\n\n @app.route('/trainers/', methods=['DELETE'])\n @requires_auth('delete:trainers')\n def delete_trainer(id):\n try:\n target_trainer = Trainer.query.filter_by(id=id).first()\n if target_trainer is None:\n raise AuthError({\n 'code': 'trainer_not_found',\n 'description': 'There is no trainer with the reuqested id to delete.'\n }, 404)\n except AuthError as e:\n abort(e.status_code, e.error)\n\n target_trainer.delete()\n\n return jsonify({\n 'success': True,\n 'deleted_trainer': target_trainer.format()\n })\n\n @app.route('/trainers/', methods=['PATCH'])\n @requires_auth('patch:trainers')\n def patch_trainer(id):\n request_data = request.get_json()\n\n try:\n target_trainer = Trainer.query.filter_by(id=id).first()\n if target_trainer is None:\n raise AuthError({\n 'code': 'trainer_not_found',\n 'description': 'There is no trainer with the reuqested id to modify.'\n }, 404)\n except AuthError as e:\n abort(e.status_code, e.error)\n\n if 'name' in request_data:\n target_trainer.name = request_data['name']\n if 'gender' in request_data:\n target_trainer.gender = request_data['gender']\n if 'age' in request_data:\n target_trainer.age = request_data['age']\n\n target_trainer.update()\n\n return jsonify({\n 'success': True,\n 'modified_trainer': target_trainer.format()\n })\n \n ##############################\n # clients related end-points #\n ##############################\n @app.route('/clients', methods=['GET'])\n @requires_auth('get:clients')\n def get_clients():\n if request.get_json():\n abort(405)\n\n try:\n clients = Client.query.all()\n if clients is None:\n raise AuthError({\n 'code': 'no_clients',\n 'description': 'There are no clients on system yet.'\n }, 404)\n except AuthError as e:\n abort(e.status_code, e.error)\n\n clients_formatted = []\n\n for client in clients:\n clients_formatted.append(client.format())\n \n return jsonify({\n 'success': True,\n 'clients': clients_formatted\n })\n \n @app.route('/clients', methods=['POST'])\n @requires_auth('post:clients')\n def add_client():\n request_data = request.get_json()\n\n try:\n if len(request_data) > 3:\n raise AuthError({'description': 'Please include only the name, gender, and age of client.'}, 400)\n if not request_data['name']:\n raise AuthError({'description': 'Client name is missing.'}, 400)\n if not request_data['gender']:\n raise AuthError({'description': 'Client gender is missing.'}, 400)\n if not request_data['age']:\n raise AuthError({'description': 'Client age is missing.'}, 400)\n except AuthError as e:\n abort(e.status_code, e.error)\n\n new_client = Client()\n new_client.name = request_data['name']\n new_client.gender = request_data['gender']\n new_client.age = request_data['age']\n\n new_client.insert()\n \n return jsonify({\n 'success': True,\n 'new_client': new_client.format()\n })\n\n @app.route('/clients/', methods=['DELETE'])\n @requires_auth('delete:clients')\n def delete_client(id):\n try:\n target_client = Client.query.filter_by(id=id).first()\n if target_client is None:\n raise AuthError({\n 'code': 'client_not_found',\n 'description': 'There is no client with the reuqested id to delete.'\n }, 404)\n except AuthError as e:\n abort(e.status_code, e.error)\n\n target_client.delete()\n\n return jsonify({\n 'success': True,\n 'deleted_client': target_client.format()\n })\n\n @app.route('/clients/', methods=['PATCH'])\n @requires_auth('patch:clients')\n def patch_client(id):\n request_data = request.get_json()\n\n try:\n target_client = Client.query.filter_by(id=id).first()\n if target_client is None:\n raise AuthError({\n 'code': 'client_not_found',\n 'description': 'There is no client with the reuqested id to modify.'\n }, 404)\n except AuthError as e:\n abort(e.status_code, e.error)\n\n if 'name' in request_data:\n target_client.name = request_data['name']\n if 'gender' in request_data:\n target_client.gender = request_data['gender']\n if 'age' in request_data:\n target_client.age = request_data['age']\n\n target_client.update()\n\n return jsonify({\n 'success': True,\n 'modified_client': target_client.format()\n })\n\n ###############################\n # sessions related end-points #\n ###############################\n @app.route('/sessions', methods=['GET'])\n @requires_auth('get:sessions')\n def get_sessions():\n if request.get_json():\n abort(405)\n\n try:\n sessions = Session.query.all()\n if sessions is None:\n raise AuthError({\n 'code': 'no_sessions',\n 'description': 'There are no sessions on system yet.'\n }, 404)\n except AuthError as e:\n abort(e.status_code, e.error)\n\n sessions_formatted = []\n\n for session in sessions:\n sessions_formatted.append(session.format())\n \n return jsonify({\n 'success': True,\n 'sessions': sessions_formatted\n })\n \n @app.route('/sessions', methods=['POST'])\n @requires_auth('post:sessions')\n def add_session():\n request_data = request.get_json()\n\n try:\n if len(request_data) > 3:\n raise AuthError({'description': 'Please include only the name, trainer_id, and client_id of the session.'}, 400)\n if not request_data['name']:\n raise AuthError({'description': 'Session name is missing.'}, 400)\n if not request_data['trainer_id']:\n raise AuthError({'description': 'Session trainer id is missing.'}, 400)\n if not request_data['client_id']:\n raise AuthError({'description': 'Session client id is missing.'}, 400)\n except AuthError as e:\n abort(e.status_code, e.error)\n\n new_session = Session()\n new_session.name = request_data['name']\n new_session.trainer_id = request_data['trainer_id']\n new_session.client_id = request_data['client_id']\n\n new_session.insert()\n \n return jsonify({\n 'success': True,\n 'new_session': new_session.format()\n })\n\n @app.route('/sessions/', methods=['DELETE'])\n @requires_auth('delete:sessions')\n def delete_session(id):\n try:\n target_session = Session.query.filter_by(id=id).first()\n if target_session is None:\n raise AuthError({\n 'code': 'session_not_found',\n 'description': 'There is no session with the reuqested id to delete.'\n }, 404)\n except AuthError as e:\n abort(e.status_code, e.error)\n\n target_session.delete()\n\n return jsonify({\n 'success': True,\n 'deleted_session': target_session.format()\n })\n\n @app.route('/sessions/', methods=['PATCH'])\n @requires_auth('patch:sessions')\n def patch_session(id):\n request_data = request.get_json()\n\n try:\n target_session = Session.query.filter_by(id=id).first()\n if target_session is None:\n raise AuthError({\n 'code': 'session_not_found',\n 'description': 'There is no session with the reuqested id to modify.'\n }, 404)\n except AuthError as e:\n abort(e.status_code, e.error)\n\n if 'name' in request_data:\n target_session.name = request_data['name']\n if 'trainer_id' in request_data:\n target_session.trainer_id = request_data['trainer_id']\n if 'client_id' in request_data:\n target_session.client_id = request_data['client_id']\n\n target_session.update()\n\n return jsonify({\n 'success': True,\n 'modified_session': target_session.format()\n })\n\n ##################\n # error handling #\n ##################\n @app.errorhandler(400)\n def authError_bad_request(error):\n return jsonify({\n \"success\": False, \n \"error\": 400,\n \"message\": error.description\n }), 400\n\n @app.errorhandler(401)\n def authError_unauthorized(error):\n return jsonify({\n \"success\": False, \n \"error\": 401,\n \"message\": error.description\n }), 401\n\n @app.errorhandler(404)\n def authError_not_found(error):\n return jsonify({\n \"success\": False, \n \"error\": 404,\n \"message\": error.description\n }), 404\n \n @app.errorhandler(405)\n def method_not_allowed(error):\n return jsonify({\n \"success\": False,\n \"error\": 405,\n \"message\": \"method not allowed\"\n }), 405\n\n\n return app\n\n\napp = create_app()\n\n\nif __name__ == '__main__':\n app.run(host='0.0.0.0', port=8080, debug=True)","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":12976,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"169489205","text":"import os\nimport pygame\nimport time\nimport cv2\next = ['.JPG']\nopen_dir = r'C:\\Users\\adff\\Downloads\\pictures'\n\ndef FindImageFilenames():\n lst = []\n for folder, dirs, files in os.walk(open_dir):\n for file in files:\n for index, extension in enumerate(ext):\n if file.endswith(extension):\n full_path = os.path.join(folder, file)\n file_name = os.path.basename(full_path)\n lst += [full_path]\n return lst\n\n\ndef Main():\n filenames = FindImageFilenames()\n pygame.init()\n for index, file_name in enumerate(filenames):\n im = cv2.imread(file_name)\n img_h, img_w, _ = im.shape\n width = pygame.display.Info().current_w\n height = pygame.display.Info().current_h\n screen = pygame.display.set_mode((width,height), pygame.FULLSCREEN)\n pygame.mouse.set_visible(False)\n pygame.event.set_grab(True)\n while True:\n filename = filenames.pop(0)\n filenames.append(filename)\n image = pygame.image.load(filename)\n image = pygame.transform.scale(image, (img_w,img_h))\n screen.blit(image,(0,0))\n pygame.display.update()\n for n in range(10):\n pygame.event.pump()\n keys = pygame.key.get_pressed()\n if keys[pygame.K_ESCAPE]:\n return\n time.sleep(1)\n\n\nif __name__ == \"__main__\":\n Main()\n","sub_path":"photoframe_w_pygame.py","file_name":"photoframe_w_pygame.py","file_ext":"py","file_size_in_byte":1297,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"429531205","text":"# @Author: yfeng\n# @Date: 2017-12-09T20:52:21+08:00\n# @Last modified by:\n# @Last modified time: 2018-02-03T00:10:41+08:00\n\n\n\nimport numpy as np\nimport matplotlib.image as mpimg\nfrom scipy import misc\n\nascii_char = list(\"$@B%8&WM#*oahkbdpqwmZO0QLCJUYXzcvunxrjft/\\|()1{}[]?-_+~<>i!lI;:,\\\"^`'. \")\n\ndef read_fig(path):\n # RGB three channels\n rgb_img = mpimg.imread(path)\n gray_img = rgb2gray(rgb_img)\n return gray_img\n\ndef rgb2gray(img):\n return np.dot(img[...,:3], [0.299, 0.587, 0.114])\n\ndef resize_img(img, height, width):\n return misc.imresize(img, (height, width))\n\ndef img2char(img):\n region_size = 256 / len(ascii_char)\n h, w = img.shape\n txt = ''\n for i in range(h):\n for j in range(w):\n txt += ascii_char[int(img[i,j]/region_size)]\n txt += '\\n'\n return txt\n\ndef main():\n img = read_fig(r'C:\\Users\\yfeng\\Desktop\\20180203001015.png')\n if height is not None and width is not None:\n img = resize_img(img, height, width)\n result = img2char(img)\n\n with open(r'C:\\Users\\yfeng\\Desktop\\result.txt','w') as f:\n f.write(result)\n\nif __name__ == \"__main__\":\n height = 60\n width = 80\n main()\n","sub_path":"python/picture2char.py","file_name":"picture2char.py","file_ext":"py","file_size_in_byte":1178,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"541179713","text":"\"\"\"\r\nCopyright (c) 2017, Battelle Memorial Institute\r\nAll rights reserved.\r\n\r\nRedistribution and use in source and binary forms, with or without\r\nmodification, are permitted provided that the following conditions are met:\r\n\r\n1. Redistributions of source code must retain the above copyright notice, this\r\n list of conditions and the following disclaimer.\r\n2. Redistributions in binary form must reproduce the above copyright notice,\r\n this list of conditions and the following disclaimer in the documentation\r\n and/or other materials provided with the distribution.\r\n\r\nTHIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\" AND\r\nANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\r\nWARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\r\nDISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR\r\nANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\r\n(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\r\nLOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\r\nON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\r\n(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\r\nSOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\r\n\r\nThe views and conclusions contained in the software and documentation are those\r\nof the authors and should not be interpreted as representing official policies,\r\neither expressed or implied, of the FreeBSD Project.\r\n\r\nThis material was prepared as an account of work sponsored by an agency of the\r\nUnited States Government. Neither the United States Government nor the United\r\nStates Department of Energy, nor Battelle, nor any of their employees, nor any\r\njurisdiction or organization that has cooperated in the development of these\r\nmaterials, makes any warranty, express or implied, or assumes any legal\r\nliability or responsibility for the accuracy, completeness, or usefulness or\r\nany information, apparatus, product, software, or process disclosed, or\r\nrepresents that its use would not infringe privately owned rights.\r\n\r\nReference herein to any specific commercial product, process, or service by\r\ntrade name, trademark, manufacturer, or otherwise does not necessarily\r\nconstitute or imply its endorsement, recommendation, or favoring by the\r\nUnited States Government or any agency thereof, or Battelle Memorial Institute.\r\nThe views and opinions of authors expressed herein do not necessarily state or\r\nreflect those of the United States Government or any agency thereof.\r\n\r\nPACIFIC NORTHWEST NATIONAL LABORATORY\r\noperated by\r\nBATTELLE\r\nfor the\r\nUNITED STATES DEPARTMENT OF ENERGY\r\nunder Contract DE-AC05-76RL01830\r\n\"\"\"\r\nimport logging\r\nfrom datetime import timedelta as td\r\nfrom volttron.platform.agent.math_utils import mean\r\n\r\nECON2 = \"Not Economizing When Unit Should Dx\"\r\nECON3 = \"Economizing When Unit Should Not Dx\"\r\nDX = \"/diagnostic message\"\r\nEI = \"/energy impact\"\r\n\r\n\r\ndef create_table_key(table_name, timestamp):\r\n return \"&\".join([table_name, timestamp.isoformat()])\r\n\r\n\r\nclass EconCorrectlyOn(object):\r\n \"\"\"Air-side HVAC economizer diagnostic for AHU/RTU systems.\r\n\r\n EconCorrectlyOn uses metered data from a BAS or controller to diagnose\r\n if an AHU/RTU is economizing when it should.\r\n \"\"\"\r\n\r\n def __init__(self, oaf_economizing_threshold, open_damper_threshold,\r\n minimum_damper_setpoint, data_window, no_required_data,\r\n cfm, eer, analysis):\r\n # Initialize data arrays\r\n self.oat_values = []\r\n self.rat_values = []\r\n self.mat_values = []\r\n self.fan_spd_values = []\r\n self.oad_values = []\r\n self.timestamp = []\r\n\r\n # Initialize not_cooling and not_economizing flags\r\n self.not_cooling = None\r\n self.not_economizing = None\r\n\r\n\r\n self.open_damper_threshold = open_damper_threshold\r\n self.oaf_economizing_threshold = oaf_economizing_threshold\r\n self.minimum_damper_setpoint = minimum_damper_setpoint\r\n self.data_window = data_window\r\n self.no_required_data = no_required_data\r\n self.cfm = cfm\r\n self.eer = eer\r\n\r\n self.analysis = analysis\r\n self.max_dx_time = td(minutes=60) if td(minutes=60) > data_window else data_window * 3 / 2\r\n self.not_economizing_dict = {key: 15.0 for key in self.oaf_economizing_threshold}\r\n self.not_cooling_dict = {key: 14.0 for key in self.oaf_economizing_threshold}\r\n self.inconsistent_date = {key: 13.2 for key in self.oaf_economizing_threshold}\r\n\r\n # Application result messages\r\n self.alg_result_messages = [\r\n \"Conditions are favorable for economizing but the the OAD is frequently below 100%.\",\r\n \"No problems detected.\",\r\n \"Conditions are favorable for economizing and OAD is 100% but the OAF is too low.\"\r\n ]\r\n\r\n def econ_alg2(self, dx_result, cooling_call, oat, rat, mat, oad, econ_condition, cur_time, fan_sp):\r\n \"\"\"\r\n Check app. pre-quisites and assemble data set for analysis.\r\n :param dx_result:\r\n :param cooling_call:\r\n :param oat:\r\n :param rat:\r\n :param mat:\r\n :param oad:\r\n :param econ_condition:\r\n :param cur_time:\r\n :param fan_sp:\r\n :return:\r\n \"\"\"\r\n dx_result, economizing = self.economizer_conditions(dx_result, cooling_call, econ_condition, cur_time)\r\n if not economizing:\r\n return dx_result\r\n\r\n self.oat_values.append(oat)\r\n self.mat_values.append(mat)\r\n self.rat_values.append(rat)\r\n self.oad_values.append(oad)\r\n self.timestamp.append(cur_time)\r\n\r\n fan_sp = fan_sp / 100.0 if fan_sp is not None else 1.0\r\n self.fan_spd_values.append(fan_sp)\r\n\r\n elapsed_time = self.timestamp[-1] - self.timestamp[0]\r\n\r\n if elapsed_time >= self.data_window and len(self.timestamp) >= self.no_required_data:\r\n table_key = create_table_key(self.analysis, self.timestamp[-1])\r\n\r\n if elapsed_time > self.max_dx_time:\r\n dx_result.insert_table_row(table_key, {ECON2 + DX: self.inconsistent_date})\r\n self.clear_data()\r\n return dx_result\r\n dx_result = self.not_economizing_when_needed(dx_result, table_key)\r\n return dx_result\r\n\r\n return dx_result\r\n\r\n def not_economizing_when_needed(self, dx_result, table_key):\r\n \"\"\"\r\n If the detected problems(s) are consistent then generate a fault\r\n message(s).\r\n :param dx_result:\r\n :param table_key:\r\n :return:\r\n \"\"\"\r\n oaf = [(m - r) / (o - r) for o, r, m in zip(self.oat_values, self.rat_values, self.mat_values)]\r\n avg_oaf = max(0.0, min(100.0, mean(oaf)*100.0))\r\n avg_damper_signal = mean(self.oad_values)\r\n diagnostic_msg = {}\r\n energy_impact = {}\r\n thresholds = zip(self.open_damper_threshold.items(), self.oaf_economizing_threshold.items())\r\n for (key, damper_thr), (key2, oaf_thr) in thresholds:\r\n if avg_damper_signal < damper_thr:\r\n msg = \"{} - {}: {}\".format(ECON2, key, self.alg_result_messages[0])\r\n # color_code = \"RED\"\r\n result = 11.1\r\n energy = self.energy_impact_calculation()\r\n else:\r\n if avg_oaf < oaf_thr:\r\n msg = \"{} - {}: {} - OAF={}\".format(ECON2, key, self.alg_result_messages[2], avg_oaf)\r\n # color_code = \"RED\"\r\n result = 12.1\r\n energy = self.energy_impact_calculation()\r\n else:\r\n msg = \"{} - {}: {}\".format(ECON2, key, self.alg_result_messages[1])\r\n # color_code = \"GREEN\"\r\n result = 10.0\r\n energy = 0.0\r\n dx_result.log(msg)\r\n diagnostic_msg.update({key: result})\r\n energy_impact.update({key: energy})\r\n\r\n dx_table = {\r\n ECON2 + DX: diagnostic_msg,\r\n ECON2 + EI: energy_impact\r\n }\r\n dx_result.insert_table_row(table_key, dx_table)\r\n self.clear_data()\r\n return dx_result\r\n\r\n def economizer_conditions(self, dx_result, cooling_call, econ_condition, cur_time):\r\n \"\"\"\r\n Check if unit is in a cooling mode.\r\n :param dx_result:\r\n :param cooling_call:\r\n :param econ_condition:\r\n :param cur_time:\r\n :return:\r\n \"\"\"\r\n if not cooling_call:\r\n dx_result.log(\"{}: not cooling at {}\".format(ECON2, cur_time))\r\n if self.not_cooling is None:\r\n self.not_cooling = cur_time\r\n if cur_time - self.not_cooling >= self.data_window:\r\n dx_result.log(\"{}: no cooling during data set - reinitialize.\".format(ECON2))\r\n dx_table = {ECON2 + DX: self.not_cooling_dict}\r\n table_key = create_table_key(self.analysis, cur_time)\r\n dx_result.insert_table_row(table_key, dx_table)\r\n self.clear_data()\r\n return dx_result, False\r\n else:\r\n self.not_cooling = None\r\n\r\n if not econ_condition:\r\n dx_result.log(\"{}: not economizing at {}.\".format(ECON2, cur_time))\r\n if self.not_economizing is None:\r\n self.not_economizing = cur_time\r\n if cur_time - self.not_economizing >= self.data_window:\r\n dx_result.log(\"{}: no economizing during data set - reinitialize.\".format(ECON2))\r\n dx_table = {ECON2 + DX: self.not_economizing_dict}\r\n table_key = create_table_key(self.analysis, cur_time)\r\n dx_result.insert_table_row(table_key, dx_table)\r\n self.clear_data()\r\n return dx_result, False\r\n else:\r\n self.not_economizing = None\r\n return dx_result, True\r\n\r\n def energy_impact_calculation(self):\r\n ei = 0.0\r\n energy_calc = [1.08 * s * self.cfm * (m - o) / (1000.0 * self.eer)\r\n for m, o, s in zip(self.mat_values, self.oat_values, self.fan_spd_values)\r\n if (m - o) > 0]\r\n if energy_calc:\r\n avg_step = (self.timestamp[-1] - self.timestamp[0]).total_seconds() / 60 if len(self.timestamp) > 1 else 1\r\n dx_time = (len(energy_calc) - 1) * avg_step if len(energy_calc) > 1 else 1.0\r\n ei = (sum(energy_calc) * 60.0) / (len(energy_calc) * dx_time)\r\n ei = round(ei, 2)\r\n return ei\r\n\r\n def clear_data(self):\r\n \"\"\"\r\n Reinitialize data arrays.\r\n :return:\r\n \"\"\"\r\n self.oad_values = []\r\n self.oat_values = []\r\n self.rat_values = []\r\n self.mat_values = []\r\n self.fan_spd_values = []\r\n self.timestamp = []\r\n self.not_economizing = None\r\n self.not_cooling = None\r\n\r\n\r\nclass EconCorrectlyOff(object):\r\n \"\"\"\r\n Air-side HVAC economizer diagnostic for AHU/RTU systems.\r\n\r\n EconCorrectlyOff uses metered data from a BAS or controller to diagnose\r\n if an AHU/RTU is economizing when it should not.\r\n \"\"\"\r\n def __init__(self, data_window, no_required_data, min_damper_sp,\r\n excess_damper_threshold, desired_oaf, cfm, eer, analysis):\r\n # Initialize data arrays.\r\n self.oat_values = []\r\n self.rat_values = []\r\n self.mat_values = []\r\n self.oad_values = []\r\n self.fan_spd_values = []\r\n self.timestamp = []\r\n\r\n self.economizing = None\r\n\r\n # Application result messages\r\n self.alg_result_messages = \\\r\n [\"The OAD should be at the minimum position but is significantly above this value.\",\r\n \"No problems detected.\",\r\n \"Inconclusive results, could not verify the status of the economizer.\"]\r\n # Map configurable parameters\r\n self.max_dx_time = td(minutes=60) if td(minutes=60) > data_window else data_window * 3/2\r\n self.data_window = data_window\r\n self.no_required_data = no_required_data\r\n self.min_damper_sp = min_damper_sp\r\n self.excess_damper_threshold = excess_damper_threshold\r\n self.economizing_dict = {key: 25.0 for key in self.excess_damper_threshold}\r\n self.inconsistent_date = {key: 23.2 for key in self.excess_damper_threshold}\r\n self.desired_oaf = desired_oaf\r\n self.analysis = analysis\r\n self.cfm = cfm\r\n self.eer = eer\r\n\r\n def econ_alg3(self, dx_result, oat, rat, mat, oad, econ_condition, cur_time, fan_sp):\r\n \"\"\"\r\n Check app. pre-quisites and assemble data set for analysis.\r\n :param dx_result:\r\n :param oat:\r\n :param rat:\r\n :param mat:\r\n :param oad:\r\n :param econ_condition:\r\n :param cur_time:\r\n :param fan_sp:\r\n :return:\r\n \"\"\"\r\n dx_result, economizing = self.economizer_conditions(dx_result, econ_condition, cur_time)\r\n if economizing:\r\n return dx_result\r\n\r\n self.oad_values.append(oad)\r\n self.oat_values.append(oat)\r\n self.mat_values.append(mat)\r\n self.rat_values.append(rat)\r\n self.timestamp.append(cur_time)\r\n\r\n fan_sp = fan_sp / 100.0 if fan_sp is not None else 1.0\r\n self.fan_spd_values.append(fan_sp)\r\n\r\n elapsed_time = self.timestamp[-1] - self.timestamp[0]\r\n\r\n if elapsed_time >= self.data_window and len(self.timestamp) >= self.no_required_data:\r\n table_key = create_table_key(self.analysis, self.timestamp[-1])\r\n\r\n if elapsed_time > self.max_dx_time:\r\n dx_result.insert_table_row(table_key, {ECON3 + DX: self.inconsistent_date})\r\n self.clear_data()\r\n return dx_result\r\n\r\n dx_result = self.economizing_when_not_needed(dx_result, table_key)\r\n return dx_result\r\n return dx_result\r\n\r\n def economizing_when_not_needed(self, dx_result, table_key):\r\n \"\"\"\r\n If the detected problems(s) are consistent then generate a\r\n fault message(s).\r\n :param dx_result:\r\n :param table_key:\r\n :return:\r\n \"\"\"\r\n desired_oaf = self.desired_oaf / 100.0\r\n avg_damper = mean(self.oad_values)\r\n diagnostic_msg = {}\r\n energy_impact = {}\r\n for sensitivity, threshold in self.excess_damper_threshold.items():\r\n if avg_damper > threshold:\r\n msg = \"{} - {}: {}\".format(ECON3, sensitivity, self.alg_result_messages[0])\r\n # color_code = \"RED\"\r\n result = 21.1\r\n energy = self.energy_impact_calculation(desired_oaf)\r\n else:\r\n msg = \"{} - {}: {}\".format(ECON3, sensitivity, self.alg_result_messages[1])\r\n # color_code = \"GREEN\"\r\n result = 20.0\r\n energy = 0.0\r\n dx_result.log(msg)\r\n diagnostic_msg.update({sensitivity: result})\r\n energy_impact.update({sensitivity: energy})\r\n\r\n dx_table = {\r\n ECON3 + DX: diagnostic_msg,\r\n ECON3 + EI: energy_impact\r\n }\r\n dx_result.insert_table_row(table_key, dx_table)\r\n self.clear_data()\r\n return dx_result\r\n\r\n def clear_data(self):\r\n \"\"\"\r\n Reinitialize data arrays.\r\n :return:\r\n \"\"\"\r\n self.oad_values = []\r\n self.oat_values = []\r\n self.rat_values = []\r\n self.mat_values = []\r\n self.fan_spd_values = []\r\n self.timestamp = []\r\n self.economizing = None\r\n\r\n def energy_impact_calculation(self, desired_oaf):\r\n ei = 0.0\r\n energy_calc = [\r\n (1.08 * spd * self.cfm * (m - (o * desired_oaf + (r * (1.0 - desired_oaf))))) / (1000.0 * self.eer)\r\n for m, o, r, spd in zip(self.mat_values, self.oat_values, self.rat_values, self.fan_spd_values)\r\n if (m - (o * desired_oaf + (r * (1.0 - desired_oaf)))) > 0\r\n ]\r\n if energy_calc:\r\n avg_step = (self.timestamp[-1] - self.timestamp[0]).total_seconds() / 60 if len(self.timestamp) > 1 else 1\r\n dx_time = (len(energy_calc) - 1) * avg_step if len(energy_calc) > 1 else 1.0\r\n ei = (sum(energy_calc) * 60.0) / (len(energy_calc) * dx_time)\r\n ei = round(ei, 2)\r\n return ei\r\n\r\n def economizer_conditions(self, dx_result, econ_condition, cur_time):\r\n if econ_condition:\r\n dx_result.log(\"{}: economizing, for data {} --{}.\".format(ECON3, econ_condition, cur_time))\r\n if self.economizing is None:\r\n self.economizing = cur_time\r\n if cur_time - self.economizing >= self.data_window:\r\n dx_result.log(\"{}: economizing - reinitialize!\".format(ECON3))\r\n dx_table = {ECON3 + DX: self.economizing_dict}\r\n table_key = create_table_key(self.analysis, cur_time)\r\n dx_result.insert_table_row(table_key, dx_table)\r\n self.clear_data()\r\n return dx_result, True\r\n else:\r\n self.economizing = None\r\n return dx_result, False\r\n","sub_path":"pnnl/EconomizerRCxAgent/economizer/diagnostics/economizer_dx.py","file_name":"economizer_dx.py","file_ext":"py","file_size_in_byte":17282,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"477689820","text":"# The contents of this file are subject to the Mozilla Public\n# License Version 1.1 (the \"License\"); you may not use this file\n# except in compliance with the License. You may obtain a copy of\n# the License at http://www.mozilla.org/MPL/\n#\n# Software distributed under the License is distributed on an \"AS\n# IS\" basis, WITHOUT WARRANTY OF ANY KIND, either express or\n# implied. See the License for the specific language governing\n# rights and limitations under the License.\n#\n# The Initial Owner of the Original Code is European Environment\n# Agency (EEA). Portions created by Eau de Web are\n# Copyright (C) European Environment Agency. All\n# Rights Reserved.\n#\n# Authors:\n#\n# Alex Morega, Eau de Web\n\nimport re\nfrom unittest import TestSuite, makeSuite\nfrom BeautifulSoup import BeautifulSoup\n\nfrom Products.Naaya.tests.NaayaFunctionalTestCase import NaayaFunctionalTestCase\n\nclass NyEventFunctionalTestCase(NaayaFunctionalTestCase):\n \"\"\" TestCase for NaayaContent object \"\"\"\n\n def afterSetUp(self):\n from Products.Naaya.NyFolder import addNyFolder\n from naaya.content.event.event_item import addNyEvent\n addNyFolder(self.portal, 'myfolder', contributor='contributor', submitted=1)\n addNyEvent(self.portal.myfolder, id='myevent', title='My event', submitted=1, contributor='contributor')\n import transaction; transaction.commit()\n\n def beforeTearDown(self):\n self.portal.manage_delObjects(['myfolder'])\n import transaction; transaction.commit()\n\n def test_add(self):\n self.browser_do_login('contributor', 'contributor')\n self.browser.go('http://localhost/portal/info/event_add_html')\n self.failUnless('

Submit Event

' in self.browser.get_html())\n form = self.browser.get_form('frmAdd')\n expected_controls = set([\n 'lang', 'title:utf8:ustring', 'description:utf8:ustring', 'coverage:utf8:ustring',\n 'keywords:utf8:ustring', 'releasedate', 'discussion:boolean',\n ])\n found_controls = set(c.name for c in form.controls)\n self.failUnless(expected_controls.issubset(found_controls),\n 'Missing form controls: %s' % repr(expected_controls - found_controls))\n\n self.browser.clicked(form, self.browser.get_form_field(form, 'title'))\n form['title:utf8:ustring'] = 'test_event'\n form['description:utf8:ustring'] = 'test_event_description'\n form['coverage:utf8:ustring'] = 'test_event_coverage'\n form['keywords:utf8:ustring'] = 'keyw1, keyw2'\n form['details:utf8:ustring'] = 'test_event_details'\n\n event_types = form.find_control('event_type:utf8:ustring').get_items()[1:]\n labels = set(map(lambda e: e.get_labels()[0].text, event_types))\n ids = set(map(lambda e: e.name, event_types))\n self.failUnlessEqual(labels, set(['Conference', 'Other', 'Meeting', 'Event']))\n self.failUnlessEqual(ids, set(['conference', 'other', 'meeting', 'event']))\n\n form['event_type:utf8:ustring'] = ['conference']\n\n self.browser.submit()\n html = self.browser.get_html()\n self.failUnless('The administrator will analyze your request and you will be notified about the result shortly.' in html)\n\n self.failUnlessEqual(self.portal.info.testevent.event_type, 'conference')\n self.portal.info.testevent.approveThis()\n\n self.browser.go('http://localhost/portal/info/testevent')\n html = self.browser.get_html()\n self.failUnless(re.search(r'

.*test_event.*

', html, re.DOTALL))\n self.failUnless('test_event_description' in html)\n self.failUnless('test_event_coverage' in html)\n self.failUnless('keyw1, keyw2' in html)\n self.failUnless('test_event_details' in html)\n\n self.browser_do_logout()\n\n def test_add_error(self):\n self.browser_do_login('contributor', 'contributor')\n self.browser.go('http://localhost/portal/myfolder/event_add_html')\n\n form = self.browser.get_form('frmAdd')\n self.browser.clicked(form, self.browser.get_form_field(form, 'title'))\n # enter no values in the fields\n self.browser.submit()\n\n html = self.browser.get_html()\n self.failUnless('The form contains errors' in html)\n self.failUnless('Value required for \"Title\"' in html)\n\n def test_edit(self):\n self.browser_do_login('admin', '')\n\n self.browser.go('http://localhost/portal/myfolder/myevent/edit_html')\n form = self.browser.get_form('frmEdit')\n\n self.failUnlessEqual(form['title:utf8:ustring'], 'My event')\n\n form['title:utf8:ustring'] = 'new_event_title'\n self.browser.clicked(form, self.browser.get_form_field(form, 'title:utf8:ustring'))\n self.browser.submit()\n\n self.failUnlessEqual(self.portal.myfolder.myevent.title, 'new_event_title')\n\n self.browser.go('http://localhost/portal/myfolder/myevent/edit_html?lang=fr')\n form = self.browser.get_form('frmEdit')\n form['title:utf8:ustring'] = 'french_title'\n self.browser.clicked(form, self.browser.get_form_field(form, 'title:utf8:ustring'))\n self.browser.submit()\n\n self.failUnlessEqual(self.portal.myfolder.myevent.title, 'new_event_title')\n self.failUnlessEqual(self.portal.myfolder.myevent.getLocalProperty('title', 'fr'), 'french_title')\n\n self.browser_do_logout()\n\n def test_edit_error(self):\n self.browser_do_login('admin', '')\n self.browser.go('http://localhost/portal/myfolder/myevent/edit_html')\n\n form = self.browser.get_form('frmEdit')\n self.browser.clicked(form, self.browser.get_form_field(form, 'title:utf8:ustring'))\n form['title:utf8:ustring'] = ''\n self.browser.submit()\n\n html = self.browser.get_html()\n self.failUnless('The form contains errors' in html)\n self.failUnless('Value required for \"Title\"' in html)\n\n self.browser_do_logout()\n\n def test_manage(self):\n self.browser_do_login('admin', '')\n\n self.browser.go('http://localhost/portal/myfolder/myevent/manage_edit_html')\n form = self.browser.get_form('frmEdit')\n self.failUnlessEqual(form['title:utf8:ustring'], 'My event')\n form['title:utf8:ustring'] = 'new_event_title'\n self.browser.clicked(form, self.browser.get_form_field(form, 'title:utf8:ustring'))\n self.browser.submit()\n\n self.failUnlessEqual(self.portal.myfolder.myevent.title, 'new_event_title')\n\n self.browser_do_logout()\n\n def test_view_in_folder(self):\n self.browser_do_login('admin', '')\n\n self.browser.go('http://localhost/portal/myfolder')\n html = self.browser.get_html()\n soup = BeautifulSoup(html)\n\n tables = soup.findAll('table', id='folderfile_list')\n self.assertTrue(len(tables) == 1)\n\n links_to_event = tables[0].findAll('a', attrs={'href': 'http://localhost/portal/myfolder/myevent'})\n self.assertTrue(len(links_to_event) == 1)\n self.assertTrue(links_to_event[0].string == 'My event')\n\n self.browser_do_logout()\n\nclass NyEventVersioningFunctionalTestCase(NaayaFunctionalTestCase):\n \"\"\" TestCase for NaayaContent object \"\"\"\n def afterSetUp(self):\n from naaya.content.event.event_item import addNyEvent\n addNyEvent(self.portal.info, id='ver_event', title='ver_event', submitted=1)\n import transaction; transaction.commit()\n\n def beforeTearDown(self):\n self.portal.info.manage_delObjects(['ver_event'])\n import transaction; transaction.commit()\n\n def test_start_version(self):\n from naaya.content.event.event_item import event_item\n self.browser_do_login('admin', '')\n self.failUnlessEqual(self.portal.info.ver_event.version, None)\n self.browser.go('http://localhost/portal/info/ver_event/startVersion')\n self.failUnless(isinstance(self.portal.info.ver_event.version, event_item))\n self.browser_do_logout()\n\n def test_edit_version(self):\n self.browser_do_login('admin', '')\n self.browser.go('http://localhost/portal/info/ver_event/startVersion')\n\n form = self.browser.get_form('frmEdit')\n form['title:utf8:ustring'] = 'ver_event_newtitle'\n self.browser.clicked(form, self.browser.get_form_field(form, 'title:utf8:ustring'))\n self.browser.submit()\n\n ver_event = self.portal.info.ver_event\n self.failUnlessEqual(ver_event.title, 'ver_event')\n # we can't do ver_event.version.title because version objects don't have the _languages property\n self.failUnlessEqual(ver_event.version.getLocalProperty('title', 'en'), 'ver_event_newtitle')\n\n self.browser_do_logout()\n\ndef test_suite():\n suite = TestSuite()\n suite.addTest(makeSuite(NyEventFunctionalTestCase))\n suite.addTest(makeSuite(NyEventVersioningFunctionalTestCase))\n return suite\n","sub_path":"obsolete/old/Naaya-2009_12-editor/naaya/content/event/tests/testFunctional.py","file_name":"testFunctional.py","file_ext":"py","file_size_in_byte":8883,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"596957798","text":"#!/usr/bin/python3\n'''\n View for Events\n'''\n\nfrom CalendarBackend.v1.views import app_views\nfrom flask import Blueprint, jsonify, abort, request\nfrom models import storage\nimport json\nfrom models.events import Events\n\n\n@app_views.route('/', methods=['GET', 'POST'])\ndef all_events():\n '''lists all events in json format and posts events'''\n if request.method == 'GET':\n stored_events = storage.all('Events').values()\n events_list = []\n for event in stored_events:\n events_dict = event.to_dict()\n events_list.append(events_dict)\n return jsonify(events_list)\n else:\n data = request.get_json()\n if data is None:\n return jsonify('Not a JSON'), 400\n if 'date' in data:\n new_event = Events(**data)\n new_event.save()\n return jsonify(new_event.to_dict()), 201\n else:\n return jsonify('Missing date'), 400\n\n\n@app_views.route('/', methods=['DELETE', 'PUT', 'GET'])\ndef events_with_id(id=None):\n '''handles updating and deleting of specific event'''\n event_obj = storage.get('Events', id)\n if event_obj is None:\n abort(404, 'Not found')\n elif request.method == 'DELETE':\n event_obj.delete()\n storage.save()\n return jsonify({}), 200\n elif request.method == 'GET':\n events_dict = event_obj.to_dict()\n return jsonify(events_dict)\n else:\n if not request.get_json():\n return jsonify({'error': 'Not a JSON'}), 400\n for attr, val in request.get_json().items():\n if attr not in ['id', 'created_at', 'updated_at']:\n setattr(event_obj, attr, val)\n event_obj.save()\n return jsonify(event_obj.to_dict())\n","sub_path":"CalendarBackend/v1/views/events.py","file_name":"events.py","file_ext":"py","file_size_in_byte":1761,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"321787809","text":"\"\"\"\nMenu utilities.\n\"\"\"\nfrom django.conf import settings\nfrom django.core.urlresolvers import reverse\nfrom django.utils.importlib import import_module\n\n\ndef _get_menu_cls(menu_cls, context):\n if isinstance(menu_cls, dict):\n curr_url = context.get('request').path\n for key in menu_cls:\n admin_site_mod, admin_site_inst = key.rsplit('.', 1)\n admin_site_mod = import_module(admin_site_mod)\n admin_site = getattr(admin_site_mod, admin_site_inst)\n admin_url = reverse('%s:index' % admin_site.name)\n if curr_url.startswith(admin_url):\n mod, inst = menu_cls[key].rsplit('.', 1)\n mod = import_module(mod)\n return getattr(mod, inst)\n else:\n mod, inst = menu_cls.rsplit('.', 1)\n mod = import_module(mod)\n return getattr(mod, inst)\n raise ValueError('Dashboard menu matching \"%s\" not found' % menu_cls)\n\n\ndef get_menu(context):\n \"\"\"\n Returns the menu defined by the user or the default one.\n \"\"\"\n menu_class = getattr(\n settings,\n 'APP_MENU',\n 'issuesdb.menu.Menu'\n )\n if not menu_class:\n return None\n return _get_menu_cls(menu_class, context)()\n\n\ndef get_media_url():\n media_url = getattr(settings, 'ISSUESDB_MEDIA_URL', None)\n if media_url is None:\n media_url = getattr(settings, 'STATIC_URL', None)\n if media_url is None:\n media_url = getattr(settings, 'MEDIA_URL')\n return media_url.rstrip('/')\n","sub_path":"issuesdb/menu/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":1507,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"72139806","text":"from torch.utils.data import ConcatDataset, DataLoader\nimport numpy as np\nimport torchvision.transforms as transforms\nfrom torch import squeeze\nimport pandas as pd\n\n\nclass Dataset(object):\n\n def __getitem__(self, index):\n raise NotImplementedError\n\n def __len__(self):\n raise NotImplementedError\n\n def __add__(self, other):\n return ConcatDataset([self, other])\n\n\nclass LoadData(Dataset):\n\n def __init__(self, path='data/ecoli_100_space_fix.csv', split_r=0.9, is_train=True, gpu_ids='0'):\n realB = list(pd.read_csv(path)['realB'])\n realA = list(pd.read_csv(path)['realA'])\n data_size = len(realB)\n split_idx = int(data_size * split_r)\n noise_dim = 128\n self.gpu_ids = gpu_ids\n if is_train:\n st, ed = 0, split_idx\n else:\n st, ed = split_idx, data_size\n self.storage, self.input_seq = [], []\n for i in range(st, ed, 1):\n self.storage.append(one_hot(realB[i].split('\\n')[0].upper()))\n self.input_seq.append(backbone_one_hot(realA[i].split('\\n')[0].upper()))\n\n def __getitem__(self, item):\n in_seq, label_seq = transforms.ToTensor()(self.input_seq[item]), transforms.ToTensor()(self.storage[item])\n if len(self.gpu_ids) > 0:\n return {'in': in_seq[0, :].float().cuda(), 'out': squeeze(label_seq).float().cuda()}\n else:\n return {'in': in_seq[0, :].float(), 'out': squeeze(label_seq).float()}\n\n def __len__(self):\n return len(self.storage)\n\n\ndef one_hot(seq):\n charmap = {'A': 0, 'T': 1, 'C': 2, 'G': 3}\n encoded = np.zeros([len(charmap), len(seq)])\n for i in range(len(seq)):\n encoded[charmap[seq[i]], i] = 1\n return encoded\n\n\ndef backbone_one_hot(seq):\n charmap = {'A': 0, 'T': 1, 'C': 2, 'G': 3}\n encoded = np.zeros([len(charmap), len(seq)])\n for i in range(len(seq)):\n if seq[i] == 'M':\n encoded[:, i] = np.random.rand(4)\n else:\n encoded[charmap[seq[i]], i] = 1\n return encoded","sub_path":"cpro/pro_data.py","file_name":"pro_data.py","file_ext":"py","file_size_in_byte":2043,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"516523798","text":"import logging\nimport requests\nimport constant\nimport json\nfrom datetime import datetime\n\nfrom model.message import UpdateJobMessage\nfrom task.module.validation import checkValidExecuteAt\n\n\ndef send_request(message):\n update_job_message = UpdateJobMessage()\n update_job_message.id = message['id']\n\n if checkValidExecuteAt(message['execute_at']):\n api_endpoint = message['server_ip'] + \"/schedule.json\"\n data = {\n \"project\": message['project'],\n \"spider\": message['spider'],\n \"max_pagination_article_depth\": constant.MAX_PAGINATION_ARTICLE_DEPTH,\n \"max_pagination_comment_depth\": constant.MAX_PAGINATION_COMMENT_DEPTH,\n \"max_pagination_reply_depth\": constant.MAX_PAGINATION_REPLY_DEPTH,\n \"user_email\": message['username'],\n \"password\": message['password'],\n \"fan_page_urls\": message['followings'],\n \"user_agent\": constant.USER_AGENT\n }\n r = requests.post(url=api_endpoint, data=data)\n # print(r.text)\n job = json.loads(str(r.text))\n\n update_job_message.real_execute_at = str(datetime.now().strftime(constant.FORMAT_DATETIME))\n update_job_message.status = constant.JOB_STATUS_STARTED_SUCCESSFULLY\n print(\"The paste bin URL is:%s\" % job[\"jobid\"])\n else:\n update_job_message.error_code = constant.JOB_ERROR_CODE_EXCEED_VALID_EXECUTED_AT\n update_job_message.status = constant.JOB_STATUS_STARTED_FAILED\n logging.error(\"Message exceed valid time: \" + message['execute_at'])\n\n return update_job_message\n # rabbitmq.send_message(constant.RABBITMQ_MONITOR_QUEUE, monitor_message)\n # broker.send_message(constant.MQTT_TOPIC_JOB_UPDATE, monitor_message)\n","sub_path":"task/module/util.py","file_name":"util.py","file_ext":"py","file_size_in_byte":1746,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"629135340","text":"\"\"\"\n根据本地的配置文件创建工作目录的工具\n\"\"\"\nimport os\nimport sys\nimport argparse\nimport urllib.parse\nimport shutil\nfrom WorkTools import SvnProcesser as Svn\nfrom WorkTools import ShellCenter as Shell\n\n\nROOT_ENV_NAME = \"SCLIENT_ROOT_PATH\"\nCONFIG_NAME = \".config.ini\"\nROOT_NAME = \"root\"\nDEFAULT_CONFIG = \"\"\"# This file is used to help organize file.\n# acturally it is a Python file.\n# so you should change it like Python code.\n\ndir_config = [\n# {\n# \"name\": \"example\", # project name\n# \"url\": \"\", # src url\n# \"url_type\": \"\", # path, svn, git\n# \"command\": \"\", # subcommand of these tools. like checkout, update.\n# \"path\": \"\", # des path\n# \"opt\": \"\", # addition options\n# }\n]\n\"\"\"\nINIT_SUCCESS = \"\"\"Init dir successed.\nPlease add the code below into ~/.bashrc to help locate the files.\n\n # add for sclient\n export {}=\"{{}}\"\n\nAfter this, please modify {{}}/.config.ini as the example.\nAnd then, you can try to fetch your codes.\n\"\"\".format(ROOT_ENV_NAME)\nSIMPLE_HELP = \"\"\"Used to create workspace.\nuse -h or --help to see more help.\n\"\"\"\nCFG = {} # read config into this global var\n\n\ndef init_actions(name_space):\n \"\"\"\n 执行参数所指定的函数\n \"\"\"\n root_path = os.path.realpath(name_space.path)\n if not root_path:\n raise Exception(\"not enough arguments.\")\n\n if not os.path.exists(root_path):\n if os.path.isdir(os.path.dirname(root_path)):\n os.mkdir(root_path)\n else:\n raise Exception(\"dir not exsits.\")\n\n if os.path.isdir(root_path):\n config_path = os.path.join(root_path, CONFIG_NAME)\n with open(config_path, mode='w+') as fp:\n fp.write(DEFAULT_CONFIG)\n file_path = os.path.join(root_path, ROOT_NAME)\n if not os.path.isdir(file_path):\n os.mkdir(file_path)\n print(INIT_SUCCESS.format(root_path, root_path))\n return\n\n raise Exception(\"init fail.\")\n\n\ndef read_config():\n \"\"\"\n 读取配置文件\n \"\"\"\n root_env = os.getenv(ROOT_ENV_NAME)\n if not root_env:\n raise Exception(\"did not init dir or did not add the env variable.\")\n\n config_path = os.path.join(root_env, CONFIG_NAME)\n if not os.path.exists(config_path):\n raise Exception(\"config not exsits.\", config_path)\n\n if \"dir_config\" not in CFG:\n with open(config_path, 'r') as fp:\n cfg_context = fp.read()\n CFG.clear()\n try:\n exec(cfg_context, CFG)\n if \"dir_config\" not in CFG:\n raise Exception(\"no dir_config in config\")\n for project in CFG[\"dir_config\"]:\n if \"name\" not in project:\n raise Exception(\"no name attr.\", project)\n if \"path\" not in project:\n raise Exception(\"no path attr.\", project)\n except Exception as e:\n raise\n\n\ndef check_action(name_space):\n try:\n read_config()\n except Exception as e:\n if name_space.verbose:\n raise e\n else:\n print(\"config invalid.\")\n exit(1)\n else:\n print(\"config ok.\")\n\n\ndef list_action(name_space):\n read_config()\n if name_space.verbose:\n print(CFG[\"dir_config\"])\n print(\"projects:\\n\")\n for project in CFG[\"dir_config\"]:\n print(\"\\t\" + project[\"name\"])\n for k, v in project.items():\n print(\"\\t\\t\", k, \":\", v)\n else:\n tips = \"projects:\\n\"\n for project in CFG[\"dir_config\"]:\n tips += project[\"name\"]\n tips += \" : \"\n tips += project[\"path\"]\n tips += \"\\n\"\n print(tips)\n\n\ndef checkout_svn_url(root_env, project):\n if \"path\" not in project:\n raise Exception(\"invalid project.\", project)\n local_path = os.path.join(root_env, project[\"path\"])\n dir_name = os.path.dirname(local_path)\n # 这里检测父目录需要存在\n if os.path.isdir(dir_name):\n opts = None\n if \"opt\" in project:\n opts = project[\"opt\"]\n if \"command\" not in project or project[\"command\"] == \"checkout\":\n if \"url\" not in project:\n raise Exception(\"invalid project.\", project)\n if os.path.isdir(local_path):\n # 如果这个路径已经存在了\n out_put = Svn.status(local_path)\n if \"svn: warning: W155007\" in out_put:\n # 不是svn路径,抛出异常给用户检查\n raise Exception(\"Checkout into an exsit folder.\")\n else:\n # 是svn路径\n out_put = Svn.info(local_path, [\"--show-item\", \"url\"])\n if urllib.parse.unquote(out_put).rstrip() == project[\"url\"]:\n # 与现有url一致\n Svn.update(local_path)\n else:\n raise Exception(\"Checkout folder with different url.\", \"remote:\", out_put, \"local:\", project[\"url\"])\n else:\n # 路径不存在直接checkout\n Svn.checkout(project[\"url\"], local_path, opts)\n elif project[\"command\"] == \"update\":\n Svn.update(local_path, opts)\n else:\n raise Exception(\"invalid command.\", project)\n else:\n raise Exception(\"invalid path.\")\n\n\ndef fetch_path_url(root_env, project):\n if \"path\" not in project:\n raise Exception(\"invalid project.\", project)\n local_path = os.path.join(root_env, project[\"path\"])\n if \"command\" not in project or project[\"command\"] == \"new\":\n if not os.path.exists(local_path):\n dir_name = os.path.dirname(local_path)\n if os.path.isdir(dir_name):\n os.mkdir(local_path)\n else:\n raise Exception(\"invalid path.\", project)\n else:\n print(\"dir already exsits.\")\n elif project[\"command\"] == \"link\":\n pass\n else:\n raise Exception(\"invalid command.\", project)\n\n\ndef fetch_git_url(root_env, project):\n if \"path\" not in project:\n raise Exception(\"invalid project.\", project)\n local_path = os.path.join(root_env, project[\"path\"])\n dir_name = os.path.dirname(local_path)\n # 这里检测父目录需要存在\n if os.path.isdir(dir_name):\n if \"command\" not in project or project[\"command\"] == \"clone\":\n if \"url\" not in project:\n raise Exception(\"invalid project.\", project)\n if os.path.isdir(local_path):\n # 如果这个路径已经存在了\n if not os.path.exists(os.path.join(local_path, \".git\")):\n # 不是git路径,抛出异常给用户检查\n raise Exception(\"Checkout into an exsit folder.\")\n else:\n # 是git路径\n cur_dir = os.path.realpath(os.curdir)\n os.chdir(local_path)\n out_put = Shell.execute_list_command(\n [\"git\", \"remote\", \"get-url\", \"origin\"]\n )\n if urllib.parse.unquote(out_put).rstrip() == project[\"url\"]:\n # 与现有url一致\n Shell.execute_list_command([\"git\", \"pull\"])\n else:\n raise Exception(\"Checkout folder with different url.\", \"remote:\", out_put, \"local:\", project[\"url\"])\n os.chdir(cur_dir)\n else:\n # 路径不存在直接checkout\n Shell.execute_list_command(\n [\"git\", \"clone\", project[\"url\"], local_path]\n )\n else:\n raise Exception(\"invalid command.\", project)\n else:\n raise Exception(\"invalid path.\")\n\n\ndef fetch_one_project(root_env, project):\n print(\"fetching project:\", project[\"name\"])\n if project[\"url_type\"] == \"svn\":\n checkout_svn_url(root_env, project)\n elif project[\"url_type\"] == \"path\":\n fetch_path_url(root_env, project)\n elif project[\"url_type\"] == \"git\":\n fetch_git_url(root_env, project)\n else:\n raise Exception(\"invalid url_type. please check the config file.\")\n print(\"project\", project[\"name\"], \"fetch done.\")\n\n\ndef fetch_actions(name_space):\n \"\"\"\n 执行参数所指定的函数\n \"\"\"\n read_config()\n root_env = os.getenv(ROOT_ENV_NAME)\n if not root_env:\n tip = \"please set environment variable {}\".format(ROOT_ENV_NAME)\n raise Exception(tip)\n if name_space.name:\n name_exsit = False\n for project in CFG[\"dir_config\"]:\n if project[\"name\"] == name_space.name:\n fetch_one_project(root_env, project)\n name_exsit = True\n break\n if not name_exsit:\n print(\"No such name:\", name_space.name)\n else:\n for project in CFG[\"dir_config\"]:\n fetch_one_project(root_env, project)\n\n\ndef revert_a_path(root_env, project):\n proj_path = os.path.join(root_env, project[\"path\"])\n if project[\"url_type\"] == \"svn\":\n Svn.revert(proj_path)\n elif project[\"url_type\"] == \"git\":\n now_dir = os.path.realpath(os.curdir)\n os.chdir(proj_path)\n Shell.execute_list_command([\"git\", \"checkout\", \".\"])\n os.chdir(now_dir)\n else:\n print(\"this proj dont need revert:\\n\", project)\n\n\ndef clear_one_project(project, b_reset=False, b_recursion=False):\n root_env = os.getenv(ROOT_ENV_NAME)\n if not root_env:\n tip = \"please set environment variable {}\".format(ROOT_ENV_NAME)\n raise Exception(tip)\n proj_path = os.path.join(root_env, project[\"path\"])\n if b_reset:\n if os.path.exists(proj_path):\n shutil.rmtree(proj_path)\n for proj in CFG[\"dir_config\"]:\n if proj[\"path\"].startswith(project[\"path\"]):\n fetch_one_project(root_env, proj)\n else:\n if b_recursion:\n for proj in CFG[\"dir_config\"]:\n if proj[\"path\"].startswith(project[\"path\"]):\n revert_a_path(root_env, proj)\n else:\n revert_a_path(root_env, project)\n\n\ndef clear_actions(name_space):\n print(name_space)\n read_config()\n if name_space.clear_project == \"all\":\n ensure = input(\"You are clearing all of the projects.(y/n)\")\n if (ensure == \"y\"):\n for project in CFG[\"dir_config\"]:\n if os.path.dirname(project[\"path\"]) == \"root\":\n # 表示顶级工程\n clear_one_project(\n project,\n b_recursion=True,\n b_reset=name_space.reset\n )\n else:\n name_exsit = False\n for project in CFG[\"dir_config\"]:\n if name_space.clear_project == project[\"name\"]:\n name_exsit = True\n clear_one_project(\n project,\n b_reset=name_space.reset,\n b_recursion=name_space.recursion\n )\n break\n if not name_exsit:\n print(\"no name:\", name_space.clear_project)\n\n\ndef simple_help():\n print(SIMPLE_HELP)\n\n\ndef main():\n parser = argparse.ArgumentParser(\n description=\"Use this script to create a workspace.\"\n )\n\n subparser = parser.add_subparsers(help=\"subcommands\")\n # init parser\n init_parser = subparser.add_parser(\n \"init\",\n help=\"init workspace folders.\",\n )\n init_parser.set_defaults(func=init_actions)\n init_parser.add_argument(\n \"path\",\n nargs=\"?\",\n help=\"root dir path.\",\n default=os.path.curdir,\n )\n # check parser\n check_parser = subparser.add_parser(\n \"check\",\n help=\"check projects.\",\n )\n check_parser.set_defaults(func=check_action)\n check_parser.add_argument(\n \"-v\", \"--verbose\",\n help=\"show all config infomation.\",\n action=\"store_true\"\n )\n # list parser\n list_parser = subparser.add_parser(\n \"list\",\n help=\"list projects.\",\n )\n list_parser.set_defaults(func=list_action)\n list_parser.add_argument(\n \"-v\", \"--verbose\",\n help=\"show all config infomation.\",\n action=\"store_true\"\n )\n # fetch parser\n fetch_parser = subparser.add_parser(\n \"fetch\",\n help=\"fetch folders based on ./config.\"\n )\n fetch_parser.set_defaults(func=fetch_actions)\n fetch_parser.add_argument(\n \"-n\", \"--name\",\n help=\"appoint config file.\",\n )\n # clear parser\n clear_parser = subparser.add_parser(\n \"clear\",\n help=\"clear a project.\"\n )\n clear_parser.set_defaults(func=clear_actions)\n clear_parser.add_argument(\n \"clear_project\",\n help=\"appoint clear project. use all to clear everything.\",\n )\n clear_parser.add_argument(\n \"-r\", \"--recursion\",\n help=\"clear the project and the projects in its path.\",\n action=\"store_true\"\n )\n clear_parser.add_argument(\n \"--reset\",\n help=\"delete the project and checkout again. \\\n notice that it will also delete the projects in it and reset them.\",\n action=\"store_true\"\n )\n\n # 执行对应动作\n name_space = parser.parse_args()\n name_space.func(name_space)\n\n\nif __name__ == \"__main__\":\n if not sys.argv[1:]:\n simple_help()\n else:\n main()\n","sub_path":"WorkspaceCreate.py","file_name":"WorkspaceCreate.py","file_ext":"py","file_size_in_byte":13466,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"623774180","text":"\"\"\"myApi URL Configuration\r\n\r\nThe `urlpatterns` list routes URLs to views. For more information please see:\r\n https://docs.djangoproject.com/en/2.0/topics/http/urls/\r\nExamples:\r\nFunction views\r\n 1. Add an import: from my_app import views\r\n 2. Add a URL to urlpatterns: path('', views.home, name='home')\r\nClass-based views\r\n 1. Add an import: from other_app.views import Home\r\n 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')\r\nIncluding another URLconf\r\n 1. Import the include() function: from django.urls import include, path\r\n 2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))\r\n\"\"\"\r\nfrom django.conf.urls import url, include\r\nfrom django.contrib import admin\r\nfrom rest_framework import routers\r\nfrom appMyZak import views\r\n\r\n\r\nfrom rest_framework.authtoken import views as rest_framework_views\r\n\r\nadmin.autodiscover()\r\n\r\nrouter = routers.DefaultRouter()\r\nrouter.register(r'users', views.UserViewSet)\r\nrouter.register(r'groups', views.GroupViewSet)\r\nrouter.register(r'departements', views.DepartementViewSet)\r\nrouter.register(r'banques', views.BanqueViewSet)\r\nrouter.register(r'comptebancaires', views.CompteBancaireViewSet)\r\nrouter.register(r'situations', views.SituationViewSet)\r\nrouter.register(r'historiques', views.HistoriqueViewSet)\r\n\r\n\r\n# Wire up our API using automatic URL routing.\r\n# Additionally, we include login URLs for the browsable API.\r\nurlpatterns = [\r\n url(r'^', include(router.urls)),\r\n url(r'^admin/', admin.site.urls ),\r\n url(r'^compte_bancaire/', views.compteBancaire),\r\n url(r'^historique_espece/', views.historiqueEspece),\r\n url(r'^historique_immo/', views.historiqueImmo),\r\n url(r'^maj_solde/', views.majSolde),\r\n url(r'^maj_etat_bloc/', views.majEtatBloc),\r\n url(r'^edit_compte_bancaire/(?P[0-9]+)/$', views.weshCompteBancaire.as_view() ),\r\n #url(r'^get_situation/', views.getSituation.as_view() ),\r\n url(r'^get_historique/', views.getSituation),\r\n url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework')),\r\n url(r'^get_auth_token/$', rest_framework_views.obtain_auth_token, name='get_auth_token'),\r\n url(r'^bonjour/$', views.bonjour_appel),\r\n\r\n url(r'^create_user/$', views.createUser),\r\n]\r\n","sub_path":"myApi/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":2248,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"70085872","text":"import numpy as np\nfrom Frame import *\nimport pivot_calibration\nimport three_dimension_transform\nimport glob\n\n\n# Jonah Yousif, Justin Joyce\n# Method to apply EM tracking data to perform a pivot calibration for the EM probe\n# input is the \"run,\" determining which data file set to use\n# Output is the new pivot calibration output for the EM probe\ndef EM_track(M):\n # Assigning Variables\n Ng = 6\n # coordinates based on frame 1\n Gframe = M[:Ng, :]\n Gmid = np.sum(Gframe, axis=0)/np.shape(Gframe)[0]\n gpos = Gframe - Gmid\n G_stack = np.zeros(1)\n p_stack = np.zeros(1)\n # relative frame transformations.\n # registers the 3d-3d points from the data to the centered frame\n # then stacks each of the resultants\n for i in range(12):\n\n Gg = M[i*Ng: (i+1)*Ng, :]\n Mj = three_dimension_transform.rigid_transform(Gg, gpos)\n if G_stack.size == 1:\n G_stack = Mj.rot\n else:\n G_stack = np.vstack((G_stack, Mj.rot))\n if p_stack.size == 1:\n p_stack = Mj.tr.T\n else:\n p_stack = np.vstack((p_stack, Mj.tr.T))\n # setting as 1d for least squares\n p_stack = p_stack.reshape(p_stack.size,)\n # performing pivot cal\n pivs = pivot_calibration.pivot_calibration(G_stack, p_stack, 12)\n return pivs\n\n\nif __name__ == '__main__':\n pass\n","sub_path":"Project2/PROGRAMS/em_correction.py","file_name":"em_correction.py","file_ext":"py","file_size_in_byte":1344,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"641325097","text":"import numpy as np\nimport matplotlib\nfrom imageParser import ImageParser\nimport tensorflow as tf\nfrom tensorflow import keras\nfrom tensorflow.keras import layers\nfrom tensorflow.keras.models import Sequential\nimport matplotlib.pyplot as plt\nimport matplotlib.image as mpimg\nimport scipy\nimport cv2\nfrom scipy import misc\n#import Pillow as PIL\nfrom PIL import Image\n#import skimage\nfrom skimage.transform import resize\n\n#scipy.misc.imresize\n\n# SAR TODO - Move this code into the Classifier class\n\nmyParser = ImageParser()\n\n\n#for i in range(447):\n# img=cv2.imread(list(myParser.imageDict.values())[i].fileName)\n# print(\"The label for this image is\", list(myParser.imageDict.values())[i].label)\n# resize_img = resize(img, (256,256,3))\n \n \n\n\nprint(list(myParser.imageDict.values())[0].fileName)\n\nimg=cv2.imread(list(myParser.imageDict.values())[3740].fileName)\nimgplot = plt.imshow(img)\nplt.show()\nplt.imshow(img)\n\nheight, width, channels = img.shape\nprint(\"width: \", width)\nprint(\"height: \", height)\n#new_shape = ()\nprint(\"The number of images are: \", len(myParser.imageDict))\nprint(\"The classification of the first image is: \", list(myParser.imageDict.values())[0].label)\n#search through the images, find the smallest resolution and scale all of the images to that resolution\n#newShape = ()\n\nimgPIL = Image.open(list(myParser.imageDict.values())[0].fileName)\nmyParser.getImageFilesDir()\n\nsmallIMG = imgPIL.resize((250,250), Image.ANTIALIAS)\n#plt.imshow(smallIMG)\n#plt.show()\n\ndata_dir = \"C:\\\\Users\\\\crsny\\\\Documents\\\\GradSchool\\\\2020-2021\\\\Project\\\\DurOrNoDur\\\\ImageFiles2\"\n\nbatch_size = 32\nimg_height = 256\nimg_width = 256\n\n#test_file = tf.keras.utils.get_file(list(myParser.imageDict.values())[0].fileName)\ntest_img = tf.keras.preprocessing.image.load_img(list(myParser.imageDict.values())[0].fileName, target_size=[img_height, img_width])\nnparray_test_img = np.array(test_img)\n\ntrain_ds = tf.keras.preprocessing.image_dataset_from_directory(\n data_dir, labels='inferred', label_mode='int', class_names=None,\n color_mode='rgb', batch_size=32, image_size=(img_height, img_width), shuffle=True, seed=123,\n validation_split=0.2, subset=\"training\", interpolation='bilinear', follow_links=False\n)\n\nval_ds = tf.keras.preprocessing.image_dataset_from_directory(\n data_dir,\n validation_split=0.2,\n subset=\"validation\",\n seed=123,\n image_size=(img_height, img_width),\n batch_size=batch_size)\n\nclass_names = train_ds.class_names\nprint(\"The names of the classes are: \", class_names)\nprint(class_names[0])\n\nplt.figure(figsize=(10, 10))\nfor images, labels in train_ds.take(1):\n for i in range(9):\n ax = plt.subplot(3, 3, i + 1)\n plt.imshow(images[i].numpy().astype(\"uint8\"))\n plt.title(class_names[labels[i]])\n plt.axis(\"off\")\n\n#testing the unshuffled test read\ndata_dir_test = \"C:\\\\Users\\\\crsny\\\\Documents\\\\GradSchool\\\\2020-2021\\\\Project\\\\DurOrNoDur\\\\ImageFilesTesting\"\ntest_ds = tf.keras.preprocessing.image_dataset_from_directory(\n data_dir_test, labels='inferred', label_mode='int', class_names=None,\n color_mode='rgb', batch_size=32, image_size=(256, 256), shuffle=False, interpolation='bilinear', follow_links=False\n)\n\nplt.figure(figsize=(10, 10))\nfor images, labels in test_ds.take(1):\n for i in range(9):\n ax = plt.subplot(3, 3, i + 1)\n plt.imshow(images[i].numpy().astype(\"uint8\"))\n plt.title(class_names[labels[i]])\n plt.axis(\"off\")\nplt.show()\n\n\nAUTOTUNE = tf.data.experimental.AUTOTUNE\n\ntrain_ds = train_ds.cache().shuffle(1000).prefetch(buffer_size=AUTOTUNE)\nval_ds = val_ds.cache().prefetch(buffer_size=AUTOTUNE)\n\nnormalization_layer = layers.experimental.preprocessing.Rescaling(1./255)\n\nnormalized_ds = train_ds.map(lambda x, y: (normalization_layer(x), y))\nimage_batch, labels_batch = next(iter(normalized_ds))\nfirst_image = image_batch[0]\n\n\nnum_classes = 2\n\n#This creates a concolution kernel convolved with the layer input to produce a tensor of outputs\n#The first two numbers dictate the dimentionality of the output spce (the number of output filters in the convolution)\n# and the height/width of the 2D convolution window\nmodel = Sequential([\n layers.experimental.preprocessing.Rescaling(1./255, input_shape=(img_height, img_width, 3)),\n layers.Conv2D(16, 3, padding='same', activation='relu'),\n layers.MaxPooling2D(),\n layers.Conv2D(32, 3, padding='same', activation='relu'),\n layers.MaxPooling2D(),\n layers.Conv2D(64, 3, padding='same', activation='relu'),\n layers.MaxPooling2D(),\n layers.Flatten(),\n layers.Dense(128, activation='relu'),\n layers.Dense(num_classes)\n])\n\nmodel.compile(optimizer='adam',\n loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True),\n metrics=['accuracy'])\n\nmodel.summary()\n\nepochs=6\nhistory = model.fit(\n train_ds,\n validation_data=val_ds,\n epochs=epochs\n)\n\nacc = history.history['accuracy']\nval_acc = history.history['val_accuracy']\n\nloss = history.history['loss']\nval_loss = history.history['val_loss']\n\nepochs_range = range(epochs)\n\nplt.figure(figsize=(8, 8))\nplt.subplot(1, 2, 1)\nplt.plot(epochs_range, acc, label='Training Accuracy')\nplt.plot(epochs_range, val_acc, label='Validation Accuracy')\nplt.legend(loc='lower right')\nplt.title('Training and Validation Accuracy')\n\nplt.subplot(1, 2, 2)\nplt.plot(epochs_range, loss, label='Training Loss')\nplt.plot(epochs_range, val_loss, label='Validation Loss')\nplt.legend(loc='upper right')\nplt.title('Training and Validation Loss')\nplt.show()\n\n#model.save('\"C:\\\\Users\\\\crsny\\\\Documents\\\\GradSchool\\\\2020-2021\\\\Project\\\\DurOrNoDur\\\\model1\"')\n#model.save('model1')\n\nvalResults = model.predict_classes(val_ds)\n\n\nnp.savetxt(\"predictionResults_v0p1.csv\", valResults, delimiter=\",\")\n\nresults = model.evaluate(val_ds)\nprint(\"test loss, test accuracy: \", results)\npredictedResults = model.predict(val_ds)\n\ndata_dir_test = \"C:\\\\Users\\\\crsny\\\\Documents\\\\GradSchool\\\\2020-2021\\\\Project\\\\DurOrNoDur\\\\ImageFilesTesting\"\n\ntest_ds = tf.keras.preprocessing.image_dataset_from_directory(\n data_dir_test, labels='inferred', label_mode='int', class_names=None,\n color_mode='rgb', batch_size=32, image_size=(img_height, img_width), shuffle=False, interpolation='bilinear', follow_links=False\n)\n\nplt.figure(figsize=(10, 10))\nfor images, labels in test_ds.take(1):\n for i in range(9):\n ax = plt.subplot(3, 3, i + 1)\n plt.imshow(images[i].numpy().astype(\"uint8\"))\n plt.title(class_names[labels[i]])\n plt.axis(\"off\")\n\nplt.show()\n\ntest_ds_pred = model.predict(test_ds)\ntest_pred_classes = model.predict_classes(test_ds)\nprint(test_ds_pred)\nnp.savetxt(\"predictionResults_testDS_v0p0.csv\", test_ds_pred, delimiter=\",\")\nnp.savetxt(\"predictionResults_testDS_Classes_v0p0.csv\", test_pred_classes, delimiter=\",\")\ntest_ds_eval = model.evaluate(test_ds)\nprint(test_ds_eval)\n\n\n#This doesn't work since the input is expecting a batch size of 32\ntest_img = tf.keras.preprocessing.image.load_img(list(myParser.imageDict.values())[0].fileName, target_size=[img_height, img_width])\ntest_img_np = np.array(test_img)\n\ntest_img_pred = model.predict(np.array(test_img))\nprint(\"Test img prediction results: \", test_img_pred)\n\ntest_img2 = tf.keras.preprocessing.image.load_img(list(myParser.imageDict.values())[3000].fileName, target_size=[img_height, img_width])\n\ntest_img_pred2 = model.predict(test_img2)\nprint(\"Test img2 prediction results: \", test_img_pred2)\n\n#model.save('model1')\n\n#trying classification to test things\n#take absolute value of classification\n#count the number of classifications for each\n# if the classification does not match save the filename\n\n\ncorrectCounter = 0\nincorrectCounter = 0\nfor i in range(100):\n img=cv2.imread(list(myParser.imageDict.values())[i].fileName)\n print(\"The label for this image is\", list(myParser.imageDict.values())[i].label)\n resize_img = resize(img, (256,256,3))\n predictions = model.predict(np.array([resize_img]))\n #testRes = np.array([-8.32, 4.1])\n absPred = abs(predictions)\n #print(absPred)\n #print(np.amax(absPred))\n print(\"raw prediction values: \", predictions)\n #classPred = class_names[np.where(absPred == np.amax(absPred))]\n resultIDX = absPred.tolist().index(np.amax(absPred))\n classPred = class_names[resultIDX]\n print(\"The classification of this image is: \", classPred)\n if resultIDX == list(myParser.imageDict.values())[i].label:\n correctCounter+=1\n elif resultIDX != list(myParser.imageDict.values())[i].label:\n incorrectCounter+=1\n \nprint(\"The number of correct classifications is: \", correctCounter)\nprint(\"The number of incorrect classifications is: \", incorrectCounter)\n\n\n#for i in range(447):\ncorrectCounter = 0\nincorrectCounter = 0\nfor j in range(2962,3000):\n img=cv2.imread(list(myParser.imageDict.values())[j].fileName)\n print(\"The label for this image is\", list(myParser.imageDict.values())[j].label)\n resize_img = resize(img, (256,256,3))\n predictions = model.predict(np.array([resize_img]))\n #testRes = np.array([-8.32, 4.1])\n absPred = abs(predictions)\n #print(absPred)\n #print(np.amax(absPred))\n print(\"raw prediction values: \", predictions)\n #classPred = class_names[np.where(absPred == np.amax(absPred))]\n resultIDX = absPred.tolist().index(np.amax(absPred))\n classPred = class_names[resultIDX]\n print(\"The classification of this image is: \", classPred)\n if resultIDX == list(myParser.imageDict.values())[j].label:\n correctCounter+=1\n elif resultIDX != list(myParser.imageDict.values())[j].label:\n incorrectCounter+=1\n \nprint(\"The number of correct classifications is: \", correctCounter)\nprint(\"The number of incorrect classifications is: \", incorrectCounter)\n\n#search through the predicted results and find some of the values that are incorrectly identified and print them....\n#plt.figure()\n#for i in len(valResults):\n #if\n","sub_path":"Python/testCNN.py","file_name":"testCNN.py","file_ext":"py","file_size_in_byte":9807,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"216298616","text":"# -*- coding: utf-8 -*-\r\n# @Time : 2019/8/9 17:28\r\n# @Author : Edgar Qian\r\n# @Email : qianneng_se@163.com\r\n# @File : MutuComparator.py\r\n\r\n\r\nclass MutuComparator:\r\n def compare(self, p_first, p_second):\r\n a_first_weight = p_first.get_mu_inf_12()\r\n a_second_weight = p_second.get_mu_inf_12()\r\n diff = a_first_weight - a_second_weight\r\n if diff > 0.0:\r\n return -1\r\n if diff < 0.0:\r\n return 1\r\n return 0\r\n","sub_path":"model/MutuComparator.py","file_name":"MutuComparator.py","file_ext":"py","file_size_in_byte":468,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"274760932","text":"import asyncio\nimport os\n\nimport pygments\nfrom pygments.formatters import ImageFormatter\nfrom pygments.lexers import Python3Lexer\n\nfrom userbot.utils import admin_cmd\n\n\n@borg.on(admin_cmd(pattern=\"pcode ?(.*)\"))\nasync def coder_print(event):\n cmd = event.text\n a = await event.get_reply_message()\n coder = \"\"\n if len(cmd) > 7:\n coder = \" \".join(cmd[7:])\n elif event.reply_to_msg_id and len(cmd) == 6:\n coder = a.message\n elif len(cmd) == 6:\n await event.reply(\"`No text given`\")\n await asyncio.sleep(2)\n await event.delete()\n return\n pygments.highlight(\n f\"{coder}\",\n Python3Lexer(),\n ImageFormatter(font_name=\"DejaVu Sans Mono\", line_numbers=True),\n \"cipherx.png\",\n )\n await event.client.send_file(event.chat_id, \"cipherx.png\", force_document=False)\n await event.delete()\n os.remove(\"cipherx.png\")\n","sub_path":"userbot/plugins/pcode.py","file_name":"pcode.py","file_ext":"py","file_size_in_byte":902,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"246326314","text":"import os\nimport json\nfrom pathlib import Path\nfrom random import choice, randint\nfrom nonebot.adapters.cqhttp import Bot, MessageEvent\n\nfrom ATRI.rule import is_in_service, to_bot\nfrom ATRI.service import Service as sv\nfrom ATRI.exceptions import LoadingError\nfrom ATRI.utils.list import count_list, del_list_aim\n\n\nHITOKOTO_DIR = Path(\".\") / \"ATRI\" / \"data\" / \"database\" / \"hitokoto\"\nsick_list = []\n\n\n__doc__ = \"\"\"\n抑郁一下\n权限组:所有人\n用法:\n @一言\n 抑郁一下\n 网抑云\n补充:\n @:at Bot\n\"\"\"\n\nhitokoto = sv.on_command(\n cmd=\"一言\", docs=__doc__, aliases={\"抑郁一下\", \"网抑云\"}, rule=is_in_service(\"一言\") & to_bot()\n)\n\n\n@hitokoto.handle()\nasync def _hitokoto(bot: Bot, event: MessageEvent) -> None:\n global sick_list\n user = event.get_user_id()\n\n if count_list(sick_list, user) == 3:\n sick_list.append(user)\n await hitokoto.finish(\"额......需要咱安慰一下嘛~?\")\n elif count_list(sick_list, user) == 6:\n sick_list = del_list_aim(sick_list, user)\n msg = \"如果心里感到难受就赶快去睡觉!别再憋自己了!\\n\" \"我...我会守在你身边的!...嗯..一定\"\n await hitokoto.finish(msg)\n else:\n sick_list.append(user)\n rd = choice(os.listdir(HITOKOTO_DIR))\n path = HITOKOTO_DIR / rd\n data = {}\n try:\n data = json.loads(path.read_bytes())\n except LoadingError:\n raise LoadingError(\"Loading error!\")\n await hitokoto.finish(data[randint(1, len(data) - 1)][\"hitokoto\"])\n","sub_path":"ATRI/plugins/hitokoto.py","file_name":"hitokoto.py","file_ext":"py","file_size_in_byte":1558,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"597967393","text":"class KNNclassifier:\n def fit(self, X_train, Y_train):\n # Adding data to object\n self.X_train = X_train\n self.Y_train = Y_train\n\n # Preparing Data for processing\n self.shape = 0\n try:\n self.shape = len(X_train[0])\n except Exception as e:\n pass\n self.space = [(self.X_train[i], self.Y_train[i]) for i in range(len(self.X_train))]\n\n def predict(self, X_predict):\n # Checking Input\n if self.shape !=0:\n try:\n if len(X_predict) != self.shape:\n return\n except Exception as e:\n return\n\n # Applying the KNNalgorithm using Euclidean Distance\n dist = -1\n prediction = None\n for i in self.space:\n two_dist = 0\n two_predict = None\n if self.shape == 0:\n two_dist = abs(X_predict - i[0])\n two_predict = i[1]\n else:\n for j in range(self.shape):\n two_dist += (X_predict[j] - i[0][j]) ** 2\n two_dist = two_dist ** 0.5\n two_predict = i[1]\n if two_dist < dist or dist == -1:\n dist = two_dist\n prediction = two_predict\n return prediction\n\n\nif __name__ == \"__main__\":\n classifier = KNNclassifier()\n X_sample = []\n Y_sample = []\n for i in range(-100000,100000):\n X_sample.append((i,i**2,i%2))\n if i+i**2+i**i%2 > 1000:\n Y_sample.append(1)\n else:\n Y_sample.append(0)\n classifier.fit(X_sample,Y_sample)\n print(classifier.predict((-200,40000,0)))\n print(classifier.predict((-1,1,-1)))\n","sub_path":"knnclass.py","file_name":"knnclass.py","file_ext":"py","file_size_in_byte":1708,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"232004424","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Fri Feb 2 13:20:39 2019\r\n\r\n@author: emirhan\r\n\"\"\"\r\n\r\nnumber_of_spaceships=-1\r\nwhile number_of_spaceships<=0 or number_of_spaceships>=70001:\r\n print('Please enter spaceship number(Must be between 0-70000):')\r\n number_of_spaceships=int(input())\r\n \r\nspaceshipID=0\r\nspaceshipIDs=[]\r\nspaceshipTimes=[]\r\ncounter=0\r\nmatrix=[]\r\nscores =[]\r\n\r\n\r\nfor i in range(number_of_spaceships):\r\n row=[]\r\n for j in range(3): \r\n row.append(0) \r\n matrix.append(row) \r\n \r\nfor i in range(number_of_spaceships):\r\n row=[]\r\n for j in range(2): \r\n row.append(0) \r\n scores.append(row) \r\n\r\n\r\nwhile counter <= number_of_spaceships:\r\n if counter==number_of_spaceships:\r\n break\r\n print('Please enter spaceshipID',counter,' StartTime and EndTime:')\r\n a, b, c = map(int, input().strip().split())\r\n if a in spaceshipIDs:\r\n print('Id Must be Unique')\r\n else:\r\n if b in spaceshipTimes:\r\n print('Time Must be Unique')\r\n else:\r\n if c in spaceshipTimes:\r\n print('Time Must be Unique')\r\n else:\r\n if int(b) > int(c):\r\n print('Start Time must be smaller then End Time',spaceshipID.split()[1],'>',spaceshipID.split()[2])\r\n else:\r\n matrix[counter][0]=int(a)\r\n matrix[counter][1]=int(b)\r\n matrix[counter][2]=int(c)\r\n spaceshipIDs.append(int(a))\r\n spaceshipTimes.append(int(b))\r\n spaceshipTimes.append(int(c))\r\n scores[counter][0]=int(a)\r\n counter=counter+1\r\n \r\nfor i in range(0,number_of_spaceships):\r\n for j in range(0,number_of_spaceships):\r\n if matrix[i][1] < matrix[j][1]:\r\n if matrix[i][2] > matrix[j][2]:\r\n scores[i][1]=scores[i][1]+1\r\n \r\ntmp0=0\r\ntmp1=0 \r\nfor i in range(0,number_of_spaceships):\r\n for j in range(0,number_of_spaceships):\r\n if scores[i][1] prev[0]: # update second longest path\n prev = (total_d, other)\n path_n = node[4] - node[1]\n path_t = other_d\n \n if total_d > res[0]: # update longest path\n path_r = node[4] - node[1]\n path_s = other_d\n res = (total_d, other)\n \n path3_total = path_n + path_t + path_s # sum longest 3 branches\n \n \n## PART 3 ##\n##### Find path length of (second longest branch with branch) + (path_r = longest branch) #####\n path2 = find_path(res, dat) # find second longest path\n \n resn = path3_total # set result\n resq = find_length(path2, dat) # length of 2 branches on the second longest branch\n\n path2_total = resq+path_r # path2_total = (second longest branch with branch) + (longest branch)\n\n## PART 4 ##\n##### Compare results of PARTS 2 and 3 #####\n if resq == 0: # if (second longest branch with branch) = 0 then only 3 branch path is possible\n resn = path3_total\n else:\n resn = max(path2_total, path3_total)\n \n t2 = time.time()\n # print( \"iterate time {}\".format(t2-t1))\n return resn\n \n\ndef find_length(path, dat):\n resq = 0\n for i in range(len(path)):\n \n node = path[i]\n node = global_var.depths[node]\n try: # if node has 0 children continue\n children = dat[node[0]]\n except:\n continue\n if len(children) != 2: # if node has 1 child continue\n continue\n else: # if node has 2 children\n if path[i+1] == children[0]: # choose other to be child NOT on path to depest node\n other = children[1]\n else:\n other = children[0]\n \n other_d = global_var.depths[other][4] - node[1] # calculate length from deepest possible to current branching node depth\n total_d = other_d + node[4] - node[1] # calculate length from deepest possible to branching node deepest possible\n \n if total_d > resq: # update length of 2 branches on the second longest branch\n resq = total_d\n return resq\n \n \ndef find_path(res, dat):\n '''\n Finds path from arbitrary node its deepest child\n :param res: tuple where res[1] = node : res=(total_d, other)\n :return path: list path from node to its deepest child \n '''\n path = []\n node = res[1]\n cond = True\n while cond:\n try: \n path.append(node)\n children = dat[node]\n\n if global_var.depths[node][5] >= global_var.depths[node][6]:\n node = children[0]\n else:\n node = children[1]\n cond = True\n except:\n cond = False\n return path\n\ndef traversePostOrder(dat, node, depth, left, deepest):\n '''\n Recursive function which traverses the tree once and populates the global variables\n :param dat: dictionary where key is a parent and values are a list of 1 or 2 children nodes\n :param node: current node\n :param depth: current depth\n :param left: right node = 0, left node = 1\n :param deepest: the deepest child of node\n '''\n try: # if node is not a leaf\n tmp = dat[node]\n depth +=1\n leaf = 0\n \n\n traversePostOrder(dat,tmp[0],depth,left=1,deepest=deepest) # recurse left child\n deepest_l = global_var.depths[tmp[0]][4]\n deepest_r = 0\n\n if len(tmp) > 1:\n traversePostOrder(dat,tmp[1], depth,left=0,deepest=deepest) # recurse right child\n deepest_r = global_var.depths[tmp[1]][4]\n if global_var.path[-1:][0][0] == tmp[1]:\n deepest = max([deepest_l,deepest_r])\n global_var.path.append((node,depth,leaf,left,deepest,deepest_l,deepest_r))\n \n deepest = max([deepest_l,deepest_r])\n global_var.depths[node] = (node,depth,leaf,left,deepest,deepest_l,deepest_r)\n\n if global_var.path[-1:][0][0] == tmp[0]:\n global_var.path.append((node,depth,leaf,left,deepest,deepest_l,deepest_r))\n \n except: # reached leaf\n depth += 1\n leaf = 1\n deepest_l, deepest_r = depth,depth\n deepest = depth\n if depth > global_var.maxd[0]:\n global_var.maxd = (depth,node)\n global_var.path = [(node,depth,leaf,left, deepest,deepest_l,deepest_r)]\n\n global_var.depths[node] = (node,depth,leaf,left, deepest,deepest_l,deepest_r)\n\n\nif __name__ == '__main__':\n ############### TEST WITH FILES BELOW THIS LINE ###################\n # print(sys.argv)\n fn = sys.argv[1]\n \n fin = './datapub/pub'+ fn + '.in'\n fout = './datapub/pub'+ fn + '.out'\n print(fin)\n \n # dim, dat = read_input(fin)\n # # print(dim)\n # # print(dat)\n # res = read_output(fout)\n # my_res = solve(dim, dat)\n \n \n # print('Actual result: {}'.format(res))\n # print('My result: {}'.format(my_res))\n \n ############### TURN IN BELOW THIS LINE ##################\n \n # dim, dat = parse_input()\n # # print(dim)\n # # print(dat)\n # my_res = solve(dim, dat)\n # print(my_res)\n \n \n \n \n \n ","sub_path":"cvut/a3/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":10970,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"586077128","text":"# Project Euler\n# Problem 71 - Ordered Fractions\n# Copyright (c) Project Chang. All rights reserved.\n# Author: Sammy Chang\n#\n# https://github.com/schang1146/project_euler\n\nimport time\n\n\ndef prev_frac(d_max,frac):\n numer = 0\n denom = 1\n for i in range(1,d_max+1):\n if int(i*3/7)/i > numer/denom and int(i*3/7)/i < 3/7:\n numer = int(i*3/7)\n denom = i\n\n return numer, denom\n\n\nif __name__ == \"__main__\":\n startTime = time.time()\n print('Answer:', prev_frac(1000000,3/7))\n print('runtime:', time.time()-startTime, 'sec')\n","sub_path":"python/p071.py","file_name":"p071.py","file_ext":"py","file_size_in_byte":566,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"548431140","text":"# -*- coding: utf-8 -*-\nfrom LIBU3D5 import pack_assets\nimport os,traceback\ndef main():\n if not os.path.exists('assets/'):\n os.makedirs('assets/')\n fl = os.listdir('assets')\n for fn in fl:\n pack_assets(fn)\n os.system('pause')\nif __name__=='__main__':\n try:\n main()\n except:\n traceback.print_exc()\n os.system('pause')\n os._exit(0)\n","sub_path":"Repacker.py","file_name":"Repacker.py","file_ext":"py","file_size_in_byte":382,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"158599785","text":"import numpy as np\nimport os\nfrom scipy.misc import imresize, imread, imsave\n\ndef resize_img(input_data):\n input_r, input_c, _ = input_data.shape\n if input_r > input_c:\n output_c = 300\n output_r = np.int32(output_c*1.0/input_c*input_r)\n else:\n output_r = 300\n output_c = np.int32(output_r*1.0/input_r*input_c)\n resized_data = imresize(input_data,(output_r,output_c))\n\n crop_size = 256\n start_r = output_r/2 - crop_size/2\n start_c = output_c/2 - crop_size/2\n crop_data = resized_data[start_r:start_r+crop_size, start_c:start_c+crop_size, :]\n\n return crop_data\n\ndata_path = '/media/sunguofei/DATA1/road_data/'\ndata_type = 'rainy'\n\nfile_list = os.listdir(data_path+data_type)\nif not os.path.exists(data_path+'processed/'+data_type):\n os.mkdir(data_path+'processed/'+data_type)\nf = open('log.txt','w')\nnum=1\nfor file_obj in file_list:\n if file_obj.find('.jpg') >= 0:\n file_path = os.path.join(data_path+data_type, file_obj)\n img = imread(file_path,mode='RGB')\n process_data = resize_img(img)\n img_name = '/'+str(num).zfill(4)+'.jpg'\n\n imsave(data_path+'processed/'+data_type+img_name, process_data)\n f.write('{}\\n'.format(file_obj))\n num +=1\n\nf.close() ","sub_path":"process_data.py","file_name":"process_data.py","file_ext":"py","file_size_in_byte":1262,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"148362545","text":"from itertools import product\nfrom math import hypot, ceil\n\ndef checkio(radius):\n whole, partial = 0, 0\n for x0, y0 in product(range(ceil(radius)), repeat=2):\n if hypot(x0, y0) < radius:\n x1, y1 = x0 + 1, y0 + 1\n if hypot(x1, y1) <= radius:\n whole += 4\n else:\n partial += 4\n return [whole, partial]\nif __name__ == \"__main__\":\n assert checkio(2) == [4, 12]\n assert checkio(3) == [16, 20]\n assert checkio(2.1) == [4, 20]\n assert checkio(2.5) == [12, 20]","sub_path":"test3.py","file_name":"test3.py","file_ext":"py","file_size_in_byte":542,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"409580424","text":"import numpy as np\nimport scipy.io\nimport os\nfrom os.path import join\nimport shutil\n\nclass Log_collector(object):\n def __init__(self, log_dir = './log'):\n # Log dictionary\n self.log_dict = {}\n self.log_type = {}\n # Log saving directory\n self.log_dir = log_dir\n\n def new_log(self, name, type):\n pass\n\n def add_log(self, name, value):\n '''\n\n '''\n if name in self.log_dict.keys():\n self.log_dict[name] += self.to_list(value)\n else:\n self.log_dict[name] = self.to_list(value)\n\n def clear_log(self, names=None):\n if names is None:\n self.log_dict = {}\n return\n names = self.to_list(names)\n for key in names:\n if key in self.log_dict:\n self.log_dict.pop(key)\n else:\n print(\"log dictionary has no key: \"+name)\n\n def to_list(self, value):\n '''\n Convert data to list\n '''\n if type(value)==list:\n return value\n if type(value)==np.ndarray:\n return np.ndarray.tolist(value)\n return [value]\n\n def display_log(self):\n for key in self.log_dict.keys():\n print(key+': '+str(type(self.log_dict[key][0])))\n #\n print(key+': ('+str(len(self.log_dict[key]))+',)')\n\n def write_image_log(self, log_names):\n pass\n\n def write_log(self, combine_list=None):\n for key in self.log_dict.keys():\n self.write_txt(key, self.log_dict[key])\n self.write_mat(key, self.log_dict[key])\n\n if combine_list is not None:\n value_list = []\n for i in range(len(combine_list)):\n value_list = value_list + [self.log_dict[combine_list[i]]]\n self.write_txt(combine_list, value_list)\n pass\n\n def write_mat(self, log_name, value):\n '''\n Will be called in self.write_log\n '''\n log_path = join(self.log_dir, log_name+'.mat')\n # value = np.asarray(value)\n mat_dict = {log_name: value}\n scipy.io.savemat(log_path, mat_dict)\n\n def write_txt(self, log_name, value_list, overwrite=True):\n '''\n Will be called in self.write_log\n '''\n\n if type(log_name) is not list:\n log_path = join(self.log_dir, log_name+'.txt')\n else:\n log_path = join(self.log_dir, 'log.txt')\n\n if overwrite:\n f = open(log_path, 'w')\n else:\n f = open(log_path, 'a')\n\n if type(log_name) is not list:\n log_name = [log_name]\n value_list = [value_list]\n\n for i in range(len(value_list[0])):\n string = str(i)\n for j in range(len(log_name)):\n value = value_list[j][i]\n if type(value) == str:\n value_str = value\n else:\n value_str = ('{:8}'.format(value)).lstrip()\n string = string + \" \" + log_name[j] + \":\" + value_str\n string += '\\n'\n f.write(string)\n f.close()\n","sub_path":"model_template/Center_loss_mnist/common/log_collector.py","file_name":"log_collector.py","file_ext":"py","file_size_in_byte":3122,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"645563277","text":"# Copyright 2014\n# The Cloudscaling Group, Inc.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"); you may not\n# use this file except in compliance with the License. You may obtain a copy\n# of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport argparse\nimport json\nimport os.path\nimport sys\n\nfrom magnumclient.openstack.common import cliutils as utils\n\n\ndef _print_list_field(field):\n return lambda obj: ', '.join(getattr(obj, field))\n\n\ndef _show_container(container):\n utils.print_dict(container._info)\n\n\ndef _show_bay(bay):\n del bay._info['links']\n utils.print_dict(bay._info)\n\n\ndef _show_baymodel(baymodel):\n del baymodel._info['links']\n utils.print_dict(baymodel._info)\n\n\ndef _show_node(node):\n utils.print_dict(node._info)\n\n\ndef _show_pod(pod):\n utils.print_dict(pod._info)\n\n\ndef _show_rc(rc):\n utils.print_dict(rc._info)\n\n\ndef _show_service(service):\n utils.print_dict(service._info)\n\n\ndef do_bay_list(cs, args):\n \"\"\"Print a list of available bays.\"\"\"\n bays = cs.bays.list()\n columns = ('uuid', 'name', 'node_count')\n utils.print_list(bays, columns,\n {'versions': _print_list_field('versions')})\n\n\n@utils.arg('--name',\n metavar='',\n help='Name of the bay to create.')\n@utils.arg('--baymodel-id',\n metavar='',\n help='The bay model ID.')\n@utils.arg('--node-count',\n metavar='',\n help='The bay node count.')\ndef do_bay_create(cs, args):\n \"\"\"Create a bay.\"\"\"\n opts = {}\n opts['name'] = args.name\n opts['baymodel_id'] = args.baymodel_id\n opts['node_count'] = args.node_count\n\n bay = cs.bays.create(**opts)\n _show_baymodel(bay)\n\n\n@utils.arg('--id',\n required=True,\n metavar='',\n help='ID of the bay to delete.')\ndef do_bay_delete(cs, args):\n \"\"\"Delete a bay.\"\"\"\n cs.bays.delete(args.id)\n\n\n@utils.arg('--id',\n required=True,\n metavar='',\n help='ID of the bay to show.')\ndef do_bay_show(cs, args):\n bay = cs.bays.get(args.id)\n _show_bay(bay)\n\n\n@utils.arg('--name',\n metavar='',\n help='Name of the bay to create.')\n@utils.arg('--image-id',\n metavar='',\n help='The name or UUID of the base image to customize for the bay.')\n@utils.arg('--keypair-id',\n metavar='',\n help='The name or UUID of the SSH keypair to load into the'\n ' Bay nodes.')\n@utils.arg('--external-network-id',\n metavar='',\n help='The external Neutron network ID to connect to this bay'\n ' model.')\n@utils.arg('--dns-nameserver',\n metavar='',\n help='The DNS nameserver to use for this Bay.')\n@utils.arg('--flavor-id',\n metavar='',\n help='The nova flavor id to use when launching the bay.')\ndef do_baymodel_create(cs, args):\n \"\"\"Create a bay.\"\"\"\n opts = {}\n opts['name'] = args.name\n opts['flavor_id'] = args.flavor_id\n opts['image_id'] = args.image_id\n opts['keypair_id'] = args.keypair_id\n opts['external_network_id'] = args.external_network_id\n opts['dns_nameserver'] = args.dns_nameserver\n\n bay = cs.baymodels.create(**opts)\n _show_baymodel(bay)\n\n\n@utils.arg('--id',\n metavar='',\n help='ID of the bay to delete.')\ndef do_baymodel_delete(cs, args):\n \"\"\"Delete a bay.\"\"\"\n cs.baymodels.delete(args.id)\n\n\n@utils.arg('--id',\n metavar='',\n help='ID of the bay to show.')\ndef do_baymodel_show(cs, args):\n baymodel = cs.baymodels.get(args.id)\n _show_baymodel(baymodel)\n\n\ndef do_baymodel_list(cs, args):\n \"\"\"Print a list of bay models.\"\"\"\n nodes = cs.baymodels.list()\n columns = ('uuid', 'name')\n utils.print_list(nodes, columns,\n {'versions': _print_list_field('versions')})\n\n\ndef do_node_list(cs, args):\n \"\"\"Print a list of configured nodes.\"\"\"\n nodes = cs.nodes.list()\n columns = ('uuid', 'type', 'image_id')\n utils.print_list(nodes, columns,\n {'versions': _print_list_field('versions')})\n\n\n@utils.arg('--type',\n metavar='',\n help='Type of node to create (virt or bare).')\n@utils.arg('--image-id',\n metavar='',\n help='The name or UUID of the base image to use for the node.')\ndef do_node_create(cs, args):\n \"\"\"Create a node.\"\"\"\n opts = {}\n opts['type'] = args.type\n opts['image_id'] = args.image_id\n\n node = cs.nodes.create(**opts)\n _show_node(node)\n\n\ndef do_pod_list(cs, args):\n \"\"\"Print a list of registered pods.\"\"\"\n pods = cs.pods.list()\n columns = ('uuid', 'name')\n utils.print_list(pods, columns,\n {'versions': _print_list_field('versions')})\n\n\n@utils.arg('--manifest-url',\n metavar='',\n help='Name/URL of the pod file to use for creating PODs.')\n@utils.arg('--manifest',\n metavar='',\n help='File path of the pod file to use for creating PODs.')\n@utils.arg('--bay-id',\n required=True,\n metavar='',\n help='The bay ID.')\ndef do_pod_create(cs, args):\n \"\"\"Create a pod.\"\"\"\n opts = {}\n opts['manifest_url'] = args.manifest_url\n opts['bay_uuid'] = args.bay_id\n\n if args.manifest is not None and os.path.isfile(args.manifest):\n with open(args.manifest, 'r') as f:\n opts['manifest'] = f.read()\n\n node = cs.pods.create(**opts)\n _show_pod(node)\n pass\n\n\n@utils.arg('--id',\n required=True,\n metavar='',\n help='ID of the pod to delete.')\ndef do_pod_delete(cs, args):\n \"\"\"Delete a pod.\"\"\"\n cs.pods.delete(args.id)\n pass\n\n\n@utils.arg('--id',\n required=True,\n metavar='',\n help='ID of the pod to show.')\ndef do_pod_show(cs, args):\n pod = cs.pods.get(args.id)\n _show_pod(pod)\n\n\ndef do_rc_list(cs, args):\n \"\"\"Print a list of registered replication controllers.\"\"\"\n rcs = cs.rcs.list()\n columns = ('uuid', 'name')\n utils.print_list(rcs, columns,\n {'versions': _print_list_field('versions')})\n\n\n@utils.arg('--manifest-url',\n metavar='',\n help='Name/URL of the replication controller file to use for '\n 'creating replication controllers.')\n@utils.arg('--manifest',\n metavar='',\n help='File path of the replication controller file to use for '\n 'creating replication controllers.')\n@utils.arg('--bay-id',\n required=True,\n metavar='',\n help='The bay ID.')\ndef do_rc_create(cs, args):\n \"\"\"Create a replication controller.\"\"\"\n opts = {}\n opts['manifest_url'] = args.manifest_url\n opts['bay_uuid'] = args.bay_id\n\n if args.manifest is not None and os.path.isfile(args.manifest):\n with open(args.manifest, 'r') as f:\n opts['manifest'] = f.read()\n\n rc = cs.rcs.create(**opts)\n _show_rc(rc)\n\n\n@utils.arg('--id',\n required=True,\n metavar='',\n help='ID of the replication controller to delete.')\ndef do_rc_delete(cs, args):\n \"\"\"Delete a replication controller.\"\"\"\n cs.rcs.delete(args.id)\n\n\n@utils.arg('--id',\n required=True,\n metavar='',\n help='ID of the replication controller to show.')\ndef do_rc_show(cs, args):\n rc = cs.rcs.get(args.id)\n _show_rc(rc)\n\n\ndef do_service_list(cs, args):\n \"\"\"Print a list of services.\"\"\"\n services = cs.services.list()\n columns = ('uuid', 'name', 'bay_uuid')\n utils.print_list(services, columns,\n {'versions': _print_list_field('versions')})\n\n\n@utils.arg('--manifest-url',\n metavar='',\n help='Name/URL of the serivce file to use for creating services.')\n@utils.arg('--manifest',\n metavar='',\n help='File path of the service file to use for creating services.')\n@utils.arg('--bay-id',\n required=True,\n metavar='',\n help='The bay ID.')\ndef do_service_create(cs, args):\n \"\"\"Create a service.\"\"\"\n opts = {}\n opts['manifest_url'] = args.manifest_url\n opts['bay_uuid'] = args.bay_id\n\n if args.manifest is not None and os.path.isfile(args.manifest):\n with open(args.manifest, 'r') as f:\n opts['manifest'] = f.read()\n\n service = cs.services.create(**opts)\n _show_service(service)\n\n\n@utils.arg('--id',\n required=True,\n metavar='',\n help='ID of the service to delete.')\ndef do_service_delete(cs, args):\n \"\"\"Delete a service.\"\"\"\n cs.services.delete(args.id)\n\n\n@utils.arg('--id',\n required=True,\n metavar='',\n help='ID of the service to show.')\ndef do_service_show(cs, args):\n service = cs.services.get(args.id)\n _show_service(service)\n\n\n#\n# Containers\n\n@utils.arg('--json',\n default=sys.stdin,\n type=argparse.FileType('r'),\n help='JSON representation of container.')\ndef do_container_create(cs, args):\n \"\"\"Create a container.\"\"\"\n container = json.loads(args.json.read())\n _show_container(cs.containers.create(**container))\n\n\ndef do_container_list(cs, args):\n \"\"\"Print a list of available containers.\"\"\"\n containers = cs.containers.list()\n columns = ('uuid', 'name', 'desc')\n utils.print_list(containers, columns,\n {'versions': _print_list_field('versions')})\n\n\n@utils.arg('--id',\n required=True,\n metavar='',\n help='ID of the container to delete.')\ndef do_container_delete(cs, args):\n \"\"\"Delete a container.\"\"\"\n cs.containers.delete(args.id)\n\n\n@utils.arg('--id',\n required=True,\n metavar='',\n help='ID of the container to show.')\n@utils.arg('--json',\n action='store_true',\n default=False,\n help='Print JSON representation of the container.')\ndef do_container_show(cs, args):\n \"\"\"Show details of a container.\"\"\"\n container = cs.containers.get(args.id)\n if args.json:\n print(json.dumps(container._info))\n else:\n _show_container(container)\n\n\n@utils.arg('--id',\n required=True,\n metavar='',\n help='ID of the container to start.')\ndef do_container_reboot(cs, args):\n cs.containers.reboot(args.id)\n\n\n@utils.arg('--id',\n required=True,\n metavar='',\n help='ID of the container to start.')\ndef do_container_stop(cs, args):\n cs.containers.stop(args.id)\n\n\n@utils.arg('--id',\n required=True,\n metavar='',\n help='ID of the container to start.')\ndef do_container_start(cs, args):\n cs.containers.start(args.id)\n\n\n@utils.arg('--id',\n required=True,\n metavar='',\n help='ID of the container to start.')\ndef do_container_pause(cs, args):\n cs.containers.pause(args.id)\n\n\n@utils.arg('--id',\n required=True,\n metavar='',\n help='ID of the container to start.')\ndef do_container_unpause(cs, args):\n cs.containers.unpause(args.id)\n\n\n@utils.arg('--id',\n required=True,\n metavar='',\n help='ID of the container to start.')\ndef do_container_logs(cs, args):\n cs.containers.logs(args.id)\n\n\n@utils.arg('--id',\n required=True,\n metavar='',\n help='ID of the container to start.')\n@utils.arg('--command',\n required=True,\n metavar='',\n help='The command to execute')\ndef do_container_execute(cs, args):\n cs.containers.execute(args.id, args.command)\n","sub_path":"magnumclient/v1/shell.py","file_name":"shell.py","file_ext":"py","file_size_in_byte":12250,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"171919680","text":"import string\nfrom collections import *\nfrom io import StringIO\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport sys\n\n\n#\n# readcsv is a starting point - it returns the rows from a standard csv file...\n#\ndef readcsv( csv_file_name ):\n \"\"\" readcsv takes as\n + input: csv_file_name, the name of a csv file\n and returns\n + output: a list of lists, each inner list is one row of the csv\n all data items are strings; empty cells are empty strings\n \"\"\"\n try:\n csvfile = open( csv_file_name, newline='' ) # open for reading\n csvrows = csv.reader( csvfile ) # creates a csvrows object\n\n all_rows = [] # we need to read the csv file\n for row in csvrows: # into our own Python data structure\n all_rows.append( row ) # adds only the word to our list\n\n del csvrows # acknowledge csvrows is gone!\n csvfile.close() # and close the file\n return all_rows # return the list of lists\n\n except FileNotFoundError as e:\n print(\"File not found: \", e)\n return []\n\n#\n# write_to_csv shows how to write that format from a list of rows...\n# + try write_to_csv( [['a', 1 ], ['b', 2]], \"smallfile.csv\" )\n#\ndef write_to_csv( list_of_rows, filename ):\n \"\"\" write_to_csv shows how to write that format from a list of rows...\n# + try write_to_csv( [['a', 1 ], ['b', 2]], \"smallfile.csv\" )\n \"\"\"\n try:\n csvfile = open( filename, \"w\", newline='' )\n filewriter = csv.writer( csvfile, delimiter=\",\")\n for row in list_of_rows:\n filewriter.writerow( row )\n csvfile.close()\n\n except:\n print(\"File\", filename, \"could not be opened for writing...\")\n\n# For Pandas's read_csv, use header=0 when you know row 0 is a header row\n# df here is a \"dataframe\":\nfile = 'reviews_mid.csv'\n\nif file == 'reviews_mid.csv':\n df = pd.read_csv(file, header=None)\n df.columns = [\"review_id\",\t\"business_id\", \"user_id\", \"stars\", \"date\", \"text\", \"useful\", \"funny\", \"cool\"]\nif file == 'reviews_1000.csv':\n df = pd.read_csv('reviews_1000.csv', header=0)\n\ndf.info()\n\n#let's drop columns with too few values or that won't be meaningful\ncol = ['stars', 'text']\ndf = df[col]\ndf = df[pd.notnull(df['text'])]\ndf.columns = ['stars', 'text']\n\n#dictionaries for future use\n# category_to_id = dict(category_id_df.values)\n# id_to_category = dict(category_id_df[['category_id', 'Product']].values)\n\nprint(\"+++ End of pandas +++\\n\")\n\n#display some data info\nfig = plt.figure(figsize=(8,6))\ndf.groupby('stars').text.count().plot.bar(ylim=0)\nplt.show()\n\nprint()\nc = input(\"continue? y/n: \")\nif c == 'n':\n sys.exit()\n\n\"\"\"\nbag of words. Turning text data into managebale forms \n\"\"\"\n\nfrom sklearn.feature_extraction.text import TfidfVectorizer\n\n#standard setting \ntfidf = TfidfVectorizer(sublinear_tf=True, min_df=5, norm='l2', encoding='latin-1', ngram_range=(1, 2), stop_words='english')\nfeatures = tfidf.fit_transform(df.text).toarray() #fit model\nlabels = df.stars\nfeatures.shape\n\n#now we can use sklearn.feature_selection.chi2 to find the words that are most correlated with the stars \nfrom sklearn.feature_selection import chi2\n\nN = 10\nSTARS = [1,2,3,4,5]\n\nfor star in sorted(STARS):\n features_chi2 = chi2(features, labels == star)\n indices = np.argsort(features_chi2[0])\n feature_names = np.array(tfidf.get_feature_names())[indices]\n unigrams = [v for v in feature_names if len(v.split(' ')) == 1]\n bigrams = [v for v in feature_names if len(v.split(' ')) == 2]\n print(\"# 'rating star - {}':\".format(star))\n print(\" . Most correlated unigrams:\\n. {}\".format('\\n. '.join(unigrams[-N:])))\n print(\" . Most correlated bigrams:\\n. {}\".format('\\n. '.join(bigrams[-N:])))\n\nprint()\nc = input(\"continue? y/n: \")\nif c == 'n':\n sys.exit()\n\"\"\"\nTime to train our classifier \n\"\"\"\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.feature_extraction.text import CountVectorizer\nfrom sklearn.feature_extraction.text import TfidfTransformer\nfrom sklearn.naive_bayes import MultinomialNB\n\n#X is our feature, y is our target result which is stars \nX_train, X_test, y_train, y_test = train_test_split(df['text'], df['stars'], random_state = 0)\ncount_vect = CountVectorizer()\nX_train_counts = count_vect.fit_transform(X_train) #vectorizing text data \ntfidf_transformer = TfidfTransformer() \nX_train_tfidf = tfidf_transformer.fit_transform(X_train_counts)\n\n#count_vect = CountVectorizer()\n#tfidf_transformer = TfidfTransformer()\nX_test_counts = count_vect.transform(X_test)\nX_test_tfidf = tfidf_transformer.transform(X_test_counts)\n\n\nclf = MultinomialNB().fit(X_train_tfidf, y_train) #classifying transformed text data to target value \n\n#calculating the mean accuracy on the given test data and labels \ntraining_score = clf.score(X_train_tfidf, y_train, sample_weight = None)\ntesting_score = clf.score(X_test_tfidf, y_test, sample_weight = None)\nprint()\nprint(\"the training_score is \" + str(training_score))\nprint()\nprint(\"the testing_score is \" + str(testing_score))\n\nc = input(\"continue? y/n: \")\nif c == 'n':\n sys.exit()\n\"\"\"\nTest out different ML models\n\"\"\"\n\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.ensemble import RandomForestClassifier\nfrom sklearn.svm import LinearSVC\nfrom sklearn.model_selection import cross_val_score\n\n\nmodels = [\n RandomForestClassifier(n_estimators=100, max_depth=20, random_state=0),\n LinearSVC(),\n MultinomialNB(),\n LogisticRegression(random_state=0),\n]\n\n\nCV = 5\ncv_df = pd.DataFrame(index=range(CV * len(models)))\nentries = []\nfor model in models:\n model_name = model.__class__.__name__\n accuracies = cross_val_score(model, features, labels, scoring='accuracy', cv=CV)\n for fold_idx, accuracy in enumerate(accuracies):\n entries.append((model_name, fold_idx, accuracy))\ncv_df = pd.DataFrame(entries, columns=['model_name', 'fold_idx', 'accuracy'])\nimport seaborn as sns\nsns.boxplot(x='model_name', y='accuracy', data=cv_df)\nsns.stripplot(x='model_name', y='accuracy', data=cv_df, \n size=8, jitter=True, edgecolor=\"gray\", linewidth=2)\n\nmedian_accuracy = []\nindex = 0\naccuracy = cv_df.accuracy \nwhile index < 20:\n ave = 0\n for off_set in range(5):\n ave += accuracy[index + off_set]\n median_accuracy.append(ave / 5)\n index += 5\n\nplt.show()\nprint(\"Median acurracy for each of the four models tested\")\nprint()\nprint(\"RandomForestClassifier: \" + str(median_accuracy[0]))\nprint(\"LinearSVC: \" + str(median_accuracy[1]))\nprint(\"MultinomialNB: \" + str(median_accuracy[2]))\nprint(\"LogisticRegression: \" + str(median_accuracy[3]))\n\nprint()\nc = input(\"continue? y/n: \")\nif c == 'n':\n sys.exit()\n\"\"\"\nFurther Digging into the LinearSVC model\n\"\"\"\n\nmodel = LinearSVC()\nX_train, X_test, y_train, y_test, indices_train, indices_test = train_test_split(features, labels, df.index, test_size=0.33, random_state=0)\nmodel.fit(X_train, y_train)\ny_pred = model.predict(X_test)\n\nfrom sklearn.metrics import confusion_matrix\n\nconf_mat = confusion_matrix(y_test, y_pred)\nfig, ax = plt.subplots(figsize=(10,10))\naxis = np.array([1,2,3,4,5])\nsns.heatmap(conf_mat, annot=True, fmt='d', xticklabels = axis, yticklabels = axis)\nplt.ylabel('Actual')\nplt.xlabel('Predicted')\nplt.show()\n\nprint()\nc = input(\"continue? y/n: \")\nif c == 'n':\n sys.exit()\n\"\"\"\nDisplay misprediction\n\"\"\"\n\nfrom IPython.display import display\n\nfor predicted in axis:\n for actual in axis:\n if predicted != actual and conf_mat[actual-1, predicted-1] >= 10:\n print(\"'{}' predicted as '{}' : {} examples.\".format(actual, predicted, conf_mat[actual-1, predicted-1]))\n display(df.loc[indices_test[(y_test == actual) & (y_pred == predicted)]].head(20)[['stars', 'text']])\n print('')\n\nprint()\nc = input(\"continue? y/n: \")\nif c == 'n':\n sys.exit()\n\"\"\"\nMore relevent for each star using LinearSVC\n\"\"\"\nmodel.fit(features, labels)\nN = 10\n\nfor star in sorted(STARS):\n indices = np.argsort(model.coef_[star-1])\n feature_names = np.array(tfidf.get_feature_names())[indices]\n unigrams = [v for v in reversed(feature_names) if len(v.split(' ')) == 1][:N]\n bigrams = [v for v in reversed(feature_names) if len(v.split(' ')) == 2][:N]\n print(\"# 'rating star - {}':\".format(star))\n print(\" . Most correlated unigrams:\\n. {}\".format('\\n. '.join(unigrams[-N:])))\n print(\" . Most correlated bigrams:\\n. {}\".format('\\n. '.join(bigrams[-N:])))\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n","sub_path":"old_files/review_rating_cla.py","file_name":"review_rating_cla.py","file_ext":"py","file_size_in_byte":8545,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"282100035","text":"import time\nimport datetime\n\nimport torch\nimport torchvision\nimport torchvision.transforms as transforms\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torch.optim as optim\nimport matplotlib.pyplot as plt\nimport numpy as np\n\n'''\nMobileNetV2 structure\n> see \"MobileNetV2: Inverted Residuals and Linear Bottlenecks\"\n'''\n\nclass MobileNetV2(nn.Module):\n\n def __init__(self):\n super(MobileNetV2, self).__init__()\n\n self.init_conv = nn.Conv2d(3, 32, kernel_size=3, padding=1, bias=False)\n self.init_bn = nn.BatchNorm2d(32)\n self.relu6 = nn.ReLU6(inplace=True)\n\n sequence_list = [ (1, 16, 1, 1),\n (6, 24, 2, 2),\n (6, 32, 3, 2),\n (6, 64, 4, 2),\n (6, 96, 3, 1),\n (6, 160, 3, 2),\n (6, 320, 1, 1) ]\n\n layers = []\n in_channels = 32\n for t, c, n, s in sequence_list:\n layers += self.make_sequence(in_channels, t, c, n, s)\n in_channels = c\n self.sequences = nn.Sequential(*layers)\n\n self.conv1 = nn.Conv2d(320, 1280, kernel_size=1, padding=0, bias=False)\n self.bn1 = nn.BatchNorm2d(1280)\n self.FNN = nn.Linear(1280, 10)\n #self.conv2 = nn.Conv2d(1280, 10, kernel_size=1, padding=0, bias=False)\n #self.bn2 = nn.BatchNorm2d(10)\n\n def forward(self, x):\n out = self.init_conv(x)\n out = self.init_bn(out)\n out = self.relu6(out)\n\n out = self.sequences(out)\n\n out = self.conv1(out)\n out = self.bn1(out)\n out = self.relu6(out)\n\n out = F.adaptive_avg_pool2d(out, (1,1))\n\n #out = self.conv2(out)\n #out = self.bn2(out)\n #out = self.relu6(out)\n\n out = out.view(out.size(0), -1)\n\n out = self.FNN(out)\n\n return out\n\n def make_sequence(self, in_ch, t, c, n, s):\n layers = []\n layers.append(ConV2Unit(in_ch, c, s, t))\n for i in range(n-1):\n layers.append(ConV2Unit(c, c, 1, t))\n return layers\n\nclass ConV2Unit(nn.Module):\n\n def __init__(self, in_channels, out_channels, stride=1, expansion_factor=6): \n super(ConV2Unit, self).__init__()\n\n self.t = expansion_factor\n self.s = stride\n\n if in_channels != out_channels:\n self.projection = IdentityPadding(out_channels, in_channels, stride)\n else:\n self.projection = None\n\n self.relu6 = nn.ReLU6(inplace=True)\n\n self.conv1 = nn.Conv2d(in_channels, in_channels*self.t, kernel_size=1, padding=0, bias=False)\n self.bn1 = nn.BatchNorm2d(in_channels*self.t)\n self.dw_conv = nn.Conv2d(in_channels*self.t, in_channels*self.t, kernel_size=3, stride=self.s, padding=1, groups=in_channels*self.t, bias=False)\n self.dw_bn = nn.BatchNorm2d(in_channels*self.t)\n self.conv2 = nn.Conv2d(in_channels*self.t, out_channels, kernel_size=1, padding=0, bias=False)\n self.bn2 = nn.BatchNorm2d(out_channels)\n\n def forward(self, x):\n residual = x\n \n out = self.conv1(x)\n out = self.bn1(out)\n out = self.relu6(out)\n\n out = self.dw_conv(out)\n out = self.dw_bn(out)\n out = self.relu6(out)\n\n out = self.conv2(out)\n out = self.bn2(out)\n\n if self.s == 1:\n if self.projection:\n residual = self.projection(residual)\n out += residual\n\n return out\n\nclass IdentityPadding(nn.Module):\n def __init__(self, num_filters, channels_in, stride):\n super(IdentityPadding, self).__init__()\n\n self.identity = nn.MaxPool2d(1, stride=stride)\n self.num_zeros = num_filters - channels_in\n \n def forward(self, x):\n out = F.pad(x, (0, 0, 0, 0, 0, self.num_zeros))\n out = self.identity(out)\n return out\n","sub_path":"CIFAR10_MobileNetV2.py","file_name":"CIFAR10_MobileNetV2.py","file_ext":"py","file_size_in_byte":3897,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"333527846","text":"import sys\nimport random\ndef win_lose(n, s, e):\n sum_vil = 0\n sum_pla = 0\n result = []\n for i in range(0,n):\n sum_vil+=s[i]\n sum_pla+=e[i]\n if (sum_pla>sum_vil):\n return 'WIN'\n else:\n return 'LOSE'\nif __name__=='__main__':\n test_cases = int(input())\n strength_villain=[]\n energy_player=[]\n test_cases_result=[]\n #random.shuffle(strength_villain)\n #random.shuffle(energy_player)\n while test_cases > 0:\n n = int(input())\n strength_villain = list(map(int, input().rstrip().split()))[:n]\n energy_player = list(map(int, input().rstrip().split()))[:n]\n #random.shuffle(strength_villain)\n #random.shuffle(energy_player)\n #sys.stdout.write(str(strength_villain))\n #sys.stdout.write(str(energy_player))\n test_cases_result.append(str(win_lose(n,strength_villain,energy_player)))\n test_cases-=1\n sys.stdout.write('\\n'.join(test_cases_result))\n sys.stdout.write('\\n')\n","sub_path":"Techgig/WinLose_1.py","file_name":"WinLose_1.py","file_ext":"py","file_size_in_byte":992,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"437938269","text":"from clientes import Clientes\nfrom tkinter import *\n\n\nclass Aplicacao:\n def __init__(self, master=None):\n self.frame = Frame(master)\n self.frame.pack()\n self.fonte = (\"Verdana\", \"8\")\n self.menu = Menu(master)\n self.menu[\"bg\"] = '#282a36'\n self.menu[\"fg\"] = '#42f97a'\n self.menuCadastro = Menu(self.menu)\n self.menuOpcoes = Menu(self.menu)\n self.subMenu = Menu(self.menu)\n self.menuCadastro.add_cascade(label='Cliente', menu=self.subMenu)\n self.subMenu.add_command(label=' Cadastrar cliente', command=self.cadastrar)\n self.menu.add_cascade(label='Cadastro', menu=self.menuCadastro)\n self.menu.add_cascade(label='Opções', menu=self.menuOpcoes)\n self.menuOpcoes.add_command(label='Sair', command=self.sair)\n master.config(menu=self.menu)\n\n\n def cadastrar(self):\n # self.newApp = Cadastro()\n self.new_jan = Tk()\n Cadastro(self.new_jan)\n self.new_jan.title(\"Clientes\")\n self.new_jan.geometry('500x400')\n self.new_jan[\"bg\"] = '#282a36'\n self.new_jan.mainloop()\n\n def sair(self):\n root.destroy()\n return\n\n\nclass Cadastro:\n def __init__(self, master=None):\n self.fonte = (\"Verdana\", \"8\")\n self.container1 = Frame(master)\n self.container1[\"pady\"] = 10\n self.container1[\"bg\"] = '#282a36'\n self.container1.pack()\n self.container2 = Frame(master)\n self.container2[\"padx\"] = 20\n self.container2[\"pady\"] = 5\n self.container2[\"bg\"] = '#282a36'\n self.container2.pack()\n self.container3 = Frame(master)\n self.container3[\"padx\"] = 20\n self.container3[\"pady\"] = 5\n self.container3[\"bg\"] = '#282a36'\n self.container3.pack()\n self.container4 = Frame(master)\n self.container4[\"padx\"] = 20\n self.container4[\"pady\"] = 5\n self.container4[\"bg\"] = '#282a36'\n self.container4.pack()\n self.container5 = Frame(master)\n self.container5[\"padx\"] = 20\n self.container5[\"pady\"] = 5\n self.container5[\"bg\"] = '#282a36'\n self.container5.pack()\n self.container6 = Frame(master)\n self.container6[\"padx\"] = 20\n self.container6[\"pady\"] = 5\n self.container6[\"bg\"] = '#282a36'\n self.container6.pack()\n self.container7 = Frame(master)\n self.container7[\"padx\"] = 20\n self.container7[\"pady\"] = 5\n self.container7[\"bg\"] = '#282a36'\n self.container7.pack()\n self.container8 = Frame(master)\n self.container8[\"padx\"] = 20\n self.container8[\"pady\"] = 10\n self.container8[\"bg\"] = '#282a36'\n self.container8.pack()\n self.container9 = Frame(master)\n self.container9[\"pady\"] = 15\n self.container9[\"bg\"] = '#282a36'\n self.container9.pack()\n self.container10 = Frame(master)\n self.container10['padx'] = 20\n self.container10['pady'] = 10\n self.container10.pack()\n\n self.titulo = Label(self.container1, text=\"Informe os dados :\")\n self.titulo[\"bg\"] = '#282a36'\n self.titulo[\"fg\"] = '#42f97a'\n self.titulo[\"font\"] = (\"Calibri\", \"9\", \"bold\")\n self.titulo.pack()\n\n self.lblidcliente = Label(self.container2,\n text=\"idcliente:\", font=self.fonte, width=10)\n self.lblidcliente[\"bg\"] = '#282a36'\n self.lblidcliente[\"fg\"] = '#42f97a'\n self.lblidcliente.pack(side=LEFT)\n\n self.txtidcliente = Entry(self.container2)\n self.txtidcliente[\"width\"] = 10\n self.txtidcliente[\"font\"] = self.fonte\n self.txtidcliente.pack(side=LEFT)\n\n self.btnBuscar = Button(self.container2, text=\"Buscar\",\n font=self.fonte, width=10)\n self.btnBuscar[\"bg\"] = '#282a36'\n self.btnBuscar[\"fg\"] = '#42f97a'\n self.btnBuscar[\"command\"] = self.buscarCliente\n self.btnBuscar.pack(side=RIGHT)\n\n self.lblnome = Label(self.container3, text=\"Nome:\",\n font=self.fonte, width=10)\n self.lblnome[\"bg\"] = '#282a36'\n self.lblnome[\"fg\"] = '#42f97a'\n self.lblnome.pack(side=LEFT)\n\n self.txtnome = Entry(self.container3)\n self.txtnome[\"width\"] = 25\n self.txtnome[\"font\"] = self.fonte\n self.txtnome.pack(side=LEFT)\n\n self.radio = Variable\n self.lbltipo = Label(self.container4, text=\"Tipo pessoa:\",\n font=self.fonte, width=10)\n self.lbltipo[\"bg\"] = '#282a36'\n self.lbltipo[\"fg\"] = '#42f97a'\n self.lbltipo.pack(side=LEFT)\n\n self.txttipo = Entry(self.container4)\n self.txttipo[\"width\"] = 25\n self.txttipo[\"font\"] = self.fonte\n self.txttipo.pack(side=LEFT)\n\n\n self.lblemail = Label(self.container5, text=\"E-mail:\",\n font=self.fonte, width=10)\n self.lblemail[\"bg\"] = '#282a36'\n self.lblemail[\"fg\"] = '#42f97a'\n self.lblemail.pack(side=LEFT)\n\n self.txtemail = Entry(self.container5)\n self.txtemail[\"width\"] = 25\n self.txtemail[\"font\"] = self.fonte\n self.txtemail.pack(side=LEFT)\n\n self.lblcidade = Label(self.container6, text=\"Cidade:\",\n font=self.fonte, width=10)\n self.lblcidade[\"bg\"] = '#282a36'\n self.lblcidade[\"fg\"] = '#42f97a'\n self.lblcidade.pack(side=LEFT)\n\n self.txtcidade = Entry(self.container6)\n self.txtcidade[\"width\"] = 25\n self.txtcidade[\"font\"] = self.fonte\n self.txtcidade.pack(side=LEFT)\n\n self.lblcpf_cnpj = Label(self.container7, text=\"cpf_cnpj\",\n font=self.fonte, width=10)\n self.lblcpf_cnpj[\"bg\"] = '#282a36'\n self.lblcpf_cnpj[\"fg\"] = '#42f97a'\n self.lblcpf_cnpj.pack(side=LEFT)\n\n self.txtcpf_cnpj = Entry(self.container7)\n self.txtcpf_cnpj[\"width\"] = 22\n #self.txtcpf_cnpj[\"show\"] = \"*\"\n self.txtcpf_cnpj[\"font\"] = self.fonte\n self.txtcpf_cnpj.pack(side=LEFT)\n\n #self.imgBotao = PhotoImage(file=\"olho15x15.png\")\n #self.bntMostrarSenha = Button(self.container7, image=self.imgBotao,\n #font=self.fonte, width=15, height=15)\n #self.bntMostrarSenha[\"command\"] = self.mostartSenha\n #self.bntMostrarSenha.pack(side=LEFT)\n\n self.bntInsert = Button(self.container8, text=\"Inserir\",\n font=self.fonte, width=12)\n self.bntInsert[\"bg\"] = '#282a36'\n self.bntInsert[\"fg\"] = '#42f97a'\n self.bntInsert[\"command\"] = self.inserirCliente\n self.bntInsert.pack(side=LEFT)\n\n self.bntAlterar = Button(self.container8, text=\"Alterar\",\n font=self.fonte, width=12)\n self.bntAlterar[\"bg\"] = '#282a36'\n self.bntAlterar[\"fg\"] = '#42f97a'\n self.bntAlterar[\"command\"] = self.alterarCliente\n self.bntAlterar.pack(side=LEFT)\n\n self.bntExcluir = Button(self.container8, text=\"Excluir\",\n font=self.fonte, width=12)\n self.bntExcluir[\"bg\"] = '#282a36'\n self.bntExcluir[\"fg\"] = '#42f97a'\n self.bntExcluir[\"command\"] = self.excluirCliente\n self.bntExcluir.pack(side=LEFT)\n\n self.lblmsg = Label(self.container9, text=\"\")\n self.lblmsg[\"font\"] = (\"Verdana\", \"9\", \"italic\")\n self.lblmsg.pack()\n\n self.bntSair = Button(self.container8, text=\"Voltar\",\n font=self.fonte, width=12)\n self.bntSair[\"bg\"] = '#282a36'\n self.bntSair[\"fg\"] = '#42f97a'\n self.bntSair[\"command\"] = self.voltar\n self.bntSair.pack(side=LEFT)\n\n def voltar(self):\n pass\n\n \"\"\"def mostartSenha(self):\n if self.txtsenha[\"show\"] == \"*\":\n self.txtsenha[\"show\"] = \"\"\n else:\n self.txtsenha[\"show\"] = \"*\"\n \"\"\"\n\n def inserirCliente(self):\n user = Clientes()\n\n user.nome = self.txtnome.get()\n user.tipo = self.txttipo.get()\n user.email = self.txtemail.get()\n user.cidade = self.txtcidade.get()\n user.cpf_cnpj = self.txtcpf_cnpj.get()\n\n\n self.lblmsg[\"text\"] = user.insertUser()\n\n self.txtidcliente.delete(0, END)\n self.txtnome.delete(0, END)\n self.txttipo.delete(0, END)\n self.txtemail.delete(0, END)\n self.txtcidade.delete(0, END)\n self.txtcpf_cnpj.delete(0, END)\n\n def alterarCliente(self):\n user = Clientes()\n\n user.idcliente = self.txtidcliente.get()\n user.nome = self.txtnome.get()\n user.tipo = self.txttipo.get()\n user.email = self.txtemail.get()\n user.cidade = self.txtcidade.get()\n user.cpf_cnpj = self.txtcpf_cnpj.get()\n\n self.lblmsg[\"text\"] = user.updateUser()\n\n self.txtidcliente.delete(0, END)\n self.txtnome.delete(0, END)\n self.txttipo.delete(0, END)\n self.txtemail.delete(0, END)\n self.txtcidade.delete(0, END)\n self.txtcpf_cnpj.delete(0, END)\n\n def excluirCliente(self):\n user = Clientes()\n\n user.idcliente = self.txtidcliente.get()\n\n self.lblmsg[\"text\"] = user.deleteUser()\n\n self.txtidcliente.delete(0, END)\n self.txtnome.delete(0, END)\n self.txttipo.delete(0, END)\n self.txtemail.delete(0, END)\n self.txtcidade.delete(0, END)\n self.txtcpf_cnpj.delete(0, END)\n\n def buscarCliente(self):\n user = Clientes()\n\n idcliente = self.txtidcliente.get()\n\n self.lblmsg[\"text\"] = user.selectUser(idcliente)\n\n self.txtidcliente.delete(0, END)\n self.txtidcliente.insert(INSERT, user.idcliente)\n\n self.txtnome.delete(0, END)\n self.txtnome.insert(INSERT, user.nome)\n\n self.txttipo.delete(0, END)\n self.txttipo.insert(INSERT, user.tipo)\n\n self.txtemail.delete(0, END)\n self.txtemail.insert(INSERT, user.email)\n\n self.txtcidade.delete(0, END)\n self.txtcidade.insert(INSERT, user.cidade)\n\n self.txtcpf_cnpj.delete(0, END)\n self.txtcpf_cnpj.insert(INSERT, user.cpf_cnpj)\n\n\n\n\n\n\nroot = Tk()\nroot.title(\"Programa versão 1.0.0\")\nroot.geometry('500x400')\nroot[\"bg\"] = '#282a36'\n# root.configure(background='#282a36')\nAplicacao(root)\nroot.mainloop()\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":10376,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"399276167","text":"import math\nimport copy\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport matplotlib.animation as animation\nfrom mpl_toolkits import mplot3d\n\n\ndef data(i, ax, X, Y, Z, V, surface):\n Z.append(X * 0)\n V.append(X * 0) \n # water propagation formule \n for j in range(20): \n for k in range(20):\n # corner cases\n if j == 0 and k == 0:\n V[i + 1][j][k] = V[i][j][k] + (Z[i][j + 1][k] + Z[i][j][k + 1] + 2 * Z[i][j][k]) / 4 - Z[i][j][k]\n elif j == 0 and k == 19:\n V[i + 1][j][k] = V[i][j][k] + (Z[i][j + 1][k] + Z[i][j][k - 1] + 2 * Z[i][j][k]) / 4 - Z[i][j][k]\n elif j == 19 and k == 0:\n V[i + 1][j][k] = V[i][j][k] + (Z[i][j - 1][k] + Z[i][j][k + 1] + 2 * Z[i][j][k]) / 4 - Z[i][j][k]\n elif j == 19 and k == 19:\n V[i + 1][j][k] = V[i][j][k] + (Z[i][j - 1][k] + Z[i][j][k - 1] + 2 * Z[i][j][k]) / 4 - Z[i][j][k]\n # edge cases\n elif j == 0:\n V[i + 1][j][k] = V[i][j][k] + (Z[i][j + 1][k] + Z[i][j][k + 1] + Z[i][j][k - 1] + Z[i][j][k]) / 4 - Z[i][j][k]\n elif j == 19:\n V[i + 1][j][k] = V[i][j][k] + (Z[i][j - 1][k] + Z[i][j][k + 1] + Z[i][j][k - 1] + Z[i][j][k]) / 4 - Z[i][j][k]\n elif k == 0:\n V[i + 1][j][k] = V[i][j][k] + (Z[i][j + 1][k] + Z[i][j - 1][k] + Z[i][j][k + 1] + Z[i][j][k]) / 4 - Z[i][j][k]\n elif k == 19:\n V[i + 1][j][k] = V[i][j][k] + (Z[i][j + 1][k] + Z[i][j - 1][k] + Z[i][j][k - 1] + Z[i][j][k]) / 4 - Z[i][j][k]\n #general case\n else:\n V[i + 1][j][k] = V[i][j][k] + (Z[i][j + 1][k] + Z[i][j - 1][k] + Z[i][j][k + 1] + Z[i][j][k - 1]) / 4 - Z[i][j][k]\n V[i + 1][j][k] *= 0.90\n Z[i + 1][j][k] = Z[i][j][k] + V[i + 1][j][k]\n ax.clear()\n ax.set_zlim(0, 1)\n surface = ax.plot_surface(X, Y, Z[i], rstride=1, cstride=1,\n cmap='viridis', edgecolor='none')\n return(surface)\n\ndef main():\n x = np.linspace(-10, 10, 20)\n y = np.linspace(-10, 10, 20)\n X, Y = np.meshgrid(x, y)\n Z = []\n Z.append(X * 0) \n V = []\n V.append(X * 0) \n #center area where the water comes from\n for j in range(len(Z[0])):\n for k in range(len(Z[0][j])):\n Z[0][j][k] = 1 if j in range (8, 12) and k in range(8, 12) else 0\n fig = plt.figure()\n ax = plt.axes(projection='3d')\n ax.set_zlim(0, 1)\n surface = ax.plot_surface(X, Y, Z[0], rstride=1, cstride=1,\n cmap='viridis', edgecolor='none')\n ani = animation.FuncAnimation(fig, data, fargs=(ax, X, Y, Z, V, surface), interval=10, blit=False)\n\n ax.view_init(30, 45)\n\n plt.show()\n\nif __name__ == \"__main__\":\n main()","sub_path":"poc_formule_center_t0.py","file_name":"poc_formule_center_t0.py","file_ext":"py","file_size_in_byte":2742,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"470183627","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu May 3 20:53:06 2018\n\n@author: MarcusF\n\"\"\"\n\nfrom qtpy import QtCore, QtWidgets,QtGui\n\nimport qimage2ndarray as qnd\nimport tifffile\nfrom qtpy.QtCore import *\nfrom qtpy.QtGui import *\nfrom qtpy.QtWidgets import QWidget,QApplication,QSlider,QMainWindow,QLabel,QGridLayout,QLineEdit,QDoubleSpinBox,QVBoxLayout,QPushButton\nfrom qtpy.QtCore import QTimer\nimport numpy as np\nimport sys\nimport os\nfrom skimage.filters import threshold_otsu\n\nclass livestream(QWidget):\n i = 0\n def __init__(self,qnd,images = None,annotations_on = True,annotate_coords = None,threshold_switch = False):\n QWidget.__init__(self)\n \n \n self.threshold_switch = threshold_switch\n self.video = images #frames buffer\n self.videobox = Label()\n if annotations_on and annotate_coords is not None:\n self.coords = annotate_coords\n\n self.videobox.switch = annotations_on\n self.videobox.activecoord = self.coords[0]\n\n \n \n if self.video is not None:\n self.videobox.activeframe = self.video[0]\n \n self.videobox.maxintens = self.video.shape[0]\n \n else:\n self.videobox.activeframe = np.loadtxt(os.getcwd() + '/defaultimage.txt')\n print(self.videobox.activeframe.shape)\n self.videobox.maxintens = np.max(self.videobox.activeframe)\n\n\n self.videobox.setGeometry(QtCore.QRect(70, 80, 310, 310))\n self.videobox.h = 310\n self.videobox.w = 310\n \n self.lyt = QVBoxLayout()\n self.lyt.addWidget(self.videobox,5)\n \n \n self.setLayout(self.lyt)\n \n \n \n self.sl = QSlider(Qt.Horizontal)\n \n self.sl.setMinimum(0.0)\n if self.video is not None:\n self.sl.setMaximum(self.video.shape[0])\n self.sl.valueChanged.connect(self.whenslidechanges)\n self.sl.setTickPosition(QSlider.TicksAbove)\n self.sl.setTracking(True)\n self.sl.setTickInterval(100)\n \n\n \n self.frame_counter = QDoubleSpinBox()\n if images is not None:\n self.frame = images[0]\n self.frame_counter.valueChanged.connect(self.video_time_update)\n self.frame_counter.setSingleStep(1)\n self.frame_counter.setRange(self.sl.minimum(),self.sl.maximum())\n self.frame_counter.valueChanged.connect(self.sl.setValue)\n\n \n self.video_time = QDoubleSpinBox()\n self.video_time.setSingleStep(30)\n self.video_time.setRange(self.sl.minimum(),30*self.sl.maximum())\n self.frameratetimer = QTimer()\n self.frameratetimer.setInterval(30)\n if self.video is not None:\n self.frameratetimer.timeout.connect(self.update_display)\n \n \n self.play_button = QPushButton('Play Video')\n self.play_button.clicked.connect(self.frameratetimer.start)\n \n self.stop_button = QPushButton('Stop Video')\n self.stop_button.clicked.connect(self.frameratetimer.stop)\n\n if self.video is not None:\n self.sl.valueChanged.connect(self.whenslidechanges)\n \n self.lyt.addWidget(self.play_button,0)\n self.lyt.addWidget(self.stop_button,1)\n self.lyt.addWidget(self.sl,2)\n self.lyt.addWidget(self.frame_counter,3)\n self.lyt.addWidget(self.video_time,4)\n \n self.show()\n \n def assign_images(self,images,centres = None):\n \n '''#first disconnect signals from eachother so nothing should change whilst video data is being updated\n self.sl.valueChanged.disconnect(self.video_time_update)\n self.frameratetimer.timeout.disconnect(self.update_display)\n self.frame_counter.valueChanged.disconnect(self.whenslidechanges)\n '''\n \n self.video = images\n self.coords = centres\n self.videobox.activeframe = self.video[0]\n if self.coords is not None:\n self.videobox.activecoord = self.coords[0]\n\n #readjust slider and ticker values to dimensions of video\n \n self.sl.setMaximum(len(self.video)-1)\n self.frame_counter.setRange(self.sl.minimum(),self.sl.maximum())\n self.video_time.setRange(self.sl.minimum(),30*self.sl.maximum())\n \n \n \n \n #connect slider and timer etc.\n \n self.sl.valueChanged.connect(self.whenslidechanges)\n self.frameratetimer.timeout.connect(self.update_display)\n self.frame_counter.valueChanged.connect(self.video_time_update)\n \n self.videobox.maxintens = np.max(self.video)\n self.videobox.update()\n \n \n def update_display(self):\n \n if self.threshold_switch:\n frame = self.video[livestream.i]\n threshold = threshold_otsu(frame)\n \n mask = np.zeros_like(frame)\n mask[frame > threshold] = 1\n self.videobox.maxintens = 1\n self.videobox.activeframe = mask\n else:\n #if threshold switch is off display usual video, so change active frame source and reset maximum intensity for passing to qimage2ndarray\n self.videobox.activeframe = self.video[livestream.i]\n self.videobox.maxintens = np.max(self.video)\n \n try:\n self.videobox.activecoord = self.coords[livestream.i]\n\n if not self.videobox.switch:\n \n \n self.videobox.switch = True\n \n except:\n self.videobox.activecoord = None\n self.videobox.switch = False\n \n \n self.videobox.update()\n self.frame_counter.setValue(float(livestream.i))\n \n livestream.i+=1\n \n def whenslidechanges(self):\n \n if self.frameratetimer.isActive():\n self.frameratetimer.stop()\n \n livestream.i = self.sl.value()\n \n self.update_display()\n livestream.i -=1\n \n self.frameratetimer.start()\n else:\n \n livestream.i = self.sl.value()\n \n self.update_display()\n livestream.i -=1\n \n def video_time_update(self):\n self.video_time.setValue(30*self.frame_counter.value())\n \n \n def turn_on_threshold(self,threshold_switch):\n self.threshold_switch = threshold_switch\n self.update_display()\n \n\nclass Label(QtWidgets.QLabel):\n def __init__(self, parent=None):\n super(Label, self).__init__(parent=parent)\n self.activeframe = None\n self.switch = False\n self.activecoord = None\n self.maxintens = None\n self.h = None\n self.w = None\n self.size = None\n self.pixsize = None\n def paintEvent(self, e):\n super().paintEvent(e)\n qp = QtGui.QPainter(self)\n \n img = qnd.gray2qimage(self.activeframe,normalize = (0,self.maxintens))\n self.size = img.size()\n pix = QtGui.QPixmap.fromImage(img).scaled(self.h,self.w,Qt.KeepAspectRatio)\n self.pixsize = pix.size()\n \n \n pos = QPoint(0,0) \n qp.drawPixmap(pos,pix) \n\n pen = QPen(Qt.red,2)\n qp.setPen(pen)\n \n if self.switch and self.activecoord is not None:\n\n qp.drawRect(10*(self.activecoord[1]-4),10*(self.activecoord[0]-4),10*8,10*8)\n \n qp.end()\n \nif __name__ == '__main__':\n \n app = QtWidgets.QApplication(sys.argv)\n \n with tifffile.TiffFile('/Users/MarcusF/Downloads/nbd pc position _10ms_bin2_em30_1_MMStack_Pos0.ome.tif') as tif:\n images =tif.asarray()\n \n ls = livestream(qnd,images,annotations_on = False)\n\n app.exec_()\n","sub_path":"Watchbackvideos.py","file_name":"Watchbackvideos.py","file_ext":"py","file_size_in_byte":7851,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"162048977","text":"import unittest\nimport Zope\ntry:\n from Interface.Verify import verifyClass\nexcept ImportError:\n # for Zope versions before 2.6.0\n from Interface import verify_class_implementation as verifyClass\n\nfrom Acquisition import aq_base\nfrom AccessControl.SecurityManagement import newSecurityManager\nfrom AccessControl.SecurityManagement import noSecurityManager\nfrom webdav.NullResource import NullResource\n\nfrom Products.PythonScripts.standard import url_quote\n\nfrom Products.CMFCore.TypesTool import FactoryTypeInformation as FTI\nfrom Products.CMFCore.TypesTool import ScriptableTypeInformation as STI\nfrom Products.CMFCore.TypesTool import TypesTool\nfrom Products.CMFCore.TypesTool import Unauthorized\n\nfrom Products.CMFCore.PortalFolder import PortalFolder\nfrom Products.CMFCore.utils import _getViewFor\n\nfrom Products.CMFCore.tests.base.testcase import SecurityRequestTest\nfrom Products.CMFCore.tests.base.security import OmnipotentUser\nfrom Products.CMFCore.tests.base.security import UserWithRoles\nfrom Products.CMFCore.tests.base.dummy import DummyObject\nfrom Products.CMFCore.tests.base.dummy import addDummy\nfrom Products.CMFCore.tests.base.dummy import DummyTypeInfo\nfrom Products.CMFCore.tests.base.dummy import DummyFolder\nfrom Products.CMFCore.tests.base.dummy import DummyFTI\n\nclass TypesToolTests( SecurityRequestTest ):\n\n def setUp( self ):\n SecurityRequestTest.setUp(self)\n root = self.root\n root.addDummy = addDummy\n\n root._setObject( 'portal_types', TypesTool() )\n tool = root.portal_types\n tool._setObject( 'Dummy Content', DummyFTI ) \n \n def test_processActions( self ):\n \"\"\"\n Are the correct, permitted methods returned for actions?\n \"\"\"\n self.root._setObject( 'portal', PortalFolder( 'portal', '' ) )\n portal = self.root.portal\n portal.invokeFactory( 'Dummy Content', 'actions_dummy' )\n dummy = portal._getOb( 'actions_dummy' )\n\n # so we can traverse to it:\n dummy.view = DummyObject(\"view\")\n dummy.view2 = DummyObject(\"view2\")\n dummy.edit = DummyObject(\"edit\")\n\n default_view = dummy()\n custom_view = _getViewFor( dummy, view='view2' )()\n unpermitted_view = _getViewFor( dummy, view='edit' )()\n\n self.failUnlessEqual(default_view, 'view')\n self.failUnlessEqual(custom_view, 'view2')\n self.failIf(unpermitted_view == 'edit')\n self.failUnlessEqual(unpermitted_view, 'view')\n\n def test_allMetaTypes(self):\n \"\"\"\n Test that everything returned by allMetaTypes can be\n traversed to.\n \"\"\"\n tool = self.root.portal_types\n meta_types={}\n # Seems we get NullResource if the method couldn't be traverse to\n # so we check for that. If we've got it, something is b0rked.\n for factype in tool.all_meta_types():\n meta_types[factype['name']]=1\n # The url_quote below is necessary 'cos of the one in\n # main.dtml. Could be removed once that is gone.\n act = tool.unrestrictedTraverse(url_quote(factype['action']))\n self.failIf(type(aq_base(act)) is NullResource)\n\n # Check the ones we're expecting are there\n self.failUnless(meta_types.has_key('Scriptable Type Information'))\n self.failUnless(meta_types.has_key('Factory-based Type Information'))\n\n def test_interface(self):\n from Products.CMFCore.interfaces.portal_types \\\n import portal_types as ITypesTool\n from Products.CMFCore.interfaces.portal_actions \\\n import ActionProvider as IActionProvider\n\n verifyClass(ITypesTool, TypesTool)\n verifyClass(IActionProvider, TypesTool)\n\n\nclass TypeInfoTests( unittest.TestCase ):\n \n def test_construction( self ):\n ti = self._makeInstance( 'Foo'\n , description='Description'\n , meta_type='Foo'\n , icon='foo.gif'\n )\n self.assertEqual( ti.getId(), 'Foo' )\n self.assertEqual( ti.Title(), 'Foo' )\n self.assertEqual( ti.Description(), 'Description' )\n self.assertEqual( ti.Metatype(), 'Foo' )\n self.assertEqual( ti.getIcon(), 'foo.gif' )\n self.assertEqual( ti.immediate_view, '' )\n\n ti = self._makeInstance( 'Foo'\n , immediate_view='foo_view'\n )\n self.assertEqual( ti.immediate_view, 'foo_view' )\n\n def _makeAndSetInstance( self,id,**kw ):\n tool = self.tool\n t = apply( self._makeInstance, (id,), kw )\n tool._setObject(id,t)\n return tool[id]\n \n def test_allowType( self ):\n self.tool = TypesTool() \n ti = self._makeAndSetInstance( 'Foo' )\n self.failIf( ti.allowType( 'Foo' ) )\n self.failIf( ti.allowType( 'Bar' ) )\n\n ti = self._makeAndSetInstance( 'Foo2', allowed_content_types=( 'Bar', ) )\n self.failUnless( ti.allowType( 'Bar' ) )\n\n ti = self._makeAndSetInstance( 'Foo3', filter_content_types=0 )\n self.failUnless( ti.allowType( 'Foo3' ) )\n\n \n def test_GlobalHide( self ):\n self.tool = TypesTool() \n tnf = self._makeAndSetInstance( 'Folder', filter_content_types=0)\n taf = self._makeAndSetInstance( 'Allowing Folder'\n , allowed_content_types=( 'Hidden'\n ,'Not Hidden'))\n tih = self._makeAndSetInstance( 'Hidden', global_allow=0)\n tnh = self._makeAndSetInstance( 'Not Hidden')\n # make sure we're normally hidden but everything else is visible\n self.failIf ( tnf.allowType( 'Hidden' ) )\n self.failUnless ( tnf.allowType( 'Not Hidden') )\n # make sure we're available where we should be\n self.failUnless ( taf.allowType( 'Hidden' ) )\n self.failUnless ( taf.allowType( 'Not Hidden') )\n # make sure we're available in a non-content-type-filtered type\n # where we have been explicitly allowed\n taf2 = self._makeAndSetInstance( 'Allowing Folder2'\n , allowed_content_types=( 'Hidden'\n , 'Not Hidden'\n )\n , filter_content_types=0\n )\n self.failUnless ( taf2.allowType( 'Hidden' ) )\n self.failUnless ( taf2.allowType( 'Not Hidden') )\n \n\n def test_allowDiscussion( self ):\n ti = self._makeInstance( 'Foo' )\n self.failIf( ti.allowDiscussion() )\n\n ti = self._makeInstance( 'Foo', allow_discussion=1 )\n self.failUnless( ti.allowDiscussion() )\n\n ACTION_LIST = \\\n ( { 'id' : 'view'\n , 'name' : 'View'\n , 'action' : 'string:foo_view'\n , 'permissions' : ( 'View', )\n , 'category' : 'object'\n , 'visible' : 1\n }\n , { 'name' : 'Edit' # Note: No ID passed\n , 'action' : 'string:foo_edit'\n , 'permissions' : ( 'Modify', )\n , 'category' : 'object'\n , 'visible' : 1\n }\n , { 'name' : 'Object Properties' # Note: No ID passed\n , 'action' : 'string:foo_properties'\n , 'permissions' : ( 'Modify', )\n , 'category' : 'object'\n , 'visible' : 1\n }\n , { 'id' : 'slot'\n , 'action' : 'string:foo_slot'\n , 'category' : 'object'\n , 'visible' : 0\n }\n )\n\n def test_listActions( self ):\n ti = self._makeInstance( 'Foo' )\n self.failIf( ti.listActions() )\n\n ti = self._makeInstance( 'Foo', actions=self.ACTION_LIST )\n\n actions = ti.listActions()\n self.failUnless( actions )\n\n ids = [ x.getId() for x in actions ]\n self.failUnless( 'view' in ids )\n self.failUnless( 'edit' in ids )\n self.failUnless( 'objectproperties' in ids )\n self.failUnless( 'slot' in ids )\n\n names = [ x.Title() for x in actions ]\n self.failUnless( 'View' in names )\n self.failUnless( 'Edit' in names )\n self.failUnless( 'Object Properties' in names )\n self.failIf( 'slot' in names )\n self.failUnless( 'Slot' in names )\n \n visible = [ x.getId() for x in actions if x.getVisibility() ]\n self.failUnless( 'view' in visible )\n self.failUnless( 'edit' in visible )\n self.failUnless( 'objectproperties' in visible )\n self.failIf( 'slot' in visible )\n\n def test_getActionById( self ):\n\n ti = self._makeInstance( 'Foo' )\n marker = []\n self.assertEqual( id( ti.getActionById( 'view', marker ) )\n , id( marker ) )\n self.assertRaises( ValueError, ti.getActionById, 'view' )\n\n ti = self._makeInstance( 'Foo', actions=self.ACTION_LIST )\n self.assertEqual( id( ti.getActionById( 'foo', marker ) )\n , id( marker ) )\n self.assertRaises( ValueError, ti.getActionById, 'foo' )\n \n action = ti.getActionById( 'view' )\n self.assertEqual( action, 'foo_view' )\n \n action = ti.getActionById( 'edit' )\n self.assertEqual( action, 'foo_edit' )\n \n action = ti.getActionById( 'objectproperties' )\n self.assertEqual( action, 'foo_properties' )\n \n action = ti.getActionById( 'slot' )\n self.assertEqual( action, 'foo_slot' )\n\n def test__convertActions_from_dict( self ):\n\n from Products.CMFCore.ActionInformation import ActionInformation\n\n ti = self._makeInstance( 'Foo' )\n ti._actions = ( { 'id' : 'bar'\n , 'name' : 'Bar'\n , 'action' : 'bar_action'\n , 'permissions' : ( 'Bar permission', )\n , 'category' : 'baz'\n , 'visible' : 0\n }\n ,\n )\n\n actions = ti.listActions()\n self.assertEqual( len( actions ), 1 )\n\n action = actions[0]\n\n self.failUnless( isinstance( action, ActionInformation ) )\n self.assertEqual( action.getId(), 'bar' )\n self.assertEqual( action.Title(), 'Bar' )\n self.assertEqual( action.getActionExpression(), 'string:bar_action' )\n self.assertEqual( action.getCondition(), '' )\n self.assertEqual( action.getPermissions(), ( 'Bar permission', ) )\n self.assertEqual( action.getCategory(), 'baz' )\n self.assertEqual( action.getVisibility(), 0 )\n\n self.failUnless( isinstance( ti._actions[0], ActionInformation ) )\n\n\nclass FTIDataTests( TypeInfoTests ):\n\n def _makeInstance( self, id, **kw ):\n return apply( FTI, ( id, ), kw )\n\n def test_properties( self ):\n ti = self._makeInstance( 'Foo' )\n self.assertEqual( ti.product, '' )\n self.assertEqual( ti.factory, '' )\n\n ti = self._makeInstance( 'Foo'\n , product='FooProduct'\n , factory='addFoo'\n )\n self.assertEqual( ti.product, 'FooProduct' )\n self.assertEqual( ti.factory, 'addFoo' )\n\n def test_interface(self):\n from Products.CMFCore.interfaces.portal_types \\\n import ContentTypeInformation as ITypeInformation\n\n verifyClass(ITypeInformation, FTI)\n \n\nclass STIDataTests( TypeInfoTests ):\n\n def _makeInstance( self, id, **kw ):\n return apply( STI, ( id, ), kw )\n\n def test_properties( self ):\n ti = self._makeInstance( 'Foo' )\n self.assertEqual( ti.permission, '' )\n self.assertEqual( ti.constructor_path, '' )\n\n ti = self._makeInstance( 'Foo'\n , permission='Add Foos'\n , constructor_path='foo_add'\n )\n self.assertEqual( ti.permission, 'Add Foos' )\n self.assertEqual( ti.constructor_path, 'foo_add' )\n\n def test_interface(self):\n from Products.CMFCore.interfaces.portal_types \\\n import ContentTypeInformation as ITypeInformation\n\n verifyClass(ITypeInformation, STI)\n \n\nclass FTIConstructionTests( unittest.TestCase ):\n\n def setUp( self ):\n noSecurityManager()\n\n def _makeInstance( self, id, **kw ):\n return apply( FTI, ( id, ), kw )\n\n def _makeFolder( self, fake_product=0 ):\n return DummyFolder( fake_product )\n\n def test_isConstructionAllowed_wo_Container( self ):\n\n ti = self._makeInstance( 'foo' )\n\n self.failIf( ti.isConstructionAllowed( None ) )\n\n ti = self._makeInstance( 'Foo'\n , product='FooProduct'\n , factory='addFoo'\n )\n\n self.failIf( ti.isConstructionAllowed( None ) )\n\n def test_isConstructionAllowed_wo_ProductFactory( self ):\n\n ti = self._makeInstance( 'foo' )\n\n folder = self._makeFolder()\n self.failIf( ti.isConstructionAllowed( folder ) )\n\n folder = self._makeFolder( fake_product=1 )\n self.failIf( ti.isConstructionAllowed( folder ) )\n\n def test_isConstructionAllowed_wo_Security( self ):\n\n ti = self._makeInstance( 'Foo'\n , product='FooProduct'\n , factory='addFoo'\n )\n folder = self._makeFolder( fake_product=1 )\n\n self.failIf( ti.isConstructionAllowed( folder ) )\n\nclass FTIConstructionTests_w_Roles( unittest.TestCase ):\n\n def tearDown( self ):\n noSecurityManager()\n\n def _makeStuff( self, prefix='' ):\n\n ti = FTI( 'Foo'\n , product='FooProduct'\n , factory='addFoo'\n )\n folder = DummyFolder( fake_product=1,prefix=prefix )\n \n return ti, folder\n\n def test_isConstructionAllowed_for_Omnipotent( self ):\n\n ti, folder = self._makeStuff()\n newSecurityManager( None\n , OmnipotentUser().__of__( folder ) )\n self.failUnless( ti.isConstructionAllowed( folder ) )\n\n def test_isConstructionAllowed_w_Role( self ):\n\n ti, folder = self._makeStuff()\n\n newSecurityManager( None\n , UserWithRoles( 'FooAdder' ).__of__( folder ) )\n self.failUnless( ti.isConstructionAllowed( folder ) )\n\n def test_isConstructionAllowed_wo_Role( self ):\n\n ti, folder = self._makeStuff()\n\n newSecurityManager( None\n , UserWithRoles( 'FooViewer' ).__of__( folder ) )\n\n def test_constructInstance_wo_Roles( self ):\n\n ti, folder = self._makeStuff()\n\n newSecurityManager( None\n , UserWithRoles( 'FooViewer' ).__of__( folder ) )\n\n self.assertRaises( Unauthorized\n , ti.constructInstance, folder, 'foo' )\n\n def test_constructInstance( self ):\n\n ti, folder = self._makeStuff()\n\n newSecurityManager( None\n , UserWithRoles( 'FooAdder' ).__of__( folder ) )\n\n ti.constructInstance( folder, 'foo' )\n foo = folder._getOb( 'foo' )\n self.assertEqual( foo.id, 'foo' )\n\n def test_constructInstance_w_args_kw( self ):\n\n ti, folder = self._makeStuff()\n\n newSecurityManager( None\n , UserWithRoles( 'FooAdder' ).__of__( folder ) )\n\n ti.constructInstance( folder, 'bar', 0, 1 )\n bar = folder._getOb( 'bar' )\n self.assertEqual( bar.id, 'bar' )\n self.assertEqual( bar._args, ( 0, 1 ) )\n\n ti.constructInstance( folder, 'baz', frickle='natz' )\n baz = folder._getOb( 'baz' )\n self.assertEqual( baz.id, 'baz' )\n self.assertEqual( baz._kw[ 'frickle' ], 'natz' )\n\n ti.constructInstance( folder, 'bam', 0, 1, frickle='natz' )\n bam = folder._getOb( 'bam' )\n self.assertEqual( bam.id, 'bam' )\n self.assertEqual( bam._args, ( 0, 1 ) )\n self.assertEqual( bam._kw[ 'frickle' ], 'natz' )\n\n def test_constructInstance_w_id_munge( self ):\n\n ti, folder = self._makeStuff( 'majyk' )\n\n newSecurityManager( None\n , UserWithRoles( 'FooAdder' ).__of__( folder ) )\n\n ti.constructInstance( folder, 'dust' )\n majyk_dust = folder._getOb( 'majyk_dust' )\n self.assertEqual( majyk_dust.id, 'majyk_dust' )\n\n\ndef test_suite():\n return unittest.TestSuite((\n unittest.makeSuite(TypesToolTests),\n unittest.makeSuite(FTIDataTests),\n unittest.makeSuite(STIDataTests),\n unittest.makeSuite(FTIConstructionTests),\n unittest.makeSuite(FTIConstructionTests_w_Roles),\n ))\n\nif __name__ == '__main__':\n unittest.main(defaultTest='test_suite')\n","sub_path":"CMF/tags/CMF-1_4beta1/CMFCore/tests/test_TypesTool.py","file_name":"test_TypesTool.py","file_ext":"py","file_size_in_byte":17028,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"18299691","text":"import enum\nimport queue\n\n\nclass Square(enum.Enum):\n Empty = 0\n Wall = 1\n Exit = 2\n\n\nclass Direction(enum.Enum):\n North = (-1, 0)\n South = (+1, 0)\n West = (0, -1)\n East = (0, +1)\n\n\ndef process_maze(maze_representation):\n rows = maze_representation.split()\n return {\n (row_index, col_index): type(square, (row_index, col_index), len(rows))\n for row_index, row in enumerate(rows)\n for col_index, square in enumerate(row)\n }\n\n\ndef type(square, position, size):\n if position == (size - 1, size - 1):\n return Square.Exit\n elif square == \"W\":\n return Square.Wall\n elif square == \".\":\n return Square.Empty\n else:\n raise ValueError(\"Invalid square\")\n\n\ndef can_reach_exit(maze):\n neighbors = queue.Queue((0, 0))\n visited = set()\n\n while neighbors:\n square = neighbors.get()\n\n if maze[square] == Square.Exit:\n return True\n\n if square not in visited:\n visited.add(square)\n\n for square in (\n (position[0] + direction.value[0], position[1] + direction.value[1])\n for direction in Direction\n ):\n if square in maze and maze[square] != Square.Wall:\n neighbors.put(square)\n\n return False\n\n\ndef path_finder(maze_representation):\n maze = process_maze(maze_representation)\n\n return can_reach_exit(maze)\n","sub_path":"path_finder1/clau_path_finder1.py","file_name":"clau_path_finder1.py","file_ext":"py","file_size_in_byte":1421,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"557657785","text":"from odoo import models, api\n\n\nclass InventoryLine(models.Model):\n _inherit = \"stock.inventory.line\"\n\n @api.depends('location_id', 'product_id', 'package_id', 'product_uom_id', 'company_id', 'prod_lot_id', 'partner_id',\n 'inventory_id.date')\n def _compute_theoretical_qty(self):\n for r in self:\n theoretical_qty = 0\n if r.product_id:\n theoretical_qty = r.with_context(to_date=r.inventory_id.date,\n location=r.location_id.id,\n lot_id=r.prod_lot_id.id,\n owner_id=r.partner_id.id,\n package_id=r.package_id.id,\n compute_child=False).product_id.qty_available\n r.theoretical_qty = theoretical_qty\n","sub_path":"customaddons/sim_inventory_backdate/sim_to_stock_backdate/models/stock_inventory_line.py","file_name":"stock_inventory_line.py","file_ext":"py","file_size_in_byte":911,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"15290142","text":"import jwt\nfrom datetime import datetime,timedelta\n# from djangotext.settings import SECRET_KEY\nSECRECT_KEY='cyc'\ndef makeToken(tel):\n datetimeInt=datetime.utcnow()+timedelta(hours=1)\n options={\n 'iss':'tiantian.com',\n 'exp':datetimeInt,\n 'aud':'webkit',\n 'message':tel\n }\n token=jwt.encode(options,SECRECT_KEY,'HS256').decode()\n return token\n\ndef openToken(token):\n data=jwt.decode(token, SECRECT_KEY,audience='webkit', algorithms=['HS256'])\n return data\n","sub_path":"user/utilss/make_token.py","file_name":"make_token.py","file_ext":"py","file_size_in_byte":505,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"394005020","text":"\n# coding: utf-8\n\n# In[1]:\n\nimport pandas as pd\nimport numpy as np\nfrom sklearn import svm\nfrom sklearn.cross_validation import train_test_split\nfrom sklearn.metrics import accuracy_score\nfrom sklearn.naive_bayes import GaussianNB\nfrom sklearn.naive_bayes import MultinomialNB\nfrom sklearn.ensemble import RandomForestClassifier\nfrom sklearn import neighbors as nb\n\n\n# In[5]:\n\ndf = pd.read_csv(\"pubfig_attributes.txt\",sep='\\t')\nX = df.copy()\ndel X['person']\ndel X['imagenum']\nY = df['person']\n\n\n# In[6]:\n\nknc = nb.KNeighborsClassifier(n_neighbors=3,algorithm='kd_tree',weights='distance')\nknc.fit(X,Y)\n\n\n# In[7]:\n\narr = np.loadtxt(\"dat.txt\",delimiter='\\t') #loading the test data\nYcomparison = np.zeros(len(arr))\nXcomparison = []\nfor k in range(len(arr)):\n Ycomparison[k] = arr[k][0]\nfor l in range(len(arr)):\n Xcomparison.append(arr[l][1:147])\n\n\n# In[9]:\n\nYpredcomparison = []\nfor i in range(len(Xcomparison)):\n face1 = knc.predict(Xcomparison[i][0:73])\n face2 = knc.predict(Xcomparison[i][73:146])\n if(face1==face2):\n Ypredcomparison.append(1)\n else:\n Ypredcomparison.append(0)\nprint(accuracy_score(Ycomparison,Ypredcomparison)) # checking the model on training data given for part-1\n\n\n# In[11]:\n\narr1 = np.loadtxt(\"pubfig_kaggle_3.txt\",delimiter='\\t') # Change the number of pubfig_kaggle_ to test another file\nXcomparison1 = []\nfor l in range(len(arr1)):\n Xcomparison1.append(arr1[l])\n\n\n# In[12]:\n\ndfsoln1 = pd.read_csv(\"pubfig_kaggle_3_solution.txt\",sep=',') # Change the number of pubfig_kaggle_()_solution to test another file\narrsoln1 = dfsoln1['Prediction']\n\n\n# In[13]:\n\nYpredcomparison1 = []\nfor i in range(len(Xcomparison1)):\n face1 = knc.predict(Xcomparison1[i][0:73])\n face2 = knc.predict(Xcomparison1[i][73:146])\n if(face1==face2):\n Ypredcomparison1.append(1)\n else:\n Ypredcomparison1.append(0)\nprint(accuracy_score(arrsoln1,Ypredcomparison1)) #prints the accuracy for the the 3 evaluation data\n\n\n# In[ ]:\n\n\n\n\n# In[ ]:\n\n\n\n","sub_path":"Public_Figues_Faces_Dataset/HW3-Part2.py","file_name":"HW3-Part2.py","file_ext":"py","file_size_in_byte":1999,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"498883308","text":"import numpy as np\nfrom astropy.table import Table\n\ndef loadData(dloc = 'Tables/'):\n\t\"\"\"\n\tLoad the train and test data\n\t\"\"\"\n\t#load the train data\n\ttrain_d = Table().read(dloc + 'PhotoZFileA.vot')\n\tkeys = train_d.keys()\n\t# print(keys)\n\tXtrain = np.array([train_d['mag_r'], train_d['u-g'], train_d['g-r'], train_d['r-i'], train_d['i-z']]).T\n\tYtrain = np.array(train_d['z_spec'])\n\n\t#load the train data\n\ttest_d = Table().read(dloc + 'PhotoZFileB.vot')\n\tkeys = test_d.keys()\n\t# print(keys)\n\tXtest = np.array([test_d['mag_r'], test_d['u-g'], test_d['g-r'], test_d['r-i'], test_d['i-z']]).T\n\tYtest = np.array(test_d['z_spec'])\n\n\treturn Xtrain, Xtest, Ytrain, Ytest\n\ndef error(z_phot, z_spec):\n\t\"\"\"\n\tCompute the error.\n\n\tInput:\n\t\tz_phot, z_spec (float arrays): the photometric (predicted) and spectroscopic redshifts.\n\n\tOutput:\n\t\terror (float): the error on the prediction.\n\t\"\"\"\n\treturn np.median(np.abs(z_spec - z_phot) / (1 + z_spec))\n\ndef linear(Xtrain, Ytrain, Xtest, Ytest):\n\t\"\"\"\n\tApply linear regression\n\t\"\"\"\n\tfrom sklearn.linear_model import LinearRegression\n\n\tprint('\\nLinear regression:')\n\n\t#apply the linear model\n\treg = LinearRegression(n_jobs = -1).fit(Xtrain, Ytrain)\n\tprint('R^2: {0}'.format(reg.score(Xtrain, Ytrain)))\n\n\t#find the training error\n\tprediction = reg.predict(Xtrain)\n\tEtrain = error(prediction, Ytrain)\n\tprint('Training error: {0}'.format(Etrain))\n\n\t#find the test error\n\tprediction = reg.predict(Xtest)\n\tEtest = error(prediction, Ytest)\n\tprint('Test error: {0}'.format(Etest))\n\ndef ridge(Xtrain, Ytrain, Xtest, Ytest):\n\t\"\"\"\n\tApply ridge regression\n\t\"\"\"\n\tfrom sklearn.linear_model import Ridge\n\n\tprint('\\nRidge regression:')\n\n\talpharange = np.linspace(0.001, 0.10, 100)\n\terrorlist = np.zeros(len(alpharange))\n\n\t#hyperparameter tuning\n\tfor alpha, i in zip(alpharange, range(len(alpharange))):\n\t\treg = Ridge(alpha = alpha).fit(Xtrain, Ytrain)\n\t\tprediction = reg.predict(Xtrain)\n\t\terrorlist[i] = error(prediction, Ytrain)\n\n\tbestloc = np.argmin(errorlist)\n\tprint('Best alpha: {0}'.format(alpharange[bestloc]))\n\tprint('Corresponding error: {0}'.format(errorlist[bestloc]))\n\n\t#apply ridge regression\n\treg = Ridge(alpha = alpharange[bestloc]).fit(Xtrain, Ytrain)\n\tprint('R^2: {0}'.format(reg.score(Xtrain, Ytrain)))\n\n\t#find the training error\n\tprediction = reg.predict(Xtrain)\n\tEtrain = error(prediction, Ytrain)\n\tprint('Training error: {0}'.format(Etrain))\n\n\t#find the test error\n\tprediction = reg.predict(Xtest)\n\tEtest = error(prediction, Ytest)\n\tprint('Test error: {0}'.format(Etest))\n\ndef lasso(Xtrain, Ytrain, Xtest, Ytest):\n\t\"\"\"\n\tApply Lasso regression\n\t\"\"\"\n\tfrom sklearn.linear_model import Lasso\n\n\tprint('\\nLasso regression:')\n\n\talpharange = np.logspace(-10, 0, 100)\n\terrorlist = np.zeros(len(alpharange))\n\n\t#hyperparameter tuning\n\tfor alpha, i in zip(alpharange, range(len(alpharange))):\n\t\treg = Lasso(alpha = alpha).fit(Xtrain, Ytrain)\n\t\tprediction = reg.predict(Xtrain)\n\t\terrorlist[i] = error(prediction, Ytrain)\n\n\tbestloc = np.argmin(errorlist)\n\tprint('Best alpha: {0}'.format(alpharange[bestloc]))\n\tprint('Corresponding error: {0}'.format(errorlist[bestloc]))\n\n\t#apply ridge regression\n\treg = Lasso(alpha = alpharange[bestloc]).fit(Xtrain, Ytrain)\n\tprint('R^2: {0}'.format(reg.score(Xtrain, Ytrain)))\n\n\t#find the training error\n\tprediction = reg.predict(Xtrain)\n\tEtrain = error(prediction, Ytrain)\n\tprint('Training error: {0}'.format(Etrain))\n\n\t#find the test error\n\tprediction = reg.predict(Xtest)\n\tEtest = error(prediction, Ytest)\n\tprint('Test error: {0}'.format(Etest))\n\ndef RF(Xtrain, Ytrain, Xtest, Ytest):\n\t\"\"\"\n\tApply a random forest\n\t\"\"\"\n\tfrom sklearn.ensemble import RandomForestRegressor\n\tprint('\\nRandom Forest:')\n\n\tclf = RandomForestRegressor(n_estimators=500, n_jobs=-1).fit(Xtrain, Ytrain)\n\tprint('Accuracy: {0}'.format(clf.score(Xtrain, Ytrain)))\n\n\t#find the training error\n\tprediction = clf.predict(Xtrain)\n\tEtrain = error(prediction, Ytrain)\n\tprint('Training error: {0}'.format(Etrain))\n\n\t#find the test error\n\tprediction = clf.predict(Xtest)\n\tEtrain = error(prediction, Ytest)\n\tprint('Test error: {0}'.format(Etrain))\n\ndef Adaboost(Xtrain, Ytrain, Xtest, Ytest):\n\t\"\"\"\n\tApply the adaboost algorithm\n\t\"\"\"\n\tfrom sklearn.ensemble import AdaBoostRegressor\n\tprint('\\nAdaboost:')\n\n\tclf = AdaBoostRegressor(n_estimators=1000).fit(Xtrain, Ytrain)\n\tprint('Accuracy: {0}'.format(clf.score(Xtrain, Ytrain)))\n\n\t#find the training error\n\tprediction = clf.predict(Xtrain)\n\tEtrain = error(prediction, Ytrain)\n\tprint('Training error: {0}'.format(Etrain))\n\n\t#find the test error\n\tprediction = clf.predict(Xtest)\n\tEtrain = error(prediction, Ytest)\n\tprint('Test error: {0}'.format(Etrain))\n\n\ndef Bagging(Xtrain, Ytrain, Xtest, Ytest):\n\t\"\"\"\n\tApply the extra trees regressor\n\t\"\"\"\n\tfrom sklearn.ensemble import BaggingRegressor\n\tprint('\\nBagging regressor:')\n\n\tclf = BaggingRegressor(n_estimators=100, n_jobs=-1).fit(Xtrain, Ytrain)\n\tprint('Accuracy: {0}'.format(clf.score(Xtrain, Ytrain)))\n\n\t#find the training error\n\tprediction = clf.predict(Xtrain)\n\tEtrain = error(prediction, Ytrain)\n\tprint('Training error: {0}'.format(Etrain))\n\n\t#find the test error\n\tprediction = clf.predict(Xtest)\n\tEtrain = error(prediction, Ytest)\n\tprint('Test error: {0}'.format(Etrain))\n\ndef ExtraTrees(Xtrain, Ytrain, Xtest, Ytest):\n\t\"\"\"\n\tApply the extra trees regressor\n\t\"\"\"\n\tfrom sklearn.ensemble import ExtraTreesRegressor\n\tprint('\\nExtra trees regressor:')\n\n\tclf = ExtraTreesRegressor(n_estimators=100, n_jobs=-1).fit(Xtrain, Ytrain)\n\tprint('Accuracy: {0}'.format(clf.score(Xtrain, Ytrain)))\n\n\t#find the training error\n\tprediction = clf.predict(Xtrain)\n\tEtrain = error(prediction, Ytrain)\n\tprint('Training error: {0}'.format(Etrain))\n\n\t#find the test error\n\tprediction = clf.predict(Xtest)\n\tEtrain = error(prediction, Ytest)\n\tprint('Test error: {0}'.format(Etrain))\n\ndef SVM(Xtrain, Ytrain, Xtest, Ytest, kerneltype = 'rbf'):\n\t\"\"\"\n\tApply a support vector machine regressor\n\t\"\"\"\n\tfrom sklearn.svm import SVR\n\tprint('\\nSVM regressor:')\n\n\tclf = SVR(epsilon = 0.02, kernel = kerneltype).fit(Xtrain, Ytrain)\n\tprint('Accuracy: {0}'.format(clf.score(Xtrain, Ytrain)))\n\n\t#find the training error\n\tprediction = clf.predict(Xtrain)\n\tEtrain = error(prediction, Ytrain)\n\tprint('Training error: {0}'.format(Etrain))\n\n\t#find the test error\n\tprediction = clf.predict(Xtest)\n\tEtrain = error(prediction, Ytest)\n\tprint('Test error: {0}'.format(Etrain))\n\ndef NearestNeighbour(Xtrain, Ytrain, Xval, Yval, n_folds = 5, k_best = None):\n\t\"\"\"\n\tApply a nearest neighbour regressor. Find the optimal number of neighbours\n\twith cross validation and grid search.\n\t\"\"\"\n\timport matplotlib.pyplot as plt\n\tfrom sklearn.neighbors import KNeighborsRegressor\n\timport seaborn as sns\n\n\tsns.set(font = 'Latin Modern Roman',rc = {'legend.frameon': True})\n\tprint('\\nNearest neighbour regressor:')\n\n\t#find the best number of neighbours if none is given\n\tif k_best == None:\n\t\tfrom sklearn.model_selection import KFold\n\t\tkf = KFold(n_splits = n_folds)\n\t\t#the range of values of the amount of neighbours to test\n\t\tk_range = np.arange(3, 100, 1)\n\t\t#the array which will store the error of each number of neighbours\n\t\terrorlist = np.zeros(len(k_range))\t\n\t\t#array storing the median error\n\t\tmed_err = np.zeros(len(k_range))\n\n\t\tprint('Finding the best number of neighbours...')\n\t\tfor k, i in zip(k_range, np.arange(len(k_range))):\n\t\t\tle = []\n\t\t\t#apply 4 fold cross validation\n\t\t\tfor train_i, test_i in kf.split(Xtrain, Ytrain):\n\t\t\t\t#split the data into a train and test set \n\t\t\t\tXtr, Xte = Xtrain[train_i], Xtrain[test_i]\n\t\t\t\tYtr, Yte = Ytrain[train_i], Ytrain[test_i]\n\t\t\t\tmodel = KNeighborsRegressor(n_neighbors = k, n_jobs = -1).fit(Xtr, Ytr)\n\n\t\t\t\t# lhscore = model.score(Xte, Yte)\n\t\t\t\terr = error(model.predict(Xte), Yte)\n\t\t\t\t\n\t\t\t\tle = np.append(le, err)\n\t\t\t\t\n\t\t\terrorlist[i] = np.mean(le)\n\t\t\tmed_err[i] = np.median(le)\n\n\t\t\tprint('Iteration {0}, n_neighbours {1}, mean error: {2}'.format(i, k, errorlist[i]))\n\n\t\t#find the best amount of neighbours. Usually this is 3\n\t\tk_best = k_range[np.argmin(errorlist)]\n\n\t\tprint('Best number of neighbours using median error: {0}'.format(k_range[np.argmin(med_err)]))\n\t\tprint('Best number of neighbours using mean error: {0}'.format(k_range[np.argmin(errorlist)]))\n\n\t\tplt.plot(k_range, med_err, label = 'Median error')\n\t\tplt.plot(k_range, errorlist, label = 'Mean error')\n\t\tplt.xlabel('Number of neighbours')\n\t\tplt.ylabel('Error')\n\t\tplt.title('Nearest neighbour error for different number of neighbours')\n\t\tplt.legend(loc = 'best')\n\t\tplt.savefig('Nearest_neighbours_median_mean_error.pdf', dpi = 300)\n\t\tplt.close()\n\n\tprint(f'Number of neighbours: {k_best}')\n\n\tmodel = KNeighborsRegressor(n_neighbors = k_best, n_jobs = -1).fit(Xtrain, Ytrain)\n\tprint('Accuracy: {0}'.format(model.score(Xtrain, Ytrain)))\n\n\t#find the training error\n\tprediction = model.predict(Xtrain)\n\tEtrain = error(prediction, Ytrain)\n\tprint('Training error: {0}'.format(Etrain))\n\n\t#find the validation set error\n\tprediction = model.predict(Xval)\n\tEtrain = error(prediction, Yval)\n\tprint('Validation error: {0}'.format(Etrain))\n\n\n#############################################################################\n# Functions for the hand written neural network. This code was written by me \n# for the Coursera course on neural networks. Therefore, it will have many\n# similarities with code written by others for this course.\n#############################################################################\n\n# np.random.seed(1)\n\ndef sigmoid(Z):\n\treturn 1 / (1 + np.exp(-Z)), Z\n\ndef relu(Z):\n\treturn np.maximum(Z, 0), Z\n\ndef tanh(Z):\n\treturn 6*np.tanh(Z), Z\n\ndef sigmoid_backward(dA, cache):\n\ts = 1 / (1 + np.exp(-cache))\n\treturn dA * s * (1 - s)\n\ndef relu_backward(dA, cache):\n\tdZ = np.array(dA, copy = True)\n\tdZ[cache <= 0] = 0\n\treturn dZ\n\ndef tanh_backward(dA, cache):\n\treturn dA * 6 * (1 / np.cosh(cache)**2)\n\ndef initialize_parameters_deep(layer_dims):\n\t\"\"\"\n\tArguments:\n\tlayer_dims -- python array (list) containing the dimensions of each layer in our network\n\t\n\tReturns:\n\tparameters -- python dictionary containing your parameters \"W1\", \"b1\", ..., \"WL\", \"bL\":\n\t\t\t\t\tWl -- weight matrix of shape (layer_dims[l], layer_dims[l-1])\n\t\t\t\t\tbl -- bias vector of shape (layer_dims[l], 1)\n\t\"\"\"\n\t\n\tnp.random.seed(3)\n\tparameters = {}\n\tL = len(layer_dims)\t\t\t# number of layers in the network\n\n\tfor l in range(1, L):\n\t\tparameters['W' + str(l)] = np.random.randn(layer_dims[l], layer_dims[l-1]) * 0.01\n\t\tparameters['b' + str(l)] = np.zeros((layer_dims[l], 1))\n\t\t\n\t\tassert(parameters['W' + str(l)].shape == (layer_dims[l], layer_dims[l-1]))\n\t\tassert(parameters['b' + str(l)].shape == (layer_dims[l], 1))\n\n\t\t\n\treturn parameters\n\ndef linear_forward(A, W, b):\n\t\"\"\"\n\tImplement the linear part of a layer's forward propagation.\n\n\tArguments:\n\tA -- activations from previous layer (or input data): (size of previous layer, number of examples)\n\tW -- weights matrix: numpy array of shape (size of current layer, size of previous layer)\n\tb -- bias vector, numpy array of shape (size of the current layer, 1)\n\n\tReturns:\n\tZ -- the input of the activation function, also called pre-activation parameter \n\tcache -- a python dictionary containing \"A\", \"W\" and \"b\" ; stored for computing the backward pass efficiently\n\t\"\"\"\n\t\n\tZ = np.dot(W, A) + b\n\t\n\tassert(Z.shape == (W.shape[0], A.shape[1]))\n\tcache = (A, W, b)\n\t\n\treturn Z, cache\n\ndef linear_activation_forward(A_prev, W, b, activation):\n\t\"\"\"\n\tImplement the forward propagation for the LINEAR->ACTIVATION layer\n\n\tArguments:\n\tA_prev -- activations from previous layer (or input data): (size of previous layer, number of examples)\n\tW -- weights matrix: numpy array of shape (size of current layer, size of previous layer)\n\tb -- bias vector, numpy array of shape (size of the current layer, 1)\n\tactivation -- the activation to be used in this layer, stored as a text string: \"sigmoid\" or \"relu\"\n\n\tReturns:\n\tA -- the output of the activation function, also called the post-activation value \n\tcache -- a python dictionary containing \"linear_cache\" and \"activation_cache\";\n\t\t\t stored for computing the backward pass efficiently\n\t\"\"\"\n\t\n\tif activation == \"sigmoid\":\n\t\t# Inputs: \"A_prev, W, b\". Outputs: \"A, activation_cache\".\n\t\tZ, linear_cache = linear_forward(A_prev, W, b)\n\t\tA, activation_cache = sigmoid(Z)\n\telif activation == \"relu\":\n\t\t# Inputs: \"A_prev, W, b\". Outputs: \"A, activation_cache\".\n\t\tZ, linear_cache = linear_forward(A_prev, W, b)\n\t\tA, activation_cache = relu(Z)\n\telif activation == \"tanh\":\n\t\t# Inputs: \"A_prev, W, b\". Outputs: \"A, activation_cache\".\n\t\tZ, linear_cache = linear_forward(A_prev, W, b)\n\t\tA, activation_cache = tanh(Z)\n\t\n\tassert (A.shape == (W.shape[0], A_prev.shape[1]))\n\tcache = (linear_cache, activation_cache)\n\n\treturn A, cache\n\ndef L_model_forward(X, parameters, activation, final_activation):\n\t\"\"\"\n\tImplement forward propagation for the [LINEAR->RELU]*(L-1)->LINEAR->SIGMOID computation\n\t\n\tArguments:\n\tX -- data, numpy array of shape (input size, number of examples)\n\tparameters -- output of initialize_parameters_deep()\n\t\n\tReturns:\n\tAL -- last post-activation value\n\tcaches -- list of caches containing:\n\t\t\t\tevery cache of linear_relu_forward() (there are L-1 of them, indexed from 0 to L-2)\n\t\t\t\tthe cache of linear_sigmoid_forward() (there is one, indexed L-1)\n\t\"\"\"\n\n\tcaches = []\n\tA = X\n\tL = len(parameters) // 2\t\t\t\t # number of layers in the neural network\n\t\n\t# Implement [LINEAR -> RELU]*(L-1). Add \"cache\" to the \"caches\" list.\n\tfor l in range(1, L):\n\t\tA_prev = A \n\t\tA, cache = linear_activation_forward(A_prev, parameters['W{0}'.format(l)], parameters['b{0}'.format(l)], activation)\n\t\tcaches.append(cache)\n\t\n\t# Implement LINEAR -> RELU as the final activation unit. Add \"cache\" to the \"caches\" list.\n\tAL, cache = linear_activation_forward(A, parameters['W{0}'.format(L)], parameters['b{0}'.format(L)], final_activation)\n\n\tcaches.append(cache)\n\t\n\tassert(AL.shape == (1,X.shape[1]))\n\t\t\t\n\treturn AL, caches\n\ndef compute_cost(AL, Y):\n\t\"\"\"\n\tImplement the cost function defined by equation (7).\n\n\tArguments:\n\tAL -- probability vector corresponding to your label predictions, shape (1, number of examples)\n\tY -- true \"label\" vector (for example: containing 0 if non-cat, 1 if cat), shape (1, number of examples)\n\n\tReturns:\n\tcost -- cross-entropy cost\n\t\"\"\"\n\t\n\tm = Y.shape[1]\n\n\t# Compute loss from aL and y.\n\tcost = -np.mean(Y * np.log(AL) + (1 - Y) * np.log(1 - AL))\n\t\n\tcost = np.squeeze(cost)\t # To make sure your cost's shape is what we expect (e.g. this turns [[17]] into 17).\n\tassert(cost.shape == ())\n\t\n\treturn cost\n\ndef linear_backward(dZ, cache):\n\t\"\"\"\n\tImplement the linear portion of backward propagation for a single layer (layer l)\n\n\tArguments:\n\tdZ -- Gradient of the cost with respect to the linear output (of current layer l)\n\tcache -- tuple of values (A_prev, W, b) coming from the forward propagation in the current layer\n\n\tReturns:\n\tdA_prev -- Gradient of the cost with respect to the activation (of the previous layer l-1), same shape as A_prev\n\tdW -- Gradient of the cost with respect to W (current layer l), same shape as W\n\tdb -- Gradient of the cost with respect to b (current layer l), same shape as b\n\t\"\"\"\n\tA_prev, W, b = cache\n\tm = A_prev.shape[1]\n\n\tdW = np.dot(dZ, A_prev.T) / m\n\tdb = np.mean(dZ, axis = 1, keepdims = True)\n\tdA_prev = np.dot(W.T, dZ)\n\t\n\tassert (dA_prev.shape == A_prev.shape)\n\tassert (dW.shape == W.shape)\n\tassert (db.shape == b.shape)\n\t\n\treturn dA_prev, dW, db\n\ndef linear_activation_backward(dA, cache, activation):\n\t\"\"\"\n\tImplement the backward propagation for the LINEAR->ACTIVATION layer.\n\t\n\tArguments:\n\tdA -- post-activation gradient for current layer l \n\tcache -- tuple of values (linear_cache, activation_cache) we store for computing backward propagation efficiently\n\tactivation -- the activation to be used in this layer, stored as a text string: \"sigmoid\" or \"relu\"\n\t\n\tReturns:\n\tdA_prev -- Gradient of the cost with respect to the activation (of the previous layer l-1), same shape as A_prev\n\tdW -- Gradient of the cost with respect to W (current layer l), same shape as W\n\tdb -- Gradient of the cost with respect to b (current layer l), same shape as b\n\t\"\"\"\n\tlinear_cache, activation_cache = cache\n\t\n\tif activation == \"relu\":\n\t\tdZ = relu_backward(dA, activation_cache)\n\t\tdA_prev, dW, db = linear_backward(dZ, linear_cache)\n\t\t\n\telif activation == \"sigmoid\":\n\t\tdZ = sigmoid_backward(dA, activation_cache)\n\t\tdA_prev, dW, db = linear_backward(dZ, linear_cache)\n\n\telif activation == \"tanh\":\n\t\tdZ = tanh_backward(dA, activation_cache)\n\t\tdA_prev, dW, db = linear_backward(dZ, linear_cache)\n\t\n\treturn dA_prev, dW, db\n\ndef L_model_backward(AL, Y, caches, activation, final_activation):\n\t\"\"\"\n\tImplement the backward propagation for the [LINEAR->RELU] * (L-1) -> LINEAR -> SIGMOID group\n\t\n\tArguments:\n\tAL -- probability vector, output of the forward propagation (L_model_forward())\n\tY -- true \"label\" vector (containing 0 if non-cat, 1 if cat)\n\tcaches -- list of caches containing:\n\t\t\t\tevery cache of linear_activation_forward() with \"relu\" (it's caches[l], for l in range(L-1) i.e l = 0...L-2)\n\t\t\t\tthe cache of linear_activation_forward() with \"sigmoid\" (it's caches[L-1])\n\t\n\tReturns:\n\tgrads -- A dictionary with the gradients\n\t\t\t grads[\"dA\" + str(l)] = ... \n\t\t\t grads[\"dW\" + str(l)] = ...\n\t\t\t grads[\"db\" + str(l)] = ... \n\t\"\"\"\n\tgrads = {}\n\tL = len(caches) # the number of layers\n\tm = AL.shape[1]\n\tY = Y.reshape(AL.shape) # after this line, Y is the same shape as AL\n\t\n\t# Initializing the backpropagation\n\tdAL = AL - Y\n\t\n\t# Lth layer (SIGMOID -> LINEAR) gradients. Inputs: \"AL, Y, caches\". Outputs: \"grads[\"dAL\"], grads[\"dWL\"], grads[\"dbL\"]\n\tcurrent_cache = caches[L - 1]\n\tgrads[\"dA\" + str(L)], grads[\"dW\" + str(L)], grads[\"db\" + str(L)] = linear_activation_backward(dAL, current_cache, final_activation)\n\tfor l in reversed(range(L-1)):\n\t\t# lth layer: (RELU -> LINEAR) gradients.\n\t\t# Inputs: \"grads[\"dA\" + str(l + 2)], caches\". Outputs: \"grads[\"dA\" + str(l + 1)] , grads[\"dW\" + str(l + 1)] , grads[\"db\" + str(l + 1)] \n\t\tcurrent_cache = caches[l]\n\t\tdA_prev_temp, dW_temp, db_temp = linear_activation_backward(grads['dA' + str(l+2)], current_cache, activation)\n\t\tgrads[\"dA\" + str(l + 1)] = dA_prev_temp\n\t\tgrads[\"dW\" + str(l + 1)] = dW_temp\n\t\tgrads[\"db\" + str(l + 1)] = db_temp\n\n\treturn grads\n\ndef update_parameters(parameters, grads, learning_rate):\n\t\"\"\"\n\tUpdate parameters using gradient descent\n\t\n\tArguments:\n\tparameters -- python dictionary containing your parameters \n\tgrads -- python dictionary containing your gradients, output of L_model_backward\n\t\n\tReturns:\n\tparameters -- python dictionary containing your updated parameters \n\t\t\t\t parameters[\"W\" + str(l)] = ... \n\t\t\t\t parameters[\"b\" + str(l)] = ...\n\t\"\"\"\n\t\n\tL = len(parameters) // 2 # number of layers in the neural network\n\n\t# Update rule for each parameter. Use a for loop.\n\tfor l in range(L):\n\t\tparameters['W{0}'.format(l+1)] = parameters['W{0}'.format(l+1)] - learning_rate * grads['dW{0}'.format(l+1)]\n\t\tparameters['b{0}'.format(l+1)] = parameters['b{0}'.format(l+1)] - learning_rate * grads['db{0}'.format(l+1)]\n\treturn parameters\n\ndef L_layer_model(X, Y, layers_dims, learning_rate = 0.0001, num_iterations = 3000, print_cost=False, activation = 'relu', final_activation = 'tanh'):#lr was 0.009\n\t\"\"\"\n\tImplements a L-layer neural network: [LINEAR->RELU]*(L-1)->LINEAR->SIGMOID.\n\t\n\tArguments:\n\tX -- data, numpy array of shape (number of examples, num_px * num_px * 3)\n\tY -- true \"label\" vector (containing 0 if cat, 1 if non-cat), of shape (1, number of examples)\n\tlayers_dims -- list containing the input size and each layer size, of length (number of layers + 1).\n\tlearning_rate -- learning rate of the gradient descent update rule\n\tnum_iterations -- number of iterations of the optimization loop\n\tprint_cost -- if True, it prints the cost every 100 steps\n\t\n\tReturns:\n\tparameters -- parameters learnt by the model. They can then be used to predict.\n\t\"\"\"\n\n\timport matplotlib.pyplot as plt\n\n\t# np.random.seed(1)\n\tcosts = []\t\t\t\t\t\t # keep track of cost\n\t\n\t# Parameters initialization.\n\tparameters = initialize_parameters_deep(layers_dims)\n\t\n\t# Loop (gradient descent)\n\tfor i in range(0, num_iterations):\n\n\t\t# Forward propagation: [LINEAR -> RELU]*(L-1) -> LINEAR -> SIGMOID.\n\t\tAL, caches = L_model_forward(X, parameters, activation, final_activation)\n\t\t\n\t\t# Compute cost.\n\t\tcost = compute_cost(AL, Y)\n\t\n\t\t# Backward propagation.\n\t\tgrads = L_model_backward(AL, Y, caches, activation, final_activation)\n \n\t\t# Update parameters.\n\t\tparameters = update_parameters(parameters, grads, learning_rate)\n\t\t\t\t\n\t\t# Print the cost every 100 training example\n\t\tif print_cost and i % 100 == 0:\n\t\t\tprint (\"Cost after iteration %i: %f\" %(i, cost))\n\t\tif print_cost and i % 100 == 0:\n\t\t\tcosts.append(cost)\n\t\t\t\n\t# plot the cost\n\tplt.plot(np.squeeze(costs))\n\tplt.ylabel('cost')\n\tplt.xlabel('iterations (per tens)')\n\tplt.title(\"Learning rate =\" + str(learning_rate))\n\tplt.show()\n\t\n\treturn parameters\n\nXtrain, Xtest, Ytrain, Ytest = loadData()\n\nprint(f'Shape of training data: {Xtrain.shape}')\n\n# linear(Xtrain, Ytrain, Xtest, Ytest)\n# ridge(Xtrain, Ytrain, Xtest, Ytest)\n# lasso(Xtrain, Ytrain, Xtest, Ytest)\n\n# RF(Xtrain, Ytrain, Xtest, Ytest)\n# Adaboost(Xtrain, Ytrain, Xtest, Ytest)\n# Bagging(Xtrain, Ytrain, Xtest, Ytest)\n# ExtraTrees(Xtrain, Ytrain, Xtest, Ytest)\n# SVM(Xtrain, Ytrain, Xtest, Ytest, kerneltype = 'linear')\nNearestNeighbour(Xtrain, Ytrain, Xtest, Ytest)\n\n'''\n#run the Neural Network\nlayers_dims = [5, 8, 6, 3, 1]\nparameters = L_layer_model(Xtrain.T, Ytrain[:,None].T, layers_dims, num_iterations = 1000, print_cost = True, activation = 'relu')\n\n#now input the test set and see the results\nAL, cache = L_model_forward(Xtest.T, parameters, 'relu', 'tanh')\n\nprint(AL[:100])\n\nprint('Neural network error: {0}'.format(error(AL[0], Ytest)))\n'''","sub_path":"FinalProject/Q2/finalproject_Q2.py","file_name":"finalproject_Q2.py","file_ext":"py","file_size_in_byte":21645,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"252045995","text":"from scripts import main\nfrom config import load_conf\n\n\n\n\ndef main():\n config = load_conf(args)\n app = init_app(config)\n if app.config.WEBSOCKET:\n from sanic.websocket import WebSocketProtocol\n app.run(\n host=app.config.HOST,\n port=app.config.PORT,\n worker=app.config.WORKER,\n protocol = WebSocketProtocol,\n debug=False, access_log=False\n )\n else:\n app.run(\n host=app.config.HOST,\n port=app.config.PORT,\n worker=app.config.WORKER,\n debug=False, access_log=False\n )\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"metadata_center/__main__.py","file_name":"__main__.py","file_ext":"py","file_size_in_byte":651,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"391461207","text":"#!/usr/bin/env python\n\nimport os\nfrom flask import Flask, request, jsonify, g\nimport requests\n\nfrom api.src.config.logger import create_logger\nfrom api.src.errors import OperationOutcome\nfrom api.src.producer_class import RiverApiProducer\nimport uuid\n\nPRODUCED_TOPIC = \"batch\"\nEXTRACTOR_URL = os.getenv(\"EXTRACTOR_URL\")\nTRANSFORMER_URL = os.getenv(\"TRANSFORMER_URL\")\nKAFKA_BOOTSTRAP_SERVERS = os.getenv(\"KAFKA_BOOTSTRAP_SERVERS\")\n\nlogger = create_logger(\"api\")\n\n\ndef get_producer():\n if \"producer\" not in g:\n g.producer = RiverApiProducer(broker=KAFKA_BOOTSTRAP_SERVERS)\n return g.producer\n\n\ndef create_app():\n app = Flask(__name__)\n return app\n\n\n# Create flask app object\napp = create_app()\n\n\n@app.route(\"/preview\", methods=[\"POST\"])\ndef trigger_sample_extractor():\n \"\"\"\n Extract record for the specified resource and primary key value\n \"\"\"\n body = request.get_json()\n resource_id = body.get(\"resource_id\", None)\n primary_key_values = body.get(\"primary_key_values\", None)\n logger.debug(\"PREVIEW %s %s\", resource_id, primary_key_values)\n\n try:\n extract_resp = requests.post(\n f\"{EXTRACTOR_URL}/extract\",\n json={\"resource_id\": resource_id, \"primary_key_values\": primary_key_values},\n )\n if extract_resp.status_code != 200:\n raise Exception(\n f\"Failed while extracting data: {extract_resp.content.decode('utf-8')}.\"\n )\n\n rows = extract_resp.json()[\"rows\"]\n transform_resp = requests.post(\n f\"{TRANSFORMER_URL}/transform\", json={\"resource_id\": resource_id, \"dataframe\": rows},\n )\n if transform_resp.status_code != 200:\n raise Exception(\n f\"Failed while transforming data: {transform_resp.content.decode('utf-8')}.\"\n )\n return jsonify(transform_resp.json())\n\n except Exception as e:\n raise OperationOutcome(e)\n\n\n@app.route(\"/batch\", methods=[\"POST\"])\ndef trigger_batch_extractor():\n \"\"\"\n Extract all records for the specified resources\n \"\"\"\n body = request.get_json()\n resource_ids = body.get(\"resource_ids\", None)\n batch_id = uuid.uuid4().hex\n\n try:\n for resource_id in resource_ids:\n create_extractor_trigger(resource_id, batch_id)\n return \"Success\", 200\n\n except Exception as e:\n raise OperationOutcome(e)\n\n\n@app.errorhandler(OperationOutcome)\ndef handle_bad_request(e):\n return str(e), 400\n\n\ndef create_extractor_trigger(resource_id, batch_id=None, primary_key_values=None):\n \"\"\"\n Produce event to trigger extractor\n :param batch_id:\n :param resource_id:\n :param primary_key_values:\n :return:\n \"\"\"\n\n event = dict()\n event[\"batch_id\"] = batch_id\n event[\"resource_id\"] = resource_id\n event[\"primary_key_values\"] = primary_key_values\n\n get_producer().produce_event(topic=PRODUCED_TOPIC, event=event)\n","sub_path":"api/src/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":2908,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"650693766","text":"import mysql.connector\nimport Bot.StaticResources\nfrom mysql.connector import MySQLConnection\nfrom mysql.connector import errorcode\nfrom traceback import format_exc\n\n\nclass MySQLConnector:\n conn = None\n cursor = None\n db_name = \"\"\n\n def __init__(self, username):\n print(\"Attempting connection to database\")\n self.db_name = username\n try:\n self.conn = MySQLConnection(user=\"root\")\n self.cursor = self.conn.cursor()\n self.conn.database = self.db_name\n self.init_tables()\n except mysql.connector.Error as err:\n # If the connection is refused by the server\n if err.errno == errorcode.ER_ABORTING_CONNECTION:\n print(\"Unable to access database! {}\".format(err))\n # If the database does not exist\n elif err.errno == errorcode.ER_BAD_DB_ERROR:\n self.init_database()\n self.conn.database = self.db_name\n print(\"Database created for {} and connected!\".format(username))\n self.init_tables()\n self.update_commands(\"!test\", response=\"This is an update test AGAIN!\", userlevel=\"1\")\n self.update_timeouts(\"emotes\", enabled=\"0\")\n\n # Create a database\n def init_database(self):\n try:\n self.cursor.execute(\"CREATE DATABASE {} DEFAULT CHARACTER SET 'utf8'\".format(self.db_name))\n print(\"Successfully created Database\")\n except mysql.connector.Error as cderr:\n # If database already exists\n if cderr.errno == errorcode.ER_DB_CREATE_EXISTS:\n print(\"Database already exists. Stepping forward\".format(cderr))\n # otherwise exit\n else:\n print(\"Error Creating Database: {}\".format(cderr))\n exit(1)\n\n # Init default tables if necessary\n def init_tables(self):\n # Default Table Initializers *Just in-case*\n tables = Bot.StaticResources.tables\n insert_into_tables = Bot.StaticResources.insert_to_tables\n for name in tables:\n try:\n print(\"Creating table {}: \".format(name))\n self.cursor.execute(tables[name])\n print(\"Inserting Default Settings\")\n try:\n print(insert_into_tables[name])\n self.cursor.execute(insert_into_tables[name])\n except KeyError:\n print(\"[SAFE] No defaults comfigured. Skipping.\")\n except mysql.connector.Error as err:\n if err.errno == errorcode.ER_TABLE_EXISTS_ERROR:\n print(\"[SAFE] Skipping {}. Already exists.\".format(name))\n else:\n print(err)\n else:\n print(\"OK\")\n\n # No use as of now, possible integration for custom commands???\n def raw_query(self, query):\n try:\n self.cursor.execute(query)\n except mysql.connector.Error as err:\n print(err)\n return self.cursor\n\n # Update commands based on a command\n def update_commands(self, comm_to_edit, command=None, response=None, userlevel=None, specficuser=None, enabled=None,\n repeatamount=None, usagecount=None):\n query = \"UPDATE commands SET \"\n query += \"\" if command is None else \"Command='\" + command + \"', \"\n query += \"\" if response is None else \"Response='\" + response + \"', \"\n query += \"\" if userlevel is None else \"UserLevel=\" + userlevel + \", \"\n query += \"\" if specficuser is None else \"SpecificUser='\" + specficuser + \"', \"\n query += \"\" if enabled is None else \"Enabled=\" + enabled + \", \"\n query += \"\" if repeatamount is None else \"RepeatAmount=\" + repeatamount + \", \"\n query += \"\" if usagecount is None else \"UsageCount=\" + usagecount + \", \"\n if query == \"UPDATE commands SET \":\n print(\"[ERROR] Query Attempt Empty. Breaking (commands)\")\n return\n else:\n query = query[:len(query) - 2]\n query += \" WHERE Command = '\" + comm_to_edit + \"'\"\n print(query)\n try:\n self.cursor.execute(query)\n except mysql.connector.Error as err:\n print(\"[ERROR] MySQL Error: {}\".format(err))\n except:\n print(\"[ERROR] Generic Error: {}\".format(format_exc()))\n else:\n self.conn.commit()\n print(\"OK\")\n\n # Update timers based on command\n def update_timers(self, timer_to_edit, timer=None, response=None, enabled=None, triggertime=None):\n query = \"UPDATE timers SET \"\n query += \"\" if timer is None else \"Timer='\" + timer + \"', \"\n query += \"\" if response is None else \"Response='\" + response + \"', \"\n query += \"\" if enabled is None else \"Enabled=\" + enabled + \", \"\n query += \"\" if triggertime is None else \"TriggerTime=\" + triggertime + \", \"\n if query == \"UPDATE timers SET \":\n print(\"[ERROR] Query Attempt Empty. Breaking (timers)\")\n return\n else:\n query = query[:len(query) - 2]\n print(query)\n query += \" WHERE Timer = '\" + timer_to_edit + \"'\"\n print(query)\n try:\n self.cursor.execute(query)\n except mysql.connector.Error as err:\n print(\"[ERROR] MySQL Error: {}\".format(err))\n except:\n print(\"[ERROR] Generic Error: {}\".format(format_exc()))\n else:\n self.conn.commit()\n print(\"OK\")\n\n # Update timeout settings based on command\n def update_timeouts(self, timeout_type, custom_message=None, enabled=None, message_ban=None, message_timeout=None,\n message_warning=None, message_custom=None, ratio=None, silence=None):\n query = \"UPDATE {}_timeouts SET \".format(timeout_type)\n query += \"\" if custom_message is None else \"CustomMessage=\" + custom_message + \", \"\n query += \"\" if enabled is None else \"Enabled=\" + enabled + \", \"\n query += \"\" if message_ban is None else \"MessageBan='\" + message_ban + \"', \"\n query += \"\" if message_timeout is None else \"MessageTimeout='\" + message_timeout + \"', \"\n query += \"\" if message_warning is None else \"MessageWarning='\" + message_warning + \"', \"\n query += \"\" if message_custom is None else \"MessageCustom='\" + message_custom + \"', \"\n query += \"\" if ratio is None else \"Ratio=\" + ratio + \", \"\n query += \"\" if silence is None else \"Silence=\" + silence + \", \"\n if query == \"UPDATE {}_timeouts SET \".format(timeout_type):\n print(\"[ERROR] Query Attempt Empty. Breaking (timeouts)\")\n return\n else:\n query = query[:len(query) - 2]\n print(query)\n try:\n self.cursor.execute(query)\n except mysql.connector.Error as err:\n print(\"[ERROR] MySQL Error: {}\".format(err))\n except:\n print(\"[ERROR] Generic Error: {}\".format(format_exc()))\n else:\n self.conn.commit()\n print(\"OK\")\n\n # Update generic settings based on command\n def update_settings(self, newsub=None, returnsub=None, quotes=None, isaac=None,\n globalsilence=None, specialusers=None, castermessage=None):\n query = \"UPDATE settings SET \"\n query += \"NewSub='\" + newsub + \"', \"\n query += \"ReturnSub='\" + returnsub + \"', \"\n query += \"Quotes=\" + quotes + \", \"\n query += \"Isaac=\" + isaac + \", \"\n query += \"GlobalSilence=\" + globalsilence + \", \"\n query += \"SpecialUsers=\" + specialusers + \", \"\n query += \"CasterMessage='\" + castermessage + \", \"\n if query == \"UPDATE settings SET \":\n print(\"[ERROR] Query Attempt Empty. Breaking (settings)\")\n return\n else:\n query = query[:len(query) - 2]\n print(query)\n try:\n self.cursor.execute(query)\n except mysql.connector.Error as err:\n print(\"[ERROR] MySQL Error: {}\".format(err))\n except:\n print(\"[ERROR] Generic Error: {}\".format(format_exc()))\n else:\n self.conn.commit()\n print(\"OK\")\n\n # Update user data based on command\n def update_userdata(self, user_to_update, username=None, chatlines=None, emotes=None, last_message=None,\n timeout_count=None, time_connected_online=None, total_time_connected=None, subscribed=None):\n query = \"UPDATE userdata SET \"\n query += \"\" if username is None else \"Username='\" + username + \"', \"\n query += \"\" if chatlines is None else \"Chatlines=\" + chatlines + \", \"\n query += \"\" if emotes is None else \"Emotes=\" + emotes + \", \"\n query += \"\" if last_message is None else \"LastMessage='\" + last_message + \"', \"\n query += \"\" if timeout_count is None else \"TimeoutCount=\" + timeout_count + \", \"\n query += \"\" if time_connected_online is None else \"TimeConnectedOnline=\" + time_connected_online + \", \"\n query += \"\" if total_time_connected is None else \"TotalTimeConnected=\" + total_time_connected + \", \"\n query += \"\" if subscribed is None else \"Subscribed=\" + subscribed + \", \"\n if query == \"UPDATE userdata SET \":\n print(\"[ERROR] Empty Query Attmpr. Breaking. (userdata)\")\n return\n else:\n query = query[:len(query) - 2]\n query += \" WHERE Username='\" + user_to_update + \"'\"\n print(query)\n try:\n self.cursor.execute(query)\n except mysql.connector.Error as err:\n print(\"[ERROR] MySQL Error: {}\".format(err))\n except:\n print(\"[ERROR] Generic Error: {}\".format(format_exc()))\n else:\n self.conn.commit()\n print(\"OK\")","sub_path":"Bot/CustomMySQL.py","file_name":"CustomMySQL.py","file_ext":"py","file_size_in_byte":9752,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"402007519","text":"import os\r\nimport cv2\r\nimport numpy as np\r\nimport faceRecognition as fr\r\nimport time\r\n\r\n\r\n#This module captures images via webcam and performs face recognition\r\n# face_recognizer = cv2.face.LBPHFaceRecognizer_create()\r\n# face_recognizer.read('C:/Users/vrush/PycharmProjects/project_new/trainingData.yml')#Load saved training data\r\n\r\n# name = {0: \"Donald Trump\", 1: \"Bill Gates\",2: \"Elon Musk\", 3: \"Jeff\",4: \"Obama\",5:\"Kirtan\",6:\"Vrushang\",7:\"Adesh\"}\r\nsem=input(\"Enter Semester of student:\")\r\nrollno=input(\"Enter rollno of student\")\r\n\r\ntake_name=sem+\" \"+rollno\r\ncap=cv2.VideoCapture(0)\r\nos.mkdir('C:/Users/vrush/PycharmProjects/project_new/trainingImages/'+sem+\" \"+rollno)\r\nnum=1\r\nwhile True:\r\n ret,test_img=cap.read()# captures frame and returns boolean value and captured image\r\n\r\n temp_img=test_img.copy()\r\n faces_detected,gray_img=fr.faceDetection(test_img)\r\n\r\n # num=num+1\r\n # if(num<=50):\r\n # break\r\n for (x, y, w, h) in faces_detected:\r\n cv2.rectangle(test_img, (x, y), (x + w, y + h), (255, 0, 0), thickness=7)\r\n\r\n\r\n\r\n font = cv2.FONT_HERSHEY_SIMPLEX\r\n for face in faces_detected:\r\n (x, y, w, h) = face\r\n roi_gray = gray_img[y:y + h, x:x + h]\r\n font = cv2.FONT_HERSHEY_SIMPLEX\r\n if(num==51):\r\n break\r\n\r\n\r\n if(num<=50):\r\n cv2.imwrite('C:/Users/vrush/PycharmProjects/project_new/trainingImages/' + take_name + '/' + str(num) + '.jpg',roi_gray)\r\n cv2.putText(test_img, str(num), (x, y), font, 1, (200, 255, 255))\r\n # time.sleep(1)\r\n\r\n\r\n num=num+1\r\n\r\n resized_img = cv2.resize(test_img, (1000, 700))\r\n cv2.imshow('face detection Tutorial ', resized_img)\r\n cv2.waitKey(10)\r\n if cv2.waitKey(10) == ord('q'):#wait until 'q' key is pressed\r\n break\r\n if num==51:\r\n break\r\n# q\r\ncap.release()\r\ncv2.destroyAllWindows()\r\n\r\n\r\n# take_name=input(\"Enter name of student\")\r\n# cap=cv2.VideoCapture(0)\r\n# os.mkdir('C:/Users/vrush/PycharmProjects/project_new/trainingImages/'+take_name)\r\n# num=1\r\n# while True:\r\n# ret,test_img=cap.read()# captures frame and returns boolean value and captured image\r\n#\r\n# # num=num+1\r\n# # if(num<=50):\r\n# # break\r\n# for (x, y, w, h) in test_img:\r\n# cv2.rectangle(test_img, (x, y), (x + w, y + h), (255, 0, 0), thickness=7)","sub_path":"project_new/take_sample.py","file_name":"take_sample.py","file_ext":"py","file_size_in_byte":2334,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"424603365","text":"from tkinter import *\r\nimport os\r\nfrom PIL import Image, ImageTk\r\nimport openpyxl\r\nfrom openpyxl import load_workbook\r\nfrom datetime import date\r\nfrom twilio.rest import Client\r\n\r\n\r\nclass GUI(Tk):\r\n def __init__(self):\r\n super(GUI, self).__init__()\r\n self.geometry(\"800x500\")\r\n self.config(bg=\"silver\")\r\n self.resizable(0, 0)\r\n self.title(\"Attendance system\")\r\n\r\n def create_menu(self):\r\n self.mymenu = Menu()\r\n self.mymenu.add_cascade(label=\"Attendance\", command=f1)\r\n self.mymenu.add_cascade(label=\"Students\", command=f1)\r\n\r\n m3 = Menu(self.mymenu, tearoff=0)\r\n m3.add_command(label=\"About us\")\r\n self.config(menu=self.mymenu)\r\n self.mymenu.add_cascade(label=\"More\", menu=m3)\r\n\r\n\r\ndef f1():\r\n print(\"ok\")\r\n\r\n\r\ndef write_to_txt(name_val, usn_val, sec_val, sem_val, phone_val, email_val):\r\n print(\"writting\")\r\n path = 'students'\r\n if not os.path.exists('students'):\r\n os.makedirs('students')\r\n\r\n elif not os.path.exists(f\"{path}/{sem_val}\"):\r\n os.makedirs(f\"{path}/{sem_val}/{sec_val}\")\r\n else:\r\n file = open(f\"{path}/{sem_val}/{sec_val}.txt\", \"a\")\r\n file.write(f\"{usn_val},{name_val},{sem_val},{sec_val},{phone_val},{email_val}\\n\")\r\n file.close()\r\n\r\n\r\ndef create_xls(path):\r\n wb = openpyxl.Workbook()\r\n if path == \"student.xlsx\":\r\n wb.create_sheet(\"year1\")\r\n wb.create_sheet(\"year2\")\r\n wb.create_sheet(\"year3\")\r\n wb.create_sheet(\"year4\")\r\n wb.save(path)\r\n else:\r\n wb.save(f\"Attendance\\{path}.xlsx\")\r\n\r\n\r\ndef write_to_xls(name, usn, sec, sem, phone, email):\r\n if sem == \"1\" or sem == \"2\":\r\n if sec == \"a\":\r\n year = \"year1_a\"\r\n else:\r\n year = \"year1_b\"\r\n\r\n elif sem == \"3\" or sem == \"4\":\r\n if sec == \"a\":\r\n year = \"year2_a\"\r\n else:\r\n year = \"year2_b\"\r\n elif sem == \"5\" or sem == \"6\":\r\n if sec == \"a\":\r\n year = \"year3_a\"\r\n else:\r\n year = \"year3_b\"\r\n else:\r\n if sec == \"a\":\r\n year = \"year4_a\"\r\n else:\r\n year = \"year4_b\"\r\n wb = load_workbook(f\"student.xlsx\")\r\n sheet = wb.get_sheet_by_name(f\"{year}\")\r\n sheet.cell(row=1, column=1).value = \"Sl.NO\"\r\n sheet.cell(row=1, column=2).value = \"Name\"\r\n sheet.cell(row=1, column=3).value = \"Enrollment\"\r\n sheet.cell(row=1, column=4).value = \"Section\"\r\n sheet.cell(row=1, column=5).value = \"Semester\"\r\n sheet.cell(row=1, column=6).value = \"Contact No\"\r\n sheet.cell(row=1, column=7).value = \"Email id\"\r\n sheet.cell(row=2, column=1).value = \"1\"\r\n c = 0\r\n current_row = sheet.max_row\r\n current_column = sheet.max_column\r\n\r\n sheet.cell(row=current_row, column=2).value = name\r\n sheet.cell(row=current_row, column=3).value = usn\r\n sheet.cell(row=current_row, column=4).value = sec\r\n sheet.cell(row=current_row, column=5).value = sem\r\n sheet.cell(row=current_row, column=6).value = phone\r\n sheet.cell(row=current_row, column=7).value = email\r\n sheet.cell(row=current_row + 1, column=1).value = int(sheet.cell(current_row, 1).value) + 1\r\n\r\n wb.save('student.xlsx')\r\n path = f\"Attendance/{year}.xlsx\"\r\n if not os.path.exists(path):\r\n create_xls(path)\r\n wb = load_workbook(f\"Attendance/{year}.xlsx\")\r\n sheet = wb.active\r\n sheet.cell(row=1, column=1).value = \"Sl.NO\"\r\n sheet.cell(row=1, column=2).value = \"Name\"\r\n sheet.cell(row=1, column=3).value = \"Enrollment\"\r\n sheet.cell(row=1, column=4).value = \" \"\r\n sheet.cell(row=2, column=1).value = \"1\"\r\n current_row = sheet.max_row\r\n\r\n sheet.cell(row=current_row, column=2).value = name\r\n sheet.cell(row=current_row, column=3).value = usn\r\n sheet.cell(row=current_row + 1, column=1).value = int(sheet.cell(current_row, 1).value) + 1\r\n wb.save(f'Attendance\\{year}.xlsx')\r\n\r\n\r\ndef send_message(name, sub, contact):\r\n # the following line needs your Twilio Account SID and Auth Token\r\n client = Client(\"ACf99b80984b43f1b59121a72685deaba9\", \"77eb50a8910ec309771c0a9538787a0b\")\r\n\r\n # change the \"from_\" number to your Twilio number and the \"to\" number\r\n # to the phone number you signed up for Twilio with, or upgrade your\r\n # account to send SMS to any phone number\r\n for i in range(len(name)):\r\n client.messages.create(to=f\"+91{contact[i]}\", from_=\"+1 571 290 2779\", body=f\"{name[i]} is absent for {sub} class on {date.today()}\")\r\n","sub_path":"final_year_project/exe1.py","file_name":"exe1.py","file_ext":"py","file_size_in_byte":4485,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"589657248","text":"from django import forms\nfrom .models import Reserva, restaurante\n\nclass NuevaReserva (forms.ModelForm):\n \n class Meta:\n model = Reserva\n fields = ('User', 'email', 'telefono', 'personas', 'dia', 'hora', 'mesa' )\n widgets = {'User':forms.HiddenInput(),'restaurante': forms.HiddenInput(),\n 'dia':forms.DateInput,'hora':forms.TimeInput}","sub_path":"listado/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":368,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"154286468","text":"import os\nfrom glob import glob\n\n\n'''\nMulti Epoch Test\n'''\n\ndef epoch_list_test():\n # weights_path = '../results/gen/*.hdf5'\n # weights_list = [x for x in glob(weights_path)]\n\n weights_list = [f'../results/gen/weights-{str(x).zfill(2)}.hdf5' for x in [300]]\n d_path = '/home/ubuntu/project/seoul/dataset/sample_dataset/resize_dsm/DSM/sub_8.tif'\n p_path = d_path.replace('DSM', 'PAN')\n l_path = d_path.replace('DSM', 'LABEL')\n \n\n\n for w in weights_list:\n w_name = os.path.split(w)[1]\n print('='*len(w_name))\n print(w_name)\n print('='*len(w_name))\n cmd = f'python predict.py -w {w} -d {d_path} -p {p_path} -l {l_path}'\n os.system(cmd)\n\n print('Finished...')\n\n\n'''\nMulti Image Test\n'''\n\ndef image_list_test():\n # Weights path\n W = '../results/gen/weights-2180.hdf5'\n # Get tif list\n dsm_list = sorted([x for x in glob('./sample/DSM/*.tif')])\n pan_list = sorted([x for x in glob('./sample/PAN/*.tif')])\n label_list = sorted([x for x in glob('./sample/LABEL/*.tif')])\n\n for D, P, L in zip(dsm_list, pan_list, label_list):\n cmd = f'python predict.py -d {D} -p {P} -l {L} -w {W}'\n os.system(cmd)\n\n print('Finished...')\n\n\nif __name__ == '__main__':\n # epoch_list_test()\n image_list_test()\n\n\n","sub_path":"inference/epoch_predict.py","file_name":"epoch_predict.py","file_ext":"py","file_size_in_byte":1296,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"323784441","text":"#coding=utf-8\nimport requests\nimport json\n\ndef hua2(use_id):\n hua2_url=\"http://125.35.6.84:81/xk/itownet/portalAction.do?method=getXkzsById\"\n params={\n \"id\": use_id\n }\n\n headers={\n \"User-Agent\": \"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.70 Safari/537.36\"\n }\n\n res=requests.post(url=hua2_url,params=params,headers=headers)\n return res.json()\nre=hua2(\"270b93b832a54210aa97d2444433bd72\")\nprint(re)","sub_path":"爬虫/requests_1028/化妆品监管2.py","file_name":"化妆品监管2.py","file_ext":"py","file_size_in_byte":486,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"47265639","text":"from flask_assets import Bundle\nimport os\n\n\ndef compile_assets(assets):\n main_css_bundle = Bundle(\n 'src/css/*.css',\n filters='cssmin',\n output='dist/css/main.min.css',\n extra={'rel': 'stylesheet/css'}\n )\n\n vendor_css_bundle = Bundle(\n 'src/css/vendors/*.css',\n filters='cssmin',\n output='dist/css/vendor.min.css',\n extra={'rel': 'stylesheet/css'}\n )\n\n vendor_js_bundle = Bundle(\n 'src/js/vendors/jquery.js',\n 'src/js/vendors/bootstrap.bundle.js',\n 'src/js/vendors/notify.js',\n 'src/js/vendors/jquery.validate.js',\n filters='jsmin',\n output='dist/js/vendor.min.js'\n )\n\n\n assets.register('main_css', main_css_bundle)\n assets.register('vendor_js', vendor_js_bundle)\n assets.register('vendor_css', vendor_css_bundle)\n if os.getenv('FLASK_ENV') == 'DEVELOPMENT':\n main_css_bundle.build()\n main_js_bundle.build()\n vendor_js_bundle.build()\n","sub_path":"application/assets.py","file_name":"assets.py","file_ext":"py","file_size_in_byte":1051,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"507915238","text":"import sys\r\n\r\nimport torch\r\nfrom pytorch_transformers import *\r\n\r\nfrom research.document_processor import PrepareInputForSentenceEncoder\r\nfrom research.libnlp.Document import Document\r\n\r\n\r\nclass SentenceEncoder:\r\n MODELS = [(BertModel, BertTokenizer, 'bert-base-uncased'),\r\n (OpenAIGPTModel, OpenAIGPTTokenizer, 'openai-gpt'),\r\n (GPT2Model, GPT2Tokenizer, 'gpt2'),\r\n (TransfoXLModel, TransfoXLTokenizer, 'transfo-xl-wt103'),\r\n (XLNetModel, XLNetTokenizer, 'xlnet-base-cased'),\r\n (XLMModel, XLMTokenizer, 'xlm-mlm-enfr-1024')]\r\n\r\n def __init__(self, model_type, task_type, logger, max_len):\r\n self.model_type = model_type # indicates which sentence encoder you want to use\r\n self.task_type = task_type # indicates which type of classification task you are performing\r\n self.max_len = max_len\r\n model, tokenizer, pretrained_weights = self.validate_model(model_type, logger)\r\n self.model = model.from_pretrained(pretrained_weights)\r\n self.tokenizer = tokenizer.from_pretrained(pretrained_weights)\r\n self.logger = logger\r\n\r\n def validate_model(self, type, logger):\r\n if type > len(self.MODELS):\r\n logger.error(\"Incorrect model-tokenizer-pretrained_weights combination\")\r\n sys.exit()\r\n else:\r\n return self.MODELS[type]\r\n\r\n def get_embedding(self, d, take_hypernyms):\r\n input_ids, position_vect1, position_vect2 = PrepareInputForSentenceEncoder.convert_to_input(d, self.model_type, self.task_type, self.tokenizer,\r\n self.max_len, take_hypernyms, add_positional_features=True)\r\n with torch.no_grad():\r\n d.linkTokenIDs([input_ids, position_vect1, position_vect2])\r\n self.logger.info(\"Document \" + str(d.doc_id) + \" encoded \")\r\n return d\r\n\r\n def encode_text(self, document, take_hypernyms = True):\r\n if isinstance(document, Document):\r\n document = self.get_embedding(document, take_hypernyms)\r\n if isinstance(document, dict):\r\n for idx in document.keys():\r\n document[idx] = self.get_embedding(document[idx], take_hypernyms)\r\n return document\r\n","sub_path":"research/document_processor/SentenceEncoder.py","file_name":"SentenceEncoder.py","file_ext":"py","file_size_in_byte":2280,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"46143170","text":"\"\"\"\nWork token for SQS based job control\n\"\"\"\nfrom typing import Optional\nfrom datetime import timedelta, datetime\nimport toolz\nfrom .model import WorkTokenInterface\n\n\nclass SQSWorkToken(WorkTokenInterface):\n def __init__(self, msg, timeout: int, t0: Optional[datetime] = None):\n if t0 is None:\n t0 = self.now()\n self._msg = msg\n self._t0 = t0\n self._deadline = t0 + timedelta(seconds=timeout)\n\n @property\n def start_time(self) -> datetime:\n \"\"\"\n Timestamp when SQS message was received\n \"\"\"\n return self._t0\n\n @property\n def deadline(self) -> datetime:\n \"\"\"\n Should return timestamp by which work is to be completed\n \"\"\"\n return self._deadline\n\n def done(self):\n \"\"\"\n Called when work is completed successfully\n \"\"\"\n if self._msg is not None:\n self._msg.delete()\n self._msg = None\n\n def cancel(self):\n \"\"\"\n Called when work is terminated for whatever reason without successful result\n \"\"\"\n if self._msg is None:\n return\n\n self._msg.change_visibility(VisibilityTimeout=0)\n self._msg = None\n\n def extend(self, seconds: int) -> bool:\n \"\"\"\n Called to extend work deadline\n \"\"\"\n if self._msg is None:\n return False\n\n new_deadline = self.now() + timedelta(seconds=seconds)\n\n rr = self._msg.change_visibility(VisibilityTimeout=seconds)\n ok = toolz.get_in([\"ResponseMetadata\", \"HTTPStatusCode\"], rr, default=-1) == 200\n\n if ok:\n self._deadline = new_deadline\n\n return ok\n","sub_path":"libs/stats/odc/stats/_sqs.py","file_name":"_sqs.py","file_ext":"py","file_size_in_byte":1670,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"191567968","text":"import numpy as np\nimport pickle as pkl\nimport networkx as nx\nimport scipy.sparse as sp\nfrom scipy import sparse\nfrom scipy.sparse.linalg.eigen.arpack import eigsh\nimport sys\nimport numpy as np\nimport pandas as pd\n\n\nfrom os import listdir\nfrom os.path import isfile, join\n\ndef sample_mask(idx, l):\n \"\"\"Create mask.\"\"\"\n mask = np.zeros(l)\n mask[idx] = 1\n return np.array(mask, dtype=np.bool)\n\ndef sparse_to_tuple(sparse_mx):\n \"\"\"Convert sparse matrix to tuple representation.\"\"\"\n def to_tuple(mx):\n if not sp.isspmatrix_coo(mx):\n mx = mx.tocoo()\n coords = np.vstack((mx.row, mx.col)).transpose()\n values = mx.data\n shape = mx.shape\n return coords, values, shape\n\n if isinstance(sparse_mx, list):\n for i in range(len(sparse_mx)):\n sparse_mx[i] = to_tuple(sparse_mx[i])\n else:\n sparse_mx = to_tuple(sparse_mx)\n\n return sparse_mx\n\n\ndef preprocess_features(features):\n \"\"\"Row-normalize feature matrix and convert to tuple representation\"\"\"\n from sklearn.preprocessing import normalize\n features = normalize(features, norm='l1', axis=1)\n return sparse_to_tuple(features)\n\n\ndef normalize_adj(adj):\n \"\"\"Symmetrically normalize adjacency matrix.\"\"\"\n adj = sp.coo_matrix(adj)\n rowsum = np.array(adj.sum(1))\n d_inv_sqrt = np.power(rowsum, -0.5).flatten()\n d_inv_sqrt[np.isinf(d_inv_sqrt)] = 0.\n d_mat_inv_sqrt = sp.diags(d_inv_sqrt)\n return adj.dot(d_mat_inv_sqrt).transpose().dot(d_mat_inv_sqrt).tocoo()\n\n\ndef preprocess_adj(adj):\n \"\"\"Preprocessing of adjacency matrix for simple GCN model and conversion to tuple representation.\"\"\"\n adj_normalized = normalize_adj(adj + sp.eye(adj.shape[0]))\n return sparse_to_tuple(adj_normalized)\n\n\ndef construct_feed_dict(features, support, labels, labels_mask, placeholders):\n \"\"\"Construct feed dictionary.\"\"\"\n feed_dict = dict()\n feed_dict.update({placeholders['labels']: labels})\n feed_dict.update({placeholders['labels_mask']: labels_mask})\n feed_dict.update({placeholders['features']: features})\n feed_dict.update({placeholders['support'][i]: support[i] for i in range(len(support))})\n feed_dict.update({placeholders['num_features_nonzero']: features[1].shape})\n return feed_dict\n\n\ndef chebyshev_polynomials(adj, k):\n \"\"\"Calculate Chebyshev polynomials up to order k. Return a list of sparse matrices (tuple representation).\"\"\"\n print(\"Calculating Chebyshev polynomials up to order {}...\".format(k))\n\n adj_normalized = normalize_adj(adj)\n laplacian = sp.eye(adj.shape[0]) - adj_normalized\n largest_eigval, _ = eigsh(laplacian, 1, which='LM')\n scaled_laplacian = (2. / largest_eigval[0]) * laplacian - sp.eye(adj.shape[0])\n\n t_k = list()\n t_k.append(sp.eye(adj.shape[0]))\n t_k.append(scaled_laplacian)\n\n def chebyshev_recurrence(t_k_minus_one, t_k_minus_two, scaled_lap):\n s_lap = sp.csr_matrix(scaled_lap, copy=True)\n return 2 * s_lap.dot(t_k_minus_one) - t_k_minus_two\n\n for i in range(2, k+1):\n t_k.append(chebyshev_recurrence(t_k[-1], t_k[-2], scaled_laplacian))\n\n return sparse_to_tuple(t_k)\n\ndef encode_onehot(labels):\n classes = sorted(list(set(labels)))\n classes_dict = {c: np.identity(len(classes))[i, :] for i, c in enumerate(classes)}\n labels_onehot = np.array(list(map(classes_dict.get, labels)), dtype=np.int32)\n \n return labels_onehot\n\ndef build_mst(X):\n from sklearn.metrics.pairwise import euclidean_distances\n from scipy.sparse.csgraph import minimum_spanning_tree\n \"\"\"\n \"\"\"\n D = euclidean_distances(X, X)\n adj_directed = minimum_spanning_tree(D).toarray()\n adj = adj_directed + adj_directed.T\n adj[adj > 0] = 1\n np.fill_diagonal(adj,0)\n\n return sparse.csr_matrix(adj)\n\ndef load_data(dataset,case):\n \"\"\"Load citation network dataset\"\"\"\n print('Loading {} dataset...'.format(dataset))\n\n idx_features_labels = np.genfromtxt(\"./data/{}/{}.content\".format(dataset,dataset), dtype=np.dtype(str))\n features = sp.csr_matrix(idx_features_labels[:, 1:-1], dtype=np.float32)\n labels = encode_onehot(idx_features_labels[:, -1])\n\n # build graph\n idx = np.array(idx_features_labels[:, 0], dtype=np.int32)\n idx_map = {j: i for i, j in enumerate(idx)}\n if case == \"knn\":\n sparsity_parameters_knn_k ={\n \"constructive\": 9,\n \"cora\":12,\n \"aminer\":12,\n \"digits\":6,\n \"fma\":1,\n \"cell\":3,\n \"segmentation\":7,\n }\n edges_unordered = np.genfromtxt(\"./data/{}/{}_{}_k_{}.cites\".format(dataset,dataset,case,sparsity_parameters_knn_k[dataset]), dtype=np.int32)\n if case == \"mknn\":\n sparsity_parameters_mknn_k ={\n \"constructive\": 104,\n \"cora\":39,\n \"aminer\":171,\n \"digits\":39,\n \"fma\":1,\n \"cell\":7,\n \"segmentation\":17,\n }\n edges_unordered = np.genfromtxt(\"./data/{}/{}_{}_k_{}.cites\".format(dataset,dataset,case,sparsity_parameters_mknn_k[dataset]), dtype=np.int32)\n if case == \"cknn\":\n sparsity_parameters_cknn_k ={\n \"constructive\": 29,\n \"cora\":74,\n \"aminer\":199,\n \"digits\":33,\n \"fma\":13,\n \"cell\":35,\n \"segmentation\":5,\n }\n edges_unordered = np.genfromtxt(\"./data/{}/{}_{}_delta_1_k_{}.cites\".format(dataset,dataset,case,sparsity_parameters_cknn_k[dataset]), dtype=np.int32)\n if case == \"rmst\":\n sparsity_parameters_rmst_gamma ={\n \"constructive\": 0.07421,\n \"cora\":0.02924,\n \"aminer\":0.02317,\n \"digits\":0.00296,\n \"fma\":0.01435,\n \"cell\":0.00159,\n \"segmentation\":0.03423,\n }\n edges_unordered = np.genfromtxt(\"./data/{}/{}_{}_gamma_{}_k_1.cites\".format(dataset,dataset,case,sparsity_parameters_rmst_gamma[dataset]), dtype=np.int32)\n \n # Spielman sparsification from dense CkNN\n if case == \"sssa\":\n sparsity_parameters_sssa_dense_sigma = {\n \"constructive\":0.2293,\n \"cora\":0.3401,\n \"aminer\":0.2216,\n \"digits\":0.2229,\n \"fma\":0.3816,\n \"cell\":0.7806,\n \"segmentation\":0.7003,\n }\n sparsity_parameters_cknn_k = {\n \"constructive\":120,\n \"cora\":266,\n \"aminer\":509,\n \"digits\":286,\n \"fma\":56,\n \"cell\":48,\n \"segmentation\":52,\n }\n edges_unordered = np.genfromtxt(\"./data/{}/{}_{}_epsilon_{:.4f}_cknn_delta_1_k_{}_mst.cites\".format(dataset,dataset,case,sparsity_parameters_sssa_dense_sigma[dataset],sparsity_parameters_cknn_k[dataset]), dtype=np.int32)\n\n # Spielman sparsification from optimal CkNN\n if case == \"sssa_optimalCkNN\":\n sparsity_parameters_sssa_optimal_sigma = {\n \"constructive\":0.2491,\n # \"cora\":,\n \"aminer\":0.1618,\n \"digits\":0.1034,\n # \"fma\":,\n \"cell\":0.7407,\n # \"segmentation\":,\n }\n sparsity_parameters_cknn_k ={\n \"constructive\": 29,\n \"cora\":74,\n \"aminer\":199,\n \"digits\":33,\n \"fma\":13,\n \"cell\":35,\n \"segmentation\":5,\n }\n if dataset not in [\"cora\",\"digits\",\"segmentation\"]:\n edges_unordered = np.genfromtxt(\"./data/{}/{}_{}_epsilon_{:.4f}_cknn_delta_1_k_{}_mst.cites\".format(dataset,dataset,case,sparsity_parameters_sssa_optimal_sigma[dataset],sparsity_parameters_cknn_k[dataset]), dtype=np.int32)\n else:\n case = \"cknn\"\n edges_unordered = np.genfromtxt(\"./data/{}/{}_{}_delta_1_k_{}.cites\".format(dataset,dataset,case,sparsity_parameters_cknn_k[dataset]), dtype=np.int32) \n \n edges = np.array(list(map(idx_map.get, edges_unordered.flatten())),\n dtype=np.int32).reshape(edges_unordered.shape)\n\n adj = sp.coo_matrix((np.ones(edges.shape[0]), (edges[:, 0], edges[:, 1])),\n shape=(labels.shape[0], labels.shape[0]), dtype=np.float32)\n\n # build symmetric adjacency matrix\n adj = adj + adj.T.multiply(adj.T > adj) - adj.multiply(adj.T > adj)\n\n # print('Dataset has {} nodes, {} edges, {} features.'.format(adj.shape[0], edges.shape[0], features.shape[1]))\n\n if case in [\"knn\",\"mknn\",\"cknn\"]:\n print(\"Adding mst graph\")\n from sklearn import preprocessing\n adj_mst = build_mst(preprocessing.normalize(features.toarray(), norm='l1', axis=1))\n adj = adj + adj_mst\n adj[adj > 0] = 1\n\n print('Dataset has {} nodes, {} edges, {} features.'.format(adj.shape[0], edges.shape[0], features.shape[1]))\n\n return features.tolil(), adj, labels\n\ndef get_splits(y, dataset):\n if dataset == \"constructive\":\n idx_train = range(50)\n idx_val = range(50, 150)\n idx_test = range(150, 1000)\n elif dataset == \"cora\":\n idx_train = range(119)\n idx_val = range(119, 372)\n idx_test = range(372, 2485)\n elif dataset == \"aminer\":\n idx_train = range(98)\n idx_val = range(98, 310)\n idx_test = range(310, 2072)\n elif dataset == \"digits\":\n idx_train = range(80)\n idx_val = range(80, 269)\n idx_test = range(269, 1797)\n elif dataset == \"fma\":\n idx_train = range(96)\n idx_val = range(96, 300)\n idx_test = range(300, 2000)\n elif dataset == \"cell\":\n idx_train = range(100)\n idx_val = range(100, 300)\n idx_test = range(300, 2000)\n elif dataset == \"cell_b\":\n idx_train = range(100)\n idx_val = range(100, 300)\n idx_test = range(300, 2000)\n elif dataset == \"segmentation\":\n idx_train = range(112)\n idx_val = range(112, 346)\n idx_test = range(346, 2310)\n y_train = np.zeros(y.shape, dtype=np.int32)\n y_val = np.zeros(y.shape, dtype=np.int32)\n y_test = np.zeros(y.shape, dtype=np.int32)\n y_train[idx_train] = y[idx_train]\n y_val[idx_val] = y[idx_val]\n y_test[idx_test] = y[idx_test]\n train_mask = sample_mask(idx_train, y.shape[0])\n val_mask = sample_mask(idx_val, y.shape[0])\n test_mask = sample_mask(idx_test, y.shape[0])\n\n return y_train, y_val, y_test, train_mask, val_mask, test_mask, idx_train, idx_val, idx_test","sub_path":"GCN_with_RBS/build/lib/gcn/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":10352,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"125204567","text":"from face_alignment.utils import transform\nfrom numpy.core.fromnumeric import size\nfrom scipy.ndimage.measurements import label\nfrom torch.utils.data import DataLoader, Dataset, random_split\nimport pandas as pd\nimport numpy as np\nimport skimage.io as sio\nfrom skimage.color import gray2rgb\nfrom torchvision import transforms\nfrom scipy.stats import stats\nimport torch\nimport os\nfrom torchvision.transforms.functional import scale\n\nfrom torchvision.transforms.transforms import RandomResizedCrop, RandomRotation\nimport config\n\ntorch.manual_seed(63)\n\ndef contrast_strech(img):\n imgori=img.copy()\n img=img.astype(np.float32)\n\n imgs = img.flatten()\n\n z = np.abs(stats.zscore(imgs))\n threshold = 2.5\n\n imgs = imgs[np.where(z <= threshold)]\n norm_v=(np.max(imgs) - np.min(imgs))\n if norm_v>0:\n imgnew = (img - np.min(imgs)) / norm_v\n #print (np.min(imgnew),np.max(imgnew))\n imgnew[imgnew <=0] = 0\n imgnew[imgnew >= 1] = 1\n imgnew=imgnew * 255\n else:\n imgnew=imgori\n imgnew=np.asarray(imgnew,dtype=np.uint8)\n return imgnew\n\nTRAIN_TRANSFORMS_EFF = transforms.Compose(\n [\n transforms.Resize((768,768)), #B0->224 B1->240 B2->260 B3->300 B4->380 B5->456 B6->528 B7->600\n transforms.RandomHorizontalFlip(0.5),\n transforms.RandomVerticalFlip(0.5),\n transforms.RandomRotation(degrees=(0,15)),\n #resize(250,250)->scale(0.8-1.2)->crop(224,224)\n #contrast norm\n #rotation, blur(smoothing), scale(0.8-1.2)\n transforms.ToTensor(),\n transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]), \n ]\n)\n\nEVALUATION_TRANSFORMS_EFF = transforms.Compose(\n [\n transforms.Resize((768,768)),\n transforms.ToTensor(),\n transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]), \n ]\n)\n\nclass ISBIDataset(Dataset):\n def __init__(self, csv_path, img_path, testing=False, reweight=True) -> None:\n super().__init__()\n\n self.df = pd.read_csv(csv_path, header=0)\n self.img_path = img_path\n self.preprocess = EVALUATION_TRANSFORMS_EFF if testing else TRAIN_TRANSFORMS_EFF\n self.testing = testing\n self.reweight = reweight\n self.weight = self.weightCalculation()\n \n def __getitem__(self, index):\n img_id = self.df.iloc[index][0]\n path = os.path.join(self.img_path, str(img_id) + \".png\")\n input_image = sio.imread(path) \n #input_image = contrast_strech(input_image)\n if input_image.shape[1] == 4288:\n input_image = transforms.ToPILImage()(input_image)\n input_image = transforms.functional.affine(input_image, angle=.0, scale=1,shear=0,translate = [175,0])\n input_image = transforms.CenterCrop(3423)(input_image) #((2848, 3423))\n input_tensor = self.preprocess(input_image)\n elif input_image.shape[1] == 2144:\n input_image = transforms.ToPILImage()(input_image)\n input_image = transforms.CenterCrop(1424)(input_image)\n input_tensor = self.preprocess(input_image)\n else:\n input_image = transforms.ToPILImage()(input_image)\n input_image = transforms.CenterCrop(1536)(input_image)\n input_tensor = self.preprocess(input_image)\n \n label = self.df.iloc[index][1:].to_list()\n label = torch.tensor(label).long()\n if len(label)>29:\n label = torch.cat((label[0:28],torch.tensor([1])),0) if label[28:].sum()>0 else torch.cat((label[0:28],torch.tensor([0])),0)\n ### inverse ###\n #label[0] = 1-label[0]\n if self.reweight: \n if self.testing:\n return input_tensor, label, 1\n else:\n return input_tensor, label, self.getWeight(label)\n else:\n return input_tensor, label\n \n def __len__(self):\n return len(self.df)\n \n def weightCalculation(self):\n data = self.df.values[:,1:]\n c = np.zeros((data.shape[1],))\n for i in data[:]:\n for j in range(i.shape[0]):\n if i[j]==1:\n c[j]+=1\n c[0] = data.shape[0] - c[0]\n w = np.zeros_like(c)\n for i in range(w.shape[0]):\n w[i] = np.sum(c)/c[i]\n w = w/np.min(w)\n return w\n \n def getWeight(self, label):\n weight = 0\n count = 0\n for i, n in enumerate(label):\n if n==1:\n weight += self.weight[i]\n count += 1\n if count ==0:\n return self.weight[0]\n else:\n return weight/count\n ","sub_path":"EffNet_dataset.py","file_name":"EffNet_dataset.py","file_ext":"py","file_size_in_byte":4657,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"78398452","text":"# %load q04_read_csv_data_to_ndarray/build.py\n# Default Imports\nimport numpy as np\nfrom inspect import getfullargspec\npath = './data/ipl_matches_small.csv'\n\n# Enter code here\ndtype='|S100'\ndef read_csv_data_to_ndarray(path, dtype):\n data = np.genfromtxt(path, dtype, skip_header=1, delimiter=',')\n return data\n\nread_csv_data_to_ndarray(path,dtype)\n\n","sub_path":"q04_read_csv_data_to_ndarray/build.py","file_name":"build.py","file_ext":"py","file_size_in_byte":355,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"454187099","text":"import json\nimport sys\n\nfrom pycorenlp import StanfordCoreNLP\n\nfile_name = sys.argv[1]\n\nnlp = StanfordCoreNLP('http://localhost:9000')\n\nwith open(file_name) as f:\n data = json.load(f)\n\ndef filter_pos(sent):\n sent = str(sent)\n num_verbs = 0\n num_adverbs = 0\n num_adj = 0\n num_nouns = 0\n pos_sent = nlp.annotate(sent, properties={'annotators': 'tokenize,ssplit,pos','outputFormat': 'json', 'ner.model': 'edu/stanford/nlp/models/ner/english.conll.4class.distsim.crf.ser.gz'})\n for sentence in pos_sent['sentences']:\n for token in sentence['tokens']:\n if token[\"pos\"] in [\"NN\", \"NNS\", \"NNP\", \"NNPS\"]:\n num_nouns += 1\n elif token[\"pos\"] in [\"VB\", \"VBD\", \"VBG\", \"VBN\", \"VBP\", \"VBZ\"]:\n num_verbs += 1\n elif token[\"pos\"] in [\"JJ\", \"JJR\", \"JJS\"]:\n num_adj += 1\n elif token[\"pos\"] in [\"RB\", \"RBR\", \"RBS\"]:\n num_adverbs += 1\n cnt = num_adj + num_adverbs\n return cnt\n\nbleu = 0\nsari = 0\ncnt = 0\ni = 0\nfor item in data:\n print(str(i) + \" / \" + str(len(data)))\n i += 1\n centers = item['centers']\n candidates = []\n for k,v in item['candidates'].iteritems():\n idx = int(k)\n center = centers[idx][0]\n temp = []\n for c in v:\n if c['original_rank'] == center:\n temp.append(c)\n break\n candidates.extend(temp)\n\n # new_candidates = []\n # for c in candidates:\n # sent = c['sent']\n # num_verbs = 0\n # num_adverbs = 0\n # num_adj = 0\n # num_nouns = 0\n # pos_sent = nlp.annotate(sent, properties={'annotators': 'tokenize,ssplit,pos','outputFormat': 'json', 'ner.model': 'edu/stanford/nlp/models/ner/english.conll.4class.distsim.crf.ser.gz'})\n # for sentence in pos_sent['sentences']:\n # for token in sentence['tokens']:\n # if token[\"pos\"] in [\"NN\", \"NNS\", \"NNP\", \"NNPS\"]:\n # num_nouns += 1\n # elif token[\"pos\"] in [\"VB\", \"VBD\", \"VBG\", \"VBN\", \"VBP\", \"VBZ\"]:\n # num_verbs += 1\n # elif token[\"pos\"] in [\"JJ\", \"JJR\", \"JJS\"]:\n # num_adj += 1\n # elif token[\"pos\"] in [\"RB\", \"RBR\", \"RBS\"]:\n # num_adverbs += 1\n # c['num_verbs'] = num_verbs\n # c['num_nouns'] = num_nouns\n # c['num_adj'] = num_adj\n # c['num_adverbs'] = num_adverbs\n # new_candidates.append(c)\n\n c = min(candidates, key=lambda item: filter_pos(item['val']['sent']))\n bleu += c['val']['bleu']\n sari += c['val']['sari']\n cnt += 1\n\nprint(float(bleu) / float(cnt))\nprint(float(sari) / float(cnt))\n","sub_path":"evaluate_cluster_lstm_ppl_adv_adj_new.py","file_name":"evaluate_cluster_lstm_ppl_adv_adj_new.py","file_ext":"py","file_size_in_byte":2703,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"430207980","text":"from django.shortcuts import render, redirect\nfrom .models import Contract\nfrom assists.models import Assistance\nfrom projects.models import Project\nfrom .forms import AddContractForm\nfrom django.db.models import Sum, Max\nfrom contracts.forms import ContractForm\nfrom vanilla import CreateView, UpdateView, DeleteView, ListView\nfrom django.core.urlresolvers import reverse_lazy\n\n\n# Create your views here.\nclass ContractList(ListView):\n model = Contract\n\nclass ContractCreate(CreateView):\n model = Contract\n form_class = ContractForm\n template_name = \"contracts/add_contract.html\"\n success_url = reverse_lazy('contract-list')\n\nclass ContractUpdate(UpdateView):\n model = Contract\n form_class = ContractForm\n template_name = \"contracts/add_contract.html\"\n success_url = reverse_lazy('contract-list')\n\nclass ContractDelete(DeleteView):\n model = Contract\n success_url = reverse_lazy('contract-list')\n\ndef contracts_list(request):\n contracts = Contract.objects.all()\n assist_id = request.GET.get('assist')\n\n if assist_id is not None:\n try:\n a = Assistance.objects.get(id=assist_id)\n except Assistance.DoesNotExist:\n a = None\n\n contracts = Contract.objects.filter(assistance__exact=a)\n context = {\n \"contracts\":contracts,\n }\n return render(request, \"contracts/contracts_list.html\", context)\n\ndef contract_details(request, id):\n contract = Contract.objects.get(id=id)\n spent = contract.factor_set.aggregate(sum=Sum('cost'))['sum']\n context = {\n \"contract\":contract,\n \"spent\":spent,\n\n }\n return render(request, \"contracts/contract_details.html\", context)\n\ndef add_contract(request):\n form = AddContractForm(request.POST or None)\n form_flag = form.is_valid()\n ps = Project.objects.all()\n assists = Assistance.objects.all().order_by('name')\n if form_flag:\n assistance_id = form.cleaned_data['assistance']\n project_id = form.cleaned_data['project']\n assist = Assistance.objects.get(id=assistance_id)\n project = Project.objects.get(id=project_id)\n verified = False\n if(form.cleaned_data['contract_number']):\n verified = True\n c = Contract(name=form.cleaned_data['name'], cost=form.cleaned_data['cost'], verified=form.cleaned_data['verified'],\n assistance=assist, project=project, contract_number=form.cleaned_data['contract_number'])\n c.save(force_insert=True)\n '''Contract.objects.create(name=form.cleaned_data['name'], cost=form.cleaned_data['cost'], veri fied=form.cleaned_data['verified'],\n assistance=assist, project=project)'''\n return redirect(contracts_list)\n else:\n context = {\n \"form\":form,\n \"assists\":assists,\n }\n return render(request, \"contracts/add_contract.html\", context)\n\ndef edit_contract(request, id):\n c = Contract.objects.get(id=id)\n data = {\n 'name': c.name,\n 'cost': c.cost,\n 'verified': c.verified,\n 'assistance': c.assistance.id,\n 'project': c.project.id,\n 'contract_number': c.contract_number\n }\n form = AddContractForm(request.POST or data)\n form_flag = form.is_valid()\n if form_flag:\n assistance = Assistance.objects.get(id=form.cleaned_data['assistance'])\n project = Project.objects.get(id=form.cleaned_data['project'])\n c.assistance = assistance\n c.project = project\n c.cost = form.cleaned_data['cost']\n c.name = form.cleaned_data['name']\n verified = False\n if(form.cleaned_data['contract_number']):\n verified = True\n c.verified = verified\n c.contract_number = form.cleaned_data['contract_number']\n c.save()\n\n return redirect(contract_details, id=id)\n\n else:\n context = {\n \"form\":form,\n \"c\":c,\n }\n return render(request, \"contracts/edit_contract.html\", context)\n","sub_path":"contracts/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":4007,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"570859329","text":"#!/usr/bin/python3\n# -*- coding: utf-8 -*-\n\n\"\"\"Desktop GUI for ``table_validator``.\n\nAuthor: Wolfgang Müller\nThe initial starting point was taken from zetcode\nHowever, there are only few lines that survived changes.\n\n-\nZetCode PyQt5 tutorial\n\nThis is a simple drag and\ndrop example.\n\nAuthor: Jan Bodnar\nWebsite: zetcode.com\nLast edited: August 2017\n\nhttp://zetcode.com/gui/pyqt5/dragdrop/\n\"\"\"\n\nimport logging\nimport sys\nimport urllib.request\nfrom typing import Type\n\nimport click\nfrom PyQt5.QtCore import QPropertyAnimation, QRect, Qt,QItemSelection,QItemSelectionModel,QModelIndex\nfrom PyQt5.QtWidgets import QApplication, QLabel, QVBoxLayout, QGridLayout, QWidget\nfrom PyQt5.QtGui import QBrush\nfrom .candidate_table import CandidateTableWidget, CandidateTableModel\nfrom .full_candidate_table import FullCandidateTableWidget, FullCandidateTableModel\n\nimport table_validator\nfrom PyQt5.Qt import QEvent, QPushButton\n\nlogger = logging.getLogger(__name__)\n\n__all__ = [\n 'ValidationDropTarget',\n 'main',\n]\n\n\nclass ValidationOverview(QWidget):\n \"\"\"A Qt window showing the file and error messages\"\"\"\n\n def __init__(self, app, candidate, new_table_data, errors_encountered):\n # self.label_url = 0\n super().__init__()\n\n self.errors_encountered = errors_encountered\n # init tables\n self.full_candidate_table_widget = FullCandidateTableWidget()\n self.candidate_table_widget = CandidateTableWidget()\n self.candidate_table_widget.table_view.selectRow(0)\n self.full_candidate_table_widget.model.load_data(candidate)\n self.candidate_table_widget.model.load_data(new_table_data)\n self.close_button = QPushButton(\"close window\")\n self.close_button.clicked.connect(self.closeWindow)\n\n # init window\n self.app = app\n desktop = app.desktop()\n geometry = desktop.availableGeometry()\n self.top = geometry.top()\n self.left = geometry.left()\n self.initUI()\n self._big_geometry()\n\n def closeWindow(self):\n self.destroy()\n\n def _big_geometry(self):\n self.setFixedSize(self.GEOMETRY_W, self.GEOMETRY_H)\n\n def view_clicked(self, clicked_index):\n print(\"clicked:\",clicked_index.row())\n\n #self.full_candidate_table_widget.table_view.selectRow(clicked_index.row())\n\n model = self.full_candidate_table_widget.table_view.selectionModel()\n #print(\"------\");\n #print(dir(self.full_candidate_table_widget.table_view.model()))\n #print(\"------\");\n #print(self.full_candidate_table_widget.table_view.model())\n #print(\"------\");\n\n (row, col) = self.errors_encountered[clicked_index.row()].get_location()\n\n index = self.full_candidate_table_widget.table_view.model().index(row,col)\n model.select(QItemSelection(index,index),QItemSelectionModel.Select | QItemSelectionModel.Clear)\n\n # initUI\n def initUI(self):\n\n self.GEOMETRY_W = 800\n self.GEOMETRY_H = 600\n self.GEOMETRY_X = 10\n self.GEOMETRY_Y = 10 \n\n self.setWindowFlags(Qt.WindowStaysOnTopHint | Qt.FramelessWindowHint)\n\n vbox = QGridLayout()\n\n vbox.addWidget(self.full_candidate_table_widget,0,0)\n vbox.addWidget(self.candidate_table_widget,1,0)\n vbox.addWidget(self.close_button,2,0)\n\n self.bottom = self.app.desktop().availableGeometry().bottom()\n total_height = self.bottom * 0.8\n content_height = total_height * 0.6\n\n vbox.setRowMinimumHeight(0,content_height)\n\n self.setLayout(vbox)\n\n self.setWindowTitle('INCOME table Validation result')\n\n # connect to line\n self.candidate_table_widget.defineTableClickedListener(self.view_clicked)\n\n\nclass ValidationDropTarget(QWidget):\n \"\"\"A Qt app that is a drop target and validates the file dropped.\"\"\"\n\n def __init__(self, app, validate):\n \n self.__change_size=False\n \n self.errors_encountered = []\n self.label_url = QLabel()\n self.label_success = QLabel()\n self.label_instructions = QLabel()\n self.close_button = QPushButton(\"close application\")\n self.close_button.clicked.connect(self.destroy)\n\n # self.label_url = 0\n super().__init__()\n\n self.app = app\n desktop = app.desktop()\n geometry = desktop.availableGeometry()\n self.bottom = geometry.bottom()\n self.right = geometry.right()\n self.setAcceptDrops(True)\n self.initUI()\n\n self.validate = validate\n \n self.validation_overview_window=None\n\n # taken from\n # https://www.iana.org/assignments/media-types/media-types.txt\n self.accepted_formats = ['text/uri-list']\n\n def _big_geometry(self):\n if (self.x() < self.GEOMETRY_X) and (self.y() < self.GEOMETRY_Y):\n return\n\n self.animation = QPropertyAnimation(self, b\"geometry\")\n self.animation.setDuration(self.GEOMETRY_ANIMATION_TIME)\n self.animation.setStartValue(QRect(self.GEOMETRY_X, self.GEOMETRY_Y, self.GEOMETRY_W, self.GEOMETRY_H))\n self.animation.setEndValue(QRect(self.GEOMETRY_BIG_X, self.GEOMETRY_BIG_Y, self.GEOMETRY_BIG_W, self.GEOMETRY_BIG_H))\n self.animation.start()\n self.setFixedSize(self.GEOMETRY_BIG_W, self.GEOMETRY_BIG_H)\n\n\n def _small_geometry(self):\n if (self.x() == self.GEOMETRY_X) and (self.y() == self.GEOMETRY_Y):\n return\n\n self.animation = QPropertyAnimation(self, b\"geometry\")\n self.animation.setDuration(self.GEOMETRY_ANIMATION_TIME)\n self.animation.setStartValue(QRect(self.GEOMETRY_BIG_X, self.GEOMETRY_BIG_Y, self.GEOMETRY_BIG_W, self.GEOMETRY_BIG_H))\n self.animation.setEndValue(QRect(self.GEOMETRY_X, self.GEOMETRY_Y, self.GEOMETRY_W, self.GEOMETRY_H))\n self.animation.start()\n self.setFixedSize(self.GEOMETRY_BIG_W, self.GEOMETRY_BIG_H)\n\n @staticmethod\n def preprocess_response(data):\n return table_validator.parse_tsv(data.split(\"\\n\"))\n\n def dropEvent(self, e): # noqa: N802\n \"\"\"Handle file drop events.\"\"\"\n logger.debug(\"Dropped!\")\n \n urls = e.mimeData().urls()\n response = urllib.request.urlopen(urls[0].toString()) # noqa:S310\n data = response.read().decode(\"UTF-8\")\n candidate = self.preprocess_response(data)\n\n\n logger.debug(\"Candidate %s\", candidate)\n\n self.label_url.setText(\"File examined: %s\" % urls[0].toString())\n\n successfullyValidated,errorObjects = self.validate(candidate)\n\n self.errors_encountered = errorObjects;\n new_table_data=[]\n for i in errorObjects:\n # object is SheetError\n print(i.get_formatted_full_error_message())\n new_table_data.append(i)\n\n\n self.label_instructions.hide()\n if successfullyValidated:\n self.label_success.setText(\n ''\n 'Validation succeeded!'\n ''\n )\n else:\n self.label_success.setText(\n ''\n \"\"\"\n Validation failed. Please browse errors using the error list.\n The locations of the error occurrences will be marked.\n \"\"\"\n ''\n )\n \n # create/update overview table\n self.validation_overview_window = ValidationOverview(self.app, candidate, new_table_data, self.errors_encountered)\n self.validation_overview_window.show()\n\n logger.debug(\"dropped %s\", urls)\n # self._small_geometry()\n\n def is_accepted(self, e):\n \"\"\"Check a file based on its MIME type.\"\"\"\n accept = any(\n e.mimeData().hasFormat(i)\n for i in self.accepted_formats\n )\n\n if accept:\n e.accept()\n return True\n else:\n e.ignore()\n\n return False\n\n def enterEvent(self, e):\n if self.__change_size:\n self._big_geometry()\n\n def leaveEvent(self, e):\n if self.__change_size:\n self._small_geometry()\n\n def dragEnterEvent(self, e): # noqa: N802\n \"\"\"Decide if you can drop a given type of file in the drop zone.\"\"\"\n if self.__change_size:\n self._big_geometry()\n\n logger.debug(\"enter\")\n logger.debug(\"URLs: %s\", e.mimeData().urls())\n\n if self.is_accepted(e):\n logger.debug(\"Accepted\")\n else:\n logger.debug(\"failed %s\", e.mimeData().formats())\n\n # initUI\n def initUI(self):\n\n self.GEOMETRY_W = 30\n self.GEOMETRY_H = 30\n self.GEOMETRY_X = self.right - self.GEOMETRY_W\n self.GEOMETRY_Y = self.bottom - self.GEOMETRY_H\n self.GEOMETRY_BIG_W = 400\n self.GEOMETRY_BIG_H = 300\n self.GEOMETRY_BIG_X = self.right - self.GEOMETRY_BIG_W\n self.GEOMETRY_BIG_Y = self.bottom - self.GEOMETRY_BIG_H\n self.GEOMETRY_ANIMATION_TIME = 0\n\n self.setWindowFlags(Qt.WindowStaysOnTopHint | Qt.FramelessWindowHint)\n self._small_geometry()\n # https://stackoverflow.com/questions/18975734/how-can-i-find-the-screen-desktop-size-in-qt-so-i-can-display-a-desktop-notific\n\n self.label_url.setAlignment(Qt.AlignLeft)\n self.label_url.setWordWrap(True)\n self.label_url.setText(\"Drop your files here:\")\n\n self.label_success.setAlignment(Qt.AlignLeft)\n self.label_success.setText('I did not yet analyze any file')\n\n self.label_instructions.setAlignment(Qt.AlignLeft)\n self.label_instructions.setWordWrap(True)\n self.label_instructions.setText(\"\"\"\n

\n Are you asking yourself if your tabular data file is really matching\n the template you agreed on with your collaboration partners?\n

\n Then this tool is the solution for you. Just take this file in your\n file manager (finder, windows explorer, nautilus...) and then\n drop it onto this window.\n

\n We will check the format compliance of your file and immediately\n give\n

    \n
  • information if it is correct with respect to the template\n
  • give information on where it is incorrect\n
\n\n

\n Note: Currently we process only tab delimited files.\n

\n \"\"\")\n\n vbox = QGridLayout()\n\n vbox.addWidget(self.label_url,1,0)\n vbox.addWidget(self.label_success,2,0)\n vbox.addWidget(self.label_instructions,3,0)\n vbox.addWidget(self.close_button,4,0)\n #vbox.addStretch()\n\n total_height = self.bottom * 0.8\n content_height = total_height * 0.6\n\n vbox.setRowMinimumHeight(0,content_height)\n\n self.setLayout(vbox)\n\n self.setWindowTitle('INCOME table Validation Drop Target')\n # self.setGeometry(800, 500, 300, 400)\n\ndef run_with_validator(\n validate,\n cls: Type[ValidationDropTarget] = None,\n) -> None:\n if cls is None:\n cls = ValidationDropTarget\n\n app = QApplication([])\n\n drop_target = cls(app, validate)\n drop_target.show()\n return app.exec_()\n\n\n@click.command()\n@click.option('-t', '--template', type=click.File(), default='template.tsv')\n@click.option('-v', '--verbose', is_flag=True)\ndef main(template, verbose: bool):\n \"\"\"Run the table_validator Desktop App.\"\"\"\n if verbose:\n logging.basicConfig(level=logging.DEBUG)\n logger.setLevel(logging.DEBUG)\n print(\"start with template\",template)\n\n click.echo(f'Building table validator with {template.name}')\n validate = table_validator.TemplateValidator(template)\n sys.exit(run_with_validator(validate))\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"src/table_validator/desktop/validation_drop_target.py","file_name":"validation_drop_target.py","file_ext":"py","file_size_in_byte":11915,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"70337552","text":"from aiogram.types import ContentType, Message, MediaGroup\nfrom aiogram.dispatcher.filters import Command\n\nfrom loader import dp, bot\n\n\n# Получаем айди фотки\n@dp.message_handler(content_types=ContentType.PHOTO)\nasync def find_id_photo(message: Message):\n await message.reply(text=f\"ID фотки = {message.photo[-1].file_id}\")\n\n\n# Получаем айди видоса\n@dp.message_handler(content_types=ContentType.VIDEO)\nasync def find_id_video(message: Message):\n id_video = message.video.file_id\n await message.reply(text=f\"ID видео = {id_video}\")\n\n\n@dp.message_handler(Command(\"get_photo\"))\nasync def send_atr(message: Message):\n url1 = \"https://gos.ifrigate.ru/wp-content/uploads/main2.jpg\"\n await bot.send_photo(chat_id=message.from_user.id,\n photo=url1,\n caption=f'Городская Администрация!\\n'\n f'Если хочешь больше фото, то нажми /more_attractions'\n )\n\n\n@dp.message_handler(Command(\"more_attractions\"))\nasync def more_attractions(message: Message):\n # Создаем альбом\n albums = MediaGroup()\n url1 = \"https://gos.ifrigate.ru/wp-content/uploads/main2.jpg\"\n url2 = \"http://hotel7nebo.ru/images/page/43.jpg\"\n url3 = \"https://img.geliophoto.com/rostov/12_rostov.jpg\"\n url4 = \"https://www.yuga.ru/media/0e/29/pr_budennovskogo_rostov-na-donu_ponomar__iic6nxi.jpg\"\n # Добавляем фотки\n albums.attach_photo(url1)\n albums.attach_photo(url2)\n albums.attach_photo(url3)\n albums.attach_photo(url4)\n\n # присылаем альбом\n await message.answer_media_group(media=albums)\n","sub_path":"handlers/users/sending_attrac.py","file_name":"sending_attrac.py","file_ext":"py","file_size_in_byte":1732,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"235993286","text":"import copy\nfrom datetime import datetime\n\nimport pytz\nfrom dateutil.rrule import rrule\nfrom dateutil import parser\nfrom django.contrib.postgres.fields import JSONField\nfrom django.db import models, transaction\nfrom django.utils.module_loading import import_string\nfrom fleming import fleming\nfrom manager_utils import bulk_update\nfrom timezone_field import TimeZoneField\n\n\nclass RRuleManager(models.Manager):\n \"\"\"\n Custom manager for rrule objects\n \"\"\"\n def update_next_occurrences(self, rrule_objects=None):\n if rrule_objects is None:\n return\n for rrule_object in rrule_objects:\n rrule_object.update_next_occurrence(save=False)\n\n bulk_update(self, rrule_objects, ['last_occurrence', 'next_occurrence'])\n\n @transaction.atomic\n def handle_overdue(self, **filters):\n \"\"\"\n Handles any overdue rrules\n \"\"\"\n\n # Get instances of all overdue recurrence handler classes\n instances = self.overdue_handler_class_instances(**filters)\n\n # Build a list of rrules that get returned from the handler\n rrules = []\n for instance in instances:\n rrules.extend(instance.handle())\n\n # Bulk update the next occurrences\n RRule.objects.update_next_occurrences(rrule_objects=rrules)\n\n def overdue_handler_class_instances(self, **filters):\n \"\"\"\n Returns a set of instances for any handler with an old next_occurrence\n \"\"\"\n\n # Get the rrule objects that are overdue and need to be handled\n rrule_objects = self.get_queryset().filter(\n next_occurrence__lte=datetime.utcnow(),\n **filters\n ).distinct(\n 'occurrence_handler_path'\n )\n\n # Return instances of the handler classes\n return [\n rrule_object.get_occurrence_handler_class_instance()\n for rrule_object in rrule_objects\n ]\n\n\nclass RRule(models.Model):\n \"\"\"\n Model that will hold rrule details and generate recurrences to be handled by the supplied handler\n \"\"\"\n\n # Params used to generate the rrule\n rrule_params = JSONField()\n\n # Any meta data associated with the object that created this rule\n meta_data = JSONField(default=dict)\n\n # The timezone all dates should be converted to\n time_zone = TimeZoneField(default='UTC')\n\n # The last occurrence date that was handled\n last_occurrence = models.DateTimeField(null=True, default=None)\n\n # The next occurrence date that should be handled\n next_occurrence = models.DateTimeField(null=True, default=None)\n\n # A python path to the handler class used to handle when a recurrence occurs for this rrule\n # The configuration class must extend ambition_utils.rrule.handler.OccurrenceHandler\n occurrence_handler_path = models.CharField(max_length=500, blank=False, null=False)\n\n # Custom object manager\n objects = RRuleManager()\n\n def get_time_zone_object(self):\n if self.time_zone is None:\n return pytz.utc\n\n # There is a test for this but it still doesn't hit this block\n if isinstance(self.time_zone, str): # pragma: no cover\n return pytz.timezone(self.time_zone)\n\n return self.time_zone\n\n def get_occurrence_handler_class_instance(self):\n \"\"\"\n Gets an instance of the occurrence handler class associated with this rrule\n :rtype: ambition_utils.rrule.handler.OccurrenceHandler\n :return: The instance\n \"\"\"\n return import_string(self.occurrence_handler_path)()\n\n def get_rrule(self):\n \"\"\"\n Builds the rrule object by restoring all the params.\n The dtstart param will be converted to local time if it is set.\n :rtype: rrule\n \"\"\"\n params = copy.deepcopy(self.rrule_params)\n\n # Convert next scheduled from utc back to time zone\n if params.get('dtstart') and not hasattr(params.get('dtstart'), 'date'):\n params['dtstart'] = parser.parse(params['dtstart'])\n\n # Convert until date from utc back to time zone\n if params.get('until') and not hasattr(params.get('until'), 'date'):\n params['until'] = parser.parse(params['until'])\n\n # Always cache\n params['cache'] = True\n\n # Return the rrule\n return rrule(**params)\n\n def get_next_occurrence(self, last_occurrence=None, force=False):\n \"\"\"\n Builds the rrule and returns the next date in the series or None of it is the end of the series\n :param last_occurrence: The last occurrence that was generated\n :param force: If the next occurrence is none, force the rrule to generate another\n :rtype: rrule or None\n \"\"\"\n # Get the last occurrence\n last_occurrence = last_occurrence or self.last_occurrence or datetime.utcnow()\n\n # Get the rule\n rule = self.get_rrule()\n\n # Convert to local time zone for getting next occurrence, otherwise time zones ahead of utc will return the same\n last_occurrence = fleming.convert_to_tz(last_occurrence, self.get_time_zone_object(), return_naive=True)\n\n # Generate the next occurrence\n next_occurrence = rule.after(last_occurrence)\n\n # If next occurrence is none and force is true, force the rrule to generate another date\n if next_occurrence is None and force:\n # Keep a reference to the original rrule_params\n original_rrule_params = {}\n original_rrule_params.update(self.rrule_params)\n\n # Remove any limiting params\n self.rrule_params.pop('count', None)\n self.rrule_params.pop('until', None)\n\n # Refetch the rule\n rule = self.get_rrule()\n\n # Generate the next occurrence\n next_occurrence = rule.after(last_occurrence)\n\n # Restore the rrule params\n self.rrule_params = original_rrule_params\n\n # If there is a next occurrence, convert to utc\n if next_occurrence:\n next_occurrence = self.convert_to_utc(next_occurrence)\n\n # Return the next occurrence\n return next_occurrence\n\n def update_next_occurrence(self, save=True):\n \"\"\"\n Sets the next_occurrence property to the next time in the series and sets the last_occurrence property\n to the previous value of next_occurrence. If the save option is True, the model will be saved. The\n save flag is typically set to False when wanting to bulk update records after updating the values\n of many models.\n :param save: Flag to save the model after updating the schedule.\n :type save: bool\n \"\"\"\n if not self.next_occurrence:\n return None\n\n # Only handle if the current date is >= next occurrence\n if datetime.utcnow() < self.next_occurrence:\n return False\n\n self.last_occurrence = self.next_occurrence\n self.next_occurrence = self.get_next_occurrence(self.last_occurrence)\n\n # Only save if the flag is true\n if save:\n self.save(update_fields=['last_occurrence', 'next_occurrence'])\n\n def convert_to_utc(self, dt):\n \"\"\"\n Treats the datetime object as being in the timezone of self.timezone and then converts it to utc timezone.\n :type dt: datetime\n \"\"\"\n # Add timezone info\n dt = fleming.attach_tz_if_none(dt, self.get_time_zone_object())\n\n # Convert to utc\n dt = fleming.convert_to_tz(dt, pytz.utc, return_naive=True)\n\n return dt\n\n def refresh_next_occurrence(self, current_time=None):\n \"\"\"\n Sets the next occurrence date based on the current rrule param definition. The date will be after the\n specified current_time or utcnow.\n :param current_time: Optional datetime object to compute the next time from\n \"\"\"\n # Get the current time or go off the specified current time\n current_time = current_time or datetime.utcnow()\n\n # Next occurrence is in utc here\n next_occurrence = self.get_next_occurrence(last_occurrence=current_time)\n\n if next_occurrence:\n # Only set if the new time is still greater than now\n if next_occurrence > datetime.utcnow():\n self.next_occurrence = next_occurrence\n else:\n self.next_occurrence = next_occurrence\n\n def pre_save_hooks(self):\n self.set_date_objects()\n\n def set_date_objects(self):\n # Check if this is a new rrule object\n if self.pk is None:\n # Convert next scheduled from utc back to time zone\n if self.rrule_params.get('dtstart') and not hasattr(self.rrule_params.get('dtstart'), 'date'):\n self.rrule_params['dtstart'] = parser.parse(self.rrule_params['dtstart'])\n\n # Convert until date from utc back to time zone\n if self.rrule_params.get('until') and not hasattr(self.rrule_params.get('until'), 'date'):\n self.rrule_params['until'] = parser.parse(self.rrule_params['until'])\n\n # Get the first scheduled time according to the rrule (this converts from utc back to local time)\n self.next_occurrence = self.get_rrule()[0]\n\n # Convert back to utc before saving\n self.next_occurrence = self.convert_to_utc(self.next_occurrence)\n\n # Serialize the datetime objects if they exist\n if self.rrule_params.get('dtstart') and hasattr(self.rrule_params.get('dtstart'), 'date'):\n self.rrule_params['dtstart'] = self.rrule_params['dtstart'].strftime('%Y-%m-%d %H:%M:%S')\n\n if self.rrule_params.get('until') and hasattr(self.rrule_params.get('until'), 'date'):\n self.rrule_params['until'] = self.rrule_params['until'].strftime('%Y-%m-%d %H:%M:%S')\n\n def save(self, *args, **kwargs):\n \"\"\"\n Saves the rrule model to the database. If this is a new object, the first next_scheduled time is\n determined and set. The `dtstart` and `until` objects will be safely encoded as strings if they are\n datetime objects.\n \"\"\"\n self.pre_save_hooks()\n\n # Call the parent save method\n super().save(*args, **kwargs)\n\n def generate_dates(self, num_dates=20):\n \"\"\"\n Generate the first num_dates dates of the recurrence and return a list of datetimes\n \"\"\"\n assert num_dates > 0\n\n self.pre_save_hooks()\n\n dates = []\n\n rule = self.get_rrule()\n\n try:\n d = rule[0]\n # Convert to time zone\n date_with_tz = fleming.attach_tz_if_none(d, self.time_zone)\n date_in_utc = fleming.convert_to_tz(date_with_tz, pytz.utc, True)\n dates.append(date_in_utc)\n\n for x in range(0, num_dates):\n d = rule.after(d)\n if not d:\n break\n # Convert to time zone\n date_with_tz = fleming.attach_tz_if_none(d, self.time_zone)\n date_in_utc = fleming.convert_to_tz(date_with_tz, pytz.utc, True)\n dates.append(date_in_utc)\n except Exception: # pragma: no cover\n pass\n\n return dates\n\n @classmethod\n def generate_dates_from_params(cls, rrule_params, time_zone=None, num_dates=20):\n time_zone = time_zone or pytz.utc\n rule = cls(rrule_params=rrule_params, time_zone=time_zone)\n\n return rule.generate_dates(num_dates=num_dates)\n","sub_path":"ambition_utils/rrule/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":11469,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"214792893","text":"# Copyright 2018 Google LLC\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# https://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\"\"\"Accesses the google.devtools.clouderrorreporting.v1beta1 ReportErrorsService API.\"\"\"\n\nimport pkg_resources\n\nimport google.api_core.gapic_v1.client_info\nimport google.api_core.gapic_v1.config\nimport google.api_core.gapic_v1.method\nimport google.api_core.grpc_helpers\nimport google.api_core.path_template\n\nfrom google.cloud.errorreporting_v1beta1.gapic import enums\nfrom google.cloud.errorreporting_v1beta1.gapic import report_errors_service_client_config\nfrom google.cloud.errorreporting_v1beta1.proto import common_pb2\nfrom google.cloud.errorreporting_v1beta1.proto import error_group_service_pb2\nfrom google.cloud.errorreporting_v1beta1.proto import error_stats_service_pb2\nfrom google.cloud.errorreporting_v1beta1.proto import report_errors_service_pb2\nfrom google.protobuf import duration_pb2\nfrom google.protobuf import timestamp_pb2\n\n_GAPIC_LIBRARY_VERSION = pkg_resources.get_distribution(\n 'google-cloud-error-reporting', ).version\n\n\nclass ReportErrorsServiceClient(object):\n \"\"\"An API for reporting error events.\"\"\"\n\n SERVICE_ADDRESS = 'clouderrorreporting.googleapis.com:443'\n \"\"\"The default address of the service.\"\"\"\n\n # The scopes needed to make gRPC calls to all of the methods defined in\n # this service\n _DEFAULT_SCOPES = ('https://www.googleapis.com/auth/cloud-platform', )\n\n # The name of the interface for this client. This is the key used to find\n # method configuration in the client_config dictionary.\n _INTERFACE_NAME = 'google.devtools.clouderrorreporting.v1beta1.ReportErrorsService'\n\n @classmethod\n def project_path(cls, project):\n \"\"\"Return a fully-qualified project string.\"\"\"\n return google.api_core.path_template.expand(\n 'projects/{project}',\n project=project,\n )\n\n def __init__(self,\n channel=None,\n credentials=None,\n client_config=report_errors_service_client_config.config,\n client_info=None):\n \"\"\"Constructor.\n\n Args:\n channel (grpc.Channel): A ``Channel`` instance through\n which to make calls. This argument is mutually exclusive\n with ``credentials``; providing both will raise an exception.\n credentials (google.auth.credentials.Credentials): The\n authorization credentials to attach to requests. These\n credentials identify this application to the service. If none\n are specified, the client will attempt to ascertain the\n credentials from the environment.\n client_config (dict): A dictionary of call options for each\n method. If not specified, the default configuration is used.\n client_info (google.api_core.gapic_v1.client_info.ClientInfo):\n The client info used to send a user-agent string along with\n API requests. If ``None``, then default info will be used.\n Generally, you only need to set this if you're developing\n your own client library.\n \"\"\"\n # If both `channel` and `credentials` are specified, raise an\n # exception (channels come with credentials baked in already).\n if channel is not None and credentials is not None:\n raise ValueError(\n 'The `channel` and `credentials` arguments to {} are mutually '\n 'exclusive.'.format(self.__class__.__name__), )\n\n # Create the channel.\n if channel is None:\n channel = google.api_core.grpc_helpers.create_channel(\n self.SERVICE_ADDRESS,\n credentials=credentials,\n scopes=self._DEFAULT_SCOPES,\n )\n\n # Create the gRPC stubs.\n self.report_errors_service_stub = (\n report_errors_service_pb2.ReportErrorsServiceStub(channel))\n\n if client_info is None:\n client_info = (\n google.api_core.gapic_v1.client_info.DEFAULT_CLIENT_INFO)\n client_info.gapic_version = _GAPIC_LIBRARY_VERSION\n\n # Parse out the default settings for retry and timeout for each RPC\n # from the client configuration.\n # (Ordinarily, these are the defaults specified in the `*_config.py`\n # file next to this one.)\n method_configs = google.api_core.gapic_v1.config.parse_method_configs(\n client_config['interfaces'][self._INTERFACE_NAME], )\n\n # Write the \"inner API call\" methods to the class.\n # These are wrapped versions of the gRPC stub methods, with retry and\n # timeout configuration applied, called by the public methods on\n # this class.\n self._report_error_event = google.api_core.gapic_v1.method.wrap_method(\n self.report_errors_service_stub.ReportErrorEvent,\n default_retry=method_configs['ReportErrorEvent'].retry,\n default_timeout=method_configs['ReportErrorEvent'].timeout,\n client_info=client_info,\n )\n\n # Service calls\n def report_error_event(self,\n project_name,\n event,\n retry=google.api_core.gapic_v1.method.DEFAULT,\n timeout=google.api_core.gapic_v1.method.DEFAULT,\n metadata=None):\n \"\"\"\n Report an individual error event.\n\n This endpoint accepts either an OAuth token,\n or an\n API key\n for authentication. To use an API key, append it to the URL as the value of\n a ``key`` parameter. For example:\n
POST https://clouderrorreporting.googleapis.com/v1beta1/projects/example-project/events:report?key=123ABC456
\n\n Example:\n >>> from google.cloud import errorreporting_v1beta1\n >>>\n >>> client = errorreporting_v1beta1.ReportErrorsServiceClient()\n >>>\n >>> project_name = client.project_path('[PROJECT]')\n >>> event = {}\n >>>\n >>> response = client.report_error_event(project_name, event)\n\n Args:\n project_name (str): [Required] The resource name of the Google Cloud Platform project. Written\n as ``projects/`` plus the\n `Google Cloud Platform project ID `_.\n Example: ``projects/my-project-123``.\n event (Union[dict, ~google.cloud.errorreporting_v1beta1.types.ReportedErrorEvent]): [Required] The error event to be reported.\n If a dict is provided, it must be of the same form as the protobuf\n message :class:`~google.cloud.errorreporting_v1beta1.types.ReportedErrorEvent`\n retry (Optional[google.api_core.retry.Retry]): A retry object used\n to retry requests. If ``None`` is specified, requests will not\n be retried.\n timeout (Optional[float]): The amount of time, in seconds, to wait\n for the request to complete. Note that if ``retry`` is\n specified, the timeout applies to each individual attempt.\n metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata\n that is provided to the method.\n\n Returns:\n A :class:`~google.cloud.errorreporting_v1beta1.types.ReportErrorEventResponse` instance.\n\n Raises:\n google.api_core.exceptions.GoogleAPICallError: If the request\n failed for any reason.\n google.api_core.exceptions.RetryError: If the request failed due\n to a retryable error and retry attempts failed.\n ValueError: If the parameters are invalid.\n \"\"\"\n if metadata is None:\n metadata = []\n metadata = list(metadata)\n request = report_errors_service_pb2.ReportErrorEventRequest(\n project_name=project_name,\n event=event,\n )\n return self._report_error_event(\n request, retry=retry, timeout=timeout, metadata=metadata)\n","sub_path":"error_reporting/google/cloud/errorreporting_v1beta1/gapic/report_errors_service_client.py","file_name":"report_errors_service_client.py","file_ext":"py","file_size_in_byte":8736,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"395292513","text":"\"\"\"\nSliding tile puzzle\n\"\"\"\nimport time\nfrom random import shuffle\nfrom kivy.app import App\nfrom kivy.clock import Clock\nfrom kivy.uix.gridlayout import GridLayout\nfrom kivy.uix.boxlayout import BoxLayout\nfrom kivy.animation import Animation\nfrom kivy.uix.button import Button\nfrom kivy.core.window import Window\n\nclass Card(Button):\n \"\"\"\n Card\n y row\n 100: 0, 1, 2, | 0\n 50: 3, 4, 5, | 1\n 0: 6, 7, 8 | 2\n --------------------\n 0, 70, 140 : x\n --------------------\n 0 1 2 : col\n \"\"\"\n def __init__(self, rgb, cell_num, board, **kwargs):\n kwargs[\"on_press\"] = self.click_handler\n super().__init__(**kwargs)\n self.rgb = rgb\n self.initial_cellnum = cell_num\n self.cell_num = cell_num\n self.num_cols = board.cols\n self.cell_movex = board.movex # {0:0, 1:70, 2:140}\n self.cell_movey = board.movey # {0:100, 1:50, 2:0}\n self.move_handler = board.move\n self.cards = board.children\n self.face_value = kwargs[\"text\"]\n self.trigger_rerunner = board.trigger_rerunner\n self.check_rerunner = board.check_rerunner\n\n def on_size(self, pos_size, *args):\n \"\"\"\n kivy: on_size event\n \"\"\"\n # print(\"Card.on_size\", self.face_value, pos_size)\n row_num = self.calc_row_num()\n col_num = self.calc_col_num()\n self.cell_movex[col_num] = self.pos[0]\n self.cell_movey[row_num] = self.pos[1]\n if self == self.cards[0]:\n # print(\"last\", self.face_value, self.cell_num)\n self.trigger_rerunner()\n\n def __str__(self):\n return \"(\" + str(self.x) + \",\" + str(self.y) + \",\" + str(self.width) +\\\n \",\" + str(self.height) + \")\"\n\n def click_handler(self, instance):\n \"\"\"\n click_handler\n \"\"\"\n print(\"Card.click_handler\", self.face_value, self.cell_num, instance.width, instance.height, instance.pos[0], instance.pos[1])\n self.move_handler(self, instance)\n\n def calc_row_num(self):\n \"\"\"\n calc_row_num\n \"\"\"\n return int(self.cell_num / self.num_cols)\n\n def calc_col_num(self):\n \"\"\"\n calc_col_num\n \"\"\"\n return self.cell_num % self.num_cols\n\n def on_move_end(self, anim, widget_instance):\n \"\"\"\n on_move_end\n \"\"\"\n print(\"Card.on_move_end\", self.face_value, self.cell_num, widget_instance.pos)\n self.check_rerunner()\n\n def animate_move(self, instance):\n \"\"\"\n animate_move\n \"\"\"\n col_num = self.calc_col_num() # += 1\n row_num = self.calc_row_num()\n # print(row_num, col_num, self.cell_num, self.cell_movex[row_num], self.cell_movey[col_num])\n animation = Animation(pos=(self.cell_movex[col_num], self.cell_movey[row_num]), d=0.2)\n animation.bind(on_complete=self.on_move_end)\n animation.start(instance)\n\n def move_up(self, instance):\n \"\"\"\n move_up\n \"\"\"\n row_num = self.calc_row_num()\n if row_num == 0:\n return\n self.cell_num -= self.num_cols\n self.animate_move(instance)\n\n def move_right(self, instance):\n \"\"\"\n move_right\n \"\"\"\n col_num = self.calc_col_num()\n if col_num == self.num_cols - 1:\n return\n self.cell_num += 1\n self.animate_move(instance)\n\n def move_down(self, instance):\n \"\"\"\n move_down\n \"\"\"\n row_num = self.calc_row_num()\n if row_num == self.num_cols - 1:\n return\n self.cell_num += self.num_cols\n self.animate_move(instance)\n\n def move_left(self, instance):\n \"\"\"\n move_left\n \"\"\"\n col_num = self.calc_col_num()\n if col_num == 0:\n return\n self.cell_num -= 1\n self.animate_move(instance)\n\nclass Board(GridLayout):\n \"\"\"\n Board\n \"\"\"\n def __init__(self, **kwargs):\n super(Board, self).__init__(**kwargs)\n self.cols = kwargs[\"cols\"]\n num_slots = self.cols**2\n board = []\n for i in range(1, num_slots):\n board.append(i)\n\n while True:\n shuffle(board)\n num_inversions = self.count_inversion(board)\n if num_inversions % 2 == 0:\n # Since the empty is initially in the first row from the bottom, this checks the\n # solvable board. See count_inversion() for the details.\n break\n\n print(board)\n self.movex = {}\n self.movey = {}\n self.moves = []\n self.stored_moves = []\n self.rerunner_moves = []\n self.trigger_rerunner = Clock.create_trigger(self.rerunner)\n self.trigger_dorerun = Clock.create_trigger(self.do_rerun)\n self.scheduled_rerun_time = 0\n self.scheduled_rerun = None\n for i in range(0, num_slots-1):\n self.add_widget(Card((255, 255, 0), i, self,\\\n text=str(board[i]), color=[1, 1, 0, 1.0]))\n self.free_cell = num_slots - 1\n\n def move(self, cell, widget_instance):\n \"\"\"\n move\n \"\"\"\n if cell.cell_num - self.cols == self.free_cell:\n self.free_cell = cell.cell_num\n cell.move_up(widget_instance)\n self.moves.append((cell, widget_instance))\n elif cell.calc_col_num() < self.cols - 1 and cell.cell_num + 1 == self.free_cell:\n self.free_cell = cell.cell_num\n cell.move_right(widget_instance)\n self.moves.append((cell, widget_instance))\n elif cell.cell_num + self.cols == self.free_cell:\n self.free_cell = cell.cell_num\n cell.move_down(widget_instance)\n self.moves.append((cell, widget_instance))\n elif cell.calc_col_num() > 0 and cell.cell_num - 1 == self.free_cell:\n self.free_cell = cell.cell_num\n cell.move_left(widget_instance)\n self.moves.append((cell, widget_instance))\n board = [self.cols**2] * (self.cols**2) # Empty cell gets #cols, so inversion_count treats board solved when the cards\n for card in self.children: # are in the order and the empty slot is in the bottom right.\n board[card.cell_num] = int(card.face_value)\n # print(\"move\", board)\n inversion = self.count_inversion(board)\n if inversion == 0:\n print(\"solved\")\n\n def count_inversion(self, board):\n \"\"\"\n param board List of card face values\\n\n\n An inversion is when a cell precedes another cell with a lower number on it. The solution\n state has zero inversions. For example, if, in a 3 x 3 grid, number 8 is top left, then\n there will be 7 inversions from this card, as numbers 1-7 come after it. To explain it\n another way, an inversion is a pair of cards (a,b) such that a appears before b, but a > b.\n 8, 4, 3 inversions: 7, 3, 2\n 2, 6, 1 1, 2, 0\n 7, 5 1, 0\n The formula says:\n If the grid width is odd, then the number of inversions in a solvable situation is even.\n If the grid width is even, and the blank is on an even row counting from the bottom\n (second-last, fourth-last etc), then\n the number of inversions in a solvable situation is odd.\n If the grid width is even, and the blank is on an odd row counting from the bottom\n (last, third-last, fifth-last etc) then\n the number of inversions in a solvable situation is even.\n That gives us this formula for determining solvability:\n ((grid width odd) && (#inversions even)) ||\n ((grid width even) && ((blank on odd row from bottom) == (#inversions even)))\n \"\"\"\n inversions_all = 0\n for i, val in enumerate(board[0:-1]):\n for after in board[i+1:len(board)]:\n if after < val:\n inversions_all += 1\n # print(\"inversions_all=\" + str(inversions_all))\n return inversions_all\n\n def on_size(self, *args):\n \"\"\"\n on_size\n \"\"\"\n self.free_cell = self.cols**2 - 1 # the last one\n for card in self.children:\n card.cell_num = card.initial_cellnum\n\n def rerunner(self, *args):\n \"\"\"\n rerunner\n \"\"\"\n if self.moves and not self.rerunner_moves:\n if self.scheduled_rerun_time > 0:\n self.scheduled_rerun.cancel()\n self.scheduled_rerun_time = time.time()\n self.scheduled_rerun = Clock.schedule_once(self.do_rerun, 0.5)\n\n def do_rerun(self, *args):\n \"\"\"\n do_rerun\n \"\"\"\n self.scheduled_rerun_time = 0\n print(\"Board.do_rerun\", len(self.moves), \"moves\", self.movex, self.movey)\n if self.rerunner_moves:\n move = self.rerunner_moves.pop(0)\n self.move(move[0], move[1])\n return\n if self.moves and not self.rerunner_moves:\n self.rerunner_moves = self.moves.copy()\n self.stored_moves = self.moves.copy()\n self.moves.clear()\n move = self.rerunner_moves.pop(0)\n self.move(move[0], move[1])\n\n def check_rerunner(self):\n \"\"\"\n check_rerunner\n \"\"\"\n if self.rerunner_moves:\n self.trigger_dorerun()\n\nclass Header(BoxLayout):\n \"\"\"\n Header\n \"\"\"\n def __init__(self, create_board, **kwargs):\n kwargs[\"orientation\"] = \"horizontal\"\n super(Header, self).__init__(**kwargs)\n self.add_widget(Button(text=\"3x3\", on_press=lambda btn: create_board(3)))\n self.add_widget(Button(text=\"4x4\", on_press=lambda btn: create_board(4)))\n self.add_widget(Button(text=\"5x5\", on_press=lambda btn: create_board(5)))\n self.add_widget(Button(text=\"6x6\", on_press=lambda btn: create_board(6)))\n self.add_widget(Button(text=\"7x7\", on_press=lambda btn: create_board(7)))\n\nclass Ui(BoxLayout):\n \"\"\"\n Ui\n \"\"\"\n def __init__(self, **kwargs):\n super(Ui, self).__init__(**kwargs)\n self.header = Header(self.create_board, size_hint=(1, None), height=\"60sp\")\n self.board = None\n #self.board = Board(cols=5, size_hint=(1, 1), spacing=0, padding=0)\n self.add_widget(self.header)\n #self.add_widget(self.board)\n\n def create_board(self, num_cols):\n \"\"\"\n create_board\n \"\"\"\n if self.board is not None:\n self.board.clear_widgets()\n self.remove_widget(self.board)\n self.board = Board(cols=num_cols, size_hint=(1, 1), spacing=0, padding=0)\n self.add_widget(self.board)\n\nclass SlidePuzzle(App):\n \"\"\"\n SlidePuzzle\n \"\"\"\n def build(self):\n myui = Ui(orientation=\"vertical\", spacing=0, padding=0)\n # myui.board.count_inversion([8, 4, 3, 2, 6, 1, 7, 5])\n # myui.board.count_inversion([8, 5, 4, 2, 6, 1, 3, 7])\n # myui.board.count_inversion([1, 2, 3, 4, 5, 6, 7, 8])\n return myui\n\nif __name__ == '__main__':\n # Window.size = (420, 800) # (210, 200)\n Window.clearcolor = (1, 1, 0, 0.1)\n SlidePuzzle().run()\n","sub_path":"sp_kivy.py","file_name":"sp_kivy.py","file_ext":"py","file_size_in_byte":11177,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"651663856","text":"from __future__ import print_function\nimport os\nimport sys\n\n\nfrom werkzeug.utils import secure_filename\nfrom PIL import Image\nfrom tinify import tinify\nfrom flask import Flask , render_template , request, send_file, send_from_directory\n\ntinify.key = \"KHdQmr04kWs6b4tfpm5bYgQHVzVTBS3v\"\nfiled=''\n\napp = Flask(__name__) #web is apppip install --upgrade tinify\n\n@app.route('/') #end point #staic is public template is not\n\ndef bootstrap():\n \n return render_template('upload.html')\n@app.route('/uploader', methods=['GET', 'POST']) #end point\ndef upload():\n global filed\n if request.method == \"POST\":\n f=request.files.getlist('file1')\n #f.save(f.filename)\n g=request.form.get('Services')\n h=request.form.get('height')\n w=request.form.get('width')\n q=request.form.get('quality')\n print(g)\n \n \n if g==\"Hosted\":\n cop=request.form.get('tservice')\n if cop==\"Compress\":\n filed=Hostoptcomp(f,q)\n \n \n if cop==\"Resize\":\n filed=Hostoptres(f,h,w,q)\n \n \n \n if g==\"Tinify\":\n cop=request.form.get('tservice')\n if cop==\"Compress\":\n filed=Tinicompopt(f)\n \n \n \n if cop==\"Resize\":\n cop=request.form.get('tservice')\n filed=Tiniresopt(f,h,w)\n\n \n \n return download_file(filed)\n \ndef Tinicompopt(f):\n tinify.key = \"KHdQmr04kWs6b4tfpm5bYgQHVzVTBS3v\"\n for x in range(0,len(f)):\n \n \n result = f[x].filename[::-1].find('/')\n typ=f[x].filename[-3:]\n typ=typ.lower()\n print(typ)\n o=f[x].filename[-result-1:-4]+ \".\"+typ\n \n \n \n source =tinify.from_file(path=f[x])\n source.to_file(o)\n return o\n \n\ndef Tiniresopt(f,h,w):\n tinify.key = \"KHdQmr04kWs6b4tfpm5bYgQHVzVTBS3v\"\n h=int(h)\n w=int(w)\n for x in range(0,len(f)):\n \n result = f[x].filename[::-1].find('/')\n typ=f[x].filename[-3:]\n typ=typ.lower()\n print(typ)\n o=f[x].filename[-result-1:-4]+\".\"+typ\n \n \n source = tinify.from_file(path=f[x])\n if (h!=0 and w!=0):\n resized = source.resize(\n method=\"fit\",\n width=w,\n height=h\n )\n\n else:\n resized = source.resize(\n method=\"fit\",\n width=150,\n height=100\n )\n resized.to_file(o)\n return o\ndef Hostoptres(f,h,w,q):\n h=int(h)\n w=int(w)\n q=int(q)\n for x in range(0,len(f)):\n result = f[x].filename[::-1].find('/')\n typ=f[x].filename[-3:]\n typ=typ.lower()\n print(typ)\n o=f[x].filename[-result-1:-4]+\".\"+typ\n im = Image.open(f[x])\n print('o')\n print(im.format, im.size, im.mode)\n y=im.size\n print(y[0])\n if (h!=0 and w!=0):\n foo = im.resize((int(h),int(w)),Image.ANTIALIAS)\n else:\n foo = im.resize((int(y[0]*0.5),int(y[1]*0.5)),Image.ANTIALIAS)\n if q==0:\n q=70\n foo.save(o,optimize=True,quality=q)\n return o\ndef Hostoptcomp(f,q):\n q=int(q)\n\n for x in range(0,len(f)):\n \n \n result = f[x].filename[::-1].find('/')\n typ=f[x].filename[-3:]\n typ=typ.lower()\n print(typ)\n o=f[x].filename[-result-1:-4]+\".\"+typ\n im = Image.open(f[x])\n if q==0:\n q=70\n \n im.save(o,optimize=True,quality=q) \n return o\n\n \n \n\n@app.route('/download')\ndef download_file(filed):\n return send_from_directory(directory='../../', filename=filed, as_attachment=True )\n\n #return send_file(filed,as_attachment=True)\n \n \n \n\n\napp.run(debug=True)\n","sub_path":"ImageOptimizer/compressing.py","file_name":"compressing.py","file_ext":"py","file_size_in_byte":3944,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"318958798","text":"# -*- coding: utf-8 -*-\n\nimport csv\nimport codecs # 自然语言编码转换模块\n\nfileName = 'PythonBool.csv'\n\ndef writeDataTOCsv(datas, filedNames):\n try:\n with codecs.open(fileName, 'w', 'utf-8') as csvfile:\n # 指定csv文件的头部显示\n # filedNames = ['书名', '作者']\n writer = csv.DictWriter(csvfile, fieldnames=filedNames)\n\n writer.writeheader()\n for data in datas:\n try:\n print(data)\n writer.writerow({'书名': data['title'], '作者': data['author']})\n except UnicodeEncodeError:\n print('编码错误,改数据无法写到文件中,直接忽略改数据')\n except Exception as e:\n print(e)\n\nif __name__ == \"__main__\":\n writeDataTOCsv([], [])","sub_path":"Python/csv_packages/index_write_to_csv.py","file_name":"index_write_to_csv.py","file_ext":"py","file_size_in_byte":740,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"129882130","text":"import csv\nimport json\nimport os\nfrom functools import partial\nfrom typing import Dict, Iterable, TextIO\n\n\nSUPPORTED_AUDIO_FILE_FORMAT = (\"mp3\", \"wav\")\n\n\ndef audio_file_name_iter(transcription_file_path: str, col_mapping: Dict[str, str]) -> Iterable[str]:\n filename = os.path.basename(transcription_file_path)\n file_ext = filename.split(\".\")[-1]\n path_column = [src for src, dst in col_mapping.items() if dst == \"path\"][0]\n\n if file_ext in (\"csv\", \"tsv\"):\n delimiter = \"\\t\" if file_ext == \"tsv\" else \",\"\n sample_iterator = partial(csv.DictReader, delimiter=delimiter)\n else:\n sample_iterator = json_line_iterator\n\n with open(transcription_file_path, encoding=\"utf-8\") as f:\n for sample in sample_iterator(f):\n path = sample[path_column]\n yield os.path.basename(path)\n\n\ndef json_line_iterator(f: TextIO) -> Iterable[dict]:\n for line in f:\n yield json.loads(line)\n","sub_path":"src/autonlp/audio_utils.py","file_name":"audio_utils.py","file_ext":"py","file_size_in_byte":940,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"417256742","text":"import random\nimport yaml\n\nfrom models import Server\n\n\ndef load_configuration(path):\n with open(path) as config_file:\n config = yaml.load(config_file, Loader=yaml.FullLoader)\n return config\n\n\ndef transform_backends_from_config(config):\n register = {}\n for entry in config.get('hosts', []):\n register.update({entry['host']: [Server(endpoint) for endpoint in entry['servers']]})\n for entry in config.get('paths', []):\n register.update({entry['path']: [Server(endpoint) for endpoint in entry['servers']]})\n return register\n\n\ndef get_healthy_server(host, register):\n try:\n return least_connections([server for server in register[host] if server.healthy])\n except IndexError:\n return None\n\n\ndef healthcheck(register):\n for host in register:\n for server in register[host]:\n server.healthcheck_and_update_status()\n return register\n\n\ndef process_rules(config, host, rules, modify):\n modify_options = {\"header\": \"header_rules\", \"param\": \"param_rules\"}\n for entry in config.get('hosts', []):\n if host == entry['host']:\n header_rules = entry.get(modify_options[modify], {})\n for instruction, modify_headers in header_rules.items():\n if instruction == \"add\":\n rules.update(modify_headers)\n if instruction == \"remove\":\n for key in modify_headers.keys():\n if key in rules:\n rules.pop(key)\n return rules\n\n\ndef process_rewrite_rules(config, host, path):\n for entry in config.get('hosts', []):\n if host == entry['host']:\n rewrite_rules = entry.get('rewrite_rules', {})\n for current_path, new_path in rewrite_rules['replace'].items():\n return path.replace(current_path, new_path)\n\n\ndef least_connections(servers):\n if not servers:\n return None\n return min(servers, key=lambda x: x.open_connections)\n\n\ndef process_firewall_rules_flag(config, host, client_ip=None, path=None):\n for entry in config.get('hosts', []):\n if host == entry['host']:\n firewall_rules = entry.get('firewall_rules', {})\n if client_ip in firewall_rules.get('ip_reject', []):\n return False\n if path in firewall_rules.get('path_reject', []):\n return False\n return True\n","sub_path":"utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":2394,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"392031836","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n\"\"\"\nNAME\n get_all_inp_files.py\n\nDESCRIPTION\n Retrieve all .inp files within the directory data_src\n\nSYNTAX\n get_all_inp_files.py [command line options]\n\nOPTIONS\n -h, --help :\n prints the help message and quits\n -ds, --data_src : string\n path to the top directory in which to search for files\n -nc, --nocopy :\n write to file all_inp_files.txt, but do not copy anything\n\n\"\"\"\n# import pdb\n# pdb.set_trace()\nimport os\nimport sys\nfrom string import ascii_uppercase\nimport shutil\nimport argparse\nfrom dmgui_au.utilities import find_dropbox\nglobal top_dir, pkg_dir, data_dir, data_src, inp_dir, usr_configs_read\ntry: # get path names if set\n from dmgui_au import pkg_dir, data_dir, data_src, inp_dir\n usr_configs_read = True\nexcept:\n # if setup.py is running, don't issue warning\n if sys.argv[0] != 'setup.py':\n print(\"-W- Local path names have not been set. Please run setup.py\")\n usr_configs_read = False\n\ndef get_all_inp_files(data_src='.', inp_dir='.', nocopy = False):\n \"\"\"\n Retrieve all .inp files within the directory data_src. By default, copies\n these files to directory inp_dir.\n\n Parameters\n ----------\n data_src : path\n directory to search; default is current directory\n inp_dir : path\n designated directory to which copied .inp files will be written\n nocopy : bool\n if True, do not copy any data files; only write all_inp_files.txt\n\n Returns\n -------\n list of .inp files\n\n \"\"\"\n\n if '~' in data_src:\n data_src = os.path.expanduser(data_src)\n if not os.path.isdir(data_src):\n raise NameError(\"directory %s does not exist, aborting\" % data_src)\n\n try:\n all_inp_files = []\n name_conflicts = {}\n\n for root, dirs, files in os.walk(data_src):\n for d in dirs:\n get_all_inp_files(os.path.join(root, d), inp_dir, nocopy)\n\n for f in files:\n # test if the file name matches another in the list\n already_recorded = f in map(lambda x: os.path.split(x)[1], all_inp_files)\n # add if it does not (+ other filters)\n if f.endswith(\".inp\") and not already_recorded:\n if not any(list(f.startswith(prefix) for prefix in [\".\", \"_\", \"-\"])):\n all_inp_files.append(os.path.join(root, f))\n # if matching names, are they same file? If not, add to list and\n # record the name conflict\n elif already_recorded and not any(map(lambda x: os.path.samefile(os.path.join(root, f), x), all_inp_files)):\n # add to main list so that full path to the unique file is\n # recorded\n # all_inp_files.append(os.path.join(root, f))\n # compile name conflicts in a dictionary\n # name_conflicts[f]=[x for x in all_inp_files if f in os.path.split(x)[1]]\n if f in name_conflicts.keys():\n name_conflicts[f].append(os.path.join(root,f))\n else:\n name_conflicts[f] = [os.path.join(root,f)]\n # name_conflicts[f]=[x for x in all_inp_files if f in os.path.split(x)[1]]\n out_file = open(os.path.join(inp_dir, \"all_inp_files.txt\"), \"w\")\n # print(name_conflicts)\n for inp in all_inp_files:\n out_file.write(inp+'\\n')\n # if os.path.split(inp)[1] in name_conflicts.keys():\n # for conflicted in name_conflicts[os.path.split(inp)[1]]:\n # if conflicted != inp:\n # out_file.write('## CONFLICTS WITH {}\\n'.format(conflicted))\n # print(\"-I- There are conflicting file names for {}. These \"\n # \"have been marked in all_inp_files.txt and will not be \"\n # \"copied\".format(os.path.split(inp)[1]))\n if not nocopy:\n # TODO: Check to see if file already exists before copying\n # <08-14-18, Luke Fairchild> #\n # ------\n # TODO: Above is done but still need to figure out the best way\n # to go about this...there should be an alternative to\n # overwriting, since these are not actually identical data (a\n # and b series of the same sites). Could consider mimicing the\n # directory tree rather than having all inp files in the same\n # top level directory <08-19-18, Luke Fairchild> #\n # if os.path.isfile(os.path.join(inp_dir, inp)):\n # overwrite_opt = input(\"\"\"The file {} already exists in your inp\n # directory. Do you want to overwrite it? Type 'all' after\n # your answer if you want to apply this to all conflicts.\n # (y/[N]/?all) \"\"\".format(inp))\n # if overwrite_opt.split(' ')[0].lower() in \"yes\":\n # overwrite = True\n # else:\n # overwrite = False\n # if overwrite_opt.split(' ')[1].lower()==\"all\":\n # a\n inp_copy = shutil.copy(inp, inp_dir)\n # set adequate permissions of the copied files\n os.chmod(inp_copy, 0o666)\n # copy conflicts\n # if os.path.split(inp)[1] in name_conflicts.keys():\n # conflict_files = name_conflicts[os.path.split(inp)[1]]\n # for i, conflict_file in enumerate(conflict_files):\n # conflict_name = os.path.basename(inp).replace('.inp', ascii_uppercase[i]+'.inp')\n # print('-I- Conflict file {} copied as {}'.format(inp,conflict_name))\n # inp_conflict = shutil.copy(conflict_file, os.path.join(inp_dir,conflict_name))\n # os.chmod(inp_conflict, 0o666)\n\n out_file.close()\n return all_inp_files\n except RuntimeError:\n raise RuntimeError(\n \"Recursion depth exceded, please use different working \"\n \"directory. There are too many sub-directeries to walk\")\n\n\ndef main():\n parser = argparse.ArgumentParser(description=\"\"\"Find all .inp files within a\n directory tree and copy to the inp_files repository designated for\n Demag GUI Autoupdate\"\"\",\n add_help=False,\n formatter_class=argparse.ArgumentDefaultsHelpFormatter)\n parser.add_argument('-h', action='help', help=\"\"\"show short (-h) or detailed\n (--help) help message\"\"\")\n parser.add_argument('-ds', '--data_src', nargs='?', help=\"\"\"Top-level\n directory in which to search for *.inp files\"\"\")\n parser.add_argument('-inp', '--inp_dir', nargs='?', help=\"\"\"Target for copied\n *.inp files\".\"\"\")\n parser.add_argument('--nocopy', action='store_true', help=\"\"\"Do not copy\n files\"\"\", default=False)\n if usr_configs_read:\n parser.set_defaults(data_src=data_src, inp_dir=inp_dir)\n # parser.add_argument('--help', dest='help_long', action='store_const',\n # const=True, help=argparse.SUPPRESS)\n args = vars(parser.parse_args())\n # if args['help_long']:\n # help(__name__)\n # sys.exit()\n # ds = args.pop('data_src')\n # do = args.pop('data_dir')\n # inpd = args.pop('inp_dir')\n\n # print(\"\"\"\\\n # Getting all .inp files with settings:\n # Top directory: {}\n # Main data directory: {}\n # Inp repository: {}\n # Copy files = {}\n # \"\"\".format(data_src,data_dir,inp_dir,str(not nocopy)))\n get_all_inp_files(**args)\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"dmgui_au/utilities/get_all_inp_files.py","file_name":"get_all_inp_files.py","file_ext":"py","file_size_in_byte":7844,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"332848192","text":"import matplotlib.pyplot as plt\nimport numpy as np\n\nimport module3\n\n\nRtulip = 9.6\nRcap = 12.1\nRintcanal = 29.0\nRextcanal = 33.5\nRnozzle = 12.815\nRnozzle_end = 22.0\nRpin = 11.5\nL0 = 72.0\nL1 = 20.5\nL2 = 10.0\nL3 = 70.0\nL4 = 22.05\nL5 = 30\n\n# Definition of the geometry lines\nListLines = [\n((0,Rtulip),(L0,Rtulip),1),\n((L0,Rtulip),(L0,Rcap),1),\n((L0,Rcap),(L0+L1,Rcap),2),\n((L0+L1,Rcap),(L0+L1,Rintcanal),3),\n((L0,Rintcanal),(L0+L1,Rintcanal),3),\n((L0,Rextcanal),(L0+L1+L2,Rextcanal),4),\n((L0+L1+L2,Rnozzle),(L0+L1+L2,Rextcanal),4),\n((L0+L1+L2,Rnozzle),(L0+L1+L2+L3,Rnozzle),5),\n((L0+L1+L2+L3,Rnozzle),(L0+L1+L2+L3+L4,Rnozzle_end),6),\n((L0+L1+L2+L3+L4,Rnozzle_end),(L0+L1+L2+L3+L4+L4,Rnozzle_end),7)\n]\n\n# Others geometrical parameters\nD_e_cap = 1\nD_e_nozzle = 1\nRnozzle_sortie = Rnozzle\nk_col = 0.05\n# Computed geometrical lengths\nD_l_cap=D_e_cap-D_e_cap**2/(2*Rcap);\nD_l_nozzle=D_e_nozzle-D_e_nozzle**2/(2*Rnozzle);\n\n\n############### Arc definition\nLX = L0+L1+L2+L3/4\n#LX = L0+L1+L2+L3+L4+L5\nprint(\"LX = \"+str(LX))\nRarc = 16\n###############\n\ndef computeArcDimensions(LX):\n Varc = Rarc**2*np.pi*(LX-L0)\n # Arc radius computation\n ArcRadius = [min(Rarc,Rcap-D_e_cap), min(Rarc,Rextcanal-D_e_nozzle), min(Rarc,Rnozzle-D_e_nozzle), min(Rarc,Rnozzle_sortie-D_e_nozzle), min(Rarc,Rnozzle_end-D_e_nozzle)]\n if printDebug: print(\"ArcRadius = \"+str(ArcRadius))\n # Arc lentgh computation\n ArcLenghts = [L0, min(max(LX-L0,0),L1+D_l_cap), min(max(LX-L0-L1-D_l_cap,0),L2-D_l_cap-D_l_nozzle), min(max(LX-L0-L1-L2+D_l_nozzle,0),(1-k_col)*L3+D_l_nozzle), min(max(LX-L0-L1-L2-(1-k_col)*L3,0),k_col*L3), max(min((ArcRadius[4]-ArcRadius[3])/(Rnozzle_end-Rnozzle_sortie)*L4,LX-L0-L1-L2-L3,L4),0), min(max(LX-L0-L1-L2-L3-(ArcRadius[4]-ArcRadius[3])/(Rnozzle_end-Rnozzle_sortie)*L4,0),L4), min(max(LX-L0-L1-L2-L3-L4,0),L5)]\n if printDebug: print(\"ArcLenghts = \"+str(ArcLenghts))\n ArcLenghtsCumsum = np.cumsum(ArcLenghts)\n if printDebug: print(\"ArcLenghtsCumsum = \"+str(ArcLenghtsCumsum))\n\n # Arc radius with zero length set to last arc radius (no segment)\n indEndArc = ArcLenghts.index(0)\n ArcRadius[indEndArc:] = [ArcRadius[indEndArc-1]]\n\n return ArcRadius, ArcLenghts, ArcLenghtsCumsum, Varc\n\ndef defineArcSegments(ArcLenghtsCumsum, ArcRadius):\n indexLen = [0, 1, 1, 2, 2, 3, 4, 5, 6, 7]\n CoordX = [ArcLenghtsCumsum[i] for i in indexLen]\n #print(CoordX)\n indexRad = [0, 0, 1, 1, 2, 2, 3, 4, 4, 4]\n CoordY = [ArcRadius[i] for i in indexRad]\n #print(CoordY)\n OrientationAngle = [0, 1, 0, 2, 0, 0, 3, 0, 0] # Orientation of the arc segment\n\n return CoordX, CoordY, OrientationAngle\n\ndef discretizeArcSegments(CoordX, CoordY, OrientationAngle):\n # Computing the arc segments lengths for discretization\n arcSegmentsLengths = []\n for i in range(len(CoordX)-1):\n arcSegmentsLengths.append(np.linalg.norm([CoordX[i+1]-CoordX[i],CoordY[i+1]-CoordY[i]]))\n if printDebug: print(\"arcSegmentsLengths = \"+str(arcSegmentsLengths))\n\n ############### Definition of the points for calculation ###############\n nbArcSegments = len([i for i in arcSegmentsLengths if i>0])\n RefX = []\n RefY = []\n RefAngle = []\n RefSource = []\n computationStep = int(1)\n for indArcSeg in range(len(arcSegmentsLengths)):\n if arcSegmentsLengths[indArcSeg]>0:\n scaleRef = int(np.floor(arcSegmentsLengths[indArcSeg]/computationStep))\n #RefX = RefX + list(range(CoordX[indArcSeg],CoordX[indArcSeg+1],computationStep))\n RefX = RefX + [a*(CoordX[indArcSeg+1]-CoordX[indArcSeg])/scaleRef+CoordX[indArcSeg] for a in list(range(scaleRef))]\n #RefY = RefY + list(range(CoordY[indArcSeg],CoordY[indArcSeg+1],computationStep))\n RefY = RefY + [a*(CoordY[indArcSeg+1]-CoordY[indArcSeg])/scaleRef+CoordY[indArcSeg] for a in list(range(scaleRef))]\n RefAngle = RefAngle + [OrientationAngle[indArcSeg] for a in list(range(scaleRef))]\n RefSource = RefSource + [indArcSeg for a in list(range(scaleRef))]\n nbArcPoints = len(RefX)\n if printDebug: print(\"RefX = \"+str(RefX))\n if printDebug: print(\"RefY = \"+str(RefY))\n if printDebug: print(\"RefAngle = \"+str(RefAngle))\n if printDebug: print(\"RefSource = \"+str(RefSource))\n if plotResults: plt.plot(RefX,RefY,'og')\n return nbArcSegments, RefX, RefY, RefAngle, RefSource\n\ndef oneArcCalculation(RefX, RefY, RefAngle, RefSource, nbArcPoints):\n import rayManagement, module3\n\n Results = np.zeros([nbArcPoints,7])\n\n # Ray definition\n AngleStep = int(20)\n lineLength = 2\n angleDivergent = np.rad2deg(np.arctan((Rnozzle_end-Rnozzle)/L4))\n # Tables defining the rays : 0:horizontal; 1:vertical_left; 2: vertical_right; 3:divergent_angle\n angleRange = list(range(AngleStep,180,AngleStep))\n OffsetX = lineLength*np.cos(np.deg2rad([[0+a for a in angleRange],[90+a for a in angleRange],[-90+a for a in angleRange],[angleDivergent+a for a in angleRange]]))\n OffsetY = lineLength*np.sin(np.deg2rad([[0+a for a in angleRange],[90+a for a in angleRange],[-90+a for a in angleRange],[angleDivergent+a for a in angleRange]]))\n\n # Computation for each arc point\n for indPt in range(nbArcPoints):\n # Definition of the emitting pt + directions\n RefPt = np.array([RefX[indPt],RefY[indPt]])\n ListRefPt2 = np.array([[RefPt[0]+i for i in OffsetX[RefAngle[indPt]]], [RefPt[1]+i for i in OffsetY[RefAngle[indPt]]]])\n\n # Computation for each direction\n for ind in range(ListRefPt2.shape[1]):\n RefLine = [RefPt,ListRefPt2[:,ind]]\n \n # Computing the intersections\n [Success, intersectionPt, intersectionLine, intersectionDist, otherIntersectionPt] = rayManagement.findClosestIntersection(RefLine, ListLines)\n \n if not Success:\n raise Exception(\"No intersection found, that was unexpected!\")\n Results[indPt,:] = np.array([RefSource[indPt], intersectionLine, intersectionDist, RefPt[0], RefPt[1], intersectionPt[0], intersectionPt[1]])\n\n if indPt % 4 == 0:\n # Ray\n if plotResults: plt.plot((RefLine[0][0],RefLine[1][0]),(RefLine[0][1],RefLine[1][1]))\n # Intersections\n if plotResults: plt.plot(otherIntersectionPt[:,0],otherIntersectionPt[:,1],'ob')\n if plotResults: plt.plot(intersectionPt[0],intersectionPt[1],'or')\n\n return Results\n\n\nif plotResults: plt.plot(CoordX,CoordY,'b')\nif plotResults: module3.PlotGeometry(ListLines)\n\n[ArcRadius, ArcLenghts, ArcLenghtsCumsum, Varc] = computeArcDimensions(LX)\n[CoordX, CoordY, OrientationAngle] = defineArcSegments(ArcLenghtsCumsum, ArcRadius)\n[nbArcSegments, RefX, RefY, RefAngle, RefSource] = discretizeArcSegments(CoordX, CoordY, OrientationAngle)\nResults = oneArcCalculation(RefX, RefY, RefAngle, RefSource, nbArcPoints)\n\nprint(\"-- ALMOST the end --\")\n\nif plotResults: plt.show()\n\nprint(\"-- The end --\")\n\n","sub_path":"testsArea.py","file_name":"testsArea.py","file_ext":"py","file_size_in_byte":6948,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"489271332","text":"import sys\nimport os\nimport numpy\n\nfrom PyQt5.Qt import *\nfrom PyQt5.QtGui import *\nfrom PyQt5.QtCore import *\nfrom PyQt5.QtWidgets import *\nfrom PyQt5 import uic\n\nfrom GeneticWorkerThread import GeneticWorkerThread\nfrom HillClimbingWorkerThread import HillClimbingWorkerThread\nfrom ParticleSwarmWorkerThread import ParticleSwarmWorkerThread\nfrom PLTWidget import PLTWidget\n\nclass GUI(QMainWindow):\n\n def __init__(self, width, height, title):\n super(GUI, self).__init__()\n uic.loadUi('ui.ui', self)\n self.start_button.clicked.connect(self.start)\n self.stop_button.clicked.connect(self.stop)\n self.start_button2.clicked.connect(self.start)\n self.stop_button2.clicked.connect(self.stop)\n self.start_button3.clicked.connect(self.start)\n self.stop_button3.clicked.connect(self.stop)\n self.genetic_thread = None\n self.hillclimbing_thread = None\n self.particleswarm_thread = None\n self.fitness_list = []\n self.mean_list = []\n self.std_list = []\n self.init_textedits()\n self.pltwidget.canvas.draw()\n self.show()\n\n def init_textedits(self):\n self.solution.setEnabled(False)\n self.solution2.setEnabled(False)\n self.matrix_edit.setText(\"4\")\n self.iterations_edit.setText(\"1000\")\n self.popsize_edit.setText(\"40\")\n self.mutation_edit.setText(\"0.2\")\n self.cutoff_edit.setText(\"0.8\")\n self.matrix_edit2.setText(\"4\")\n self.iterations_edit2.setText(\"1000\")\n self.matrix_edit3.setText(\"4\")\n self.iterations_edit3.setText(\"1000\")\n self.popsize_edit3.setText(\"40\")\n self.w_edit.setText(\"0.2\")\n self.c1_edit.setText(\"0.3\")\n self.c2_edit.setText(\"0.5\")\n\n def start(self):\n self.fitness_list = []\n self.mean_list = []\n self.std_list = []\n \n if self.tabWidget.currentIndex() == 0:\n try:\n self.finished.setText(\"\")\n self.best.setText(\"Best fitness so far:\")\n self.solution.setText(\"\")\n matrix_size = int(self.matrix_edit.toPlainText())\n iterations = int(self.iterations_edit.toPlainText())\n popsize = int(self.popsize_edit.toPlainText())\n mutation = float(self.mutation_edit.toPlainText())\n cutoff = float(self.cutoff_edit.toPlainText())\n self.genetic_thread = GeneticWorkerThread(30, iterations, popsize, matrix_size, mutation, cutoff)\n self.genetic_thread.run_finished.connect(self.update_graph1)\n self.genetic_thread.start()\n except ValueError:\n pass\n elif self.tabWidget.currentIndex() == 1:\n try:\n self.finished2.setText(\"\")\n self.best2.setText(\"Best fitness so far:\")\n self.solution2.setText(\"\")\n matrix_size = int(self.matrix_edit2.toPlainText())\n iterations = int(self.iterations_edit2.toPlainText())\n self.hillclimbing_thread = HillClimbingWorkerThread(30, iterations, matrix_size)\n self.hillclimbing_thread.run_finished.connect(self.update_graph2)\n self.hillclimbing_thread.start()\n except ValueError:\n pass\n elif self.tabWidget.currentIndex() == 2:\n try:\n self.finished3.setText(\"\")\n self.best3.setText(\"Best fitness so far:\")\n self.solution3.setText(\"\")\n matrix_size = int(self.matrix_edit3.toPlainText())\n iterations = int(self.iterations_edit3.toPlainText())\n popsize = int(self.popsize_edit3.toPlainText())\n w = float(self.w_edit.toPlainText())\n c1 = float(self.c1_edit.toPlainText())\n c2 = float(self.c2_edit.toPlainText())\n self.particleswarm_thread = ParticleSwarmWorkerThread(30, iterations, popsize, matrix_size, w, c1, c2)\n self.particleswarm_thread.run_finished.connect(self.update_graph3)\n self.particleswarm_thread.start()\n except ValueError:\n pass\n\n def stop(self):\n if self.tabWidget.currentIndex() == 0:\n self.genetic_thread.terminate()\n elif self.tabWidget.currentIndex() == 1:\n self.hillclimbing_thread.terminate()\n elif self.tabWidget.currentIndex() == 2:\n self.particleswarm_thread.terminate()\n\n def update_graph1(self, new_best, matrix):\n self.fitness_list.append(new_best)\n self.mean_list.append(numpy.average(self.fitness_list))\n self.std_list.append(numpy.std(self.fitness_list))\n self.pltwidget.canvas.axes.clear()\n self.pltwidget.canvas.axes.plot(self.fitness_list)\n self.pltwidget.canvas.axes.plot(self.mean_list)\n self.pltwidget.canvas.axes.plot(self.std_list)\n self.pltwidget.canvas.axes.legend(('Fitness', 'Mean', 'Standard Deviation'), loc='upper right')\n best = max(self.fitness_list)\n if(new_best >= best):\n self.solution.setText(str([str(x) for x in matrix.get_permutations()]))\n self.best.setText(\"Best fitness so far: \" + str(best))\n self.pltwidget.canvas.draw()\n if len(self.fitness_list) == 30:\n self.finished.setText(\"Finished!\")\n\n def update_graph2(self, new_best, matrix):\n self.fitness_list.append(new_best)\n self.mean_list.append(numpy.average(self.fitness_list))\n self.std_list.append(numpy.std(self.fitness_list))\n self.pltwidget2.canvas.axes.clear()\n self.pltwidget2.canvas.axes.plot(self.fitness_list)\n self.pltwidget2.canvas.axes.plot(self.mean_list)\n self.pltwidget2.canvas.axes.plot(self.std_list)\n self.pltwidget2.canvas.axes.legend(('Fitness', 'Mean', 'Standard Deviation'), loc='upper right')\n best = max(self.fitness_list)\n if(new_best >= best):\n self.solution2.setText(str([str(x) for x in matrix.get_permutations()]))\n self.best2.setText(\"Best fitness so far: \" + str(best))\n self.pltwidget2.canvas.draw()\n if len(self.fitness_list) == 30:\n self.finished2.setText(\"Finished!\")\n\n def update_graph3(self, new_best, matrix):\n self.fitness_list.append(new_best)\n self.mean_list.append(numpy.average(self.fitness_list))\n self.std_list.append(numpy.std(self.fitness_list))\n self.pltwidget3.canvas.axes.clear()\n self.pltwidget3.canvas.axes.plot(self.fitness_list)\n self.pltwidget3.canvas.axes.plot(self.mean_list)\n self.pltwidget3.canvas.axes.plot(self.std_list)\n self.pltwidget3.canvas.axes.legend(('Fitness', 'Mean', 'Standard Deviation'), loc='upper right')\n best = max(self.fitness_list)\n if(new_best >= best):\n self.solution3.setText(str([str(x) for x in matrix.get_permutations()]))\n self.best3.setText(\"Best fitness so far: \" + str(best))\n self.pltwidget3.canvas.draw()\n if len(self.fitness_list) == 30:\n self.finished3.setText(\"Finished!\")\n\n","sub_path":"Artificial Intelligence/Lab3/GUI.py","file_name":"GUI.py","file_ext":"py","file_size_in_byte":7156,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"24882439","text":"class Solution(object):\n\tdef threeSum(self, nums):\n\t\tans = []\n\t\tnums.sort()\n\t\tfor i in range(len(nums)-2):\n\t\t\ta = nums[i]\n\t\t\tif i>0 and nums[i-1]==nums[i]: # To ensure the unique triplets\n\t\t\t\tcontinue\n\t\t\tl,r = i+1,len(nums)-1\n\t\t\twhile l 0:\n\t\t\t\t\tr -= 1\n\t\t\t\telse:\n\t\t\t\t\tans.append([nums[i],nums[l],nums[r]])\n\t\t\t\t\ta,b = nums[l],nums[r]\n\t\t\t\t\twhile l int:\n people.sort(reverse = True)\n total = 0\n fat, skinny = 0, len(people)-1\n while fat <= skinny:\n if people[fat] + people[skinny] <= limit:\n skinny -=1\n fat += 1\n total +=1\n return total","sub_path":"lc/review_881.BoatsToSavePeople.py","file_name":"review_881.BoatsToSavePeople.py","file_ext":"py","file_size_in_byte":1202,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"353138754","text":"from locale import localeconv\nfrom reinforces_intrinsic.rephraser import transition\nfrom reinforces_intrinsic.reinforce_utils import *\nfrom reinforces_intrinsic import rephraser\nfrom reinforces_intrinsic.Annunciator import TransScorer, pad_negatives\nfrom reinforces_intrinsic.ReplayBuffer import SharedReplayBuffer\nfrom reinforces_intrinsic.trans_env import Translate_Env\nfrom reinforces_intrinsic.trans_env import build_translate_model\nfrom src.utils.logging import *\nfrom src.utils.common_utils import *\nfrom src.data.dataset import Dataset, TextLineDataset, ZipDataset\nfrom src.data.data_iterator import DataIterator\nfrom torch.utils.tensorboard import SummaryWriter\n\nimport argparse\nimport torch\nimport numpy as np\nimport torch.multiprocessing as _mp\n\nos.system('export PYTHONWARNINGS=\"ignore:semaphore_tracker:UserWarning\" ')\n\nparser = argparse.ArgumentParser()\nparser.add_argument(\"--n\", type=int, default=1,\n help=\"parallel attacker process (default as 1)\")\nparser.add_argument(\"--config_path\", type=str,\n default=\"./configs/cwmt_zh2en_reinforce.yaml\",\n help=\"the path to reinforcement config file.\")\nparser.add_argument(\"--save_to\", type=str, default=\"./reinforces/reinforce_tf_zh2en_log\",\n help=\"the path for model-saving and log saving.\")\nparser.add_argument(\"--action_roll_steps\", type=int, default=35,\n help=\"training rolling steps (default as 35)\")\nparser.add_argument(\"--max_episodes\", type=int, default=5000000,\n help=\"maximum environment episode for learning (default as 500k)\")\nparser.add_argument(\"--use_gpu\", action=\"store_true\", default=False,\n help=\"Whether to use GPU.(default as false)\")\nparser.add_argument(\"--seed\", type=int, default=1,\n help=\"random seed (default as 1)\")\n\n\ndef run():\n # default actor threads as 1\n os.environ[\"OMP_NUM_THREADS\"] = \"1\"\n mp = _mp.get_context('spawn')\n\n args = parser.parse_args()\n if not os.path.exists(args.save_to):\n os.mkdir(args.save_to)\n # load reinforce configs\n with open(args.config_path, \"r\") as f, \\\n open(os.path.join(args.save_to, \"current_reinforce.yaml\"), \"w\") as current_configs:\n INFO(\"load reinforce configures\")\n configs = yaml.load(f, Loader=yaml.FullLoader)\n # save current configs to the save_path\n yaml.dump(configs, current_configs)\n reinforce_configs = configs[\"reinforce_configs\"]\n agent_configs = configs[\"agent_configs\"]\n\n # the Global variable of USE_GPU is mainly used for environments\n GlobalNames.SEED = reinforce_configs[\"seed\"]\n GlobalNames.USE_GPU = args.use_gpu\n torch.manual_seed(GlobalNames.SEED)\n\n # build vocabulary and data iterator for env\n with open(reinforce_configs[\"victim_configs\"], \"r\") as victim_f:\n INFO(\"open victim configs at %s\" % reinforce_configs[\"victim_configs\"])\n victim_configs = yaml.load(victim_f, Loader=yaml.FullLoader)\n\n data_configs = victim_configs[\"data_configs\"]\n src_vocab = Vocabulary(**data_configs[\"vocabularies\"][0])\n trg_vocab = Vocabulary(**data_configs[\"vocabularies\"][1])\n data_set = ZipDataset(\n TextLineDataset(\n data_path=data_configs[\"train_data\"][0],\n vocabulary=src_vocab, max_len=data_configs[\"max_len\"][0],min_len=30),\n TextLineDataset(\n data_path=data_configs[\"train_data\"][1],\n vocabulary=trg_vocab, max_len=data_configs[\"max_len\"][1], min_len=30),\n shuffle=reinforce_configs[\"shuffle\"]\n ) # we build the parallel data sets and iterate inside a thread\n # collect range of action space: (use_max_dist=True means max range of delta ot UNK)\n _, _, step_dist, max_dist = load_or_extract_near_vocab(\n config_path=reinforce_configs[\"victim_configs\"],\n model_path=reinforce_configs[\"victim_model\"],\n init_perturb_rate=reinforce_configs[\"init_perturb_rate\"],\n save_to=os.path.join(args.save_to, \"near_vocab\"),\n save_to_full=os.path.join(args.save_to, \"full_near_vocab\"),\n top_reserve=10, emit_as_id=True)\n\n # build global SACAgent for the final policy (on cpu)\n victim_model_path = reinforce_configs[\"victim_model\"]\n _, trg_emb, _ = build_translate_model(\n victim_configs, victim_model_path,\n vocab_src=src_vocab, vocab_trg=trg_vocab,\n device=\"cpu\") # create trg_vocab_emb for global model\n global_agent = rephraser.SACAgent(\n step_dist=step_dist,\n max_dist=max_dist,\n agent_configs=agent_configs,\n is_global_model=True,\n device=\"cpu\",\n trg_vocab_emb=trg_emb,\n save_to=args.save_to,\n num_kept_checkpoints=reinforce_configs[\"num_kept_checkpoints\"]\n )\n # load global ckp (only for the AC parameters) if needed\n global_step = global_agent.load_model()\n print(\"global_step:\", global_step)\n if global_step != 0:\n INFO(\"restarting at step %d\"%global_step)\n else: # save the initial model\n global_agent.save_model(global_step)\n global_agent.save_model(save_to_final=args.save_to)\n\n global_replay_buffer = SharedReplayBuffer(\n max_sen_len=data_configs[\"max_len\"][0],\n state_dim=victim_configs[\"model_configs\"][\"d_word_vec\"],\n action_dim=victim_configs[\"model_configs\"][\"d_word_vec\"],\n capacity=reinforce_configs[\"replay_buffer_capacity\"])\n\n # move global objects to shared memory\n global_replay_buffer.share_memory()\n global_agent.share_memory()\n\n # collect available devices and distribute env on the available gpu\n if args.use_gpu:\n device = \"cuda\"\n devices = []\n for i in range(torch.cuda.device_count()):\n devices += [\"cuda:%d\" % i]\n print(\"available gpus:\", devices)\n else:\n device = \"cpu\"\n devices = [device]\n\n # initialize global parameters for the current training trial\n global_step_lock = mp.Lock()\n global_step_counter = mp.Value(\"i\", global_step) # \"i is the type code for c_int\"\n\n # train_thread(0, device, args,\n # reinforce_configs, agent_configs,\n # src_vocab, trg_vocab, data_set,\n # global_agent, global_replay_buffer,\n # global_step_counter, global_step_lock)\n\n # valid_thread(device, args,\n # reinforce_configs, agent_configs,\n # src_vocab, trg_vocab, data_set,\n # global_agent, global_replay_buffer,\n # global_step_counter, global_step_lock)\n\n # build multi thread for learning and validation\n process = []\n for rank in range(args.n):\n print(\"initialize training thread on cuda:%d\" % (rank+1))\n p=mp.Process(\n target=train_thread,\n args=(rank, \"cuda:%d\"%(rank+1), args,\n reinforce_configs, agent_configs,\n src_vocab, trg_vocab, data_set,\n global_agent, global_replay_buffer,\n global_step_counter, global_step_lock)\n )\n p.start()\n process.append(p)\n # run the dev thread for initiation\n print(\"initialize dev thread on cuda:0\")\n p = mp.Process(\n target=valid_thread,\n args=(\"cuda:0\", args,\n reinforce_configs, agent_configs,\n src_vocab, trg_vocab, data_set,\n global_agent, global_replay_buffer,\n global_step_counter, global_step_lock)\n )\n p.start()\n process.append(p)\n for p in process:\n p.join()\n\ndef train_thread(\n rank, device, args,\n reinforce_configs, local_agent_configs,\n src_vocab, trg_vocab, data_set,\n global_SACAgent, global_replay_buffer,\n global_step_counter, global_step_lock):\n \"\"\"\n build training thread for a local SACAgent on gpu device\n provide parameter soft-updates for the global_models.\n \"\"\"\n GlobalNames.USE_GPU = args.use_gpu\n GlobalNames.SEED = reinforce_configs[\"seed\"]\n torch.manual_seed(GlobalNames.SEED + rank)\n # build local SACAgent\n with open(reinforce_configs[\"victim_configs\"], \"r\") as victim_f:\n victim_configs = yaml.load(victim_f, Loader=yaml.FullLoader)\n local_summary_writer = SummaryWriter(\n log_dir=os.path.join(args.save_to, \"train_env%d\" % rank))\n\n _, _, step_dist, max_dist = load_or_extract_near_vocab(\n config_path=reinforce_configs[\"victim_configs\"],\n model_path=reinforce_configs[\"victim_model\"],\n init_perturb_rate=reinforce_configs[\"init_perturb_rate\"],\n save_to=os.path.join(args.save_to, \"near_vocab\"),\n save_to_full=os.path.join(args.save_to, \"full_near_vocab\"),\n top_reserve=10,\n emit_as_id=True)\n # max_perturbation_round = int(max_dist/step_dist)+1\n max_perturbation_round = local_agent_configs[\"max_perturbation_round\"]\n\n # build environment\n reinforce_iterator = DataIterator(\n dataset=data_set, batch_size=reinforce_configs[\"batch_size\"],\n use_bucket=True, buffer_size=reinforce_configs[\"buffer_size\"],\n numbering=True)\n local_data_iterator = reinforce_iterator.build_generator()\n local_env = Translate_Env(\n reinforce_configs=reinforce_configs,\n src_vocab=src_vocab, trg_vocab=trg_vocab,\n data_iterator=local_data_iterator,\n save_to=args.save_to, device=device)\n episode_count = 0 # a batch of sentences as an episode & learning episodes\n # build local_agent\n local_agent = rephraser.SACAgent(\n step_dist=step_dist,\n max_dist=max_dist,\n agent_configs=local_agent_configs,\n device=device,\n trg_vocab_emb=local_env.trg_emb,\n save_to=os.path.join(args.save_to),\n num_kept_checkpoints=reinforce_configs[\"num_kept_checkpoints\"]\n )\n\n with global_step_lock:\n # initiate local agent update steps\n local_step = global_step_counter.value\n patience_t = reinforce_configs[\"patience\"]\n min_loss = 99999.\n k=int(max_perturbation_round/2) # perturbation round counter\n while k < max_perturbation_round:\n INFO(\"max perturbation round=%d\"%k)\n while True: # infinite loop of data set iterator (epoch)\n # we will continue with a new iterator with refreshed environments\n # whenever the last iterator breaks with \"StopIteration\"\n rephraser_iterator = reinforce_iterator.build_generator()\n local_env.reset_data_iter(rephraser_iterator)\n try:\n while True: # loop training episodes with new batch of sentence\n # the environment will scale up perturbation by an actor for exploration\n local_env.init_state()\n for perturbation_round_counter in range(k):\n episode_length = 0 # the rollout steps\n episode_rewards = np.array([0.] * local_env.x_emb.shape[0])\n done = True # whether the episode is finished & should reset episode with new batch\n local_agent = local_agent.to(device).train() # switch the agent to training mode\n if done: # restart a new perturbation round\n INFO(\"sync from global agent (dynamics critic & feature_enc)\")\n local_agent.sync_from(global_SACAgent)\n local_agent.to(device)\n local_env.reset()\n local_agent = local_agent.train()\n done = False\n\n obs, masks, rephrase_positions, _, seqs_y = local_env.get_state()\n for i in range(args.action_roll_steps):\n # sample actions for buffer collection (start with fully random)\n if global_replay_buffer.size() < local_agent_configs[\"learn_batch_size\"]*(rank+1) or \\\n local_step%(local_agent_configs[\"learn_batch_size\"])<=50:\n # fast random actions in the **action_space** as exploration\n actions = local_env.step_dist * np.random.randn(obs.shape[0], obs.shape[2])\n actions = torch.tensor(actions, dtype=torch.float32, device=device)\n else: # explore and exploit\n local_agent.train(False) # set to validation mode\n sliced_emb = rephraser.slice_by_indices(obs, rephrase_positions, device=device)\n s_t = torch.cat([\n local_agent.feature_encoder(o_t=obs, x_pad_indicator=1.-masks),\n local_agent.feature_encoder(o_t=sliced_emb)\n ], dim=-1)\n actions, _ = local_agent.noiser.sample_normal(\n s_t, reparamization=False)\n local_agent.train()\n \n # able to update agent with current buffer, else first update the dynamics\n if global_replay_buffer.size() >= local_agent_configs[\"learn_batch_size\"]*(rank+1):\n local_agent.train()\n dynamic_loss, denoise_loss = local_agent.update_local_net(\n local_agent_configs,\n global_replay_buffer,\n target_agent=global_SACAgent.to(device),\n update_step=local_step,\n discount_factor=reinforce_configs[\"gamma\"],\n summary_writer=local_summary_writer\n )\n if dynamic_loss < min_loss:\n min_loss = dynamic_loss\n patience_t = reinforce_configs[\"patience\"]\n else:\n patience_t -= 1\n\n global_SACAgent.to(\"cpu\") # update global model\n if local_step % local_agent_configs[\"soft_update_freq\"] == 0:\n with global_step_lock:\n INFO(\"update global by device: %s\" % device)\n global_step_counter.value += 1\n local_agent.soft_update_target_net(global_SACAgent, reinforce_configs[\"tau\"])\n\n if global_step_counter.value % reinforce_configs[\"save_freq\"] == 0:\n INFO(\"save global model %d by device: %s\"%(global_step_counter.value, device))\n with global_SACAgent.soft_update_lock:\n global_SACAgent.save_model(global_step_counter.value)\n # save final global model (as object)\n global_SACAgent.save_model(save_to_final=args.save_to)\n INFO(\"finish local update: %2f\"%global_SACAgent.dynamics_trust_region)\n elif global_replay_buffer.size() >= local_agent_configs[\"learn_batch_size\"]: \n # update dynamics\n INFO(\"only update dynamics\")\n local_agent.train()\n train_obs, train_masks, _, _, \\\n _, _, _, _, train_seqs_y = global_replay_buffer.sample(\n local_agent_configs[\"learn_batch_size\"], device=device)\n local_agent.update_dynamics(\n train_obs, train_masks, train_seqs_y, \n local_summary_writer,update_step=local_step)\n global_SACAgent.to(\"cpu\")\n local_agent.to(\"cpu\")\n with global_step_lock, global_SACAgent.soft_update_lock:\n for param, target_param in zip(local_agent.feature_encoder.parameters(), global_SACAgent.feature_encoder.parameters()):\n target_param.data.copy_(0.01 * param.data + (1-0.01) * target_param.data)\n # soft update dynamics\n for param, target_param in zip(local_agent.dynamics_module.parameters(), global_SACAgent.dynamics_module.parameters()):\n target_param.data.copy_(0.01 * param.data + (1-0.01) * target_param.data)\n local_agent.to(device)\n\n local_step += 1\n _, rewards, _ = local_env.step(actions)\n local_summary_writer.add_scalar(\n \"overall_mean\",\n abs(local_env.x_emb[:, local_env.index-1, :] - local_env.initial_emb[:, local_env.index-1, :]).mean(),\n local_step)\n new_obs, _, new_rephrase_positions, survival_signals, _ = local_env.get_state()\n\n episode_rewards = [episode_rewards[t]+rewards[t] for t in range(obs.shape[0])]\n survival_signals_cpu = survival_signals.cpu().numpy().tolist()\n survival_and_no_max = np.array(\n [0 if episode_length == local_env.sent_len[t]\n else survival_signals_cpu[t][0]\n for t in range(obs.shape[0])]\n )\n INFO(\"step %d of episode:%d, r:%f, device:%s\" % (i, episode_count, np.array(episode_rewards).mean(), actions.device))\n # add the tensor variables to the replay buffer,\n # learn by rollout rewards or episode reward accumulated\n\n # update the overall signals for rollout\n if 1 in survival_signals:\n done = False\n else:\n done = True\n\n if local_env.index == obs.shape[1]-1:\n # note that the environment index will increase beyond the shape\n # no need to push the buffer and break from the rollout\n done = True\n break\n\n # survival_signals.shape, torch.tensor(survival_and_no_max).shape)\n INFO(\"buffer writing:\")\n #cleanse unecessary experience to save time\n invalid_sample = []\n if local_env.index>min(local_env.sent_len):\n for i in range(obs.shape[0]): # for every record\n if local_env.index > local_env.sent_len[i]:\n invalid_sample.append(i)\n # the trust region is still recorded to measure the deviation of experience\n global_replay_buffer.add(\n obs=obs,\n masks=masks,\n actions=actions,\n rephrase_positions=rephrase_positions,\n rewards=torch.tensor(rewards, dtype=torch.float32).unsqueeze(dim=-1),\n survival_signals=survival_signals,\n survive_and_no_max=torch.tensor(survival_and_no_max, dtype=torch.float32).unsqueeze(dim=-1),\n trs=torch.tensor(\n np.array([global_SACAgent.dynamics_trust_region] *\n masks.shape[0]), dtype=torch.float32).unsqueeze(dim=-1),\n refs_y=seqs_y,\n invalid_sample=invalid_sample\n )\n INFO(\"buffer updated, size=%d\" % global_replay_buffer.size())\n episode_length += 1\n obs = new_obs\n rephrase_positions = new_rephrase_positions\n \n episode_count += 1\n # check to expand the perturbation range and reset patience if needed\n if patience_t == 0:\n INFO(\"perturbation expanded\")\n k+=1\n patience_t = reinforce_configs[\"patience\"]\n if k > max_perturbation_round or episode_count > args.max_episodes:\n WARN(\"maximum patience & training step reached. Thread stop\")\n return\n\n except StopIteration:\n INFO(\"finish one training epoch, reset data_iterator\")\n continue\n\n\ndef valid_thread(\n device, args,\n reinforce_configs, local_agent_configs,\n src_vocab, trg_vocab, data_set,\n global_SACAgent, global_replay_buffer,\n global_step_counter, global_step_lock):\n \"\"\"\n build validation thread to check global SACAgent tests and update buffer\n \"\"\"\n GlobalNames.USE_GPU = args.use_gpu\n GlobalNames.SEED = reinforce_configs[\"seed\"]\n torch.manual_seed(GlobalNames.SEED)\n\n # build local agent and sync from the global model to avoid deadlock\n with open(reinforce_configs[\"victim_configs\"], \"r\") as victim_f:\n victim_configs = yaml.load(victim_f, Loader=yaml.FullLoader)\n local_summary_writer = SummaryWriter(\n log_dir=os.path.join(args.save_to, \"valid_env\"))\n\n _, _, step_dist, max_dist = load_or_extract_near_vocab(\n config_path=reinforce_configs[\"victim_configs\"],\n model_path=reinforce_configs[\"victim_model\"],\n init_perturb_rate=reinforce_configs[\"init_perturb_rate\"],\n save_to=os.path.join(args.save_to, \"near_vocab\"),\n save_to_full=os.path.join(args.save_to, \"full_near_vocab\"),\n top_reserve=10,\n emit_as_id=True)\n # max_perturbation_round = int(max_dist/step_dist)+1\n max_perturbation_round = local_agent_configs[\"max_perturbation_round\"]\n # build an independent dev env\n reinforce_iterator = DataIterator(\n dataset=data_set, batch_size=reinforce_configs[\"batch_size\"],\n use_bucket=True, buffer_size=reinforce_configs[\"buffer_size\"],\n numbering=True)\n local_data_iterator = reinforce_iterator.build_generator()\n local_env = Translate_Env(\n reinforce_configs=reinforce_configs,\n src_vocab=src_vocab, trg_vocab=trg_vocab,\n data_iterator=local_data_iterator,\n save_to=args.save_to, device=device)\n # build local_agent\n local_agent = rephraser.SACAgent(\n step_dist=step_dist,\n max_dist=max_dist,\n agent_configs=local_agent_configs,\n device=device,\n trg_vocab_emb=local_env.trg_emb,\n save_to=os.path.join(args.save_to),\n num_kept_checkpoints=reinforce_configs[\"num_kept_checkpoints\"]\n )\n with global_step_lock:\n # sync local agent update steps\n local_step = global_step_counter.value\n\n # initiate agent policy\n episode_count = 0 # determines the global sync\n INFO(\"valid w/ max perturbation round=%d\"%max_perturbation_round)\n while True: # inifinite loop of dataset iterator\n rephraser_iterator = reinforce_iterator.build_generator()\n local_env.reset_data_iter(rephraser_iterator)\n try:\n while True: # inifinite loop of the episodes for validation\n # prepare a new episode, pull from the global parameters for validation\n local_agent.sync_from(global_SACAgent)\n local_agent = local_agent.to(device).train(False)\n local_env.init_state()\n for perturbation_round in range(max_perturbation_round):\n local_env.reset() # reset environment attributes for new round of perturbation\n obs, masks, rephrase_positions, _, seqs_y = local_env.get_state()\n episode_rewards = np.array([0.] * obs.shape[0])\n episode_length = 0\n done = False\n while not done:\n with global_step_lock:\n local_step = global_step_counter.value\n obs, masks, rephrase_positions, _, _ = local_env.get_state()\n sliced_emb = rephraser.slice_by_indices(obs, rephrase_positions, device=device)\n s_t = torch.cat([\n local_agent.feature_encoder(o_t=obs, x_pad_indicator=1.-masks),\n local_agent.feature_encoder(o_t=sliced_emb)\n ], dim=-1)\n # denoiser validation w/o reparamization in validation\n actions, _ = local_agent.denoiser.act(s_t)\n # base_act, _ = local_agent.noiser.act(s_t)\n # q1,q2 = local_agent.critic(s_t, actions)\n # base_q1, base_q2 = local_agent.critic(s_t, base_act)\n # critique = torch.min(q1, q2) - torch.min(base_q1, base_q2)\n # denoiser achieves greater degradation expectation, collect for training\n actions_mask = masks[:, episode_length+1].unsqueeze(dim=1) #(critique).gt(0).int()*\n actions *= actions_mask\n _, rewards, _ = local_env.step(actions)\n local_summary_writer.add_scalar(\n \"overall_mean\",\n abs(local_env.x_emb[:, local_env.index - 1, :] -\n local_env.initial_emb[:, local_env.index - 1, :]).mean(),\n local_step\n )\n next_obs = transition(obs, masks, actions, rephrase_positions)\n encoded_o_t = local_agent.feature_encoder(o_t=obs, x_pad_indicator=1.-masks)\n encoded_next_o_t = local_agent.feature_encoder(o_t=next_obs, x_pad_indicator=1.-masks)\n padded_y, positive_indicator = pad_negatives(\n refs=seqs_y.cpu().numpy(), sample_amount=local_agent.dynamics_module.sample_amount,\n vocab_size=local_agent.dynamics_module.trg_vocab_emb.embeddings.num_embeddings,\n near_trg_dict=local_agent.dynamics_module.near_trg_dict)\n padded_y = encoded_o_t.new_tensor(padded_y).long()\n positive_indicator = encoded_o_t.new_tensor(positive_indicator)\n r_s = local_agent.r_s_weight * (\n local_agent.dynamics_module.get_density_score(encoded_next_o_t, padded_y, positive_indicator)-\n local_agent.dynamics_module.get_density_score(encoded_o_t, padded_y, positive_indicator)\n ).detach()\n r_s = (r_s)/(r_s.std()+1e-5)\n r_s = r_s.cpu().tolist()\n episode_rewards = [episode_rewards[t]+r_s[t] for t in range(obs.shape[0])] # rewards[i] is 0 or metric variant\n new_obs, _, _, survival_signals, _ = local_env.get_state()\n survival_signals_cpu = survival_signals.cpu().numpy().tolist()\n survival_and_no_max = np.array(\n [0 if episode_length == local_env.sent_len[t]\n else survival_signals_cpu[t][0]\n for t in range(obs.shape[0])])\n INFO(\"step %d survive and no max:%d, %s\"%(episode_length, survival_and_no_max.sum(), actions.device))\n local_step += 1\n if 1 in survival_signals:\n done = False\n else: # finished episode\n episode_count += 1\n done = True\n if done: # skip the final step\n break\n INFO(\"write buffer begin\")\n invalid_sample = []\n if local_env.index > min(local_env.sent_len):\n for i in range(obs.shape[0]): # for every record\n if local_env.index > local_env.sent_len[i]:\n invalid_sample.append(i)\n # survival_signals.shape, torch.tensor(survival_and_no_max).shape)\n global_replay_buffer.add(\n obs=obs,\n masks=masks,\n actions=actions,\n rephrase_positions=rephrase_positions,\n rewards=torch.tensor(rewards, dtype=torch.float32).unsqueeze(dim=-1),\n survival_signals=survival_signals,\n survive_and_no_max=torch.tensor(survival_and_no_max, dtype=torch.float32).unsqueeze(dim=-1),\n trs=torch.tensor(\n np.array([global_SACAgent.dynamics_trust_region] *\n masks.shape[0]), dtype=torch.float32).unsqueeze(dim=-1),\n refs_y=seqs_y,\n invalid_sample=invalid_sample\n )\n INFO(\"write buffer end, size=%d\"%global_replay_buffer.size())\n episode_length += 1\n INFO(\"mean episode rewards on batch:%f\"%np.array(episode_rewards).mean())\n # calculate episodic metric variant\n perturbed_results = local_env.translate()\n episodic_delta_metric = []\n for i, sent in enumerate(local_env.seqs_y):\n episodic_delta_metric.append(\n local_env.metric.corpus_score(\n [local_env.trg_vocab.ids2sent(perturbed_results[i])],\n [[local_env.trg_vocab.ids2sent(sent)]] ).score - 100*local_env.origin_metric[i]\n )\n local_summary_writer.add_scalar(\n \"dev_metric_variant\",\n scalar_value=np.array(episodic_delta_metric)[-1],\n global_step=global_step_counter.value\n )\n local_summary_writer.add_scalar(\n \"dev_episode_r\",\n scalar_value=np.array(episode_rewards)[-1],\n global_step=global_step_counter.value)\n\n except StopIteration:\n INFO(\"finish one validation epoch, reset data_iterator\")\n continue\n\n\nif __name__ == \"__main__\":\n run()\n\n","sub_path":"reinforces_intrinsic/main_rephrase.py","file_name":"main_rephrase.py","file_ext":"py","file_size_in_byte":31453,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"324857130","text":"from __future__ import absolute_import\nfrom cassandra.cluster import Cluster\nfrom cassandra.cqlengine import connection\nfrom cassandra.query import dict_factory\nfrom cassandra.policies import RetryPolicy, ConstantReconnectionPolicy\nfrom cassandra.cqlengine.management import sync_table\nfrom cassandra.cqlengine.management import drop_table\nfrom frontera.core.components import DistributedBackend\nfrom frontera.contrib.backends import CommonBackend\nfrom frontera.contrib.backends.cassandra.components import Metadata, Queue, States\nfrom frontera.utils.misc import load_object\nimport logging\n\n\nclass CassandraBackend(CommonBackend):\n def __init__(self, manager):\n self.manager = manager\n settings = manager.settings\n cluster_ips = settings.get('CASSANDRABACKEND_CLUSTER_IPS')\n cluster_port = settings.get('CASSANDRABACKEND_CLUSTER_PORT')\n drop_all_tables = settings.get('CASSANDRABACKEND_DROP_ALL_TABLES')\n keyspace = settings.get('CASSANDRABACKEND_KEYSPACE')\n keyspace_create = settings.get('CASSANDRABACKEND_CREATE_KEYSPACE_IF_NOT_EXISTS')\n models = settings.get('CASSANDRABACKEND_MODELS')\n crawl_id = settings.get('CASSANDRABACKEND_CRAWL_ID')\n generate_stats = settings.get('CASSANDRABACKEND_GENERATE_STATS')\n\n self.models = dict([(name, load_object(klass)) for name, klass in models.items()])\n\n self.cluster = Cluster(\n contact_points=cluster_ips,\n port=cluster_port,\n compression=True,\n default_retry_policy=RetryPolicy(),\n reconnection_policy=ConstantReconnectionPolicy(10, 100)\n )\n\n self.session = self.cluster.connect()\n self.session.row_factory = dict_factory\n self.session.encoder.mapping[dict] = self.session.encoder.cql_encode_map_collection\n self.crawl_id = crawl_id\n self.generate_stats = generate_stats\n\n if keyspace_create:\n query = \"\"\"CREATE KEYSPACE IF NOT EXISTS \\\"%s\\\"\n WITH replication = {'class': 'SimpleStrategy', 'replication_factor' : 3}\"\"\" % (keyspace, )\n self.session.execute(query)\n\n self.session.set_keyspace(keyspace)\n\n connection.set_session(self.session)\n\n if drop_all_tables:\n for key, value in self.models.iteritems():\n drop_table(value)\n\n for key, value in self.models.iteritems():\n if (self.generate_stats is False and key != 'CrawlStatsModel') or self.generate_stats is True:\n sync_table(value)\n\n self._metadata = Metadata(self.session, self.models['MetadataModel'], self.crawl_id, self.generate_stats)\n self._states = States(self.session, self.models['StateModel'],\n settings.get('STATE_CACHE_SIZE_LIMIT'), self.crawl_id)\n self._queue = self._create_queue(settings)\n\n def frontier_stop(self):\n self.states.flush()\n self.session.shutdown()\n\n def _create_queue(self, settings):\n return Queue(self.session, self.models['QueueModel'], settings.get('SPIDER_FEED_PARTITIONS'),\n self.crawl_id, self.generate_stats)\n\n @property\n def queue(self):\n return self._queue\n\n @property\n def metadata(self):\n return self._metadata\n\n @property\n def states(self):\n return self._states\n\nBASE = CassandraBackend\n\n\nclass Distributed(DistributedBackend):\n def __init__(self, manager):\n self.manager = manager\n settings = manager.settings\n cluster_ips = settings.get('CASSANDRABACKEND_CLUSTER_IPS') # Format: ['192.168.0.1', '192.168.0.2']\n cluster_port = settings.get('CASSANDRABACKEND_CLUSTER_PORT')\n keyspace = settings.get('CASSANDRABACKEND_KEYSPACE')\n keyspace_create = settings.get('CASSANDRABACKEND_CREATE_KEYSPACE_IF_NOT_EXISTS') # Default: true\n models = settings.get('CASSANDRABACKEND_MODELS')\n\n self.cluster = Cluster(cluster_ips, cluster_port)\n self.models = dict([(name, load_object(klass)) for name, klass in models.items()])\n\n self.session = self.cluster.connect()\n self.session.row_factory = dict_factory\n\n if keyspace_create:\n query = \"\"\"CREATE KEYSPACE IF NOT EXISTS \\\"%s\\\"\n WITH replication = {'class': 'SimpleStrategy', 'replication_factor' : 3}\"\"\" % (keyspace, )\n self.session.execute(query)\n self.session.set_keyspace(keyspace)\n connection.set_session(self.session)\n\n self._metadata = None\n self._queue = None\n self._states = None\n\n @classmethod\n def strategy_worker(cls, manager):\n b = cls(manager)\n settings = manager.settings\n drop_all_tables = settings.get('CASSANDRABACKEND_DROP_ALL_TABLES')\n crawl_id = settings.get('CASSANDRABACKEND_CRAWL_ID')\n model = b.models['StateModel']\n\n if drop_all_tables:\n drop_table(model)\n\n sync_table(model)\n\n b._states = States(b.session, model,\n settings.get('STATE_CACHE_SIZE_LIMIT'), crawl_id)\n return b\n\n @classmethod\n def db_worker(cls, manager):\n b = cls(manager)\n settings = manager.settings\n drop = settings.get('CASSANDRABACKEND_DROP_ALL_TABLES')\n crawl_id = settings.get('CASSANDRABACKEND_CRAWL_ID')\n generate_stats = settings.get('CASSANDRABACKEND_GENERATE_STATS')\n\n metadata_m = b.models['MetadataModel']\n queue_m = b.models['QueueModel']\n stats_m = b.models['CrawlStatsModel']\n if drop:\n drop_table(metadata_m)\n drop_table(queue_m)\n drop_table(stats_m)\n\n sync_table(metadata_m)\n sync_table(queue_m)\n if generate_stats is True:\n sync_table(stats_m)\n\n b._metadata = Metadata(b.session, metadata_m, crawl_id, generate_stats)\n b._queue = Queue(b.session, queue_m, settings.get('SPIDER_FEED_PARTITIONS'), crawl_id, generate_stats)\n return b\n\n @property\n def queue(self):\n return self._queue\n\n @property\n def metadata(self):\n return self._metadata\n\n @property\n def states(self):\n return self._states\n\n def frontier_start(self):\n for component in [self.metadata, self.queue, self.states]:\n if component:\n component.frontier_start()\n\n def frontier_stop(self):\n for component in [self.metadata, self.queue, self.states]:\n if component:\n component.frontier_stop()\n\n def add_seeds(self, seeds):\n self.metadata.add_seeds(seeds)\n\n def get_next_requests(self, max_next_requests, **kwargs):\n partitions = kwargs.pop('partitions', [0]) # TODO: Collect from all known partitions\n batch = []\n for partition_id in partitions:\n batch.extend(self.queue.get_next_requests(max_next_requests, partition_id, **kwargs))\n return batch\n\n def page_crawled(self, response, links):\n self.metadata.page_crawled(response, links)\n\n def request_error(self, request, error):\n self.metadata.request_error(request, error)\n\n def finished(self):\n return NotImplementedError\n\n\n","sub_path":"frontera/contrib/backends/cassandra/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":7214,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"653854969","text":"from openpyxl import Workbook\nfrom openpyxl import load_workbook\n\ndef get_data(ro,col,sheet):\n return sheet.cell(row = ro, column = col).value\n\n#main\n\n#load the excel\nwork_b = load_workbook(filename='_filter.xlsx') #here is the name of your xlsx file\nsheetnames = work_b.get_sheet_names()\nsheet = work_b.get_sheet_by_name(sheetnames[0])\n\nwb = Workbook() # Creat sheet\nws = wb.active\n\nlist1 = []\nfor row in range(1,500000+1):\n if get_data(row, 1, sheet) == \"stop_here\":\n break\n\n if get_data(row, 1, sheet) == \"ACP\":\n continue\n else:\n if get_data(row,1,sheet) not in list1:\n list1.append(get_data(row,1,sheet))\nnum = len(list1)\nprint(num)\nr_row = 1\nfor i in range(0,num):\n ap = list1[i]\n min = 2000\n max = -2000\n sam = 0\n for row in range(1, 500000 + 1):\n if get_data(row, 1, sheet) == \"stop_here\":\n break\n if get_data(row,1,sheet) == ap:\n sam += 1\n if get_data(row, 2, sheet) < min:\n min = get_data(row, 2, sheet)\n if get_data(row, 2, sheet) > max:\n max = get_data(row, 2, sheet)\n if max > -72:\n for rssi in range(min, max + 1):\n quan = 0\n for row in range(1, 500000 + 1):\n if get_data(row, 1, sheet) == \"stop_here\":\n break\n if get_data(row, 1, sheet) == ap:\n if get_data(row, 2, sheet) == rssi:\n quan += 1\n if quan>0 :\n ws['A' + str(r_row)] = ap\n ws['B' + str(r_row)] = rssi\n ws['C' + str(r_row)] = quan/sam\n r_row += 1\n ws['A' + str(r_row)] = \"ACP\"\n r_row += 1\nws['A' + str(r_row)] = \"stop_here\"\nwb.save(\"_gaussian.xlsx\")\n","sub_path":"Assignment02/Gaussian_extraction/step6_gaussian.py","file_name":"step6_gaussian.py","file_ext":"py","file_size_in_byte":1781,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"250852480","text":"\"\"\"\nFull training of the first feature model. Using parameters found from experimentation. \n\"\"\"\nimport pickle, random, sys\nimport numpy as np\nsys.path.append('../')\nfrom models.SequenceModel import *\n\nFULL_DATA_FN = \"../data/full_handposbase_pitches.p\"\nX_full, f_full, y_full = pickle.load(open(FULL_DATA_FN, \"rb\"))\nprint(\"data loaded from {}\".format(FULL_DATA_FN))\n\ndata = list(zip(X_full, f_full, y_full))\nrandom.shuffle(data)\nX_full, f_full, y_full = zip(*data)\n\nNUM_TRAIN = 4500\nNUM_TEST = 4500\n\n# NOTE: Trying to overfit right now. large network, same data for test/train.\nX_train, f_train, y_train = X_full[:NUM_TRAIN], f_full[:NUM_TRAIN], y_full[:NUM_TRAIN]\nX_test, f_test, y_test = X_full[:NUM_TRAIN], f_full[:NUM_TRAIN], y_full[:NUM_TRAIN]\n# X_test, f_test, y_test = X_full[NUM_TRAIN:NUM_TRAIN+NUM_TEST], f_full[NUM_TRAIN:NUM_TRAIN+NUM_TEST], y_full[NUM_TRAIN:NUM_TRAIN+NUM_TEST]\nprint(\"data split. {} training examples, {} test examples.\".format(NUM_TRAIN, NUM_TEST))\n\nRATE = 0.001\nLAYERSIZES = [64, 32]\nEPOCHS = 5\nBATCH_SIZE = 50\nTEST_ID = \"multilayer_0-001_64_32\"\n\nmodel_type = \"feature\"\ncell_type = \"lstm\"\n\nr_str = str(RATE).replace(\".\", \"-\")\nid_str = \"{}_{}_{}\".format(TEST_ID, model_type, cell_type)\n\nprint(\"training model: {}\".format(id_str))\nmodel = SequenceModel(model_type, RATE, cell_type, LAYERSIZES)\nmodel.train([X_train, f_train, y_train], BATCH_SIZE, EPOCHS, id_str)\nacc = model.test([X_test, f_test, y_test], id_str)\nprint(\"acc: {}\".format(acc))\t\t\t\t\t\t\t\n\n\n\n\n","sub_path":"src/testing/training_handposbase_full.py","file_name":"training_handposbase_full.py","file_ext":"py","file_size_in_byte":1491,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"502443397","text":"import tensorflow as tf\n# y = Wx + b, 初始化的时候随便定义一个初始值\nW = tf.Variable([.3], dtype=tf.float32)\nb = tf.Variable([-.3], dtype=tf.float32)\n# 输入值 x, 定义为占位符, 便于在学习过程中换成不同的值\nx = tf.placeholder(tf.float32)\n# 定义线性模型\nlinear_model = W*x + b\n# 输出值 y, 定义为占位符, 便于在学习过程中换成不同的值\ny = tf.placeholder(tf.float32)\n# 损失loss,线性模型中以欧式距离来衡量损失值\nloss = tf.reduce_sum(tf.square(linear_model - y))\n# 定义优化器optimizer\noptimizer = tf.train.GradientDescentOptimizer(0.01)\ntrain = optimizer.minimize(loss)\n# 4个蓝色点的训练数据,分解成x和y的数组为\nx_train = [1, 2, 3, 4]\ny_train = [0, -1, -2, -3]\n# 初始化Session\ninit = tf.global_variables_initializer()\nsess = tf.Session()\nsess.run(init)\n\n# 保存计算图\nloss_summary = tf.summary.scalar(\"loss\", loss)\nsummaryWriter = tf.summary.FileWriter(logdir='logs_linear_regression', graph=tf.get_default_graph())\nallSummary = tf.summary.merge_all()\n\n# 循环1000次,训练模型\nfor i in range(1000):\n\tsess.run(train, {x: x_train, y: y_train})\n\t# 评估准确率\n\tlogSummary, curr_W, curr_b, curr_loss = sess.run([allSummary, W, b, loss], {x: x_train, y: y_train})\n\tsummaryWriter.add_summary(logSummary, i)\n\tprint(\"W: %s b: %s loss: %s\"%(curr_W, curr_b, curr_loss))\n\tsummaryWriter.flush()\nsummaryWriter.close()\nsess.close()\n\n\n\n\n","sub_path":"tpu/ml.tensorboard.py","file_name":"ml.tensorboard.py","file_ext":"py","file_size_in_byte":1451,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"224007754","text":"# -*- coding: utf-8 -*-\n# (c) Copyright IBM Corp. 2010, 2022. All Rights Reserved.\n\n\"\"\"AppFunction implementation\"\"\"\nfrom resilient_lib import validate_fields, IntegrationError\nfrom resilient_circuits import AppFunctionComponent, app_function, FunctionResult\n\nfrom fn_teams.lib import constants\nfrom fn_teams.lib.microsoft_teams import TeamsInterface\nfrom fn_teams.lib.microsoft_authentication import MicrosoftAuthentication\n\nPACKAGE_NAME = constants.PACKAGE_NAME\nFN_NAME = \"ms_teams_create_team\"\n\n\nclass FunctionComponent(AppFunctionComponent):\n \"\"\"Component that implements function 'ms_teams_create_team'\"\"\"\n\n def __init__(self, opts):\n super(FunctionComponent, self).__init__(opts, PACKAGE_NAME)\n\n @app_function(FN_NAME)\n def _app_function(self, fn_inputs):\n \"\"\"\n This application allows for creating a Microsoft Team using the Microsoft Graph API. This\n provides SOAR with the ability to create a MS Team from within a SOAR incident or a task. This\n ms_teams_create_team function has the ability to create an MS Team with a Name and description\n from an Incident or a task. It also has the ability to add multiple owners by specifying\n their email addresses in a comma-separated manner. At least one owner must be mentioned for group\n creation. The function is developed to automatically add all members of an incident or a task\n to the MS Team. If the function is executed from within a task, in addition to task members,\n all incident members can also be automatically added if that option is selected. Apart from\n automatic member addition, individual members can be added by directly specifying their email\n addresses.\n\n Inputs:\n -------\n task_id : If called from task then Task ID\n incident_id : Incident ID\n ms_team_name : Name of the Microsoft Team to be created\n ms_owners_list : List of owners email addresses\n add_members_from : Specifies if members to be added form incident or task\n ms_description : Description for the group to be created\n additional_members : List of email addresses of additional members to be added\n\n Returns:\n --------\n Response : A response with the room/team options and details\n or the error message if the meeting creation\n \"\"\"\n\n yield self.status_message(constants.STATUS_STARTING_APP.format(FN_NAME))\n\n required_parameters = {}\n required_parameters[\"rc\"] = self.rc\n required_parameters[\"logger\"] = self.LOG\n required_parameters[\"resclient\"] = self.rest_client()\n\n validate_fields([\n \"incident_id\",\n \"ms_team_name\",\n \"ms_owners_list\",\n \"add_members_from\"], fn_inputs)\n\n required_parameters[\"incident_id\"] = fn_inputs.incident_id\n required_parameters[\"displayName\"] = fn_inputs.ms_team_name\n required_parameters[\"owners_list\"] = fn_inputs.ms_owners_list\n required_parameters[\"add_members_from\"] = fn_inputs.add_members_from\n\n required_parameters[\"task_id\"] = fn_inputs.task_id if hasattr(\n fn_inputs, 'task_id') else None\n required_parameters[\"description\"] = fn_inputs.ms_description if hasattr(\n fn_inputs, 'ms_description') else \"\"\n required_parameters[\"additional_members\"] = fn_inputs.additional_members if hasattr(\n fn_inputs, 'additional_members') else None\n\n try:\n yield self.status_message(constants.STATUS_GENERATE_HEADER)\n authenticator = MicrosoftAuthentication(self.rc, self.options)\n required_parameters[\"header\"] = authenticator.authenticate_application_permissions()\n authenticated = True\n yield self.status_message(constants.STATUS_SUCCESSFULLY_AUTHENTICATED)\n\n except IntegrationError as err:\n self.LOG.error(constants.STATUS_SUCCESSFULLY_AUTHENTICATED)\n yield self.status_message(constants.STATUS_AUTHENTICATION_FAILED)\n authenticated = False\n yield FunctionResult({}, success=False, reason=str(err))\n\n if authenticated:\n try:\n team_manager = TeamsInterface(required_parameters)\n response = team_manager.create_team(required_parameters)\n yield FunctionResult(response, success=True)\n except IntegrationError as err:\n yield FunctionResult({}, success=False, reason=str(err))\n","sub_path":"fn_teams/fn_teams/components/funct_ms_teams_create_team.py","file_name":"funct_ms_teams_create_team.py","file_ext":"py","file_size_in_byte":4646,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"235943161","text":"import yaml\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport matplotlib.ticker as plticker\nimport matplotlib\nfrom hist import Hist\nimport hist\n\n# Quick construction, no other imports needed:\n\n\nwith open(\"../summary_data/fhr_summary.yaml\", 'r') as stream:\n dic_fhr = yaml.load(stream)\n\nwith open(\"../summary_data/thr_summary.yaml\", 'r') as stream:\n dic_thr = yaml.load(stream)\n\nstaves = list(dic_fhr.keys())[:-1]\n\n\ntest_type = ['tuned_fhr', 'tuned_fhr_masked']\noutput_string = ['Tuned FHR w/o masking', 'Tuned FHR w/ masking']\n\n\n\n\nfor test,output in zip(test_type, output_string):\n fhr_list = []\n thr_list = []\n for i,stave in enumerate(staves):\n mean_fhr_arr = np.array(dic_fhr[stave]['mean'][test])\n mask_fhr = mean_fhr_arr > 0\n mean_thr_arr = np.array(dic_thr[stave]['mean'])\n mask_thr = mean_thr_arr > 0\n fhr_list.append(np.mean(np.log10(mean_fhr_arr[mask_fhr])))\n thr_list.append(np.mean(mean_thr_arr[mask_thr]))\n\n\n\n\n h = Hist(\n hist.axis.Regular(\n 20, np.min(thr_list), np.max(thr_list), name=\"Average Threshold Scan (electrons)\", label=\"\", underflow=False, overflow=False\n ),\n hist.axis.Regular(\n 15, -12, -5, name=\"Average Fake Hit Rate\", label=\"\", underflow=False, overflow=False\n ),\n )\n\n\n\n h.fill(thr_list, fhr_list)\n\n\n fig, ax = plt.subplots(figsize=(16, 9))\n w, x, y = h.to_numpy()\n mesh = ax.pcolormesh(x, y, w.T, cmap = 'viridis')\n\n ax.set_xlabel('Average Threshold Scan (electrons)', fontsize=18)\n ax.set_ylabel('Average Fake Hit Rate (log)', fontsize=18)\n\n fig.colorbar(mesh)\n\n plt.text( 90, -5.5, f'Outer Barrel: {output}', fontsize = 20, color = 'white')\n\n\n plt.tight_layout()\n plt.savefig(f'../results/2D_corr_{test}.png')\n plt.show()","sub_path":"summary_plots/2D_correlation.py","file_name":"2D_correlation.py","file_ext":"py","file_size_in_byte":1807,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"382473154","text":"from __future__ import print_function\n\nimport sys\nimport os\nimport grpc\nimport agenda_pb2\nimport agenda_pb2_grpc\n\n##\n# Descricao: aqui mostramos o menu da opcoes disponiveis na nossa agenda, se for adicionar pegamos o nome e telefone enviamos isso ao nosso servidor, removemos o contato a partir do nome e enviamos isso nosso servidor e listamos os contatos da nossa agenda.\n# Autor: Alexandre Yuji Kajihara\n# Data de criacao: 27/10/17\n# Data de atualizacao: 27/10/17\n##\n\n##\n# Para adicionar um contato precisamos de nome e telefone e solicitamos isso ao cliente da nossa agenda, e retornamos a pessoa com essas informacoes.\n# @return retorna pessoa, com o nome e o telefone.\n##\ndef adicionaContato():\n\tpessoa = agenda_pb2.Pessoa()\n\tpessoa.nome = raw_input('Nome: ')\n\tpessoa.telefone = raw_input('Telefone: ')\n\treturn pessoa\n\n##\n# Para remover um contato precisamos de nome e solicitamos isso ao cliente da nossa agenda, e retornamos a pessoa com essas informacao.\n# @return retorna pessoa, com o nome.\n##\ndef removeContato():\n\tpessoa = agenda_pb2.Pessoa()\n\tpessoa.nome = raw_input('Nome: ')\n\treturn pessoa\n\n##\n# Exibe o menu e no caso de adicionar e remover passamos as informacoes que o usuario que adicionar ou remover ao servidor, e no caso de lista, apenas esperamos as pessoas presentes na agenda.\n# @return retorna nada.\n##\ndef run():\n\tcanal = grpc.insecure_channel('localhost:50051')\n\t#Agenda arquivo que foi gerado pelo Makefile\n\tstub = agenda_pb2_grpc.AgendaStub(canal)\n\topcao = 0\n\tos.system('clear')\n\n\twhile(True):\n\t\tprint(\"1 -> Adicionar contato\")\n\t\tprint(\"2 -> Remover contato\")\n\t\tprint(\"3 -> Listar os contatos\")\n\t\tprint(\"4 -> Sair\")\n\t\topcao = int(raw_input('Opcao: '))\n\n\t\tif opcao == 1:\n\t\t\tpessoa = adicionaContato()\n\t\t\tresponse = stub.AdicionaContato(pessoa)\n\t\t\tos.system('clear')\n\t\t\tif response.reply:\n\t\t\t\tprint(\"Contato adicionando com sucesso!\")\n\t\telif opcao == 2:\n\t\t\tpessoa = removeContato()\n\t\t\tresponse = stub.RemoveContato(pessoa)\n\t\t\tos.system('clear')\n\t\t\tif response.reply:\n\t\t\t\tprint(\"Contato removido com sucesso!\")\n\t\t\telse:\n\t\t\t\tprint(\"Contato nao existe!\")\t\t\t\n\t\telif opcao == 3:\n\t\t\tresponse = stub.ListaContato(agenda_pb2.BoolRequest(request = True))\n\t\t\tprint(response)\n\t\t\tos.system('clear')\n\t\t\tlistaVazia = False\n\t\t\tfor pessoa in response:\n\t\t\t\tlistaVazia = True\n\t\t\t\tprint(pessoa)\n\t\t\tif listaVazia == False:\n\t\t\t\tprint('Nao existe elementos na lista')\n\t\telif opcao == 4:\n\t\t\tprint(\"Tchau tchau!!!\")\n\t\t\treturn\n\n#Invoca a classe que inicializa o cliente e envia as requisicoes dos clientes ao servidor\nif __name__ == '__main__':\n\trun()\n","sub_path":"Cliente.py","file_name":"Cliente.py","file_ext":"py","file_size_in_byte":2557,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"316914420","text":"# -*- coding: utf-8 -*-\nimport re\nimport os\n\nSRC_FILE_PATH = r\"/sf/data/local/TESTCASE/HW_Platform/test_script/rhel8_changelog/\"\n# SRC_FILE_PATH7 = r\"/sf/data/local/TESTCASE/HW_Platform/test_script/rhel7_changelog/\"\nSRC_FILE_PATH7 = r\"/home/xyc/LB/rhel8/\"\n\nDATE_PATTERN = r\"([0-9]{3}[1-9]|[0-9]{2}[1-9][0-9]{1}|[0-9]{1}[1-9][0-9]{2}|[1-9][0-9]{3})-(((0[13578]|1[02])-(0[1-9]|[12][0-9]|3[01]))|((0[469]|11)-(0[1-9]|[12][0-9]|30))|(02-(0[1-9]|[1][0-9]|2[0-8])))\"\nCATEGORY_PATTERN = r\"- (\\[)\\w+(\\])\"\n\n# DST_FILE_PATH_PREFIX = r\"/sf/data/local/TESTCASE/HW_Platform/test_script/rhel8/\"\n# DST_FILE_PATH_PREFIX = r\"/sf/data/local/TESTCASE/HW_Platform/test_script/rhel7/\"\nDST_FILE_PATH_PREFIX = r\"/home/xyc/LB/rhel8_change/\"\n\n\n# DST_CATEGORIES_DIRS = r\"/sf/data/local/TESTCASE/HW_Platform/test_script/rhel8/\"\n\nclass RHELChangeLogHandler:\n\n def __init__(self, dir_path):\n self.dir_path = dir_path\n\n def get_all_categories(self):\n \"\"\"获取所有种类的目录\"\"\"\n all_categories = list()\n for dir_path, dir_names, filenames in os.walk(self.dir_path):\n for dir_name in dir_names:\n all_categories.append(dir_name)\n return all_categories\n\n def make_category_dir_by_rhel(self):\n \"\"\"根据rhel文本中的日志类别创建目录\"\"\"\n for dir_path, dir_names, filenames in os.walk(self.dir_path):\n for filename in filenames:\n file = \"\".join([self.dir_path, filename])\n with open(file, \"r\") as fp:\n datas = fp.readlines()\n for item in datas:\n item = item.strip(\"\\n\")\n item = item.strip()\n # res_title = re.match(DATE_PATTERN, item)\n res_category = re.match(CATEGORY_PATTERN, item)\n if res_category:\n category_dir = res_category.group().lstrip(\n \"- \").lstrip(\"[\").rstrip(\"]\")\n CATEGORY_FILE_PATH = \"\".join(\n [DST_FILE_PATH_PREFIX, category_dir])\n if not os.path.exists(CATEGORY_FILE_PATH):\n os.makedirs(CATEGORY_FILE_PATH)\n\n def get_element_index_by_rhel_file_txt(self):\n \"\"\"根据rhel文本获取日期(当做标题)及日志内容的索引位置\"\"\"\n file_index_map = dict()\n for dir_path, dir_names, filenames in os.walk(self.dir_path):\n for filename in filenames:\n file = \"\".join([self.dir_path, filename])\n title_indexs = list()\n with open(file, \"r\") as fp:\n datas = fp.readlines()\n for item in datas:\n obj = item.strip(\"\\n\")\n obj = obj.strip()\n res_title = re.match(DATE_PATTERN, obj)\n if res_title:\n title_index = datas.index(item)\n # res_title_index_map = {\n # res_title:\n # }\n title_indexs.append(title_index)\n # import pdb;pdb.set_trace()\n res_category_obj = datas[title_index + 1]\n\n file_index_map[filename] = title_indexs\n return file_index_map\n\n # get_element_index_by_rhel_file_txt(SRC_FILE_PATH)\n def trans_each_changelog_file_data_format_by_rhel_txt(self):\n \"\"\"根据指定的rhel文本内容构建数据格式:\n 返回数据格式:\n title_objs =\n [\n {标题一:[数据一,数据二,...]},\n {标题二:[数据一,数据二,...]},\n {标题三:[数据一,数据二,...]},\n ...\n ...\n ]\n 单个文件的情况\n \"\"\"\n pass\n\n def trans_changelog_file_data_format_by_rhel_txt(self):\n \"\"\"根据rhel文本内容构建数据格式:\n 返回数据格式:\n title_objs =\n [\n {标题一:[数据一,数据二,...]},\n {标题二:[数据一,数据二,...]},\n {标题三:[数据一,数据二,...]},\n ...\n ...\n ]\n all_log_file_datas = {\n \"文件一\":title_objs,\n \"文件二\":title_objs,\n ...\n }\n \"\"\"\n file_index_map = self.get_element_index_by_rhel_file_txt()\n all_log_file_datas = dict()\n for dir_path, dir_names, filenames in os.walk(self.dir_path):\n for filename in filenames:\n file = \"\".join([self.dir_path, filename])\n # file = \"\".join([SRC_FILE_PATH, \"changelog-2020-06-30-10-44-48-4.18.0-80.el8999.txt\"])\n with open(file, \"r\") as fp:\n datas = fp.readlines()\n current_title_indexes = file_index_map[filename]\n # current_title_indexes = file_index_map[\"changelog-2020-06-30-10-44-48-4.18.0-80.el8999.txt\"]\n print(current_title_indexes)\n # import pdb;pdb.set_trace()\n # [2, 4, 13, 15, 21, 25, 33, 60, 71, 73]\n # 先获取当前的更新日志标题:\n # [{标题一:[数据一,数据二,...]}, {标题一:[数据一,数据二,...]},... ]\n title_objs = list()\n times = len(current_title_indexes)\n i = 0\n #########问题出在这里:双层循环导致的数据不一致################\n # [2, 4, 13]\n for title_index in current_title_indexes:\n\n if i < times - 1:\n # {标题一:[数据一,数据二,...]}\n title_data = dict()\n # 文本中的每一个标题\n title = datas[title_index]\n # 取出title就把空格去掉\n title = title.strip(\"\\n\").strip()\n # 下一个标题的索引\n next_title_index = current_title_indexes.index(\n title_index) + 1\n # 下一个日志内容的索引\n next_log_obj_index = current_title_indexes[\n next_title_index]\n # 日志内容\n log_items = datas[\n (title_index + 1):next_log_obj_index]\n title_data[title] = [item.strip() for item in\n log_items]\n title_objs.append(title_data)\n\n if i == times - 1:\n # 说明是最后一个标题\n last_title_data = dict()\n last_index = current_title_indexes[i]\n last_items = list()\n for item in datas[(last_index + 1):]:\n item = item.strip()\n last_items.append(item)\n last_title = datas[last_index]\n # 取出title就把空格去掉\n last_title = last_title.strip(\"\\n\").strip()\n last_title_data[last_title] = last_items\n title_objs.append(last_title_data)\n\n i += 1\n # 单个文件的title_objs\n all_log_file_datas[filename] = title_objs\n\n return all_log_file_datas\n\n # make_changelog_file_by_rhel_txt(SRC_FILE_PATH)\n def get_all_files_name(self):\n \"\"\"获取所有文件名称\"\"\"\n for dir_path, dir_names, filenames in os.walk(self.dir_path):\n return filenames\n\n def get_single_file_title(self, file, filename):\n \"\"\"获取单个文件的所有标题\"\"\"\n with open(file, \"r\") as fp:\n datas = fp.readlines()\n items = list()\n for data in datas:\n obj = data.strip(\"\\n\")\n obj = obj.strip()\n items.append(obj)\n file_index_map = self.get_element_index_by_rhel_file_txt()\n current_title_indexes = file_index_map[filename]\n titles = list()\n for title_index in current_title_indexes:\n # 在这里将标题的空格和\\n去掉\n title = items[title_index]\n titles.append(title)\n\n return titles\n\n def get_res_category_obj_dir_path(self, title, res_category_objs):\n \"\"\"获取日志内容的目录路径\"\"\"\n res_title = re.match(DATE_PATTERN, title)\n file_dirs = list()\n for res_category_obj in res_category_objs:\n category_obj = res_category_obj.strip(\"\\n\")\n category_obj = category_obj.strip()\n res_category = re.match(CATEGORY_PATTERN, category_obj)\n if res_category:\n category_dir = res_category.group().lstrip(\"- \").lstrip(\n \"[\").rstrip(\"]\")\n DST_FILE_PATH = \"\".join(\n [DST_FILE_PATH_PREFIX, category_dir, \"/\",\n res_title.group(), \".txt\"])\n file_dirs.append(DST_FILE_PATH)\n return file_dirs\n\n def make_changelog_file_by_rhel_txt(self):\n \"\"\"按照日志类别写入日志文件内容\"\"\"\n all_files_log_data = self.trans_changelog_file_data_format_by_rhel_txt()\n filenames = self.get_all_files_name()\n for filename in filenames:\n each_log_datas = all_files_log_data[filename]\n # import pdb;pdb.set_trace()\n # {标题一:[数据一,数据二,...]},\n for data in each_log_datas:\n title = [k for k in data.keys()][0]\n # import pdb;pdb.set_trace()\n res_category_objs = data[title]\n # res_title_obj = title.strip(\"\\n\").strip()\n res_title = re.match(DATE_PATTERN, title)\n # 去搜索\n file_dirs = self.get_res_category_obj_dir_path(title,\n res_category_objs)\n for file_dir in file_dirs:\n # 先写入标题,再去写内容\n with open(file_dir, \"w\") as f:\n f.write(title + \"\\n\")\n for res_category_obj in res_category_objs:\n category_obj = res_category_obj.strip(\"\\n\")\n category_obj = category_obj.strip()\n res_category = re.match(CATEGORY_PATTERN, category_obj)\n if res_category:\n category_dir = res_category.group().lstrip(\n \"- \").lstrip(\n \"[\").rstrip(\"]\")\n DST_FILE_PATH = \"\".join(\n [DST_FILE_PATH_PREFIX, category_dir, \"/\",\n res_title.group(), \".txt\"])\n with open(DST_FILE_PATH, \"a\") as f:\n f.write(\"\".join([\" \", res_category_obj, \"\\n\"]))\n\n\ndef main():\n log_handler = RHELChangeLogHandler(SRC_FILE_PATH7)\n # all_log_file_datas = log_handler.trans_changelog_file_data_format_by_rhel_txt()\n log_handler.make_category_dir_by_rhel()\n log_handler.make_changelog_file_by_rhel_txt()\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"analyse_data/analyse_data.py","file_name":"analyse_data.py","file_ext":"py","file_size_in_byte":11677,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"167750636","text":"\"\"\"\r\nAssume you have an array of length n initialized with all 0's and are given k update operations.\r\n\r\nEach operation is represented as a triplet: [startIndex, endIndex, inc] which increments each element of subarray A[startIndex ... endIndex] (startIndex and endIndex inclusive) with inc.\r\n\r\nReturn the modified array after all k operations were executed.\r\n\"\"\"\r\n\r\n\"\"\"\r\nThis is tricky question. If you just naively follow the question, it is not\r\nvery efficient because you have to traverse the entire array for k time\r\n=> O(kn)\r\n\r\n=> better algo is only O(n + k)\r\nhttps://discuss.leetcode.com/topic/75639/python-solution-with-detailed-explanation\r\n\"\"\"\r\n\r\ndef get_modified_array(length, updates):\r\n \"\"\"\r\n :type length: int\r\n :type updates: List[List[int]]\r\n :rtype List[int]\r\n \"\"\"\r\n result = [0 for _ in range(length)]\r\n\r\n for s, e, inc in updates:\r\n result[s] += inc\r\n if e + 1 < length:\r\n result[e + 1] -= inc\r\n\r\n for i in range(1, length):\r\n result[i] += result[i - 1]\r\n\r\n return result\r\n","sub_path":"LeetCode/range_addition.py","file_name":"range_addition.py","file_ext":"py","file_size_in_byte":1052,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"401114305","text":"\"\"\"Kurzbeschreibung des Programmes (\"Standardabbildung\")\n\nCP - Aufgabe 1\n\nDurch einen Linksklick auf den Plot-Bereich wird \ngemaess der Aufgabenstellung ein Orbit erzeugt. \nDabei entspricht der gewaehlte Punkt dem Anfangs-\nwert im Phasenraum: (x,y) = (theta0, p0).\n\nClemens Mart 2014\n\"\"\"\n\nfrom numpy import *\nfrom matplotlib import pyplot as plt\n\ndef randbed(wert, minimum, maximum):\n\t\"\"\"Zur Einhaltung der periodischen Randbedingungen wird \"wert\" in den Bereich zwischen \"minimum\" und \"maximum\" umgeklappt.\"\"\"\n\treturn (wert-minimum) % (maximum-minimum) + minimum\n\ndef random_color():\n\t\"\"\"Generiert eine zufaellige Farbe im Format [R,G,B,A]\"\"\"\n\trandom.seed()\n\trnd = random.random()\n\tcolor = [rnd, 1-rnd, (rnd*10)%1, 1] # Weiss/Schwarz waeren nicht gut, daher sollen R und G entgegengesetzt sein.\n\treturn color\n\ndef mouse_click(event):\n\t\"\"\"Beginne Berechnung mit Mausposition als Anfangsbedingungen\"\"\"\n\t# Nicht zeichnen, wenn im Zoom-Modus\n\tif plt.get_current_fig_manager().toolbar.mode == '':\n\t\tcalc_orbit(2.6, event.xdata, event.ydata)\n\t\n\ndef calc_orbit(K=2.6, theta0=0, p0=0.1):\n\t\"\"\"Berechne und zeichne einen Orbit mit den uebergebenen Anfangswerten theta0, p0 sowie dem freien Parameter K. \"\"\"\n\t# Variable des Systemes (2 Freiheitsgrade), initialisierung mit Nullen fuer 1000 Iterationen\n\ttheta = zeros(1000)\n\tp = zeros(1000)\n\n\t# Anfangsbedingungen des Systems (2 AB)\n\ttheta[0] = theta0\n\tp[0] = p0\n\t\n\tn = 0\t\n\twhile n < 999:\n\t\t# Ausfuehrung der Standardabbildung\n\t\ttheta[n+1] = randbed(theta[n] + p[n], 0, 2*pi)\n\t\tp[n+1] = randbed(p[n] + K*sin(theta[n+1]), -pi, pi)\n\t\tn += 1 \n\n\t# Datenpunkte des Durchganges zeichnen\n\tplt.scatter(theta, p, 10, random_color(), \"o\", linewidths=0)\n\tplt.draw()\n\n# Hauptprogramm\n# Vorbereiten der Zeichenflaeche und Abwarten einer Benutzereingabe\nplt.figure(0)\nplt.subplot(111, autoscale_on=False)\nplt.connect('button_press_event', mouse_click)\nplt.axis([0, 2*pi, -pi, pi])\nplt.show()\n\n# Programm erfolgreich beendet...\nprint(\"Programm beendet.\")\n\n# Bemerkung: \n\n# - Bei K=0 bleibt p natuerlich konstant. (waagerechte Phasenraumlinien) \n# - Fuer Werte von K>0 bildet sich bei (p=0, theta=pi) eine \"Insel\" aus, \n# um welche die PR-Linien verlaufen. Kommt der Schlag von rechts, \n# \t wuerde das Pendel nun links stehen und durch die Schlaege auch\n# etwa in dieser Lage gehalten werden.\n# - Angrenzend an die \"Insel\" sind Phasenraumpunkte, fuer die eine\n# ungeordnete Bewegung eintritt. Dieser Bereich wird wiederum von zahl-\n# reichen immer kleineren \"Inseln der Stabilitaet\" unterbrochen. \n# (z.B. K=2,6) (die fraktal aussehen, wow)\n# - Fuer grosse Werte von K wird der stabile Bereich immer kleiner. Er \n# liegt nun nicht mehr um (0, pi), sondern das Pendel wechselt zwischen\n# zwei \"Inseln\" ausserhalb der Mitte, um die sich wiederum eine \"wechselnde\"\n# konzentrische Bewegung einstellt\n\n\n","sub_path":"1_1_clemens_mart.py","file_name":"1_1_clemens_mart.py","file_ext":"py","file_size_in_byte":2839,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"490447151","text":"from functools import partial\nfrom PySide2.QtGui import *\nfrom PySide2.QtCore import *\nfrom PySide2.QtWidgets import *\nfrom nodes import utils as utils\nimport constants as const\nimport nebula_ui.nCoreui.toolButton as button\nfrom nebula_libs.nicon import Icon as Icon\n\n\n\nclass RigUtilsToolBar(QToolBar):\n def __init__(self, parent = None):\n super(RigUtilsToolBar, self).__init__(parent = parent)\n\n self.setIconSize(QSize(16,16))\n ########################\n ### Main buttons on toolbar\n deleteHistoryInfo = 'Delete History'\n self.deleteHistory = self.addAction(Icon('iconmonstr-x-mark-5-240'), 'DelHist')\n self._setActionInfo(self.deleteHistory, deleteHistoryInfo)\n self.deleteHistory.triggered.connect(utils.deleteHistory)\n\n selHrcInfo = 'Select hierarchy'\n self.selHrc = self.addAction(Icon('iconmonstr-sort-26-240'), 'SelHrc')\n self._setActionInfo(self.selHrc, selHrcInfo)\n self.selHrc.triggered.connect(utils.selHrc)\n\n centerPivInfo = 'Center Pivots'\n self.centerPiv = self.addAction(Icon('iconmonstr-crosshair-4-240'),'CenterPiv')\n self._setActionInfo(self.centerPiv, centerPivInfo)\n self.centerPiv.triggered.connect(utils.centerPiv)\n\n freezeXfrmInfo = 'Freeze Transform'\n self.freezeXfrm = self.addAction(Icon('iconmonstr-crosshair-1-240'),'FrzXform')\n self._setActionInfo(self.freezeXfrm, freezeXfrmInfo)\n self.freezeXfrm.triggered.connect(utils.freezeXfrm)\n\n ########################\n ## Modify Menu\n self.modifyMenu = button.ToolButton(self, 'Modify')\n self.addWidget(self.modifyMenu)\n self.modifyAddAttr = self.modifyMenu.menu.addAction('Add Attrib')\n self.modifyAddAttr.setIcon(Icon('iconmonstr-plus-4-240'))\n self.modifyAddAttr.triggered.connect(partial(utils.melEval, \"AddAttribute;\"))\n\n self.modifySearchReplace = self.modifyMenu.menu.addAction('Search Replace')\n self.modifySearchReplace.setIcon(Icon('iconmonstr-help-4-240'))\n self.modifySearchReplace.triggered.connect(partial(utils.melEval, \"performSearchReplaceNames 1;\"))\n\n ########################\n ## Utils Menu\n self.utilsMenu = button.ToolButton(self, 'Utils')\n self.addWidget(self.utilsMenu)\n ## Utils - Snap\n self.snapsLabel = QWidgetAction(self)\n self.snapsLabel.setDefaultWidget(QLabel('Snap:'))\n self.addSnapsLabel = self.utilsMenu.menu.addAction(self.snapsLabel)\n\n self.snapToEdgeLoopCenter = self.utilsMenu.menu.addAction('Snp Sel to edgelp center')\n self.snapToEdgeLoopCenter.setIcon(Icon('iconmonstr-log-out-4-240'))\n self._setActionInfo(self.snapToEdgeLoopCenter, 'Select item, then edge to snap to edgeloop center.')\n self.snapToEdgeLoopCenter.triggered.connect(utils.snapToEdgeLoopCenter)\n\n self.snapToVertCenter = self.utilsMenu.menu.addAction('Snp Sel to vertPair center')\n self.snapToVertCenter.setIcon(Icon('iconmonstr-log-out-4-240'))\n self._setActionInfo(self.snapToVertCenter, 'Select item, then 2 verts to snap to the item to the center of.')\n self.snapToVertCenter.triggered.connect(utils.dosnapToVertCenter)\n\n self.sep03 = self.utilsMenu.menu.addSeparator()\n ## Utils - General\n self.generalLabel = QWidgetAction(self)\n self.generalLabel.setDefaultWidget(QLabel('General:'))\n self.addgeneralLabel = self.utilsMenu.menu.addAction(self.generalLabel)\n\n ## Naming Menu\n self.namingLabel = QWidgetAction(self)\n self.namingLabel.setDefaultWidget(QLabel('Naming:'))\n self.addnamingLabel = self.utilsMenu.menu.addAction(self.namingLabel)\n self.renamer = self.utilsMenu.menu.addAction('Rename')\n self.renamer.setIcon(Icon('iconmonstr-text-21-240'))\n self.renamer.triggered.connect(utils.dorename)\n\n self.geoSuffix = self.utilsMenu.menu.addAction('Add _geo suffix')\n self.geoSuffix.triggered.connect(partial(utils.addGeoSuffix))\n self.geoSuffix.setIcon(Icon('iconmonstr-text-21-240'))\n\n self.sep05 = self.utilsMenu.menu.addSeparator()\n self.charLabel = QWidgetAction(self)\n self.charLabel.setDefaultWidget(QLabel('Char:'))\n self.addcharLabel = self.utilsMenu.menu.addAction(self.charLabel)\n\n\n ########################\n ## Lock Menu\n self.lockMenu = button.ToolButton(self, 'Lock/Hide')\n self.addWidget(self.lockMenu)\n self.lockMenuAll = self.lockMenu.menu.addAction(Icon(\"iconmonstr-lock-30-240\"), 'ALL')\n self.lockMenuAll.triggered.connect(partial(utils.lockchans, channels = const.ALLCHANS, lock = True, keyable = False))\n\n self.sep01 = self.lockMenu.menu.addSeparator()\n self.lockMenuTranslate = self.lockMenu.menu.addAction(Icon(\"iconmonstr-lock-30-240\"), 'Translate')\n self.lockMenuTranslate.triggered.connect(partial(utils.lockchans, channels = const.TRANS, lock = True, keyable = False))\n\n self.lockMenuRotate = self.lockMenu.menu.addAction(Icon(\"iconmonstr-lock-30-240\"), 'Rotate')\n self.lockMenuRotate.triggered.connect(partial(utils.lockchans, channels = const.ROT, lock = True, keyable = False))\n\n self.lockMenuScale = self.lockMenu.menu.addAction(Icon(\"iconmonstr-lock-30-240\"), 'Scale')\n self.lockMenuScale.triggered.connect(partial(utils.lockchans, channels = const.SCALE, lock = True, keyable = False))\n\n self.lockMenuVis = self.lockMenu.menu.addAction(Icon(\"iconmonstr-lock-30-240\"), 'Vis')\n self.lockMenuVis.triggered.connect(partial(utils.lockchans, channels = const.VIS, lock = True, keyable = False))\n\n ########################\n ## Build the UnLock Menu\n self.unlockMenu = button.ToolButton(self, 'unLock/unHide')\n self.addWidget(self.unlockMenu)\n self.unlockMenuAll = self.unlockMenu.menu.addAction(Icon(\"iconmonstr-lock-28-240\"), 'ALL')\n self.unlockMenuAll.triggered.connect(partial(utils.lockchans, channels = const.ALLCHANS, lock = False, keyable = True))\n self.sep02 = self.unlockMenu.menu.addSeparator()\n self.unlockMenuTranslate = self.unlockMenu.menu.addAction(Icon(\"iconmonstr-lock-28-240\"), 'Translate')\n self.unlockMenuTranslate.triggered.connect(partial(utils.lockchans, channels = const.TRANS, lock = False, keyable = True))\n self.unlockMenuRotate = self.unlockMenu.menu.addAction(Icon(\"iconmonstr-lock-28-240\"), 'Rotate')\n self.unlockMenuRotate.triggered.connect(partial(utils.lockchans, channels = const.ROT, lock = False, keyable = True))\n self.unlockMenuScale = self.unlockMenu.menu.addAction(Icon(\"iconmonstr-lock-28-240\"), 'Scale')\n self.unlockMenuScale.triggered.connect(partial(utils.lockchans, channels = const.SCALE, lock = False, keyable = True))\n self.unlockMenuVis = self.unlockMenu.menu.addAction(Icon(\"iconmonstr-lock-28-240\"), 'Vis')\n self.unlockMenuVis.triggered.connect(partial(utils.lockchans, channels = const.VIS, lock = False, keyable = True))\n\n self.parent().closed.connect(self.close) ## Custom Signal from MSMainWindow emits QCloseEvent\n\n def _setActionInfo(self, action, info):\n action.setToolTip(info)\n action.setStatusTip(info)\n action.hovered.connect(partial(self._hoverStatusTip, info))\n\n def _hoverStatusTip(self, info):\n if hasattr(self.parent(), 'statusBar'):\n self.parent().statusBar().showMessage(info)","sub_path":"nebula_ui/nMayaui_rig/tb_rigUtils.py","file_name":"tb_rigUtils.py","file_ext":"py","file_size_in_byte":7485,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"570649267","text":"import matplotlib.pyplot as plt\nimport numpy as np\nfrom matplotlib.collections import PatchCollection\n\"Funksjoner\"\ndef henteParametere():\n f = open(parameterpath+'.txt', 'r')\n tekst = f.read()\n lines =tekst.split('\\n')\n data = lines[1].split('\\t')\n f.close()\n dL,r,nf,Vf = float(data[9]),float(data[1]),float(data[2]),float(data[3])\n a = 1\n if nf == 0 or Vf == 0:\n a=0\n return a,dL,r\n\ndef hentePopulation():\n #Les fiber matrix populasjon\n xy=list()\n f = open(coordpath,'r')\n tekst = f.read()\n f.close()\n lines = tekst.split('\\n')\n #lagre koordinater til stottefil\n for line in lines:\n data = line.split('\\t')\n a = float(data[0])\n b = float(data[1])\n c = float(data[2])\n xy.append([a,b,c])\n return xy\n\ndef saveplot():\n fig, sx = plt.subplots(figsize=(5,5))\n plt.axis([-dL / 2, dL / 2, -dL / 2, dL / 2]) # faa en kvadratisk plot\n sx.set_title('Fiberpopulasjon')\n sx.set_xticks(np.arange(-dL / 2, dL / 2, dL/10))\n sx.set_yticks(np.arange(-dL / 2, dL / 2, dL/10))\n sx.grid(True)\n plt.tight_layout()\n if a:\n fiberlist = list()\n for i in range(0, len(coord)):\n circle = plt.Circle((coord[i][0], coord[i][1]), coord[i][2])\n fiberlist.append(circle)\n p = PatchCollection(fiberlist, alpha=0.8)\n sx.add_collection(p)\n fig.savefig('D:/RVEmodel.png')\n plt.show()\n\n\"\"\"Variabler\"\"\"\nGitHub = 'C:/Multiscale-Modeling/'\nparameterpath = GitHub+'Parametere'\ncoordpath = GitHub+'coordst.txt'\na,dL,r= henteParametere()\nif a:\n coord =hentePopulation()\n print(coord)\nsaveplot()\n","sub_path":"Reference_scriptsandFiles/Illustrate_MultiscaleModel.py","file_name":"Illustrate_MultiscaleModel.py","file_ext":"py","file_size_in_byte":1642,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"176177735","text":"import requests\r\nimport urllib\r\nfrom pprint import pprint\r\n\r\nRAKUTEN_URL = \"https://app.rakuten.co.jp/services/api/Product/Search/20170426\"\r\nAPPLICATIONID = \"\"\r\n\r\ndef get_api(url, params):\r\n result = requests.get(url, params=params)\r\n return result.json()\r\n\r\ndef main():\r\n keyword = \"鬼滅\"\r\n params = {\r\n 'format': \"json\",\r\n 'keyword': keyword,\r\n 'applicationId' : APPLICATIONID,\r\n 'page': 1,\r\n 'hits': 10\r\n }\r\n \r\n result = get_api(RAKUTEN_URL, params)\r\n\r\n for i in range(0, len(result['Products'])):\r\n item_maxprice = result['Products'][i][\"Product\"]['maxPrice']\r\n item_minprice = result['Products'][i][\"Product\"]['minPrice']\r\n print(\"-\"*30)\r\n print(f\"最大価格: {item_maxprice}\")\r\n print(f\"最小価格: {item_minprice}\")\r\n\r\nmain()\r\n","sub_path":"最安値と最高値を取得.py","file_name":"最安値と最高値を取得.py","file_ext":"py","file_size_in_byte":838,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"170097934","text":"# -*- coding: utf-8 -*-\nfrom datetime import datetime\nimport json\nfrom FundNavSpiders import GGFundNavSpider\nfrom FundNavSpiders import GGFundNavItem\n\n\nclass ShanXiSecuritiesSpider(GGFundNavSpider):\n name = 'FundNav_ShanXiSecurities'\n sitename = '山西证券'\n channel = 'PB' # 需求未写明\n allowed_domains = ['www.i618.com.cn']\n start_urls = ['http://www.i618.com.cn/gsyw/tgyw/xxpl/index/index.shtml']\n cookies = 'score = 98'\n\n fps = [{\n 'url': 'http://www.i618.com.cn/servlet/json',\n 'form': {\n 'funcNo': '820010',\n 'jjdm': '',\n 'manage_id': '',\n 'curPage': '1',\n 'numPerPage': '500'\n },\n 'ref': start_urls[0]\n }]\n\n def __init__(self, *args, **kwargs):\n super(ShanXiSecuritiesSpider, self).__init__(*args, **kwargs)\n\n def start_requests(self):\n yield self.request_next()\n\n def parse_fund(self, response):\n products = json.loads(response.text)['results'][0]['data']\n\n for p in products:\n self.ips.append({\n 'url': 'http://www.i618.com.cn/servlet/json',\n 'ref': response.url,\n 'form': {\n 'funcNo': '820012',\n 'jjdm': p['jjdm'],\n 'curPage': '1',\n 'numPerPage': '500'\n },\n 'ext': {\n 'fund_name': p['jjmc']\n }\n })\n yield self.request_next()\n\n def parse_item(self, response):\n fund_name = response.meta['ext']['fund_name']\n rows = json.loads(response.text)['results'][0]['data']\n if rows:\n for row in rows:\n nav = row['nav']\n add_nav = row['accumulativenav']\n statistic_date = row['tradedate']\n\n item = GGFundNavItem()\n item['sitename'] = self.sitename\n item['channel'] = self.channel\n item['fund_name'] = fund_name\n item['statistic_date'] = datetime.strptime(statistic_date, '%Y-%m-%d') if statistic_date else None\n item['nav'] = float(nav) if nav else None\n item['added_nav'] = float(add_nav) if add_nav else None\n yield item\n\n response.meta['form']['curPage'] = str(int(response.meta['form']['curPage']) + 1)\n self.ips.append({\n 'url': 'http://www.i618.com.cn/servlet/json',\n 'ref': response.url,\n 'form': response.meta['form'],\n 'ext': {\n 'fund_name': fund_name\n }\n })\n\n yield self.request_next()\n","sub_path":"FundNavSpiders/ShanXiSecurities.py","file_name":"ShanXiSecurities.py","file_ext":"py","file_size_in_byte":2699,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"44981379","text":"from guardian.shortcuts import assign_perm, remove_perm\nfrom rest_framework import serializers as rest_serializers\n\nfrom api import models as api_models\nfrom api.mixins import ReadOnlySerializerMixin\nfrom api.users import serializers as api_users_serializers\n\n\nclass TeamMinimalSerializer(rest_serializers.ModelSerializer, ReadOnlySerializerMixin):\n class Meta:\n model = api_models.Team\n fields = (\n 'id',\n 'name',\n 'rating',\n )\n\n\nclass TeamViewSerializer(rest_serializers.ModelSerializer, ReadOnlySerializerMixin):\n captain_details = api_users_serializers.UserMinimalSerializer(\n read_only=True,\n source='captain',\n )\n participants_details = api_users_serializers.UserMinimalSerializer(\n many=True,\n read_only=True,\n source='participants',\n )\n\n can_edit_team = rest_serializers.BooleanField(read_only=True)\n can_delete_team = rest_serializers.BooleanField(read_only=True)\n\n class Meta:\n model = api_models.Team\n fields = (\n 'id',\n 'name',\n 'created_at',\n 'captain_details',\n 'participants_details',\n 'can_edit_team',\n 'can_delete_team',\n 'rating',\n 'max_rating',\n )\n\n extra_kwargs = {\n 'rating': {\n 'read_only': True,\n },\n 'max_rating': {\n 'read_only': True,\n },\n }\n\n\nclass TeamFullSerializer(rest_serializers.ModelSerializer):\n captain_details = api_users_serializers.UserMinimalSerializer(\n read_only=True,\n source='captain',\n )\n participants_details = api_users_serializers.UserMinimalSerializer(\n many=True,\n read_only=True,\n source='participants',\n )\n\n can_edit_team = rest_serializers.BooleanField(read_only=True)\n can_delete_team = rest_serializers.BooleanField(read_only=True)\n\n class Meta:\n model = api_models.Team\n fields = (\n 'id',\n 'name',\n 'join_token',\n 'created_at',\n 'captain_details',\n 'captain',\n 'rating',\n 'max_rating',\n 'participants_details',\n 'can_edit_team',\n 'can_delete_team',\n )\n\n extra_kwargs = {\n 'rating': {\n 'read_only': True,\n },\n 'max_rating': {\n 'read_only': True,\n },\n }\n\n def validate_captain(self, captain):\n if self.instance and captain:\n if isinstance(captain, int):\n exists = self.instance.participants.filter(id=captain)\n else:\n exists = self.instance.participants.filter(id=captain.id)\n\n if not exists:\n raise rest_serializers.ValidationError('Only a team member can be made captain')\n return captain\n\n def update(self, instance, validated_data):\n if 'join_token' in validated_data:\n name = validated_data.get('name', instance.name)\n validated_data['join_token'] = api_models.Team.gen_join_token(name)\n if 'captain' in validated_data and validated_data['captain'] != instance.captain:\n new_captain = validated_data['captain']\n assign_perm('view_team', new_captain, instance)\n assign_perm('change_team', new_captain, instance)\n assign_perm('delete_team', new_captain, instance)\n\n remove_perm('view_team', instance.captain, instance)\n remove_perm('change_team', instance.captain, instance)\n remove_perm('delete_team', instance.captain, instance)\n\n return super(TeamFullSerializer, self).update(instance, validated_data)\n\n def create(self, validated_data):\n validated_data['captain'] = self.context['request'].user\n validated_data['join_token'] = api_models.Team.gen_join_token(validated_data[\"name\"])\n instance = super(TeamFullSerializer, self).create(validated_data)\n assign_perm('view_team', instance.captain, instance)\n assign_perm('change_team', instance.captain, instance)\n assign_perm('delete_team', instance.captain, instance)\n assign_perm('register_team', instance.captain, instance)\n instance.participants.add(instance.captain)\n return instance\n\n\nclass TeamContestsHistorySerializer(rest_serializers.ModelSerializer, ReadOnlySerializerMixin):\n contest_title = rest_serializers.SlugRelatedField(\n read_only=True,\n slug_field='title',\n source='contest',\n )\n registered_users_details = api_users_serializers.UserMinimalSerializer(\n many=True,\n read_only=True,\n source='registered_users',\n )\n\n class Meta:\n model = api_models.ContestParticipantRelationship\n fields = (\n 'id',\n 'contest',\n 'contest_title',\n 'delta',\n 'has_opened_contest',\n 'registered_users_details',\n )\n","sub_path":"ctforces_backend/api/teams/serializers.py","file_name":"serializers.py","file_ext":"py","file_size_in_byte":5052,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"9410663","text":"import os\nimport shutil\nfrom distutils.dir_util import copy_tree\nimport build_util\n\nBUILD_PATH = os.getcwd()\nWORKSPACE_PATH = f\"{os.getcwd()}/../autolens_workspace\"\nSCRIPTS_ROOT_PATH = f\"{WORKSPACE_PATH}/scripts\"\nSCRIPTS_NO_RUN = [\n \"mask.py\",\n \"positions.py\",\n \"lens_light_centre.py\",\n \"scaled_dataset.py\",\n \"tutorial_3_lens_and_source.py\",\n \"tutorial_4_x2_lens_galaxies.py\",\n \"tutorial_5_complex_source.py\",\n \"tutorial_8_model_fit.py\",\n \"tutorial_6_model_fit.py\",\n \"tutorial_searches.py\",\n \"tutorial_2_samples.py\",\n \"hyper_mode.py\",\n \"pipeline.py\",\n \"light_parametric__mass_total__source_inversion.py\",\n \"Emcee.py\",\n \"PySwarms.py\",\n \"Zeus.py\",\n \"EmceePlotter.py\",\n \"PySwarmsPlotter.py\",\n \"ZeusPlotter.py\",\n \"UltraNestPlotter.py\",\n \"DynestyPlotter.py\",\n]\n\ndef main():\n\n copy_tree(f\"autolens/configs/default\", f\"{WORKSPACE_PATH}/config\")\n\n os.chdir(WORKSPACE_PATH)\n\n if os.path.exists(f\"{WORKSPACE_PATH}/output\"):\n try:\n os.rename(f\"{WORKSPACE_PATH}/output\", f\"{WORKSPACE_PATH}/output_backup\")\n except OSError:\n shutil.rmtree(f\"{WORKSPACE_PATH}/output\")\n\n if not os.path.exists(f\"{WORKSPACE_PATH}/auto_files\"):\n os.system(\"git clone https://github.com/Jammy2211/auto_files --depth 1\")\n\n if not os.path.exists(f\"{WORKSPACE_PATH}/output\"):\n os.mkdir(f\"{WORKSPACE_PATH}/output\")\n\n os.system(f\"cp -r {WORKSPACE_PATH}/auto_files/autolens/output {WORKSPACE_PATH}\")\n\n os.chdir(SCRIPTS_ROOT_PATH)\n\n for folder in [\n \"howtolens\",\n # \"database\"\n ]:\n\n build_util.execute_scripts_in_folder(\n workspace_path=WORKSPACE_PATH,\n folder=folder,\n root_path=f\"{SCRIPTS_ROOT_PATH}/{folder}\",\n scripts_no_run=SCRIPTS_NO_RUN\n )\n\n os.chdir(BUILD_PATH)\n copy_tree(f\"autolens/configs/test\", f\"{WORKSPACE_PATH}/config\")\n\n for folder in [\n # \"imaging\",\n # \"interferometer\",\n # \"point_source\",\n # \"misc\",\n \"plot\"\n ]:\n\n build_util.execute_scripts_in_folder(\n workspace_path=WORKSPACE_PATH,\n folder=folder,\n root_path=f\"{SCRIPTS_ROOT_PATH}/{folder}\",\n scripts_no_run=SCRIPTS_NO_RUN\n )\n\n shutil.rmtree(f\"{WORKSPACE_PATH}/output\")\n os.rename(f\"{WORKSPACE_PATH}/output_backup\", f\"{WORKSPACE_PATH}/output\")\n\n os.chdir(BUILD_PATH)\n copy_tree(f\"autolens/configs/default\", f\"{WORKSPACE_PATH}/config\")\n os.chdir(WORKSPACE_PATH)\n os.system(f\"git add -f config\")\n os.chdir(BUILD_PATH)\n\n os.chdir(WORKSPACE_PATH)\n shutil.rmtree(\"auto_files\")\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"autolens/run_python.py","file_name":"run_python.py","file_ext":"py","file_size_in_byte":2680,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"221276356","text":"\n\n\n\ndato = \"0023EEA9A64B6DC3F89686C6FCB839F7\"\narchivo = \"CDR-2016-31.csv\"\n\n\n\n\n\n\ndef string_from(array):\n prepared_string = \"\"\n string_id = 0\n for string in array:\n \n if (string_id == 0):\n prepared_string += string\n \n else:\n prepared_string += \", \" + string\n \n string_id += 1\n return prepared_string\n\n\n\n\n\nexplore_file = open(archivo)\nconsole_log = open(\"log_\" + dato + \"_in_\" + archivo, \"w\")\n\nheader = False\n\niteration = 0\nfor fact in explore_file:\n if (header):\n header = False\n continue\n \n fact = fact.split(\",\")\n \n if dato in fact:\n console_log.write(str(iteration) + \", \" + string_from(fact))\n \nconsole_log.close()\n","sub_path":"4_data_explorer.py","file_name":"4_data_explorer.py","file_ext":"py","file_size_in_byte":737,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"222701038","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Jan 28 14:32:45 2020\n\n@author: Nillan\n\"\"\"\n\nfrom basketball_reference_scraper.seasons import get_schedule, get_standings\nfrom datetime import timedelta\nimport pandas as pd\nfrom basketball_reference_scraper.teams import get_roster, get_team_stats, get_opp_stats, get_roster_stats, get_team_misc\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom sklearn import preprocessing\n\n\nstart_year = 2010\nend_year = 2013\ndf_columns = ['year', 'team', 'b2b_away_pct', 'b2b_away_wins', 'b2b_away_games', 'season_WL_pct', 'diff']\nfinal_dict = {}\nflat_final = pd.DataFrame(columns = df_columns)\n\n#year = 2010\n\nfor year in range(start_year, end_year, 1):\n all_results = get_schedule(year, playoffs=False)\n teams = all_results.HOME.unique().tolist()\n \n date = str(year) + '-06-06'\n standings = get_standings(date=date)\n combined_standings = pd.concat([standings['EASTERN_CONF'], standings['WESTERN_CONF']])\n combined_standings.TEAM = combined_standings.TEAM.str.rstrip('*')\n\n final_dict[year] = {} \n \n for team in teams:\n #team = 'Miami Heat'\n \n heat_home = all_results[all_results.HOME.eq(team)]\n heat_away = all_results[all_results.VISITOR.eq(team)]\n \n heat = all_results[(all_results['HOME']==team) | (all_results['VISITOR']==team)]\n \n num_games = heat.shape[0]\n \n heat[\"GAME_BEFORE\"] = [False] * num_games\n \n for i in range (0, num_games - 1):\n if (heat.DATE.iloc[i] + timedelta(days = 1) == heat.DATE.iloc[i + 1]):\n heat.GAME_BEFORE.iloc[i] = True\n heat.GAME_BEFORE.iloc[i + 1] = True\n \n heat_b2b = heat[(heat['GAME_BEFORE'] == True)]\n \n heat_b2b_away = heat_b2b[(heat['VISITOR'] == team)]\n heat_b2b_home = heat_b2b[(heat['HOME'] == team)]\n \n num_b2b = heat_b2b.shape[0]\n \n #new df, same structure\n b2b_away = pd.DataFrame(data=None, columns=heat_b2b.columns)\n \n #go thru home, look to see if there is a date + 1 in away, if there is get that data in b2b away\n num_b2b_home = heat_b2b_home.shape[0]\n \n for j in range(0, num_b2b_home):\n \n date = heat_b2b_home.DATE.iloc[j]\n date_pp = pd.Timestamp(date + timedelta(days = 1))\n \n if (date_pp in heat_b2b_away.DATE.tolist()):\n temp = pd.DataFrame(heat_b2b_away[heat_b2b_away['DATE'] == date_pp])\n b2b_away = pd.concat([b2b_away, temp])\n \n num_b2b_away = b2b_away.shape[0]\n num_b2b_away_wins = 0\n \n for i in range(0, num_b2b_away):\n vis_pts = b2b_away.VISITOR_PTS.iloc[i]\n home_pts = b2b_away.HOME_PTS.iloc[i]\n \n if (vis_pts > home_pts):\n num_b2b_away_wins += 1\n \n if (num_b2b_away != 0):\n b2b_away_pct = round(num_b2b_away_wins / num_b2b_away, 2)\n else:\n b2b_away_pct = 0 #0 or null?\n \n temp = combined_standings[combined_standings.TEAM.eq(team)]\n WL_perc = round(float(temp['W/L%']), 2)\n difference = round(b2b_away_pct - WL_perc, 2)\n final_dict[year][team] = {'b2b_away_pct' : b2b_away_pct,\n 'b2b_away_wins' : num_b2b_away_wins,\n 'b2b_away_games' : num_b2b_away,\n 'season_WL_pct' : WL_perc,\n 'diff' : difference}\n\n temp_dict = final_dict[year][team] \n \n temp_dict['year'] = year\n temp_dict['team'] = team\n \n temp_df = pd.DataFrame(temp_dict, index = [0])\n \n cols = temp_df.columns.tolist()\n \n cols = cols[-1:] + cols[:-1]\n cols = cols[-1:] + cols[:-1]\n \n temp_df = temp_df[cols]\n flat_final = pd.concat([temp_df, flat_final])\n\ncorr = flat_final.iloc[: , 2:-1].corr()\nflat_final.iloc[: , 2:-1].head(5).corr()\n\n#normalizing data\n\nnormalized = flat_final.copy()\n\nnormalized.iloc[:, 2:-1].values\n\nx = normalized.iloc[:, 2:-1].values #returns a numpy array\nmin_max_scaler = preprocessing.MinMaxScaler()\nx_scaled = min_max_scaler.fit_transform(x)\nnormalized = pd.DataFrame(x_scaled, columns = df_columns[2:-1])\ncorr = normalized.corr()\n\n#normalized.plot(x = 'b2b_away_pct', y = 'b2b_away_games', kind = 'scatter')\n\n#plt.scatter(x = normalized['b2b_away_pct'], y = normalized['b2b_away_games'])\n\nplt.scatter(y = flat_final['b2b_away_pct'], x = flat_final['season_WL_pct'], s = flat_final['season_WL_pct'] ** -3.5, alpha = .4)\n#plotting\n \n","sub_path":"W:L - B2B_AWAY.py","file_name":"W:L - B2B_AWAY.py","file_ext":"py","file_size_in_byte":4640,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"550329199","text":"#!/usr/bin/python3\n\n\"\"\" Module that defines square \"\"\"\n\n\nclass Square:\n \"\"\" Represents class defining Square parameters \"\"\"\n def __init__(self, size=0, position=(0, 0)):\n \"\"\" Method that initializes size and position \"\"\"\n self.size = size\n self.position = position\n\n @property\n def size(self):\n \"\"\" Getter method to set private size attribute \"\"\"\n return self.__size\n\n @size.setter\n def size(self, value):\n \"\"\" Setter method to set size and raise exceptions \"\"\"\n if not isinstance(value, int):\n raise TypeError(\"size must be an integer\")\n elif value < 0:\n raise ValueError(\"size must be >= 0\")\n else:\n self.__size = value\n\n @property\n def position(self):\n \"\"\" Getter method to set private position attribute \"\"\"\n return self.__position\n\n @position.setter\n def position(self, value):\n \"\"\" Setter method to set position tuple and raise exception \"\"\"\n if not (isinstance(value, tuple) and\n len(value) == 2 and\n isinstance(value[0], int) and\n isinstance(value[1], int) and\n min(value) >= 0):\n raise TypeError(\"position must be a tuple of 2 positive integers\")\n else:\n self.__position = value\n\n def area(self):\n \"\"\" Method that calculates area by base * height of square \"\"\"\n area = self.size ** 2\n return area\n\n def my_print(self):\n \"\"\" Method to print square defined in class \"\"\"\n if self.size == 0:\n print()\n else:\n for downP in range(self.position[1]):\n print()\n for downS in range(self.size):\n for acrossP in range(self.position[0]):\n print(\" \", end=\"\")\n for acrossS in range(self.size):\n print(\"#\", end=\"\")\n print()\n","sub_path":"0x06-python-classes/6-square.py","file_name":"6-square.py","file_ext":"py","file_size_in_byte":1939,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"43776035","text":"# Given a string, determine if a permutation of the string could form a palindrome.\n\n# For example,\n# \"code\" -> False, \"aab\" -> True, \"carerac\" -> True.\n\n# Hint:\n\n# Consider the palindromes of odd vs even length. What difference do you notice?\n# Count the frequency of each character.\n# If each character occurs even number of times, then it must be a palindrome. How about character which occurs odd number of times?\n\nclass Solution:\n def canPermutePalindrome(self, s):\n if len(s) < 2:\n return True\n mapping = dict()\n for ss in s:\n if mapping.has_key(ss):\n mapping[ss] += 1\n else:\n mapping[ss] = 1\n return sum(v%2 for v in mapping.values()) < 2 \n \n\nclass Solution:\n def canPermutePalindrome(self, s):\n return sum(v % 2 for v in collections.Counter(s).values()) < 2\n \n# Given a string, determine if a permutation of the string could form a palindrome.\n\n# For example,\n# \"code\" -> False, \"aab\" -> True, \"carerac\" -> True.\n\n# 题解:\n# HashMap,奇数个的character的种类不能超过1.\n","sub_path":"LEETCODE/Palindrome_Permutation.py","file_name":"Palindrome_Permutation.py","file_ext":"py","file_size_in_byte":1048,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"530242609","text":"# coding:utf-8\n\nfrom flask import jsonify, json, request\nfrom flask_jwt_extended import jwt_required\n\nfrom common.FormatStr import dictRemoveNone\nfrom common.Log import queryLog, addLog, deleteLog, updateLog\nfrom common.OperationOfDB import conditionDataListFind, findById, deleteById, insertToSQL, updataById, \\\n sqlFunctionCallBoss\nfrom common.ReturnMessage import returnMsg, errorCode, returnErrorMsg\nfrom models.Boss.Organization import Organization, tableChangeDic\nfrom models.Boss.Role import Role\nfrom models.Boss.User import User\nfrom version.v3.bossConfig import app\n\n\n# 获取 列表\n@app.route(\"/findOrganizationByCondition\", methods=[\"POST\"])\n@jwt_required\n@queryLog('boss_organization')\ndef findOrganizationBycondition():\n jsonData = request.get_data()\n dataDict = json.loads(jsonData)\n if dataDict.get('condition', None) == None:\n resultDict = returnErrorMsg(errorCode[\"param_error\"])\n return jsonify(resultDict)\n tablename = Organization.__tablename__\n # multiSort: {field: [\"ozSort\"], sort: [\"asc\"]}\n intColumnClinetNameList = [u'id', u'ozPid', u'ozSort', u'isLock']\n orderByStr = \" order by oz_sort asc \"\n tableList, count = conditionDataListFind(dataDict, tableChangeDic, intColumnClinetNameList, tablename,\n orderByStr=orderByStr)\n if tableList:\n InfoList = []\n for tableData in tableList:\n infoDict = {\"id\": tableData[0],\n \"ozName\": tableData[1],\n \"ozPid\": tableData[2],\n \"ozSort\": tableData[3],\n \"ozCode\": tableData[4],\n \"isLock\": tableData[5],\n \"remark\": tableData[6], }\n infoDict = dictRemoveNone(infoDict)\n InfoList.append(infoDict)\n resultDict = returnMsg(InfoList)\n resultDict[\"total\"] = count\n else:\n resultDict = returnErrorMsg()\n return jsonify(resultDict)\n\n\n# 获取详情 \n@app.route(\"/getOrganizationDetail\", methods=[\"POST\"])\n@jwt_required\n@queryLog('boss_organization')\ndef getOrganizationDetail():\n jsonData = request.get_data()\n dataDict = json.loads(jsonData)\n id = dataDict.get(\"id\", [])\n if not id:\n resultDict = returnErrorMsg(errorCode[\"param_error\"])\n return jsonify(resultDict)\n\n table = findById(Organization, \"id\", id)\n if not table:\n resultDict = returnMsg(\"not find table\")\n return jsonify(resultDict)\n infoDict = {\"id\": table.id,\n \"ozName\": table.oz_name,\n \"ozPid\": table.oz_pid,\n \"ozSort\": table.oz_sort,\n \"ozCode\": table.oz_code,\n \"isLock\": table.is_lock,\n \"remark\": table.remark, }\n infoDict = dictRemoveNone(infoDict)\n resultDict = returnMsg(infoDict)\n return jsonify(resultDict)\n\n\n# 删除 \n@app.route(\"/deleteOrganization\", methods=[\"POST\"])\n@jwt_required\n@deleteLog('boss_organization')\ndef deleteOrganization():\n jsonData = request.get_data()\n dataDict = json.loads(jsonData)\n ids = dataDict.get(\"idArray\", [])\n if not ids:\n resultDict = returnErrorMsg(errorCode[\"param_error\"])\n return jsonify(resultDict)\n for id in ids:\n table = Organization.query.filter(Organization.oz_pid == id).all()\n if table:\n resultDict = returnErrorMsg(errorCode[\"oz_oz\"])\n return jsonify(resultDict)\n usertable = User.query.filter(User.oz_id == id).first()\n if usertable:\n resultDict = returnErrorMsg(errorCode[\"oz_people\"])\n return jsonify(resultDict)\n\n table = deleteById(Organization, ids, \"id\")\n if table:\n resultDict = returnMsg({})\n return jsonify(resultDict)\n else:\n resultDict = returnErrorMsg(errorCode[\"param_error\"])\n return jsonify(resultDict)\n\n\n# 添加 \n@app.route(\"/addOrganization\", methods=[\"POST\"])\n@jwt_required\n@addLog('boss_organization')\ndef addOrganization():\n jsonData = request.get_data()\n dataDict = json.loads(jsonData)\n columsStr = (dataDict.get(\"ozName\", None), dataDict.get(\"ozPid\", None), dataDict.get(\"ozSort\", None),\n dataDict.get(\"ozCode\", None), dataDict.get(\"isLock\", None), dataDict.get(\"remark\", None))\n table = insertToSQL(Organization, *columsStr)\n if not table:\n resultDict = returnErrorMsg(errorCode[\"system_error\"])\n return jsonify(resultDict)\n resultDict = returnMsg({})\n return jsonify(resultDict)\n\n\n# 更新 \n@app.route(\"/updataOrganization\", methods=[\"POST\"])\n@jwt_required\n@updateLog('boss_organization')\ndef updataOrganization():\n jsonData = request.get_data()\n dataDict = json.loads(jsonData)\n id = dataDict.get(\"id\", \"\")\n if not id:\n resultDict = returnErrorMsg(errorCode[\"param_error\"])\n return jsonify(resultDict)\n intColumnClinetNameList = [u'id', u'ozPid', u'ozSort', u'isLock']\n table = updataById(Organization, dataDict, \"id\", id, tableChangeDic, intColumnClinetNameList)\n\n if table:\n resultDict = returnMsg({})\n return jsonify(resultDict)\n else:\n resultDict = returnErrorMsg(errorCode[\"system_error\"])\n return jsonify(resultDict)\n\n\n@app.route(\"/findUserOzByConditions\", methods=[\"POST\"])\n@jwt_required\n@queryLog(\"base_user\")\ndef findUserOzByConditions():\n jsonData = request.get_data()\n dataDict = json.loads(jsonData)\n roleId = dataDict.get(\"roleId\", None)\n if not roleId:\n resultDict = returnErrorMsg(errorCode[\"param_error\"])\n return jsonify(resultDict)\n if dataDict.get('condition', None) == None:\n resultDict = returnErrorMsg(errorCode[\"param_error\"])\n return jsonify(resultDict)\n else:\n role = Role.query.filter(Role.role_id == roleId).first()\n if not role:\n resultDict = returnErrorMsg(errorCode[\"param_error\"])\n return jsonify(resultDict)\n ozId = role.oz_id\n intColumnClinetNameList = (\"adminId\", \"isLock\", 'ozId', 'ozPid', 'ozSort', 'isLock')\n # tableName = User.__tablename__\n resultList = sqlFunctionCallBoss(\"call getUserRoleOz({})\".format(roleId))\n\n # tableName = \"view_user_role_oz\"\n # newChangeDic = dict(tableChangeDic, **userChangeDic)\n # # ozList = Organization.query.filter(Organization.id != 1).all()\n ozList = Organization.query.filter(Organization.id == ozId).all()\n # adminsList, count = conditionDataListFind(dataDict, newChangeDic, intColumnClinetNameList, tableName)\n if resultList:\n talbeList = []\n infoLists = []\n for talbe in resultList:\n talbeList.append(talbe)\n for ozInfo in ozList:\n allList = {}\n allList[\"id\"] = \"b\" + str(ozInfo.id)\n allList[\"isMenu\"] = True\n allList[\"ids\"] = ozInfo.id\n allList[\"pid\"] = ozInfo.oz_pid\n allList[\"text\"] = ozInfo.oz_name\n infoList = []\n for table in talbeList:\n # if table.role_pid == roleId:\n infoList.append({\"id\": table.admin_id,\n \"text\": table.admin_real_name, \"adminName\": table.admin_name,\n \"ozId\":ozInfo.id})\n if infoList == []:\n continue\n allList[\"children\"] = infoList\n infoLists.append(allList)\n # ids = [ozs[\"ids\"] for ozs in infoLists]\n # for oz in infoLists:\n # for id in ids:\n # if oz[\"pid\"] == id:\n # infoLists[ids.index(id)][\"children\"].append(oz)\n # infoLists.remove(oz)\n resultDict = returnMsg(infoLists)\n resultDict[\"total\"] = len(infoLists)\n else:\n resultDict = returnMsg({})\n # resultDict = returnErrorMsg()\n return jsonify(resultDict)\n","sub_path":"boss_service/controllers/OrganizationApi.py","file_name":"OrganizationApi.py","file_ext":"py","file_size_in_byte":7984,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"369428705","text":"from typing import Iterable, List\n\nimport resolvelib\n\nfrom mach_nix.data.nixpkgs import NixpkgsIndex\nfrom mach_nix.data.providers import DependencyProviderBase, Candidate\nfrom mach_nix.deptree import remove_circles_and_print\nfrom mach_nix.requirements import Requirement, filter_versions\nfrom mach_nix.resolver import Resolver, ResolvedPkg\n\n\n# Implement logic so the resolver understands the requirement format.\nclass Provider:\n def __init__(self, nixpkgs: NixpkgsIndex, deps_db: DependencyProviderBase):\n self.nixpkgs = nixpkgs\n self.provider = deps_db\n\n def get_extras_for(self, dependency):\n # return selected extras\n return tuple(sorted(dependency.selected_extras))\n\n def get_base_requirement(self, candidate):\n return Requirement(\"{}=={}\".format(candidate.name, candidate.ver))\n\n def identify(self, dependency):\n return dependency.name\n\n def get_preference(self, resolution, candidates, information):\n return len(candidates)\n\n def find_matches(self, req):\n return self.provider.find_matches(req)\n\n def is_satisfied_by(self, requirement, candidate: Candidate):\n res = bool(len(list(filter_versions([candidate.ver], requirement))))\n return res\n\n def get_dependencies(self, candidate):\n install_requires, setup_requires = self.provider.get_pkg_reqs(candidate)\n deps = install_requires + setup_requires\n return deps\n\n\nclass ResolvelibResolver(Resolver):\n def __init__(self, nixpkgs: NixpkgsIndex, deps_provider: DependencyProviderBase):\n self.nixpkgs = nixpkgs\n self.deps_provider = deps_provider\n\n def resolve(self, reqs: Iterable[Requirement]) -> List[ResolvedPkg]:\n reporter = resolvelib.BaseReporter()\n result = resolvelib.Resolver(Provider(self.nixpkgs, self.deps_provider), reporter).resolve(reqs, max_rounds=1000)\n nix_py_pkgs = []\n for name in result.graph._forwards.keys():\n if name is None or name.startswith('-'):\n continue\n candidate = result.mapping[name]\n ver = candidate.ver\n install_requires, setup_requires = self.deps_provider.get_pkg_reqs(candidate)\n prop_build_inputs = list(filter(\n lambda name: not name.startswith('-'),\n list({req.key for req in install_requires})))\n build_inputs = list(filter(\n lambda name: not name.startswith('-'),\n list({req.key for req in setup_requires})))\n is_root = name in result.graph._forwards[None]\n nix_py_pkgs.append(ResolvedPkg(\n name=name,\n ver=ver,\n build_inputs=build_inputs,\n prop_build_inputs=prop_build_inputs,\n is_root=is_root,\n provider_info=candidate.provider_info,\n extras_selected=list(result.mapping[name].selected_extras),\n build=candidate.build\n ))\n remove_circles_and_print(nix_py_pkgs, self.nixpkgs)\n return nix_py_pkgs\n","sub_path":"mach_nix/resolver/resolvelib_resolver.py","file_name":"resolvelib_resolver.py","file_ext":"py","file_size_in_byte":3064,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"30889911","text":"import nltk\r\nfrom nltk.tokenize import word_tokenize\r\nimport numpy as np\r\nimport random\r\nimport pickle\r\nfrom collections import Counter\r\nfrom nltk.stem import WordNetLemmatizer\r\nimport tensorflow as tf\r\nlemmatizer = WordNetLemmatizer()\r\n\r\n\r\n\r\n# here we aredefining how many nodes each layer should have..\r\n# input layer has already 28 X 28 nodes\r\nn_nodes_hl1 = 500\r\nn_nodes_hl2 = 500\r\nn_nodes_hl3 = 500\r\nn_classes = 10\r\n\r\n# We also can compile whole data set in one go...but it is good to go \r\n# with 100 data ate once\r\nbatch_size = 100\r\n\r\n# PlaceHolders for some values\r\nx = tf.placeholder('float', [None, 423])\r\ny = tf.placeholder('float')\r\n\r\n\r\n\r\n\r\n\r\ndef nural_network_model(data,w1,b1,w2,b2,w3,b3,wo,bo):\r\n '''\r\n hidden_1_layer ={'weights' : tf.Variable(tf.random_normal([784,n_nodes_hl1])),\r\n 'biases' : tf.Variable(tf.random_normal([n_nodes_hl1]))}\r\n hidden_2_layer = {'weights' : tf.Variable(tf.random_normal([n_nodes_hl1,n_nodes_hl2])),\r\n 'biases' : tf.Variable(tf.random_normal([n_nodes_hl2]))}\r\n hidden_3_layer = {'weights' : tf.Variable(tf.random_normal([n_nodes_hl2,n_nodes_hl3])),\r\n 'biases' : tf.Variable(tf.random_normal([n_nodes_hl3]))}\r\n output_layer = {'weights' : tf.Variable(tf.random_normal([n_nodes_hl3,n_classes])),\r\n 'biases' : tf.Variable(tf.random_normal([n_classes]))}\r\n '''\r\n l1= tf.add(tf.matmul(([data]),w1),b1)\r\n l1=tf.nn.relu(l1)\r\n \r\n l2= tf.add(tf.matmul(l1,w2),b2)\r\n l2=tf.nn.relu(l2)\r\n \r\n l3= tf.add(tf.matmul(l2,w3),b3)\r\n l3=tf.nn.relu(l3)\r\n \r\n output= tf.add(tf.matmul(l3,wo),bo)\r\n \r\n return output\r\n\r\n\r\n\r\n \r\n\r\ndef use_neural_network(input_data):\r\n \r\n \r\n #prediction = nural_network_model(x)\r\n tf.reset_default_graph() \r\n saver2 = tf.train.import_meta_graph('drive/My Drive/ml4/mymodel.meta')\r\n\r\n with tf.Session() as sess:\r\n sess.run(tf.global_variables_initializer())\r\n saver2.restore(sess, 'drive/My Drive/ml4/mymodel')\r\n graph = tf.get_default_graph()\r\n \r\n with open('drive/My Drive/lexicon.pickle','rb') as f:\r\n lexicon = pickle.load(f)\r\n print(\"lexion\",len(lexicon))\r\n current_words = word_tokenize(input_data.lower())\r\n current_words = [lemmatizer.lemmatize(i) for i in current_words]\r\n features = np.zeros(len(lexicon))\r\n\r\n for word in current_words:\r\n if word.lower() in lexicon:\r\n index_value = lexicon.index(word.lower())\r\n print(index_value)\r\n # OR DO +=1, test both\r\n features[index_value] += 1\r\n\r\n #features = np.array(list(features))\r\n \r\n #features=np.array(((features)))\r\n features=np.array(features)\r\n features=tf.convert_to_tensor(features, np.float32)\r\n print(\"features\",sess.run(features))\r\n w1 = graph.get_tensor_by_name(\"wh1:0\")\r\n b1 = graph.get_tensor_by_name(\"bh1:0\")\r\n w2 = graph.get_tensor_by_name(\"wh2:0\") \r\n b2 = graph.get_tensor_by_name(\"bh2:0\")\r\n w3 = graph.get_tensor_by_name(\"wh3:0\")\r\n b3 = graph.get_tensor_by_name(\"bh3:0\")\r\n wo = graph.get_tensor_by_name(\"wo:0\") \r\n bo = graph.get_tensor_by_name(\"bo:0\")\r\n result=nural_network_model(features,w1,b1,w2,b2,w3,b3,wo,bo)\r\n result=tf.reshape(result, [2])\r\n print(sess.run(result))\r\n print(sess.run(tf.argmax(result)))\r\n '''\r\n wh1 = graph.get_tensor_by_name(\"wh1:0\")\r\n print(sess.run(wh1))\r\n \r\n \r\n result = (sess.run(tf.argmax(prediction.eval(feed_dict={x:[input_data]}),1)))\r\n print(result[0])\r\n \r\n \r\n '''\r\nuse_neural_network(\"everyone blames her\")\r\n","sub_path":"testing_model.py","file_name":"testing_model.py","file_ext":"py","file_size_in_byte":3740,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"342433456","text":"import argparse\nfrom os import listdir, path\nimport calendar\nimport datetime\nimport textwrap\n\n\ndef create_new():\n parser = argparse.ArgumentParser()\n parser.add_argument('--root', help='Root directory for notes.')\n\n args = parser.parse_args()\n\n root_dir = args.root\n\n now = datetime.datetime.now()\n year = now.year\n month = str(now.month).zfill(2)\n month_name = now.strftime(('%B'))\n day = str(now.day).zfill(2)\n day_of_week = calendar.day_name[now.weekday()]\n\n current_month_dir = '{root}/{y}/{y}{m} {m_name}'.format(root=root_dir, y=year, m=month, m_name=month_name)\n\n latest_file = '{}/{}'.format(current_month_dir, max(listdir(current_month_dir)))\n\n with open(latest_file, 'r') as fin:\n data = fin.read().splitlines(True)\n\n today_header = '# {d_of_week}, {m_name} {d}, {y}'.format(d_of_week=day_of_week, m_name=month_name, d=day, y=year)\n\n new_header = textwrap.dedent('''\\\n {}\n \n To-Do List \n Personal Calendar\n Personal Email\n Work Calendar\n Work Email\n '''.format(today_header)).splitlines(keepends=True)\n\n new_data = new_header + data[1:]\n\n today_file = '{root}/{y}-{m}-{d}-{d_of_week}.md'.format(root=current_month_dir, y=year, m=month, d=day,\n d_of_week=day_of_week)\n\n if path.exists(today_file):\n print(\"File already exists for today.\")\n else:\n with open(today_file, 'w') as fout:\n fout.writelines(new_data)\n print('Successfully created new notes files for {}'.format(today_header))\n\nif __name__ == '__main__':\n create_new()\n","sub_path":"daily_notes.py","file_name":"daily_notes.py","file_ext":"py","file_size_in_byte":1650,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"502865151","text":"#----------------------------------------------\n# -*- encoding=utf-8 -*- #\n# __author__:'xiaojie' #\n# CreateTime: #\n# 2019/4/12 10:38 #\n# #\n# 天下风云出我辈, #\n# 一入江湖岁月催。 #\n# 皇图霸业谈笑中, #\n# 不胜人生一场醉。 #\n#----------------------------------------------\n\n# 总结:该示例代码用的还是WGAN,损失函数还是原始的WGAN的损失函数,只不过,还用了谱归一化的技术。\n#谱归一化\n\n# 参考《深度学习中的Lipschitz约束:泛化与生成模型》:\n# https://zhuanlan.zhihu.com/p/46924315\n# https://github.com/bojone/gan/blob/master/keras/wgan_sn_celeba.py\n\n# 实现基于“谱归一化”的Keras代码,实现方式是添加kernel_constraint\n# 注意使用代码前还要修改Keras源码,修改\n# keras/engine/base_layer.py的Layer对象的add_weight方法\n\n\nimport numpy as np\nfrom scipy import misc\nimport glob\nfrom keras.models import Model\nfrom keras.layers import *\nfrom keras import backend as K\nfrom keras.optimizers import Adam\nimport os\nfrom keras.utils import plot_model\n\nif not os.path.exists('samples'):\n os.mkdir('samples')\n\nimgs = glob.glob('../../images/img_align_celeba/*.jpg')\nnp.random.shuffle(imgs)\n\n\nheight,width = misc.imread(imgs[0]).shape[:2]\ncenter_height = int((height-width)/2)\nimg_dim = 64\nz_dim = 100\n\ndef imread(f):\n x = misc.imread(f)\n x=x[center_height:center_height+width,:]\n x = misc.imresize(x,(img_dim,img_dim))\n return x.astype(np.float32)/255*2-1\n\ndef data_generator(batch_size = 32):\n X=[]\n while True:\n np.random.shuffle(imgs)\n for f in imgs:\n X.append(imread(f))\n if len(X) == batch_size:\n X = np.array(X)\n yield X\n X=[]\n\ndef spectral_norm(w,r=5):\n w_shape=K.int_shape(w)\n in_dim=np.prod(w_shape[:-1]).astype(int)\n out_dim = w_shape[-1]\n w = K.reshape(w,(in_dim,out_dim))\n u = K.ones((1,in_dim))\n for i in range(r):\n v = K.l2_normalize(K.dot(u,w))\n u = K.l2_normalize(K.dot(v,K.transpose(w)))\n return K.sum(K.dot(K.dot(u,w),K.transpose(v)))\n\ndef spectral_normalization(w):\n return w/spectral_norm(w)\n\n# 判别器\nx_in = Input(shape=(img_dim,img_dim,3))\nx=x_in\n\nx=Conv2D(img_dim,\n (5,5),\n strides=(2,2),\n padding='same',\n kernel_constraint=spectral_normalization)(x)\nx=LeakyReLU()(x)\n\nfor i in range(3):\n x=Conv2D(img_dim*2**(i+1),\n (5,5),\n strides=(2,2),\n padding='same',\n kernel_constraint=spectral_normalization)(x)\n x=BatchNormalization(gamma_constraint=spectral_normalization)(x)\n x=LeakyReLU()(x)\n\nx=Flatten()(x)\nx=Dense(1,use_bias=False,kernel_constraint=spectral_normalization)(x)\n\nd_model=Model(x_in,x)\nplot_model(d_model,to_file='./png/w_gan_sn_d_model.png',show_shapes=True)\n\n# 生成器\nz_in = Input(shape=(z_dim,))\nz=z_in\n\nz=Dense(4*4*img_dim*8)(z)\nz=BatchNormalization()(z)\nz=Activation('relu')(z)\nz=Reshape((4,4,img_dim*8))(z)\n\nfor i in range(3):\n z=Conv2DTranspose(img_dim*4//2**i,(5,5),strides=(2,2),padding='same')(z)\n z=BatchNormalization()(z)\n z=Activation('relu')(z)\n\nz=Conv2DTranspose(3,(5,5),strides=(2,2),padding='same')(z)\nz=Activation('tanh')(z)\n\ng_model=Model(z_in,z)\nplot_model(d_model,to_file='./png/w_gan_sn_g_model.png',show_shapes=True)\n\n# 整合模型(训练判别器)\nx_in = Input(shape=(img_dim,img_dim,3))\nz_in=Input(shape=(z_dim,))\ng_model.trainable=False\n\nx_fake=g_model(z_in)\nx_real_score=d_model(x_in)\nx_fake_score=d_model(x_fake)\n\nd_train_model=Model([x_in,z_in],[x_real_score,x_fake_score])\n\nd_loss=K.mean(x_fake_score-x_real_score)\nd_train_model.add_loss(d_loss)\nd_train_model.compile(optimizer=Adam(2e-4,0.5))\n\n#整合模型(训练生成器)\ng_model.trainable=True\nd_model.trainable=False\nx_fake_score=d_model(g_model(z_in))\n\ng_train_model=Model(z_in,x_fake_score)\ng_train_model.add_loss(K.mean(-x_fake_score))\ng_train_model.compile(optimizer=Adam(2e-4,0.5))\n\n\n#检查模型结构\nplot_model(d_train_model,to_file='./png/w_gan_sn_d_train_model.png',show_shapes=True)\nplot_model(g_train_model,to_file='./png/w_gan_sn_g_train_model.png',show_shapes=True)\n\n\n#采样函数\ndef sample(path):\n n = 9\n figure = np.zeros((img_dim * n, img_dim * n, 3))\n for i in range(n):\n for j in range(n):\n z_sample = np.random.randn(1, z_dim)\n x_sample = g_model.predict(z_sample)\n digit = x_sample[0]\n figure[i * img_dim:(i + 1) * img_dim,\n j * img_dim:(j + 1) * img_dim] = digit\n figure = (figure + 1) / 2 * 255\n figure = np.round(figure, 0).astype(int)\n misc.imsave(path, figure)\n\n\niter_per_sample=100\ntotal_iter=1000000\nbatch_size=20\nimg_generator=data_generator(batch_size)\n\nfor i in range(total_iter):\n for j in range(5):\n z_sample=np.random.randn(batch_size,z_dim)\n d_loss2 = d_train_model.train_on_batch([next(img_generator),z_sample],None)\n for j in range(1):\n z_sample = np.random.randn(batch_size,z_dim)\n g_loss = g_train_model.train_on_batch(z_sample,None)\n if i%10==0:\n print('iter: %s, d_loss: %s, g_loss: %s' % (i, d_loss2, g_loss))\n if i%iter_per_sample ==0:\n # sample('sample/test_%s.png'%i)\n sample('samples/test_%s.png' % i)\n g_train_model.save_weights('./g_train_model.weights')\n\n","sub_path":"wgan相关/wgan_sn_celeba.py","file_name":"wgan_sn_celeba.py","file_ext":"py","file_size_in_byte":5609,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"588611940","text":"from config import *\nimport pymysql\nimport urllib.parse\nimport urllib.request\nimport http.client\nimport hashlib\nimport json\n\nSTART_ID = 1000001 # 数据库连接\nCOUNT = 0\nappid = '20190410000286677' # 百度的翻译接口,需要自己填\nsecretKey = '1Sizz2cmcYlRg3hw51QX'\nSQL_Q = \"select content from forums where id = %d\"\nSQL_I = \"update forums set content = %s where id = %d\"\n\nconnect = pymysql.connect(\n\n host = MYSQL_HOST,\n port = MYSQL_PORT,\n user = MYSQL_USER,\n passwd = MYSQL_PASSWD,\n db = MYSQL_DBNAME,\n charset = MYSQL_CHARSET\n)\n\ndef query_content(count): # 数据查询\n\n cursor = connect.cursor()\n id = START_ID + count\n mysql = SQL_Q % (id)\n cursor.execute(mysql)\n result = cursor.fetchone()\n content_ru = result[0].strip()\n return content_ru,id\n\ndef insert_content(content,id): # 翻译后的数据更新\n\n cursor = connect.cursor()\n mysql = SQL_I % (content,id)\n cursor.execute(mysql)\n connect.commit()\n\ndef trans_en(ori_content): # 构造url,进行翻译\n httpClient = None\n myurl = '/api/trans/vip/translate'\n q = ori_content\n fromLang = 'auto'\n toLang = 'en'\n salt = random.randint(32768, 65536)\n sign = appid + q + str(salt) + secretKey\n sign = sign.encode('UTF-8')\n m1 = hashlib.md5()\n m1.update(sign)\n sign = m1.hexdigest()\n myurl = myurl + '?appid=' + appid + '&q=' + urllib.parse.quote(\n q) + '&from=' + fromLang + '&to=' + toLang + '&salt=' + str(salt) + '&sign=' + sign\n\n try:\n httpClient = http.client.HTTPConnection('api.fanyi.baidu.com')\n httpClient.request('GET', myurl)\n # response是HTTPResponse对象\n response = httpClient.getresponse()\n result = response.read().decode(\"utf-8\")\n target = json.loads(result)\n src = target[\"trans_result\"][0][\"dst\"]\n return src\n except Exception as e:\n return e\n finally:\n if httpClient:\n httpClient.close()\n\ndef content_deal(content): # 超长字符处理,这里定义google最大支持翻译字符串长度为4900\n\n if len(content) <= 4900:\n en_contant = trans_en(content).strip()\n\n else: # 超长字符串处理\n len_num = int(len(content)/4900)\n content_list = []\n trans_content = ''\n for k in range(len_num + 1):\n temp = content[4900*k:4900*(k+1) + 1]\n content_list.append(temp)\n\n for str in content_list:\n trans_content = trans_content + trans_en(str)\n\n en_contant = trans_content.strip()\n\n return en_contant\n\nif __name__ == \"__main__\":\n\n for num in range(3599):\n\n count = num + COUNT\n content_ru, id = query_content(count)\n en_contant = trans_en(content_ru)\n print(id)\n print(content_ru)\n print(en_contant)\n # insert_content(en_contant,id)\n\n\n\n","sub_path":"baidu-translate/translate.py","file_name":"translate.py","file_ext":"py","file_size_in_byte":2906,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"4773323","text":"import numpy as np\nimport matplotlib as mpl\nmpl.use('Agg', warn=False, force=True)\nimport matplotlib.pyplot as plt\nimport iris\nimport iris.plot as iplt\nimport os\nimport warnings\nimport logging\nfrom ffff import rPeriod_, schF_keys_, iter_str_\nfrom cccc import extract_period_cube, guessBnds_cube, load_res_\nfrom pppp import pdf_iANDe_, axColor_, aligned_tx_\n\n\ndef main():\n import argparse\n import yaml\n parser = argparse.ArgumentParser('map plot (hwmi)')\n parser.add_argument(\"controlfile\",\n help=\"yaml file with metadata\")\n args = parser.parse_args()\n with open(args.controlfile, 'r') as ymlfile:\n cfg = yaml.safe_load(ymlfile)\n warnings.filterwarnings(\"ignore\",\n message=\"Collapsing a non-contiguous coordinate.\")\n\n #periods\n p0s = [2020, 2070]\n\n #directory options\n odir = cfg['root'] + cfg['experiment'] + '/' + cfg['fig']\n os.makedirs(odir, exist_ok=True)\n fnf = odir + cfg['v'] + '_HISTvsRCP' + cfg['fn_pdf']\n idir = cfg['root'] + cfg['experiment'] + '/' + cfg['res']\n\n #############################\n\n fig = plt.figure(figsize = (8, 8))\n fig.subplots_adjust(hspace=0.1, wspace=0.075,\n top=0.95, bottom=0.075,\n left=0.075, right=0.95)\n #colors\n #prop_cycle = plt.rcParams['axes.prop_cycle']\n #colors = prop_cycle.by_key()['color']\n colors = ['tab:blue', 'tab:cyan', 'tab:green', 'tab:orange', 'tab:red',\n 'tab:purple','tab:gray']\n\n #axes option\n xtk = [.125, .25, .5, 1, 2, 4, 8, 16, 32]\n xtkl = iter_str_(xtk)\n ax_opt = {'ylim': [0, .8],\n 'xlim': [np.log(.125), np.log(32)],\n 'xticks': np.log(xtk),\n 'xticklabels': xtkl,\n 'facecolor': 'lightgray'}\n ##cmp\n ax1 = fig.add_subplot(2, 1, 1, **ax_opt)\n aligned_tx_(fig, ax1, 'CMIP5', rpo='tc', itv=-0.005)\n ##cdx\n ax_opt.update({'xlabel': 'HWMI'})\n ax2 = fig.add_subplot(2, 1, 2, **ax_opt)\n aligned_tx_(fig, ax2, 'CORDEX', rpo='tc', itv=-0.005)\n\n el = []\n lg = []\n ##obs\n ddir = idir + 'obs/'\n color = 'black'\n [il0, el0] = pdf_iANDe_(ax1, color, cfg, ddir, cfg['dn_obs'],\n [1986, 2005], True)\n pdf_iANDe_(ax2, color, cfg, ddir, cfg['dn_obs'], [1986, 2005], True)\n el.append(el0)\n lg.append(rPeriod_([1986, 2005], True) + ' (EOBS)')\n\n ##cmp&cdx\n #hist\n ddir = idir + 'cmip5/hist/'\n color = colors[0]\n [il0, el0] = pdf_iANDe_(ax1, color, cfg, ddir, cfg['dn_cmp'],\n [1986, 2005], True)\n el.append(el0)\n lg.append(rPeriod_([1986, 2005], True) + ' (Historical)')\n ddir = idir + 'cordex/hist/'\n pdf_iANDe_(ax2, color, cfg, ddir, cfg['dn_cdx'], [1986, 2005], True)\n for i, p0 in enumerate(p0s):\n #rcp45\n ddir = idir + 'cmip5/rcp45/'\n color = colors[i + 1]\n p = [p0, p0 + 29]\n [il0, el0] = pdf_iANDe_(ax1, color, cfg, ddir, cfg['dn_cmp'], p, True)\n el.append(el0)\n lg.append(rPeriod_(p, True) + ' (RCP45)')\n ddir = idir + 'cordex/rcp45/'\n pdf_iANDe_(ax2, color, cfg, ddir, cfg['dn_cdx'], p, True)\n #rcp85\n ddir = idir + 'cmip5/rcp85/'\n color = colors[i + 3]\n [il0, el0] = pdf_iANDe_(ax1, color, cfg, ddir, cfg['dn_cmp'], p, True)\n el.append(el0)\n lg.append(rPeriod_(p, True) + ' (RCP85)')\n ddir = idir + 'cordex/rcp85/'\n pdf_iANDe_(ax2, color, cfg, ddir, cfg['dn_cdx'], p, True)\n\n #more settings\n ax1.grid(True, color='w', zorder=-5)\n ax1.tick_params(length=0.)\n axColor_(ax1, None)\n ax1.legend(el, lg)\n ax2.grid(True, color='w', zorder=-5)\n ax2.tick_params(length=0.)\n axColor_(ax2, None)\n\n plt.savefig(fnf, **cfg['sv_opts'])\n plt.close()\n\nif __name__ == '__main__':\n main()\n","sub_path":"climi/pppp/plt_hwmi_pdf_HISTvsRCP.py","file_name":"plt_hwmi_pdf_HISTvsRCP.py","file_ext":"py","file_size_in_byte":3846,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"455610267","text":"from django.db import models\n\n\nclass MaternalPostFuDxTManager(models.Manager):\n\n def get_by_natural_key(self, lab_del_dx, report_datetime, visit_instance, appt_status, visit_definition_code, subject_identifier_as_pk):\n MaternalVisit = models.get_model('mpepu_maternal', 'MaternalVisit')\n MaternalPostFuDx = models.get_model('mpepu_maternal', 'MaternalPostFuDx')\n maternal_visit = MaternalVisit.objects.get_by_natural_key(report_datetime, visit_instance, appt_status, visit_definition_code, subject_identifier_as_pk)\n maternal_post_fu_dx = MaternalPostFuDx.objects.get(maternal_visit=maternal_visit)\n return self.get(lab_del_dx=lab_del_dx, maternal_post_fu_dx=maternal_post_fu_dx)\n","sub_path":"bhp056/apps/mpepu_maternal/managers/maternal_post_fu_dx_t_manager.py","file_name":"maternal_post_fu_dx_t_manager.py","file_ext":"py","file_size_in_byte":718,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"179360511","text":"from astropy.io import fits\nimport numpy as np\nimport matplotlib.pyplot as plt\n\ndef angbin(angle):\n\tswitcher = {\n\t\t0.71336: 1,\n\t\t1.45210: 2,\n\t\t2.95582: 3,\n\t\t6.01675: 4,\n\t\t12.24745: 5,\n\t\t24.93039: 6,\n\t\t50.74725: 7,\n\t\t103.29898: 8,\n\t\t210.27107: 9,\n\n\t\t0.713365: 1,\n\t\t1.452096: 2,\n\t\t2.955825: 3,\n\t\t6.016752: 4,\n\t\t12.24745: 5,\n\t\t24.93039: 6,\n\t\t50.74726: 7,\n\t\t103.299: 8,\n\t\t210.271: 9,\n\n\t\t0.71336E+00: 1,\n\t\t0.14521E+01: 2,\n\t\t0.29558E+01: 3,\n\t\t0.60168E+01: 4,\n\t\t0.12247E+02: 5,\n\t\t0.24930E+02: 6,\n\t\t0.50747E+02: 7,\n\t\t0.10330E+03: 8,\n\t\t0.21027E+03: 9,\n\t}\n\treturn switcher.get(angle, 99999)\n\ndef bin_num(p,m):\n\tif p == 1:\n\t\tif m == 1:\n\t\t\treturn 0\n\t\tif m == 2:\n\t\t\treturn 1\n\t\tif m == 3:\n\t\t\treturn 2\n\t\tif m == 4:\n\t\t\treturn 3\n\tif p == 2:\n\t\tif m == 2:\n\t\t\treturn 4\n\t\tif m == 3:\n\t\t\treturn 5\n\t\tif m == 4:\n\t\t\treturn 6\n\tif p == 3:\n\t\tif m == 3:\n\t\t\treturn 7\n\t\tif m == 4:\n\t\t\treturn 8\n\tif p == 4:\n\t\tif m == 4:\n\t\t\treturn 9\n\n\treturn 99999\n\t\t\n\n#-----------------------------Covariance Matrix----------------------------------\ncov = np.genfromtxt('./KiDS_Data/COV_MAT/Cov_mat_all_scales.txt')\nCOVMAT = np.zeros((180, 180))\n\nfor i in range(len(cov)):\n\n\tCOVMAT[int(cov[i, 2]*90 + 10*(angbin(cov[i, 3])-1)+bin_num(cov[i, 0], cov[i, 1])), \n\tint(cov[i, 6]*90 + 10*(angbin(cov[i, 7])-1)+bin_num(cov[i, 4], cov[i, 5]))] = cov[i, 8]+cov[i, 9]+cov[i, 10]\n\n\tCOVMAT[int(cov[i, 6]*90 + 10*(angbin(cov[i, 7])-1)+bin_num(cov[i, 4], cov[i, 5])), \n\tint(cov[i, 2]*90 + 10*(angbin(cov[i, 3])-1)+bin_num(cov[i, 0], cov[i, 1]))] = cov[i, 8]+cov[i, 9]+cov[i, 10]\n\nhdu_covmat = fits.ImageHDU(COVMAT)\nhdu_covmat.header['COVDATA'] = True\nhdu_covmat.header['EXTNAME'] = 'COVMAT'\nhdu_covmat.header['STRT_0'] = 0\nhdu_covmat.header['NAME_0'] = 'xi_plus'\nhdu_covmat.header['STRT_1'] = 90\nhdu_covmat.header['NAME_1'] = 'xi_minus'\n\n\n#--------------------------------------------------------------------------------\n#-----------------------------Correlation Function-------------------------------\nXI_PLUS = np.zeros((90,5))\nXI_MINUS = np.zeros((90,5))\n\nindex = 0\nfor i in range(1,5):\n\tfor j in range (i,5):\n\t\tcurrxi = np.genfromtxt('/media/juancordero/Gaia/Documentos/Manchester/KIDS/CosmoParams/KiDS_Data/DATA_VECTOR/KiDS-450_xi_pm_files/KiDS-450_xi_pm_tomo_' + str(i) + '_' + str(j) + '_logbin_mcor.dat')\n\t\tfor k in range(len(currxi)):\t\t\t\n\t\t\tXI_PLUS[k*10+index,:] = i, j, angbin(currxi[k,0]), currxi[k,1], currxi[k,0]\n\t\t\tXI_MINUS[k*10+index,:] = i, j, angbin(currxi[k,0]), currxi[k,2], currxi[k,0]\n\t\tindex += 1\n\t\t\ncol1_p = fits.Column(name = 'BIN1', format = 'K', array = XI_PLUS[:,0])\ncol2_p = fits.Column(name = 'BIN2', format = 'K', array = XI_PLUS[:,1])\ncol3_p = fits.Column(name = 'ANGBIN', format = 'K', array = XI_PLUS[:,2])\ncol4_p = fits.Column(name = 'VALUE', format = 'D', array = XI_PLUS[:,3])\ncol5_p = fits.Column(name = 'ANG', format = 'D', array = XI_PLUS[:,4])\n\ncol1_m = fits.Column(name = 'BIN1', format = 'K', array = XI_MINUS[:,0])\ncol2_m = fits.Column(name = 'BIN2', format = 'K', array = XI_MINUS[:,1])\ncol3_m = fits.Column(name = 'ANGBIN', format = 'K', array = XI_MINUS[:,2])\ncol4_m = fits.Column(name = 'VALUE', format = 'D', array = XI_MINUS[:,3])\ncol5_m = fits.Column(name = 'ANG', format = 'D', array = XI_MINUS[:,4])\n\ncols_p = fits.ColDefs([col1_p,col2_p,col3_p,col4_p,col5_p])\ncols_m = fits.ColDefs([col1_m,col2_m,col3_m,col4_m,col5_m])\n\nhdu_xi_plus = fits.BinTableHDU.from_columns(cols_p)\nhdu_xi_minus = fits.BinTableHDU.from_columns(cols_m)\n\nhdu_xi_plus.header['2PTDATA'] = True\nhdu_xi_plus.header['EXTNAME'] = 'xi_plus'\nhdu_xi_plus.header['QUANT1'] = 'G+R'\nhdu_xi_plus.header['QUANT2'] = 'G+R'\nhdu_xi_plus.header['KERNEL_1'] = 'NZ_SAMPLE'\nhdu_xi_plus.header['KERNEL_2'] = 'NZ_SAMPLE'\nhdu_xi_plus.header['WINDOWS'] = 'SAMPLE'\nhdu_xi_plus.header['N_ZBIN1'] = 4\nhdu_xi_plus.header['N_ZBIN2'] = 4\nhdu_xi_plus.header['N_ANG'] = 9\nhdu_xi_plus.header['TUNIT5'] = 'arcmin'\n\nhdu_xi_minus.header['2PTDATA'] = True\nhdu_xi_minus.header['EXTNAME'] = 'xi_minus'\nhdu_xi_minus.header['QUANT1'] = 'G-R'\nhdu_xi_minus.header['QUANT2'] = 'G-R'\nhdu_xi_minus.header['KERNEL_1'] = 'NZ_SAMPLE'\nhdu_xi_minus.header['KERNEL_2'] = 'NZ_SAMPLE'\nhdu_xi_minus.header['WINDOWS'] = 'SAMPLE'\nhdu_xi_minus.header['N_ZBIN1'] = 4\nhdu_xi_minus.header['N_ZBIN2'] = 4\nhdu_xi_minus.header['N_ANG'] = 9\nhdu_xi_minus.header['TUNIT5'] = 'arcmin'\n\n#--------------------------------------------------------------------------------\n#-----------------------------Redshift number density distribution---------------\n\n\nnz_cc = np.zeros((40,7))\n\nfor i in range(4):\n\tccfile = np.genfromtxt('./KiDS_Data/Nz_CC/Nz_CC_z0.' + str(1+i*2) + 't0.' + str(3+i*2) + '.asc')\n\tfor j in range(len(ccfile)):\n\t\tnz_cc[j,3+i] = ccfile[j,1]\n\t\tif i == 3:\n\t\t\tnz_cc[j,0] = ccfile[j,0]\n\t\t\tif j < len(ccfile)-1:\n\t\t\t\tnz_cc[j,2] = ccfile[j+1,0]\n\t\t\telse:\n\t\t\t\tnz_cc[j,2] = ccfile[j,0]+0.05\n\t\t\tnz_cc[j,1] = 0.5*(nz_cc[j,0] + nz_cc[j,2])\n\ncol1_cc = fits.Column(name = 'Z_LOW', format = 'D', array = nz_cc[:,0])\ncol2_cc = fits.Column(name = 'Z_MID', format = 'D', array = nz_cc[:,1])\ncol3_cc = fits.Column(name = 'Z_HIGH', format = 'D', array = nz_cc[:,2])\ncol4_cc = fits.Column(name = 'BIN1', format = 'D', array = nz_cc[:,3])\ncol5_cc = fits.Column(name = 'BIN2', format = 'D', array = nz_cc[:,4])\ncol6_cc = fits.Column(name = 'BIN3', format = 'D', array = nz_cc[:,5])\ncol7_cc = fits.Column(name = 'BIN4', format = 'D', array = nz_cc[:,6])\n\ncols_cc = fits.ColDefs([col1_cc, col2_cc, col3_cc, col4_cc, col5_cc, col6_cc, col7_cc])\n\nhdu_nz_cc = fits.BinTableHDU.from_columns(cols_cc)\n\n\nhdu_nz_cc.header['NZDATA'] = True\nhdu_nz_cc.header['EXTNAME'] = 'NZ_SAMPLE'\nhdu_nz_cc.header['NBIN'] = 4\nhdu_nz_cc.header['NZ'] = 40\n\n\n#--------------------------------------------------------------------------------\nprihdr = fits.Header()\nprihdu = fits.PrimaryHDU(header=prihdr)\nthdulist = fits.HDUList([prihdu, hdu_covmat, hdu_xi_plus, hdu_xi_minus, hdu_nz_cc])\nthdulist.writeto('KiDS_like_CC.fits', clobber = True)\n\nplt.axhline(y=0, xmin = 0, xmax = 2, ls='dashed', color = 'k')\nplt.axvspan(0.1, 0.3, alpha=0.5, color='k')\nplt.axvspan(0.3, 0.5, alpha=0.5, color='g')\nplt.axvspan(0.5, 0.7, alpha=0.5, color='b')\nplt.axvspan(0.7, 0.9, alpha=0.5, color='r')\n\nplt.plot(nz_cc[:,1],nz_cc[:,3], color = 'k')\nplt.plot(nz_cc[:,1],nz_cc[:,4], color = 'g')\nplt.plot(nz_cc[:,1],nz_cc[:,5], color = 'b')\nplt.plot(nz_cc[:,1],nz_cc[:,6], color = 'r')\nplt.savefig('nz_CC.png', dpi=200)\nplt.savefig('nz_CC.pdf', dpi=200)\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n","sub_path":"2ptformatCC.py","file_name":"2ptformatCC.py","file_ext":"py","file_size_in_byte":6402,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"366457786","text":"#!/usr/bin/env python\nimport glob\nimport os\nfrom functools import reduce\nfrom pathlib import Path\nimport pickle as pkl\nimport matplotlib.pyplot as plt\nfrom utils import get_number, create_cnn_one_file\n\n\ndef get_notes(mid_dir, png_dir):\n \"\"\" Get all the notes and chords from the midi files in the ./midi_songs directory \"\"\"\n notes_tuple = []\n for file in glob.glob(os.path.join(mid_dir, f\"*.mid\")):\n # print(\"Parsing %s\" % file)\n filename, number = get_number(file)\n\n png_name = os.path.split(file)[1].replace(\".mid\", \".png\")\n img, one_hot = create_cnn_one_file(png_name, mid_dir=mid_dir, png_dir=png_dir)\n notes_tuple.append((filename, int(number), one_hot, img))\n # append NAME, SLICE_INDEX, ONE_HOT, IMG\n\n notes_tuple = sorted(notes_tuple, key=lambda tup: (tup[0], tup[1]))\n return notes_tuple\n\ndef save(filename, tab):\n\n with open(filename, 'wb') as f:\n pkl.dump(tab, f)\n\n\ndef load(filename):\n with open(filename, 'rb') as f:\n data = pkl.load(f)\n return data\n\ndef analyse_song(song_list, positive, negative):\n vector = [0]*128\n pitchnames_vector = [0] * 12\n chords = [0] * 7\n for item in song_list:\n how_many_notes = reduce(lambda a,b : a+b, item[2])\n how_many_notes = int(how_many_notes)\n positive += how_many_notes\n negative += (128-how_many_notes)\n if how_many_notes > 5:\n chords[6]+=1\n else:\n chords[how_many_notes] +=1\n vector = list(map(sum, zip(vector,item[2]))) # vector 128, count of pitches\n for i in range (0,12):\n pitchnames_vector[i] = reduce(lambda a,b : a+b, vector[i::12])\n\n pitches_count = reduce(lambda a,b : a+b, pitchnames_vector)\n\n vector_divided = list(map(lambda x: x/pitches_count, vector))\n pitchnames_vector_divided = list(map(lambda x: x/pitches_count, pitchnames_vector))\n chords_divided = list(map(lambda x: x/len(song_list), chords))\n directory = song_list[0][0].replace('.mid', '')\n tmp_name = os.path.split(directory)\n tmp_name = tmp_name[len(tmp_name) - 1]\n Path(\"plots\").mkdir(parents=True, exist_ok=True)\n Path(f'plots/{tmp_name}').mkdir(parents=True, exist_ok=True)\n\n # count of all pitches\n plt.plot(vector_divided)\n tmp_name = os.path.split(directory)\n tmp_name = tmp_name[len(tmp_name)-1]\n plt.title(f'{tmp_name}')\n plt.suptitle(f'pitch distribution')\n plt.ylabel(\"%\")\n plt.xlabel(\"pitch\")\n plt.savefig(f'plots/{tmp_name}/all_pitches_percentage.png')\n plt.show()\n\n # count of pitchnamed pitches\n labels = [\"C\", \"C#\", \"D\", \"D#\", \"E\", \"F\", \"F#\", \"G\", \"G#\", \"A\", \"A#\", \"H\"]\n plt.bar(labels, pitchnames_vector_divided)\n\n plt.title(f'{tmp_name}')\n plt.suptitle(f'pitchname distribution')\n plt.ylabel(\"%\")\n plt.xlabel(\"pitchname\")\n plt.savefig(f'plots/{tmp_name}/pitchname_percentage.png')\n plt.show()\n\n #count of how many notes played at once\n labels = [\"0\", \"1\", \"2\", \"3\", \"4\", \"5\", \">5\"]\n plt.bar(labels, chords_divided)\n plt.title(f'{tmp_name}')\n plt.suptitle(f'different pitch number distribution')\n plt.ylabel(\"%\")\n plt.xlabel(\"number of notes at once\")\n plt.savefig(f'plots/{tmp_name}/chords_percentage.png')\n plt.show()\n\n return positive,negative\n\n\ndef analyse_songs(pickle):\n data = load(pickle)\n song_set = set(item[0] for item in data)\n positive = 0\n negative = 0\n for item in song_set:\n song = list(filter(lambda x: x[0] == item, data))\n p_temp, n_temp =analyse_song(song, positive, negative)\n positive = p_temp\n negative = n_temp\n\n print(f\"POSITIVE: {positive}, NEGATIVE: {negative}\")\n print(f\"POSITIVE: {positive/(positive+negative)}%, NEGATIVE: {negative/(positive+negative)}%\")\n\n\n# data = get_notes()\n# save(\"data2.pickle\", data)\n# analyse_songs(\"data2.pickle\")\n","sub_path":"data_analysis.py","file_name":"data_analysis.py","file_ext":"py","file_size_in_byte":3851,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"188156043","text":"import os\nParallel = True\nnjobs = 16#4\nncores = 2\n\nif Parallel == True:\n \n #Run the model using MPI (w/OMP)\n os.system('aprun -n %d -d %d python Driver.py parallel' % (njobs,ncores))\n\nelif Parallel == False:\n\n #Run the model without MPI (w/OMP)\n os.system('python Driver.py serial')\n","sub_path":"Main.py","file_name":"Main.py","file_ext":"py","file_size_in_byte":283,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"326516853","text":"import numpy as np\nfrom matplotlib import pyplot as plt\n\n\ndef init():\n global v0\n global L\n global Lx\n global Ly\n L = 12\n Lx = 80\n # Ly = 60\n v0 = 1\n stm = np.zeros([120, 120])\n stm[-1, :] = v0\n stm[0, int(np.floor(stm.shape[0] / 4)): int(np.floor(3 * stm.shape[0] / 4))] = - v0 / 2\n return stm\n\n\ndef edge_correct(newm):\n newm[0, 0:int(np.floor(newm.shape[0] / 4))] = newm[1, 0:int(np.floor(newm.shape[0] / 4))]\n newm[0, int(np.floor(3 * newm.shape[0] / 4)):] = newm[1, int(np.floor(3 * newm.shape[0] / 4)):]\n newm[0, int(np.floor(newm.shape[0] / 4)): int(np.floor(3 * newm.shape[0] / 4))] = newm[1, int(\n np.floor(newm.shape[0] / 4)): int(np.floor(3 * newm.shape[0] / 4))] - v0 / 2\n newm[-1, :] = newm[-2, :] + v0\n newm[:, 0] = newm[:, 1]\n newm[:, -1] = newm[:, -2]\n newm[Lx, Ly:Ly + L + 1] = newm[Lx - 1, Ly:Ly + L + 1]\n newm[Lx + L, Ly:Ly + L + 1] = newm[Lx + L + 1, Ly:Ly + L + 1]\n newm[Lx + 1:Lx + L, Ly] = newm[Lx + 1:Lx + L, Ly - 1]\n newm[Lx + 1:Lx + L, Ly + L] = newm[Lx + 1:Lx + L, Ly + L + 1]\n newm = np.subtract(newm, np.average(newm))\n return newm\n\n\ndef step(stm):\n newm = np.copy(stm)\n for i in range(1, stm.shape[0] - 1):\n for j in range(1, stm.shape[1] - 1):\n newm[i, j] = (stm[i, j + 1] + stm[i + 1, j] + stm[i - 1, j] + stm[i, j - 1]) / 4\n newm = edge_correct(newm)\n return newm\n\n # if i==0 and j==0:\n # pass\n # elif i==0 and j==stm.shape[1]:\n # pass\n # elif i==stm.shape[0] and j==0:\n # pass\n # elif i==stm.shape[0] and j==stm.shape[1]:\n # pass\n # elif i==0 and j!=0 and j!=stm.shape[1]:\n # pass\n # elif i==stm.shape[0] and j!=0 and j!=stm.shape[1]:\n # pass\n # elif j==0 and i!=0 and i!=stm.shape[1]:\n # pass\n # elif j==stm.shape[1] and i!=0 and i!=stm.shape[1]:\n # pass\n # else:\n # pass\n\nfor Ly in range(0,100,10):\n m = init()\n for l in range(1000):\n m = step(m)\n np.savetxt('data'+str(Ly)+'.txt', m)\n","sub_path":"relaxation.py","file_name":"relaxation.py","file_ext":"py","file_size_in_byte":2035,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"339618745","text":"import unittest\nimport read_in\nimport axelrod\nimport pandas\nimport numpy\n\n\nclass TestStrategies(unittest.TestCase):\n df = read_in.strategies_properties()\n\n def test_strategies_properties(self):\n\n self.assertIsInstance(self.df, pandas.DataFrame)\n self.assertEqual(len(self.df), len(axelrod.strategies))\n self.assertTrue([nm.name for nm in axelrod.strategies],\n self.df['Name'])\n for memory_depth in self.df['Memory_depth']:\n self.assertIsInstance(memory_depth, float)\n\n for use_of_game in self.df['Makes_use_of_game']:\n\n self.assertIsInstance(use_of_game, bool)\n\n for use_of_length in self.df['Makes_use_of_length']:\n self.assertIsInstance(use_of_length, bool)\n\n def test_specific_strategy_properties(self):\n\n tit_for_tat = self.df[self.df['Name'] == 'Tit For Tat']\n self.assertTrue(tit_for_tat.Name.all(), 'Tit For Tat')\n self.assertTrue(tit_for_tat.Memory_depth.all(), 1.0)\n self.assertFalse(tit_for_tat.Stochastic.all())\n self.assertEqual(tit_for_tat.Makes_use_of_game.all(), 0.0)\n self.assertEqual(tit_for_tat.Makes_use_of_length.all(), 0.0)\n\n adaptive = self.df[self.df['Name'] == 'Adaptive']\n self.assertTrue(adaptive.Name.all(), 'Adaptive')\n self.assertTrue(adaptive.Memory_depth.all(), numpy.inf)\n self.assertFalse(adaptive.Stochastic.all())\n self.assertEqual(adaptive.Makes_use_of_game.all(), 1.0)\n self.assertEqual(adaptive.Makes_use_of_length.all(), 0.0)\n\n\nclass TestParameters(unittest.TestCase):\n\n def test_pameters_data_frame(self):\n parameters_df = read_in.parameters_data_frame()\n\n self.assertIsInstance(parameters_df, pandas.DataFrame)\n self.assertEqual(len(parameters_df), 10002)\n self.assertTrue(parameters_df.columns.all(), ['noise', 'probend',\n 'repetitions', 'seed',\n 'size', 'turns'])\n\n\nclass TestReader(unittest.TestCase):\n parameters_df = read_in.parameters_data_frame()\n row = parameters_df.sample(n=1)\n reader = read_in.Reader(row)\n\n def test_reader_init(self):\n\n self.assertEqual(self.reader.noise_param.values[0],\n self.row.noise.values[0])\n self.assertEqual(self.reader.probend_param.values[0],\n self.row.probend.values[0])\n self.assertEqual(self.reader.seed.values[0],\n self.row.seed.values[0])\n self.assertEqual(self.reader.size.values[0],\n self.row['size'].values[0])\n self.assertEqual(self.reader.turns_param.values[0],\n self.row.turns.values[0])\n\n def test_get_noise_df(self):\n noise = self.reader.get_noise_df()\n self.assertIsInstance(noise, pandas.DataFrame)\n self.assertTrue(noise.columns.all(), ['Rank', 'Name', 'Median_score',\n 'Cooperation_rating', 'Wins',\n 'CC_rate', 'CD_rate', 'DC_rate',\n 'DD_rate', 'noise', 'turns',\n 'repetitions', 'size', 'seed'])\n\n def test_get_probend_noise_df(self):\n probend_noise = self.reader.get_probend_noise_df()\n self.assertIsInstance(probend_noise, pandas.DataFrame)\n self.assertTrue(probend_noise.columns.all(), ['Rank', 'Name',\n 'Median_score',\n 'Cooperation_rating',\n 'Wins', 'CC_rate',\n 'CD_rate', 'DC_rate',\n 'DD_rate', 'noise',\n 'probend', 'repetitions',\n 'size', 'seed'])\n\n def test_get_standar_df(self):\n std = self.reader.get_standar_df()\n self.assertIsInstance(std, pandas.DataFrame)\n self.assertTrue(std.columns.all(), ['Rank', 'Name', 'Median_score',\n 'Cooperation_rating', 'Wins',\n 'CC_rate', 'CD_rate', 'DC_rate',\n 'DD_rate', 'turns', 'repetitions',\n 'size', 'seed'])\n\n def test_get_proend_df(self):\n probend = self.reader.get_proend_df()\n self.assertIsInstance(probend, pandas.DataFrame)\n self.assertTrue(probend.columns.all(), ['Rank', 'Name', 'Median_score',\n 'Cooperation_rating', 'Wins',\n 'CC_rate', 'CD_rate',\n 'DC_rate', 'DD_rate',\n 'probend', 'repetitions',\n 'size', 'seed'])\n\n\nclass TestReadingIn(unittest.TestCase):\n parameters_df = read_in.parameters_data_frame()\n parameters_df = parameters_df.sample(n=2)\n\n def test_reading_in_data(self):\n df = read_in.reading_in_data(self.parameters_df)\n\n probend_data = df[df['turns'].isnull()]\n self.assertEqual(len(probend_data), len(df[df['probend'].notnull()]))\n self.assertEqual(list(probend_data.CC_rate),\n list(df[df['probend'].notnull()].CC_rate))\n\n turns_data = df[df['probend'].isnull()]\n self.assertEqual(len(turns_data), len(df[df['turns'].notnull()]))\n self.assertEqual(list(turns_data.CC_rate),\n list(df[df['turns'].notnull()].CC_rate))\n self.assertEqual(sum(df.turns.notnull()) + sum(df.probend.notnull()),\n len(df))\n\n # some extra tests\n self.assertTrue(all(df.seed.notnull()))\n self.assertTrue(all(df.repetitions.notnull()))\n self.assertTrue(all(df['size'].notnull()))\n\n\n","sub_path":"src/test_read_in.py","file_name":"test_read_in.py","file_ext":"py","file_size_in_byte":6140,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"339742580","text":"\"\"\"\r\n ganomaly.py\r\n Base code from : https://github.com/LeeDoYup/AnoGAN\r\n\"\"\"\r\nfrom __future__ import division\r\nimport os\r\nimport time\r\nimport math\r\nfrom glob import glob\r\nimport tensorflow as tf\r\nimport numpy as np\r\nfrom six.moves import xrange\r\nimport sys\r\nsys.path.append(os.path.abspath('..'))\r\n\r\nfrom utils.ops import *\r\nfrom utils.utils import *\r\nfrom utils.data import *\r\nfrom .model import NET\r\n\r\nclass GANOMALY_ORIGIN(NET):\r\n def __init__(self, sess, config, dataset=None):\r\n\r\n super(GANOMALY_ORIGIN, self).__init__(sess,\r\n dataset,\r\n config,\r\n 'ganomaly_origin',\r\n 'GANOMALY_ORIGIN-model')\r\n\r\n self.net_dim = self.default_dim\r\n self.g_train = config.g_train\r\n self.d_train = config.d_train\r\n self.lamb = config.gnl_l\r\n\r\n self.d, self.h = 0, self.input_height\r\n while True:\r\n if self.h <= 4:\r\n break;\r\n self.h = conv_out_size_same(self.h, 2)\r\n self.d += 1\r\n\r\n self.build_model()\r\n\r\n def build_model(self):\r\n\r\n #Construct Generator, Discriminators and Encoders\r\n if self.aug:\r\n self.inputs_x = self.inputs_arg\r\n else:\r\n self.inputs_x = self.inputs\r\n\r\n self.Ge, self.e1_bn = self.encoder(self.inputs_x, name='encoder1')\r\n self.Gd = self.generator(self.Ge)\r\n self.Dx_logits = self.discriminator(self.inputs_x)\r\n self.Dz_logits = self.discriminator(self.Gd, reuse=True)\r\n self.e, self.e2_bn = self.encoder(self.Gd, name='encoder2')\r\n self.sampler = self.generator(self.encoder(self.inputs, reuse=True, bn=self.e1_bn, name='encoder1'), reuse=True)\r\n\r\n #Create Loss Functions\r\n # Update Discriminator\r\n self.d_loss_real = tf.reduce_mean(\r\n sigmoid_cross_entropy_with_logits(self.Dx_logits, tf.ones_like(self.Dx_logits)))\r\n self.d_loss_fake = tf.reduce_mean(\r\n sigmoid_cross_entropy_with_logits(self.Dz_logits, tf.zeros_like(self.Dz_logits)))\r\n self.adv_loss = tf.reduce_mean(\r\n sigmoid_cross_entropy_with_logits(self.Dz_logits, tf.ones_like(self.Dz_logits)))\r\n\r\n # Update Generator and Encoder\r\n # Contextual Loss\r\n self.con_loss = tf.reduce_mean(tf.reduce_sum(tf.abs(tf.subtract(self.inputs_arg, self.Gd)), axis=1))\r\n\r\n # Encoder Loss\r\n self.enc_loss = tf.reduce_mean(tf.reduce_sum(tf.square(tf.subtract(self.Ge, self.e)), axis=1))\r\n\r\n # total d_loss\r\n self.d_loss = self.d_loss_real + self.d_loss_fake\r\n\r\n self.g_loss = self.adv_loss + self.lamb * self.con_loss + self.enc_loss\r\n\r\n t_vars = tf.trainable_variables()\r\n t_ops = tf.get_collection(tf.GraphKeys.UPDATE_OPS)\r\n # variables for each networks.\r\n d_vars = [var for var in t_vars if 'd_' in var.name]\r\n d_ops = [op for op in t_ops if 'd_' in op.name]\r\n g_vars = [var for var in t_vars if 'g_' in var.name]\r\n g_ops = [op for op in t_ops if 'g_' in op.name]\r\n e1_vars = [var for var in t_vars if 'encoder1' in var.name]\r\n e1_ops = [op for op in t_ops if 'encoder1' in op.name]\r\n e2_vars = [var for var in t_vars if 'encoder2' in var.name]\r\n e2_ops = [op for op in t_ops if 'encoder2' in op.name]\r\n\r\n # Optimization Setting\r\n with tf.control_dependencies(d_ops):\r\n self.d_optim = tf.train.AdamOptimizer(self.d_lr, beta1=self.beta1) \\\r\n .minimize(self.d_loss, var_list=d_vars)\r\n with tf.control_dependencies(g_ops):\r\n self.g_optim = tf.train.AdamOptimizer(self.g_lr, beta1=self.beta1) \\\r\n .minimize(self.g_loss, var_list=g_vars)\r\n with tf.control_dependencies(e1_ops):\r\n self.e1_optim = tf.train.AdamOptimizer(self.e1_lr, beta1=self.beta1) \\\r\n .minimize(self.g_loss, var_list=e1_vars)\r\n with tf.control_dependencies(e2_ops):\r\n self.e2_optim = tf.train.AdamOptimizer(self.e2_lr, beta1=self.beta1) \\\r\n .minimize(self.g_loss, var_list=e2_vars)\r\n\r\n self.saver = tf.train.Saver()\r\n\r\n\r\n def train(self, config):\r\n sample_dir = os.path.join(config.sample_dir,self.network_name, self.model_dir)\r\n if not os.path.exists(sample_dir):\r\n os.makedirs(sample_dir)\r\n\r\n counter = 1\r\n start_time = time.time()\r\n could_load, checkpoint_counter, checkpoint_epoch = self.load(self.checkpoint_dir, config.epoch)\r\n if could_load:\r\n counter = checkpoint_counter\r\n print(\" [*] Load SUCCESS\")\r\n if checkpoint_epoch == config.epoch and config.epoch > 0:\r\n print(\" [*] Train is already done with given epoch.\")\r\n return\r\n else:\r\n print(\" [!] Load failed...\")\r\n\r\n\r\n batch_idxs = self.dataset.ntrain_batch(config.batch_size)\r\n\r\n\r\n for epoch in xrange(checkpoint_epoch, config.epoch):\r\n for idx in xrange(batch_idxs):\r\n\r\n #Prepare batch data for learning\r\n if self.dataset is not None:\r\n batch_images = self.data_X[idx*config.batch_size:(idx+1)*config.batch_size]\r\n else:\r\n batch_files = self.data[idx*config.batch_size:(idx+1)*config.batch_size]\r\n batch = [ get_image(batch_file, input_height=self.input_height, input_width=self.input_width,\r\n resize_height=self.output_height, resize_width=self.output_width,\r\n crop=self.crop, grayscale=self.grayscale) for batch_file in batch_files]\r\n if self.grayscale:\r\n batch_images = np.array(batch).astype(np.float32)[:, :, :, None]\r\n else:\r\n batch_images = np.array(batch).astype(np.float32)\r\n\r\n #Make feed dictionary\r\n feed_dict = {self.inputs: batch_images, self.is_train:True}\r\n\r\n for i in range(self.d_train):\r\n #Run Optimization and Summary Operation of Discriminator\r\n self.sess.run(self.d_optim, feed_dict = feed_dict)\r\n\r\n for i in range(self.g_train):\r\n #Run Optimization and Summary Operation of Generator and Encoder\r\n self.sess.run([self.g_optim, self.e1_optim, self.e2_optim], feed_dict = feed_dict)\r\n\r\n # Calculate Loss Values of Discriminator and Generator\r\n\r\n counter += 1\r\n\r\n if config.verbose:\r\n if np.mod(counter, config.print_interval) == 0:\r\n errD, errG = self.sess.run([self.d_loss, self.g_loss], feed_dict = feed_dict)\r\n print(\"Epoch: [%2d] [%4d/%4d] time: %4.4f, d_loss: %.8f, g_loss: %.8f\" \\\r\n % (epoch, idx, batch_idxs, time.time() - start_time, errD, errG))\r\n\r\n if np.mod(counter, int(batch_idxs/5)) == 0 and self.data_type == 'image' and np.mod(epoch, self.epoch_interval) == 0:\r\n if self.sampling:\r\n samples, d_loss, g_loss = self.sess.run([self.sampler, self.d_loss, self.g_loss], feed_dict = self.sample_feed_dict)\r\n save_images(samples, image_manifold_size(samples.shape[0]),\r\n './{}/train_{:02d}_{:04d}.png'.format(sample_dir, epoch, idx))\r\n else:\r\n d_loss, g_loss = self.sess.run([self.d_loss, self.g_loss], feed_dict = self.sample_feed_dict)\r\n print(\"Epoch: [%2d] [%4d/%4d] time: %4.4f [Sample] d_loss: %.8f, g_loss: %.8f\" % (epoch, idx, batch_idxs, time.time() - start_time, d_loss, g_loss))\r\n\r\n if np.mod(epoch+1, config.epoch_save_interval) == 0:\r\n self.save(config.checkpoint_dir, counter, epoch+1)\r\n samples = self.sess.run(self.sampler, feed_dict = self.sample_feed_dict)\r\n save_images(samples, image_manifold_size(samples.shape[0]),\r\n './{}/valid_{}.png'.format(sample_dir, epoch))\r\n self.save(config.checkpoint_dir, counter, epoch+1)\r\n print(\" [!] Training is Done...\")\r\n\r\n def encoder(self, x, reuse=False, bn=None, name='encoder'):\r\n with tf.variable_scope(name) as scope:\r\n if reuse:\r\n scope.reuse_variables()\r\n assert bn is not None\r\n else:\r\n bn = [batch_norm(self.is_train, name='e_bn{}'.format(i), use=bool(i)) for i in range(self.d+2)] # conv1 - convs - linear\r\n lrelu = lambda x:leak_relu(x, 0.2)\r\n\r\n assert self.input_height == self.input_width\r\n\r\n if self.data_type == 'image':\r\n dims = [int(self.net_dim/2) * (2**i) for i in range(self.d+1)]\r\n st, out = [1] + [2]*self.d, x\r\n for i in range(self.d+1):\r\n out = lrelu(bn[i](conv2d(out, dims[i], ks=4, st=st[i], name='e_conv{}'.format(i), bias=False))) # 1/4\r\n\r\n out = lrelu(bn[i+1](conv2d(out, self.z_dim, ks=self.h, st=1, padding='VALID', name='e_conv{}'.format(i+1), bias=False)))\r\n\r\n if self.data_type == 'static':\r\n assert False\r\n if reuse:\r\n return out\r\n else:\r\n return out, bn\r\n\r\n def discriminator(self, x, reuse=False):\r\n with tf.variable_scope('discriminator') as scope:\r\n if reuse:\r\n scope.reuse_variables()\r\n else:\r\n self.d_bn = [batch_norm(self.is_train, name='d_bn{}'.format(i), use=bool(i)) for i in range(self.d+2)]\r\n lrelu = lambda x:leak_relu(x, 0.2)\r\n if self.data_type == 'image':\r\n dims = [int(self.net_dim/2) * (2**i) for i in range(self.d+1)]\r\n st, out = [1] + [2]*self.d, x\r\n for i in range(self.d+1):\r\n out = lrelu(self.d_bn[i](conv2d(out, dims[i], ks=4, st=st[i], name='e_conv{}'.format(i+1), bias=False))) # 1/4\r\n out = linear(out, 1, 'd_fc1')\r\n\r\n return out\r\n if self.data_type == 'static':\r\n assert False\r\n def generator(self, z, reuse=False):\r\n batch_size = tf.shape(z)[0]\r\n with tf.variable_scope(\"generator\") as scope:\r\n if reuse:\r\n scope.reuse_variables()\r\n else:\r\n self.g_bn = [batch_norm(self.is_train, name='g_bn{}'.format(i), use=bool(i-self.d-1)) for i in range(self.d+2)]\r\n if self.data_type == 'image':\r\n siz = [conv_out_size_same(self.output_width, 2**i) for i in range(self.d+1)]\r\n dims = [self.c_dim]+[self.net_dim * (2**i) for i in range(self.d)]\r\n assert self.h == siz[-1], (self.h, siz[-1])\r\n out = self.g_bn[0](deconv2d(z, [batch_size, self.h, self.h, dims[-1]], ks=self.h, st=1, padding='VALID', name='g_deconv0', bias=False))\r\n\r\n for i in range(self.d):\r\n out = self.g_bn[i+1](deconv2d(relu(out), [batch_size, siz[-i-2], siz[-i-2], dims[-2-i]], name='g_deconv{}'.format(i+1), bias=False))\r\n\r\n return tf.nn.tanh(out)\r\n if self.data_type == 'static':\r\n assert False\r\n\r\n def get_test_data(self):\r\n if self.dataset is not None:\r\n self.test_data_names = ['{}_test_data_{:05}'.format(self.dataset_name, i)\r\n for i in range(len(self.test_y))]\r\n self.test_data = self.test_x\r\n else:\r\n self.test_data_names = glob(self.test_dir+'/*.*')\r\n batch = [get_image(name, input_height=self.input_height, input_width = self.input_width,\r\n resize_height = self.output_height, resize_width = self.output_width,\r\n crop = self.crop, grayscale=self.grayscale) for name in self.test_data_names]\r\n if self.grayscale:\r\n batch_images = np.array(batch).astype(np.float32)[:,:,:,None]\r\n else:\r\n batch_images = np.array(batch).astype(np.float32)\r\n #print np.shape(batch_images)\r\n self.test_data = batch_images\r\n sample_dir = os.path.join('samples',self.network_name, self.model_dir)\r\n if not os.path.exists(sample_dir):\r\n os.makedirs(sample_dir)\r\n samples = self.sess.run(self.sampler, feed_dict = self.sample_feed_dict)\r\n save_images(samples, image_manifold_size(samples.shape[0]),\r\n './{}/test.png'.format(sample_dir))\r\n print (\"[*] test data for anomaly detection is loaded\")\r\n\r\n\r\n def build_anomaly_detector(self):\r\n self.get_test_data()\r\n\r\n if self.data_type == 'image':\r\n self.test_inputs = tf.placeholder(tf.float32, [None] + self.image_dims, name='test_images')\r\n if self.data_type == 'static':\r\n self.test_inputs = tf.placeholder(tf.float32, [None, self.output_width], name='test_inputs')\r\n\r\n self.ano_gE = self.encoder(self.test_inputs, reuse=True, bn=self.e1_bn, name='encoder1')\r\n self.ano_G = self.generator(self.ano_gE, reuse=True)\r\n self.ano_eE = self.encoder(self.ano_G, reuse=True, bn=self.e2_bn, name='encoder2')\r\n self.anomaly_score_enc_loss = mean_square_error_Loss(self.ano_gE, self.ano_eE, mode='l1')\r\n\r\n return self.model_dir, ['enc-loss_']\r\n\r\n def anomaly_detector(self, test_data, test_data_names, config):\r\n\r\n if self.dataset:\r\n y = [int(test_data_name.split('_')[-1]) for test_data_name in test_data_names]\r\n is_anomal = [True if self.test_y[y_i] in self.excluded else False for y_i in y]\r\n y_idx = [self.test_y[y_i] for y_i in y]\r\n # if self.data_type == 'image':\r\n # test_data_name = test_data_name+'.jpg'\r\n # if self.data_type == 'image':\r\n # test_data_name = test_data_name+'.jpg'\r\n else:\r\n is_anomal = None\r\n\r\n feed_dict = {self.test_inputs: test_data,\r\n self.is_train:False}\r\n ano_enc = self.sess.run(self.anomaly_score_enc_loss, feed_dict = feed_dict)\r\n if config.verbose:\r\n if self.dataset is not None:\r\n print(\"[{:05d}]th sample Label: [{}:{}] anomaly score(enc_loss): {:.8f}\"\\\r\n .format(y_i, self.test_y[y_i], is_anomal, ano_enc))\r\n else:\r\n print(\"anomaly score: {:.8f} :by feature matching, {:.8f}:by cross-entropy\"\\\r\n .format(ano_feature, ano_cross))\r\n\r\n return [list(ano_enc)], is_anomal, y_idx\r\n","sub_path":"models/ganomaly_origin.py","file_name":"ganomaly_origin.py","file_ext":"py","file_size_in_byte":13511,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"186380483","text":"# This is a helper class to make working with LED matrixes easier\n\nimport max7219\nfrom machine import Pin, SPI\nfrom time import sleep\n\nclass Matrix:\n def __init__(self, cspin = 15, sckpin = 14, mosipin = 13, num = 1):\n spi = SPI(1, baudrate=14500000, sck = Pin(int(sckpin)), mosi = Pin(int(mosipin)))\n self.display = max7219.Max7219(spi, Pin(int(cspin)), num)\n self.display.brightness(0)\n\n # Display normal text\n def text(self, txt, x = 0, y = 0, c = 1):\n self.display.fill(0)\n self.display.text(txt, x, y, c)\n self.display.show()\n\n # Scrolling text. I was not able to make official scroll method work,\n # also on the website they warn \"This may leave a footprint of the previous colors in the FrameBuffer.\"\n # So I wrote this simple method which speed is adjustable.\n # For now, I'm waiting for my other led matrixes to arrive, then I can test further and add more options like scroll direction and etc.\n def scroll(self, txt, s = 0.5, c = 1, loops = 0):\n text_len = len(txt) * 8 + 8\n counter = 1\n while True:\n for i in range(text_len):\n self.text(txt, 8 - i)\n sleep(s)\n if loops != 0:\n if counter >= loops:\n break\n counter += 1\n else:\n sleep(s)\n\n\n # Draw a shape. all this needs is to set shape pattern.\n # For example [[0,0,0,0,0,0,0,0], [0,1,1,0,0,1,1,0], [1,0,0,1,1,0,0,1], [1,0,0,0,0,0,0,1], [1,0,0,0,0,0,0,1], [0,1,0,0,0,0,1,0], [0,0,1,0,0,1,0,0], [0,0,0,1,1,0,0,0]] will display a heart\n def shape(self, patern = [], delay = 0):\n self.display.fill(0)\n for li, l in enumerate(patern):\n for di, d in enumerate(l):\n if d == 1:\n sleep(delay)\n self.display.pixel(int(di), int(li), 1)\n self.display.show()","sub_path":"matrix.py","file_name":"matrix.py","file_ext":"py","file_size_in_byte":1749,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"226749277","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\nimport json\n\nfrom alipay.aop.api.response.AlipayResponse import AlipayResponse\nfrom alipay.aop.api.domain.ItemSkuIdPair import ItemSkuIdPair\n\n\nclass AlipayOpenAppItemCreateResponse(AlipayResponse):\n\n def __init__(self):\n super(AlipayOpenAppItemCreateResponse, self).__init__()\n self._item_id = None\n self._out_item_id = None\n self._skus = None\n\n @property\n def item_id(self):\n return self._item_id\n\n @item_id.setter\n def item_id(self, value):\n self._item_id = value\n @property\n def out_item_id(self):\n return self._out_item_id\n\n @out_item_id.setter\n def out_item_id(self, value):\n self._out_item_id = value\n @property\n def skus(self):\n return self._skus\n\n @skus.setter\n def skus(self, value):\n if isinstance(value, list):\n self._skus = list()\n for i in value:\n if isinstance(i, ItemSkuIdPair):\n self._skus.append(i)\n else:\n self._skus.append(ItemSkuIdPair.from_alipay_dict(i))\n\n def parse_response_content(self, response_content):\n response = super(AlipayOpenAppItemCreateResponse, self).parse_response_content(response_content)\n if 'item_id' in response:\n self.item_id = response['item_id']\n if 'out_item_id' in response:\n self.out_item_id = response['out_item_id']\n if 'skus' in response:\n self.skus = response['skus']\n","sub_path":"alipay/aop/api/response/AlipayOpenAppItemCreateResponse.py","file_name":"AlipayOpenAppItemCreateResponse.py","file_ext":"py","file_size_in_byte":1530,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"156024452","text":"from twilio.rest import Client\nfrom time import time\nclass SmsManager:\n\n client = Client(\"ACxxxxxxxx\", \"xxxxxxxxxx\")\n prev_tags = []\n prev_time = -1\n\n def sendText(self, message):\n self.client.messages.create(to=\"+15555555555\", from_=\"+15555555555\", body=message)\n\n #Returns the highest probablity tag in the json object (takes the output as json.loads as input)\n def notify(self, tags):\n tags.sort()\n if ((tags != self.prev_tags and self.prev_time - time() > 10) or self.prev_time - time() > 30):\n self.prev_time = time()\n self.prev_tags = tags\n if not tags:\n # Motion detected, but no objects recognized\n message = 'There\\'s motion at your door!'\n else:\n # We see something!\n message = 'There\\'s a '\n if (len(tags) > 1):\n for i in range (0, len(tags) - 1):\n message += tags[i] + ', '\n message += tags[len(tags) - 1] + ' at your door!'\n self.sendText(message)\n\n \n","sub_path":"modules/SenseHatDisplay/app/SmsManager.py","file_name":"SmsManager.py","file_ext":"py","file_size_in_byte":1097,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"69506047","text":"import sys\r\nimport os\r\nimport re\r\nimport sqlite3\r\n\r\n'''\r\nThis class is used to connect to the history of various browsers. More will be added shortly.\r\n'''\r\nclass HistoryConnector():\r\n\r\n def __init__(self):\r\n #Build location list \r\n #Firefox is a pain\r\n ffbasePath = os.getenv('APPDATA') + r\"\\Mozilla\\Firefox\\Profiles\"\r\n for filename in os.listdir(ffbasePath):\r\n if re.match(\"[a-zA-z0-9]{1,12}.default\", filename):\r\n self.FIREFOX_LOCATION = ffbasePath + \"\\\\\" + filename + r\"\\places.sqlite\"\r\n #Google made it easy on us\r\n self.CHROME_LOCATION = os.getenv('LOCALAPPDATA') \\\r\n + r\"\\Google\\Chrome\\User Data\\Default\\History\"\r\n\r\n def __del__(self):\r\n self.conn.close()\r\n\r\n def RetrieveHistoryList(self):\r\n firefox = self.retrieveFirefox()\r\n chrome = self.retrieveChrome()\r\n historylist = firefox + chrome\r\n\r\n return {h[0] for h in historylist}\r\n \r\n def retrieveFirefox(self):\r\n historylocation = self.FIREFOX_LOCATION\r\n self.conn = sqlite3.connect(historylocation)\r\n self.cursor = self.conn.cursor()\r\n self.cursor.execute(\"SELECT host FROM moz_hosts\")\r\n historylist = self.cursor.fetchall()\r\n self.conn.close()\r\n return historylist\r\n\r\n\r\n def retrieveChrome(self):\r\n historylocation = self.CHROME_LOCATION\r\n self.conn = sqlite3.connect(historylocation)\r\n self.cursor = self.conn.cursor()\r\n self.cursor.execute(\"SELECT url FROM urls\")\r\n historylist = self.cursor.fetchall()\r\n self.conn.close()\r\n return historylist\r\n ","sub_path":"build/exe.win32-3.6/HistoryConnector.py","file_name":"HistoryConnector.py","file_ext":"py","file_size_in_byte":1647,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"303737456","text":"\"\"\"\"\r\n设计一个名为Rectangle的类,来表示矩形。\r\n\"\"\"\r\nclass Rectangle(object):\r\n def getArea(self, width = 1,heightd =2):\r\n self.width = width\r\n self.heightd= heightd\r\n print(self.width * self.heightd)\r\n def getPerimeter(self,width = 1,heightd =2):\r\n print(self.width *2+self.heightd * 2)\r\nR = Rectangle()\r\nR.getArea(3,4)\r\nR.getPerimeter()\r\n\r\n\"\"\"\r\n设计一个名为Account的类\r\n\"\"\"\r\nclass Account(object):\r\n def __init__(self):\r\n self.InterestRate=0\r\n self.annuallnterestRate=100\r\n self.Interest=0\r\n def information(self,id,yu_e):\r\n self.id=id\r\n self.yu_e=yu_e\r\n def getMonthlyInterestRate(self,InterestRate):\r\n self.InterestRate=InterestRate\r\n def getMonthlyInterest(self):\r\n A=self.annuallnterestRate*self.InterestRate\r\n self.Interest=A\r\n def withdraw(self):\r\n print(\"请输入取钱金额\")\r\n res = input(\"输入\")\r\n self.annuallnterestRate = self.annuallnterestRate - int(res)\r\n print(\"您成功取出\",res,\"元\")\r\n def deposit(self):\r\n print(\"请输入存钱金额\")\r\n res1=input(\"输入\")\r\n self.annuallnterestRate=self.annuallnterestRate+int(res1)\r\n print(\"您成功存入\",res1,\"元\")\r\n \r\n print(self.id,\"您账户余额为:\",self.annuallnterestRate,\"利率为:\",self.InterestRate,\"利息为\",self.Interest)\r\n \r\nE = Account()\r\nE.information(1122,20000)\r\nE.getMonthlyInterestRate(0.045)\r\nE.getMonthlyInterest()\r\nE.withdraw()\r\nE.deposit()\r\n\r\n\"\"\"\r\n设计一个名为Fan的类表示一个风扇\r\n\"\"\"\r\nclass Fan(object):\r\n def __init__(self,speed ,on,radius ,color ):\r\n self.__speed = speed\r\n self.__on = on\r\n self.__radius = radius\r\n self.__color = color\r\n def fensu(self):\r\n if self.__speed ==1:\r\n print(\"SLOW档\")\r\n elif self.__speed ==2:\r\n print(\"MEDIUM档\")\r\n else:\r\n print(\"FAST档\")\r\n def kaiguan(self):\r\n if self.__on ==\"False\":\r\n print(\"关闭\")\r\n else:\r\n print(\"打开\")\r\n def daxiao(self):\r\n a = self.__radius \r\n print(\"半径为:%f\" % a)\r\n def yanse(self):\r\n b= self.__color \r\n print(\"风扇颜色为:%s\" % b )\r\nf = Fan(1,\"False\",5,\"blue\")\r\nf.fensu()\r\nf.kaiguan()\r\nf.daxiao()\r\nf.yanse()\r\n\r\n\r\n\"\"\"\r\n一个正n边形的边都有同样的长度,所有的角都有同样的度数(即多边形是等角的)\r\n设计一个名为RegularPolygon的类\r\n\"\"\"\r\nimport math\r\nclass RegularPolygon(object):\r\n def __init__(self,n=3,side=1,x=0,y=0):\r\n self.__n = n\r\n self.__side = side\r\n self.__x = x\r\n self.__y = y\r\n def getPerimeter(self):\r\n perimeter = self.__n + self.__side + self.__x + self.__y\r\n print(\"多边形的周长为:\",perimeter)\r\n def getArea(self):\r\n area = (self.__n * (self.__side**2))/4 * (math.tan((3.14/self.__n)))\r\n print(\"多边形的面积:\",area)\r\n\r\n\r\n\r\n\"\"\"\r\n设计一个名为LinearEquation的类,它是2*2的线性方程\r\n\"\"\"\r\nclass LinearEquation(object):\r\n def __init__(self,a,b,c,d,e,f):\r\n self.__a=a\r\n self.__b=b\r\n self.__c=c\r\n self.__d=d\r\n self.__e=e\r\n self.__f=f\r\n self.x=0\r\n self.y=0\r\n self.z=0\r\n def isSolvable(self):\r\n s=self.__a*self.__d-self.__b*self.__c\r\n if s !=0:\r\n self.s=True\r\n else:\r\n self.s=False\r\n def get(self):\r\n self.x=(self.__e*self.__d-self.__b*self.__f)/(self.__a*self.__d-self.__b*self.__c)\r\n self.y=(self.__a*self.__f-self.__e*self.__c)/(self.__a*self.__d-self.__b*self.__c)\r\n def getX(self):\r\n self.isSolvable()\r\n if self.s == True:\r\n self.get()\r\n print(self.x)\r\n else:\r\n pass\r\n def getY(self):\r\n self.isSolvable()\r\n if self.s == True:\r\n self.get()\r\n print(self.y)\r\n else:\r\n pass\r\n \r\nq = LinearEquation(1,2,3,4,5,6)\r\nq.getX()\r\nq.getY()\r\n\r\n\"\"\"\r\n交叉线\r\n\"\"\"\r\nimport numpy as np\r\ndef get_crossing(s1,s2):\r\n x1,y1 = s1[0][0],s1[0][1]\r\n x2,y2 = s1[1][0],s1[1][1]\r\n x3,y3 = s2[0][0],s2[0][1]\r\n x4,y4 = s2[1][0],s2[1][1]\r\n #判断两条直线是否相交,矩阵行列式计算\r\n a = np.matrix(\r\n [\r\n [x2-x1,-(x4-x3)],\r\n [y2-y1,-(y4-y3)]\r\n ]\r\n )\r\n delta = np.linalg.det(a)\r\n #不相交,返回两线段\r\n if np.fabs(delta) < 1e-6:\r\n print(delta)\r\n return None \r\n #求两个参数lambda和miu\r\n c = np.matrix(\r\n [\r\n [x3-x1,-(x4-x3)],\r\n [y3-y1,-(y4-y3)]\r\n ]\r\n )\r\n d = np.matrix(\r\n [\r\n [x2-x1,x3-x1],\r\n [y2-y1,y3-y1]\r\n ]\r\n )\r\n lamb = np.linalg.det(c)/delta\r\n miu = np.linalg.det(d)/delta\r\n #相交\r\n if lamb <= 1 and lamb >= 0 and miu >= 0 and miu <= 1:\r\n x = x3 + miu*(x4-x3)\r\n y = y3 + miu*(y4-y3)\r\n return (x,y)\r\n #相交在延长线上\r\n else:\r\n return None\r\nget_crossing(((1,2),(3,3)),((2,2),(2,3)))","sub_path":"zjj4.py","file_name":"zjj4.py","file_ext":"py","file_size_in_byte":5163,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"20185949","text":"\nfrom django.conf.urls import include, url\nfrom rest_framework.routers import DefaultRouter\n\nfrom lelegis.api.views import ApiViewSetConstrutor\n\nfrom .apps import AppConfig\n\n\napp_name = AppConfig.name\n\n\nrouter = DefaultRouter()\n\nfor app, built_sets in ApiViewSetConstrutor._built_sets.items():\n for view_prefix, viewset in built_sets.items():\n router.register(app.label + '/' +\n view_prefix._meta.model_name, viewset)\n\n\nurlpatterns_router = router.urls\n\n\nurlpatterns = [\n url(r'^api/', include(urlpatterns_router)),\n\n]\n","sub_path":"lelegis/api/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":555,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"84003878","text":"#!/usr/bin/env python\n\"\"\"Kinematic function skeleton code for Prelab 3.\nCourse: EE 106A, Fall 2015\nWritten by: Aaron Bestick, 9/10/14\nUsed by: EE106A, 9/11/15\n\nThis Python file is a code skeleton for Pre lab 3. You should fill in \nthe body of the eight empty methods below so that they implement the kinematic \nfunctions described in the homework assignment.\n\nWhen you think you have the methods implemented correctly, you can test your \ncode by running \"python kin_func_skeleton.py at the command line.\n\nThis code requires the NumPy and SciPy libraries. If you don't already have \nthese installed on your personal computer, you can use the lab machines or \nthe Ubuntu+ROS VM on the course page to complete this portion of the homework.\n\"\"\"\n\nimport numpy as np\nfrom scipy import linalg\n\nnp.set_printoptions(precision=4,suppress=True)\n\ndef skew_3d(omega):\n \"\"\"\n Converts a rotation vector in 3D to its corresponding skew-symmetric matrix.\n \n Args:\n omega - (3,) ndarray: the rotation vector\n \n Returns:\n omega_hat - (3,3) ndarray: the corresponding skew symmetric matrix\n \"\"\"\n if not omega.shape == (3,):\n raise TypeError('omega must be a 3-vector')\n \n omega_hat = np.array([[0, -omega[2], omega[1]],\n [omega[2], 0, -omega[0]],\n\t\t [-omega[1], omega[0], 0]])\n\n return omega_hat\n\ndef rotation_2d(theta):\n \"\"\"\n Computes a 2D rotation matrix given the angle of rotation.\n \n Args:\n theta: the angle of rotation\n \n Returns:\n rot - (3,3) ndarray: the resulting rotation matrix\n \"\"\"\n from math import sin, cos\n \n rot = np.array([[cos(theta), -sin(theta)],\n [sin(theta), cos(theta)]])\n\n return rot\n\ndef rotation_3d(omega, theta):\n \"\"\"\n Computes a 3D rotation matrix given a rotation axis and angle of rotation.\n \n Args:\n omega - (3,) ndarray: the axis of rotation\n theta: the angle of rotation\n \n Returns:\n rot - (3,3) ndarray: the resulting rotation matrix\n \"\"\"\n if not omega.shape == (3,):\n raise TypeError('omega must be a 3-vector')\n \n from math import sqrt, sin, cos\n from numpy.linalg import norm\n\n I = np.identity(3)\n n = linalg.norm(omega)\n omegahat = skew_3d(omega)\n if n == 0.0:\n rot = I\n else:\n rot = I + omegahat/n * sin(n*theta) + np.dot(omegahat,omegahat)/(n**2) * (1 - cos(n*theta))\n \n return rot\n\ndef hat_2d(xi):\n \"\"\"\n Converts a 2D twist to its corresponding 3x3 matrix representation\n \n Args:\n xi - (3,) ndarray: the 2D twist\n \n Returns:\n xi_hat - (3,3) ndarray: the resulting 3x3 matrix\n \"\"\"\n if not xi.shape == (3,):\n raise TypeError('omega must be a 3-vector')\n\n xi_hat=np.array([[0,-xi[2],xi[0]],\n [xi[2],0,xi[1]],\n [0,0,0]])\n\n return xi_hat\n\ndef hat_3d(xi):\n \"\"\"\n Converts a 3D twist to its corresponding 4x4 matrix representation\n \n Args:\n xi - (6,) ndarray: the 3D twist\n \n Returns:\n xi_hat - (4,4) ndarray: the corresponding 4x4 matrix\n \"\"\"\n if not xi.shape == (6,):\n raise TypeError('xi must be a 6-vector')\n\n vx, vy, vz, wx, wy, wz = xi\n\n xi_hat=np.array([[0,-wz,wy,vx],\n [wz,0,-wx,vy],\n [-wy,wx,0,vz],\n [0,0,0,0]])\n\n return xi_hat\n\ndef homog_2d(xi, theta):\n \"\"\"\n Computes a 3x3 homogeneous transformation matrix given a 2D twist and a \n joint displacement\n \n Args:\n xi - (3,) ndarray: the 2D twist\n theta: the joint displacement\n \n Returns:\n g - (3,3) ndarray: the resulting homogeneous transformation matrix\n \"\"\"\n if not xi.shape == (3,):\n raise TypeError('xi must be a 3-vector')\n\n from math import sin, cos\n vx, vy, w = xi\n r=np.array([[cos(w*theta),-sin(w*theta)],\n [sin(w*theta),cos(w*theta)]])\n p=np.dot(np.identity(2)-r,np.array([[-vy/w],[vx/w]]))\n g=np.vstack(( np.hstack((r,p)),np.array([0,0,1]) ))\n \n return g\n\ndef homog_3d(xi, theta):\n \"\"\"\n Computes a 4x4 homogeneous transformation matrix given a 3D twist and a \n joint displacement.\n \n Args:\n xi - (6,) ndarray: the 3D twist\n theta: the joint displacement\n\n Returns:\n g - (4,4) ndarary: the resulting homogeneous transformation matrix\n \"\"\"\n if not xi.shape == (6,):\n raise TypeError('xi must be a 6-vector')\n\n from numpy.linalg import norm\n vx, vy, vz, wx, wy, wz = xi\n v = np.array([[vx,vy,vz]]).T\n w = np.array([[wx,wy,wz]]).T\n what = skew_3d(w.T[0])\n wnorm = norm(w)\n\n r = rotation_3d(w.T[0], theta)\n p = (np.dot(np.identity(3)-r,np.dot(what,v)) + np.dot(np.dot(w,w.T),v*theta)) / (wnorm**2)\n\n g=np.vstack(( np.hstack((r,p)),np.array([0,0,0,1]) ))\n\n return g\n\ndef prod_exp(xi, theta):\n \"\"\"\n Computes the product of exponentials for a kinematic chain, given \n the twists and displacements for each joint.\n \n Args:\n xi - (6,N) ndarray: the twists for each joint\n theta - (N,) ndarray: the displacement of each joint\n \n Returns:\n g - (4,4) ndarray: the resulting homogeneous transformation matrix\n \"\"\"\n if not xi.shape[0] == 6:\n raise TypeError('xi must be a 6xN')\n\n from functools import reduce\n homog = [homog_3d(xi.T[i], theta[i]) for i in range(len(theta))]\n g = reduce(np.dot, homog)\n return g\n\n#-----------------------------Testing code--------------------------------------\n#-------------(you shouldn't need to modify anything below here)----------------\n\ndef array_func_test(func_name, args, ret_desired):\n ret_value = func_name(*args)\n if not isinstance(ret_value, np.ndarray):\n print('[FAIL] ' + func_name.__name__ + '() returned something other than a NumPy ndarray')\n elif ret_value.shape != ret_desired.shape:\n print('[FAIL] ' + func_name.__name__ + '() returned an ndarray with incorrect dimensions')\n elif not np.allclose(ret_value, ret_desired, rtol=1e-3):\n print('[FAIL] ' + func_name.__name__ + '() returned an incorrect value')\n else:\n print('[PASS] ' + func_name.__name__ + '() returned the correct value!')\n\nif __name__ == \"__main__\":\n print('Testing...')\n\n #Test skew_3d()\n arg1 = np.array([1.0, 2, 3])\n func_args = (arg1,)\n ret_desired = np.array([[ 0., -3., 2.],\n [ 3., -0., -1.],\n [-2., 1., 0.]])\n array_func_test(skew_3d, func_args, ret_desired)\n\n #Test rotation_2d()\n arg1 = 2.658\n func_args = (arg1,)\n ret_desired = np.array([[-0.8853, -0.465 ],\n [ 0.465 , -0.8853]])\n array_func_test(rotation_2d, func_args, ret_desired)\n\n #Test rotation_3d()\n arg1 = np.array([2.0, 1, 3])\n arg2 = 0.587\n func_args = (arg1,arg2)\n ret_desired = np.array([[-0.1325, -0.4234, 0.8962],\n [ 0.8765, -0.4723, -0.0935],\n [ 0.4629, 0.7731, 0.4337]])\n array_func_test(rotation_3d, func_args, ret_desired)\n\n #Test hat_2d()\n arg1 = np.array([2.0, 1, 3])\n func_args = (arg1,)\n ret_desired = np.array([[ 0., -3., 2.],\n [ 3., 0., 1.],\n [ 0., 0., 0.]])\n array_func_test(hat_2d, func_args, ret_desired)\n\n #Test hat_3d()\n arg1 = np.array([2.0, 1, 3, 5, 4, 2])\n func_args = (arg1,)\n ret_desired = np.array([[ 0., -2., 4., 2.],\n [ 2., -0., -5., 1.],\n [-4., 5., 0., 3.],\n [ 0., 0., 0., 0.]])\n array_func_test(hat_3d, func_args, ret_desired)\n\n #Test homog_2d()\n arg1 = np.array([2.0, 1, 3])\n arg2 = 0.658\n func_args = (arg1,arg2)\n ret_desired = np.array([[-0.3924, -0.9198, 0.1491],\n [ 0.9198, -0.3924, 1.2348],\n [ 0. , 0. , 1. ]])\n array_func_test(homog_2d, func_args, ret_desired)\n\n #Test homog_3d()\n arg1 = np.array([2.0, 1, 3, 5, 4, 2])\n arg2 = 0.658\n func_args = (arg1,arg2)\n ret_desired = np.array([[ 0.4249, 0.8601, -0.2824, 1.7814],\n [ 0.2901, 0.1661, 0.9425, 0.9643],\n [ 0.8575, -0.4824, -0.179 , 0.1978],\n [ 0. , 0. , 0. , 1. ]])\n array_func_test(homog_3d, func_args, ret_desired)\n\n #Test prod_exp()\n arg1 = np.array([[2.0, 1, 3, 5, 4, 6], [5, 3, 1, 1, 3, 2], [1, 3, 4, 5, 2, 4]]).T\n arg2 = np.array([0.658, 0.234, 1.345])\n func_args = (arg1,arg2)\n ret_desired = np.array([[ 0.4392, 0.4998, 0.7466, 7.6936],\n [ 0.6599, -0.7434, 0.1095, 2.8849],\n [ 0.6097, 0.4446, -0.6562, 3.3598],\n [ 0. , 0. , 0. , 1. ]])\n array_func_test(prod_exp, func_args, ret_desired)\n\n print('Done!')\n","sub_path":"MZP/src/project/src/kin_func_skeleton.py","file_name":"kin_func_skeleton.py","file_ext":"py","file_size_in_byte":8900,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"489837641","text":"#coding:utf-8\nimport cv2\nimport numpy as np\nimport os\nfrom copy import copy\n\nfrom multiprocessing import Pool\nfrom multiprocessing import Process\n\nfrom keras.preprocessing.image import NumpyArrayIterator\n\nclass Load_data():\n def __init__(self, train_path, hint_path, target_path, namefile, batchsize):\n self.train_path = train_path\n self.hint_path = hint_path\n self.target_path = target_path\n self.namelist = self.read_text(namefile)\n self.batchsize = batchsize\n self.neiborhood24 = np.array([[1, 1, 1, 1, 1],\n [1, 1, 1, 1, 1],\n [1, 1, 1, 1, 1],\n [1, 1, 1, 1, 1],\n [1, 1, 1, 1, 1]],\n np.uint8)\n self.nb_data = len(self.namelist)\n\n def read_text(self,namefile):\n with open(namefile, \"r\") as f:\n names = f.readlines()\n namelist = [line.rstrip(\"\\n\") for line in names]\n return namelist\n\n \"\"\"\n def generate_arrays_from_file(self):\n while True:\n for name in self.namelist:\n train, target = self.process_line(name)\n yield (train, target)\n \"\"\"\n\n def generate_arrays_from_file(self):\n while True:\n for name in self.namelist:\n train, target = self.process_line(name)\n yield (train, target)\n\n \"\"\"\n def process_line(self, name):\n train = cv2.resize(cv2.imread(self.train_path + \"/\" + name, cv2.IMREAD_GRAYSCALE),(256,256))\n train = train.reshape((1,256,256))\n hint = cv2.resize(cv2.imread(self.hint_path + \"/\" + name),(256,256)).transpose(2,0,1)\n train = np.concatenate((train, hint))\n target = cv2.resize(cv2.imread(self.target_path + \"/\" + name),(256,256)).transpose(2,0,1)\n train = train / 255\n target = target / 255\n return train[np.newaxis,:], target[np.newaxis,:]\n \"\"\"\n\n def process_line(self, name):\n train = np.zeros((self.batchsize,4,256,256))\n #train = np.zeros((self.batchsize,1,256,256))\n target = np.zeros((self.batchsize,3,256,256))\n for i in range(self.batchsize):\n X_c = cv2.resize(cv2.imread(self.train_path + \"/\" + name, cv2.IMREAD_GRAYSCALE),(256,256))\n X_c = X_c.reshape((1,256,256))\n X_h = cv2.resize(cv2.imread(self.hint_path + \"/\" + name),(256,256)).transpose(2,0,1)\n X = np.concatenate((X_c, X_h))\n #X = X_c\n y = cv2.resize(cv2.imread(self.target_path + \"/\" + name),(256,256)).transpose(2,0,1)\n train[i,:], target[i,:] = X, y\n train = train / 255\n target = target / 255\n return (train, target)\n\n def make_val_data(self):\n name = self.namelist[0]\n X_val, y_val = self.process_line(name)\n return (X_val, y_val)\n\ndef make_name_text():\n path = \"/Volumes/DATASET/pixiv_images_dataset_for_coloring/\"\n namelist = os.listdir(path)\n with open(\"name.txt\", \"w\") as f:\n for name in namelist:\n f.write(name+\"\\n\")\n\ndef make_contour_image(imgname):\n neiborhood24 = np.array([[1, 1, 1, 1, 1],\n [1, 1, 1, 1, 1],\n [1, 1, 1, 1, 1],\n [1, 1, 1, 1, 1],\n [1, 1, 1, 1, 1]],\n np.uint8)\n From = \"./demo\"\n To = \"./demo\"\n path = From + \"/\" + imgname\n img = cv2.imread(path, cv2.IMREAD_GRAYSCALE)\n dilated = cv2.dilate(img,neiborhood24,iterations=1)\n diff = cv2.absdiff(dilated, img)\n contour = 255 - diff\n topath = To + \"/\" + imgname\n cv2.imwrite(topath, contour)\n\ndef make_contour_dataset(core):\n namefile = \"./test.txt\"\n p = Pool(core)\n with open(namefile) as f:\n namelist = f.readlines()\n namelist = [name.strip(\"\\n\") for name in namelist]\n p.map(make_contour_image, namelist)\n\ndef make_hint_image(img):\n neiborhood24 = np.array([[1, 1, 1, 1, 1],\n [1, 1, 1, 1, 1],\n [1, 1, 1, 1, 1],\n [1, 1, 1, 1, 1],\n [1, 1, 1, 1, 1]],\n np.uint8)\n himg = cv2.resize(cv2.imread(img), (256,256)).transpose(2,0,1)\n z = np.zeros((256,256))\n rs = np.random.randint(0, 255, 30)\n cs = np.random.randint(0, 255, 30)\n indices = [(r,c) for (r,c) in zip(rs, cs)]\n for ix in indices:\n z[ix] = 1\n z = cv2.dilate(z,neiborhood24,iterations=1)\n for i in range(3):\n himg[i,:,:] = himg[i,:,:] * z #(3,256,256)\n return himg.transpose(1,2,0)\n\nif __name__ == \"__main__\":\n hint = make_hint_image(\"/Users/kento_watanabe/Desktop/work/coloring/demo/shinobu.jpg\")\n cv2.imwrite(\"../hint/shinobu.jpg\", hint)\n","sub_path":"preprocess.py","file_name":"preprocess.py","file_ext":"py","file_size_in_byte":4879,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"55767744","text":"import mysteryword as mw\n\n\ndef words_of_the_right_length(word_list, blankstring):\n length_of_word = len(blankstring)\n reduced_list = word_length_selector(length_of_word, length_of_word)\n return reduced_list\n\n\ndef words_with_right_letters(word_list, blankstring):\n reduced_list = [word for word in word_list if word_matches(blankstring)]\n return reduced_list\n\n\ndef word_matches(given_word, blankstring):\n word_comparison = zip(given_word, blankstring)\n for letter in word_comparison:\n if letter[1] == \"_\" or letter[0] == letter[1]:\n continue\n else:\n return False\n return True\n","sub_path":"mw_solver.py","file_name":"mw_solver.py","file_ext":"py","file_size_in_byte":635,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"18814549","text":"from . import __version__ as app_version\n\napp_name = \"cargo_management\"\napp_title = \"Cargo Management\"\napp_publisher = \"Agile Shift\"\napp_description = \"Track Packages across multiple carriers.\"\napp_icon = \"icon-paper-clip\"\napp_color = \"red\"\napp_email = \"contacto@gruporeal.org\"\napp_license = \"MIT\"\nsource_link = \"https://github.com/AgileShift/cargo_management\"\n\n# Custom Values to personalize the logos\napp_logo_url = '/assets/cargo_management/images/quickbox-imagotipo.svg'\n\n# Includes in \n# ------------------\n\n# include js, css files in header of desk.html\napp_include_css = [\"/assets/css/package-indicator.min.css\"]\n# app_include_js = \"/assets/cargo_management/js/package_management.js\"\n\n# include js, css files in header of web template\n# web_include_css = \"/assets/cargo_management/css/package_management.css\"\n# web_include_js = \"/assets/cargo_management/js/package_management.js\"\n\n# include js, css files in header of web form\n# webform_include_js = {\"doctype\": \"public/js/doctype.js\"}\n# webform_include_css = {\"doctype\": \"public/css/doctype.css\"}\n\n# include js in page\n# page_js = {\"page\" : \"public/js/file.js\"}\n\n# include js in doctype views\n# doctype_js = {\"doctype\" : \"public/js/doctype.js\"}\n# doctype_list_js = {\"doctype\" : \"public/js/doctype_list.js\"}\n# doctype_tree_js = {\"doctype\" : \"public/js/doctype_tree.js\"}\n# doctype_calendar_js = {\"doctype\" : \"public/js/doctype_calendar.js\"}\n\n# Home Pages\n# ----------\n\n# application home page (will override Website Settings)\n# home_page = \"login\"\n\n# website user home page (by Role)\n# role_home_page = {\n#\t\"Role\": \"home_page\"\n# }\n\n# Website user home page (by function)\n# get_website_user_home_page = \"cargo_management.utils.get_home_page\"\n\n# Generators\n# ----------\n\n# automatically create page for each record of this doctype\n# website_generators = [\"Web Page\"]\n\n# Installation\n# ------------\n\n# before_install = \"cargo_management.install.before_install\"\n# after_install = \"cargo_management.install.after_install\"\n\n# Desk Notifications\n# ------------------\n# See frappe.core.notifications.get_notification_config\n\n# notification_config = \"cargo_management.notifications.get_notification_config\"\n\n# Permissions\n# -----------\n# Permissions evaluated in scripted ways\n\n# permission_query_conditions = {\n# \t\"Event\": \"frappe.desk.doctype.event.event.get_permission_query_conditions\",\n# }\n#\n# has_permission = {\n# \t\"Event\": \"frappe.desk.doctype.event.event.has_permission\",\n# }\n\n# Document Events\n# ---------------\n# Hook on document methods and events\n\n# doc_events = {\n# \t\"*\": {\n# \t\t\"on_update\": \"method\",\n# \t\t\"on_cancel\": \"method\",\n# \t\t\"on_trash\": \"method\"\n#\t}\n# }\n\n# Scheduled Tasks\n# ---------------\n\n# scheduler_events = {\n# \t\"all\": [\n# \t\t\"cargo_management.tasks.all\"\n# \t],\n# \t\"daily\": [\n# \t\t\"cargo_management.tasks.daily\"\n# \t],\n# \t\"hourly\": [\n# \t\t\"cargo_management.tasks.hourly\"\n# \t],\n# \t\"weekly\": [\n# \t\t\"cargo_management.tasks.weekly\"\n# \t]\n# \t\"monthly\": [\n# \t\t\"cargo_management.tasks.monthly\"\n# \t]\n# }\n\n# Testing\n# -------\n\n# before_tests = \"cargo_management.install.before_tests\"\n\n# Overriding Methods\n# ------------------------------\n#\n# override_whitelisted_methods = {\n# \t\"frappe.desk.doctype.event.event.get_events\": \"cargo_management.event.get_events\"\n# }\n#\n# each overriding function accepts a `data` argument;\n# generated from the base implementation of the doctype dashboard,\n# along with any modifications made in other Frappe apps\n# override_doctype_dashboards = {\n# \t\"Task\": \"cargo_management.task.get_dashboard_data\"\n# }\n\n# exempt linked doctypes from being automatically cancelled\n#\n# auto_cancel_exempted_doctypes = [\"Auto Repeat\"]\n\n# TODO: Add 'domains' this, can be useful. Like add default data\n\nglobal_search_doctypes = {\n\t\"Default\": [\n\t\t{\"doctype\": \"Package\"},\n\t\t{\"doctype\": \"Warehouse Receipt\"},\n\t\t{\"doctype\": \"Cargo Shipment\"},\n\t\t{\"doctype\": \"Cargo Shipment Receipt\"},\n\t]\n}\n","sub_path":"cargo_management/hooks.py","file_name":"hooks.py","file_ext":"py","file_size_in_byte":3863,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"416821106","text":"import numpy as np\nimport matplotlib.pyplot as plt\nfrom scipy import optimize\nfrom matplotlib.ticker import (MultipleLocator, FormatStrFormatter,AutoMinorLocator)\n\ndef factor(epsilon,zeta):\n\treturn (zeta-1)/(zeta*(1+epsilon)**(3/2) - (1+epsilon)**(-3/2))\n\n\ndef factorfull(epsilon,zeta,psi0):\n\tstrain = 1+epsilon\n\targument = strain**(-3/2)/(1-zeta) /np.sin(2*psi0)\n\targument -= strain**(-3/2)/2 * np.tan(psi0)\n\targument -= strain**(3/2) /(1-zeta) /np.sin(2*psi0)\n\targument += strain**(3/2)/2 *1/np.tan(psi0)\n\treturn (1/(2*psi0))*np.arctan(1/argument)\n\n\nepsilonlist = np.linspace(0,0.1,num=1000)\n\n\npsi0tendon = 0.036\npsi0tendon2 = 0.075\n\n###############Experimental Data\n\nbellepsilondata=np.array([1-1,1.014-1,1.028-1,1.05-1])\nbellfdata = np.array([1,14/16,12/16,11/16])\nbellferror = np.array([np.sqrt(2)/16,np.sqrt((14/16)**2 + 1)/16,np.sqrt((12/16)**2 + 1)/16,np.sqrt((11/16)**2 + 1)/16])\n\nshgepsilondata = np.array([1-1,1.00404-1,1.00802-1,1.01195-1,1.01598-1])\nshgfdata=np.array([1,0.0346900406387585/psi0tendon,0.0316705591953319/psi0tendon,0.0278961803653616/psi0tendon,0.0258797680232975/psi0tendon])\nshgfdata2 = np.array([1,0.07369/psi0tendon2,0.07067/psi0tendon2,0.066896/psi0tendon2,0.0648798/psi0tendon2])\nshgferror1=np.zeros(5)\nshgferror2=np.zeros(5)\nshgferror3=np.zeros(5)\n\nlaurenterror1=np.array([0.00720290292326979,0.00716817247255574,0.00708863396758596,0.0069902131882552,0.0069380856395288])\nlaurenterror2=np.array([0.0188333936879618,0.0181698641106537,0.0166343259001043,0.014702858673892,0.0136654767342154])\n\nfor i in range(5):\n\tshgferror1[i] = laurenterror1[i]/psi0tendon * np.sqrt(1+shgfdata[i]**2)\n\tshgferror2[i] = laurenterror2[i]/psi0tendon * np.sqrt(1+shgfdata[i]**2)\n\tshgferror3[i] = laurenterror1[i]/psi0tendon2 * np.sqrt(1+shgfdata2[i]**2)\n\n\n################Plotting\n\nfig, ax = plt.subplots()\n\nax.errorbar(100*bellepsilondata,bellfdata,bellferror,label='Corneal Fibrils, WAXS (Bell et al, 2018)',fmt='D:k')\n#ax.errorbar(100*shgepsilondata,shgfdata,shgferror1,label='Tendon Data (Gusachenko et al, 2012), $\\psi_0 = 0.036$',fmt='X:g')\nax.errorbar(100*shgepsilondata,shgfdata2,shgferror3,label='Tendon Fibrils, P-SHG (Gusachenko et al, 2012)',fmt='X:r')\n\nax.plot(100*(epsilonlist),factor(epsilonlist,1.2),label='$\\zeta=1.2$',linestyle='--',color='green')\nax.plot(100*(epsilonlist),factor(epsilonlist,1.3),label='$\\zeta=1.3$')\nax.plot(100*(epsilonlist),factor(epsilonlist,1.4),label='$\\zeta=1.4$',linestyle='-.')\n#ax.plot(100*(epsilonlist),factor(epsilonlist,1.14),label='$\\zeta=1.14$')\n\n#ax.plot(100*(epsilonlist),factorfull(epsilonlist,1.34,0.3),linestyle=':',label='Full Solution, $\\zeta=1.34$')\n#ax.plot(100*(epsilonlist),factorfull(epsilonlist,1.14,0.036),linestyle=':',label='Full Solution, $\\zeta=1.14$')\n\nax.set_xlabel('Fibril Strain',fontsize=20,labelpad=10)\nax.set_ylabel(r'$\\frac{\\langle \\psi\\rangle}{\\langle\\psi_0\\rangle}$',fontsize=30,rotation=0,labelpad=30)\nax.set_xlim(0,8)\nax.set_xticks([0,2,4,6,8])\nax.set_xticklabels(['0%','2%', '4%','6%', '8%'],fontsize=16)\nax.set_yticks([0.4,0.5,0.6,0.7,0.8,0.9,1.0])\nax.set_yticklabels(['0.4','0.5','0.6','0.7','0.8','0.9','1.0'],fontsize=16)\nax.set_ylim(0.5,1.05)\nax.legend(loc='best',fancybox=True,fontsize='x-large')\nax.xaxis.set_minor_locator(MultipleLocator(0.2))\nax.yaxis.set_minor_locator(MultipleLocator(0.02))\n\nplt.subplots_adjust(left=0.16,bottom=0.18,top=0.97,right=0.96)\nplt.show()\n\n\n\n\n\n\n####################### Fitting:\n\ndef Costfunction(zeta,xdata,ydata):\n\treturn np.sum((ydata - factor(xdata,zeta))**2)\n\nx = optimize.curve_fit(factor,bellepsilondata,bellfdata,sigma = bellferror,p0=1.3)\ny = optimize.curve_fit(factor,shgepsilondata,shgfdata,sigma = shgferror1,p0=1.3)\nz = optimize.curve_fit(factor,shgepsilondata,shgfdata,sigma = shgferror2,p0=1.3)\n","sub_path":"Scripts/FittingAnisotropyData.py","file_name":"FittingAnisotropyData.py","file_ext":"py","file_size_in_byte":3745,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"39522816","text":"import pickle\nimport os\nfrom skimage.io import imread\nfrom skimage.feature import hog\nfrom utils import *\nfrom sklearn.metrics import accuracy_score, precision_score\nimport pdb\nfrom sklearn.svm import LinearSVC\n\n\ndef get_data(path, img_folder, lm_file):\n files = os.listdir(path + img_folder)\n fimages = [os.path.join(path + img_folder, f) for f in files if f[-3:] == 'jpg']\n fd = np.zeros((len(fimages), 7688))\n for i, fi in enumerate(fimages):\n image = imread(fi)\n fd[i], hog_images = hog(image, orientations=8, pixels_per_cell=(16, 16),\n cells_per_block=(1, 1), visualize=True, multichannel=True)\n data = loadmat(path + lm_file)\n face_landmarks = data['face_landmark']\n vote_diff = data['vote_diff']\n return fd, face_landmarks, vote_diff\n\ndef find_rank_data(X, voting_diff):\n n = len(X)\n print(n)\n #.set_trace()\n Xp = []\n diff = []\n yp = []\n for i in range(0, int(n/2), 2):\n Xp.append(X[i + 1] - X[i])\n diff.append(abs(voting_diff[i]))\n if np.sign(voting_diff[i + 1] - voting_diff[i]) == 0:\n yp.append(1)\n else:\n yp.append(np.sign(voting_diff[i + 1] - voting_diff[i]))\n\n for i in range(int(n/2), n, 2):\n Xp.append(X[i] - X[i + 1])\n diff.append(abs(voting_diff[i]))\n if np.sign(voting_diff[i] - voting_diff[i + 1]) == 0:\n yp.append(1)\n else:\n yp.append(np.sign(voting_diff[i] - voting_diff[i + 1]))\n yp = [int(yp[i]) for i in range(len(yp))]\n print(\"Unique yp values are..\")\n print(np.unique(yp))\n return Xp, diff, yp\n\ndef rank_svm(elec_type, img_folder, lm_file, i):\n # create features\n print(\"Loading data....\")\n print(path + '/' + elec_type + 'Xp_2_1.pkl')\n if not os.path.exists(path + '/' + elec_type + 'Xp_2_1.pkl'):\n fd, face_landmarks, vote_diff = get_data(path, img_folder, lm_file)\n print(\"Concatenating features...\")\n concat_features = np.concatenate((fd, face_landmarks), axis=1)\n Xp, diff, yp = find_rank_data(concat_features, vote_diff)\n # Save features\n print(\"Saving values....\")\n pickle.dump(Xp, open(path + '/' + elec_type + 'Xp_2_1.pkl', 'wb'))\n pickle.dump(yp, open(path + '/' + elec_type + 'yp_2_1.pkl', 'wb'))\n else:\n print(\"Reading saved values..\")\n Xp = pickle.load(open(path + '/' + elec_type + 'Xp_2_1.pkl', 'rb'))\n yp = pickle.load(open(path + '/' + elec_type + 'yp_2_1.pkl', 'rb'))\n # Split data\n print(\"Splitting and saving values...\")\n X_train, X_test, y_train, y_test = split_data_rank_svm(Xp, yp, i)\n # Scale data\n X_train_scaled, X_test_scaled = scale_features(X_train, X_test)\n #pdb.set_trace()\n # grid search\n print(\"Grid search....\")\n if not os.path.exists(path + '/' + elec_type + 'best_params_2_1.pkl'):\n cost_vals = [2**x for x in range(-15, 15)]\n best_params, best_mse = grid_search_rank_svm(X_train_scaled, y_train, cost_vals)\n pickle.dump(best_params, open(path + '/' + elec_type + 'best_params_2_1.pkl', 'wb'))\n pickle.dump(best_mse, open(path + '/' + elec_type + 'best_mse_2_1.pkl', 'wb'))\n else:\n best_params = pickle.load(open(path + '/' + elec_type + 'best_params_2_1.pkl', 'rb'))\n best_mse = pickle.load(open(path + '/' + elec_type + 'best_mse_2_1.pkl', 'rb'))\n # Create model\n clf = LinearSVC(C=best_params['C'], fit_intercept=False)\n # Find train accuracy and precision\n print(\"Training....\")\n clf.fit(X_train_scaled, y_train)\n y_train_predict = clf.predict(X_train_scaled)\n train_acc_score = accuracy_score(y_train, y_train_predict)\n train_prec_score = precision_score(y_train, y_train_predict)\n print(\"Training accuracy and precision for \" + elec_type)\n print(train_acc_score, train_prec_score)\n # Find test accuracy and precision\n print(\"Testing...\")\n y_test_predict = clf.predict(X_test_scaled)\n test_acc_score = accuracy_score(y_test, y_test_predict)\n test_prec_score = precision_score(y_test, y_test_predict)\n print(\"Testing accuracy and precision for \" + elec_type)\n print(test_acc_score, test_prec_score)\n # Save all values\n print(\"Saving values...\")\n pickle.dump(train_acc_score, open(path + '/' + elec_type + 'train_acc_2_1.pkl', 'wb'))\n pickle.dump(test_acc_score, open(path + '/' + elec_type + 'test_acc_2_1.pkl', 'wb'))\n pickle.dump(train_prec_score, open(path + '/' + elec_type + 'train_prec_2_1.pkl', 'wb'))\n pickle.dump(test_prec_score, open(path + '/' + elec_type + 'test_prec_2_1.pkl', 'wb'))\n\nelec_type = 'sen'\npath = 'C:/Users/hsatreya/Desktop/RupaFolder/project4_code_and_data'\n\nprint(\"Setting values in sen..\")\nimg_folder = '/img-elec/senator'\nlm_file = '/stat-sen.mat'\nrank_svm(elec_type, img_folder, lm_file, 12)\n\nelec_type = 'gov'\nimg_folder = '/img-elec/governor'\nlm_file = '/stat-gov.mat'\nrank_svm(elec_type, img_folder, lm_file, 16)\n","sub_path":"Project3/Part2_1.py","file_name":"Part2_1.py","file_ext":"py","file_size_in_byte":4958,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"202186161","text":"#!/usr/bin/env python3\n\nfrom collections import Counter\nfrom concurrent.futures import ProcessPoolExecutor\nimport enum\nimport json\nimport multiprocessing\nfrom multiprocessing.managers import BaseManager, NamespaceProxy\nimport os\nimport os.path as osp\nimport subprocess\n\nfrom . import LOGS_DIR\n\n__author__ = \"Dibyo Majumdar\"\n__email__ = \"dibyo.majumdar@gmail.com\"\n\n\n@enum.unique\nclass TestExecStatusEnum(enum.Enum):\n errored = -1\n done = 0\n queued = 1\n dryrun = 2\n executing = 3\n\n\nclass TestExecResult:\n \"\"\"Wrapper for the results of executing a set of tests.\n\n This provides conversion from test output to result and an iterator\n for easy recording of results.\n \"\"\"\n\n class TestStep:\n symbol_result_map = {\n '.': 'passed',\n 'F': 'failed',\n '-': 'skipped',\n }\n\n def __init__(self, result: 'TestExecResult' or 'TestExecResultProxy', step: dict):\n self.test_exec_result = result\n self.step = step\n\n def set_result(self, symbol: str):\n result = self.symbol_result_map[symbol]\n self.step['result']['status'] = result\n self.test_exec_result.update_counters(result)\n\n def __init__(self, status: TestExecStatusEnum=TestExecStatusEnum.queued,\n counters: dict=None, data=None):\n self.status = status\n self.counters = counters if counters is not None else Counter()\n self._data = data if data is not None else []\n self._step_refs = list(test_step.step for test_step in self.iterator())\n self._step_ref_pos = 0\n\n @property\n def data(self):\n return self._data\n\n @data.setter\n def data(self, data):\n self._data = data\n self._step_refs = []\n self._step_ref_pos = 0\n self.counters['total'] = 0\n for test_step in self.iterator():\n test_step.step['result']['status'] = 'pending'\n self._step_refs.append(test_step.step)\n self.counters['total'] += 1\n\n def json(self):\n steps = []\n for test_file in self._data:\n scenarios = []\n scenario_steps = []\n for test_scenario in test_file['elements']:\n tags = [test_scenario['keyword']]\n for test_step in test_scenario['steps']:\n scenario_steps.append({\n 'tags': tags,\n 'keyword': test_step['keyword'],\n 'name': test_step['name'],\n 'status': test_step['result']['status']\n })\n if test_scenario['keyword'] != 'Background':\n scenarios.append({\n 'name': test_scenario['name'],\n 'steps': scenario_steps\n })\n scenario_steps = []\n steps.append({\n 'name': test_file['name'],\n 'scenarios': scenarios\n })\n return json.dumps({\n 'status': self.status.name.upper(),\n 'counters': self.counters,\n 'steps': steps\n }, indent=4)\n\n def iterator(self):\n if self.data is None or isinstance(self.data, Exception):\n return\n\n for test_file in self.data:\n for test_scenario in test_file['elements']:\n for test_step in test_scenario['steps']:\n yield TestExecResult.TestStep(self, test_step)\n\n def update_counters(self, curr_result: str):\n step = self._step_refs[self._step_ref_pos]\n step['result']['status'] = curr_result\n self._step_ref_pos += 1\n self.counters[curr_result] += 1\n self.counters['completed'] += 1\n\n\nclass TestExecResultProxy(NamespaceProxy):\n \"\"\"Proxy for TestExecResult, for syncing between multiple processes.\"\"\"\n _exposed_ = ('__getattribute__', '__setattr__', '__delattr__',\n 'update_counters')\n\n def iterator(self):\n return TestExecResult.iterator(self)\n\n def update_counters(self, curr_result: str):\n return self._callmethod('update_counters', (curr_result, ))\n\n\nclass TestExecResultsManager(BaseManager):\n pass\n\nTestExecResultsManager.register('TestExecResult', TestExecResult, TestExecResultProxy)\n\n\nCUCUMBER_DRYRUN_CMD = 'bundle exec cucumber -d' \\\n ' -f json'\nCUCUMBER_EXECUTION_CMD = 'bundle exec cucumber' \\\n ' -f json -o {output}' \\\n ' -f progress'\n\n\ndef execute_tests(test_exec_uuid: str, test_exec_result: TestExecResult or TestExecResultProxy):\n print('{worker}: starting {uuid}'.format(worker=multiprocessing.current_process().name,\n uuid=test_exec_uuid))\n logs_output = osp.join(LOGS_DIR, test_exec_uuid)\n subprocess.check_call('mkdir -p {}'.format(logs_output).split())\n\n try:\n # dryrun\n test_exec_result.status = TestExecStatusEnum.dryrun\n dryrun = subprocess.Popen(CUCUMBER_DRYRUN_CMD.split(),\n stdout=subprocess.PIPE)\n json_data = dryrun.stdout.read().decode('utf-8')\n test_exec_result.data = json.loads(json_data)\n\n # execution\n test_exec_result.status = TestExecStatusEnum.executing\n results_output_file = os.path.join(logs_output, 'cucumber_report.json')\n execution = subprocess.Popen(\n CUCUMBER_EXECUTION_CMD.format(output=results_output_file).split(),\n stdout=subprocess.PIPE)\n for test_step in test_exec_result.iterator():\n symbol = execution.stdout.read1(1).decode('utf-8')\n test_step.set_result(symbol)\n\n # completion\n test_exec_result.status = TestExecStatusEnum.done\n except Exception as error:\n test_exec_result.status = TestExecStatusEnum.errored\n print(error)\n test_exec_result.data = error\n with open(osp.join(logs_output, 'error.txt'), 'w') as error_out:\n error_out.write(str(error))\n finally:\n with open(osp.join(logs_output, 'result.json'), 'w') as result_out:\n result_out.write(test_exec_result.json())\n\n\nclass TestsExecutor(ProcessPoolExecutor):\n \"\"\"ProcessPoolExecutor implementation for tests set execution.\n\n This implementation adds a dictionary of current tests sets which get\n updated when tests set executions are requested and when tests set\n executions are completed.\n \"\"\"\n def __init__(self, results_manager: TestExecResultsManager, max_workers: int=None,\n execute_tests_func=execute_tests):\n super().__init__(max_workers)\n self.current_test_execs = {}\n self.results_manager = results_manager\n self.execute_tests_func = execute_tests_func\n\n def submit(self, test_exec_uuid: str):\n test_exec_result = self.results_manager.TestExecResult()\n self.current_test_execs[test_exec_uuid] = test_exec_result\n future = super().submit(self.execute_tests_func, test_exec_uuid, test_exec_result)\n future.add_done_callback(lambda _: self.current_test_execs.pop(test_exec_uuid))\n","sub_path":"qatserver/qatserver/executor.py","file_name":"executor.py","file_ext":"py","file_size_in_byte":7137,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"323784425","text":"import csv\nimport datetime\nimport re\nfrom threading import Lock\n\nimport requests\nfrom bs4 import BeautifulSoup\n\n# 全局变量\n\nlock = Lock()\n\nindex_zol_lst = []\nbrand_lst = [] # 所有手机型号\nbrand_url_lst = [] # 型号���url\npage_lst = [] # 该品牌下的页数\nall_url_lst = [] # 所有手机的detail页面\nOLED_lst = [] # OLED列\nfull_screen_lst = [] # full screen列\nphone_name_lst = [] # 手机型号列\ncam_num_lst = [] # 摄像头列\nfront_cam_lst = [] # 前置摄像头列\nback_cam_lst = [] # 后置摄像头列\nCPU_lst = [] # CPU列\nram_lst = [] # ram列\ndpi_lst = [] # dpi列\nppi_lst = [] # ppi列\nsize_lst = [] # size列\nrelease_date_lst = [] # release date列\nbattery_vol_lst = [] # battery vol列\nrom_lst = [] # rom列\nWG_lst = [] # 5G列\nprice_lst = [] # price列\nIP_lst = [] # IP列\nunlock_lst = [] # fingerprint type列\nback_cam_num_lst = [] # 后摄像头数量\nback_cam_1 = [] # 5个后摄像头像素\nback_cam_2 = []\nback_cam_3 = []\nback_cam_4 = []\nback_cam_5 = []\nfront_cam_num_lst = [] # 前摄像头数量\nfront_cam_1 = [] # 5个前摄像头像素\nfront_cam_2 = []\nfront_cam_3 = []\nfront_cam_4 = []\nfront_cam_5 = []\ndevice_length = [] # 设备尺寸\ndevice_width = []\ndevice_thickness = []\nreleaseY = [] # 发布年\nreleaseM = [] # 发布月\nCPU_brand = [] # CPU品牌\nwireless_charge_lst = [] # 无线充电列\nscreen_size_lst = [] # 屏幕尺寸列\nmbrand_lst = [] # 手机品牌列\n# ------------------------------\n\ncsv_file = open('data/file_url.csv') # 打开csv文件\ncsv_reader_lines = csv.reader(csv_file) # 逐行读取csv文件\nall_url_lst = [] # 创建列表准备接收csv各行数据\nfor one_line in csv_reader_lines:\n all_url_lst.append(one_line) # 将读取的csv分行数据按行存入列表‘date’中\n# for d_url in all_url_lst:\n# print(d_url[0])\n# print(len(all_url_lst))\n\nheaders = {\n \"User-Agent\": \"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_5) AppleWebKit/537.36 (KHTML, like Gecko) \"\n \"Chrome/85.0.4183.83 Safari/537.36 \"\n}\ncookies = {'cookie': 'ip_ck=4sGF5Pryj7QuNTY0MzA1LjE1OTk1MzU0MTM%3D; '\n 'z_pro_city=s_provice%3Dshanghai%26s_city%3Dshanghai; '\n 'Hm_lvt_ae5edc2bc4fc71370807f6187f0a2dd0=1599535425; visited_subcateId=57; '\n 'visited_subcateProId=57-0; userProvinceId=2; userCityId=0; userCountyId=0; userLocationId=26; '\n 'realLocationId=26; userFidLocationId=26; '\n 'z_day=izol110770%3D3%26izol110792%3D5%26izol110769%3D3%26izol110794%3D2%26ixgo20%3D1%26rdetail'\n '%3D9; questionnaire_pv=1599523236; '\n 'visited_serachKw=%u5C0F%u7C73%7C%u534E%u4E3A%7C%u590F%u666EAQUOS%20mini%20SH-03H; Adshow=5; '\n 'lv=1599543319; vn=2; Hm_lpvt_ae5edc2bc4fc71370807f6187f0a2dd0=1599543319; listSubcateId=57'}\n\n\ndef url_data(url):\n res = requests.get(url, cookies=cookies, headers=headers)\n d = res.text\n return d\n\n\nstarttime = datetime.datetime.now()\nprint(\"开始时间:\", starttime)\n\n\n# 循环一下获取到的主lst 对detail info进行爬取\ndef grab_all(d_url):\n # threadpools = ThreadPoolExecutor(max_workers=3)\n try: # 有时会出现out of range的错误\n # print(\"------\", d_url)\n try:\n data = url_data(d_url) # 读取detail url的信息\n soup = BeautifulSoup(data, \"html.parser\")\n print(d_url)\n # print(\"1\")\n phone_name = soup.select(\"body > div.product-model.page-title.clearfix > h1\") # 手机型号列\n # print(phone_name)\n phone_name_lst.append(phone_name[0].get_text()[:-2])\n except Exception as e:\n phone_name_lst.append(\"\")\n\n index_zol = re.findall(\".*/(.*)/param.shtml.*\", d_url) # 正则 匹配index_zol列\n index_zol_lst.append(index_zol) # 将index_zol存入其主列\n\n # CPU列\n # try:\n # cpu = soup.select(\"body > div.wrapper.clearfix.mt30 > div.info-list-fr > ul > li:nth-child(1) > div > \"\n # \"span.product-link\")\n # cpu = cpu[0].get_text()\n # # print(cpu)\n # CPU_lst.append(cpu)\n # except Exception as e:\n # try:\n # cpu = soup.select(\n # \"body > div.wrapper.clearfix.mt30 > div.info-list-fr > ul > li:nth-child(1) > div > a\")\n # cpu = cpu[0].get_text()\n # CPU_lst.append(cpu)\n # except Exception as e:\n # CPU_lst.append(\"\")\n\n # 后置像素列\n # try:\n # back_cam = soup.select(\n # \"body > div.wrapper.clearfix.mt30 > div.info-list-fr > ul > li:nth-child(2) > div.box-item-fl > \"\n # \"span.product-link\")\n # back_cam = back_cam[0].get_text()\n # back_cam_lst.append(back_cam)\n # except Exception as e:\n # try:\n # back_cam = soup.select(\n # \"body > div.wrapper.clearfix.mt30 > div.info-list-fr > ul > li.info-item.t-xiangsu-hd > \"\n # \"div.box-item-fl > span.product-link\")\n # back_cam = back_cam[0].get_text()\n # # print(\"back\", back_cam, back_cam == null)\n # back_cam_lst.append(back_cam)\n # except Exception as e:\n # # print(\"back\", back_cam, back_cam == null)\n # back_cam_lst.append(\"\")\n # if back_cam == \"\":\n # back_cam_lst.append(\"\")\n # 前置像素列\n # try:\n # try:\n # front_cam = soup.select(\n # \"body > div.wrapper.clearfix.mt30 > div.info-list-fr > ul > li:nth-child(3) > div.box-item-fl > \"\n # \"span.product-link\")\n # front_cam = front_cam[0].get_text()\n # except Exception as e:\n # front_cam = soup.select(\n # \"body > div.wrapper.clearfix.mt30 > div.info-list-fr > ul > li:nth-child(3) > div.box-item-fl > a\")\n # front_cam = front_cam[0].get_text()\n # # print(front_cam)\n # if \"GB\" not in front_cam:\n # front_cam_lst.append(front_cam)\n # # print(front_cam)\n # else:\n # front_cam_lst.append(\"\")\n # except Exception as e:\n # try:\n # front_cam = soup.select(\n # \"body > div.wrapper.clearfix.mt30 > div.info-list-fr > ul > li.info-item.t-xiangsu-putong > \"\n # \"div.box-item-fl > a\")\n # front_cam = front_cam[0].get_text()\n # # print(front_cam)\n # if \"GB\" not in front_cam:\n # front_cam_lst.append(front_cam)\n # # print(front_cam)\n # else:\n # front_cam_lst.append(\"\")\n # except Exception as e:\n # front_cam_lst.append(\"\")\n\n # 内存ram\n # try:\n # ram = soup.select(\n # \"body > div.wrapper.clearfix.mt30 > div.info-list-fr > ul > li.info-item.t-ramrongliang-liuchang > \"\n # \"div.box-item-fl > a\")\n # ram = ram[0].get_text()\n # # print(ram)\n # ram_lst.append(ram)\n # except Exception as e:\n # ram_lst.append(\"\")\n\n # 分辨率\n # try:\n # dpi = soup.select(\n # \"body > div.wrapper.clearfix.mt30 > div.info-list-fr > ul > li.info-item.t-fenbianlv-hd > \"\n # \"div.box-item-fl > span.product-link\")\n # dpi = dpi[0].get_text()\n # # print(dpi)\n # dpi_lst.append(dpi)\n # except Exception as e:\n # try:\n # dpi = soup.select(\"body > div.wrapper.clearfix.mt30 > div.info-list-fr > ul > \"\n # \"li.info-item.t-fenbianlv-hd > div.box-item-fl > a\")\n # dpi = dpi[0].get_text()\n # # print(dpi)\n # dpi_lst.append(dpi)\n # except Exception as e1:\n # dpi_lst.append(\"\")\n\n # 电池容量\n # try:\n # battery_vol = soup.select(\"body > div.wrapper.clearfix.mt30 > div.info-list-fr > ul > \"\n # \"li.info-item.t-dianchirongliang-yiban > div.box-item-fl > span.product-link\")\n # battery_vol = battery_vol[0].get_text()\n # battery_vol_lst.append(battery_vol[:-3])\n # except Exception as e:\n # battery_vol_lst.append(\"\")\n\n # 屏幕尺寸\n # try:\n # screen_size = soup.select(\"body > div.wrapper.clearfix.mt30 > div.info-list-fr > ul > \"\n # \"li.info-item.t-shuangshou > div.box-item-fl > span.product-link\")\n # screen_size = screen_size[0].get_text()\n # screen_size_lst.append(screen_size[:-2])\n # except Exception as e:\n # screen_size_lst.append(\"\")\n\n # 手机品牌\n try:\n mbrand = soup.select(\"#_j_breadcrumb\")\n mbrand = mbrand[0].get_text()\n mbrand_lst.append(mbrand)\n except Exception as e:\n mbrand_lst.append(\"\")\n\n # ----对所有detail行进行遍历,直到寻找到需要的数据即停止---- flag == 0 不执行\n # OLED列\n all_num = 61\n all_count = all_num - 1\n\n OLED_flag = 1\n full_screen_flag = 1\n ppi_flag = 1\n size_flag = 1\n release_date_flag = 1\n rom_flag = 1\n WG_flag = 1\n price_flag = 1\n IP_flag = 1\n unlock_flag = 1\n wireless_charge_flag = 1\n screen_size_flag = 1\n front_cam_flag = 1\n back_cam_flag = 1\n ram_flag = 1\n battery_vol_flag = 1\n CPU_flag = 1\n dpi_flag = 1\n\n for i in range(0, all_num):\n\n try:\n soup_Val = soup.select(\"#newPmVal_\" + str(i))\n soup_Val = soup_Val[0].get_text()\n # OLED列\n try:\n if OLED_flag == 1:\n OLED = soup_Val\n if \"OLED\" in OLED:\n OLED = \"1\"\n OLED_lst.append(OLED)\n OLED_flag = 0\n elif i == all_count:\n OLED_lst.append(\"0\")\n OLED_flag = 0\n pass\n except Exception as e:\n OLED_lst.append(\"0\")\n OLED_flag = 0\n\n # full screen列\n try:\n if full_screen_flag == 1:\n full_screen = soup_Val\n if \"全面\" in full_screen:\n f_screen = \"1\"\n full_screen_lst.append(f_screen)\n full_screen_flag = 0\n elif i == all_count:\n full_screen_lst.append(\"0\")\n full_screen_flag = 0\n pass\n except Exception as e:\n full_screen_lst.append(\"0\")\n full_screen_flag = 0\n\n # ppi列\n try:\n if ppi_flag == 1:\n ppi = soup_Val\n if \"ppi\" in ppi:\n ppi_lst.append(ppi)\n ppi_flag = 0\n elif i == all_count:\n ppi_lst.append(\"\")\n ppi_flag = 0\n pass\n except Exception as e:\n ppi_lst.append(\"\")\n ppi_flag = 0\n\n # 手机尺寸\n try:\n if size_flag == 1:\n size = soup_Val\n if \"mm\" in size and (\"x\" in size or \"*\" in size):\n size_lst.append(size)\n size_flag = 0\n elif i == all_count:\n size_lst.append(\"\")\n size_flag = 0\n pass\n except Exception as e:\n size_lst.append(\"\")\n size_flag = 0\n\n # 发布会时间\n try:\n if release_date_flag == 1:\n release_date = soup.select(\"#newPmName_\" + str(i))\n release_date = release_date[0].get_text()\n if \"发布会\" or \"上市\" in release_date:\n release_date_lst.append(soup_Val)\n release_date_flag = 0\n elif i == all_count:\n release_date_lst.append(\"\")\n release_date_flag = 0\n pass\n except Exception as e:\n release_date_lst.append(\"\")\n release_date_flag = 0\n\n # CPU\n try:\n if CPU_flag == 1:\n CPU = soup.select(\"#newPmName_\" + str(i))\n CPU = CPU[0].get_text()\n if \"CPU\" in CPU:\n CPU_lst.append(soup_Val)\n CPU_flag = 0\n elif i == all_count:\n CPU_lst.append(\"\")\n CPU_flag = 0\n pass\n except Exception as e:\n CPU_lst.append(\"\")\n CPU_flag = 0\n\n # CPU\n try:\n if dpi_flag == 1:\n dpi = soup.select(\"#newPmName_\" + str(i))\n dpi = dpi[0].get_text()\n if \"主屏分辨率\" in dpi:\n dpi_lst.append(soup_Val.split(\">\")[0])\n dpi_flag = 0\n elif i == all_count:\n dpi_lst.append(\"\")\n dpi_flag = 0\n pass\n except Exception as e:\n dpi_lst.append(\"\")\n dpi_flag = 0\n\n # 电池容量\n try:\n if battery_vol_flag == 1:\n battery_vol = soup.select(\"#newPmName_\" + str(i))\n battery_vol = battery_vol[0].get_text()\n if \"电池容量\" in battery_vol:\n battery_vol_val = re.findall(r'\\d+', soup_Val)\n if len(battery_vol_val) > 0:\n battery_vol_lst.append(battery_vol_val[0])\n else:\n battery_vol_lst.append(\"\")\n battery_vol_flag = 0\n elif i == all_count:\n battery_vol.append(\"\")\n battery_vol = 0\n pass\n except Exception as e:\n battery_vol_lst.append(\"\")\n battery_vol_flag = 0\n\n # 5G\n try:\n if WG_flag == 1:\n WG = soup_Val\n if \"5G手机\" in WG:\n WG_lst.append(\"1\")\n WG_flag = 0\n elif i == all_count:\n WG_lst.append(\"\")\n WG_flag = 0\n pass\n except Exception as e:\n WG_lst.append(\"\")\n WG_flag = 0\n\n # ROM\n try:\n if rom_flag == 1:\n rom_val = soup_Val\n rom = soup.select(\"#newPmName_\" + str(i))\n rom = rom[0].get_text()\n if \"ROM容量\" in rom:\n rom_val = re.findall(r'\\d+GB', rom_val) # 取值\n rom_lst.append(rom_val[0])\n # print(rom_val[0])\n rom_flag = 0\n elif i == all_count:\n rom_lst.append(\"\")\n rom_flag = 0\n pass\n except Exception as e:\n rom_lst.append(\"\")\n rom_flag = 0\n\n # RAM\n try:\n if ram_flag == 1:\n ram_val = soup_Val\n ram = soup.select(\"#newPmName_\" + str(i))\n ram = ram[0].get_text()\n if \"RAM容量\" in ram:\n ram_val = re.findall(r'\\d+GB', ram_val) # 取值\n ram_lst.append(ram_val[0])\n # print(ram_val[0])\n ram_flag = 0\n elif i == all_count:\n ram_lst.append(\"\")\n ram_flag = 0\n pass\n except Exception as e:\n rom_lst.append(\"\")\n rom_flag = 0\n\n # price\n try:\n if price_flag == 1:\n price = soup_Val\n if \"¥\" in price:\n price = price.split(\"¥\")\n price_lst.append(price[1])\n price_flag = 0\n elif i == all_count:\n price_lst.append(\"\")\n price_flag = 0\n pass\n except Exception as e:\n price_lst.append(\"\")\n price_flag = 0\n\n # IP\n try:\n if IP_flag == 1:\n IP = soup_Val\n if \"IP\" in IP:\n pattern = re.compile(r'(?<=IP)\\d+')\n new_IP = pattern.findall(IP)\n IP_lst.append(\"IP\" + str(new_IP[0]))\n IP_flag = 0\n elif i == all_count:\n IP_lst.append(\"\")\n IP_flag = 0\n pass\n except Exception as e:\n IP_lst.append(\"\")\n IP_flag = 0\n\n # 解锁方式\n try:\n unlock_val_new = \"\"\n if unlock_flag == 1:\n unlock_val = soup_Val\n unlock = soup.select(\"#newPmName_\" + str(i))\n unlock = unlock[0].get_text()\n if \"解锁方式\" in unlock:\n if \"前置\" in unlock_val:\n unlock_val_new = unlock_val_new + \"前置指纹 \"\n if \"后置\" in unlock_val:\n unlock_val_new = unlock_val_new + \"后置指纹 \"\n if \"屏幕\" in unlock_val:\n unlock_val_new = unlock_val_new + \"屏幕指纹 \"\n if \"侧面\" in unlock_val:\n unlock_val_new = unlock_val_new + \"侧面指纹\"\n unlock_lst.append(unlock_val_new)\n unlock_flag = 0\n elif i == all_count:\n unlock_lst.append(\"\")\n unlock_flag = 0\n pass\n except Exception as e:\n unlock_lst.append(\"\")\n unlock_flag = 0\n\n # 无线充���\n try:\n if wireless_charge_flag == 1:\n wireless_charge_val = soup_Val\n wireless_charge = soup.select(\"#newPmName_\" + str(i))\n wireless_charge = wireless_charge[0].get_text()\n if \"电池充电\" in wireless_charge:\n if \"无线\" in wireless_charge_val:\n wireless_charge_lst.append(\"1\")\n else:\n wireless_charge_lst.append(\"\")\n wireless_charge_flag = 0\n elif i == all_count:\n wireless_charge_lst.append(\"\")\n wireless_charge_flag = 0\n pass\n except Exception as e:\n wireless_charge_lst.append(\"\")\n wireless_charge_flag = 0\n\n # 屏幕尺寸\n try:\n if screen_size_flag == 1:\n screen_size_val = soup_Val\n screen_size = soup.select(\"#newPmName_\" + str(i))\n screen_size = screen_size[0].get_text()\n if \"主屏尺寸\" in screen_size:\n screen_size_val = re.findall(r'-?\\d+\\.?\\d*e?-?\\d*?', screen_size_val)\n screen_size_lst.append(screen_size_val[0])\n screen_size_flag = 0\n elif i == all_count:\n screen_size_lst.append(\"\")\n screen_size_flag = 0\n except Exception as e:\n screen_size_lst.append(\"\")\n screen_size_flag = 0\n\n # 前置摄像头\n try:\n if front_cam_flag == 1:\n front_cam_val = soup_Val\n front_cam = soup.select(\"#newPmName_\" + str(i))\n front_cam = front_cam[0].get_text()\n if \"前置摄像\" in front_cam:\n front_cam_lst.append(front_cam_val)\n front_cam_flag = 0\n elif i == all_count:\n front_cam_lst.append(\"\")\n front_cam_flag = 0\n except Exception as e:\n front_cam_lst.append(\"\")\n front_cam_flag = 0\n\n # 后置摄像头\n try:\n if back_cam_flag == 1:\n back_cam_val = soup_Val\n back_cam = soup.select(\"#newPmName_\" + str(i))\n back_cam = back_cam[0].get_text()\n if \"后置摄像\" in back_cam:\n back_cam_lst.append(back_cam_val)\n back_cam_flag = 0\n elif i == all_count:\n back_cam_lst.append(\"\")\n back_cam_flag = 0\n except Exception as e:\n back_cam_lst.append(\"\")\n back_cam_flag = 0\n\n except Exception as e: # 为空属性append一个\"\"\n # print(\"该机型有某个数据缺失 已经置空\")\n if ppi_flag == 1:\n ppi_lst.append(\"\")\n if size_flag == 1:\n size_lst.append(\"\")\n if OLED_flag == 1:\n OLED_lst.append(\"0\")\n if full_screen_flag == 1:\n full_screen_lst.append(\"\")\n if release_date_flag == 1:\n release_date_lst.append(\"\")\n if rom_flag == 1:\n rom_lst.append(\"\")\n if WG_flag == 1:\n WG_lst.append(\"\")\n if price_flag == 1:\n price_lst.append(\"\")\n if IP_flag == 1:\n IP_lst.append(\"\")\n if unlock_flag == 1:\n unlock_lst.append(\"\")\n if wireless_charge_flag == 1:\n wireless_charge_lst.append(\"\")\n if screen_size_flag == 1:\n screen_size_lst.append(\"\")\n if front_cam_flag == 1:\n front_cam_lst.append(\"\")\n if back_cam_flag == 1:\n back_cam_lst.append(\"\")\n if ram_flag == 1:\n ram_lst.append(\"\")\n if battery_vol_flag == 1:\n battery_vol_lst.append(\"\")\n if CPU_flag == 1:\n CPU_lst.append(\"\")\n if dpi_flag == 1:\n dpi_lst.append(\"\")\n break\n # print(len(phone_name_lst) == len(mbrand_lst) == len(index_zol_lst) == len(price_lst) == len(OLED_lst) ==\n # len(IP_lst) == len(full_screen_lst) == len(screen_size_lst) == len(back_cam_lst) == len(front_cam_lst) ==\n # len(CPU_lst) == len(ram_lst) == len(rom_lst) == len(WG_lst) == len(dpi_lst) == len(ppi_lst) == len(\n # unlock_lst) == len(release_date_lst) == len(wireless_charge_lst) == len(battery_vol_lst) == len(size_lst))\n except Exception as e:\n print(\"被drop的URL\", d_url[0])\n # continue\n\n\ndef save_all():\n # # 拆分字段-------------------------------------------------------------------------------\n\n # 后置摄像头字段拆分\n for i in back_cam_lst:\n if i != \"\":\n all_back_cam = re.findall(r'\\d+', i)\n # for ii in all_back_cam:\n # if int(ii) < 100:\n # all_back_cam.remove(ii)\n n = len(all_back_cam)\n back_cam_num_lst.append(n)\n if n > 0:\n if n == 1:\n back_cam_1.append(all_back_cam[0])\n back_cam_2.append(\"\")\n back_cam_3.append(\"\")\n back_cam_4.append(\"\")\n back_cam_5.append(\"\")\n if n == 2:\n back_cam_1.append(all_back_cam[0])\n back_cam_2.append(all_back_cam[1])\n back_cam_3.append(\"\")\n back_cam_4.append(\"\")\n back_cam_5.append(\"\")\n if n == 3:\n back_cam_1.append(all_back_cam[0])\n back_cam_2.append(all_back_cam[1])\n back_cam_3.append(all_back_cam[2])\n back_cam_4.append(\"\")\n back_cam_5.append(\"\")\n if n == 4:\n back_cam_1.append(all_back_cam[0])\n back_cam_2.append(all_back_cam[1])\n back_cam_3.append(all_back_cam[2])\n back_cam_4.append(all_back_cam[3])\n back_cam_5.append(\"\")\n if n >= 5:\n back_cam_1.append(all_back_cam[0])\n back_cam_2.append(all_back_cam[1])\n back_cam_3.append(all_back_cam[2])\n back_cam_4.append(all_back_cam[3])\n back_cam_5.append(all_back_cam[4])\n else:\n back_cam_1.append(\"\")\n back_cam_2.append(\"\")\n back_cam_3.append(\"\")\n back_cam_4.append(\"\")\n back_cam_5.append(\"\")\n\n else:\n back_cam_num_lst.append(\"\")\n back_cam_1.append(\"\")\n back_cam_2.append(\"\")\n back_cam_3.append(\"\")\n back_cam_4.append(\"\")\n back_cam_5.append(\"\")\n\n # 前置摄像头字段拆分\n for i in front_cam_lst:\n if i != \"\":\n all_front_cam = re.findall(r'\\d+', i)\n # for ii in all_front_cam:\n # if int(ii) < 100:\n # all_front_cam.remove(ii)\n n = len(all_front_cam)\n if n > 0:\n front_cam_num_lst.append(n)\n if n == 1:\n front_cam_1.append(all_front_cam[0])\n front_cam_2.append(\"\")\n front_cam_3.append(\"\")\n front_cam_4.append(\"\")\n front_cam_5.append(\"\")\n if n == 2:\n front_cam_1.append(all_front_cam[0])\n front_cam_2.append(all_front_cam[1])\n front_cam_3.append(\"\")\n front_cam_4.append(\"\")\n front_cam_5.append(\"\")\n if n == 3:\n front_cam_1.append(all_front_cam[0])\n front_cam_2.append(all_front_cam[1])\n front_cam_3.append(all_front_cam[2])\n front_cam_4.append(\"\")\n front_cam_5.append(\"\")\n if n == 4:\n front_cam_1.append(all_front_cam[0])\n front_cam_2.append(all_front_cam[1])\n front_cam_3.append(all_front_cam[2])\n front_cam_4.append(all_front_cam[3])\n front_cam_5.append(\"\")\n if n >= 5:\n front_cam_1.append(all_front_cam[0])\n front_cam_2.append(all_front_cam[1])\n front_cam_3.append(all_front_cam[2])\n front_cam_4.append(all_front_cam[3])\n front_cam_5.append(all_front_cam[4])\n else:\n front_cam_1.append(\"\")\n front_cam_2.append(\"\")\n front_cam_3.append(\"\")\n front_cam_4.append(\"\")\n front_cam_5.append(\"\")\n\n else:\n front_cam_num_lst.append(\"\")\n front_cam_1.append(\"\")\n front_cam_2.append(\"\")\n front_cam_3.append(\"\")\n front_cam_4.append(\"\")\n front_cam_5.append(\"\")\n\n # 拆分size\n for i in size_lst:\n i = str(i)[:-2]\n if i != \"\" and (\"*\" in i or \"x\" in i):\n i = i.replace(\"*\", \"x\").split(\"x\")\n try:\n device_length.append(i[0])\n except Exception as e:\n device_length.append(\"\")\n try:\n device_width.append(i[1])\n except Exception as e:\n device_width.append(\"\")\n try:\n device_thickness.append(i[2])\n except Exception as e:\n device_thickness.append(\"\")\n else:\n device_length.append(\"\")\n device_width.append(\"\")\n device_thickness.append(\"\")\n\n # 拆出CPU品牌\n for i in CPU_lst:\n if i != \"\":\n i = i.split(\" \")\n CPU_brand.append(i[0])\n else:\n CPU_brand.append(\"\")\n\n # 拆分发布日期\n for i in release_date_lst:\n i = str(i)\n if i != \"\":\n i = re.findall(r'\\d+', i)\n try:\n releaseY.append(i[0])\n except Exception as e:\n releaseY.append(\"\")\n try:\n releaseM.append(i[1])\n except Exception as e:\n releaseM.append(\"\")\n else:\n releaseY.append(\"\")\n releaseM.append(\"\")\n # 保存操作\n # -------------------------------------------------------------------------------\n # -------------------------------------------------------------------------------\n\n file_path = \"data/file_mobile.csv\"\n with open(file_path, \"w\", newline='', encoding='utf-8-sig') as f:\n fieldnames = [\"型号\", \"brand\", \"index_zol\", \"price\", \"OLED\", \"IP\", \"full screen\", \"screen_size\", \"back_cam_lst\",\n \"back_cam_num\", \"back_cam_1\",\n \"back_cam_2\",\n \"back_cam_3\", \"back_cam_4\", \"back_cam_5\", \"front_cam_lst\", \"front_cam_num\", \"front_cam_1\",\n \"front_cam_2\",\n \"front_cam_3\", \"front_cam_4\", \"front_cam_5\", \"CPU_brand\", \"CPU\",\n \"ram\", \"rom\", \"5G\", \"dpi\", \"ppi\", \"device_length\", \"device_width\", \"device_thickness\",\n \"fingerprint_type\", \"release date\", \"releaseY\", \"releaseM\", \"wireless_charge\", \"battery vol\"]\n\n f_csv = csv.DictWriter(f, fieldnames=fieldnames)\n f_csv.writeheader()\n for i in range(0, len(index_zol_lst)):\n f_csv.writerow(\n {\n \"型号\": phone_name_lst[i],\n \"brand\": mbrand_lst[i],\n \"index_zol\": index_zol_lst[i][0],\n \"price\": price_lst[i],\n \"OLED\": OLED_lst[i],\n \"IP\": IP_lst[i],\n \"full screen\": full_screen_lst[i],\n \"screen_size\": screen_size_lst[i],\n \"back_cam_lst\": back_cam_lst[i],\n \"back_cam_num\": back_cam_num_lst[i],\n \"back_cam_1\": back_cam_1[i],\n \"back_cam_2\": back_cam_2[i],\n \"back_cam_3\": back_cam_3[i],\n \"back_cam_4\": back_cam_4[i],\n \"back_cam_5\": back_cam_5[i],\n \"front_cam_lst\": front_cam_lst[i],\n \"front_cam_num\": front_cam_num_lst[i],\n \"front_cam_1\": front_cam_1[i],\n \"front_cam_2\": front_cam_2[i],\n \"front_cam_3\": front_cam_3[i],\n \"front_cam_4\": front_cam_4[i],\n \"front_cam_5\": front_cam_5[i],\n \"CPU_brand\": CPU_brand[i],\n \"CPU\": CPU_lst[i],\n \"ram\": ram_lst[i][:-2],\n \"rom\": rom_lst[i][:-2],\n \"5G\": WG_lst[i],\n \"dpi\": dpi_lst[i],\n \"ppi\": ppi_lst[i],\n \"device_length\": device_length[i],\n \"device_width\": device_width[i],\n \"device_thickness\": device_thickness[i],\n \"fingerprint_type\": unlock_lst[i],\n \"release date\": release_date_lst[i].replace(\"年\", \"/\").replace(\"月\", \"/\").replace(\"日\", \"\"),\n \"releaseY\": releaseY[i],\n \"releaseM\": releaseM[i],\n \"wireless_charge\": wireless_charge_lst[i],\n \"battery vol\": battery_vol_lst[i]\n }\n )\n endtime = datetime.datetime.now()\n print(\"Starttime:\", starttime)\n print(\"Endtime:\", endtime)\n print(\"This Program runs \", (endtime - starttime).seconds, \" seconds!\")\n\n\n# if __name__ == '__main__':\n# with ProcessPoolExecutor(max_workers=3) as p:\n# for url in all_url_lst[0:10]:\n# p.submit(grab_all, url[0])\n# save_all()\n# print(\"343434\")\n# threads = []\n# n = 0\n# p = 0\n# for d_url in all_url_lst:\n# # try:\n# # if p % 100 == 0:\n# # time.sleep(10)\n# # print(\"暂停10s\")\n# t = threading.Thread(target=grab_all, args=(d_url[0],))\n# threads.append(t)\n# # t.setDaemon(True)\n# # t.start()\n# # if n > 15:\n# # # time.sleep(4)\n# # t.join()\n# # print(\"join\")\n# # n = 0\n# for t in threads:\n# p = p + 1\n# # print(\"执行了join\")\n# if p % 300 == 0:\n# time.sleep(10)\n# p = 0\n# t.start()\n# for t in threads:\n# # print(\"执行了join\")\n# t.join()\n# tasks = []\n# for url in all_url_lst[0]:\n# c = url_data(url)\n# d_url = asyncio.ensure_future(c)\n# d_url.add_done_callback(grab_all)\n# tasks.append(d_url)\n# loop = asyncio.get_event_loop()\n# loop.run_until_complete(asyncio.wait(tasks))\nfor url in all_url_lst:\n grab_all(url[0])\nsave_all()\n\n# while len(threading.enumerate()) > 1:\n# pass\n","sub_path":"phone/find_detail.py","file_name":"find_detail.py","file_ext":"py","file_size_in_byte":35636,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"216217613","text":"#! /usr/bin/python\n\nimport sys\nfrom collections import defaultdict\nimport math\n\ndef emmission_param(e_count,u_count,e_param,count):\n\tfor key in u_count:\n\t\tfor word in count:\n\t\t\tif (word,key) in e_count:\n\t\t\t\te_param[(word,key)] = float(e_count[(word,key)])/u_count[key]\n\t\tif (\"_RARE_\",key) in e_count:\n\t\t\te_param[(\"_RARE_\",key)] = float(e_count[(\"_RARE_\",key)])/float(u_count[key])\n\ndef trans_param(b_count, t_count, t_param):\n\tfor key in t_count:\n\t\tt_param[(key[2],key[0],key[1])] = float(t_count[key])/b_count[(key[0],key[1])]\n\t\n\ntry:\n\tinput = open(sys.argv[1],\"r\")\nexcept IOError:\n\tsys.stderr.write(\"ERROR: Cannot read inputfile %s.\\n\" % arg)\n\tsys.exit(1)\n\n#count(x)\n\ncount = defaultdict(int)\nline = input.readline()\nwhile(line):\n\tif line != \"\\n\":\n\t\t#print (line)\n\t\tword = line.split()[0]\n\t\tif word in count:\n\t\t\tcount[word] += 1\n\t\telse:\n\t\t\tcount[word] = 1\n\tline = input.readline()\n\n#run count_freqs again and open gene.count to read counts\n\ntry:\n\tin_count = open(\"gene.count\",\"r\")\nexcept IOError:\n\tsys.stderr.write(\"ERROR: Cannot read inputfile %s.\\n\" % arg)\n\tsys.exit(1)\n\n#initialize dictionaries for count(y~>x), unigram, bigram and trigram counts\n\ne_count = defaultdict(int)\nu_count = defaultdict(int)\nb_count = defaultdict(int)\nt_count = defaultdict(int)\n\n#dictionary for emission parameters\ne_param = defaultdict(float)\n\n#read counts in resp dictionaries\nline = in_count.readline()\nwhile(line):\n\tif line != \"\\n\":\n\t\twords = line.split()\n\t\tif words[1] == \"WORDTAG\":\n\t\t\te_count[(words[3],words[2])] = int(words[0])\n\t\telif words[1] == \"1-GRAM\":\n\t\t\tu_count[words[2]] = int(words[0])\n\t\telif words[1] == \"2-GRAM\":\n\t\t\tb_count[(words[2],words[3])] = int(words[0])\n\t\telif words[1] == \"3-GRAM\":\n\t\t\tt_count[(words[2],words[3],words[4])] = int(words[0])\n\t\telse:\n\t\t\tprint(\"Error -->\",words[1])\n\t\t\texit(1)\n\t\t\n\tline = in_count.readline()\n\nin_count.close()\ninput.close()\n\n#part 1 open gene.dev and out file\ntry:\n\tinput = open(\"gene.test\",\"r\")\nexcept IOError:\n\tsys.stderr.write(\"ERROR: Cannot read inputfile %s.\\n\" % arg)\n\tsys.exit(1)\n\ntry:\n\toutput = open(\"gene_dev.p1.out\",\"w\")\nexcept IOError:\n\tsys.stderr.write(\"ERROR: Cannot read inputfile %s.\\n\" % arg)\n\tsys.exit(1)\n\n#calculate the emission parameters\nemmission_param(e_count,u_count,e_param,count)\n\n#tag the input and write to out file\nline = input.readline()\nwhile line:\n\tif line != \"\\n\":\n\t\ttest_word = line.split()\n\t\tmax_e_count = -1.0\n\t\ttag = \"\"\n\t\tfor key in u_count:\n\t\t\tif((test_word[0] in count) and (count[test_word[0]] >= 5)):\n\t\t\t\tif e_param[(test_word[0],key)] > max_e_count:\n\t\t\t\t\tmax_e_count = e_param[(test_word[0],key)]\n\t\t\t\t\ttag = key\n\t\t\telse:\n\t\t\t\tif e_param[(\"_RARE_\",key)] > max_e_count:\n\t\t\t\t\tmax_e_count = e_param[(\"_RARE_\",key)]\n\t\t\t\t\ttag = key\n\t\toutput.write(test_word[0] + \" \" + tag + \"\\n\")\n\telse:\n\t\toutput.write(\"\\n\")\n\tline = input.readline()\n\noutput.close()\n\n#dictionary for transmission parameters\nt_param = defaultdict(float)\n\n#calculate the transmission parameters\ntrans_param(b_count, t_count, t_param)\n\nSlis = []\nfor k in u_count:\n\tSlis.append(k)\n\ntry:\n\toutput = open(\"gene_dev.p2.out\",\"w\")\nexcept IOError:\n\tsys.stderr.write(\"ERROR: Cannot read inputfile %s.\\n\" % arg)\n\tsys.exit(1)\n\n#rset file pointer to start of file\ninput.seek(0,0)\nline = input.readline()\nwhile line:\n\tmax_prob = defaultdict(float)\n\tbp = defaultdict(str)\n\ty = defaultdict(str)\n\tmax_prob[(0,\"*\",\"*\")] = 1\n\tsent = defaultdict(str)\n\torig_sent = defaultdict(str)\n\ti = 0\n\tS = defaultdict(set)\n\tS[-1] = set('*')\n\tS[0] = set('*')\n\twhile line!=\"\\n\":\n\t\ti += 1\n\t\torig_sent[i] = line.splitlines()[0]\n\t\tsent[i] = line.splitlines()[0]\n\t\tS[i] = set(Slis)\n\t\tline = input.readline()\n\tfor k in sent:\n\t\tfor u in S[k-1]:\n\t\t\tfor v in S[k]:\n\t\t\t\tmax_prob[(k,u,v)] = -1\n\t\t\t\tfor w in S[k-2]:\n\t\t\t\t\tif(sent[k] in count and count[sent[k]]>=5):\n\t\t\t\t\t\tt = max_prob[(k-1,w,u)]*t_param[(v,w,u)]*e_param[(sent[k],v)]\n\t\t\t\t\t\tif(t>=max_prob[(k,u,v)]):\n\t\t\t\t\t\t\tmax_prob[(k,u,v)] = t\n\t\t\t\t\t\t\tbp[(k,u,v)] = w\n\t\t\t\t\telse:\n\t\t\t\t\t\tt = max_prob[(k-1,w,u)]*t_param[(v,w,u)]*e_param[(\"_RARE_\",v)]\n\t\t\t\t\t\tif(t>max_prob[(k,u,v)]):\n\t\t\t\t\t\t\tmax_prob[(k,u,v)] = t\n\t\t\t\t\t\t\tbp[(k,u,v)] = w\n\tt = -1\n\tfor u in S[i-1]:\n\t\tfor v in S[i]:\n\t\t\tm = max_prob[(i,u,v)]*t_param[(\"STOP\",u,v)]\n\t\t\tif(m>=t):\n\t\t\t\tt = m\n\t\t\t\ty[i-1] = u\n\t\t\t\ty[i] = v\n\tfor j in range(2,i):\n\t\tk = i - j\n\t\ty[k] = bp[k+2,y[k+1],y[k+2]]\n\tfor k in orig_sent:\n\t\toutput.write(orig_sent[k]+\" \"+y[k]+\"\\n\")\n\toutput.write(\"\\n\")\n\tline = input.readline()\n\ninput.close()\noutput.close()\n","sub_path":"count.py","file_name":"count.py","file_ext":"py","file_size_in_byte":4414,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"594238685","text":"try:\n from unittest2 import unittest\nexcept ImportError:\n import unittest\n\ntry:\n from cStringIO import StringIO\nexcept ImportError:\n from StringIO import StringIO\n\nfrom datetime import datetime\n\nfrom sockjs_gevent import util\n\n\nclass WSGITestApp(object):\n def __init__(self, test):\n self.test = test\n self.status = None\n self.headers = None\n self.out = StringIO()\n\n def start_response(self, status, headers):\n self.status = status\n self.headers = headers\n\n return self.out.write\n\n def assertStatus(self, status):\n self.test.assertEqual(self.status, status)\n\n def assertContentType(self, content_type):\n response_type = self.getHeader('Content-Type')\n\n self.test.assertEqual(len(response_type), 1,\n 'More than one Content-Type header found')\n\n self.test.assertEqual(response_type[0], content_type)\n\n def assertHeaders(self, headers):\n assert self.status, 'start_response not called'\n\n if len(headers) != len(self.headers):\n self.test.assertEqual(headers, self.headers)\n\n for header in self.headers:\n if header not in headers:\n self.test.assertEquals(headers, self.headers)\n\n def getHeader(self, key):\n \"\"\"\n Returns a list of values for a specific header.\n \"\"\"\n ret = []\n\n for response_header in self.headers:\n if key != response_header[0]:\n continue\n\n ret.append(response_header[1])\n\n return ret\n\n def assertHasHeader(self, header):\n \"\"\"\n Ensures that the headers from the call to `start_response` contain\n this header tuple only once.\n \"\"\"\n found = False\n\n for response_header in self.headers:\n if header[0] != response_header[0]:\n continue\n\n if found:\n raise AssertionError('Multiple headers found %r' % (\n self.headers,\n ))\n\n self.test.assertEqual(header[1], response_header[1])\n found = True\n\n if found:\n return\n\n raise AssertionError('No header %r found' % (header,))\n\n def assertCookie(self):\n \"\"\"\n Checks the response from the call to ``start_response`` for a SockJS\n compliant cookie\n \"\"\"\n found = False\n\n for header in self.headers:\n if header[0] != 'Set-Cookie':\n continue\n\n if found:\n raise AssertionError('Multiple cookie headers found %r' % (\n self.headers,\n ))\n\n self.test.assertEqual(header[1], 'JSESSIONID=dummy; Path=/')\n found = True\n\n if found:\n return\n\n raise AssertionError('No cookie header found')\n\n def assertCached(self):\n \"\"\"\n Checks the response from ``start_response`` for a valid cacheable\n response.\n \"\"\"\n expected_headers = [\n ('Cache-Control', 'max-age=31536000, public'),\n ('Access-Control-Max-Age', '31536000'),\n ]\n\n for header in expected_headers:\n self.assertHasHeader(header)\n\n expires = self.getHeader('Expires')\n\n self.test.assertEqual(len(expires), 1,\n 'More than one Expires header found')\n\n expires = datetime.strptime(expires[0], '%a, %d %b %Y %H:%M:%S GMT')\n seconds_delta = (expires - datetime.utcnow()).seconds\n\n self.test.assertEqual(seconds_delta, 86399)\n\n def assertNotCached(self):\n \"\"\"\n Checks the response from ``start_response`` for a valid non-cacheable\n response.\n \"\"\"\n self.assertHasHeader(\n ('Cache-Control', 'no-store, no-cache, must-revalidate, max-age=0')\n )\n\n def assertCors(self):\n \"\"\"\n Ensures that the response is cross domain compatible.\n \"\"\"\n expected_headers = [\n ('Access-Control-Allow-Origin', '*'),\n ('Access-Control-Allow-Credentials', 'true'),\n ]\n\n for header in expected_headers:\n self.assertHasHeader(header)\n\n\nclass BaseHandlerTestCase(unittest.TestCase):\n \"\"\"\n Tests for `util.BaseHandler`\n \"\"\"\n\n handler_class = util.BaseHandler\n\n def make_app(self):\n return WSGITestApp(self)\n\n def make_handler(self, *args):\n return self.handler_class(*args)\n\n\nclass OptionHandlerTestCase(BaseHandlerTestCase):\n \"\"\"\n Tests for `util.BaseHandler.handle_option`\n \"\"\"\n\n def test_disallowed_method(self):\n \"\"\"\n Attempting to fetch a disallowed method must result in a error http\n response.\n \"\"\"\n environ = {\n 'REQUEST_METHOD': 'PATCH'\n }\n app = self.make_app()\n handler = self.make_handler(environ, app.start_response)\n\n result = handler.handle_options('GET')\n\n self.assertTrue(result)\n app.assertStatus('405 Not Allowed')\n app.assertHeaders([\n ('Allow', 'OPTIONS, GET'),\n ('Connection', 'close'),\n ])\n self.assertEqual(app.out.getvalue(), '')\n\n def test_allowed_method(self):\n \"\"\"\n Fetching a resource with an allowed method must not result in an http\n status.\n \"\"\"\n environ = {\n 'REQUEST_METHOD': 'GET'\n }\n app = self.make_app()\n handler = self.make_handler(environ, app.start_response)\n\n result = handler.handle_options('GET')\n\n self.assertFalse(result)\n self.assertFalse(app.status)\n\n def test_options(self):\n \"\"\"\n Fetching a resource with the OPTIONS method must provide a list of\n allowed HTTP verbs\n \"\"\"\n environ = {\n 'REQUEST_METHOD': 'OPTIONS'\n }\n app = self.make_app()\n handler = self.make_handler(environ, app.start_response)\n\n result = handler.handle_options('GET', 'POST')\n\n self.assertTrue(result)\n app.assertStatus('204 No Content')\n app.assertCookie()\n app.assertCached()\n app.assertCors()\n app.assertHasHeader(\n ('Access-Control-Allow-Methods', 'OPTIONS, GET, POST'),\n )\n\n\nclass WriteTestCase(BaseHandlerTestCase):\n \"\"\"\n Tests for `util.BaseHandler.write_*`.\n \"\"\"\n\n def test_write_text(self):\n \"\"\"\n Writing a text response must call `start_response` with the correct\n content type.\n \"\"\"\n app = self.make_app()\n handler = self.make_handler({}, app.start_response)\n\n result = handler.write_text('This is a test!')\n\n self.assertEqual(result, app.out.write)\n self.assertEqual(app.out.getvalue(), 'This is a test!')\n app.assertStatus('200 OK')\n app.assertContentType('text/plain; encoding=UTF-8')\n\n def test_write_html(self):\n \"\"\"\n Writing a html response must call `start_response` with the correct\n content type.\n \"\"\"\n app = self.make_app()\n handler = self.make_handler({}, app.start_response)\n\n result = handler.write_html('This is a test!')\n\n self.assertEqual(result, app.out.write)\n self.assertEqual(app.out.getvalue(), 'This is a test!')\n app.assertStatus('200 OK')\n app.assertContentType('text/html; encoding=UTF-8')\n\n def test_write_js(self):\n \"\"\"\n Writing a json response must call `start_response` with the correct\n content type.\n \"\"\"\n app = self.make_app()\n handler = self.make_handler({}, app.start_response)\n\n result = handler.write_js('This is a test!')\n\n self.assertEqual(result, app.out.write)\n self.assertEqual(app.out.getvalue(), 'This is a test!')\n app.assertStatus('200 OK')\n app.assertContentType('application/json; encoding=UTF-8')\n\n def test_write_js_object(self):\n \"\"\"\n Passing in a Python object should attempt to encode it in JSON\n \"\"\"\n app = self.make_app()\n handler = self.make_handler({}, app.start_response)\n\n result = handler.write_js({'foo': 'bar'})\n\n self.assertEqual(result, app.out.write)\n self.assertEqual(app.out.getvalue(), '{\"foo\": \"bar\"}')\n app.assertStatus('200 OK')\n app.assertContentType('application/json; encoding=UTF-8')\n\n def test_write_nothing(self):\n \"\"\"\n `write_nothing` must send a 204 response\n \"\"\"\n app = self.make_app()\n handler = self.make_handler({}, app.start_response)\n\n result = handler.write_nothing()\n\n self.assertEqual(result, app.out.write)\n self.assertEqual(app.out.getvalue(), '')\n app.assertStatus('204 No Content')\n app.assertHeaders([])\n\n def test_not_allowed(self):\n \"\"\"\n `not_allowed` must send a 405 response.\n \"\"\"\n app = self.make_app()\n handler = self.make_handler({}, app.start_response)\n\n result = handler.not_allowed(['GET'])\n\n self.assertEqual(result, app.out.write)\n self.assertEqual(app.out.getvalue(), '')\n app.assertStatus('405 Not Allowed')\n\n expected_headers = [\n ('Allow', 'GET'),\n ('Connection', 'close'),\n ]\n app.assertHeaders(expected_headers)\n\n def test_bad_request(self):\n \"\"\"\n `bad_request` must send a 400 response.\n \"\"\"\n app = self.make_app()\n handler = self.make_handler({}, app.start_response)\n\n result = handler.bad_request('Naughty!')\n\n self.assertEqual(result, app.out.write)\n self.assertEqual(app.out.getvalue(), 'Naughty!')\n app.assertStatus('400 Bad Request')\n app.assertHeaders([])\n\n def test_not_modified(self):\n \"\"\"\n `not_modified` must send a 304 response.\n \"\"\"\n app = self.make_app()\n handler = self.make_handler({}, app.start_response)\n\n result = handler.not_modified()\n\n self.assertEqual(result, app.out.write)\n self.assertEqual(app.out.getvalue(), '')\n app.assertStatus('304 Not Modified')\n app.assertHeaders([])\n\n def test_not_found(self):\n \"\"\"\n `not_found` must send a 404 response.\n \"\"\"\n app = self.make_app()\n handler = self.make_handler({}, app.start_response)\n\n result = handler.not_found('Foo Bar!')\n\n self.assertEqual(result, app.out.write)\n self.assertEqual(app.out.getvalue(), 'Foo Bar!')\n app.assertStatus('404 Not Found')\n app.assertContentType('text/plain; encoding=UTF-8')\n app.assertCookie()\n\n def test_internal_error(self):\n \"\"\"\n `internal_error` must send a 500 response.\n \"\"\"\n app = self.make_app()\n handler = self.make_handler({}, app.start_response)\n\n result = handler.internal_error()\n\n self.assertEqual(result, app.out.write)\n self.assertEqual(app.out.getvalue(), '')\n app.assertStatus('500 Internal Server Error')\n","sub_path":"tests/test_util.py","file_name":"test_util.py","file_ext":"py","file_size_in_byte":11025,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"146625707","text":"#! /usr/bin/env python\n\ndef main():\n power = 32\n num_primes = 500\n counter = 1\n primes = list(erat(power))\n open('c.out', 'a').write('Case #1:\\n')\n for x in xrange(2**(power-1) + 1, 2**power, 2):\n w = get_factors(x, primes)\n if w:\n open('c.out', 'a').write('{} {}\\n'.format(bin(x)[2:], ' '.join(map(str, w))))\n if counter >= num_primes:\n return\n counter += 1\n\ndef erat(bound):\n # iterator of primes < sqrt(2**16)\n D = {}\n for q in range(2, 2**(bound/2)+1):\n p = D.get(q, None)\n if p is None:\n yield q\n D[q*q] = q\n else:\n x = p + q\n while x in D:\n x += p\n D[x] = p\n\n\ndef get_factors(x, primes):\n # if bin(x) interpreted in base 2..10 has factors, return as an array, else None.\n s = bin(x)[2:]\n array = []\n for base in range(2, 11):\n num = int(s, base)\n for p in primes:\n if num % p == 0:\n array.append(p)\n break\n else:\n return None\n return array\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"solutions_5738606668808192_1/Python/azsorkin/c.py","file_name":"c.py","file_ext":"py","file_size_in_byte":1155,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"605729402","text":"# -*- coding: utf-8 -*-\nimport os\nimport re\nimport sys\nimport time\nMaru_tool_path = \"F:\\\\Marubox\\\\tools\\\\\"\ntemp_dir = \"F:\\\\Marubox\\\\\"\nmkv_list = []\nsub_list = []\nexecute_time = str(time.time())\nexecute_tag = \"\"\nbat_obj=open(temp_dir+\"Batch_\"+execute_time+\".bat\",'w')\ndef main():\n global bat_obj\n if len(sys.argv)==1:\n input_err(\"No file was input.\")\n for path_in in sys.argv[1:]:\n if os.path.exists(path_in)==False:\n input_err(\"Invalid input.\")\n elif os.path.isdir(path_in):\n BatchProcess(path_in)\n elif os.path.isfile(path_in):\n MakeCompressedMixMKV(path_in)\n bat_obj.close()\n return\ndef file_dir(source_path):\n return os.path.dirname(source_path)\ndef file_extension(source_path):\n return source_path.split(\".\")[-1]\ndef extless_file_name(source_path):\n return os.path.basename(source_path).split(\".\")[0]\ndef find_sub(source_path):\n puredir = file_dir(source_path)\n sub_str_tmp = \"\"\n for dirpath,dirnames,filenames in os.walk(puredir):\n for file in filenames:\n if file_extension(file)==\"ass\":\n fullpath=os.path.join(dirpath,file)\n if extless_file_name(source_path) in fullpath:\n sub_str_tmp+=(\" \\\"\"+fullpath+\"\\\"\")\n return sub_str_tmp\ndef BatchProcess(source_dir):\n global bat_obj,execute_time\n bat_obj.close()\n execute_tag = os.path.basename(source_dir)\n bat_obj=open(temp_dir+\"Batch_\"+execute_tag+\".bat\",'w')\n for dirpath,dirnames,filenames in os.walk(source_dir):\n for file in filenames:\n if file_extension(file)==\"mkv\":\n if \"Merged\" in dirpath:\n break\n elif \"NCOP\" in file:\n break\n elif \"NCED\" in file:\n break\n elif \"PV\" in file:\n break\n fullpath=os.path.join(dirpath,file)\n MakeCompressedMixMKV(fullpath)\n return\ndef MakeCompressedMixMKV(source_path):\n purename = extless_file_name(source_path)\n outdir = os.path.join(file_dir(source_path),\"Merged\")\n SUB_FILES=find_sub(source_path)\n cmd_list=[\"\\\"\"+Maru_tool_path+\"ffmpeg.exe\\\" -i \\\"\"+source_path+\"\\\" -vn -sn -v 0 -c:a pcm_s16le -f wav pipe:|\\\"\"+Maru_tool_path+\"neroAacEnc.exe\\\" -ignorelength -lc -br 128000 -if - -of \\\"\"+temp_dir+purename+\"_atemp.mp4\\\"\\n\",\n \"\\\"\"+Maru_tool_path+\"x264_64-8bit.exe\\\" --crf 23.5 --preset 8 -I 240 -r 4 -b 3 --me umh -i 1 --scenecut 60 -f 1:1 --qcomp 0.5 --psy-rd 0.3:0 --aq-mode 2 --aq-strength 0.8 -o \\\"\"+temp_dir+\"\\\\\"+purename+\"_vtemp.mp4\\\" \\\"\"+source_path+\"\\\"\\n\",\n \"\\\"\"+Maru_tool_path+\"mp4box.exe\\\" -add \\\"\"+temp_dir+purename+\"_vtemp.mp4#trackID=1:name=\\\" -add \\\"\"+temp_dir+purename+\"_atemp.mp4#trackID=1:name=\\\" -new \\\"\"+temp_dir+purename+\".mp4\\\"\\n\",\n \"del \\\"\"+temp_dir+purename+\"_atemp.mp4\\\"\\n\",\n \"del \\\"\"+temp_dir+purename+\"_vtemp.mp4\\\"\\n\",\n \"\\\"\"+Maru_tool_path+\"mkvextract.exe\\\" chapters \\\"\"+source_path+\"\\\">\\\"\"+temp_dir+\"temp.xml\\\"\\n\",\n \"\\\"\"+Maru_tool_path+\"mkvmerge.exe\\\" -o \\\"\"+outdir+\"\\\\\"+purename+\".mkv\\\" \"+\"--chapters \"+\"\\\"\"+temp_dir+\"temp.xml\\\"\"+SUB_FILES+\" \"+\"\\\"\"+temp_dir+purename+\".mp4\\\"\\n\",\n \"del \\\"\"+temp_dir+purename+\".mp4\\\"\\n\"]\n print(cmd_list)\n global bat_obj\n bat_obj.writelines(cmd_list)\n return\ndef input_err(flag):\n print(flag)\n global bat_obj\n bat_obj.close()\n exit();\n return\nif __name__ == \"__main__\":\n main()\n","sub_path":"AnimeCompressor/AnimeCompressor.py","file_name":"AnimeCompressor.py","file_ext":"py","file_size_in_byte":3542,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"616860311","text":"# eval.py\n\n\"\"\"\n- Author: tamnv\n- Description: Evaluate pretrained model independently. Note:\nwe must have pretrained model before.\n\nUsage: python eval.py --model [path/to/model/directory]\n--data-dir [path/to/data/directory]\n\"\"\"\n\nimport argparse\nfrom sys import argv\nimport pickle as pkl\n\nimport numpy as np\nimport matplotlib\nmatplotlib.use('agg')\nimport matplotlib.pyplot as plt\n\nimport keras\nfrom keras.models import model_from_json\nimport ember\nfrom util import get_paths\nfrom sklearn.metrics import roc_curve, auc\n\n\ndef parse_arguments(argv):\n \"\"\"Parse command line arguments.\"\"\"\n parser = argparse.ArgumentParser(prog='MalNet')\n parser.add_argument('--data-dir', dest='data_dir', type=str, default='data',\n help='Path to data directory contains test dataset.')\n parser.add_argument('--model', dest='model_dir', type=str,\n help='Path to model directory.')\n parser.add_argument('--scale', dest='scale', type=float, default=1.,\n help='Scale of training/test dataset.')\n return parser.parse_args(argv)\n\n\n# Parse arguments\nargs = parse_arguments(argv[1:])\n\n# Generate dummy data\nprint('Loading data...')\ndata_dir = args.data_dir\n_, _, X_test, y_test = ember.read_vectorized_features(data_dir, scale=args.scale)\nX_test = np.array(X_test)\n\nX_test = X_test[y_test != -1]\ny_test = y_test[y_test != -1]\n\nmodel_dir = args.model_dir\npath_dict = get_paths(model_dir)\njson_file = open(path_dict['graph'], 'r')\nloaded_model_json = json_file.read()\njson_file.close()\nmodel = model_from_json(loaded_model_json)\nmodel.load_weights(path_dict['model'])\nwith open(path_dict['scaler'], 'rb') as f:\n scaler = pkl.load(f)\n\nX_test = scaler.transform(X_test)\nX_test = np.expand_dims(X_test, axis=-1)\ny_test = keras.utils.to_categorical(y_test, num_classes=2)\n\n# ROC curve\ny_pred = model.predict(X_test)\nfpr, tpr, thresholds = roc_curve(np.argmax(y_test, axis=1), y_pred[:, 1], pos_label=1)\nacc = np.mean(np.equal(np.argmax(y_test, axis=1), np.argmax(y_pred, axis=1)))\n\n# Summary result\nprint('Model directory: %s' % args.model_dir)\nprint('Accuracy: %.4f' % (acc))\nprint('AUC: %.4f' % (auc(fpr, tpr)))\nprint('')\nplt.plot(fpr, tpr)\n\nplt.xlim([-0.1, 1.05])\nplt.ylim([-0.1, 1.05])\nplt.xlabel('False Positive Rate')\nplt.ylabel('True Positive Rate')\nplt.legend('MalNet', loc='lower right')\nplt.title('ROC curve of MalNet')\nplt.plot([0, 1], [0, 1], color='navy', lw=2, linestyle='--')\nplt.show()\nplt.close()\n","sub_path":"src/eval.py","file_name":"eval.py","file_ext":"py","file_size_in_byte":2469,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"450425080","text":"from django import forms\n\n\nclass OrderCreateForm(forms.Form):\n first_name = forms.CharField(max_length=50)\n last_name = forms.CharField(max_length=50)\n email = forms.EmailField()\n phone = forms.CharField(max_length=15)\n address = forms.CharField(max_length=100)\n\n def __init__(self, *args, authorized=False, **kwargs):\n super(OrderCreateForm, self).__init__(*args, **kwargs)\n self.user_authorized = False\n if authorized:\n self.user_authorized = authorized\n self.user_authenticated()\n\n def user_authenticated(self):\n unauthorized_fields = ['first_name', 'last_name', 'email']\n for field in unauthorized_fields:\n self.fields[field].widget = forms.HiddenInput()\n self.fields[field].required = False\n\n def user_data(self):\n fields = ['phone', 'address']\n data = {}\n for field in fields:\n data[field] = self.data[field]\n return data\n\n def is_valid(self):\n if not self.user_authorized:\n valid = super(OrderCreateForm, self).is_valid()\n return valid\n else:\n if (self.data['address'] and self.data['phone']) is not None:\n return True\n return False\n","sub_path":"orders/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":1258,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"27221576","text":"import csv\nimport numpy as np\n\ndef get_iter_nasdaq_csv():\n # Create iterator to read CSV file\n with open('nasdaq_companies.csv') as csvfile:\n datareader = csv.reader(csvfile)\n for row in datareader: \n # Criteria 1: Filter out listings without market cap data\n if row[3] != 'n/a':\n yield row\n\ndef get_info_nasdaq_csv():\n # Collect info with iterator\n SYMBOL, MARKET_CAP, SECTOR, INDUSTRY = [], [], [], []\n for row in get_iter_nasdaq_csv():\n symbol,_,_, market_cap, _,sector, industry,_,_ = row\n SYMBOL.append(symbol.strip())\n MARKET_CAP.append(market_cap)\n SECTOR.append(sector)\n INDUSTRY.append(industry)\n\n # Remove dollar signs and replace M (million), B (billion) with numbers\n de = {'M': 'e6', 'B': 'e9'}\n for i,x in enumerate(MARKET_CAP[1:]):\n temp = x.replace('$','')\n if temp[-1] in de:\n temp = temp.replace(temp[-1], de[temp[-1]])\n MARKET_CAP[i+1] = (float(temp))\n return SYMBOL, MARKET_CAP, SECTOR, INDUSTRY\n\n\n","sub_path":"companies.py","file_name":"companies.py","file_ext":"py","file_size_in_byte":1063,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"276672832","text":"\n'''Import basic modules.'''\nimport pandas as pd\nimport numpy as np\nfrom scipy import stats\n\n'''Customize visualization\nSeaborn and matplotlib visualization.'''\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nsns.set_style(\"whitegrid\")\n### matplotlib inline\n\n'''Special Visualization'''\nfrom wordcloud import WordCloud \nimport missingno as msno\n\n'''Plotly visualization .'''\nimport plotly.offline as py\nfrom plotly.offline import iplot, init_notebook_mode\nimport plotly.graph_objs as go\npy.init_notebook_mode(connected = True) # Required to use plotly offline in jupyter notebook\n\nimport cufflinks as cf #importing plotly and cufflinks in offline mode \nimport plotly.offline \ncf.go_offline() \ncf.set_config_file(offline=False, world_readable=True)\n\n'''Display markdown formatted output like bold, italic bold etc.'''\nfrom IPython.display import Markdown\ndef bold(string):\n display(Markdown(string))\ndf = pd.read_csv('../input/netflix-shows/netflix_titles_nov_2019.csv')\ndf[\"date_added\"] = pd.to_datetime(df['date_added'])\ndf['year_added'] = df['date_added'].dt.year\ndf['month_added'] = df['date_added'].dt.month\n\ndf['season_count'] = df.apply(lambda x : x['duration'].split(\" \")[0] if \"Season\" in x['duration'] else \"\", axis = 1)\ndf['duration'] = df.apply(lambda x : x['duration'].split(\" \")[0] if \"Season\" not in x['duration'] else \"\", axis = 1)\ndf.head()\n'''A Function To Plot Pie Plot using Plotly'''\n\ndef pie_plot(cnt_srs, colors, title):\n labels=cnt_srs.index\n values=cnt_srs.values\n trace = go.Pie(labels=labels, \n values=values, \n title=title, \n hoverinfo='percent+value', \n textinfo='percent',\n textposition='inside',\n hole=0.7,\n showlegend=True,\n marker=dict(colors=colors,\n line=dict(color='#000000',\n width=2),\n )\n )\n return trace\n\nbold(\"**NETFLIX HAVE MORE MOVIES THAN TV SHOWS**\")\npy.iplot([pie_plot(df['type'].value_counts(), ['cyan', 'gold'], 'Content Type')])\nd1 = df[df[\"type\"] == \"TV Show\"]\nd2 = df[df[\"type\"] == \"Movie\"]\n\ncol = \"year_added\"\n\nvc1 = d1[col].value_counts().reset_index()\nvc1 = vc1.rename(columns = {col : \"count\", \"index\" : col})\nvc1['percent'] = vc1['count'].apply(lambda x : 100*x/sum(vc1['count']))\nvc1 = vc1.sort_values(col)\n\nvc2 = d2[col].value_counts().reset_index()\nvc2 = vc2.rename(columns = {col : \"count\", \"index\" : col})\nvc2['percent'] = vc2['count'].apply(lambda x : 100*x/sum(vc2['count']))\nvc2 = vc2.sort_values(col)\n\ntrace1 = go.Scatter(\n x=vc1[col], \n y=vc1[\"count\"], \n name=\"TV Shows\", \n marker=dict(color = 'rgb(249, 6, 6)',\n line=dict(color='rgb(0,0,0)',width=1.5)))\n\ntrace2 = go.Scatter(\n x=vc2[col], \n y=vc2[\"count\"], \n name=\"Movies\", \n marker= dict(color = 'rgb(26, 118, 255)',\n line=dict(color='rgb(0,0,0)',width=1.5)))\nlayout = go.Layout(hovermode= 'closest', title = 'Content added over the years' , xaxis = dict(title = 'Year'), yaxis = dict(title = 'Count'),template= \"plotly_dark\")\nfig = go.Figure(data = [trace1, trace2], layout=layout)\nfig.show()\ntemp_df = df['rating'].value_counts().reset_index()\n\n\n# create trace1\ntrace1 = go.Bar(\n x = temp_df['index'],\n y = temp_df['rating'],\n marker = dict(color = 'rgb(255,165,0)',\n line=dict(color='rgb(0,0,0)',width=1.5)))\nlayout = go.Layout(template= \"plotly_dark\",title = 'MOST OF PROGRAMME ON NEYFLIX IS TV-14 & TV-MA RATED' , xaxis = dict(title = 'Rating'), yaxis = dict(title = 'Count'))\nfig = go.Figure(data = [trace1], layout = layout)\nfig.show()\n\ndef pie_plot(cnt_srs, title):\n labels=cnt_srs.index\n values=cnt_srs.values\n trace = go.Pie(labels=labels, \n values=values, \n title=title, \n hoverinfo='percent+value', \n textinfo='percent',\n textposition='inside',\n hole=0.7,\n showlegend=True,\n marker=dict(colors=plt.cm.viridis_r(np.linspace(0, 1, 14)),\n line=dict(color='#000000',\n width=2),\n )\n )\n return trace\n\npy.iplot([pie_plot(df['rating'].value_counts(), 'Content Type')])\ndf1 = df[df[\"type\"] == \"TV Show\"]\ndf2 = df[df[\"type\"] == \"Movie\"]\n\ntemp_df1 = df1['rating'].value_counts().reset_index()\ntemp_df2 = df2['rating'].value_counts().reset_index()\n\n\n# create trace1\ntrace1 = go.Bar(\n x = temp_df1['index'],\n y = temp_df1['rating'],\n name=\"TV Shows\",\n marker = dict(color = 'rgb(249, 6, 6)',\n line=dict(color='rgb(0,0,0)',width=1.5)))\n# create trace2 \ntrace2 = go.Bar(\n x = temp_df2['index'],\n y = temp_df2['rating'],\n name = \"Movies\",\n marker = dict(color = 'rgb(26, 118, 255)',\n line=dict(color='rgb(0,0,0)',width=1.5)))\n\n\nlayout = go.Layout(template= \"plotly_dark\",title = 'RATING BY CONTENT TYPE' , xaxis = dict(title = 'Rating'), yaxis = dict(title = 'Count'))\nfig = go.Figure(data = [trace1, trace2], layout = layout)\nfig.show()\nbold('**MOST POPULAR GENRES ON NETFILX ARE:**')\nbold('**DOCUMENTARIES,COMEDIES, DRAMAS, INTERNATIONAL, ACTION**')\nimport squarify\ndf['Genres'] = df['listed_in'].str.extract('([A-Z]\\w{2,})', expand=True)\ntemp_df = df['Genres'].value_counts().reset_index()\n\nsizes=np.array(temp_df['Genres'])\nlabels=temp_df['index']\ncolors = [plt.cm.Paired(i/float(len(labels))) for i in range(len(labels))]\nplt.figure(figsize=(12,8), dpi= 100)\nsquarify.plot(sizes=sizes, label=labels, color = colors, alpha=.5, edgecolor=\"black\", linewidth=3, text_kwargs={'fontsize':15})\nplt.title('Treemap of Genres of Netflix Show', fontsize = 15)\nplt.axis('off')\nplt.show()\nbold('**HEATMAP(Correlation)**')\nfrom sklearn.preprocessing import MultiLabelBinarizer # Similar to One-Hot Encoding\n\ndata= df['listed_in'].astype(str).apply(lambda s : s.replace('&',' ').replace(',', ' ').split()) \n\ntest = data\nmlb = MultiLabelBinarizer()\nres = pd.DataFrame(mlb.fit_transform(test), columns=mlb.classes_)\ncorr = res.corr()\nmask = np.zeros_like(corr, dtype=np.bool)\nmask[np.triu_indices_from(mask)] = True\nf, ax = plt.subplots(figsize=(35, 34))\ncmap = sns.diverging_palette(220, 10, as_cmap=True)\nsns.heatmap(corr, mask=mask, cmap=cmap, vmax=.3, center=0,square=True, linewidths=.5, cbar_kws={\"shrink\": .5})\nplt.show()\nbold('**NETWORKX (Correlation)**')\nimport networkx as nx\n\nstocks = corr.index.values\ncor_matrix = np.asmatrix(corr)\nG = nx.from_numpy_matrix(cor_matrix)\nG = nx.relabel_nodes(G,lambda x: stocks[x])\nG.edges(data=True)\n\ndef create_corr_network(G, corr_direction, min_correlation):\n H = G.copy()\n for stock1, stock2, weight in G.edges(data=True):\n if corr_direction == \"positive\":\n if weight[\"weight\"] <0 or weight[\"weight\"] < min_correlation:\n H.remove_edge(stock1, stock2)\n else:\n if weight[\"weight\"] >=0 or weight[\"weight\"] > min_correlation:\n H.remove_edge(stock1, stock2)\n \n edges,weights = zip(*nx.get_edge_attributes(H,'weight').items())\n weights = tuple([(1+abs(x))**2 for x in weights])\n d = nx.degree(H)\n nodelist, node_sizes = zip(*d)\n positions=nx.circular_layout(H)\n \n plt.figure(figsize=(10,10), dpi=72)\n \n nx.draw_networkx_nodes(H,positions,node_color='#DA70D6',nodelist=nodelist,\n node_size=tuple([x**2 for x in node_sizes]),alpha=0.8)\n \n nx.draw_networkx_labels(H, positions, font_size=8, \n font_family='sans-serif')\n \n if corr_direction == \"positive\": edge_colour = plt.cm.GnBu \n else: edge_colour = plt.cm.PuRd\n \n nx.draw_networkx_edges(H, positions, edge_list=edges,style='solid',\n width=weights, edge_color = weights, edge_cmap = edge_colour,\n edge_vmin = min(weights), edge_vmax=max(weights))\n plt.axis('off')\n plt.show() \n \ncreate_corr_network(G, 'positive', 0.3)\ncreate_corr_network(G, 'positive', -0.3)\ntemp_df1 = df['release_year'].value_counts().reset_index()\n\n\n# create trace1\ntrace1 = go.Bar(\n x = temp_df1['index'],\n y = temp_df1['release_year'],\n marker = dict(color = 'rgb(255,165,0)',\n line=dict(color='rgb(0,0,0)',width=1.5)))\nlayout = go.Layout(template= \"plotly_dark\",title = 'CONTENT RELEASE OVER THE YEAR' , xaxis = dict(title = 'Rating'), yaxis = dict(title = 'Count'))\nfig = go.Figure(data = [trace1], layout = layout)\nfig.show()\ndf1 = df[df[\"type\"] == \"TV Show\"]\ndf2 = df[df[\"type\"] == \"Movie\"]\n\ntemp_df1 = df1['release_year'].value_counts().reset_index()\ntemp_df2 = df2['release_year'].value_counts().reset_index()\n\n\n# create trace1\ntrace1 = go.Bar(\n x = temp_df1['index'],\n y = temp_df1['release_year'],\n name=\"TV Shows\",\n marker = dict(color = 'rgb(249, 6, 6)'))\n# create trace2 \ntrace2 = go.Bar(\n x = temp_df2['index'],\n y = temp_df2['release_year'],\n name = \"Movies\",\n marker = dict(color = 'rgb(26, 118, 255)'))\n\n\nlayout = go.Layout(template= \"plotly_dark\",title = 'CONTENT RELEASE OVER THE YEAR BY CONTENT TYPE' , xaxis = dict(title = 'Year'), yaxis = dict(title = 'Count'))\nfig = go.Figure(data = [trace1, trace2], layout = layout)\nfig.show()\ntrace = go.Histogram(\n x = df['duration'],\n xbins=dict(size=0.5),\n marker = dict(color = 'rgb(26, 118, 255)'))\nlayout = go.Layout(template= \"plotly_dark\", title = 'Distribution of Movies Duration', xaxis = dict(title = 'Minutes'))\nfig = go.Figure(data = [trace], layout = layout)\nfig.show()\nbold(\"**GREY'S ANATOMY AND NCIS HAVE HIGHEST NO. OF SEASON ON NETFLIX**\")\ndisplay(df[df['season_count'] == '15'][['title','director', 'cast','country','release_year']])\n\n# image\nimport urllib.request\nfrom PIL import Image\n\nplt.subplots(figsize=(30,60))\nplt.subplot(121)\nimage = Image.open(urllib.request.urlopen(url='https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQ0A6upRBYwNBw68tempa18gIxAliLNWkv60-X-fbgQ6rgQOGwC&s'))\nplt.imshow(image)\nplt.axis('off')\n\nplt.subplot(122)\nimage = Image.open(urllib.request.urlopen(url='https://i.pinimg.com/originals/58/dc/ba/58dcba558659a13a843c489fa29146f2.jpg'))\nplt.imshow(image)\nplt.axis('off')\nplt.show()\n\n# plot\ntrace = go.Histogram(\n x = df['season_count'],\n marker = dict(color = 'rgb(249, 6, 6)'))\nlayout = go.Layout(template= \"plotly_dark\", title = 'Seasons of TV Shows', xaxis = dict(title = 'No. of Seasons'))\nfig = go.Figure(data = [trace], layout = layout)\nfig.show()\nbold('**OLDEST MOVIES ON NETFLIX**')\noldest = df.sort_values(\"release_year\", ascending = True)\noldest = oldest[oldest['duration'] != \"\"]\ndisplay(oldest[['title', \"release_year\", 'listed_in','country']][:10])\n\nplt.subplots(figsize=(30,60))\nplt.subplot(121)\nimage = Image.open(urllib.request.urlopen(url='https://m.media-amazon.com/images/M/MV5BMTY3NTMyMDQ4NF5BMl5BanBnXkFtZTgwMjkzODgwMzE@._V1_QL50_.jpg'))\nplt.imshow(image)\nplt.axis('off')\n\nplt.subplot(122)\nimage = Image.open(urllib.request.urlopen(url='https://m.media-amazon.com/images/M/MV5BMTY3Njg3MDUxMl5BMl5BanBnXkFtZTcwMzE4MTU1MQ@@._V1_QL50_.jpg'))\nplt.imshow(image)\nplt.axis('off')\nplt.show()\nbold('**OLDEST TV SHOW ON NETFLIX**')\noldest = df.sort_values(\"release_year\", ascending = True)\noldest = oldest[oldest['season_count'] != \"\"]\ndisplay(oldest[['title', \"release_year\", 'listed_in','country']][:10])\n\nplt.subplots(figsize=(30,60))\nplt.subplot(121)\nimage = Image.open(urllib.request.urlopen(url='https://images-na.ssl-images-amazon.com/images/I/71ddmI5x94L._SL1500_.jpg'))\nplt.imshow(image)\nplt.axis('off')\n\nplt.subplot(122)\nimage = Image.open(urllib.request.urlopen(url='https://images-na.ssl-images-amazon.com/images/I/51KqZA%2B42OL._SY445_.jpg'))\nplt.imshow(image)\nplt.axis('off')\nplt.show()\ntemp_df = df['country'].value_counts().reset_index()[:20]\n\n\n# create trace1\ntrace1 = go.Bar(\n x = temp_df['index'],\n y = temp_df['country'],\n marker = dict(color = 'rgb(153,255,153)',\n line=dict(color='rgb(0,0,0)',width=1.5)))\nlayout = go.Layout(template= \"plotly_dark\",title = 'TOP 20 COUNTIES WITH MOST CONTENT' , xaxis = dict(title = 'Countries'), yaxis = dict(title = 'Count'))\nfig = go.Figure(data = [trace1], layout = layout)\nfig.show()\nfrom collections import Counter\n\ntemp_df = df[df['type']=='Movie']\ntemp_df = temp_df[temp_df['country']=='India']\n\ncategories = \", \".join(temp_df['director'].fillna(\"\")).split(\", \")\ncounter_list = Counter(categories).most_common(11)\ncounter_list = [_ for _ in counter_list if _[0] != \"\"]\nlabels = [_[0] for _ in counter_list][::-1]\nvalues = [_[1] for _ in counter_list][::-1]\ntrace1 = go.Bar(\n x = labels,\n y = values,\n marker = dict(color = 'rgb(51,255,255)',\n line=dict(color='rgb(0,0,0)',width=1.5)))\nlayout = go.Layout(template= \"plotly_dark\",title = 'TOP 10 MOVIES DIRECTORS FROM INDIA WITH MOST CONTENT' , xaxis = dict(title = 'Directors'), yaxis = dict(title = 'Count'))\nfig = go.Figure(data = [trace1], layout = layout)\nfig.show()\n\nplt.subplots(figsize=(30,60))\nplt.subplot(121)\nimage = Image.open(urllib.request.urlopen(url='https://upload.wikimedia.org/wikipedia/commons/7/7f/S._S._Rajamouli_at_the_trailer_launch_of_Baahubali.jpg'))\nplt.title('S.S.Rajamouli', fontsize=35)\nplt.imshow(image)\nplt.axis('off')\n\nplt.subplot(122)\nimage = Image.open(urllib.request.urlopen(url='https://i2.cinestaan.com/image-bank/640-360/45001-46000/45877.jpg'))\nplt.title('Dibakar Banerji', fontsize=35)\nplt.imshow(image)\nplt.axis('off')\nplt.show()\ntemp_df = df[df['type']=='Movie']\ntemp_df = temp_df[temp_df['country']=='United States']\n\ncategories = \", \".join(temp_df['director'].fillna(\"\")).split(\", \")\ncounter_list = Counter(categories).most_common(11)\ncounter_list = [_ for _ in counter_list if _[0] != \"\"]\nlabels = [_[0] for _ in counter_list][::-1]\nvalues = [_[1] for _ in counter_list][::-1]\ntrace1 = go.Bar(\n x = labels,\n y = values,\n marker = dict(color = 'rgb(255,51,153)',\n line=dict(color='rgb(0,0,0)',width=1.5)))\nlayout = go.Layout(template= \"plotly_dark\",title = 'TOP 10 MOVIES DIRECTORS FROM U.S. WITH MOST CONTENT' , xaxis = dict(title = 'Directors'), yaxis = dict(title = 'Count'))\nfig = go.Figure(data = [trace1], layout = layout)\nfig.show()\n\nplt.subplots(figsize=(10,20))\nplt.subplot(121)\nimage = Image.open(urllib.request.urlopen(url='http://www.gstatic.com/tv/thumb/persons/530202/530202_v9_ba.jpg'))\nplt.title('Jay Karas', fontsize=15)\nplt.imshow(image)\nplt.axis('off')\nplt.show()\ntemp_df = df[df['type']=='Movie']\ntemp_df = temp_df[temp_df['country']=='India']\n\ncategories = \", \".join(temp_df['cast'].fillna(\"\")).split(\", \")\ncounter_list = Counter(categories).most_common(11)\ncounter_list = [_ for _ in counter_list if _[0] != \"\"]\nlabels = [_[0] for _ in counter_list][::-1]\nvalues = [_[1] for _ in counter_list][::-1]\ntrace1 = go.Bar(\n x = labels,\n y = values,\n marker = dict(color = 'rgb(51,255,255)',\n line=dict(color='rgb(0,0,0)',width=1.5)))\nlayout = go.Layout(template= \"plotly_dark\",title = 'TOP 10 MOVIES ACTORS FROM INDIA WITH MOST CONTENT' , xaxis = dict(title = 'Actors'), yaxis = dict(title = 'Count'))\nfig = go.Figure(data = [trace1], layout = layout)\nfig.show()\n\nplt.subplots(figsize=(30,60))\nplt.subplot(121)\nimage = Image.open(urllib.request.urlopen(url='https://timesofindia.indiatimes.com/thumb/msid-67834646,imgsize-23733,width-800,height-600,resizemode-4/67834646.jpg'))\nplt.title('Anupam Kher', fontsize=35)\nplt.imshow(image)\nplt.axis('off')\n\nplt.subplot(122)\nimage = Image.open(urllib.request.urlopen(url='https://timesofindia.indiatimes.com/thumb/msid-69340156,width-800,height-600,resizemode-4/69340156.jpg'))\nplt.title('Shah Rukh Khan', fontsize=35)\nplt.imshow(image)\nplt.axis('off')\nplt.show()\ntemp_df = df[df['type']=='Movie']\ntemp_df = temp_df[temp_df['country']=='United States']\n\ncategories = \", \".join(temp_df['cast'].fillna(\"\")).split(\", \")\ncounter_list = Counter(categories).most_common(11)\ncounter_list = [_ for _ in counter_list if _[0] != \"\"]\nlabels = [_[0] for _ in counter_list][::-1]\nvalues = [_[1] for _ in counter_list][::-1]\ntrace1 = go.Bar(\n x = labels,\n y = values,\n marker = dict(color = 'rgb(255,51,153)',\n line=dict(color='rgb(0,0,0)',width=1.5)))\nlayout = go.Layout(template= \"plotly_dark\",title = 'TOP 10 MOVIES ACTORS FROM U.S. WITH MOST CONTENT' , xaxis = dict(title = 'Actors'), yaxis = dict(title = 'Count'))\nfig = go.Figure(data = [trace1], layout = layout)\nfig.show()\n\nplt.subplots(figsize=(20,40))\nplt.subplot(121)\nimage = Image.open(urllib.request.urlopen(url='https://m.media-amazon.com/images/M/MV5BNTg0YTkxNGEtNjM2YS00NzYwLWIwMDktYmMzMzE0NTRiZDQwXkEyXkFqcGdeQXVyMjQwMDg0Ng@@._V1_.jpg'))\nplt.title('Luara Bailey', fontsize=35)\nplt.imshow(image)\nplt.axis('off')\n\nplt.subplot(122)\nimage = Image.open(urllib.request.urlopen(url='https://cdn.britannica.com/24/157824-050-D8E9E191/Adam-Sandler-2011.jpg'))\nplt.title('Adam Sandler', fontsize=35)\nplt.imshow(image)\nplt.axis('off')\nplt.show()\ntemp_df1 = df[df['type']=='TV Show']\ntemp_df1 = temp_df1[temp_df1['country']=='United States']\ncategories1 = \", \".join(temp_df1['director'].fillna(\"\")).split(\", \")\ncounter_list1 = Counter(categories1).most_common(11)\ncounter_list1 = [_ for _ in counter_list1 if _[0] != \"\"]\nlabels1 = [_[0] for _ in counter_list1][::-1]\nvalues1 = [_[1] for _ in counter_list1][::-1]\n\ntemp_df2 = df[df['type']=='TV Show']\ntemp_df2 = temp_df2[temp_df2['country']=='India']\ncategories2 = \", \".join(temp_df2['director'].fillna(\"\")).split(\", \")\ncounter_list2 = Counter(categories2).most_common(11)\ncounter_list2 = [_ for _ in counter_list2 if _[0] != \"\"]\nlabels2 = [_[0] for _ in counter_list2][::-1]\nvalues2 = [_[1] for _ in counter_list2][::-1]\n\nfrom plotly.subplots import make_subplots\n\nfig = make_subplots(rows=1, cols=2,subplot_titles=(\"United States\", \"India\"))\n\ntrace1 = go.Bar(\n x = labels1,\n y = values1,\n marker = dict(color = 'rgb(255,51,153)',\n line=dict(color='rgb(0,0,0)',width=1.5))\n )\n\ntrace2 = go.Bar(\n x = labels2,\n y = values2,\n marker = dict(color = 'rgb(51,255,255)',\n line=dict(color='rgb(0,0,0)',width=1.5))\n \n )\n\nfig.append_trace(trace1, 1, 1)\nfig.append_trace(trace2, 1, 2)\nfig.update_layout(height=600, width=600,template= \"plotly_dark\",title_text = 'TOP 10 TV SHOW DIRECTORS MOST CONTENT')\nfig.show()\ntemp_df1 = df[df['type']=='TV Show']\ntemp_df1 = temp_df1[temp_df1['country']=='United States']\ncategories1 = \", \".join(temp_df1['cast'].fillna(\"\")).split(\", \")\ncounter_list1 = Counter(categories1).most_common(11)\ncounter_list1 = [_ for _ in counter_list1 if _[0] != \"\"]\nlabels1 = [_[0] for _ in counter_list1][::-1]\nvalues1 = [_[1] for _ in counter_list1][::-1]\n\ntemp_df2 = df[df['type']=='TV Show']\ntemp_df2 = temp_df2[temp_df2['country']=='India']\ncategories2 = \", \".join(temp_df2['cast'].fillna(\"\")).split(\", \")\ncounter_list2 = Counter(categories2).most_common(11)\ncounter_list2 = [_ for _ in counter_list2 if _[0] != \"\"]\nlabels2 = [_[0] for _ in counter_list2][::-1]\nvalues2 = [_[1] for _ in counter_list2][::-1]\n\nfrom plotly.subplots import make_subplots\n\nfig = make_subplots(rows=1, cols=2,subplot_titles=(\"United States\", \"India\"))\n\ntrace1 = go.Bar(\n x = labels1,\n y = values1,\n marker = dict(color = 'rgb(255,51,153)',\n line=dict(color='rgb(0,0,0)',width=1.5))\n )\ntrace2 = go.Bar(\n x = labels2,\n y = values2,\n marker = dict(color = 'rgb(51,255,255)',\n line=dict(color='rgb(0,0,0)',width=1.5))\n \n )\n\nfig.append_trace(trace1, 1, 1)\nfig.append_trace(trace2, 1, 2)\nfig.update_layout(height=600, width=600,template= \"plotly_dark\",title_text = 'TOP 10 TV SHOW ACTORS MOST CONTENT')\nfig.show()\n\n","sub_path":"sources/netflix-movies-and-tv-shows-feat-plotly.py","file_name":"netflix-movies-and-tv-shows-feat-plotly.py","file_ext":"py","file_size_in_byte":20906,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"443338240","text":"from common import * \nimport matplotlib.pyplot as plt\nimport numpy as np \nfrom scipy import signal\nimport math\n\ndef gaussian_filter(image, sigma):\n # Given an image, apply a Gaussian filter with the input kernel size\n # and standard deviation \n # Input- image: image of size HxW\n # sigma: scalar standard deviation of Gaussian Kernel\n # Output- Gaussian filtered image of size HxW\n image = image*1.0\n H, W = image.shape\n # -- good heuristic way of setting kernel size \n kernel_size = int(2 * np.ceil(2*sigma) + 1)\n\n # make sure that kernel size isn't too big and is odd \n kernel_size = min(kernel_size, min(H,W)//2) \n if kernel_size % 2 == 0: kernel_size = kernel_size + 1 \n\n #TODO implement gaussian filtering with size kernel_size x kernel_size \n # feel free to use your implemented convolution function or a convolution function from a library \n kernel = np.zeros((kernel_size,kernel_size))\n for i in range(-int(kernel_size/2),int(kernel_size/2)):\n \tfor j in range(-int(kernel_size/2),int(kernel_size/2)):\n \t\tkernel[j][i] = (1/(2*math.pi*sigma*sigma))*np.exp(-(i**2+j**2)/(2*sigma*sigma))\n\n kernel = kernel*1.0\n # kernel = kernel/np.sum(kernel)\n output = signal.convolve2d(image, kernel, boundary='symm', mode='same')\t\n\n\n return output \n\ndef scale_space(image, min_sigma, k=np.sqrt(2), S=8):\n # Calcualtes a DoG scale space of the image\n # Input- image: image of size HxW\n # min_sigma: smallest sigma in scale space\n # k: scalar multiplier for scale space\n # S: number of scales considers\n # Output- Scale Space of size HxWx(S-1)\n\n image_shape = np.shape(image)\n output = np.zeros((image_shape[0],image_shape[1],S-1))\n\n for i in range(S-1):\n \tgauss_2 = gaussian_filter(image,min_sigma*k**(i+1))\n \tgauss_1 = gaussian_filter(image,min_sigma*k**(i))\n\n \toutput[:,:,i] = gauss_2-gauss_1\n\n return output\n\n\n##### You shouldn't need to edit the following 3 functions \ndef find_maxima(scale_space, k_xy=5, k_s=1):\n # Extract the peak x,y locations from scale space\n # Input- scale_space: Scale space of size HxWxS\n # k: neighborhood in x and y \n # ks: neighborhood in scale\n # Output- list of (x,y) tuples; x neighbors) == num_neighbors:\n maxima.append( (i,j,s) )\n return maxima\n\ndef visualize_scale_space(scale_space, min_sigma, k, file_path=None):\n # Visualizes the scale space\n # Input- scale_space: scale space of size HxWxS\n # min_sigma: the minimum sigma used \n # k: the sigma multiplier \n if len(scale_space.shape) == 2:\n scale_space = scale_space[:, :, None] \n H, W, S = scale_space.shape\n\n # number of subplots\n p_h = int(np.floor(np.sqrt(S))) \n p_w = int(np.ceil(S/p_h))\n for i in range(S):\n plt.subplot(p_h, p_w, i+1)\n plt.axis('off')\n plt.title('{:.1f}:{:.1f}'.format(min_sigma * k**i, min_sigma * k**(i+1)))\n plt.imshow(scale_space[:, :, i])\n\n # plot or save to fig \n if file_path:\n plt.savefig(file_path)\n else:\n plt.show() \n\ndef visualize_maxima(image, maxima, min_sigma, k, file_path=None):\n # Visualizes the maxima on a given image\n # Input- image: image of size HxW\n # maxima: list of (x,y) tuples; x= 0 and y >= 0\n radius = np.sqrt(2 * min_sigma * (k ** s))\n circ = plt.Circle((x, y), radius, color='r', fill=False)\n ax.add_patch(circ)\n\n if file_path:\n plt.savefig(file_path)\n else:\n plt.show() \n\n\ndef main():\n image = read_img('polka.png')\n image = image*1.0\n\n ### -- Detecting Polka Dots -- ## \n print(\"Detect small polka dots\")\n # -- Detect Small Circles\n sigma_1, sigma_2 = 8, 12\n gauss_1 = gaussian_filter(image,sigma_1)\n gauss_2 = gaussian_filter(image,sigma_2)\n\n # calculate difference of gaussians\n DoG_small = gauss_2-gauss_1\n\n # visualize maxima \n maxima = find_maxima(DoG_small, k_xy=int(sigma_1))\n visualize_scale_space(DoG_small, sigma_1, sigma_2/sigma_1,'polka_small_DoG.png')\n visualize_maxima(image, maxima, sigma_1, sigma_2/sigma_1, 'polka_small.png')\n \n # -- Detect Large Circles\n print(\"Detect large polka dots\")\n # sigma_1, sigma_2 = 45, 50\n sigma_1, sigma_2 = 55, 58\n gauss_1 = gaussian_filter(image,sigma_1)\n gauss_2 = gaussian_filter(image,sigma_2)\n\n # calculate difference of gaussians \n DoG_large = gauss_2 - gauss_1\n \n # visualize maxima \n # Value of k_xy is a sugguestion; feel free to change it as you wish.\n maxima = find_maxima(DoG_large, k_xy=10)\n visualize_scale_space(DoG_large, sigma_1, sigma_2/sigma_1, 'polka_large_DoG.png')\n visualize_maxima(image, maxima, sigma_1, sigma_2/sigma_1, 'polka_large.png')\n\n\n ## -- TODO Implement scale_space() and try to find both polka dots \n\n min_sig = 6\n k = 1.44\n spaces=scale_space(image,min_sig,k,8)\n maxima = find_maxima(spaces, k_xy=13,k_s=3)\n visualize_scale_space(spaces, min_sig, k, 'polka_scale_space.png')\n visualize_maxima(image, maxima, min_sig, k, 'polka_small2large.png')\n\n ## -- TODO Try to find the cells in any of the cell images in vgg_cells \n\n image = read_img('cells/001cell.png')\n\n image = -1.0*image\n min_sig = 2.3\n k = 1.12\n spaces=scale_space(image,min_sig,k,8)\n maxima = find_maxima(spaces, k_xy=17,k_s=5)\n visualize_scale_space(spaces, min_sig, k, 'cell_scale_space.png')\n visualize_maxima(image, maxima, min_sig, k, 'cell_number.png')\n print(len(maxima))\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"hw2_submission/unghee/hw2_files/blob_detection.py","file_name":"blob_detection.py","file_ext":"py","file_size_in_byte":6656,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"244864096","text":"# Submitter: kfarsany(Farsany, Kian)\n\nimport re, traceback, keyword\n\ndef pnamedtuple(type_name, field_names, mutable=False):\n def show_listing(s):\n for aline,its_text in enumerate(s.split('\\n'), 1):\n print(f' {aline: >3} {its_text.rstrip()}')\n\n # put your code here\n legal_name = re.compile('^[a-zA-Z]\\w*$')\n if type_name in keyword.kwlist:\n raise SyntaxError('Class name cannot be Python keyword')\n if type(type_name) is not str or re.match(legal_name, type_name) == None:\n raise SyntaxError('Class name does not match proper format')\n \n def unique(iterable):\n iterated = set()\n for i in iterable:\n if i not in iterated:\n iterated.add(i)\n yield i\n \n if type(field_names) not in {str, list}:\n raise SyntaxError('field names must be placed in str or list')\n if type(field_names) is str:\n field_names = field_names.replace(',', ' ').strip().split()\n filtered_fields = []\n for name in unique(field_names):\n if name in keyword.kwlist:\n raise SyntaxError(f'{name} cannot be Python keyword')\n if re.match(legal_name, name) == None:\n raise SyntaxError(f'{name} does not match proper format')\n filtered_fields.append(name)\n field_names = filtered_fields\n\n def gen_init(fields: [str]) -> str:\n result = \"def __init__(self\"\n for field in fields:\n result += f', {field}'\n result += '):\\n '\n for field in fields:\n result += f'self.{field} = {field}\\n '\n result += f'self._fields = {fields}\\n '\n result += f'self._mutable = {mutable}\\n'\n return result\n \n def gen_repr(fields: [str]) -> str:\n result = \"def __repr__(self):\\n \"\n result += f\"return '{type_name}(\"\n result += ','.join([field+'={'+field+'}' for field in fields]) + \")'.format(\"\n result += ','.join([f'{field}=self.{field}' for field in fields]) + ')\\n'\n return result\n \n def gen_getters(fields: [str]) -> str:\n result = \"\"\n for field in fields:\n result += f'def get_{field}(self):\\n '\n result += f'return self.{field}\\n\\n '\n return result[:-5]\n \n \n # bind class_definition (used below) to the string constructed for the class\n class_definition = f'''\\\nclass {type_name}:\n {gen_init(field_names)}\n \n {gen_repr(field_names)}\n \n {gen_getters(field_names)}\n \n def __getitem__(self, value):\n if type(value) is int:\n if value >= len(self._fields):\n raise IndexError\n return eval('self.get_' + self._fields[value] + '()')\n elif type(value) is str:\n if value not in self._fields:\n raise IndexError\n return eval('self.get_' + value + '()')\n raise IndexError\n \n def __eq__(self, i):\n if type(i) == type(self) and i._fields == self._fields:\n for x in range(len(i._fields)):\n if self.__getitem__(x) != i.__getitem__(x):\n return False\n return True\n return False\n \n def _replace(self, **kargs):\n for k in kargs:\n if k not in self._fields:\n raise TypeError\n if self._mutable:\n for k,v in kargs.items():\n self.__dict__[k] = v\n return None\n else:\n result = dict()\n for field in self._fields:\n if field in kargs:\n result[field] = kargs[field]\n else:\n result[field] = eval('self.get_' + field + '()')\n return {type_name}(**result)'''\n \n \n\n # For initial debugging, remove comment to show the source code for the clas\n # show_listing(class_definition)\n \n # Execute the class_definition string in a local name space; later, bind the\n # source_code name in its dictionary to the class_defintion; return the\n # class object created; if there is a syntax error, list the class and\n # also show the error\n name_space = dict(__name__ = f'pnamedtuple_{type_name}')\n try:\n exec(class_definition,name_space)\n name_space[type_name].source_code = class_definition\n except [TypeError, SyntaxError]:\n show_listing(class_definition)\n traceback.print_exc()\n return name_space[type_name]\n\n\n \nif __name__ == '__main__':\n # Test pnamedtuple in script below using Point = pnamedtuple('Point', 'x y')\n\n #driver tests\n import driver\n driver.default_file_name = 'bscp3W18.txt'\n# driver.default_show_exception= True\n# driver.default_show_exception_message= True\n# driver.default_show_traceback= True\n driver.driver()\n","sub_path":"ICS_33/pnamedtuple/pcollections.py","file_name":"pcollections.py","file_ext":"py","file_size_in_byte":4820,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"465948663","text":"import os\n\nfrom geopy.geocoders import GoogleV3\n\n\ndef get_location(latitude, longitude):\n\n geolocator = GoogleV3(api_key=os.environ.get(\"GOOGLE_API_KEY\"))\n\n location = geolocator.reverse(\"{latitude}, {longitude}\".format(\n latitude=latitude,\n longitude=longitude,\n ))\n\n address = location[0].address\n address_list = address.split(\",\")\n country = address_list[-1]\n city = address_list[-2]\n\n result = {\n \"country\": country,\n \"city\": city,\n }\n\n return result\n","sub_path":"airmap/travels/utils/location.py","file_name":"location.py","file_ext":"py","file_size_in_byte":513,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"173026073","text":"#!/usr/local/bin/python3\n# -*- coding: utf-8 -*-\nfrom typing import List\n\n\nclass Solution:\n def kConcatenationMaxSum(self, arr: List[int], k: int) -> int:\n nums = [i for i in arr if i <= 0]\n sum_ = sum(arr)\n if not nums:\n return sum_ % (10 ** 9 + 7) * k\n if len(nums) == len(arr):\n return 0\n if k == 1:\n nums = arr\n else:\n nums = arr + arr\n\n res = 0\n maxn = 0\n for i in nums:\n maxn = max(maxn + i, i)\n res = max(res, maxn)\n res %= (10 ** 9 + 7)\n if k <= 2 or sum_ < 0:\n return res\n tmp1, tmp2 = 0, 0\n max1, max2 = 0, 0\n for i in arr:\n tmp1 += i\n max1 = max(max1, tmp1)\n for i in arr[::-1]:\n tmp2 += i\n max2 = max(max2, tmp2)\n return max(res, (sum_ * (k - 2) + max1 + max2) % (10 ** 9 + 7))\n\n\n\n\n\n\ns = Solution()\nprint(s.kConcatenationMaxSum(arr = [1,2], k = 3))\nprint(s.kConcatenationMaxSum(arr = [1,-2,1], k = 5))\nprint(s.kConcatenationMaxSum(arr = [-1,-2], k = 7))\nprint(s.kConcatenationMaxSum([-5,-2,0,0,3,9,-2,-5,4], 5))\n","sub_path":"1191.py","file_name":"1191.py","file_ext":"py","file_size_in_byte":1160,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"539733405","text":"# -*- coding: utf-8 -*-\n\n# Copyright 2015 Mirantis, Inc.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\"); you may\n# not use this file except in compliance with the License. You may obtain\n# a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS, WITHOUT\n# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the\n# License for the specific language governing permissions and limitations\n# under the License.\n\nimport functools\nimport logging\nimport os\nimport re\n\nfrom io import open\n\nfrom fuel_upgrade.engines.docker_engine import DockerUpgrader\nfrom fuel_upgrade.engines.host_system import HostSystemUpgrader\nfrom fuel_upgrade.pre_upgrade_hooks.base import PreUpgradeHookBase\n\nfrom fuel_upgrade import utils\n\n\nlogger = logging.getLogger(__name__)\n\n\nclass SetFixedVersionInSupervisor(PreUpgradeHookBase):\n \"\"\"Set fixed version in containers' supervisor configs.\n\n Currently, containers' supervisor configs don't have the Fuel version\n in the command line. It means that when supervisor tries to start a\n container its version retrieved on fly from the '/etc/fuel/version.yaml'.\n Since Fuel 6.1, the '/etc/fuel/version.yaml` has to be new, because\n otherwise the 'host-upgrade.pp' will use incorrect current version.\n Unfortunately, if '/etc/fuel/version.yaml' is new and the puppet\n upgrades Docker package, the Docker containers will be stopped and\n they won't up again because 'detecting container version on fly' will\n give us wrong result (e.g. 6.1 instead of 6.0). So, the only thing\n we can do is to set fixed container version in supervisor's configs,\n so it won't rely on current state of '/etc/fuel/version.yaml'.\n \"\"\"\n\n #: this hook is required only for docker upgrade engine\n enable_for_engines = [HostSystemUpgrader, DockerUpgrader]\n\n #: a list of containers for which we have to change supervisor configs.\n #: please note, it's better to have an explicit list, because user\n #: may have custom supervisor confs and we don't want to touch them.\n _containers = [\n 'astute',\n 'cobbler',\n 'keystone',\n 'mcollective',\n 'nailgun',\n 'nginx',\n 'ostf',\n 'postgres',\n 'rabbitmq',\n 'rsync',\n 'rsyslog',\n ]\n\n def __init__(self, *args, **kwargs):\n super(SetFixedVersionInSupervisor, self).__init__(*args, **kwargs)\n\n #: a function that recieves input text, replace command string\n #: and returns result\n self._replace = functools.partial(\n re.compile(r'command=dockerctl start (\\w+) --attach').sub,\n r'command=docker start -a fuel-core-{version}-\\1'.format(\n version=self.config.from_version))\n\n def _set_version_in(self, confname):\n with open(confname, 'rt', encoding='utf-8') as f:\n data = self._replace(f.read())\n\n with open(confname, 'wt', encoding='utf-8') as f:\n f.write(data)\n\n def check_if_required(self):\n # should be applied if from_version < 6.1\n return utils.compare_version(self.config.from_version, '6.1') > 0\n\n def run(self):\n for container in self._containers:\n confname = '/etc/supervisord.d/{version}/{container}.conf'.format(\n version=self.config.from_version,\n container=container)\n\n if os.path.exists(confname):\n self._set_version_in(confname)\n else:\n logger.info('Could not find supervisor conf: \"%s\"', confname)\n\n # apply updated configurations without actual restart\n utils.safe_exec_cmd('supervisorctl update')\n","sub_path":"fuel_upgrade_system/fuel_upgrade/fuel_upgrade/pre_upgrade_hooks/from_any_to_6_1_fix_version_in_supervisor.py","file_name":"from_any_to_6_1_fix_version_in_supervisor.py","file_ext":"py","file_size_in_byte":3839,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"436956877","text":"\n\nimport web\nimport web.webapi\nimport urllib.parse as parse\n\n\nclass api:\n\n #example: http://qemu/p/map/center=30.3,120.3\n my_key=\"AIzaSyAVGkcH1n7tBj9qnBlxnFSB0nhS07NXMO4\"\n def GET(self, path):\n params = {\"zoom\":14,\n \"size\":\"512x512\",\n \"key\":api.my_key}\n # \"center\":\"Berkeley,CA\"}\n base = \"https://maps.googleapis.com/maps/api/staticmap?\"\n url = base + path + \"&\" + parse.urlencode(params) \n tag = \"\"% url\n\n web.webapi.header(\"Content-type\",\"text/html\")\n return tag\n\n","sub_path":"my_app/todo/static_map.py","file_name":"static_map.py","file_ext":"py","file_size_in_byte":579,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"582314351","text":"from django.contrib import admin\n\n# Register your models here.\nfrom .models import Flowchart, Flowchartprocess\n\nclass ProcessInline(admin.StackedInline):\n model = Flowchartprocess\n extra = 3\n\n\nclass FlowchartAdmin(admin.ModelAdmin):\n fieldsets = [\n (None, {'fields': ['part_name']}),\n ('Header', {'fields': ['mold_num','cust_name'], 'classes': ['collapse']}),\n ]\n inlines = [ProcessInline]\n\nadmin.site.register(Flowchart, FlowchartAdmin)\n","sub_path":"materialprice/mysite/flowchart/admin.py","file_name":"admin.py","file_ext":"py","file_size_in_byte":481,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"253503047","text":"#coding:utf-8\n#mainWindow.py\n#http://wiki.qt.io/QtCreator_and_PySide\n\nimport sys\nfrom PySide import QtGui, QtCore\nfrom Ui_MainWindow import Ui_MainWindow\n\n\nclass Win(QtGui.QMainWindow):\n def __init__(self, parent=None):\n super(Win, self).__init__(parent)\n self.initUI()\n \n def initUI(self):\n self.ui = Ui_MainWindow()\n self.ui.setupUi(self)\n self.show()\n \n \ndef main():\n app = QtGui.QApplication(sys.argv)\n win = Win()\n sys.exit(app.exec_())\n \n \nif __name__ == '__main__':\n main()","sub_path":"PySideExercise/mainWindow.py","file_name":"mainWindow.py","file_ext":"py","file_size_in_byte":560,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"41607912","text":"import numpy as np\nimport cv2\nimport matplotlib.pyplot as plt\nblack_img=np.zeros((512,512,3))\n##variables declared here\ndrawing=False\nix,iy=-1,-1\n#function below\ndef draw_red(event,x,y,flag,param):\n global ix,iy,drawing\n if event==cv2.EVENT_LBUTTONDOWN:\n drawing=True\n ix,iy=x,y\n elif event==cv2.EVENT_MOUSEMOVE:\n if drawing==True:\n r=((x-ix)**2+(y-iy)**2)**0.5#making it calculate the readius\n cv2.circle(black_img, (ix, iy), int(r), (0, 0,255), -1)\n elif event==cv2.EVENT_LBUTTONUP:\n drawing=False\n#setting mouse callback\ncv2.namedWindow('black')\ncv2.setMouseCallback('black',draw_red)\nwhile True:\n cv2.imshow('black',black_img)\n if cv2.waitKey(20) & 0xFF==27:\n break\ncv2.destroyAllWindows()","sub_path":"drawcircle.py","file_name":"drawcircle.py","file_ext":"py","file_size_in_byte":768,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"457852715","text":"import tushare as ts\nimport aiohttp\nimport asyncio\nimport jieba\nfrom bs4 import BeautifulSoup\nimport re\nimport os\nimport traceback\nimport const\nimport async_timeout\nimport uvloop\n\nURL = \"http://vip.stock.finance.sina.com.cn/corp/go.php/vCB_Bulletin/stockid/{}/page_type/ndbg.phtml\"\n\n\ndef get_url(html):\n soup = BeautifulSoup(html, \"html.parser\")\n links = soup.select(\".datelist a\")\n if len(links) > 0:\n return \"http://vip.stock.finance.sina.com.cn%s\" % links[0].get(\"href\")\n return \"\"\n\n\nasync def handle_task(code):\n try:\n async with aiohttp.ClientSession(loop=loop) as client:\n print('begin', code)\n with async_timeout.timeout(60):\n async with client.get(URL.format(code)) as resp:\n body = await resp.text('gbk')\n print('get list', code)\n\n new_url = get_url(body)\n if len(new_url) > 0:\n with async_timeout.timeout(60):\n async with client.get(new_url) as resp:\n body = await resp.text('gbk')\n print('get body', code)\n soup = BeautifulSoup(body, \"html.parser\")\n content = soup.find(id=\"content\")\n html = content.get_text()\n with open(os.path.join(const.base_dir, code + \".txt\"), 'w+',\n encoding='utf8', newline='') as file:\n file.write(html)\n except Exception as error:\n traceback.print_exc()\n\n\nif __name__ == '__main__':\n codes = ts.get_stock_basics().index.values\n print(\"get all codes\")\n loop = uvloop.new_event_loop()\n asyncio.set_event_loop(loop)\n tasks = []\n for code in codes:\n tasks.append(handle_task(code))\n\n loop.run_until_complete(asyncio.gather(*tasks))\n loop.close()\n","sub_path":"netease/annual.py","file_name":"annual.py","file_ext":"py","file_size_in_byte":1831,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"448916004","text":"from django.http import JsonResponse\nfrom django.shortcuts import render\n\nfrom cart.models import ShoppingCart\nfrom goods.models import Goods\nfrom order.models import OrderInfo, OrderGoods\n\n\ndef order(request):\n if request.method == 'POST':\n # 1 . 从购物车中取出当前登录系统用户且is_select为1的商品信息\n user_id = request.session.get('user_id')\n carts = ShoppingCart.objects.filter(user_id=user_id,\n is_select=1\n ).all()\n order_mount = 0\n for cart in carts:\n order_mount += int(cart.nums) * int(cart.goods.shop_price)\n # 2.创建订单\n\n order = OrderInfo.objects.create(user_id=user_id,order_sn='',\n order_mount=order_mount)\n # 3.创建订单详情\n for cart in carts:\n OrderGoods.objects.create(order=order,\n goods=cart.goods,\n goods_nums=cart.nums\n )\n # 4.删除购物车中已经下单的商品信息\n carts.delete()\n return JsonResponse({'code':200, 'msg':'请求成功'})\n","sub_path":"ttsx/fresh_shop/order/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1230,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"555866094","text":"# Formats and outputs measurement data on the RS232 port\n\nfrom sl3 import *\nimport utime\nimport serial\n\n\n\ndef format_number_right_digits(value, right_digits):\n \"\"\"\n Formats the provided value with the correct number of right digits\n E.g. if value is 1.258999 and right_digits is 3, it returns \"1.259\"\n\n :param value: the number to format\n :type value: float\n :param right_digits: print how many digits after the decimal point?\n :type right_digits: int\n :return: the formatted value\n :rtype: str\n \"\"\"\n result = ('{0:.{1}f}'.format(value, right_digits))\n return result\n\n\ndef format_meas(time, include_batt):\n \"\"\"\n Formats all active measurements into a string that looks like\n “04/22/21,13:30:00,13.94,1.78,2.89”\n where we have date MM/DD/YY,time HH:MM:SS,battery voltage,measurement M1,measurement M2\n\n :param include_batt: should the data include the current battery voltage?\n :type include_batt: bool\n :return: formatted measurement data\n :rtype: str\n \"\"\"\n out = ascii_time(time)\n\n # include the battery voltage?\n if include_batt:\n out += \",\"\n out += format_number_right_digits(batt(), 2)\n\n # format all the measurement readings\n for meas_index in range(1, 10):\n\n # is this measurement active?\n if \"ON\" in setup_read(\"M{} Active\".format(meas_index)).upper():\n\n # get the measurement reading\n reading = measure(meas_index)\n\n # format the value\n out += \",\"\n out += format_number_right_digits(reading.value, reading.right_digits)\n\n # add the delimiter at the end\n out += \"\\n\"\n return out\n\n \n@TASK\ndef output_data():\n \"\"\"\n Outputs measurement data on the RS232 port\n \"\"\"\n message = format_meas(time_scheduled(), True)\n with serial.Serial(\"RS232\", 19200) as output:\n output.write(message)\n output.flush() # needed to make sure all the data is sent before closing the port.\n\n # for diagnostics in script status:\n print(message)\n\n\n\n","sub_path":"projects/AutoPrint_RS232/AutoPrint_RS232_script.py","file_name":"AutoPrint_RS232_script.py","file_ext":"py","file_size_in_byte":2040,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"355478458","text":"from django.urls import path\nfrom django.conf.urls import url\n\n# import views.py\nfrom . import views\napp_name = 'courses'\n# url patterns is a container\nurlpatterns = [\n path('', views.first_view, name='course_list'),\n path('', views.course_detail, name='course_detail'),\n path('/create_quiz', views.quiz_create, name='create_quiz'),\n path('/t/', views.text_detail, name='text'),\n path('/q/', views.quiz_detail, name='quiz')\n ]\n","sub_path":"courses/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":524,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"171147031","text":"import random\r\n\r\nclass Player(object):\r\n\t# Персонаж игры.\r\n\tdef __init__(self, name):\r\n\t\tself.name = name\r\n\t\tself.health = 100\r\n\tdef __str__(self):\r\n\t\trep = (f\"\\tПерсонаж {self.name}, {self.health} HP\")\r\n\t\treturn rep\r\n\tdef ability_1(self, enemy):\r\n\t\t# Способность наносить урон в диапозоне 18 - 25.\r\n\t\tability_power = random.randint(-25, -18)\r\n\t\tenemy.use(ability_power)\r\n\t\tprint(f\"Персонаж {self.name} наносит {-ability_power} едениц умеренного урона персонажу {enemy.name}.\")\r\n\tdef ability_2(self, enemy):\r\n\t\t# Способность наносить урон в диапозоне 10 - 35.\r\n\t\tability_power = random.randint(-35, -10)\r\n\t\tenemy.use(ability_power)\r\n\t\tprint(f\"Персонаж {self.name} наносит {-ability_power} едениц большого урона персонажу {enemy.name}.\")\r\n\tdef ability_3(self, enemy):\r\n\t\t# Способность излечивать себя в диапозоне 18 - 25.\r\n\t\tability_power = random.randint(18 ,25)\r\n\t\tenemy.use(ability_power)\r\n\t\tprint(f\"Персонаж {self.name} исцеляет себя на {ability_power} едениц здоровья.\")\r\n\tdef random_ability(self, enemy):\r\n\t\t# Выбор случайной сбособности.\r\n\t\tability = [self.ability_1, self.ability_2, self.ability_3]\r\n\t\tability = random.choices(ability, [1, 1, 1])\r\n\t\t# Вероятность выбора каждой способности 1/3.\r\n\t\tif ability[0] == self.ability_3:\r\n\t\t\t# Использовать способность на себя, если это способность - лечение.\r\n\t\t\tability[0](self)\r\n\t\telse:\r\n\t\t\tability[0](enemy)\r\n\tdef use(self, ability_power):\r\n\t\t# Применение способности.\r\n\t\tself.health += ability_power\r\n\t\tif self.health <= 0:\r\n\t\t\tself.health = 0\r\n\t\tif self.health >= 100:\r\n\t\t\tself.health = 100\r\n\tdef die(self):\r\n\t\t# Персонаж умер.\r\n\t\tif self.health <= 0:\r\n\t\t\tself.health = 0\r\n\t\t\treturn True\r\n\tdef lose(self):\r\n\t\t# Персонаж проиграл.\r\n\t\tprint(f\"Персонаж {self.name} проиграл!\")\r\n\tdef win(self):\r\n\t\t# Персонаж выиграл.\r\n\t\tprint(f\"\\nПерсонаж {self.name} одержал победу!\")\r\n\t\t\r\nclass Computer(Player):\r\n\t# Персонаж игры - Компьютер.\r\n\tdef random_ability(self, enemy):\r\n\t\tability = [self.ability_1, self.ability_2, self.ability_3]\r\n\t\tif self.health < 35:\r\n\t\t\t# Увеличение шанса на лечение при достижение здоровья персонажа < 35.\r\n\t\t\tprint(f\"Персонаж {self.name} увеличил шанс на исцеление.\")\r\n\t\t\tability = random.choices(ability, [1, 1, 2])\r\n\t\t\t# Вероятность выбора способностей 1/4, 1/4, 1/2 соответсвенно.\r\n\t\telse:\r\n\t\t\tability = random.choices(ability, [1, 1, 1])\r\n\t\tif ability[0] == self.ability_3:\r\n\t\t\tability[0](self)\r\n\t\telse:\r\n\t\t\tability[0](enemy)\t\r\n\r\nclass Game(object):\r\n\t# Игровой процесс.\r\n\tdef __init__(self, name):\r\n\t\tself.player = Player(name)\r\n\t\tself.machine = Computer(\"Компьютер\")\r\n\tdef move_selection(self):\r\n\t\t# Случайный выбор хода.\r\n\t\treturn random.randint(0, 1)\r\n\tdef play(self):\r\n\t\tif self.move_selection():\r\n\t\t\tprint(f\"\\nХодит персонаж - {self.player.name}:\")\r\n\t\t\tself.player.random_ability(self.machine)\r\n\t\t\tprint(self.player, self.machine, sep = '\\n')\r\n\t\telse:\r\n\t\t\tprint(f\"\\nХодит персонаж - {self.machine.name}:\")\r\n\t\t\tself.machine.random_ability(self.player)\r\n\t\t\tprint(self.player, self.machine, sep = '\\n')\r\n\t\tif self.player.die():\r\n\t\t\tself.machine.win()\r\n\t\t\tself.player.lose()\r\n\t\tif self.machine.die():\r\n\t\t\tself.player.win()\r\n\t\t\tself.machine.lose()\t\r\n\r\ndef main():\r\n\tinput(\"Нажмите Enter, чтобы начать.\")\r\n\tgame = Game(\"Игрок\")\r\n\twhile(not game.player.die() and not game.machine.die()):\r\n\t\tgame.play()\r\n\tinput(\"\\n\\n Нажмите Enter, чтобы выйти.\")\r\n\r\nmain()\r\n\r\n","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":4051,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"408606156","text":"# -*- coding:utf-8 -*-\n\nimport os\nimport json\nimport uuid\nimport pprint\nimport datetime as dt\nfrom datetime import timedelta\nimport pendulum\nimport logging\nimport pika\nfrom typing import Optional\nfrom airflow.models import DAG\nfrom qcos_addons.models.curve_template import CurveTemplateModel\nfrom typing import Dict\nfrom airflow.operators.python_operator import PythonOperator\nfrom plugins.entities.redis import ClsRedisConnection, gen_template_key\nfrom plugins.entities.result_mq import ClsResultMQ\nfrom plugins.utils.utils import parse_template_name\nfrom plugins.rabbitmq.rabbimq_plugin import RabbitmqOperator\n\nCURVE_TEMPLATE_UPGRADE_TASK = 'curve_template_upgrade'\n\nCURVE_TEMPLATE_KEY_PREFIX = os.environ.get(\n \"CURVE_TEMPLATE_KEY_PREFIX\", \"qcos_templates\")\n\nDAG_ID = 'curve_template_upgrade'\n\nRUNTIME_ENV = os.environ.get('RUNTIME_ENV', 'dev')\n\nif RUNTIME_ENV == 'prod':\n schedule_interval = '@once'\n loggingLevel = logging.INFO\nelse:\n schedule_interval = '@once'\n loggingLevel = logging.DEBUG\n\n_logger = logging.getLogger(__name__)\n_logger.addHandler(logging.StreamHandler())\n\n_logger.setLevel(loggingLevel)\n\n\ndef onUpgradeCurveTmplFail(context):\n _logger.debug(\"{0} Run Fail\".format(context))\n\n\ndef onUpgradeCurveTmplSuccess(context):\n _logger.debug(\"{0} Run Success\".format(context))\n\n\nlocal_tz = pendulum.timezone(\"Asia/Shanghai\")\n\ndesoutter_default_args = {\n 'owner': 'qcos',\n 'depends_on_past': False,\n 'start_date': dt.datetime(2020, 1, 1, tzinfo=local_tz),\n 'retries': 4,\n 'retry_delay': timedelta(minutes=2),\n 'on_failure_callback': onUpgradeCurveTmplFail,\n 'on_success_callback': onUpgradeCurveTmplSuccess,\n 'on_retry_callback': None,\n 'trigger_rule': 'all_success'\n}\n\nredis_connection: Optional[ClsRedisConnection] = None\n\n\ndef template_upgrade_handler(ch, method: pika.spec.Basic.Deliver, properties: pika.spec.BasicProperties, body: bytes):\n \"\"\"\n 处理从rabbitmq订阅到的结果,作为channel.basic_consume的on_message_callback参数。\n @param ch: BlockingChannel\n @param method: spec.Basic.Deliver\n @param properties: spec.BasicProperties\n @param body: bytes 消息体\n \"\"\"\n try:\n if not body:\n return\n data = body\n channel = method.routing_key or ''\n if not data or not channel:\n return\n # 解析模板名称和数据\n if isinstance(channel, bytes):\n channel = channel.decode('utf-8')\n if isinstance(data, bytes):\n data = data.decode('utf-8')\n template: Dict = json.loads(data)\n _logger.debug(\"Recv Template Data, key:{}, data: {}\".format(channel, pprint.pformat(template, indent=4)))\n template_name = parse_template_name(channel)\n except Exception as e:\n _logger.error(\"template_upgrade_handler error: {}\".format(repr(e)))\n raise e\n\n try:\n key, val = CurveTemplateModel.get_fuzzy_active(key=template_name, deserialize_json=True)\n _logger.debug(\"Get Template Var: {}\".format(key))\n # 保留现有模板参数中的windows\n windows = val.get('curve_param').get('windows', None) if val.get('curve_param', False) else None\n if windows:\n template.update({'windows': windows})\n # 版本+1\n template.update({'version': val.get('version', 0) + 1})\n CurveTemplateModel.set(key=key, value=template, serialize_json=True) # 此业务场景下 params不会变化故覆盖现有的variable\n\n except KeyError as e:\n _logger.info(f\"收到不存在的模板{template_name},不进行任何操作\")\n return\n # 没有这个key 重新创建这个key\n # key = \"{}@@{}\".format(template_name, str(uuid.uuid4()))\n # CurveTemplateModel.set(key=key, value=template, serialize_json=True)\n except Exception as e:\n _logger.error(\"template_upgrade_handler error: {}\".format(repr(e)))\n # 缓存到redis\n try:\n global redis_connection\n if redis_connection is None:\n redis_connection = ClsRedisConnection()\n redis_connection.store_templates({\n template_name: json.dumps(template)\n })\n except Exception as e:\n _logger.error('store curve template to redis error: {}'.format(repr(e)))\n\n\ndag = DAG(\n dag_id=DAG_ID,\n description=u'拧紧曲线分析-曲线模板更新',\n start_date=dt.datetime(2020, 1, 1, tzinfo=pendulum.timezone(\"Asia/Shanghai\")),\n catchup=False,\n concurrency=1,\n max_active_runs=1,\n schedule_interval=timedelta(seconds=1),\n default_args={\n 'owner': 'qcos',\n 'depends_on_past': False,\n 'retries': 0,\n 'trigger_rule': 'all_success'\n },\n tags=['training', 'mq']\n)\n\nupgrade_curve_template_task = RabbitmqOperator(\n task_id=CURVE_TEMPLATE_UPGRADE_TASK,\n dag=dag,\n priority_weight=9,\n mq_config={\n 'conn_id': 'qcos_rabbitmq',\n 'queue': os.environ.get('MQ_TEMPLATE_QUEUE', 'qcos_templates'),\n 'queue_args': {\n 'durable': True\n },\n 'exchange': os.environ.get('MQ_TEMPLATE_EXCHANGE', 'qcos_templates'),\n 'exchange_args': {\n 'exchange_type': 'fanout'\n },\n 'binding_args': {\n 'routing_key': gen_template_key('*'),\n },\n 'message_handler': template_upgrade_handler\n }\n)\n","sub_path":"dags/mq_upgrade_curve_template.py","file_name":"mq_upgrade_curve_template.py","file_ext":"py","file_size_in_byte":5334,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"365255803","text":"import csv, os, requests, sqlite3\nimport pandas as pd\nfrom bs4 import BeautifulSoup\nfrom datetime import datetime\nfrom random import randint\nfrom time import sleep\n\nimport constants\nimport database\nimport utils\n\nclass Scrape84Race:\n def __init__(self):\n self.session = requests.Session()\n adapter = requests.adapters.HTTPAdapter(max_retries=5)\n self.session.mount('https://', adapter)\n self.session.mount('http://', adapter)\n self.get = lambda url: self.__get(url)\n self.post = lambda url, data=None: self.__post(url, data)\n\n def __get(self, url):\n response = self.session.get(url, headers=utils.get_header())\n self.__check_response(response)\n return response\n\n def __post(self, url, data=None):\n if data:\n response = self.session.post(url, data=data, headers=utils.get_header())\n else:\n response = self.session.post(url, headers=utils.get_header())\n self.__check_response(response)\n return response\n\n def __check_response(self, response):\n response.raise_for_status()\n return response\n\n def scrape_athletes(self):\n response = self.post(\n constants.ATHLETE_RANKING_URL,\n data = {'search': '', 'hangmuc_id': ''}\n )\n soup = BeautifulSoup(response.content, 'lxml')\n athlete_list = []\n for tr in soup.find_all('tr'):\n athlete_url = tr.select_one('a[href*=\"' + constants.MEMBER_URL + '\"]')['href']\n athlete_id = athlete_url.replace(constants.MEMBER_URL, '')\n athlete_name = tr.select_one('small').text\n team_id_tag = tr.select_one('.detail_team')\n team_id = None if team_id_tag is None else team_id_tag.attrs.get(\"data-id\", None)\n total_distance = tr.select_one('td:nth-child(4)').text\n athlete_list.append(\n (athlete_id, athlete_name, team_id, total_distance)\n )\n db = database.get_db()\n query = '''INSERT INTO athlete (id_84race, name_84race, team_id, total_distance_84race)\n VALUES (?, ?, ?, ?)\n ON CONFLICT (id_84race)\n DO UPDATE SET total_distance_84race=excluded.total_distance_84race'''\n try:\n with db:\n db.executemany(query, athlete_list)\n except sqlite3.Error as e:\n return False\n\n return True\n\n def scrape_teams(self):\n response = self.post(\n constants.TEAM_LIST_URL\n )\n soup = BeautifulSoup(response.content, 'lxml')\n team_list = []\n for tr in soup.find_all('tr')[1:]:\n hyperlink = tr.select_one('td:nth-child(2) a')\n team_id = hyperlink.attrs.get(\"data-id\", None)\n team_name = hyperlink.text\n team_list.append(\n (team_id, team_name)\n )\n db = database.get_db()\n query = '''INSERT INTO team (id, name) VALUES (?, ?)'''\n try:\n with db:\n db.executemany(query, team_list)\n except sqlite3.Error as e:\n return False\n\n return True\n\n def scrape_activities(self):\n race_start_datetime = datetime.strptime(constants.RACE_START_DATETIME, '%Y/%m/%d %H:%M:%S')\n race_end_datetime = datetime.strptime(constants.RACE_END_DATETIME, '%Y/%m/%d %H:%M:%S')\n db = database.get_db()\n cur = db.cursor()\n select_athletes_query = 'SELECT id_84race FROM athlete'\n cur.execute(select_athletes_query)\n rows = cur.fetchall()\n\n for row in rows:\n athlete_id = row['id_84race']\n page = 1\n while True:\n response = self.post(\n constants.PERSONAL_ACTIVITIES_URL + str(athlete_id),\n data = {'page': page, 'listCateId': ''}\n )\n if not response.text:\n break\n soup = BeautifulSoup(response.content, 'lxml')\n activity_list = []\n for wrapper in soup.select('div.post.d-bor30'):\n activity_url = wrapper.select_one('a[href*=\"' + constants.ACTIVITY_84RACE_URL + '\"]')['href']\n activity_id = activity_url.replace(constants.ACTIVITY_84RACE_URL, '')\n ic_classes = wrapper.select_one('i.ic').get('class')\n if 'ic-shose2' in ic_classes:\n sport_type = 'Run'\n elif 'ic-question' in ic_classes:\n sport_type = 'Walk'\n else:\n continue\n activity_name = wrapper.select_one('div.head h4.name').text\n start_datetime = wrapper.select_one('div.head time').text\n start_datetime = datetime.strptime(start_datetime, '%d/%m/%Y %H:%M:%S')\n if start_datetime < race_start_datetime or start_datetime > race_end_datetime:\n continue\n else:\n start_datetime = start_datetime.strftime('%Y-%m-%d %H:%M:%S')\n distance, moving_time, average_pace, heart_rate = [item.find(text=True, recursive=False).strip() for item in wrapper.select('div.ct2.ct3 div.ibl')]\n distance = distance.replace('km', '').strip()\n time_arr = [s[:-1] for s in moving_time.split()]\n moving_time = ':'.join(time_arr)\n average_pace = average_pace.replace('/km', '').strip()\n if float(distance) == 0 and average_pace.find(':') == -1 and int(average_pace) == 0:\n continue\n activity_list.append(\n (activity_id, athlete_id, activity_name, sport_type, start_datetime, distance, moving_time, average_pace, 1)\n )\n db = database.get_db()\n query = '''INSERT OR IGNORE INTO activity\n (id, id_84race, name_84race, type_84race, start_datetime_84race, distance_84race, moving_time_84race, average_pace_84race, scrape_step)\n VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)'''\n try:\n with db:\n db.executemany(query, activity_list)\n except sqlite3.Error as e:\n return False\n sleep(1)\n page += 1\n sleep(randint(3, 5))\n\n return True\n\n def compare_tracklog(self):\n current_dir = os.path.dirname(__file__)\n\n # 84Race activities\n # with open(os.path.join(current_dir, 'personal/duc_uploaded.html'), 'r', encoding='utf-8') as f:\n # contents = f.read()\n # soup = BeautifulSoup(contents, 'lxml')\n\n # uploaded_id_list = []\n # uploaded_total_distance = 0\n # for wrapper in soup.select('div.post.d-bor30'):\n # a = wrapper.select_one('div.head div.text a')\n # uploaded_id_list.append(int(a['href'].replace('https://84race.com/personal/edit-activity/', '')))\n # distance = wrapper.select_one('div.ct2.ct3 div.ibl:nth-child(1)').find(text=True, recursive=False).replace('km', '').strip()\n # uploaded_total_distance += float(distance)\n\n # 84Race race tracklog\n with open(os.path.join(current_dir, 'personal/thao_tracklog.html'), 'r', encoding='utf-8') as f:\n contents = f.read()\n soup = BeautifulSoup(contents, 'lxml')\n\n tracklog_id_list = []\n tracklog_total_distance = 0\n for tr in soup.select('tbody > tr'):\n a = tr.select_one('td:last-child > a')\n tracklog_id_list.append(int(a.text))\n distance = tr.select_one('td:nth-child(3)').find(text=True, recursive=False).replace('km', '').strip()\n tracklog_total_distance += float(distance)\n\n usecols = ['id', 'start_date_local', 'distance', 'moving_time']\n df = pd.read_csv(os.path.join(current_dir, 'personal/thao_strava_activities.csv'), usecols=usecols)\n strava_id_list = df['id'].tolist()\n\n # uploaded_not_in_tracklog = [id for id in uploaded_id_list if id not in tracklog_id_list]\n # tracklog_not_in_uploaded = [id for id in tracklog_id_list if id not in uploaded_id_list]\n not_in_tracklog = [id for id in strava_id_list if id not in tracklog_id_list]\n # not_in_uploaded = [id for id in strava_id_list if id not in uploaded_id_list]\n\n df = df.set_index(['id'])\n df['start_date_local'] = pd.to_datetime(df['start_date_local'], format='%Y-%m-%dT%H:%M:%SZ')\n df['start_datetime'] = df['start_date_local'].dt.tz_localize('Asia/Tokyo').dt.tz_convert('Asia/Ho_Chi_Minh')\n data = df.loc[df.index.isin(not_in_tracklog)].to_csv(os.path.join(current_dir, 'personal/thao_output.csv'), index=True)\n return True\n","sub_path":"scrape_84race.py","file_name":"scrape_84race.py","file_ext":"py","file_size_in_byte":8926,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"475046267","text":"import pandas as pd\n\nfrom util.data import Column, Data\nfrom util.timer import timer\n\n\n@timer\ndef get_movies_with_similar_genres(movie_id: int, n: int = 5, popularity_bias: bool = False\n , user_bias: bool = False, movies: pd.DataFrame = None):\n # Get all movies and split them into the base movie and the rest\n\n if n is None:\n n = 5\n\n # Use the preferred movie df\n if movies is None:\n all_movies = Data.movie_meta()[Column.genres.value]\n else:\n all_movies = movies[Column.genres.value]\n\n # get the base out of the df and remove it from the rest\n base_genres = eval(all_movies.loc[movie_id])\n all_movies = all_movies.drop(movie_id)\n\n # count similar genres\n all_movies = all_movies.apply(\n lambda row: count_elements_in_set(row, base_genres)\n )\n # remove all movies which have no genre in common\n filtered_movies_sum = all_movies[all_movies > 0]\n\n # if user_bias is true\n if user_bias:\n # reduce the amount of movies to n * 10 movies\n top_n_mul_ten = filtered_movies_sum.nlargest(n * 10)\n ratings = Data.ratings()\n\n # group by movie\n ratings_grouped = ratings.groupby(str(Column.movie_id))\n # calculate mean rating and number of ratings for each movie\n # (select rating to remove first level of column index. before: (rating: (mean, count)), after: (mean, count) )\n measures: pd.DataFrame = ratings_grouped.agg(['mean', 'count'])[str(Column.rating)]\n\n # merging mean, count and genre sum into one DataFrame\n measures_movies = pd.merge(measures, pd.DataFrame(top_n_mul_ten), left_index=True, right_index=True)\n\n if popularity_bias:\n # give more weight to the number of ratings (~popularity)\n # by raising the avg ratings to some power (to preserve some notion of good vs. bad ratings)\n # and multiplying the count back in\n # additionally multiply the genre back in\n # to prevent good rated movies with little correlation to the genres\n results = measures_movies.eval('(mean ** 3) * count * genres')\n else:\n # multiply genre to prevent good rated movies with little correlation to the genres\n results = measures_movies.eval('mean * genres')\n else:\n results = filtered_movies_sum\n\n # breakpoint()\n return results\n\n\n# function to count the elements in row which are in the base too\ndef count_elements_in_set(row: list, base: list):\n genres = eval(row)\n return len((set(base).intersection(genres)))\n","sub_path":"project/recommendations/strategies/shared/genre_filter.py","file_name":"genre_filter.py","file_ext":"py","file_size_in_byte":2594,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"239557054","text":"import tensorflow as tf\nimport random\nimport matplotlib.pyplot as plt\nfrom tensorflow.examples.tutorials.mnist import input_data\n\ntf.set_random_seed(777) #reproducibility\n\nmnist = input_data.read_data_sets(\"MNIST_data/\", one_hot = True)\n#잘정리 되어있는 이미지들을 받아와서 onehot인코딩을 통해 클래스를 분류해줌\nlearning_rate = 0.001 #러닝하면서 찾아갈 이동 단위\ntraining_epochs = 10 #훈련을 시킬 횟수\nbatch_size = 100 #훈련시킬 데이터의 묶음\n\nX = tf.placeholder(tf.float32, [None, 784])\nX_img = tf.reshape(X,[-1,28,28,1]) #img 28x28x1(black/white)\nY = tf.placeholder(tf.float32, [None, 10])\nkeep_prob = tf.placeholder(tf.float32)\n\nW1 = tf.Variable(tf.random_normal([3, 3, 1, 16], stddev=0.01)) \n#표준편차가 0.01인 3x3매트릭스(깊이1) 데이터를 16개만큼 뽑겠다\n#28x28x16\nL1 = tf.nn.conv2d(X_img, W1, strides=[1, 1, 1, 1], padding='SAME')\n#strides를 통해 축을 여러개 만들어 주어 이동방향을 여러방향으로 하게 했으나 가운데 1,1만 적용이 된다 \n#제로패딩을통해 사이즈를 동일하게 만듬\nL1 = tf.nn.relu(L1) #relu함수를 이용 음수값을 제거하는 방법으로 사용된다.\nL1 = tf.nn.max_pool(L1, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='SAME')\n#컨벌루션된 결과를 max pooling을 통해 최댓값으로 다시 정리 1차원축으로 2칸 2차원축으로도 2칸이동한다\n#제로패딩을 통해 크기가 줄지 않아야하지만 2x2필터를 사용하여서 크기가 반으로 줄어든다 depth는 그대로 유지된다(32)\n#14x14x16\nW2 = tf.Variable(tf.random_normal([3, 3, 16, 32], stddev=0.01))\n#역시 필터를 생성하는데 3x3매트릭스의 깊이가16인 데이터를 32개를 사용한다\nL2 = tf.nn.conv2d(L1, W2, strides=[1, 1, 1, 1], padding='SAME') #14x14x32\nL2 = tf.nn.relu(L2)\nL2 = tf.nn.max_pool(L2, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='SAME')\n#7x7x32\n#===============================================================================\n#레이어 추가 부분\nW3 = tf.Variable(tf.random_normal([3, 3, 32, 64], stddev =0.01))\nL3 = tf.nn.conv2d(L2, W3, strides=[1, 1, 1, 1], padding='SAME') #7x7x64\nL3 = tf.nn.relu(L3)\nL3 = tf.nn.max_pool(L3, ksize = [1, 2, 2, 1], strides=[1, 2, 2, 1], padding='SAME')\n#4x4x64\n#===============================================================================\nL3_flat = tf.reshape(L3,[-1, 4 * 4 * 64])\n\nW4 = tf.Variable(tf.random_normal([4 * 4 * 64, 10],stddev=0.01))\n# 최종 출력값 L2 에서의 출력 7*7*64개를 입력값으로 받아서 0~9 레이블인 10개의 출력값을 만듬\nb = tf.Variable(tf.random_normal([10]))\nhypothesis = tf.matmul(L3_flat, W4) +b\n\ncost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits = hypothesis, \n labels = Y))\n#costfunction\noptimizer = tf.train.AdamOptimizer(learning_rate=learning_rate).minimize(cost)\n#adamoptimizer를 사용 adam은 최적값의 근사치일때 넓게 점프해서 한번더 체크해준다\nsess = tf.Session()\n#세션을 통해 메모리에 설정한것들을 올려준다\nsess.run(tf.global_variables_initializer())\n\nfor epoch in range(training_epochs) : #같은 트레이닝데이터를 epoch수만큼 훈련시킨다\n avg_cost = 0 #오버피팅을 통한 정확도 상승을 목표로 한다\n total_batch = int(mnist.train._num_examples / batch_size)\n #train set에 example들을 batchsize(100)만큼 나누어주어 total batch를 구한다\n for i in range(total_batch) : #전체 데이터를 100장씩 훈련시키게 된다\n batch_xs, batch_ys = mnist.train.next_batch(batch_size)\n feed_dict = {X:batch_xs, Y:batch_ys} #placeholder로 설정한 그릇에 데이터 담아줌\n cost_val, _ = sess.run([cost,optimizer],feed_dict=feed_dict)\n avg_cost += cost_val / total_batch #출력을 위해 avg코스트를 만들어주어 확인\n \n print('Epoch :', '%04d'%(epoch+1),'cost = ','{:9f}'.format(avg_cost))\n \nprint('Learning Finished!!') #15번의 훈련(epoch)을 모두 마치면 출력\n\ncorrect_prediction = tf.equal(tf.argmax(hypothesis,1),tf.argmax(Y,1))\naccuracy = tf.reduce_mean(tf.cast(correct_prediction,tf.float32))\nprint('Accuracy : ', sess.run(accuracy, feed_dict={X:mnist.test.images,\n Y:mnist.test.labels}))\n\nr = random.randint(0,mnist.test._num_examples -1)\nprint('Label : ',sess.run(tf.argmax(mnist.test.labels[r:r+1],1)))\nprint('Prediction : ',sess.run(tf.argmax(hypothesis,1),\n feed_dict={X:mnist.test.images[r:r+1]}))\n\nplt.imshow(mnist.test.images[r:r+1].reshape(28,28),cmap = 'Greys',\n interpolation='nearest')\nplt.show()","sub_path":"tensorflow_practice/tensor_14.py","file_name":"tensor_14.py","file_ext":"py","file_size_in_byte":4814,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"8571673","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sat May 12 14:45:51 2018\n\n@author: zsc\n\"\"\"\n\nfrom optimize import optimize\nfrom utils import save_image, get_image, check_path\n\nCONTENT_WEIGHT=7.5e0\nSTYLE_WEIGHT=1e2\nTV_WEIGHT=2e2\nVGG_PATH = 'data/imagenet-vgg-verydeep-19.mat'\nLEARNING_RATE = 1e-3\nNUM_EPOCHS = 2\nPATH=['transfer_model','data/scream.jpg','data/handsome.jpg',VGG_PATH]\nBATCH_SIZE = 4\n\ndef main():\n check_path(PATH)\n style_image=get_image(PATH[1])\n optimize(PATH[2],style_image,CONTENT_WEIGHT,STYLE_WEIGHT,TV_WEIGHT,VGG_PATH)\n\n\nif __name__=='__main__':\n main()\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n ","sub_path":"train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":796,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"583653676","text":"'''Two of the most useful methods on strings involve lists of strings.\nThe split method breaks a string into a list of words.\nBy default, any number of whitespace characters is considered a word boundary.\n'''\nsong = \"The rain in Spain...\"\nwds = song.split()\nprint(wds)\n\n\n'''An optional argument called a delimiter can be used to specify which characters to use as word boundaries.\n The following example uses the string ai as the delimiter:\n'''\n\nsong = \"The rain in Spain...\"\nwds = song.split('ai')\nprint(wds)\n\n'''Notice that the delimiter doesn’t appear in the result.\n\nThe inverse of the split method is join. You choose a desired separator string,\n(often called the glue) and join the list with the glue between each of the elements.\n'''\n\nwds = [\"red\", \"blue\", \"green\"]\nglue = ';'\ns = glue.join(wds)\nprint(s)\nprint(wds)\n\nprint(\"***\".join(wds))\nprint(\"\".join(wds))\n\n\n'''The list that you glue together (wds in this example) is not modified.\nAlso, you can use empty glue or multi-character strings as glue.\n'''\n\nmyname = \"Edgar Allan Poe\"\nnamelist = myname.split()\ninit = \"\"\nfor aname in namelist:\n init = init + aname[0]\nprint(init)\n'''Correct! Yes, split creates a list of the three names. The for loop iterates through the names and creates a string from the first characters.'''\n","sub_path":"ClassExercise & studio/chapter 11/Strings and Lists.py","file_name":"Strings and Lists.py","file_ext":"py","file_size_in_byte":1289,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"506170331","text":"from django.conf import settings\nfrom twilio.base.exceptions import TwilioRestException\nfrom twilio.rest import Client\n\n# Set up Twilio client\nclient = Client(settings.TWILIO_ACCOUNT_SID, settings.TWILIO_AUTH_TOKEN)\n\ndef send_sms(to_number, body, media_link=None):\n try:\n message = client.messages.create(\n to=to_number,\n from_=settings.TWILIO_NUMBER,\n media_url=media_link,\n body=body)\n\n print(\"SID of message sent: \" + message.sid)\n return message.sid\n except TwilioRestException as e:\n # Implement fallback code\n print(\"Failed to send SMS with following exception: \" + e)\n\ndef make_call(to_number, url = None):\n if url is None:\n url=\"http://demo.twilio.com/docs/voice.xml\"\n \n call = client.calls.create(\n to=to_number,\n from_=settings.TWILIO_NUMBER,\n url=url\n )\n\n print(\"SID of call made: \" + call.sid)\n return call.sid\n","sub_path":"matching/lib_twilio.py","file_name":"lib_twilio.py","file_ext":"py","file_size_in_byte":954,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"297999068","text":"import pygame\r\nimport time\r\n\r\npygame.init()\r\n\r\nTITLE = \"Sudoku Solver\"\r\nSIZE = (1000, 600)\r\nWHITE = (255,255,255)\r\nBLUE = (51,204,255)\r\nBLACK = (0,0,0)\r\nROWS = 9\r\nCOLS = 9\r\nARIAL_40 = pygame.font.SysFont(\"arial\", 40, bold=True)\r\nARIAL_20 = pygame.font.SysFont(\"arial\", 20, bold=True)\r\nNUMBER_FONT = pygame.font.SysFont(\"comicsans\", 40)\r\n\r\nBOARD1 = [\r\n [5, 0, 0, 1, 0, 0, 0, 9, 0],\r\n [0, 7, 9, 5, 6, 0, 1, 0, 2],\r\n [2, 3, 0, 0, 4, 0, 8, 0, 0],\r\n [6, 9, 0, 0, 0, 0, 0, 0, 0],\r\n [3, 0, 0, 2, 9, 1, 0, 0, 8],\r\n [0, 0, 0, 0, 0, 0, 0, 2, 4],\r\n [0, 0, 6, 0, 7, 0, 0, 1, 9],\r\n [9, 0, 3, 0, 5, 2, 7, 4, 0],\r\n [0, 4, 0, 0, 0, 6, 0, 0, 3]\r\n]\r\n\r\nBOARD3 = [\r\n [8, 0, 0, 1, 0, 0, 0, 6, 0],\r\n [2, 9, 6, 0, 0, 5, 0, 0, 0],\r\n [0, 0, 4, 9, 0, 2, 0, 0, 0],\r\n [0, 0, 1, 0, 5, 8, 0, 0, 0],\r\n [6, 4, 0, 0, 0, 0, 0, 8, 9],\r\n [0, 0, 0, 4, 2, 0, 6, 0, 0],\r\n [0, 0, 0, 2, 0, 3, 5, 0, 0],\r\n [0, 0, 0, 5, 0, 0, 4, 9, 1],\r\n [0, 6, 0, 0, 0, 4, 0, 0, 3]\r\n]\r\n\r\nBOARD5 = [\r\n [8, 0, 0, 0, 0, 0, 0, 0, 0],\r\n [0, 0, 3, 6, 0, 0, 0, 0, 0],\r\n [0, 7, 0, 0, 9, 0, 2, 0, 0],\r\n [0, 5, 0, 0, 0, 7, 0, 0, 0],\r\n [0, 0, 0, 0, 4, 5, 7, 0, 0],\r\n [0, 0, 0, 1, 0, 0, 0, 3, 0],\r\n [0, 0, 1, 0, 0, 0, 0, 6, 8],\r\n [0, 0, 8, 5, 0, 0, 0, 1, 0],\r\n [0, 9, 0, 0, 0, 0, 4, 0, 0]\r\n]\r\n\r\nclass Number:\r\n def __init__(self, value, row, col, width, height):\r\n self.value = value\r\n self.row = row\r\n self.col = col\r\n self.width = width\r\n self.height = height\r\n\r\n def set(self, value):\r\n self.value = value\r\n \r\n def draw(self, screen):\r\n if self.value != 0:\r\n cell_size = self.width / COLS\r\n cell_x = self.col * cell_size\r\n cell_y = self.row * cell_size\r\n text = NUMBER_FONT.render(str(self.value), 1, WHITE)\r\n\r\n text_pos_x = cell_x + (cell_size/2 - text.get_width()/2)\r\n text_pos_y = cell_y + (cell_size/2 - text.get_height()/2)\r\n screen.blit(text, (text_pos_x, text_pos_y))\r\n \r\n def change_number(self, screen, color):\r\n cell_size = self.width / COLS\r\n cell_x = self.col * cell_size\r\n cell_y = self.row * cell_size\r\n pygame.draw.rect(screen, BLACK, (cell_x, cell_y, cell_size, cell_size), 0)\r\n text = NUMBER_FONT.render(str(self.value), 1, WHITE)\r\n\r\n text_pos_x = cell_x + (cell_size/2 - text.get_width()/2)\r\n text_pos_y = cell_y + (cell_size/2 - text.get_height()/2)\r\n screen.blit(text, (text_pos_x, text_pos_y))\r\n\r\n if color:\r\n pygame.draw.rect(screen, (0, 255, 0), (cell_x, cell_y, cell_size, cell_size), 3)\r\n else:\r\n pygame.draw.rect(screen, (255, 0, 0), (cell_x, cell_y, cell_size, cell_size), 3)\r\n\r\n\r\nclass Grid:\r\n def __init__(self, rows, cols, width, height, screen, difficulty):\r\n self.iterations = 0\r\n self.rows = rows\r\n self.cols = cols\r\n self.width = width\r\n self.height = height\r\n self.screen = screen\r\n self.difficulty = difficulty\r\n self.experiment = None\r\n\r\n if self.difficulty == 1:\r\n self.numbers = [[Number(BOARD1[i][j], i, j, width, height) for j in range(cols)] for i in range(rows)]\r\n elif self.difficulty == 3:\r\n self.numbers = [[Number(BOARD3[i][j], i, j, width, height) for j in range(cols)] for i in range(rows)]\r\n elif self.difficulty == 5:\r\n self.numbers = [[Number(BOARD5[i][j], i, j, width, height) for j in range(cols)] for i in range(rows)]\r\n self.update_experiment()\r\n\r\n def draw_board(self):\r\n \"\"\"\r\n Draws grid and numbers to screen\r\n \"\"\"\r\n cell_size = self.width / ROWS\r\n for i in range(self.rows+1):\r\n if i % 3 == 0:\r\n line_thickness = 4\r\n else:\r\n line_thickness = 1\r\n pygame.draw.line(self.screen, WHITE, (0, i*cell_size), (self.width, i*cell_size), line_thickness)\r\n pygame.draw.line(self.screen, WHITE, (i*cell_size, 0), (i*cell_size, self.height), line_thickness)\r\n \r\n for i in range(self.rows):\r\n for j in range(self.cols):\r\n self.numbers[i][j].draw(self.screen)\r\n\r\n def solve(self):\r\n \"\"\"\r\n Solves sudoku using backtracking\r\n \"\"\"\r\n #Check if solved\r\n empty = next_cell(self.experiment)\r\n if not empty:\r\n self.finish()\r\n return True\r\n else:\r\n row, column = empty\r\n self.iterations += 1\r\n\r\n #Try numbers from 1 to 9\r\n for i in range(1, 10):\r\n if check_action(self.experiment, i, (row, column)):\r\n self.experiment[row][column] = i\r\n self.numbers[row][column].set(i)\r\n self.numbers[row][column].change_number(self.screen, True)\r\n self.update_experiment()\r\n pygame.display.update()\r\n if self.difficulty == 1:\r\n pygame.time.delay(90)\r\n elif self.difficulty == 3:\r\n pygame.time.delay(10)\r\n\r\n if self.solve():\r\n return True\r\n \r\n self.experiment[row][column] = 0\r\n self.numbers[row][column].set(0)\r\n self.update_experiment()\r\n self.numbers[row][column].change_number(self.screen, False)\r\n pygame.display.update()\r\n if self.difficulty == 1:\r\n pygame.time.delay(90)\r\n elif self.difficulty == 3:\r\n pygame.time.delay(10)\r\n\r\n def update_experiment(self):\r\n self.experiment = [[self.numbers[i][j].value for j in range(self.cols)] for i in range(self.rows)]\r\n\r\n def finish(self):\r\n pygame.draw.rect(self.screen, BLUE, (560, 90, 400, 60), 0)\r\n arial_30 = pygame.font.SysFont(\"arial\", 30, bold=True)\r\n text1 = ARIAL_40.render(\"SOLVED!\", 1 ,BLACK)\r\n text2 = arial_30.render(str(self.iterations) + \" iterations\", 1, BLACK)\r\n text3 = arial_30.render(\"Press DEL to go back\", 1, BLACK)\r\n self.screen.blit(text1, (570, 100))\r\n self.screen.blit(text2, (570, 180))\r\n self.screen.blit(text3, (570, 400))\r\n self.draw_board()\r\n pygame.display.update()\r\n\r\n\r\ndef print_start_screen(screen):\r\n screen.fill(BLUE)\r\n pygame.draw.rect(screen, (255, 153, 51), (220, 50, 590, 450), 10)\r\n guide1 = ARIAL_40.render(\"Choose sudoku by pressing\", 1, BLACK)\r\n guide2 = ARIAL_40.render(\"one of the keys listed below\", 1, BLACK)\r\n simple = ARIAL_40.render(\"(1) Simple\", 1, BLACK)\r\n medium = ARIAL_40.render(\"(3) Medium\", 1, BLACK)\r\n hard = ARIAL_40.render(\"(5) Hard*\", 1, BLACK)\r\n info = ARIAL_20.render(\"*Number five is titled to be the worlds hardest sudoku. Solving might take a while.\", 1, BLACK)\r\n screen.blit(guide1, (250, 80))\r\n screen.blit(guide2, (250, 120))\r\n screen.blit(simple, (250, 300))\r\n screen.blit(medium, (250, 360))\r\n screen.blit(hard, (250, 420))\r\n screen.blit(info, (10, 550))\r\n pygame.display.update()\r\n\r\ndef update_screen(screen, board):\r\n text = ARIAL_40.render(\"Press SPACE to start!\", 1, BLACK)\r\n screen.blit(text, (570, 100))\r\n board.draw_board()\r\n\r\ndef next_cell(board):\r\n \"\"\"\r\n Return next empty spot on the board (row, col)\r\n \"\"\"\r\n for i in range(ROWS):\r\n for j in range(COLS):\r\n if board[i][j] == 0:\r\n return (i, j)\r\n\r\n return None\r\n\r\ndef check_action(board, number, position):\r\n \"\"\"\r\n Return True of False if the attempted move is valid or not\r\n \"\"\"\r\n row_pos = position[0]\r\n column_pos = position[1]\r\n \r\n #Check if there is same number in current row or column\r\n for i in range(ROWS):\r\n if board[row_pos][i] == number and column_pos != i:\r\n return False\r\n\r\n for i in range(COLS):\r\n if board[i][column_pos] == number and row_pos != i:\r\n return False\r\n\r\n #Corner position of current cell\r\n cell_x = column_pos // 3\r\n cell_y = row_pos // 3\r\n\r\n for i in range(cell_y*3, cell_y*3 + 3):\r\n for j in range(cell_x * 3, cell_x*3 + 3):\r\n if board[i][j] == number and (i,j) != position:\r\n return False\r\n\r\n return True\r\n\r\n\r\ndef main():\r\n start_screen = True\r\n finished = False\r\n screen = pygame.display.set_mode(SIZE)\r\n pygame.display.set_caption(TITLE)\r\n key = 1\r\n sudoku = Grid(9, 9, 540, 540, screen, key)\r\n\r\n running = True\r\n while running:\r\n for event in pygame.event.get():\r\n if event.type == pygame.QUIT:\r\n running = False\r\n if event.type == pygame.KEYDOWN:\r\n if event.key == pygame.K_1:\r\n key = 1\r\n start_screen = False\r\n if event.key == pygame.K_3:\r\n key = 3\r\n start_screen = False\r\n if event.key == pygame.K_5:\r\n key = 5\r\n start_screen = False\r\n if event.key == pygame.K_SPACE and start_screen == False:\r\n pygame.draw.rect(screen, BLUE, (560, 90, 440, 60), 0)\r\n text = ARIAL_40.render(\"Solving...\", 1, BLACK)\r\n screen.blit(text, (570, 100))\r\n sudoku.solve()\r\n finished = True\r\n if event.key == pygame.K_DELETE:\r\n start_screen = True\r\n finished = False\r\n\r\n if start_screen:\r\n print_start_screen(screen)\r\n elif not finished:\r\n sudoku = Grid(9, 9, 540, 540, screen, key)\r\n screen.fill(BLUE)\r\n pygame.draw.rect(screen, BLACK, (0, 0, 540, 540), 0)\r\n update_screen(screen, sudoku)\r\n pygame.display.update()\r\n\r\nmain()\r\npygame.quit()","sub_path":"Sudoku_Solver.py","file_name":"Sudoku_Solver.py","file_ext":"py","file_size_in_byte":9902,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"445864452","text":"\"\"\"\n\nAuthor - Benjamin Townsend\n\nUnless explicitly stated in the Doc-string all code that follows was written\nby the Author.\n\"\"\"\nimport codecs\nimport string\nfrom random import shuffle\nimport numpy as np\nimport sys\n_TRAIN_SET = \"train.csv\"\n_TEST_SET = \"test.csv\"\n\nUNKNOWN_THRESHOLD = 100\n\n__UNK__ = \"__UNK__\"\n__PAD__ = \"__PAD__\"\n__EOU__ = \"__EOU__\"\n__GO__ = \"__GO__\"\n\ndef strip_punctuation_and_case(s):\n \"\"\"\n Args: \n s : A sentence in the form of a python string. \n\n Returns:\n A python list of the words in string s with any case and punctuation\n removed. For example:\n strip_punctuation_and_case(\"Hello, my name is Ben!!\")\n would return [\"hello\",\"my\",\"name\",\"is\",\"ben\"]\n\n \"\"\"\n return [word.lower() for word in s.translate(\n str.maketrans('', '', string.punctuation)).split(\" \")]\n\n\nclass YahooAnswersDataStore:\n def __init__(self,\n train_file_path,\n test_file_path,\n max_sentence_length=50,\n vocab_filename=\"CNNVocabulary.txt\"):\n \"\"\"\n Given file paths to csv files where each row is in the form:\n , \n The format used is a \"loose\" CSV whereby the rightmost comma is the\n separating comma. This allows the utterance to contain commas.\n\n Designed for use with the Yahoo answers data sets as preprocessed by\n XMLEater.py but could be used for any data] in this form.\n\n Args:\n train_file_path : a string with a relative path to a training set.\n test_file_path : a string with a relative path to a testing set.\n max_sentence_length: An integer for the longest allowed sentences, \n anything longer will be truncated. Anything shorter will be \n vocab_filename: a string with a relative path to a file whereby the\n vocabulary should be saved. It is saved as a text file with a word \n per line.\n \"\"\"\n self.train_file = codecs.open(train_file_path, 'r', \"utf-8\")\n self.test_file = codecs.open(test_file_path, 'r', \"utf-8\")\n\n self.__enumerate_vocabulary(vocab_filename)\n self.__enumerate_categories()\n self.max_sentence_length = max_sentence_length\n\n self.__generate_data_set()\n\n self.train_batch_count = 0\n self.test_batch_count = 0\n\n def __enumerate_categories(self):\n \"\"\"\n This takes the dataset and extracts categories and generates a set of\n dictionaries:\n cat_to_num\n num_to_cat\n to map categories to their integer representation and back again.\n\n Args:\n None\n Returns:\n None\n \"\"\"\n categories = {}\n\n for line in self.train_file:\n categories[line.strip().split(',')[-1]] = 1 \n\n for line in self.test_file:\n categories[line.strip().split(',')[-1]] = 1 \n\n self.train_file.seek(0) #reset the file pointer.\n self.test_file.seek(0)\n\n categories_list = list(categories.keys())\n\n categories_list.sort() \n #sorting allows a reproducable order\n self.cat_to_num = {}\n self.num_to_cat = {}\n\n for i, cat in enumerate(categories_list):\n self.cat_to_num[cat] = i\n self.num_to_cat[i] = cat\n self.num_classes = len(categories_list)\n\n def __enumerate_vocabulary(self, vocab_filename):\n \"\"\"\n Reads the files and assigns numerical values each word, will take out any \n words that occour less than UNKNOWN_THRESHOLD times. The aim of this is to\n remove uncommon words that do not occour frequenctly for the classifier to \n learn propperly and whos negative impact from \"cluttering\" the vocabulary\n is more prominant than the benfits of that word.\n Args:\n vocab_filename : a string with a relative path to a file whereby the\n vocabulary should be saved. It is saved as a text file with a word \n per line.\n Returns:\n None\n \"\"\"\n vocab = {}\n #Takes each line of the file, then each word in that line. \n #Note - only the training set is evaluated for vocabulary.\n for line in self.train_file:\n utterance = line.strip().rsplit(',', 1)[0]\n for word in strip_punctuation_and_case(utterance):\n if(word.lower() in vocab):\n vocab[word.lower()] += 1\n else:\n vocab[word.lower()] = 1\n\n self.train_file.seek(0)\n #remove uncommon words\n #the reason a list is created is that this loop removes items from vocab\n for key in list(vocab.keys()):\n if(vocab[key]) <= UNKNOWN_THRESHOLD:\n vocab.pop(key)\n\n vocab[__UNK__] = 1 #Add unknown and pad values.\n vocab[__PAD__] = 1\n\n vocab = list(vocab.keys())\n\n self.vocab_size = len(vocab)\n vocab.sort() \n #sorting ro create a reproducable order.\n self.word_to_num = {}\n self.num_to_word = {}\n\n #produce the dictionaries.\n for i,word in enumerate(vocab):\n self.word_to_num[word] = i\n self.num_to_word[i] = word\n\n #write the vocab to file for use by the Seqence to Sequence model.\n vocab_file = codecs.open(vocab_filename, \"w\", \"utf-8\")\n [vocab_file.write(word + \"\\n\") for word in vocab]\n vocab_file.close()\n\n self.pad_val = self.word_to_num[__PAD__]\n\n def __pad_to_length(self, data, length):\n \"\"\"\n Args:\n data : A python list of tuples, of the form (,)\n length : The length that the utterances should be padded to.\n Returns:\n Returns the padded utterance and the targets, now in numpy arrays \n \"\"\"\n utterances = np.zeros((len(data), length))\n targets = np.zeros(len(data))\n\n for i,datum in enumerate(data):\n utterances[i] = np.array(datum[0]+[self.pad_val] * (length-len(datum[0])))\n targets[i] = datum[1]\n\n return utterances, targets\n\n def __generate_data_set(self):\n \"\"\"\n Taking the values assigned to categories and the vocabulary does a final \n pass over the file, reading and convering the data into integer values \n ready to be fed into a classifier.\n\n Args:\n None\n Returns:\n None\n \"\"\"\n train = []\n test = []\n\n for line in self.train_file:\n line_proc = line.strip().rsplit(',', 1)\n try:\n train.append(\n (sentence_to_ints(\n line_proc[0], self.word_to_num)[: self.max_sentence_length],\n self.cat_to_num[line_proc[1]]))\n except:\n pass \n #Some utterances do not seem to have catagories associated with them\n #this is likely a problem with XMLEater.py however this quick fix \n #works for now.\n\n for line in self.test_file:\n line_proc = line.strip().rsplit(',',1)\n test.append(\n (sentence_to_ints(\n line_proc[0],self.word_to_num)[:self.max_sentence_length],\n self.cat_to_num[line_proc[1]]))\n\n\n self.sentence_length = max([len(t[0]) for t in train+test])\n\n self.raw_test_data = test\n self.raw_train_data = train\n\n self.shuffle_and_regenerate_data()\n\n self.raw_train_data = None\n self.raw_test_data = None\n\n\n def int_to_category(self,num):\n \"\"\"\n Performs the Lookup for the values assigned to categories to their\n category names.\n Args:\n num : An integer corresponding to a word in the vocabulary.\n Returns:\n Returns the coresponding category string.\n \"\"\"\n return self.num_to_cat[num]\n\n def category_to_int(self,category):\n \"\"\"\n Performs the lookup from string category to the coresponding integer.\n \"\"\"\n return self.cat_to_num[category]\n\n def shuffle_and_regenerate_data(self):\n \"\"\"\n Shuffles the dataset.\n \"\"\"\n shuffle(self.raw_test_data)\n shuffle(self.raw_train_data)\n\n self.test_data,self.test_targets = self.__pad_to_length(\n self.raw_test_data,self.sentence_length)\n\n self.train_data,self.train_targets = self.__pad_to_length(\n self.raw_train_data,self.sentence_length)\n\n def get_batch(self,size = 100,train = True):\n \"\"\"\n Returns a batch of a given size from either the test or the training sets.\n Args:\n size : The number of pieces of data in the batch.\n train : A boolean value, True to return training batches, \n False to return testing batches.\n Returns:\n Returns a 2D array of sentences X batchsize\n and a 1D array of targets size batchsize.\n \"\"\"\n if(train):\n self.train_batch_count=(size+self.train_batch_count)%len(self.train_data)\n return (\n self.train_data[self.train_batch_count-size:self.train_batch_count],\n self.train_targets[self.train_batch_count-size:self.train_batch_count])\n else:\n self.test_batch_count=(size+self.test_batch_count)%len(self.test_data)\n return (\n self.test_data[self.test_batch_count-size:self.test_batch_count],\n self.test_targets[self.test_batch_count-size:self.test_batch_count])\n\n\nclass UseNetDataStore:\n def __init__(self,\n lines_used = 45000000,\n percentage_in_test = 10,\n max_sentence_len= 50,\n context_encoder_vocab = None,\n file = None):\n \"\"\"\n This class will process and store a part of the UseNet corpus for \n training a conversational language model on.\n\n Args:\n lines_used : this is the number of lines of the file that should be\n processed and trained on.\n percentage_in_test : the percentage of the lines_used that should be \n put into a testing set.\n max_sentence_len : the maximum length of the context delivered by train\n batch methods.\n context_encoder_vocab : This is the path to a file of vocabulary used by \n the context encoder. \n \"\"\"\n if(file is None):\n file = \"./mini_UseNet.txt\"\n \n if(context_encoder_vocab is not None):\n self.context_vocab_file = codecs.open(context_encoder_vocab,'r',\"utf-8\")\n else:\n self.context_vocab_file = None\n\n self.utterances = []\n self.test_context = None\n self.test_targets = None\n self.train_context = None\n self.train_targets = None\n self.max_sentence_len = max_sentence_len\n\n self.__load_usenet(file,lines_used)\n self.__enumerate_vocabulary()\n self.go_num = self.word_to_num[__GO__]\n self.__generate_data_set(percentage_in_test)\n #train and test batch counters.\n self.tr_batch_count = 0\n self.te_batch_count = 0\n\n def __load_usenet(self,file,batch_size):\n \"\"\"\n This method takes a copy of the usenet database, a single file of \n conversation, sepparated by an end of turn marker and processes it into a \n list of utterances. \n\n Args: \n file : a relative file path to the usenet database.\n batch_size : the amount of the file that will be processed.\n \"\"\"\n f = codecs.open(file,\"r\",\"cp437\")\n buff = \"\"\n counter = 0\n \n for line in f:\n if(line == \"---END.OF.DOCUMENT---\\n\"):\n self.utterances.append(buff)\n buff = \"\"\n continue\n counter+=1\n if(counter ==batch_size):\n break\n buff+=line\n\n\n for i,s in enumerate(self.utterances):\n s.split(':', 1)[-1].strip(\"\\n\") #takes the bit after the \"somebody said:\" \n self.utterances[i] = [word.lower().strip() for word in s.translate(\n str.maketrans('','',string.punctuation)).split(\" \") if word!='']\n self.utterances[i].append(__EOU__)\n\n\n def __enumerate_vocabulary(self):\n \"\"\"\n Reads the files and assigns numerical values each word, will take out any \n words that occour less than UNKNOWN_THRESHOLD times. The aim of this is to\n remove uncommon words that do not occour frequenctly for the classifier to\n learn propperly and whos negative impact from \"cluttering\" the vocabulary \n is more prominant than the benfits of that word.\n\n Args:\n None\n Returns:\n None\n \"\"\"\n vocab = {}\n for u in self.utterances:\n\n for word in u:\n if(word.lower() in vocab):\n vocab[word.lower()]+=1\n else:\n vocab[word.lower()]=1\n #remove uncommon words\n for key in list(vocab.keys()): #ineficcient but required??\n if(vocab[key]) <=UNKNOWN_THRESHOLD:\n vocab.pop(key)\n\n vocab[__UNK__] = 1\n vocab[__PAD__] = 1\n vocab[__EOU__] = 1 \n vocab[__GO__] = 1\n\n vocab = list(vocab.keys())\n self.vocab_size = len(vocab)\n vocab.sort() \n #sorting allows a reproducable order\n self.word_to_num = {}\n self.num_to_word = {}\n for i,word in enumerate(vocab):\n self.word_to_num[word] = i\n self.num_to_word[i] = word\n\n self.pad_val = self.word_to_num[__PAD__]\n self.context_word_to_num={}\n\n if(self.context_vocab_file is not None):\n for i,word in enumerate(self.context_vocab_file):\n self.context_word_to_num[word.strip()] = i \n self.context_vocab_file.close()\n else:\n self.context_word_to_num = None\n\n def __pad_to_length_and_convert_to_np(self,\n data,\n context_length,\n response_length):\n \"\"\"\n Args:\n data : A python list of tuples, the utterance in the first element and \n the category in the seccond element.\n length : The length that the utterances should be padded to.\n Returns:\n Returns the padded utterance and the targets, now in seperate numpy arrays. \n\n \"\"\"\n utterances = np.zeros((len(data),context_length))\n targets = np.zeros((len(data),response_length))\n cnn_utterances = np.zeros((len(data),context_length))\n for i,datum in enumerate(data):\n utterances[i] = np.array(datum[0]+[self.pad_val]*(\n context_length-len(datum[0])))[:context_length][::-1] #reversed\n\n targets[i] = np.array(datum[1]+[self.pad_val]*(\n response_length-len(datum[1])))[:response_length] #trim long ones\n\n cnn_utterances[i] = np.array(datum[2]+[self.pad_val]*(\n context_length-len(datum[2])))[:context_length] #not_reversed\n\n return utterances,targets,cnn_utterances\n\n def __generate_data_set(self,percentage_in_test):\n \"\"\"\n Taking the values assigned to categories and the vocabulary does a final\n pass over the file reading and convering the data into integer values ready\n to be fed into a classifier.\n\n Args:\n None\n Returns:\n None\n \"\"\"\n num_in_test = int(percentage_in_test*len(self.utterances)/100)\n train_seg = self.utterances[num_in_test:]\n test_seg = self.utterances[:num_in_test]\n\n train = []\n test = []\n\n CNN_train = []\n CNN_test = []\n #context is last 2 utterances response is next utterance.\n\n for i,utt in enumerate(train_seg):\n train_seg[i] = sentence_to_ints(utt,self.word_to_num)\n CNN_train.append(sentence_to_ints(utt,self.context_word_to_num))\n if(i>=3):\n #context,targets,CNN-in\n train.append((train_seg[i-2]+train_seg[i-1],\n train_seg[i],CNN_train[i-2]+CNN_train[i-1]))\n\n for i,utt in enumerate(test_seg):\n test_seg[i] = sentence_to_ints(utt,self.word_to_num)\n CNN_test.append(sentence_to_ints(utt,self.context_word_to_num))\n if(i>=3):\n test.append((test_seg[i-2]+test_seg[i-1],\n test_seg[i],CNN_test[i-2]+CNN_test[i-1]))\n \n\n\n\n self.context_length = min([max([len(t[0]) for t in train+test]),\n self.max_sentence_len])\n self.response_length = min([max([len(t[1]) for t in train+test]),\n self.max_sentence_len])\n\n self.raw_test_data = test\n self.raw_train_data = train\n\n self.shuffle_and_regenerate_data()\n\n\n def shuffle_and_regenerate_data(self):\n \"\"\"\n Shuffles the dataset.\n \"\"\"\n shuffle(self.raw_test_data)\n shuffle(self.raw_train_data)\n\n data = self.__pad_to_length_and_convert_to_np(self.raw_test_data,\n self.context_length,\n self.response_length)\n self.test_context ,self.test_targets,self.CNN_test_context = data\n\n data = self.__pad_to_length_and_convert_to_np(self.raw_train_data,\n self.context_length,\n self.response_length)\n self.train_context,self.train_targets,self.CNN_train_context = data \n\n\n self.decoder_ins = None\n\n def get_batch(self,size = 50,train = True):\n \"\"\"\n Returns a batch of a given size from either the test of the training sets.\n Args:\n size : The number of pieces of data in the batch.\n train = True : A boolean value, true to return training batches,\n false to return testing batches.\n Returns:\n Returns 2D array of sentencesXbatchsize - the input for the seq2seq model\n 1D array of targets size batchsize.\n 2D array - the input for the CNN model (if used)\n \n\n \"\"\"\n sys.stdout.flush()\n\n #set only the first time and whenever the batchsize changes.\n if(self.decoder_ins is None or len(self.decoder_ins)!= size):\n self.decoder_ins = np.array([np.array([self.go_num]\n +(self.response_length-1)\n *[self.pad_val]) for _ in range(size)])\n\n if(train):\n self.tr_batch_count=size+(size+self.tr_batch_count)%\\\n (len(self.train_context)-size)\n\n return (\n self.train_context[self.tr_batch_count-size:self.tr_batch_count],\n self.train_targets[self.tr_batch_count-size:self.tr_batch_count],\n self.decoder_ins,\n self.CNN_train_context[self.tr_batch_count-size:self.tr_batch_count])\n\n else: \n self.te_batch_count=size+(size+self.te_batch_count)%\\\n (len(self.test_context)-size)\n return (\n self.test_context[self.te_batch_count-size:self.te_batch_count],\n self.test_targets[self.te_batch_count-size:self.te_batch_count],\n self.decoder_ins,\n self.CNN_test_context[self.te_batch_count-size:self.te_batch_count])\n\n\ndef sentence_to_ints(sentence, encoder):\n \"\"\"\n This method takes a sentence and converts it to a list of intgers by using \n the vocabulary lookups that were generated by enumerate vocabulary. \n It first strips case and punctuation.\n\n Args:\n sentence : A python sentence\n encoder : the dictionary used to make the conversion\n Returns:\n Returns a python list of integers coresponding to each word.\n\n \"\"\"\n output = []\n for word in sentence:\n if encoder is not None and word in encoder:\n output.append(encoder[word])\n else:\n output.append(encoder[__UNK__])\n\n return output\n\ndef ints_to_sentence(ints, encoder):\n \"\"\"\n Takes a list of integers coresponding to words in the vocabulary and decodes\n them into a list of strings, each element of the list is a word,\n __PAD__ or __UNK__\n \"\"\"\n return [encoder[x] for x in ints]\n \n\n\n#print(UseNetDataStore().get_batch(1))\n#d = YahooAnswersDataStore(TRAIN_SET,TEST_SET)\n#print(d.ints_to_sentence(d.get_batch(100)[0][0]))\n\n","sub_path":"data_prep.py","file_name":"data_prep.py","file_ext":"py","file_size_in_byte":18824,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"150739051","text":"import tensorflow as tf\nimport numpy as np\nfrom sklearn.cluster import KMeans\nimport os\nimport time\n\n\n#ARD kernel\nMATRIX_JITTER = 1e-6\nNN_MAX = 20.0\nFLOAT_TYPE = tf.float32\nDELTA_JITTER= 1e-6\n\ndef kernel_cross_tf(tf_Xm, tf_Xn, tf_log_amp, tf_log_lengthscale, return_raw_K = False):\n '''\n :param tf_Xm: [m, d]\n :param tf_Xn: [n,d]\n :param tf_log_amp:\n :param tf_log_lengthscale:\n :return: K [ m,n]\n '''\n\n '''\n tf_Xm = tf.matmul(tf_Xm, tf.linalg.tensor_diag(1.0 / tf.exp(0.5 * tf.reshape(tf_log_lengthscale, [-1]))))\n tf_Xn = tf.matmul(tf_Xn, tf.linalg.tensor_diag(1.0 / tf.exp(0.5 * tf.reshape(tf_log_lengthscale, [-1]))))\n col_norm1 = tf.reshape(tf.reduce_sum(tf_Xm * tf_Xm, 1), [-1, 1])\n col_norm2 = tf.reshape(tf.reduce_sum(tf_Xn * tf_Xn, 1), [-1, 1])\n K = col_norm1 - 2.0 * tf.matmul(tf_Xm, tf.transpose(tf_Xn)) + tf.transpose(col_norm2)\n if return_raw_K:\n return tf.exp( -0.5 * K + tf_log_amp), K\n else:\n return tf.exp( -0.5 * K + tf_log_amp)\n '''\n lengthscale = 1.0 / tf.exp(tf_log_lengthscale)\n X = tf.expand_dims(tf_Xm, 1)\n Y = tf.expand_dims(tf_Xn, 0)\n K = (X - Y) *(X - Y) * tf.reshape( lengthscale, [-1])\n K = tf.reduce_sum(K, axis=-1)\n K = tf.exp(-0.5 * K + tf_log_amp)\n return K\n\ndef KL_q_p_tf( Kmm, Ltril, mu, k):\n '''\n return KL( q(alpha) || p( alpha))\n :param Kmm:\n :param Kmm_inv:\n :param Sig: Ltril@Ltril.T\n :param Ltril:\n :param mu: [ length, 1]\n :return:\n '''\n\n #KL = 0.5 * tf.linalg.trace( Kmm_inv @ ( Sig + mu@tf.transpose( mu)))\n KL = 0.5 * tf.linalg.trace( tf.linalg.solve( Kmm, Ltril @ tf.transpose( Ltril) + mu@tf.transpose( mu) ))\n KL = KL - k * 0.5 + 0.5 * tf.linalg.logdet( Kmm) - tf.reduce_sum( tf.log( tf.abs( tf.linalg.diag_part( Ltril))))\n return KL\n\ndef sample_pst_f_tf(mu_alpha, Ltril_alpha,Kmm, Knm, log_amp, jitter, return_alpha = False ):\n '''\n\n :param mu_alpha:\n :param Ltril_alpha:\n :param Kmm:\n :param Knm:\n :param log_amp:\n :param jitter:\n :param return_alpha:\n :return:\n '''\n #sample alpha\n z = tf.random.normal( mu_alpha.shape, dtype=FLOAT_TYPE)\n alpha = mu_alpha + Ltril_alpha @ z\n\n z_f = tf.random.normal([Knm.shape[0].value, 1], dtype=FLOAT_TYPE)\n stdev = tf.sqrt( tf.exp( log_amp) + jitter - tf.reduce_sum( Knm * tf.transpose( tf.linalg.solve( Kmm, tf.transpose(Knm))), axis=1, keepdims=True ))\n f = Knm @ tf.linalg.solve( Kmm,alpha) + stdev*z_f\n\n if return_alpha:\n return f,alpha\n else:\n return f\n\ndef sample_pst_f_tf_MLE(mu_alpha,Kmm, Knm ):\n '''\n\n :param mu_alpha:\n :param Ltril_alpha:\n :param Kmm:\n :param Knm:\n :param log_amp:\n :param jitter:\n :param return_alpha:\n :return:\n '''\n #sample alpha\n alpha = mu_alpha\n f = Knm @ tf.linalg.solve( Kmm,alpha)\n return f\n\n\ndef concat_embeddings( U, ind):\n '''\n get the concatenated embeddings\n :param U: list of embeddings [ nmod, num_item, rank]\n :param ind: index to embedings [ batch, nmod]\n :return:\n '''\n nmod = len(U)\n X = tf.concat([tf.gather(U[k], ind[:, k]) for k in range(nmod)], 1)\n return X\n\ndef log_CP_base_rate( U, ind):\n nmod = len(U)\n components = [tf.gather(U[k], ind[:, k]) for k in range(nmod)]\n cp = tf.reduce_prod( components, axis=0)\n base_rate = tf.reduce_sum( cp, axis=1, keepdims=True)\n return base_rate\n\ndef assemble_time_decay_GP_input( Xi, Xn, len_X, len_N):\n Xi = tf.expand_dims( Xi, 1)\n Xn = tf.expand_dims( Xn, 0)\n\n Xi = tf.tile( Xi, [1, len_N,1])\n Xn = tf.tile( Xn, [len_X, 1,1])\n input_tensor = tf.concat( [ Xi,Xn] ,axis=2)\n return input_tensor\n\n\nclass DataGenerator:\n def __init__(self, X, y=None, shuffle = True):\n self.X = X\n self.y = y\n self.shuffle = shuffle\n #self.repeat = repeat\n\n self.num_elems = len(X)\n self.curr_idx = 0\n\n if self.shuffle:\n self.random_idx = np.random.permutation(self.num_elems)\n else:\n self.random_idx = np.arange( self.num_elems)\n\n\n def draw_last(self, return_idx = False):\n '''\n draw last batch sample\n :return:\n '''\n if self.y is not None:\n if return_idx:\n return self.X[self.last_arg_idx], self.y[self.last_arg_idx], self.last_arg_idx\n else:\n return self.X[self.last_arg_idx], self.y[self.last_arg_idx]\n else:\n if return_idx:\n return self.X[self.last_arg_idx], self.last_arg_idx\n else:\n return self.X[self.last_arg_idx]\n\n\n def draw_next(self, batch_size, return_idx = False):\n if batch_size > self.num_elems:\n raise NameError(\"Illegal batch size\")\n\n if batch_size + self.curr_idx > self.num_elems:\n # shuffle\n\n if self.shuffle:\n self.random_idx = np.random.permutation(self.num_elems)\n else:\n self.random_idx = np.arange(self.num_elems)\n self.curr_idx = 0\n\n arg_idx = self.random_idx[self.curr_idx: self.curr_idx + batch_size]\n self.last_arg_idx = arg_idx\n\n self.curr_idx += batch_size\n\n if self.y is not None:\n if return_idx:\n return self.X[arg_idx], self.y[arg_idx], arg_idx\n else:\n return self.X[arg_idx], self.y[arg_idx]\n else:\n if return_idx:\n return self.X[arg_idx], arg_idx\n else:\n return self.X[arg_idx]\n\n\ndef get_end_time( train_y, start_idx, window_size):\n '''\n :param train_y:\n :param start_idx: [batch_size,]\n :param window_size: scalar\n :return:\n '''\n upper_bound = len( train_y) - 1\n upper_idx = start_idx + window_size\n upper_idx = np.minimum( upper_idx, upper_bound )\n end_y = train_y[ upper_idx]\n\n return end_y\n\ndef generate_inner_event_y( outter_idx, train_ind, train_y, window_size):\n lower_idx = outter_idx - window_size\n\n ind_acc = []\n y_acc = []\n\n for i in range( len( outter_idx)):\n li = lower_idx[i]\n ri = outter_idx[i]\n if li >=0:\n idxes = np.arange( li, ri)\n else:\n idxes = list( range( 0, ri))\n idxes = [-1] * ( -li) + idxes\n idxes = np.array( idxes)\n\n ind = np.expand_dims ( train_ind[ idxes],0) #[1, 300, nmod]\n y = train_y[ idxes].reshape( ( 1,-1)) #[ 1, 300]\n\n ind_acc.append( ind)\n y_acc.append( y)\n\n ind_acc = np.vstack( ind_acc)\n y_acc = np.vstack( y_acc)\n\n return ind_acc, y_acc\n\n\n\ndef init_base_gp_pseudo_inputs(U, ind, pseudo_num):\n nmod = ind.shape[1]\n uniq_inds = np.unique( ind, axis=0)\n part = [U[k][uniq_inds[:,k],:] for k in range(nmod)]\n X = np.hstack(part)\n kmeans = KMeans(n_clusters=pseudo_num, random_state=0, n_jobs= 7,).fit(X)\n return kmeans.cluster_centers_\n\ndef init_decay_gp_pseudo_inputs(U, ind, pseudo_num):\n nmod = ind.shape[1]\n uniq_inds = np.unique( ind, axis=0)\n\n N = len( uniq_inds)\n\n random_arg = np.random.choice( range( N),pseudo_num)\n sub_inds_1 = uniq_inds[ random_arg]\n\n random_arg = np.random.choice(range(N), pseudo_num)\n sub_inds_2 = uniq_inds[ random_arg]\n\n X1 = np.hstack( [U[k][sub_inds_1[:,k],:] for k in range(nmod)])\n X2 = np.hstack( [U[k][sub_inds_2[:,k],:] for k in range(nmod)])\n\n #Cartisian Product\n X1 = np.tile( X1, [ pseudo_num,1])\n X2 = np.repeat( X2, pseudo_num, axis=0)\n\n X = np.hstack( [X1,X2])\n kmeans = KMeans(n_clusters=pseudo_num, random_state=0, n_jobs= 7,).fit(X)\n return kmeans.cluster_centers_\n\n\n#Loading data set\ndef load_dataSet( data_name, path_dataSet_folder = \"../Data\"):\n valid_names = {'article'}\n\n if data_name not in valid_names:\n raise NameError(\"No such data set: %s. valid data set: %s\" % ( data_name, str( valid_names)))\n\n if data_name == 'article':\n ind = np.load( os.path.join(path_dataSet_folder, 'article_70k_inds.npy'))\n y = np.load( os.path.join(path_dataSet_folder, 'article_70k_ys.npy')).reshape(-1, 1)\n\n hours = 3600\n y = y / hours\n\n NUM_TRAIN = 50000\n\n train_ind = ind[:NUM_TRAIN]\n train_y = y[:NUM_TRAIN]\n\n test_ind = ind[NUM_TRAIN:]\n test_y = y[NUM_TRAIN:]\n\n return (ind, y), (train_ind, train_y), (test_ind, test_y)\n\ndef log_results( log_file_path, data_name, rank, lr, test_log_llk ):\n with open( log_file_path, 'a') as log_file:\n date = time.asctime()\n\n log_file.write(date + '\\n')\n log_file.write( \"data set = %s, rank = %d, lr = %f\\n\" % ( data_name, rank, lr))\n log_file.write('test_log_llk:\\n')\n for log_llk in test_log_llk:\n log_file.write( '%g\\n' % log_llk)\n log_file.write('\\n')\n\ndef extract_event_tensor_Reileigh( ind, y):\n '''\n Precompute Event tensor information for Rayleigh process\n :param ind:\n :param y:\n :return: uniq_inds, n_i: len of seq, sq_sum:sum of square of time diff, log_sum: sum of log time diff\n '''\n if len( ind) != len( y):\n raise NameError('lengths not match')\n\n N = len(ind)\n\n event_tensor = {}\n for i in range( N):\n idx = tuple( ind[i])\n if idx in event_tensor:\n event_tensor[idx].append( y[i,0])\n else:\n event_tensor[idx] = [y[i,0]]\n\n T0, T1 = y[0,0], y[-1,0]\n\n uniq_inds = [ * event_tensor.keys()]\n uniq_inds = np.array( uniq_inds)\n time_seq = [ * event_tensor.values()]\n\n if len( uniq_inds) != len( time_seq):\n raise NameError('K V len not match')\n\n N_seq = len( uniq_inds)\n\n n_i = []\n sq_sum = []\n log_sum = []\n for i in range( N_seq):\n seq = np.array( time_seq[i])\n n_i.append( len( seq))\n\n #insert beginning timestamp\n if T0 not in seq:\n seq = np.insert( seq, 0, T0)\n\n shift_seq = np.roll( seq, -1 )\n\n diff = (shift_seq - seq)[:-1]\n diff = diff[ diff > 0]\n\n log_sum.append( np.sum( np.log( diff)))\n sq_sum.append( 0.5 * np.sum( diff * diff) + 0.5 * (T1 - seq[-1]) ** 2)\n\n n_i = np.array( n_i).reshape(( -1,1))\n sq_sum = np.array( sq_sum).reshape( ( -1,1))\n log_sum = np.array( log_sum).reshape( ( -1,1))\n\n return uniq_inds, n_i, sq_sum, log_sum\n\ndef init_log_file( log_file_path, data_name, model_config, mode = 'a'):\n log_file = open( log_file_path, mode = mode)\n\n date = time.asctime()\n\n log_file.write('\\n\\n' + date + '\\n')\n log_file.write(\"data set = %s\\n\" %data_name)\n log_file.write('model config:\\n%s\\n' %( str( model_config)))\n\n return log_file\n\nif __name__ == '__main__':\n (ind, y), (train_ind, train_y), (test_ind, test_y) = load_dataSet('article', '../Data')\n #uni_ind, n_i, sq_sum, log_sum = extract_event_tensor_Reileigh( train_ind, train_y)\n print( train_ind.shape, train_y.shape, test_ind.shape, test_y.shape)\n\n print( 'train_ind[:10]:\\n',train_ind[:10])\n print('train_y[:10]:\\n', train_y[:10])\n print( y[-1,0] - y[0,0])\n\n print( \"Done\")\n\n\n\n\n\n\n\n\n\n\n\n\n","sub_path":"Code/utils_funcs.py","file_name":"utils_funcs.py","file_ext":"py","file_size_in_byte":11058,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"512290989","text":"# Copyright 2017 Google Inc. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS-IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\"\"\"Unit tests for blockable handlers.\"\"\"\nimport datetime\nimport httplib\n\nimport mock\nimport webapp2\n\nfrom google.appengine.ext import ndb\n\nfrom upvote.gae.datastore import test_utils\nfrom upvote.gae.datastore import utils\nfrom upvote.gae.datastore.models import base\nfrom upvote.gae.datastore.models import bit9\nfrom upvote.gae.datastore.models import santa\nfrom upvote.gae.modules.upvote_app.api.handlers import blockables\nfrom upvote.gae.shared.common import basetest\nfrom upvote.shared import constants\n\n\nclass BlockablesTest(basetest.UpvoteTestCase):\n \"\"\"Base class for Audit Logs handler tests.\"\"\"\n\n def setUp(self, app):\n super(BlockablesTest, self).setUp(wsgi_app=app)\n\n self.bit9_blockable = test_utils.CreateBit9Binary(\n id='zzzzzzzzzaaa',\n id_type=constants.ID_TYPE.SHA256,\n file_name='Mac.app.exe')\n self.bit9_blockable2 = test_utils.CreateBit9Binary(\n id='zzzzzzzzzbbb',\n id_type=constants.ID_TYPE.SHA256,\n file_name='app.exe')\n\n self.generic_blockable = test_utils.CreateBlockable(\n file_name='Not4Mac.exe',\n state=constants.STATE.SUSPECT)\n self.santa_blockable = test_utils.CreateSantaBlockable(\n publisher='Arple',\n product_name='New Shiny',\n flagged=True)\n self.santa_certificate = test_utils.CreateSantaCertificate(\n id_type=constants.ID_TYPE.SHA256,\n common_name='Best Cert Ever',\n organization='Totally Legit CA')\n\n self.PatchValidateXSRFToken()\n\n\nclass BlockableQueryHandlerTest(BlockablesTest):\n\n def setUp(self):\n app = webapp2.WSGIApplication([\n webapp2.Route('//',\n handler=blockables.BlockableQueryHandler)])\n super(BlockableQueryHandlerTest, self).setUp(app)\n\n def testAdminGetList(self):\n \"\"\"Admin getting list of all blockables.\"\"\"\n with self.LoggedInUser(admin=True):\n response = self.testapp.get('/all/all')\n\n output = response.json\n\n self.assertIn('application/json', response.headers['Content-type'])\n self.assertIsInstance(output['content'], list)\n self.assertEqual(len(output['content']), 5)\n\n def testAdminGetListWithPlatform(self):\n \"\"\"Admin getting list of all blockables on a specific platform.\"\"\"\n with self.LoggedInUser(admin=True):\n response = self.testapp.get('/santa/certificates')\n\n output = response.json\n\n self.assertIn('application/json', response.headers['Content-type'])\n self.assertIsInstance(output['content'], list)\n self.assertEqual(len(output['content']), 1)\n\n def testUserGetBlockableList(self):\n \"\"\"Normal user getting a list of all blockables.\"\"\"\n\n with self.LoggedInUser():\n self.testapp.get('/all/all', status=httplib.FORBIDDEN)\n\n def testUserGetFlaggedBlockables(self):\n \"\"\"Normal user getting a list of flagged blockables.\"\"\"\n params = {'filter': 'flagged'}\n with self.LoggedInUser():\n self.testapp.get('/all/all', params, status=httplib.FORBIDDEN)\n\n def testUserGetSuspectBlockables(self):\n \"\"\"Normal user getting a list of suspect blockables.\"\"\"\n params = {'filter': 'suspect'}\n with self.LoggedInUser():\n self.testapp.get('/all/all', params, status=httplib.FORBIDDEN)\n\n def testUserGetOwnBlockables(self):\n\n user_1 = test_utils.CreateUser()\n user_2 = test_utils.CreateUser()\n\n # Create two events for this user.\n test_utils.CreateBit9Event(\n self.bit9_blockable,\n executing_user=user_2.nickname,\n host_id='a_host_id',\n parent=utils.ConcatenateKeys(\n user_2.key, ndb.Key('Host', 'a_host_id'),\n self.santa_blockable.key)\n )\n host_id = 'AAAAAAAA-1111-BBBB-2222-CCCCCCCCCCCC'\n test_utils.CreateSantaEvent(\n self.santa_blockable,\n executing_user=user_2.nickname,\n event_type=constants.EVENT_TYPE.ALLOW_UNKNOWN,\n file_name='Product.app',\n file_path='/Applications/Product.app/Contents/MacOs',\n host_id=host_id,\n last_blocked_dt=datetime.datetime(2015, 4, 1, 1, 0, 0),\n first_blocked_dt=datetime.datetime(2015, 4, 1, 1, 0, 0),\n parent=utils.ConcatenateKeys(\n user_2.key, ndb.Key('Host', host_id),\n self.santa_blockable.key)\n )\n # Create one event for another user. This should not be included in\n # the results when fetching blockables for user_2.\n test_utils.CreateBit9Event(\n self.bit9_blockable2,\n executing_user=user_1.nickname,\n file_name='notepad++.exe',\n file_path=r'c:\\program files (x86)\\notepad++',\n host_id='a_host_id',\n last_blocked_dt=datetime.datetime(2015, 5, 1, 1, 0, 0),\n first_blocked_dt=datetime.datetime(2015, 5, 1, 1, 0, 0),\n parent=utils.ConcatenateKeys(\n user_1.key, ndb.Key('Host', 'a_host_id'),\n self.santa_blockable.key)\n )\n\n params = {'filter': 'own'}\n with self.LoggedInUser(user=user_2):\n response = self.testapp.get('/all/all', params)\n\n output = response.json\n\n # Verify that only two blockables (from the two events) are returned to\n # this user.\n self.assertIn('application/json', response.headers['Content-type'])\n self.assertIsInstance(output['content'], list)\n self.assertEqual(len(output['content']), 2)\n\n def testUserGetOwnBlockables_UserHasNoBlockables(self):\n params = {'filter': 'own'}\n with self.LoggedInUser():\n response = self.testapp.get('/all/all', params)\n output = response.json\n\n self.assertIn('application/json', response.headers['Content-type'])\n self.assertIsInstance(output['content'], list)\n self.assertEqual(len(output['content']), 0)\n\n def testAdminGetListOfFlaggedBlockables(self):\n \"\"\"Admin getting a list of flagged blockables.\"\"\"\n params = {'filter': 'flagged'}\n\n with self.LoggedInUser(admin=True):\n response = self.testapp.get('/all/all', params)\n\n output = response.json\n\n self.assertIn('application/json', response.headers['Content-type'])\n self.assertIsInstance(output['content'], list)\n self.assertEqual(len(output['content']), 1)\n\n def testAdminGetListOfSuspectBlockables(self):\n \"\"\"Admin getting a list of flagged blockables.\"\"\"\n params = {'filter': 'suspect'}\n\n with self.LoggedInUser(admin=True):\n response = self.testapp.get('/all/all', params)\n\n output = response.json\n\n self.assertIn('application/json', response.headers['Content-type'])\n self.assertIsInstance(output['content'], list)\n self.assertEqual(len(output['content']), 1)\n\n def testAdminGetQueryByFileName(self):\n \"\"\"Admin searching for a blockable by filename.\"\"\"\n params = {'search': 'Not4Mac.exe', 'searchBase': 'fileName'}\n\n with self.LoggedInUser(admin=True):\n response = self.testapp.get('/all/all', params)\n\n output = response.json\n self.assertIn('application/json', response.headers['Content-type'])\n self.assertTrue(isinstance(output, dict))\n self.assertTrue(isinstance(output['content'], list))\n self.assertEqual(len(output['content']), 1)\n\n def testAdminGetQueryByPublisher(self):\n \"\"\"Admin searching for a blockable by filename.\"\"\"\n params = {'search': 'Arple', 'searchBase': 'publisher'}\n\n with self.LoggedInUser(admin=True):\n response = self.testapp.get('/all/all', params)\n\n output = response.json\n self.assertIn('application/json', response.headers['Content-type'])\n self.assertTrue(isinstance(output, dict))\n self.assertTrue(isinstance(output['content'], list))\n self.assertEqual(len(output['content']), 1)\n\n def testAdminGetQueryByProductName(self):\n \"\"\"Admin searching for a blockable by filename.\"\"\"\n params = {'search': 'New Shiny', 'searchBase': 'productName'}\n\n with self.LoggedInUser(admin=True):\n response = self.testapp.get('/all/all', params)\n\n output = response.json\n self.assertIn('application/json', response.headers['Content-type'])\n self.assertTrue(isinstance(output, dict))\n self.assertTrue(isinstance(output['content'], list))\n self.assertEqual(len(output['content']), 1)\n\n def testAdminGetQueryPlatform(self):\n \"\"\"Admin searching for a blockable by platform.\"\"\"\n params = {'search': 'New Shiny', 'searchBase': 'productName'}\n\n with self.LoggedInUser(admin=True):\n response = self.testapp.get('/santa/binaries', params)\n\n output = response.json\n self.assertIn('application/json', response.headers['Content-type'])\n self.assertTrue(isinstance(output, dict))\n self.assertTrue(isinstance(output['content'], list))\n self.assertEqual(len(output['content']), 1)\n\n def testAdminGetQueryByUnknown(self):\n \"\"\"Admin searching for a blockable by an unknown property.\"\"\"\n params = {'search': 'ProbablyNotReal', 'searchBase': 'notReal'}\n\n with self.LoggedInUser(admin=True):\n self.testapp.get('/all/all', params, status=httplib.BAD_REQUEST)\n\n def testAdminGetQueryBadPlatform(self):\n \"\"\"Admin searching by a property not valid for the specified platform.\"\"\"\n params = {'search': 'DoesntMatter', 'searchBase': 'bundle_id'}\n\n with self.LoggedInUser(admin=True):\n self.testapp.get('/bit9/binaries', params, status=httplib.BAD_REQUEST)\n\n\nclass BlockableHandlerTest(BlockablesTest):\n\n def setUp(self):\n app = webapp2.WSGIApplication(\n [webapp2.Route('/',\n handler=blockables.BlockableHandler)])\n super(BlockableHandlerTest, self).setUp(app)\n\n def testUserGetGenericByID(self):\n \"\"\"Normal user querying for a blockable by hash.\"\"\"\n with self.LoggedInUser():\n response = self.testapp.get('/' + self.generic_blockable.key.id())\n\n output = response.json\n\n self.assertIn('application/json', response.headers['Content-type'])\n self.assertIsInstance(output, dict)\n self.assertEqual(output['fileName'], self.generic_blockable.file_name)\n self.assertIsNone(output.get('operating_system_family'))\n self.assertIn('Blockable', output['class_'])\n\n def testUserGetSantaBlockableByID(self):\n \"\"\"Normal user querying for a blockable by hash.\"\"\"\n with self.LoggedInUser():\n response = self.testapp.get('/' + self.santa_blockable.key.id())\n\n output = response.json\n\n self.assertIn('application/json', response.headers['Content-type'])\n self.assertIsInstance(output, dict)\n self.assertEqual(output['fileName'], self.santa_blockable.file_name)\n self.assertEqual(\n output['operatingSystemFamily'], constants.PLATFORM.MACOS)\n self.assertIn('Blockable', output['class_'])\n self.assertIn('SantaBlockable', output['class_'])\n\n def testUserGetBit9BinaryByID(self):\n \"\"\"Normal user querying for a blockable by hash.\"\"\"\n with self.LoggedInUser():\n response = self.testapp.get('/' + self.bit9_blockable.key.id())\n\n output = response.json\n\n self.assertIn('application/json', response.headers['Content-type'])\n self.assertIsInstance(output, dict)\n self.assertEqual(output['id'], self.bit9_blockable.key.id())\n self.assertEqual(output['fileName'], self.bit9_blockable.file_name)\n self.assertEqual(\n output['operatingSystemFamily'], constants.PLATFORM.WINDOWS)\n self.assertIn('Blockable', output['class_'])\n self.assertIn('Bit9Binary', output['class_'])\n\n def testUserGetSantaCertificateByID(self):\n \"\"\"Normal user querying for a cert by hash.\"\"\"\n with self.LoggedInUser():\n response = self.testapp.get('/' + self.santa_certificate.key.id())\n\n output = response.json\n\n self.assertIn('application/json', response.headers['Content-type'])\n self.assertIsInstance(output, dict)\n self.assertEqual(\n output['commonName'], self.santa_certificate.common_name)\n self.assertIn('Blockable', output['class_'])\n self.assertIn('SantaCertificate', output['class_'])\n\n def AddBlockableToDatastore(self, *args):\n test_utils.CreateSantaBlockable(id='NotYetSynced')\n return mock.Mock(status_code=httplib.OK)\n\n def testUserGetUnknownId_Santa(self):\n with self.LoggedInUser():\n self.testapp.get('/Nonexistent', status=httplib.NOT_FOUND)\n\n def testAdminPostCallRecount(self):\n \"\"\"Admin requesting a recount for a blockable.\"\"\"\n # Create an anomalous global blacklist rule that should be deactivated by\n # the recount.\n rule = test_utils.CreateSantaRule(self.santa_blockable.key)\n self.assertTrue(rule.in_effect)\n\n id_ = self.santa_blockable.key.id()\n params = {'recount': 'recount'}\n with self.LoggedInUser(admin=True):\n response = self.testapp.post('/' + id_, params)\n\n self.assertFalse(rule.key.get().in_effect)\n\n output = response.json\n self.assertIn('application/json', response.headers['Content-type'])\n self.assertIsInstance(output, dict)\n self.assertEqual(output['fileName'], self.santa_blockable.file_name)\n self.assertIn('Blockable', output['class_'])\n\n def testAdminPostReset(self):\n \"\"\"Admin requesting a blockable be reset.\"\"\"\n id_ = self.generic_blockable.key.id()\n params = {'reset': 'reset'}\n\n with self.LoggedInUser(admin=True):\n with mock.patch.object(\n blockables.BlockableHandler, '_reset_blockable') as mock_method:\n _ = self.testapp.post('/' + id_, params)\n mock_method.assert_called_once_with(id_)\n\n def testAdminPostInsertUnknownType(self):\n \"\"\"Admin tries to inject a blockable of unknown type.\"\"\"\n id_ = 'qqqqrrrrsssstttt'\n params = {'type': 'mock_blockable', 'hash': id_}\n\n with mock.patch.object(blockables, 'model_mapping') as mock_mapping:\n mock_mapping.BlockableTypeModelMap.mock_blockable = None\n with self.LoggedInUser(admin=True):\n self.testapp.post('/' + id_, params, status=httplib.BAD_REQUEST)\n\n def testAdminPostInsertExistingID(self):\n \"\"\"Admin tries to inject an existing blockable.\"\"\"\n id_ = self.generic_blockable.key.id()\n params = {'type': 'Blockable', 'hash': id_}\n\n with mock.patch.object(blockables, 'model_mapping'):\n with self.LoggedInUser(admin=True):\n self.testapp.post('/' + id_, params, status=httplib.CONFLICT)\n\n def testAdminPostInsert(self):\n \"\"\"Admin posting a valid blockable.\"\"\"\n id_ = 'qqqqrrrrsssstttt'\n params = {\n 'type': constants.BLOCKABLE_TYPE.SANTA_BINARY,\n 'fileName': 'MacIIci.app',\n 'publisher': 'Arple'}\n mock_model = mock.MagicMock()\n mock_model.get_by_id.return_value = False\n test_blockable = test_utils.CreateBlockable(id=id_)\n mock_model.get_or_insert.return_value = test_blockable\n\n with mock.patch.object(blockables, 'model_mapping') as mock_mapping:\n mock_mapping.BlockableTypeModelMap.SANTA_BINARY = mock_model\n with self.LoggedInUser(admin=True):\n response = self.testapp.post('/%s' % id_, params)\n\n output = response.json\n\n self.assertIn('application/json', response.headers['Content-type'])\n self.assertEqual(output['id'], 'qqqqrrrrsssstttt')\n mock_model.get_or_insert.assert_called_with(\n 'qqqqrrrrsssstttt',\n file_name='MacIIci.app',\n publisher='Arple',\n flagged=False,\n id_type=constants.ID_TYPE.SHA256\n )\n\n def testAdminPostInsert_Note(self):\n \"\"\"Admin posting a valid blockable.\"\"\"\n id_ = 'qqqqrrrrsssstttt'\n params = {\n 'notes': 'foo',\n 'fileName': 'bar',\n 'type': constants.BLOCKABLE_TYPE.SANTA_BINARY}\n\n with self.LoggedInUser(admin=True):\n self.testapp.post('/%s' % id_, params)\n\n blockable = base.Blockable.get_by_id(id_)\n self.assertEqual('bar', blockable.file_name)\n\n self.assertEntityCount(base.Note, 1)\n note = base.Note.query().fetch()[0]\n\n self.assertEqual(note.message, 'foo')\n self.assertEqual(note.key.parent(), blockable.key)\n\n def testResetBlockable(self):\n \"\"\"Test private reset method.\"\"\"\n\n # Create a vote and trigger a recount on the blockable to update the score.\n test_utils.CreateVote(self.santa_blockable)\n self.santa_blockable.put()\n\n # Ensure Vote properly updated the blockable score.\n with self.LoggedInUser(admin=True):\n response = self.testapp.get('/%s' % self.santa_blockable.key.id())\n output = response.json\n\n self.assertEqual(output['id'], self.santa_blockable.key.id())\n self.assertEqual(output['score'], 1)\n\n # Issue a reset and ensure the resulting score is 0.\n params = {'reset': 'reset'}\n response = self.testapp.post(\n '/%s' % self.santa_blockable.key.id(), params)\n output = response.json\n\n self.assertEqual(output['id'], self.santa_blockable.key.id())\n self.assertEqual(output['score'], 0)\n\n\nclass AuthorizedHostCountHandlerTest(BlockablesTest):\n\n def setUp(self):\n app = webapp2.WSGIApplication(\n [webapp2.Route(r'/',\n handler=blockables.AuthorizedHostCountHandler)])\n super(AuthorizedHostCountHandlerTest, self).setUp(app)\n\n def testGloballyWhitelisted(self):\n self.santa_blockable.state = constants.STATE.GLOBALLY_WHITELISTED\n self.santa_blockable.put()\n\n with self.LoggedInUser(admin=True):\n response = self.testapp.get('/%s' % self.santa_blockable.key.id())\n output = response.json\n\n self.assertEqual(-1, output)\n\n def testNone(self):\n with self.LoggedInUser(admin=True):\n response = self.testapp.get('/%s' % self.santa_blockable.key.id())\n output = response.json\n\n self.assertEqual(0, output)\n\n def testNormal(self):\n expected = 3\n for i in xrange(expected):\n test_utils.CreateSantaRule(\n self.santa_blockable.key,\n policy=constants.RULE_POLICY.WHITELIST,\n host_id='host%s' % i)\n test_utils.CreateSantaRule(\n self.santa_blockable.key,\n policy=constants.RULE_POLICY.BLACKLIST)\n test_utils.CreateSantaRule(\n self.santa_blockable.key,\n policy=constants.RULE_POLICY.WHITELIST,\n in_effect=False)\n\n with self.LoggedInUser(admin=True):\n response = self.testapp.get('/%s' % self.santa_blockable.key.id())\n output = response.json\n\n self.assertEqual(expected, output)\n\n def testBlockableNotFound(self):\n with self.LoggedInUser(admin=True):\n self.testapp.get('/NotARealBlockable', status=httplib.NOT_FOUND)\n\n def testBadBlockableType(self):\n with self.LoggedInUser(admin=True):\n self.testapp.get(\n '/%s' % self.bit9_blockable.key.id(), status=httplib.BAD_REQUEST)\n\n def testNoPermission(self):\n with self.LoggedInUser():\n self.testapp.get(\n '/%s' % self.santa_blockable.key.id(), status=httplib.FORBIDDEN)\n\n\nclass UniqueEventCountHandlerTest(BlockablesTest):\n\n def setUp(self):\n app = webapp2.WSGIApplication(\n [webapp2.Route(r'/',\n handler=blockables.UniqueEventCountHandler)])\n super(UniqueEventCountHandlerTest, self).setUp(app)\n\n def testBinary_Normal(self):\n test_utils.CreateSantaEvent(self.santa_blockable)\n\n with self.LoggedInUser():\n response = self.testapp.get('/%s' % self.santa_blockable.key.id())\n output = response.json\n\n self.assertEqual(1, output)\n\n def testCert_Normal(self):\n test_utils.CreateSantaEvent(\n self.santa_blockable,\n cert_sha256=self.santa_certificate.key.id())\n\n with self.LoggedInUser():\n response = self.testapp.get('/%s' % self.santa_certificate.key.id())\n output = response.json\n\n self.assertEqual(1, output)\n\n def testBlockableNotFound(self):\n self.santa_blockable.key.delete()\n with self.LoggedInUser():\n self.testapp.get(\n '/%s' % self.santa_blockable.key.id(), status=httplib.NOT_FOUND)\n\n def testBadBlockableType(self):\n with self.LoggedInUser():\n self.testapp.get(\n '/%s' % self.generic_blockable.key.id(),\n status=httplib.BAD_REQUEST)\n\n\nclass PackageContentsHandlerTest(BlockablesTest):\n\n def setUp(self):\n app = webapp2.WSGIApplication(\n [webapp2.Route(r'/',\n handler=blockables.PackageContentsHandler)])\n super(PackageContentsHandlerTest, self).setUp(app)\n\n def testSuccess_Bundle(self):\n test_blockables = test_utils.CreateSantaBlockables(4)\n bundle = test_utils.CreateSantaBundle(bundle_binaries=test_blockables)\n\n with self.LoggedInUser():\n response = self.testapp.get('/%s' % bundle.key.id())\n output = response.json\n\n self.assertSameElements(\n (blockable.key.id() for blockable in test_blockables),\n (blockable_dict['id'] for blockable_dict in output))\n\n def testSuccess_NoContents(self):\n bundle = test_utils.CreateSantaBundle()\n\n with self.LoggedInUser():\n response = self.testapp.get('/%s' % bundle.key.id())\n output = response.json\n\n self.assertFalse(output)\n\n def testSuccess_SantaBinaryOrder(self):\n bundle = test_utils.CreateSantaBundle(binary_count=4)\n path_pairs = [('a', 'z'), ('a', 'y'), ('a/b/c', 'x'), ('a/b', 'z')]\n expected_path_order = ['a/y', 'a/z', 'a/b/z', 'a/b/c/x']\n for rel_path, file_name in path_pairs:\n binary = test_utils.CreateSantaBlockable()\n santa.SantaBundleBinary.Generate(\n bundle.key, binary.key, cert_key=binary.cert_key,\n rel_path=rel_path, file_name=file_name).put()\n\n with self.LoggedInUser():\n response = self.testapp.get('/%s' % bundle.key.id())\n output = response.json\n\n self.assertListEqual(\n expected_path_order,\n [blockable_dict['fullPath'] for blockable_dict in output])\n\n def testNotFound(self):\n with self.LoggedInUser():\n self.testapp.get('/DoesntExist', status=httplib.NOT_FOUND)\n\n def testNotAPackage(self):\n blockable = test_utils.CreateSantaBlockable()\n with self.LoggedInUser():\n self.testapp.get('/%s' % blockable.key.id(), status=httplib.BAD_REQUEST)\n\n def testNotASantaBundle(self):\n package_key = base.Package(id='foo', id_type='SHA256').put()\n with self.LoggedInUser():\n self.testapp.get('/%s' % package_key.id(), status=httplib.BAD_REQUEST)\n\n\nclass PendingStateChangeHandlerTest(BlockablesTest):\n\n def setUp(self):\n app = webapp2.WSGIApplication(\n [webapp2.Route(\n r'/', handler=blockables.PendingStateChangeHandler)])\n super(PendingStateChangeHandlerTest, self).setUp(app)\n\n def testPendingGlobalRule(self):\n test_utils.CreateBit9Rule(\n self.bit9_blockable.key, host_id='', is_committed=False)\n\n with self.LoggedInUser():\n response = self.testapp.get('/%s' % self.bit9_blockable.key.id())\n output = response.json\n\n self.assertTrue(output)\n\n def testPendingDisabledRule(self):\n test_utils.CreateBit9Rule(\n self.bit9_blockable.key, host_id='', is_committed=False,\n in_effect=False)\n\n with self.LoggedInUser():\n response = self.testapp.get('/%s' % self.bit9_blockable.key.id())\n output = response.json\n\n self.assertFalse(output)\n\n def testPendingGlobalRule_InstallerRule(self):\n test_utils.CreateBit9Rule(\n self.bit9_blockable.key, host_id='',\n policy=constants.RULE_POLICY.FORCE_INSTALLER, is_committed=False)\n\n with self.LoggedInUser():\n response = self.testapp.get('/%s' % self.bit9_blockable.key.id())\n output = response.json\n\n self.assertFalse(output)\n\n def testPendingLocalRule_ForUser(self):\n with self.LoggedInUser() as user:\n bit9_host = test_utils.CreateBit9Host(users=[user.nickname])\n test_utils.CreateBit9Rule(\n self.bit9_blockable.key, host_id=bit9_host.key.id(),\n user_key=user.key, is_committed=False)\n response = self.testapp.get('/%s' % self.bit9_blockable.key.id())\n output = response.json\n\n self.assertTrue(output)\n\n def testPendingLocalRule_ForSomeoneElse(self):\n other_user = test_utils.CreateUser()\n\n with self.LoggedInUser():\n bit9_host = test_utils.CreateBit9Host(users=[other_user.nickname])\n test_utils.CreateBit9Rule(\n self.bit9_blockable.key, host_id=bit9_host.key.id(),\n user_key=other_user.key, is_committed=False)\n response = self.testapp.get('/%s' % self.bit9_blockable.key.id())\n output = response.json\n\n self.assertFalse(output)\n\n def testNoRules(self):\n with self.LoggedInUser():\n response = self.testapp.get('/%s' % self.bit9_blockable.key.id())\n output = response.json\n\n self.assertFalse(output)\n\n def testOtherPlatform(self):\n with self.LoggedInUser():\n response = self.testapp.get('/%s' % self.santa_blockable.key.id())\n output = response.json\n\n self.assertFalse(output)\n\n def testUnknownBlockable(self):\n with self.LoggedInUser():\n self.testapp.get('/not-a-real-blockable', status=httplib.NOT_FOUND)\n\n\nclass PendingInstallerStateChangeHandlerTest(BlockablesTest):\n\n def setUp(self):\n app = webapp2.WSGIApplication(\n [webapp2.Route(\n r'/',\n handler=blockables.PendingInstallerStateChangeHandler)])\n super(PendingInstallerStateChangeHandlerTest, self).setUp(app)\n\n def testPendingInstallerRule(self):\n test_utils.CreateBit9Rule(\n self.bit9_blockable.key, is_committed=False,\n policy=constants.RULE_POLICY.FORCE_INSTALLER)\n\n with self.LoggedInUser():\n response = self.testapp.get('/%s' % self.bit9_blockable.key.id())\n output = response.json\n\n self.assertTrue(output)\n\n def testPendingNonInstallerRule(self):\n test_utils.CreateBit9Rule(\n self.bit9_blockable.key, is_committed=False,\n policy=constants.RULE_POLICY.WHITELIST)\n\n with self.LoggedInUser():\n response = self.testapp.get('/%s' % self.bit9_blockable.key.id())\n output = response.json\n\n self.assertFalse(output)\n\n def testPendingDisabledRule(self):\n test_utils.CreateBit9Rule(\n self.bit9_blockable.key, host_id='', is_committed=False,\n in_effect=False, policy=constants.RULE_POLICY.FORCE_INSTALLER)\n\n with self.LoggedInUser():\n response = self.testapp.get('/%s' % self.bit9_blockable.key.id())\n output = response.json\n\n self.assertFalse(output)\n\n def testNoRules(self):\n with self.LoggedInUser():\n response = self.testapp.get('/%s' % self.bit9_blockable.key.id())\n output = response.json\n\n self.assertFalse(output)\n\n def testOtherPlatform(self):\n with self.LoggedInUser():\n response = self.testapp.get('/%s' % self.santa_blockable.key.id())\n output = response.json\n\n self.assertFalse(output)\n\n def testUnknownBlockable(self):\n with self.LoggedInUser():\n self.testapp.get('/not-a-real-blockable', status=httplib.NOT_FOUND)\n\n\nclass SetInstallerStateHandlerTest(BlockablesTest):\n\n def setUp(self):\n app = webapp2.WSGIApplication(\n [webapp2.Route(\n r'/', handler=blockables.SetInstallerStateHandler)])\n super(SetInstallerStateHandlerTest, self).setUp(app)\n\n def testNoPreexistingRule(self):\n self.assertFalse(self.bit9_blockable.is_installer)\n\n with self.LoggedInUser():\n response = self.testapp.post(\n '/%s' % self.bit9_blockable.key.id(), {'value': True})\n output = response.json\n\n self.assertTrue(output)\n\n self.assertEntityCount(bit9.Bit9Rule, 1)\n self.assertEntityCount(bit9.RuleChangeSet, 1)\n self.assertEntityCount(base.AuditLog, 1, ancestor=self.bit9_blockable.key)\n self.assertTrue(self.bit9_blockable.key.get().is_installer)\n self.assertTaskCount(constants.TASK_QUEUE.BIT9_COMMIT_CHANGE, 1)\n\n def testPreexistingRule(self):\n test_utils.CreateBit9Rule(\n self.bit9_blockable.key,\n policy=constants.RULE_POLICY.FORCE_INSTALLER)\n self.bit9_blockable.is_installer = True\n self.bit9_blockable.put()\n\n with self.LoggedInUser():\n response = self.testapp.post(\n '/%s' % self.bit9_blockable.key.id(), {'value': False})\n output = response.json\n\n self.assertFalse(output)\n\n self.assertEntityCount(bit9.Bit9Rule, 2)\n self.assertEntityCount(bit9.RuleChangeSet, 1)\n self.assertEntityCount(base.AuditLog, 1, ancestor=self.bit9_blockable.key)\n self.assertFalse(self.bit9_blockable.key.get().is_installer)\n self.assertTaskCount(constants.TASK_QUEUE.BIT9_COMMIT_CHANGE, 1)\n\n def testSameStateAsPreexistingRule(self):\n test_utils.CreateBit9Rule(\n self.bit9_blockable.key,\n policy=constants.RULE_POLICY.FORCE_INSTALLER)\n self.bit9_blockable.is_installer = True\n self.bit9_blockable.put()\n\n with self.LoggedInUser():\n response = self.testapp.post(\n '/%s' % self.bit9_blockable.key.id(), {'value': True})\n output = response.json\n\n self.assertTrue(output)\n\n self.assertEntityCount(bit9.Bit9Rule, 1)\n self.assertEntityCount(bit9.RuleChangeSet, 0)\n self.assertEntityCount(base.AuditLog, 0)\n self.assertTrue(self.bit9_blockable.key.get().is_installer)\n self.assertTaskCount(constants.TASK_QUEUE.BIT9_COMMIT_CHANGE, 0)\n\n def testOtherPlatform(self):\n with self.LoggedInUser():\n self.testapp.post(\n '/%s' % self.santa_blockable.key.id(), {'value': 'false'},\n status=httplib.BAD_REQUEST)\n\n def testUnknownBlockable(self):\n with self.LoggedInUser():\n self.testapp.post(\n '/not-a-real-blockable', {'value': 'false'}, status=httplib.NOT_FOUND)\n\n\nif __name__ == '__main__':\n basetest.main()\n","sub_path":"upvote/gae/modules/upvote_app/api/handlers/blockables_test.py","file_name":"blockables_test.py","file_ext":"py","file_size_in_byte":29603,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"382735984","text":"from django.shortcuts import render, HttpResponse, redirect\nfrom django.views import View\nfrom library import models\n\n\ndef index(request):\n return render(request, \"index.html\")\n\n\ndef test(request):\n return HttpResponse(\"ok\")\n\n\ndef many(request):\n # 1自定义\n # obj = models.Author.objects.filter(name=\"alex\").first()\n # book_list = obj.many_set.all()\n # for row in book_list:\n # print(row.book.title)\n\n # book_list = models.Many.objects.filter(author__name=\"小明\")\n # for row in book_list:\n # print(row.book.title)\n\n # book_list = models.Many.objects.filter(author__name=\"小明\").values(\"book__title\")\n # for item in book_list:\n # print(item[\"book__title\"])\n\n book_list = models.Many.objects.filter(author__name=\"小明\").select_related(\"book\")\n for obj in book_list:\n print(obj.book.title)\n\n # 2django自动生成\n # obj = models.Author.objects.filter(name=\"alex\").first()\n # print(obj.id,obj.name)\n # obj.book.add(1,2)\n # obj.book.add(*[1,])\n # obj.book.set([1,]) #重设\n # obj.book.remove([1,])\n # obj.book.clear() #删除\n # book_list = obj.book.all()\n\n # 反向\n # obj = models.Book.objects.filter(title=\"Java教程\").first()\n # v = obj.author_set.values()\n # print(v)\n\n return HttpResponse(\"ok\")\n\n\nclass Publish(View):\n\n def publisher_list(self, request):\n ret = models.Publisher.objects.all()\n print(ret)\n # ret = models.Publisher.objects.all().order_by(\"id\")\n return render(request, \"library/publisher/publisher_list.html\", {\"publisher_list\": ret})\n\n def add_publisher(self, request):\n if request.method == \"POST\":\n new_name = request.POST.get(\"publisher_name\")\n\n models.Publisher.objects.create(name=new_name)\n return redirect(\"/publisher_list/\")\n\n return render(request, \"library/publisher/add_publisher.html\")\n\n def delete_publisher(self, request):\n error_msg = \"\"\n del_id = request.GET.get('id', None)\n if del_id:\n del_obj = models.Publisher.objects.get(id=del_id).delete()\n return redirect(\"/publisher_list/\")\n else:\n error_msg = \"删除的id不存在!\"\n\n return render(request, \"library/publisher/add_publisher.html\", {\"error\": error_msg})\n\n def edit_publisher(self, request):\n if request.method == \"POST\":\n new_name = request.POST.get('publisher_name')\n edit_id = request.POST.get('id')\n edit_obj = models.Publisher.objects.get(id=edit_id)\n edit_obj.name = new_name\n edit_obj.save()\n\n return redirect(\"/publisher_list/\")\n\n edit_id = request.GET.get('id')\n if edit_id:\n edit_obj = models.Publisher.objects.get(id=edit_id)\n return render(request, \"library/publisher/edit_publisher.html\", {\"publisher\": edit_obj})\n\n\nclass Book(View):\n\n def book_list(self, request):\n all_book = models.Book.objects.all()\n # print(all_book)\n return render(request, \"library/book/book_list.html\", {\"book_list\": all_book})\n\n def add_book(self, request):\n if request.method == \"POST\":\n new_book = request.POST.get(\"book_name\")\n new_publisher = request.POST.get(\"publisher\")\n\n models.Book.objects.create(title=new_book, publisher_id=new_publisher)\n return redirect(\"/book_list/\")\n ret = models.Publisher.objects.all()\n return render(request, \"library/book/add_book.html\", {\"publisher_list\": ret})\n\n def edit_book(self, request):\n if request.method == \"POST\":\n edit_id = request.POST.get(\"id\")\n new_title = request.POST.get(\"title\")\n new_publisher = request.POST.get(\"publisher\")\n\n edit_obj = models.Book.objects.get(id=edit_id)\n edit_obj.title = new_title\n edit_obj.publisher_id = new_publisher\n edit_obj.save()\n\n return redirect(\"/book_list/\")\n\n edit_id = request.GET.get(\"id\")\n edit_book_obj = models.Book.objects.get(id=edit_id)\n ret = models.Publisher.objects.all()\n return render(request, \"library/book/edit_book.html\", {\"publisher_list\": ret, \"book\": edit_book_obj})\n\n def delete_book(self, request):\n del_id = request.GET.get(\"id\")\n if del_id:\n models.Book.objects.get(id=del_id).delete()\n\n return redirect(\"/book_list/\")\n\n\nclass Author(View):\n\n def author_list(self, request):\n ret = models.Author.objects.all()\n\n return render(request, \"library/author/author_list.html\", {\"author_list\": ret})\n\n def add_author(self, request):\n if request.method == \"POST\":\n new_name = request.POST.get(\"name\")\n books = request.POST.getlist(\"books\")\n new_author_obj = models.Author.objects.create(name=new_name)\n\n new_author_obj.book.set(books)\n\n return redirect(\"/author_list/\")\n\n ret = models.Book.objects.all()\n return render(request, \"library/author/add_author.html\", {\"book_list\": ret})\n\n def edit_author(self, request):\n if request.method == \"POST\":\n edit_id = request.POST.get(\"id\")\n new_name = request.POST.get(\"author\")\n books = request.POST.getlist(\"books\")\n edit_obj = models.Author.objects.get(id=edit_id)\n edit_obj.name = new_name\n edit_obj.book.set(books)\n edit_obj.save()\n return redirect(\"/author_list/\")\n\n edit_id = request.GET.get(\"id\")\n author_ret = models.Author.objects.get(id=edit_id)\n book_ret = models.Book.objects.all()\n\n return render(request, \"library/author/edit_author.html\", {\"author\": author_ret, \"book_list\": book_ret})\n\n def delete_author(self, request):\n del_id = request.GET.get(\"id\")\n if del_id:\n models.Author.objects.get(id=del_id).delete()\n\n return redirect(\"/author_list/\")\n","sub_path":"web_server/library_manage/library/cbv_views.py","file_name":"cbv_views.py","file_ext":"py","file_size_in_byte":5985,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"142921259","text":"import logging\n\nfrom flask import Blueprint, request, Response, current_app\nfrom werkzeug.exceptions import HTTPException\n\nfrom robot_service.service.robot import (\n add_robot,\n get_robots,\n delete_robot,\n get_robots_by_id,\n)\nfrom robot_service.utils import serializer\n\nbp = Blueprint('robots', __name__, url_prefix='/robots')\n\nlogger = logging.getLogger(__name__)\n\n\n@bp.route(\n '/',\n methods=['GET', 'POST']\n)\ndef root():\n if request.method == 'GET':\n return json_response(get_robots())\n if request.method == 'POST':\n data = request.form\n try:\n _validate_new_robot_data(data, request.files)\n return json_response(add_robot(data, request.files['file']))\n except Exception as e:\n logger.error(e)\n raise HTTPException(\n description=str(e),\n response=Response(\n status=400,\n response=str(e),\n )\n )\n\n\n@bp.route(\n '/',\n methods=['GET', 'DELETE']\n)\ndef robot_by_id(robot_id):\n if ',' in robot_id:\n robot_id = list(map(str.strip, robot_id.split(',')))\n if request.method == 'GET':\n robots = get_robots_by_id(robot_id)\n return json_response(robots)\n\n if request.method == 'DELETE':\n delete_robot(robot_id)\n return current_app.response_class(\n status=204\n )\n\n\ndef _validate_new_robot_data(data, files):\n if not data:\n raise Exception('Robot data is required')\n\n if 'name' not in data:\n raise Exception('Robot name is required')\n\n if not files or 'file' not in files:\n raise Exception('Robot jar file is required')\n\n\ndef json_response(data):\n return current_app.response_class(\n serializer.dumps(data) + \"\\n\",\n mimetype=current_app.config[\"JSONIFY_MIMETYPE\"],\n )\n","sub_path":"robot-service/robot_service/api/robot.py","file_name":"robot.py","file_ext":"py","file_size_in_byte":1871,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"153663095","text":"\"\"\"\nLets you type math symbols by typing their names and then hitting ctrl + space.\n\nI wrote this in a haste, so I realise some things can be done more elegantly.\nFor example, you can only define shortcuts of up to two words, so \"for all\"\nworks but not \"if and only if\". Write your own fix to it if you need.\nPress space to reset current_word as necessary.\n\nDefine your own shortcuts in the replace_matching_symbols function.\n\nTimo Brønseth, January 2020.\n\"\"\"\nfrom pynput.keyboard import Key, Listener, Controller\n# Package docs: https://pythonhosted.org/pynput/\n\n\n# GLOBAL CONSTANTS\nALPHABET = tuple(\"abcdefghijklmnopqrstuvwxyz\")\n\n# GLOBAL VARIABLES\nlast_word = \"\" # Need this to check against two-word symbols.\ncurrent_word = \"\" # All keyboard presses gets recorded here and then recinded once space is pressed.\nkeyboard = Controller()\nctrl_modifier = False\n\n\ndef add_to_word(character: str) -> None:\n \"\"\"\n Updates global word if character is in alphabet.\n \"\"\"\n global current_word\n\n character = character.replace(\"'\", \"\")\n if character in ALPHABET:\n current_word += character\n\n\ndef is_space(key):\n \"\"\"\n Returns True if key is space, False otherwise.\n \"\"\"\n global current_word, last_word\n\n if key == Key.space:\n return True\n else:\n return False\n\n\ndef is_symbol(symbol: str) -> bool:\n \"\"\"\n Checks if user has typed anything that corresponds to one of the\n defined symbols, and then presses backspace to delete that/those\n words before returning True or False to caller function.\n \"\"\"\n global current_word, last_word\n phrase = last_word + \" \" + current_word\n\n if symbol == current_word:\n # You are currently pressing ctrl, so we only need to\n # press backspace once to delete the last word you typed.\n keyboard.press(Key.backspace)\n keyboard.release(Key.backspace)\n current_word = \"\"\n return True\n\n elif symbol == phrase:\n # You are currently pressing ctrl, so we only need to\n # press backspace twice to delete the two last words you typed.\n keyboard.press(Key.backspace)\n keyboard.release(Key.backspace)\n keyboard.press(Key.backspace)\n keyboard.release(Key.backspace)\n current_word = \"\"\n return True\n\n else:\n return False\n\n\ndef replace_matching_symbols() -> None:\n \"\"\"...\"\"\"\n global current_word, last_word\n\n if is_symbol(\"and\"):\n keyboard.type(\"∧\")\n return\n\n elif is_symbol(\"or\"):\n keyboard.type(\"∨\")\n return\n\n elif is_symbol(\"xor\"):\n keyboard.type(\"⊻\")\n return\n\n elif is_symbol(\"implies\"):\n keyboard.type(\"→\")\n return\n\n elif is_symbol(\"biconditional\"):\n keyboard.type(\"↔\")\n return\n\n elif is_symbol(\"there exists\"):\n keyboard.type(\"∃\")\n return\n\n elif is_symbol(\"negative existential\"):\n keyboard.type(\"∄\")\n return\n\n elif is_symbol(\"for all\"):\n keyboard.type(\"∀\")\n return\n\n elif is_symbol(\"times\"):\n keyboard.type(\"×\")\n return\n\n elif is_symbol(\"union\"):\n keyboard.type(\"∪\")\n return\n\n elif is_symbol(\"intersection\"):\n keyboard.type(\"∩\")\n return\n\n elif is_symbol(\"proper subset\"):\n keyboard.type(\"⊂\")\n return\n\n elif is_symbol(\"subset\"):\n keyboard.type(\"⊆\")\n return\n\n elif is_symbol(\"not subset\"):\n keyboard.type(\"⊄\")\n return\n\n elif is_symbol(\"proper superset\"):\n keyboard.type(\"⊃\")\n return\n\n elif is_symbol(\"superset\"):\n keyboard.type(\"⊇\")\n return\n\n elif is_symbol(\"element of\"):\n keyboard.type(\"∈\")\n return\n\n elif is_symbol(\"not element\"):\n keyboard.type(\"∉\")\n return\n\n elif is_symbol(\"empty set\"):\n keyboard.type(\"∅\")\n return\n\n elif is_symbol(\"inclusive less\"):\n keyboard.type(\"≤\")\n return\n\n elif is_symbol(\"inclusive more\"):\n keyboard.type(\"≥\")\n return\n\n # Apparently keyboard won't type these.\n # elif is_symbol(\"natural numbers\"):\n # keyboard.type(\"ℕ\")\n # return\n #\n # elif is_symbol(\"rational numbers\"):\n # keyboard.type(\"ℚ\")\n # return\n #\n # elif is_symbol(\"universal set\"):\n # keyboard.type(\"𝕌\")\n # return\n #\n # elif is_symbol(\"real numbers\"):\n # keyboard.type(\"ℝ\")\n # return\n #\n # elif is_symbol(\"primes\"):\n # keyboard.type(\"ℙ\")\n # return\n #\n # elif is_symbol(\"complex numbers\"):\n # keyboard.type(\"ℂ\")\n # return\n\n elif is_symbol(\"not\"):\n keyboard.type(\"¬\")\n return\n\n\ndef on_press(key):\n global current_word, last_word, ctrl_modifier\n\n if is_space(key):\n\n # If ctrl was the last pressed key before space, write_matching_symbols\n if ctrl_modifier:\n replace_matching_symbols()\n ctrl_modifier = False\n\n # Update words\n last_word = current_word\n current_word = \"\"\n return\n\n # Set ctrl_modifier to True if key is ctrl, otherwise reset it\n ctrl_modifier = True if key == Key.ctrl_l else False\n\n # Converts the native KeyCode type to str before adding it to current_word\n add_to_word(key.__str__())\n\n\ndef main():\n\n # Collect events until released\n with Listener(on_press) as listener:\n listener.join()\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"__main__.py","file_name":"__main__.py","file_ext":"py","file_size_in_byte":5487,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"359537870","text":"\n\n#################\n#### MODULES ####\n\n##get_ipython().magic('matplotlib inline')\n##get_ipython().magic(\"config InlineBackend.figure_format = 'retina'\")\nimport matplotlib.pyplot as plt\nimport pandas as pd\nimport numpy as np\nimport seaborn as sns\nimport warnings\nfrom pathlib import Path\n\nwarnings.filterwarnings('ignore')\npd.options.display.float_format = '{:,.2f}'.format\npd.set_option('display.max_rows', 100)\npd.set_option('display.max_columns', 200)\npd.set_option('display.width', 250)\n\nfrom __future__ import print_function\nfrom datetime import datetime\nfrom matplotlib.colors import ListedColormap\nfrom sklearn.datasets import make_classification, make_moons, make_circles\nfrom sklearn.metrics import confusion_matrix, classification_report, mean_squared_error, mean_absolute_error, r2_score\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.utils import shuffle\nfrom tensorflow.keras.models import Sequential\nfrom tensorflow.keras.layers import Dense, Dropout, BatchNormalization, Activation\nfrom tensorflow.keras.optimizers import Adam\nfrom tensorflow.keras.callbacks import EarlyStopping\nfrom tensorflow.python.keras.utils.np_utils import to_categorical\nfrom sklearn.preprocessing import StandardScaler, LabelEncoder, OneHotEncoder, MinMaxScaler\nfrom sklearn.model_selection import train_test_split, cross_val_score, StratifiedKFold, KFold\nimport tensorflow.keras.backend as K\nfrom tensorflow.keras.wrappers.scikit_learn import KerasClassifier\n\nimport os\nos.chdir(\"/cluster/home/quever/git/Applied-Deep-Learning-with-Keras/py\")\nfrom models import *\nfrom P2_utility_functions import *\n\n\n\n#################################\n#### Case Study - Regression ####\n# We will be using the house sales dataset from King County, WA on Kaggle: https://www.kaggle.com/harlfoxem/housesalesprediction\n# The data has around 21,000 rows with 20 features. The value we're tring to predict is a floating point number labeld as \"price\".\n\n############################################\n#### Data Visualization & Preprocessing ####\ndatadir=Path('~/git/Applied-Deep-Learning-with-Keras')\nrawdf = pd.read_csv(datadir / 'data' / 'kc_house_data.csv')\nrawdf.head()\n\n\n## Describe dataset\nrawdf.describe()\nrawdf.hist(figsize=(10, 10))\nplt.tight_layout()\n\nplt.figure(figsize=(6, 8))\nsns.heatmap(rawdf.corr()[['price']], annot=True, vmin=-1, vmax=1)\n\n## Scale features\ndf = rawdf.copy()\n\nss = StandardScaler()\nscale_features = ['bathrooms', 'bedrooms', 'grade', 'sqft_above',\n 'sqft_basement', 'sqft_living', 'sqft_living15', 'sqft_lot', 'sqft_lot15']\ndf[scale_features] = ss.fit_transform(df[scale_features])\n\n## Bucketization of features\nbucketized_features = ['yr_built', 'yr_renovated', 'lat', 'long']\n\nbins = range(1890, 2021, 10)\ndf['yr_built'] = pd.cut(df.yr_built, bins, labels=bins[:-1])\n\nbins = np.append([-10], np.arange(1930, 2021, 10))\ndf['yr_renovated'] = pd.cut(df.yr_renovated, bins, labels=bins[:-1])\n\nbins = np.arange(47.00, 47.90, 0.05)\ndf['lat'] = pd.cut(df.lat, bins, labels=bins[:-1])\n\nbins = np.arange(-122.60, -121.10, 0.05)\ndf['long'] = pd.cut(df.long, bins, labels=bins[:-1])\n\n## One-hot encoding of categorical features\ndf['date'] = [datetime.strptime(x, '%Y%m%dT000000').strftime('%Y-%m') for x in rawdf['date'].values]\ndf['zipcode'] = df['zipcode'].astype(str)\ncategorical_features = ['zipcode', 'date']\ncategorical_features.extend(bucketized_features)\ndf_cat = pd.get_dummies(df[categorical_features])\ndf = df.drop(categorical_features, axis=1)\ndf = pd.concat([df, df_cat], axis=1)\n\n## drop features\ndrop_features = ['id']\ndf = df.drop(drop_features, axis=1)\n\ndf.head()\n\n\n## Visualization: Feature correlations with price\nplt.figure(figsize=(4, 8))\ntempdf = df.corr()[['price']].sort_values('price', ascending=False).iloc[:20, :]\nsns.heatmap(tempdf, annot=True, vmin=-1, vmax=1)\n\n\n########################\n#### Model Building ####\nX = df.drop(['price'], axis=1).values\ny = df['price'].values\n\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=0)\nprint(X_train.shape, y_train.shape, X_test.shape, y_test.shape)\n\n## Winsorization of y-values\nfactor = 5\ny_train[np.abs(y_train - y_train.mean()) > (factor * y_train.std())] = y_train.mean() + factor*y_train.std()\n\n## scale the price\nss_price = StandardScaler()\ny_train = ss_price.fit_transform(y_train.reshape(-1, 1))\ny_test = ss_price.transform(y_test.reshape(-1,1))\n\n####################\n#### Dumb Model ####\ntrain_prices = ss_price.inverse_transform(y_train)\ndumb_prices = np.zeros(real_prices.shape)\ndumb_prices.fill(train_prices.mean())\ndumb_error = mean_absolute_error(real_prices, dumb_prices)\nprint('Dumb model error:', output_dollars(dumb_error))\n\n\n#################################\n#### Linear Regression Model ####\nM = RegressionModels(X)\nM.linear_model()\n\nlinr_history = M.model.fit(X_train, y_train, epochs=30, verbose=0, validation_split=0.2)\nplot_loss(linr_history)\n\n## Performance metrics\nM.model.evaluate(X_test, y_test, verbose=0)\n\n## Get coefficients of linear model\nlinr_wdf = pd.DataFrame(M.model.get_weights()[0].T,\n columns=df.drop(['price'], axis=1).columns).T.sort_values(0, ascending=False)\nlinr_wdf.columns = ['feature_weight']\nlinr_wdf.iloc[:20,:]\n\n## Get predictions and error\nlinr_predictions = M.model.predict(X_test).ravel()\nlinr_prices = ss_price.inverse_transform(linr_predictions)\nlinr_error = mean_absolute_error(real_prices, linr_prices)\nprint('Linear model error:', output_dollars(linr_error))\n\n###############################\n#### Deep Regression Model ####\n# The loss is behaving incosistently between runs, this one was good but the previous ones were bad. Needs debugging.\nM = RegressionModels(X)\nM.ann_model()\n\n\ndeep_history = M.model.fit(X_train, y_train, epochs=30, verbose=0, validation_split=0.2)\nplot_loss(deep_history)\nM.model.evaluate(X_test, y_test, verbose=0)\n\n## with early stopping callback\nearly_stop = EarlyStopping(monitor='val_loss', patience=2, verbose=1)\ndeep_early = M.model.fit(X_train, y_train, epochs=30, verbose=0, validation_split=0.2,\n callbacks=[early_stop])\nplot_loss(deep_early)\nM.model.evaluate(X_test, y_test, verbose=0)\n\n\n## Performance metrics\nplot_compare_histories([linr_history, deep_history, deep_early],\n ['Linear Reg', 'Deep ANN', 'Deep ANN (early)'],\n plot_accuracy=False)\n\ndef output_dollars(num):\n return '$'+str(\"{:,}\".format(int(num)))\n\nprint('Average house price:', output_dollars(rawdf['price'].mean()))\n\nreal_prices = ss_price.inverse_transform(y_test)\n\n## Get predictions and error\ndeep_predictions = M.model.predict(X_test).ravel()\ndeep_prices = ss_price.inverse_transform(deep_predictions)\ndeep_error = mean_absolute_error(real_prices, deep_prices)\nprint('Deep model error:', output_dollars(deep_error))\n\n###################################\n#### Assemble Prediction Error ####\ntdf = pd.DataFrame([['Naive Model', output_dollars(dumb_error)],\n ['Linear Regression', output_dollars(linr_error)],\n ['Deep ANN', output_dollars(deep_error)]],\n columns=['Model', 'Price Error'])\ntdf\n\nprint(r2_score(real_prices, dumb_prices), r2_score(real_prices, linr_prices), r2_score(real_prices, deep_prices))\n","sub_path":"py/P2_regression.py","file_name":"P2_regression.py","file_ext":"py","file_size_in_byte":7251,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"315648092","text":"\"\"\"Module to package a protein complex\"\"\"\n\nfrom symmlightdock.structure.space import SpacePoints\n\n\nclass Complex(object):\n \"\"\"Represents a molecular complex\"\"\"\n def __init__(self, chains, atoms=None, residues=None, structure_file_name='', structures=None, representative_id=0):\n \"\"\"Creates a new complex that can deal with multiple coordinates for a given atom\"\"\"\n self.chains = chains\n # Set atoms at the upper level for fast indexing\n if atoms:\n self.atoms = atoms\n else:\n self.atoms = [atom for chain in self.chains\n for residue in chain.residues for atom in residue.atoms]\n for atom_index, atom in enumerate(self.atoms):\n atom.index = atom_index\n\n # Same for residues\n if residues:\n self.residues = residues\n else:\n self.residues = [residue for chain in self.chains for residue in chain.residues]\n for residue_index, residue in enumerate(self.residues):\n residue.index = residue_index\n\n if structures:\n self.num_structures = len(structures)\n self.structure_file_names = [structure['file_name'] for structure in structures]\n self.atom_coordinates = [SpacePoints([[atom.x, atom.y, atom.z]\n for atom in structure['atoms']]) for structure in structures]\n else:\n self.num_structures = 1\n self.structure_file_names = [structure_file_name]\n self.atom_coordinates = [SpacePoints([[atom.x, atom.y, atom.z] for atom in self.atoms])]\n\n self.num_atoms = len(self.atoms)\n self.num_residues = len(self.residues)\n self.representative_id = representative_id\n\n @staticmethod\n def from_structures(structures, representative_id=0):\n return Complex(structures[representative_id]['chains'],\n structures[representative_id]['atoms'],\n structures[representative_id]['residues'],\n structures[representative_id]['file_name'],\n structures, representative_id)\n\n def increase_chain(self):\n \"\"\"Increases in one the name of the chain\"\"\"\n for chain in self.chains:\n chain.cid = chr(ord(chain.cid)+1)\n for residue in chain.residues:\n for atom in residue.atoms:\n atom.chain_id = chain.cid\n\n def clone(self):\n \"\"\"Creates a copy of the current complex\"\"\"\n molecule = Complex([chain.clone() for chain in self.chains])\n molecule.num_structures = self.num_structures\n molecule.structure_file_names = self.structure_file_names\n molecule.atom_coordinates = self.copy_coordinates()\n return molecule\n\n def copy_coordinates(self):\n return [coordinates.clone() for coordinates in self.atom_coordinates]\n\n def center_of_mass(self, structure=None):\n \"\"\"Calculates the center of mass\"\"\"\n if not structure:\n structure = self.representative_id\n if len(self.atoms):\n total_x = 0.\n total_y = 0.\n total_z = 0.\n total_mass = 0.\n for atom in self.atoms:\n total_x += self.atom_coordinates[structure][atom.index][0] * atom.mass\n total_y += self.atom_coordinates[structure][atom.index][1] * atom.mass\n total_z += self.atom_coordinates[structure][atom.index][2] * atom.mass\n total_mass += atom.mass\n return [total_x/total_mass, total_y/total_mass, total_z/total_mass]\n else:\n return [0., 0., 0.]\n\n def center_of_coordinates(self, structure=None):\n \"\"\"Calculates the center of coordinates\"\"\"\n if not structure:\n structure = self.representative_id\n atoms = [atom for atom in self.atoms if not atom.is_hydrogen()]\n dimension = len(atoms)\n if dimension:\n total_x = 0.\n total_y = 0.\n total_z = 0.\n for atom in atoms:\n total_x += self.atom_coordinates[structure][atom.index][0]\n total_y += self.atom_coordinates[structure][atom.index][1]\n total_z += self.atom_coordinates[structure][atom.index][2]\n return [total_x/dimension, total_y/dimension, total_z/dimension]\n else:\n return [0., 0., 0.]\n\n def translate(self, vector):\n \"\"\"Translates atom coordinates based on vector\"\"\"\n for coordinates in self.atom_coordinates:\n coordinates.translate(vector)\n\n def rotate(self, q):\n \"\"\"Rotates this complex using a quaternion q\"\"\"\n for coordinates in self.atom_coordinates:\n coordinates.rotate(q)\n\n def move_to_origin(self):\n \"\"\"Moves the structure to the origin of coordinates\"\"\"\n translation = [-1*c for c in self.center_of_coordinates()]\n self.translate(translation)\n\n def __getitem__(self, item):\n return self.atom_coordinates[item]\n\n def __setitem__(self, index, item):\n self.atom_coordinates[index] = item\n\n def __iter__(self):\n for coordinates in self.atom_coordinates:\n yield coordinates\n\n def __len__(self):\n return self.atom_coordinates.shape[0]\n\n def representative(self):\n return self.atom_coordinates[self.representative_id]\n","sub_path":"symmlightdock/structure/complex.py","file_name":"complex.py","file_ext":"py","file_size_in_byte":5399,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"199194301","text":"import csv\nimport matplotlib.pyplot as plt\nimport argparse\nimport os\nimport numpy as np\nimport math\nparser = argparse.ArgumentParser(description='Plotting Reward')\nparser.add_argument('--load_level', default= 0, type=int, help = 'Set if there are different load levels, 1 is with changing load levels')\nparser.add_argument('--average', default= 1, type=int, help = 'How many datapoints should be plotted as an average')\nargs = parser.parse_args()\n# check how many folders\n\nplt.figure()\n\ndirList= []\nfolder = ['Random', 'SPF']\nsteps = 30\nfor fld in folder:\n\tprint(fld)\n\tdirss = os.listdir(fld)\n\t#folderStr = fld + '/' + dirss\n\tfor dir in dirss:\n\t\tdirStr = fld + '/' + dir\n\t\tprint(\"Dir: {}\".format(dirStr))\n\t\tif os.path.isdir(dirStr):\n\t\t dirList.append(dirStr)\n\tprint(dirList)\n\tdataList = []\n\tfor dir in dirList:\n\n\t\tif args.load_level:\n\t\t # read Out Mininet\n\t\t mininetTimeStampLoadList = []\n\t\t mininetLoadList = []\n\t\t with open('timestamp_changing_load_levels_mininet.csv') as csvfile:\n\t\t reader = csv.reader(csvfile, delimiter= ',')\n\t\t for row in reader:\n\t\t if '#' not in row[0]:\n\t\t mininetTimeStampLoadList.append(row[1])\n\t\t mininetLoadList.append(row[0])\n\t\t timeStampRowIterator = 0\n\t\t verticalLineList = []\n\n\t\trewardList = []\n\t\tstepList = []\n\n\t\t# read out reward\n\t\twith open('{}/reward_controller.csv'.format(dir)) as csvfile:\n\t\t reader = csv.reader(csvfile, delimiter= ',')\n\t\t rowIterator = 0\n\t\t for row in reader:\n\t\t if '#' not in row[0]:\n\t\t if int(row[0]) < 5000:\n\t\t rewardList.append(float(row[1]))\n\t\t stepList.append(int(row[0]))\n\t\t if args.load_level:\n\t\t time = row[2]\n\t\t if timeStampRowIterator < len(mininetLoadList):\n\t\t if time > mininetTimeStampLoadList[timeStampRowIterator]:\n\t\t verticalLineList.append((int(row[0]), mininetLoadList[timeStampRowIterator]))\n\t\t timeStampRowIterator += 1\n\t\t rowIterator += 1\n\t\t else:\n\t\t break\n\n\t\tif args.load_level:\n\t\t print(verticalLineList)\n\t\t for verticalLine in verticalLineList:\n\t\t plt.axvline(verticalLine[0], color='g')\n\t\t if(int(verticalLine[1]) > 1):\n\t\t plt.text(verticalLine[0] + 1, -13, s=str(verticalLine[1]), rotation=90)\n\t\t else:\n\t\t plt.text(verticalLine[0] + 1, -13, s='End', rotation=90)\n\t\tdataList.append((stepList, rewardList))\n\taverage = args.average\n\tif not args.load_level:\n\t\tprint(dataList)\n\t\tlowest = math.inf\n\t\tfor data in dataList:\n\t\t if lowest > len(data[0]):\n\t\t lowest = len(data[0])\n\t\tsteps = lowest // average\n\t\tdataPointList = {}\n\t\tfor step in range(0, steps):\n\t\t lowBorder = step * average\n\t\t highBorder = (step+1) * average\n\t\t dataPointList[step] = []\n\t\t for data in dataList:\n\t\t dataArray = []\n\t\t for x in range(lowBorder, highBorder):\n\t\t dataArray.append(data[1][x])\n\t\t dataPointList[step].append(np.average(dataArray))\n\t\tprint(dataPointList)\n\n\tx = []\n\ty = []\n\tyerr = []\n\tyerrup = []\n\tyerrdown = []\n\tfor dataPoint in dataPointList:\n\t\tavg = np.average(dataPointList[dataPoint])\n\t\tstd = np.std(dataPointList[dataPoint])\n\t\tyerr.append(std)\n\t\tyerrup.append(avg + std)\n\t\tyerrdown.append(avg - std)\n\t\ty.append(avg)\n\t\tx.append(dataPoint)\n\n\t\n\tx = x[:steps]\n\ty = y[:steps]\n\tyerrup = yerrup[:steps]\n\tyerrdown = yerrdown[:steps]\n\n\tplt.plot(x, y, label='{}'.format(fld))\n\tplt.fill_between(x, yerrup, yerrdown, alpha=.2)\n\nplt.xlabel('Steps')\nplt.ylabel('Average Reward')\nplt.savefig('Average_Reward.pdf')\nplt.legend(loc='lower right')\nplt.show()\n","sub_path":"0_pre_diploma/2_data_bias_SPF_Random/plot_reward_all_iterations_folder.py","file_name":"plot_reward_all_iterations_folder.py","file_ext":"py","file_size_in_byte":3726,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"38569652","text":"# uncompyle6 version 3.7.4\n# Python bytecode 3.7 (3394)\n# Decompiled from: Python 3.6.9 (default, Apr 18 2020, 01:56:04) \n# [GCC 8.4.0]\n# Embedded file name: build/bdist.macosx-10.14-x86_64/egg/a3cosmos_gas_evolution/Common_Python_Code/calc_dust_opacity_kappa.py\n# Compiled at: 2019-07-18 22:30:15\n# Size of source mod 2**32: 845 bytes\nfrom __future__ import print_function\nimport os, sys, re, json, time, astropy, numpy as np\nif sys.version_info.major >= 3:\n long = int\nelse:\n if __name__ == '__main__':\n if len(sys.argv) <= 1:\n print('Usage: ')\n print('calc_dust_opacity_kappa.py lambda_um')\n print('')\n sys.exit()\n else:\n lambda_um = float(sys.argv[1])\n if lambda_um >= 700.0:\n beta = 1.68\n else:\n beta = 2.0\n kappa_ = 0.596 * (lambda_um / 700.0) ** (-beta)\n print(kappa_, '[cm^2 g^{-1}]')","sub_path":"pycfiles/a3cosmos_gas_evolution-1.0.0-py3.7/calc_dust_opacity_kappa.cpython-37.py","file_name":"calc_dust_opacity_kappa.cpython-37.py","file_ext":"py","file_size_in_byte":933,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"289379194","text":"#! /usr/bin/env python\n\n## Takes a mapped tree and dictionary file from phylip_map.py as \n# input and replaces the mapped taxon names (seq0, seq1..) with their\n# original names.\n\nUsage = \"\"\"\ntree_unmap.py \n\"\"\"\n\nfrom Bio import Phylo\nimport sys \nimport copy\n\ninfile = sys.argv[1]\ninfilecore = infile.split('.')[0]\nmapping = sys.argv[2]\n\ndef get_mapping(infile): \n \"\"\"Opens file with mapping info and returns dictionary\"\"\"\n with open(infile) as map:\n my_map = eval(map.read().strip('\\n'))\n return my_map \n \ndef get_value(dict, key):\n \"\"\"Returns dictionary value for key\"\"\"\n return dict[key]\n \ntree = Phylo.read(infile, \"nexus\")\nnewtree = copy.deepcopy(tree) ## Copy input tree\n\n#replace terminal names (keys: seq0...) with their values from input\n#dictionary.\nfor clade in newtree.get_terminals():\n clade.name = get_value(get_mapping(mapping), clade.name.strip(\"'\"))\n \nPhylo.write([newtree], infilecore + \"_unmap.nex\", \"nexus\")\n \n","sub_path":"tree_unmap_nex.py","file_name":"tree_unmap_nex.py","file_ext":"py","file_size_in_byte":1147,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"225426259","text":"import numpy as np\nfrom netCDF4 import Dataset\nfrom numba import jit\n\nfrom matplotlib import pyplot as plt\nimport timeit\n\nimport cProfile, pstats, io\nfrom pstats import SortKey\n\n#comment out the line below to see how much slower regular python is\n\n@jit(nopython = True)\ndef AtmLevelWts_Numba( weighting_function = None,\n surface_weight = None,\n space_weight = None,\n pressure = None,\n pressure_bounds = None,\n surface_pressure = None,\n temp_profiles = None,\n ts = None,\n num_lats = None,\n num_lons = None,\n num_levels = None,\n ps = None,\n levels = None,\n land_frac = None,\n surface = None):\n '''\n\n :param weighting_function:\n :param surface_weight:\n :param space_weight:\n :param pressure:\n :param pressure_bounds:\n :param surface_pressure:\n :param temp_profiles:\n :param ts:\n :param num_lats:\n :param num_lons:\n :param num_levels:\n :param ps:\n :param levels:\n :param land_frac:\n :param surface:\n :return:\n '''\n\n MAX_SURF_PRESSURE = 1100.0\n MIN_SURF_PRESSURE = 500.0\n level_wts = np.zeros((num_levels,num_lats,num_lons))\n surface_wts = np.zeros((num_lats,num_lons))\n space_wts = np.zeros((num_lats,num_lons))\n tbs = np.zeros((num_lats,num_lons))\n\n\n for ilat in np.arange(0, num_lats):\n for ilon in range(0, num_lons):\n ps_flt = ps[ilat, ilon]\n\n ps_int = int(np.round(ps_flt))\n if ps_int > MAX_SURF_PRESSURE:\n raise ValueError('Surface pressure > 1100 hPa')\n if ps_int < MIN_SURF_PRESSURE:\n raise ValueError('Surface pressure < 500 hPa')\n for ps_index in np.arange(0,600):\n if ps_int == surface_pressure[ps_index]:\n break\n wt_func = weighting_function[:, ps_index]\n surf_wt = surface_weight[ps_index]\n space_wt = space_weight[ps_index]\n\n above_surf = np.where(levels < ps_int)\n lowest_level = above_surf[0][-1]\n\n p_lower = ps_int\n p_upper = levels[lowest_level]\n index_lower = np.where(p_lower >= pressure)[0][0]\n index_upper = np.where(p_upper >= pressure)[0][0]\n\n p_layer = p_lower - 0.5 - np.arange(0, index_upper - index_lower)\n T_lower_wt_temp = 1.0 - (np.log(p_layer / p_lower) / np.log(p_upper / p_lower))\n T_upper_wt_temp = np.log(p_layer / p_lower) / np.log(p_upper / p_lower)\n\n T_lower_wt = np.sum(T_lower_wt_temp * wt_func[index_lower:index_upper])\n T_upper_wt = np.sum(T_upper_wt_temp * wt_func[index_lower:index_upper])\n\n surf_wt = surf_wt + T_lower_wt\n wt_ref = np.zeros((num_levels))\n wt_ref[lowest_level] += T_upper_wt\n\n # Now step through the rest of the levels\n for i in np.arange(lowest_level, 0, -1):\n p_lower = levels[i]\n p_upper = levels[i - 1]\n index_lower = np.where(p_lower >= pressure)[0][0]\n index_upper = np.where(p_upper >= pressure)[0][0]\n\n if index_upper > index_lower:\n p_layer = p_lower - 0.5 - np.arange(0, index_upper - index_lower)\n T_lower_wt_temp = 1 - (np.log(p_layer / p_lower) / np.log(p_upper / p_lower))\n T_upper_wt_temp = np.log(p_layer / p_lower) / np.log(p_upper / p_lower)\n T_lower_wt = np.sum(T_lower_wt_temp * wt_func[index_lower:index_upper])\n T_upper_wt = np.sum(T_upper_wt_temp * wt_func[index_lower:index_upper])\n else:\n T_lower_wt = 0.0\n T_upper_wt = 0.0\n # print(i, T_lower_wt, T_upper_wt)\n wt_ref[i - 1] = wt_ref[i - 1] + T_upper_wt\n wt_ref[i] = wt_ref[i] + T_lower_wt\n\n p_lower = levels[0]\n p_upper = pressure[-1]\n index_lower = np.where(p_lower >= pressure)[0][0]\n index_upper = np.where(p_upper >= pressure)[0][0]\n\n # now the very top levels\n if ((index_upper > index_lower) and (index_upper > 0) and (index_lower > 0)):\n p_layer = p_lower - 0.5 - np.arange(0, index_upper - index_lower)\n T_lower_wt_temp = 1 - (np.log(p_layer / p_lower) / np.log(p_upper / p_lower))\n T_upper_wt_temp = np.log(p_layer / p_lower) / np.log(p_upper / p_lower)\n t_lower_wt = np.sum(T_lower_wt_temp * wt_func[index_lower:index_upper])\n t_upper_wt = np.sum(T_upper_wt_temp * wt_func[index_lower:index_upper])\n else:\n t_lower_wt = 0.0\n t_upper_wt = 0.0\n\n # for this last level, we include the weight from the level all the way to\n # the highest pressure\n\n wt_ref[0] = wt_ref[0] + t_lower_wt\n wt_ref[0] = wt_ref[0] + t_upper_wt\n\n level_wts[:,ilat,ilon] = wt_ref\n surface_wts[ilat,ilon] = surf_wt\n space_wts[ilat,ilon] = space_wt\n\n tbs[ilat,ilon] = ts[ilat,ilon]*surf_wt + np.sum(temp_profiles[:,ilat,ilon]*wt_ref) + space_wt*2.730\n\n return tbs,level_wts,surface_wts,space_wts\n\nclass AtmWt():\n '''Class for level weights for MSU/AMSU'''\n\n def __init__(self, channel='TLT',surface = 'ocean',RTM_Data_Path='./data/',verbose=True):\n\n path = RTM_Data_Path + 'wt_tables/'\n nc_file = path + 'std_atmosphere_wt_function_msu_chan_'+channel+'_'+surface+'_by_surface_pressure.1100.V4.nc'\n if verbose:\n print('Reading: ' + nc_file)\n nc_fid = Dataset(nc_file, 'r')\n self.surface = surface\n pressure = np.array(nc_fid.variables['pressure'][:]) # extract/copy the data\n self.pressure = pressure\n pressure_bounds = np.array(nc_fid.variables['pressure_bounds'][:])\n self.pressure_bounds = pressure_bounds\n surface_pressure = np.array(nc_fid.variables['surface_pressure'][:])\n surface_pressure = surface_pressure.astype(np.int32)\n self.surface_pressure = surface_pressure\n surface_weight = np.array(nc_fid.variables['surface_weight'][:])\n self.surface_weight = surface_weight\n\n space_weight = np.array(nc_fid.variables['space_weight'][:])\n self.space_weight = space_weight\n weighting_function = np.array(nc_fid.variables['weighting_function'][:,:])\n self.weighting_function = weighting_function\n\n def AtmLevelWts(self, temp_profiles = None, ps = None, ts = None,levels = None,land_frac=None):\n\n '''\n\n :param temp_profiles: numpy array of temperature profiles to be converted to MSU equivalent Assumed to be 3D [levels,lat,lon]\n Assumed to ordered low P to high P\n Units = K\n :param ps: numpy array containing surface pressure to be converted. Assumed to be 2D [lat,lon].\n Units = hPa\n :param ts: numpy array containing surface temperature to be converted. Assumed to be 2D [lat,lon].\n Units K\n :param levels: numpy array of level pressures for the profiles in temp proffiles. Assumed to ordered low P to high P.\n Units = hPa\n :param land_frac: numpy array of land fraction. Assumed to be 2D [lat,lon].\n Units = fraction, 0.0 to 1.0\n :return values:\n tbs numpy array of MSU equivalent brightness temperatures, 2D, [lat,lon]\n level_wts numpy array of level weights, 3D, [level_index,lat,lon]\n surface_wts numpy array of surface weights, 2D, [lat,lon]\n space_wts numpy array of \"space\" weights, 2D, [lat,lon]. Multiplied by 2.73K in routine\n '''\n\n sz1 = temp_profiles.shape\n sz2 = ps.shape\n sz3 = levels.shape\n\n try:\n assert(sz1[0] == sz3[0])\n assert(sz1[1] == sz2[0])\n assert(sz1[2] == sz2[1])\n except:\n raise ValueError('Array sizes do not match in AtmLevelWts')\n\n tbs,level_wts,surface_wts,space_wts = AtmLevelWts_Numba(weighting_function = self.weighting_function,\n surface_weight = self.surface_weight,\n space_weight = self.space_weight,\n pressure = self.pressure,\n surface_pressure = self.surface_pressure,\n pressure_bounds = self.pressure_bounds,\n temp_profiles = temp_profiles,\n ts = ts,\n num_lats = sz1[1],\n num_lons = sz1[2],\n num_levels = sz1[0],\n ps = ps,\n levels = levels,\n land_frac = land_frac,\n surface = self.surface)\n return tbs,level_wts,surface_wts,space_wts\n\nif __name__ == '__main__':\n\n from era5_monthly import read_era5_monthly_means_3D, read_era5_monthly_means_2D\n from global_map import global_map\n\n import xarray as xr\n year = 2000\n month = 1\n channel = 'TLS'\n use_t2m = True\n perform_profile = True\n d = read_era5_monthly_means_3D(year=year, month=month, variable='temperature',\n era5_path='./era5/monthly/3D/')\n t = (d['T'][0, :, :, :]).astype(np.float32) #Temperature in Kelvin\n levels = (d['levels'][:]).astype(np.float32) #Pressure Levels in hPa\n\n\n ps = read_era5_monthly_means_2D(year=year, month=month, variable='surface_pressure',\n era5_path='./era5/monthly/2D/')['PS'][0, :, :]\n #ps in ERA5 is in Pa\n #convert to hPa\n ps = (ps/100.0).astype(np.float32)\n\n if use_t2m: #both types of ts are in Kelvin\n ts = read_era5_monthly_means_2D(year=year, month=month, variable='2m_temperature',\n era5_path='./era5/monthly/2D/')['T2m'][0, :, :]\n #this ts is the 2m air temperature.\n # advantages of use: more closelt tied to observations\n # disadvantage: Not really what the satellite sees. The difference between T2m and Tskin can be large\n # under daytime and night time clear sky conditions\n else:\n ts = read_era5_monthly_means_2D(year=year, month=month, variable='skin_temperature',\n era5_path='./era5/monthly/2D/')['TSkin'][0, :, :]\n # this ts is the skin temperature as relevant to long-wave IR\n # advantage of use: closer to microwave skin temperature, at least for moist soils\n # disadvantage: appears to be a sort of free parameter in the model which is adjusted to satisfy\n # energy balance\n # for dry soil, Longwave IR and MW penetration depth are very different.\n\n ts = ts.astype(np.float32)\n\n land_frac = read_era5_monthly_means_2D(year=year, month=month, variable = 'land_sea_mask',\n era5_path='./era5/monthly/2D/')['land_frac'][0, :, :]\n\n sea_ice_frac = read_era5_monthly_means_2D(year=year, month=month, variable = 'sea_ice_cover',\n era5_path='./era5/monthly/2D/')['SeaIce'][0, :, :]\n\n sea_ice_frac[np.isnan(sea_ice_frac)] = 0.0\n sea_ice_frac[sea_ice_frac < -1.0] = 0.0\n not_ocean = land_frac + sea_ice_frac\n not_ocean[not_ocean > 1.0] = 1.0\n\n #initialize AtmWt classes.\n AtmWt_MSU_Ocean = AtmWt(channel = channel,surface = 'ocean')\n AtmWt_MSU_Land = AtmWt(channel = channel,surface = 'land')\n\n if perform_profile:\n #start the profiler\n pr = cProfile.Profile()\n pr.enable()\n\n # calculate the Tbs and weights.\n print('Performing Ocean Calculation')\n tbs_ocean,level_wts_ocean,surface_wts_ocean,space_wts_ocean = AtmWt_MSU_Ocean.AtmLevelWts(temp_profiles=t,ts = ts, ps=ps, levels=levels,land_frac=not_ocean)\n print('Performing Land Calculation')\n tbs_land,level_wts_land, surface_wts_land, space_wts_land = AtmWt_MSU_Land.AtmLevelWts(temp_profiles=t,ts = ts, ps=ps, levels=levels,land_frac=not_ocean)\n\n if perform_profile:\n # end profiled section\n pr.disable()\n\n #report the profiles info.\n s = io.StringIO()\n sortby = SortKey.TIME\n ps1 = pstats.Stats(pr, stream=s).sort_stats(sortby)\n ps1.print_stats(0.01)\n print(s.getvalue())\n\n # combine the land and ocean results together.\n surface_wts_combined = not_ocean * surface_wts_land + (1.0 - not_ocean)*surface_wts_ocean\n tbs_combined = not_ocean * tbs_land + (1.0 - not_ocean)*tbs_ocean\n\n # adjust to match RSS plotting routine\n not_ocean_to_plot = np.roll(np.flipud(not_ocean),shift = 180,axis=(1))\n surface_wts_land = np.roll(np.flipud(surface_wts_land),shift = 180,axis=(1))\n surface_wts_ocean = np.roll(np.flipud(surface_wts_ocean),shift = 180,axis=(1))\n surface_wts_combined = np.roll(np.flipud(surface_wts_combined),shift=180,axis=1)\n\n ps = np.roll(np.flipud(ps),shift=180,axis=1)\n ts = np.roll(np.flipud(ts),shift=180,axis=1)\n\n tbs_land = np.roll(np.flipud(tbs_land),shift=180,axis=1)\n tbs_ocean = np.roll(np.flipud(tbs_ocean),shift=180,axis=1)\n tbs_combined = np.roll(np.flipud(tbs_combined),shift=180,axis=1)\n\n # make plots for sanity check.\n global_map(surface_wts_combined,vmin = 0.0,vmax = 0.3,plt_colorbar = True,title = channel+' surface weights')\n global_map(tbs_combined,vmin = 190.0,vmax = 240.0,plt_colorbar = True,title = channel+' Brightness Temperature(K)')\n global_map(not_ocean_to_plot,vmin = 0.0,vmax = 1.0,plt_colorbar = True,title = channel+' land and ice fraction')\n plt.show()\n\n # read in data from IDL calculation\n compare_file_name = f\"./test/ERA5_test_case_msu_channel_{channel}_{year:04}_{month:02}.nc\"\n d = xr.open_dataset(compare_file_name)\n #roll it in longitude by 180 degrees to match the python maps\n tbs_from_idl = np.roll(d['Tb'].values, shift=180, axis=1)\n tbs_land_from_idl = np.roll(d['Tb_land'].values, shift=180, axis=1)\n tbs_ocean_from_idl = np.roll(d['Tb_ocean'].values, shift=180, axis=1)\n not_ocean_idl = np.roll(d['land_fraction'].values, shift=180, axis=1)\n\n global_map(tbs_combined,vmin = 220.0,vmax = 280.0,plt_colorbar = True,title = channel+' Brightness Temperature(K), from Python')\n global_map(tbs_from_idl,vmin = 220.0,vmax = 280.0,plt_colorbar = True,title = channel+' Brightness Temperature(K), from IDL')\n global_map(tbs_combined - tbs_from_idl,vmin =-0.02,vmax = 0.02,plt_colorbar = True,title = channel+' Brightness Temperature(K), from IDL')\n\n land_diff = tbs_land - tbs_land_from_idl\n ocean_diff = tbs_ocean - tbs_ocean_from_idl\n comb_diff = tbs_combined - tbs_from_idl\n\n print(np.min(land_diff),np.max(land_diff),np.mean(land_diff),np.std(land_diff))\n print(np.min(ocean_diff),np.max(ocean_diff),np.mean(ocean_diff),np.std(ocean_diff))\n print(np.min(comb_diff),np.max(comb_diff),np.mean(comb_diff),np.std(comb_diff))\n\n print()\n plt.show()\n print\n\n\n\n\n print\n\n\n\n","sub_path":"AtmWts_method_1.py","file_name":"AtmWts_method_1.py","file_ext":"py","file_size_in_byte":16103,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"596436213","text":"import requests\nimport json\n\ndata_base = []\nclient_id = '2c3e7b46480cfde24db5'\nclient_secret = '109bf0bc21498512f3ae1194efdd17ef'\nr = requests.post('https://api.artsy.net/api/tokens/xapp_token',\n data={'client_id': client_id,\n 'client_secret': client_secret\n })\nj = json.loads(r.text)\ntoken = j['token']\nheaders = {'X-Xapp-Token': token}\n\nwith open('dataset_24476_4.txt') as inf:\n for line in inf:\n artist_id = line.strip()\n response = requests.get('https://api.artsy.net/api/artists/' + artist_id, headers=headers)\n artist_data = json.loads(response.text)\n name = artist_data['sortable_name']\n birth = str(artist_data['birthday'])\n data_base.append(birth + name)\n\ndata_base.sort()\nfor i in data_base:\n print(i[4:])\n","sub_path":"3_6 API/task2.py","file_name":"task2.py","file_ext":"py","file_size_in_byte":821,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"411743037","text":"from django.urls import path\n\nfrom .api_views import (\n CategoryDetailAPIView, \n BeerProductListAPIView, \n BeerProductDetailAPIView, \n CustomersListAPIView,\n CustomerDetailAPIView,\n CategoryAPIView, \n PizzaProductAPIView,\n PizzaProductDetailAPIView,\n UserAPIView,\n UserDetailAPIView,\n CartProductAPIView,\n CartProductDetailAPIView,\n CartAPIView,\n CartDetailAPIView,\n OrderAPIView,\n OrderDetailAPIView\n)\n\n\nurlpatterns = [\n path('categories/', CategoryAPIView.as_view(), name='categories_list'),\n path('categories//', CategoryDetailAPIView.as_view(), name='category_detail'),\n path('customers/', CustomersListAPIView.as_view(), name='customers_list'),\n path('customers//', CustomerDetailAPIView.as_view(), name='customer_detail'),\n path('beer/', BeerProductListAPIView.as_view(), name='beer_list'),\n path('beer//', BeerProductDetailAPIView.as_view(), name='beer_detail'),\n path('pizza/', PizzaProductAPIView.as_view(), name='pizza_list'),\n path('pizza//', PizzaProductDetailAPIView.as_view(), name='pizza_detail'),\n path('orders/', OrderAPIView.as_view(), name='orders_list'),\n path('orders//', OrderDetailAPIView.as_view(), name='order_detail'),\n path('carts/', CartAPIView.as_view(), name='carts_list'),\n path('carts//', CartDetailAPIView.as_view(), name='cart_detail'),\n path('cartproducts/', CartProductAPIView.as_view(), name='cartproducts_list'),\n path('cartproducts//', CartProductDetailAPIView.as_view(), name='cartproduct_detail'),\n path('users/', UserAPIView.as_view(), name='users_list'),\n path('users//', UserDetailAPIView.as_view(), name='user_detail'),\n]","sub_path":"pizza_shop/mainapp/api/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1728,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"245948154","text":"import discord\r\nfrom base64 import *\r\nimport codecs\r\nimport json, io\r\nimport time\r\n\r\nimport dicttoxml\r\nfrom random import randint\r\nimport os\r\nfrom struct import *\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\nclient = discord.Client()\r\n #if not os.path.exists(\"Another_Save_File/Thing1\"):\r\n #os.makedirs(\"Another_Save_File/Thing1\")\r\n\r\n\r\ndef MakeAltSave(UserID, SaveFolderName):\r\n if not os.path.exists(\"Another_Save_File/\" + str(UserID)):\r\n os.makedirs(\"Another_Save_File/\" + str(UserID))\r\n if not os.path.exists(\"Another_Save_File/\" + str(UserID) + \"/\" + SaveFolderName):\r\n os.makedirs(\"Another_Save_File/\" + str(UserID) + \"/\" + SaveFolderName)\r\n\r\n with codecs.open(\"Another_Save_File/\"+ str(UserID) + \"/\" + SaveFolderName + \"/Life.ini\", \"w\", \"utf-8\") as file:\r\n life = 0\r\n life = str(life)\r\n life = life.encode('utf-8')\r\n file.write((b85encode(life)).decode('utf-8'))\r\n\r\n with codecs.open(\"Another_Save_File/\" + str(UserID) + \"/\" + SaveFolderName +\"/LifeMax.ini\", \"w\", \"utf-8\") as file:\r\n lifeMax = 0\r\n lifeMax = str(lifeMax)\r\n lifeMax = lifeMax.encode('utf-8')\r\n file.write((b85encode(lifeMax)).decode('utf-8')) \r\n\r\n with codecs.open(\"Another_Save_File/\" + str(UserID) + \"/\" + SaveFolderName + \"/Power.ini\", \"w\", \"utf-8\") as file:\r\n power = 0\r\n power = str(power)\r\n power = power.encode('utf-8')\r\n file.write((b85encode(power)).decode('utf-8'))\r\n\r\n with codecs.open(\"Another_Save_File/\" + str(UserID) + \"/\" + SaveFolderName + \"/PowerMax.ini\", \"w\", \"utf-8\") as file:\r\n powerMax = 0\r\n powerMax = str(powerMax)\r\n powerMax = powerMax.encode('utf-8')\r\n file.write((b85encode(powerMax)).decode('utf-8')) \r\n\r\n with codecs.open(\"Another_Save_File/\" + str(UserID) + \"/\" + SaveFolderName + \"/XP.ini\", \"w\", \"utf-8\") as file:\r\n XP = 0\r\n XP = str(XP)\r\n XP = XP.encode('utf-8')\r\n file.write((b85encode(XP)).decode('utf-8')) \r\n\r\n with codecs.open(\"Another_Save_File/\" + str(UserID) + \"/\" + SaveFolderName + \"/LastSlept.ini\", \"w\", \"utf-8\") as file:\r\n lastslept = (\"%d\" % time.time())\r\n lastslept = lastslept.encode('utf-8')\r\n file.write((b85encode(lastslept)).decode('utf-8')) \r\n\r\n with codecs.open(\"Another_Save_File/\" + str(UserID)+ \"/\" + SaveFolderName + \"/Money.ini\", \"w\", \"utf-8\") as file:\r\n money = 0\r\n money = str(money)\r\n money = money.encode('utf-8')\r\n file.write((b85encode(money)).decode('utf-8')) \r\n\r\n with codecs.open(\"Another_Save_File/\" + str(UserID) + \"/\" + SaveFolderName + \"/Attack.ini\", \"w\", \"utf-8\") as file:\r\n atkval = 0\r\n atkval = str(atkval)\r\n atkval = atkval.encode('utf-8')\r\n file.write((b85encode(atkval)).decode('utf-8')) \r\n\r\n with codecs.open(\"Another_Save_File/\" + str(UserID) + \"/\" + SaveFolderName + \"/Defense.ini\", \"w\", \"utf-8\") as file:\r\n defval = 0\r\n defval = str(defval)\r\n defval = defval.encode('utf-8')\r\n file.write((b85encode(defval)).decode('utf-8')) \r\n\r\n with codecs.open(\"Another_Save_File/\" + str(UserID) + \"/\" + SaveFolderName + \"/Level.ini\", \"w\", \"utf-8\") as file:\r\n lvl = 0\r\n lvl = str(lvl)\r\n lvl = lvl.encode('utf-8')\r\n file.write((b85encode(lvl)).decode('utf-8')) \r\n\"\"\"\r\nClasses\r\n-----------------------------\r\nNone Yet....\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\"\"\"\r\ndef MakeBinaryFile(UserID):\r\n PackFormat = \"5qB2Q?Bf\"\r\n BinarySaveFileData = {}\r\n if not os.path.exists(str(UserID)): os.makedirs(\"Bin_Data/\" + str(UserID))\r\n #if UserID in BinarySaveFileData is False:\r\n BinarySaveFileData[UserID] = {}\r\n BinarySaveFileData[UserID][\"file\"] = open(\"Bin_Data/\" + str(UserID) + \"/Save.dat\", \"wb\")\r\n BinarySaveFileData[UserID][\"Life\"] = randint(0,2**48)\r\n BinarySaveFileData[UserID][\"LifeMax\"] = randint(BinarySaveFileData[UserID][\"Life\"],2**48)\r\n BinarySaveFileData[UserID][\"Power\"] = randint(0,2**48)\r\n BinarySaveFileData[UserID][\"PowerMax\"] = randint(BinarySaveFileData[UserID][\"Power\"],2**48)\r\n BinarySaveFileData[UserID][\"MoneyPockets\"] = randint(0,2**48)\r\n BinarySaveFileData[UserID][\"MoneyBank\"] = randint(0,2**48)\r\n BinarySaveFileData[UserID][\"XP\"] = 0\r\n BinarySaveFileData[UserID][\"Level\"] = randint(0,2147483647)%255#255\r\n BinarySaveFileData[UserID][\"IsPoison\"] = True\r\n BinarySaveFileData[UserID][\"PoisonTurns\"] = 1\r\n BinarySaveFileData[UserID][\"SomeFloat\"] = 25.000\r\n BinarySaveFileData[UserID][\"writeData\"] = pack(PackFormat, BinarySaveFileData[UserID][\"Life\"], BinarySaveFileData[UserID][\"LifeMax\"],BinarySaveFileData[UserID][\"Power\"],BinarySaveFileData[UserID][\"PowerMax\"],BinarySaveFileData[UserID][\"XP\"],BinarySaveFileData[UserID][\"Level\"],BinarySaveFileData[UserID][\"MoneyPockets\"],BinarySaveFileData[UserID][\"MoneyBank\"],BinarySaveFileData[UserID][\"IsPoison\"],BinarySaveFileData[UserID][\"PoisonTurns\"],BinarySaveFileData[UserID][\"SomeFloat\"])\r\n BinarySaveFileData[UserID][\"file\"].write(BinarySaveFileData[UserID][\"writeData\"])\r\n BinarySaveFileData[UserID][\"file\"].close()\r\n\r\npass\r\n\r\n\r\ndef GetStats(message):\r\n format = \"HB\"\r\n if not os.path.exists('Temp_RP_Data/' + message.author.id):\r\n os.makedirs('Temp_RP_Data/' + message.author.id)\r\n with open('Temp_RP_Data/' + message.author.id + '/Save.dat', 'wb') as file:\r\n a = randint(0,1000)\r\n b = randint(0,100)\r\n file.write(pack(format, a, b))\r\n return unpack(format, open('Temp_RP_Data/' + message.author.id + '/Save.dat', 'wb'))","sub_path":"Python/The_Cypher_Bot_MK2/Plugin_Scripts/RP_Code/RP.py","file_name":"RP.py","file_ext":"py","file_size_in_byte":5123,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"228908657","text":"# pin courtsey PAPERPLANE\n\n\"\"\"Pins the replied message\nSyntax: .cpin [LOUD], Pin [silent]\"\"\"\nfrom telethon import events\nfrom asyncio import sleep\nfrom os import remove\n\nfrom telethon.errors import (BadRequestError, ChatAdminRequiredError,\n ImageProcessFailedError, PhotoCropSizeSmallError,\n UserAdminInvalidError)\nfrom telethon.errors.rpcerrorlist import (UserIdInvalidError,\n MessageTooLongError)\nfrom telethon.tl.functions.channels import (EditAdminRequest,\n EditBannedRequest,\n EditPhotoRequest)\nfrom telethon.tl.functions.messages import UpdatePinnedMessageRequest\nfrom telethon.tl.types import (PeerChannel, ChannelParticipantsAdmins,\n ChatAdminRights, ChatBannedRights,\n MessageEntityMentionName, MessageMediaPhoto,\n ChannelParticipantsBots)\n\nfrom telethon.tl import functions, types\nfrom uniborg.util import admin_cmd\nfrom platform import python_version, uname\nfrom sample_config import Config\n\n\n# =================== CONSTANT ===================\nPP_TOO_SMOL = \"`The image is too small`\"\nPP_ERROR = \"`Failure while processing the image`\"\nNO_ADMIN = \"`I am not an admin!`\"\nNO_PERM = \"`I don't have sufficient permissions!`\"\nNO_SQL = \"`Running on Non-SQL mode!`\"\n\nCHAT_PP_CHANGED = \"`Chat Picture Changed`\"\nCHAT_PP_ERROR = \"`Some issue with updating the pic,`\" \\\n \"`maybe coz I'm not an admin,`\" \\\n \"`or don't have enough rights.`\"\nINVALID_MEDIA = \"`Invalid Extension`\"\n\nBANNED_RIGHTS = ChatBannedRights(\n until_date=None,\n view_messages=True,\n send_messages=True,\n send_media=True,\n send_stickers=True,\n send_gifs=True,\n send_games=True,\n send_inline=True,\n embed_links=True,\n)\n\nUNBAN_RIGHTS = ChatBannedRights(\n until_date=None,\n send_messages=None,\n send_media=None,\n send_stickers=None,\n send_gifs=None,\n send_games=None,\n send_inline=None,\n embed_links=None,\n)\n\nMUTE_RIGHTS = ChatBannedRights(until_date=None, send_messages=True)\n\nUNMUTE_RIGHTS = ChatBannedRights(until_date=None, send_messages=False)\nBOTLOG = Config.BOTLOG\nBOTLOG_CHATID = Config.PRIVATE_GROUP_BOT_API_ID\n# ================= CONSTANT =================\n\n@borg.on(admin_cmd(\"cpin ?(.*)\"))\nasync def _(event):\n if event.fwd_from:\n return\n silent = True\n input_str = event.pattern_match.group(1)\n if input_str:\n silent = False\n if event.message.reply_to_msg_id is not None:\n message_id = event.message.reply_to_msg_id\n try:\n await borg(functions.messages.UpdatePinnedMessageRequest(\n event.chat_id,\n message_id,\n silent\n ))\n except Exception as e:\n await event.edit(str(e))\n else:\n await event.delete()\n else:\n await event.edit(\"Reply to a message to pin the message in this Channel.\")\n\n \n@borg.on(admin_cmd(\"Pin ?(.*)\"))\nasync def pin(msg):\n \"\"\" For .Pin command, pins the replied/tagged message on the top the chat. \"\"\"\n # Admin or creator check\n chat = await msg.get_chat()\n admin = chat.admin_rights\n creator = chat.creator\n\n # If not admin and not creator, return\n if not admin and not creator:\n await msg.edit(NO_ADMIN)\n return\n\n to_pin = msg.reply_to_msg_id\n\n if not to_pin:\n await msg.edit(\"`Reply to a message to pin it.`\")\n return\n\n options = msg.pattern_match.group(1)\n\n is_silent = True\n\n if options.lower() == \"loud\":\n is_silent = False\n\n try:\n await msg.client(\n UpdatePinnedMessageRequest(msg.to_id, to_pin, is_silent))\n except BadRequestError:\n await msg.edit(NO_PERM)\n return\n\n await msg.edit(\"`Pinned Successfully!`\")\n\n user = await get_user_from_id(msg.from_id, msg)\n\n if BOTLOG:\n await msg.client.send_message(\n BOTLOG_CHATID, \"#PIN\\n\"\n f\"ADMIN: [{user.first_name}](tg://user?id={user.id})\\n\"\n f\"CHAT: {msg.chat.title}(`{msg.chat_id}`)\\n\"\n f\"LOUD: {not is_silent}\")\n\n\nasync def get_user_from_event(event):\n \"\"\" Get the user from argument or replied message. \"\"\"\n args = event.pattern_match.group(1).split(' ', 1)\n extra = None\n if event.reply_to_msg_id and not len(args) == 2:\n previous_message = await event.get_reply_message()\n user_obj = await event.client.get_entity(previous_message.from_id)\n extra = event.pattern_match.group(1)\n elif args:\n user = args[0]\n if len(args) == 2:\n extra = args[1]\n\n if user.isnumeric():\n user = int(user)\n\n if not user:\n await event.edit(\"`Pass the user's username, id or reply!`\")\n return\n\n if event.message.entities is not None:\n probable_user_mention_entity = event.message.entities[0]\n\n if isinstance(probable_user_mention_entity,\n MessageEntityMentionName):\n user_id = probable_user_mention_entity.user_id\n user_obj = await event.client.get_entity(user_id)\n return user_obj\n try:\n user_obj = await event.client.get_entity(user)\n except (TypeError, ValueError) as err:\n await event.edit(str(err))\n return None\n\n return user_obj, extra\n\n\nasync def get_user_from_id(user, event):\n if isinstance(user, str):\n user = int(user)\n\n try:\n user_obj = await event.client.get_entity(user)\n except (TypeError, ValueError) as err:\n await event.edit(str(err))\n return None\n\n return user_obj\n","sub_path":"stdplugins/pin_message.py","file_name":"pin_message.py","file_ext":"py","file_size_in_byte":5795,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"404021870","text":"import os\nimport re\nimport regex\n#from java import *\n\ndef remove_comments(string):\n #font: https://stackoverflow.com/a/18381470/8316383\n pattern = r\"(\\\".*?\\\"|\\'.*?\\')|(/\\*.*?\\*/|//[^\\r\\n]*$)\"\n # first group captures quoted strings (double or single)\n # second group captures comments (//single-line or /* multi-line */)\n regex = re.compile(pattern, re.MULTILINE|re.DOTALL)\n def _replacer(match):\n # if the 2nd group (capturing comments) is not None,\n # it means we have captured a non-quoted (real) comment string.\n if match.group(2) is not None:\n return \"\" # so we will return empty to remove the comment\n else: # otherwise, we will return the 1st group\n return match.group(1) # captured quoted-string\n return regex.sub(_replacer, string)\n\ndef separators(string):\n pattern = r\"(\\\".*?\\\"|\\'.*?\\')|(\\W)\" #r'([^a-zA-z0-9\\\"\\'\\s])'\n matches = regex.finditer(pattern, string)\n indices = [0]\n [(indices.append(m.span()[0]), indices.append(m.span()[1])) for m in matches]\n return [string[i:j].strip() for i,j in zip(indices, indices[1:]+[None]) if string[i:j]]\n\ndef recognize_function(phrase):\n result = []\n middle_pattern = r\"[\\s]([A-Za-z0-9]+[\\s]*\\([A-Za-z0-9\\[\\]\\,\\s*]*\\))\"\n end_pattern = r\"\\{\"\n mp = re.compile(middle_pattern)\n ep = re.compile(end_pattern)\n matches = []\n if (mp.search(phrase) and ep.search(phrase)):\n matches = mp.search(phrase) # [mp.search(phrase), ep.search(phrase)]\n return matches\n\ndef separate_function(phrase):\n b, e = recognize_function(phrase).span()\n components = (phrase[:b].split(\" \"), phrase[b+1:e], (phrase[e+1:-1].strip()).split(\" \"))\n return components\n\ndef separate(text):\n pattern = r\"(\\\".*?\\\"|\\'.*?\\')|([\\{\\};])\"\n regex = re.compile(pattern, re.MULTILINE|re.DOTALL)\n matches = regex.finditer(text)\n indices = [0]\n [(indices.append(m.span()[0]+1), indices.append(m.span()[1])) for m in matches if m.group(1) is None]\n return [text[i:j].strip() for i,j in zip(indices, indices[1:]+[None]) if text[i:j]]\n\ndef function_content(line, func):\n pattern1 = regex.compile(r'\\{((?:[^{}]|(?R))*)\\}')\n result = \"\"\n # return(pattern1.search(line).captures(1))\n for s in pattern1.search(line).captures(1):\n if (func + s + '}') in line:\n # print(s.replace(\"\\t\", \"\").split(\"\\n\"))\n result = s # repr(s)\n return result\n\ndef files_info(file, file_name):\n result = {}\n name = file_name.split('.')[0]\n print()\n with open(file) as f:\n total = \"\"\n for line in f:\n total = total + line # (line.replace(\"\\t\", \"\"))\n aux = remove_comments(total) # .replace(\"\\n\", \"\")\n print(name)\n for s in separate(aux):\n if recognize_function(s):\n # funct = (recognize_function(s))\n result[s] = function_content(aux, s)\n return result\n\ndef list_files(startpath = 'file/path'):\n for root, dirs, files in os.walk(startpath):\n for f in files:\n if \".java\" in f:\n # files_info(root + '/' + f, f)\n detalhes = files_info(root + '/' + f, f)\n for d in detalhes:\n #print(d, \"\\n\", repr(detalhes[d]) )\n aux = (detalhes[d].replace(\"\\t\", \"\").replace(\"\\n\", \"\").replace(\"}\", \"\")).split(\";\")\n print(separate_function(d) , \":\\n\" )\n for a in aux:\n print(separators(a))\n\nlist_files('/home/lucas/Scripts/java/fj-21-jdbc')\n\n#teste\n#import regex\n#def function_content(line):\n# pattern1 = regex.search(r'\\{((?:[^{}]|(?R))+)\\}', line)\n# #result = pattern1.(line)\n# print(line)\n# for r in pattern1.captures(1)[::-1]:\n# print(r)\n\n#function_content( \"Eu sou uma string {dentro de uma string {dentro de outra} }\" )","sub_path":"reader.py","file_name":"reader.py","file_ext":"py","file_size_in_byte":3853,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"460850316","text":"#!/usr/bin/env python\n\nimport turbotutils\nimport turbotutils.account\nimport requests\nimport json\nimport urllib\nimport operator\nfrom pprint import pprint\n\n\ndef get_notifications(turbot_host, turbot_api_access_key, turbot_api_secret_key, turbot_host_certificate_verification, namespace, api_version):\n \"\"\" Gets the turbot notification for account\n \n :param turbot_host: turbot host\n :param turbot_api_access_key: turbot access key\n :param turbot_api_secret_key: turbot secret key\n :param turbot_host_certificate_verification: should be true\n :param namespace: the turbot namespace to look for alarms\n :param api_version: api version\n :return: Returns notification_list of all active notifications\n \"\"\"\n api_method = \"GET\"\n api_url = \"/api/%s/resources/%s/controls?filter=state:alarm,error\" % (api_version, namespace)\n notification_list = []\n response = requests.request(\n api_method,\n urllib.parse.urljoin(turbot_host, api_url),\n auth=(turbot_api_access_key, turbot_api_secret_key),\n verify=turbot_host_certificate_verification,\n headers={\n 'content-type': \"application/json\",\n 'cache-control': \"no-cache\"\n }\n )\n\n responseObj = json.loads(response.text)\n for notification in responseObj['items']:\n notification_list.append(notification['alarmUrn'])\n return notification_list\n\n\nif __name__ == '__main__':\n # Set to False if you do not have a valid certificate for your Turbot Host\n turbot_host_certificate_verification = True\n\n # Set to your Turbot Host URL\n turbot_host = turbotutils.get_turbot_host()\n\n # Get the access and secret key pairs\n (turbot_api_access_key,turbot_api_secret_key) = turbotutils.get_turbot_access_keys()\n\n # Get the turbot version\n api_version = turbotutils.get_api_version()\n\n # Get the turbot account numbers\n cluster_id = turbotutils.cluster.get_cluster_id(turbot_host, turbot_api_access_key, turbot_api_secret_key, turbot_host_certificate_verification, api_version)\n\n accounts = turbotutils.cluster.get_turbot_account_ids(turbot_api_access_key, turbot_api_secret_key, turbot_host_certificate_verification, turbot_host, api_version)\n\n top_level = 'urn:turbot'\n notification_list = []\n notification_count = {}\n for account_id in accounts:\n namespace = cluster_id + \":\" + account_id\n for notification in get_notifications(turbot_host, turbot_api_access_key, turbot_api_secret_key, turbot_host_certificate_verification, namespace, api_version):\n if notification in notification_count:\n notification_count[notification] += 1\n else:\n notification_count[notification] = 1\n\n sorted_dict = sorted(notification_count.items(), key=operator.itemgetter(1), reverse=True)\n\n pprint(sorted_dict)","sub_path":"examples/aggrigrate_notifications_for_all.py","file_name":"aggrigrate_notifications_for_all.py","file_ext":"py","file_size_in_byte":2847,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"494882035","text":"# %%\n\nimport torch\nimport torch.nn as nn\nfrom spade.options.test_options import TestOptions\nfrom spade.util.visualizer import Visualizer\nfrom spade.models.SpadeGAN import SpadeGAN\nfrom spade.util.test_util import *\nfrom spade.util.train_util import mkdir, tensor2img, get_device\nfrom PIL import Image, ImageFile\nImageFile.LOAD_TRUNCATED_IMAGES = True\n\nopt = TestOptions()\nspade_gan = SpadeGAN(opt)\n\nif torch.cuda.is_available() > 0:\n # https://www.zhihu.com/question/67726969/answer/389980788\n spade_gan = nn.DataParallel(spade_gan).to(get_device(opt))\n\n\ndef spade_generate(label_image, style_image):\n label_tensor = load_label_tensor(label_image, opt)\n style_tensor = load_img_tensor(style_image, opt)\n fake_image = spade_gan(label_tensor, style_tensor).squeeze()\n fake_image = tensor2img(fake_image, opt)\n fake_image = Image.fromarray(fake_image).convert('RGB')\n return fake_image\n\n\ndef main():\n label_image = Image.open(opt.label_path)\n style_image = Image.open(opt.style_path)\n fake_image = spade_generate(label_image, style_image)\n fake_image.save(opt.result_path)\n print(f'Image saved at: {opt.result_path}', flush=True)\n\n\nif __name__ == '__main__':\n main()\n\n","sub_path":"spade/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":1207,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"131360761","text":"from django.utils.timezone import now\nfrom fabric.api import env, local, settings, sudo\n\nfrom ._core import ServerManagementBaseCommand, load_config\n\n\nclass Command(ServerManagementBaseCommand):\n\n def handle(self, *args, **options):\n # Load server config from project\n config, remote = load_config(env, options.get('remote', ''), debug=options.get('debug', False))\n\n with settings(warn_only=True):\n # Dump the database on the server.\n sudo('su - {user} -c \\'pg_dump {name} -cOx -U {user} -f /home/{user}/{name}.sql --clean\\''.format(\n name=remote['database']['name'],\n user=remote['database']['user'],\n ))\n\n # Create a backups folder\n local('mkdir -p ~/Backups/')\n\n # Pull the SQL file down.\n local('scp {} {}@{}:/home/{}/{}.sql ~/Backups/{}-{}.sql'.format(\n '' if not getattr(env, 'key_filename') else ' -i {} '.format(env.key_filename),\n env.user,\n env.host_string,\n remote['database']['user'],\n remote['database']['name'],\n config['local']['database']['name'],\n now().isoformat(),\n ))\n\n # Delete the file on the server.\n sudo('rm /home/{}/{}.sql'.format(\n remote['database']['user'],\n remote['database']['name'],\n ))\n","sub_path":"server_management/management/commands/backupdb.py","file_name":"backupdb.py","file_ext":"py","file_size_in_byte":1430,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"201609661","text":"# Scrapy settings for australia_wine project\n#\n# For simplicity, this file contains only the most important settings by\n# default. All the other settings are documented here:\n#\n# http://doc.scrapy.org/en/latest/topics/settings.html\n#\n\nBOT_NAME = 'australia_wine'\n\nSPIDER_MODULES = ['australia_wine.spiders']\nNEWSPIDER_MODULE = 'australia_wine.spiders'\nFEED_FORMAT = \"csv\"\nFEED_STORE_EMPTY = True\n# Crawl responsibly by identifying yourself (and your website) on the user-agent\n#USER_AGENT = 'australia_wine (+http://www.yourdomain.com)'\n","sub_path":"australia_wine/australia_wine/settings.py","file_name":"settings.py","file_ext":"py","file_size_in_byte":560,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"89924886","text":"import re\nimport os\n\nwzorzec = re.compile(r'nauka[0-9]+\\.txt')\n\nfor nazwa in os.listdir():\n if not wzorzec.match(nazwa):\n continue\n print(f\"-- {nazwa} --\")\n with open(nazwa,\"r\", encoding=\"utf-8\") as f:\n print(f.read())\n print(\"---------------\")\n\nprint([nazwa for nazwa in os.listdir() if wzorzec.match(nazwa)])\n","sub_path":"pliki/nauka12.py","file_name":"nauka12.py","file_ext":"py","file_size_in_byte":337,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"153129172","text":"#!/bin/env python\n\n##############################################################################\n# TO USE MAKE SURE YOUR aws_access_key_id and aws_secret_access_key\n# ARE STORED IN ~/.aws/credentials\n##############################################################################\n\nfrom tornado_botocore import Botocore\nimport tornado.web\nimport tornado.gen\n\nimport config\nimport logger\n\nclass SesEmailHandler(object):\n\t\"\"\"\n\tHandler class for Amazon SES external email service provider.\n\n\tSource: https://aws.amazon.com/ses/\n \"\"\"\n\n\tdef __init__(self, main_logger = None):\n\t\t\"\"\"Initalizes the logger for the object.\n\t\tCreates an async boto client to communicate with the aws service.\n\t\tAPI keys are derived from the environment (e.g. ~/.aws/credentials).\n\n\t Args:\n\t \tmain_logger: logger to which the logs should be sent, optional\n\t \"\"\"\n\t\tself.log = main_logger or logger.init_logger(\"ses\")\n\n\t\tself.ses_client = Botocore(\n\t\t\tservice='ses', operation='SendEmail', region_name='eu-west-1'\n\t\t)\n\n\t@tornado.gen.engine\n\tdef send_email(self, to_addr, cc_addr, bcc_addr, topic, text, callback):\n\t\t\"\"\"Sends an email using mailgun service.\n\n\t\tIf call succeedes, returns QUEUED status. An SNS topic has been created\n\t\tand webhook with a subscription to the topic has been setup for\n\t\tdelivery confirmations (server.DeliverySesHandler).\n\n\t Args:\n\t \tto_addr: Email address of the main recipient.\n\t cc_addr: A list of email addresses of all cc'd recipients.\n\t bcc_addr: A list of email addresses of all bcc'd recipients.\n\t topic: Email subject.\n\t text: Email body.\n\t Returns:\n\t \t(SendStatus, ExternalId)\n\t \tSendStatus: FAILED/QUEUED\n\t \tExternalId: External id that the service assigned to the email. None if FAIELD.\n\t \"\"\"\n\t\tmessage = self._prepare_message(topic, text)\n\t\tdestination = self._prepare_destination(to_addr, cc_addr, bcc_addr)\n\n\t\tresponse = yield tornado.gen.Task(self.ses_client.call,\n\t\t\tSource=config.FROM_ADDRESS, Message=message, Destination=destination\n\t\t)\n\t\tif (int(response['ResponseMetadata']['HTTPStatusCode'])\n\t\t\t\t== config.RESPONSE_OK):\n\t\t\t# SES always queues.\n\t\t\tcallback(config.SEND_STATUS.QUEUED, response['MessageId'])\n\t\t\treturn\n\n\t\t# failed\n\t\tcallback(config.SEND_STATUS.FAILED, None)\n\t\treturn\n\n\tdef _prepare_message(self, topic, text):\n\t\treturn {\n\t\t\t'Subject': {\n\t\t\t\t'Data': topic.decode('utf-8'),\n\t\t\t},\n\t\t\t'Body': {\n\t\t\t\t'Text': {\n\t\t\t\t\t'Data': text.decode('utf-8'),\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\tdef _prepare_destination(self, to_addr, cc_addr, bcc_addr):\n\t\tdestination = {\n\t\t\t'ToAddresses': [to_addr]\n\t\t}\n\t\tif cc_addr:\n\t\t\tdestination['CcAddresses'] = cc_addr\n\t\tif bcc_addr:\n\t\t\tdestination['BccAddresses'] = bcc_addr\n\t\treturn destination","sub_path":"server/email_handlers/ses_handler.py","file_name":"ses_handler.py","file_ext":"py","file_size_in_byte":2700,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"543425489","text":"# =============================================================================\n# Authors: PAR Government\n# Organization: DARPA\n#\n# Copyright (c) 2016 PAR Government\n# All rights reserved.\n# ==============================================================================\n\nimport logging\nfrom maskgen.software_loader import getFileName\n\n# tools for assisting with S3 and HTTP functionality\n\ndef loadS3(values):\n import boto3\n import os\n logging.getLogger('maskgen').info( 'Download operations and software via S3')\n s3 = boto3.client('s3','us-east-1')\n BUCKET = values[0][0:values[0].find('/')]\n DIR=values[0][values[0].find('/')+1:]\n place = getFileName('operations.json')\n if place is None:\n place = os.path.abspath(os.getenv('MASKGEN_RESOURCES', '.'))\n else:\n place = os.path.dirname(place)\n s3.download_file(BUCKET, DIR + \"/operations.json\", os.path.join(place,\"operations.json\"))\n s3.download_file(BUCKET, DIR + \"/software.csv\", os.path.join(place,\"software.csv\"))\n s3.download_file(BUCKET, DIR + \"/project_properties.json\", os.path.join(place,\"project_properties.json\"))\n s3.download_file(BUCKET, DIR + \"/ManipulatorCodeNames.txt\", os.path.join(place, \"ManipulatorCodeNames.txt\"))\n\ndef loadHTTP(values):\n import requests\n import os\n logging.getLogger('maskgen').info( 'Download operations and software via HTTP')\n head = {}\n place = getFileName('operations.json')\n if place is None:\n place = os.path.abspath(os.getenv('MASKGEN_RESOURCES', '.'))\n else:\n place = os.path.dirname(place)\n for p in range(1, len(values)):\n name = values[p].split(':')[0].strip()\n val = values[p].split(':')[1].strip()\n head[name]=val\n r = requests.get(values[0] + '/operations.json',headers=head)\n if r.status_code < 300:\n with open(os.path.join(place,\"operations.json\"), 'w') as f:\n f.write(r.content)\n r = requests.get(values[0] + '/software.csv',headers=head)\n if r.status_code < 300:\n with open(os.path.join(place,\"software.csv\"), 'w') as f:\n f.write(r.content)\n\n\n","sub_path":"maskgen/external/web_tools.py","file_name":"web_tools.py","file_ext":"py","file_size_in_byte":2072,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"389407510","text":"import selenium\nfrom selenium.webdriver import ActionChains\nfrom PIL import Image\nimport pytesseract\nimport cv2\n\n\n\n\n# configuration of the web browser\ndriver = selenium.webdriver.Firefox(executable_path=\"/home/sarcazeem/Downloads/geckodriver\")\nactionChains = ActionChains(driver)\n\n# open the website\ndriver.get('https://atacs.atilim.edu.tr/login/Welcome?ReturnUrl=%2f')\n\n# automation in the website find elements and click etc\ndriver.find_element_by_xpath(\"/html/body/div[2]/div[2]/div[1]/div[1]/div/ul/li[1]/a\").click()\ndriver.find_element_by_id(\"mail\").send_keys(\"\")\ndriver.find_element_by_id(\"password\").send_keys(\"\")\n\n# locate the captcha image then get the size of the element using selenium\n# and get the screenshot of the current browser window\ncaptcha = driver.find_element_by_xpath(\"/html/body/div[2]/div[2]/div[2]/div/div[3]/form/div[3]/div/img\")\nlocation = captcha.location\nsize = captcha.size\ndriver.save_screenshot('captcha.png')\n\n# get the location widths and save them to variables\nx = location['x']\ny = location['y']\nwidth = location['x'] + size['width']\nheight = location['y'] + size['height']\n\n# open the image and crop the full sized image into the cropped captcha size\nim = Image.open('captcha.png')\nim = im.crop((int(x), int(y), int(width), int(height)))\nim.save('captcha.png')\n\n# opencv image enhancements\nimg = cv2.imread('captcha.png')\nimg = cv2.medianBlur(img, 5)\n\ngray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\n\n# edge detection\nedges = cv2.Canny(img, 150, 200)\ncv2.imwrite('outputCaptcha.png', edges)\n\n\n# read the saved image by using ocr technology which is tesseract in this case\nprint(pytesseract.image_to_string(Image.open('captcha.png')))\nprint(pytesseract.image_to_string(Image.open('outputCaptcha.png')))\n# close the browser.\ndriver.close()\n","sub_path":"Selenium/Atacs.py","file_name":"Atacs.py","file_ext":"py","file_size_in_byte":1773,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"5782546","text":"from django.contrib import admin\nfrom .models import Establecimiento, Localidad, PruebaCienciasNaturales, PruebaLectura, PruebaMatematicas\n\n\n# Register your models here\n\nclass LocalidadInline(admin.TabularInline):\n model=Localidad\n extra= 0\n\nclass PruebaCienciasInline(admin.TabularInline):\n model=PruebaCienciasNaturales\n extra= 0\n\nclass PruebaLecturaInline(admin.TabularInline):\n model= PruebaLectura\n extra=0\n\n\nclass PruebaMatematicasInline(admin.TabularInline):\n model= PruebaMatematicas\n extra= 0\n\n\nclass EstablecimientoAdmin(admin.ModelAdmin):\n \n list_display= ('nombre','rbd')\n inlines=(LocalidadInline, PruebaCienciasInline,PruebaMatematicasInline,PruebaLecturaInline)\n search_fields= [ 'nombre', 'rbd']\n\nadmin.site.register(Establecimiento, EstablecimientoAdmin)\n","sub_path":"appsim/admin.py","file_name":"admin.py","file_ext":"py","file_size_in_byte":810,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"63896918","text":"import os\nimport shutil\nimport warnings\nimport konlpy\nfrom konlpy.tag import *\nimport re\nfrom gensim.models import KeyedVectors\nfrom datetime import datetime\n \ndef createFolder(directory):\n try:\n if not os.path.exists(directory):\n os.makedirs(directory)\n except OSError:\n print ('Error: Creating directory. ' + directory)\ndef write_file(to_folder, from_folder, file):\n src = \"./mail_data/\"+from_folder+\"/\"+file\n dsc = to_folder+\"/\"\n shutil.copy(src,dsc)\n\ndef file_list_in_folder(folderName):\n path_dir = \"./mail_data/\"+folderName\n file_list = os.listdir(path_dir)\n return file_list\ndef testfile_list_in_folder(folderName):\n path_dir = \"./test_data/\"+folderName\n dir_list = os.listdir(path_dir)\n full_file_list = []\n num=0\n index_info = []\n for dir1 in dir_list:\n index_info.append([dir1.replace, num])\n path_dir = \"./test_data/\"+folderName+\"/\"+dir1\n file_list = os.listdir(path_dir)\n full_file_list.append([{i : num} for i in file_list])\n num+=1\n return index_info, full_file_list\n\ndef list_of_word_in_file(folderName, fileName):\n f = open(\"./mail_data/\"+folderName+\"/\"+fileName, 'r')\n full_data = \"\"\n line = f.readline()\n title = line.replace(\"\\n\",\"\")\n while(line):\n if(line != \"\\n\"):\n if(\"본 메일은\" in line):\n line = line.split(\"본 메일은\")\n line = ' '.join(line[0].split())\n full_data+=line\n break\n line = line.replace(\"\\n\",\" \")\n line = ' '.join(line.split())\n full_data+=line\n line = f.readline()\n f.close()\n return full_data, title\n\ndef folder_name(option1, option2, option3): #폴더명 생성\n timestr = datetime.now().strftime(\"%Y-%m-%d-%H-%M-%S\")\n full_name = \"testresult_\"+str(option1)+\"_\"+str(option2)+\"_\"+str(option3)+\"_\"+timestr\n return full_name\n\ndef findNeighborWords(loaded_model, keyword):\n flag = True\n newlist = []\n try:\n model_result=loaded_model.most_similar(keyword, topn=4)\n newlist = [[i[0],round(i[1],4)] for i in model_result if i[1] >= 0.5]\n except:\n flag = False\n\n return newlist, flag\n\ndef word_list(option, listData):\n wordlist = []\n\n if option == 2:\n loaded_model = KeyedVectors.load_word2vec_format(\"training_data/vector_clean_data_final_ver2w7_m15_iter1000\")\n for keyword in listData:\n newlist, flag = findNeighborWords(loaded_model, keyword)\n if flag:\n newlist.insert(0, [keyword, 1])\n wordlist.append(newlist)\n else:\n for keyword in listData:\n newlist = []\n newlist.append([keyword, 1])\n wordlist.append(newlist)\n return wordlist\n\ndef make_sentence(data):\n sentence = \"\"\n for i in data:\n if(i.endswith('.\\n')):\n sentence+=i.replace(\"\\n\",\" \")\n result = sentence.split(\".\")\n return result\n\ndef data_text_cleaning(data):\n # 특수문자 제거\n delete_spe = re.sub('[-=+,#/\\?:^$.@*\\\"※~&%ㆍ!』\\\\‘|\\《\\(\\)\\[\\]\\<\\>`\\'…》]', ' ', data)\n # 영어 제거\n delete_eng = re.sub('[a-zA-z]',' ',delete_spe)\n #숫자 제거\n delete_num = re.sub('[0-9]',' ',delete_eng)\n #공백 한개만\n delete_blank = re.sub('\\s+',' ',delete_num)\n if(delete_blank == \" \"):\n return \" \"\n # 단어만 \n warnings.simplefilter(\"ignore\")\n mecab = Mecab()\n noun_data = mecab.nouns(delete_blank)\n\n delete_list = [\"이\", \"것\", \"수\", \"를\", \"개\", \"후\", \"을\", \"메\", \"의\", \"은\", \"년\", \"만\", \"그\", \"만\", \"외\"]\n for i in delete_list:\n if(i in noun_data):\n noun_data.remove(i)\n return noun_data\ndef count_word(data):\n wordCount = {} \n for word in data:\n # Get 명령어를 통해, Dictionary에 Key가 없으면 0리턴\n wordCount[word] = wordCount.get(word, 0) + 1 \n keys = sorted(wordCount.keys())\n count = sorted(wordCount.items(), \n reverse=True, \n key=lambda item: item[1])\n count_key = [i[0] for i in count]\n return count_key[:10]\n \n\ndef print_menu():\n print(\"1. 키워드 추가\")\n print(\"2. 키워드 삭제\")\n print(\"3. 키워드 조회\")\n print(\"4. 키워드별 메일 확인\")\n print(\"5. 종료\")\n\n menu = input(\"메뉴 선택: \")\n return int(menu)\n\ndef splitMailHead(filename):\n mailFile = open(\"./mail_data/\"+filename, \"r\")\n\n readdata = []\n line = mailFile.readline()\n while(line):\n readdata.append(line)\n line = mailFile.readline()\n readdata = make_sentence(readdata)\n # print(readdata)\n # print(len(readdata))\n mailFile.close()\n result = []\n num = 0\n for line in readdata:\n num+=1\n if(num%1000==0):\n print(num)\n if(line!=\"\\n\"):\n data = data_text_cleaning(line)\n if(len(data)!=1):\n result.append([line, data])\n return result\n\n\ndef splitKeyword():\n keywordFile = open(\"./visualizing_data/keyword.txt\", \"r\")\n\n keywordList = keywordFile.read().split()\n \n keywordFile.close()\n\n return keywordList\n\ndef add_keyword():\n newKeyword = input(\"추가할 키워드를 입력하세요: \")\n keywordSet.add(newKeyword)\n\n\ndef del_keyword():\n delKeyword = input(\"삭제할 키워드를 입력하세요: \")\n if delKeyword in list(keywordSet):\n keywordSet.remove(delKeyword)\n else:\n print(\"해당 키워드는 존재하지 않습니다.\")\n\n\ndef lookup_keyword():\n print(list(keywordSet))\n\ndef printByTitle(result, option1, option2, option3, neighborKeywords, model, score_norm):\n weightFigureList = []\n rankList = []\n for rLine in result:\n weightFigure = 0\n mailList = word_list(option3, rLine[1])\n for keywordInfo in neighborKeywords:\n word = keywordInfo[0]\n frequency = keywordInfo[1]\n\n if option1 == 1:\n weightFigure += findSimilarityByAvg(model, mailList, word) * frequency\n elif option1 == 2:\n weightFigure += findSimilarityBySum(model, mailList, word, 0) * frequency\n if weightFigure >= score_norm:\n weightFigureList.append([weightFigure, rLine[0]])\n # rankList.append([\"{}과 {}사이의 유사도\".format(rLine[0], neighborKeywords[0][0]), weightFigure])\n\n sortedRankList = sorted(weightFigureList, key=lambda t: t[0], reverse=True)\n for idx in range(len(sortedRankList)):\n print(\"[{}]의 유사도: {}\".format(sortedRankList[idx][1], sortedRankList[idx][0]))\n \n return weightFigureList\n\n\ndef printByContent(folderName_of_file, filelist, option1, option2, option3, neighborKeywords, model, score_norm):\n weightFigureList = []\n for filename in filelist:\n full_content , title = list_of_word_in_file(folderName_of_file, filename)\n wordlist_of_full_content = data_text_cleaning(full_content)\n \n weightFigure = 0\n mailList = word_list(option3, wordlist_of_full_content)\n for keywordInfo in neighborKeywords:\n word = keywordInfo[0]\n frequency = keywordInfo[1]\n\n if option1 == 1:\n weightFigure += findSimilarityByAvg(model, mailList, word) * frequency\n elif option1 == 2:\n weightFigure += findSimilarityBySum(model, mailList, word, 0) * frequency\n # print(\"{}과 {}사이의 유사도\".format(title, neighborKeywords[0][0]), weightFigure)\n if weightFigure >= score_norm:\n weightFigureList.append([weightFigure, title, filename])\n \n sortedRankList = sorted(weightFigureList, key=lambda t: t[0], reverse=True)\n for idx in range(len(sortedRankList)):\n print(\"[{}]의 유사도: {}\".format(sortedRankList[idx][1], sortedRankList[idx][0]))\n\n return weightFigureList\ndef printByContent_freq(folderName_of_file, filelist, option1, option2, option3, neighborKeywords, model, score_norm):\n weightFigureList = []\n for filename in filelist:\n full_content , title = list_of_word_in_file(folderName_of_file, filename)\n wordlist_of_full_content = data_text_cleaning(full_content)\n wordlist_of_full_content = count_word(wordlist_of_full_content)\n weightFigure = 0\n mailList = word_list(option3, wordlist_of_full_content)\n for keywordInfo in neighborKeywords:\n word = keywordInfo[0]\n frequency = keywordInfo[1]\n\n if option1 == 1:\n weightFigure += findSimilarityByAvg(model, mailList, word) * frequency\n elif option1 == 2:\n weightFigure += findSimilarityBySum(model, mailList, word, 0) * frequency\n # print(\"{}과 {}사이의 유사도\".format(title, neighborKeywords[0][0]), weightFigure)\n if weightFigure >= score_norm:\n weightFigureList.append([weightFigure, title, filename])\n \n sortedRankList = sorted(weightFigureList, key=lambda t: t[0], reverse=True)\n for idx in range(len(sortedRankList)):\n print(\"[{}]의 유사도: {}\".format(sortedRankList[idx][1], sortedRankList[idx][0]))\n\n return weightFigureList\n\ndef printResult(option1, option2, option3, wordlist, model, foldername):\n if option3 == 1 or option3 == 2:\n title_filename = input(\"파일 이름을 입력해주세요 : \")\n result = splitMailHead(title_filename)\n \n if option3 == 3 or option3 == 4:\n folderName_of_file = input(\"확인할 파일이 있는 폴더명을 입력해주세요 : \")\n filelist = file_list_in_folder(folderName_of_file)\n\n createFolder(\"./consequence/\"+foldername)\n for neighborKeywords in wordlist:\n print(\"---------- {} 키워드 정보 ----------\".format(neighborKeywords[0][0]))\n createFolder(\"./consequence/\"+foldername+\"/\"+neighborKeywords[0][0])\n f = open(\"./consequence/\"+foldername+\"/\"+neighborKeywords[0][0]+\".txt\", \"w\")\n # f2 = open(\"./consequence/\"+foldername+\"/not_\"+neighborKeywords[0][0]+\".txt\", \"w\")\n if option3 == 1:\n if option2 == 1:\n score_norm = 0.3\n elif option2 == 2:\n score_norm = 1.0\n weightFigureList = printByTitle(result, option1, option2, option3, neighborKeywords, model, score_norm)\n elif option3 == 2:\n if option2 == 1:\n score_norm = 0.3\n elif option2 == 2:\n score_norm = 1.0\n weightFigureList = printByTitle(result, option1, option2, option3, neighborKeywords, model, score_norm)\n elif(option3 == 3):\n if option2 == 1:\n # score_norm = float(input(\"score_num 입력 : \"))\n score_norm = 0.27\n elif option2 == 2:\n score_norm = 1.0\n weightFigureList = printByContent(folderName_of_file, filelist, option1, option2, option3, neighborKeywords, model, score_norm)\n elif(option3 == 4):\n weightFigureList = printByContent_freq(folderName_of_file, filelist, option1, option2, option3, neighborKeywords, model, score_norm)\n\n #rankList.append([\"{}과 {}사이의 유사도\".format(title, neighborKeywords[0][0]), weightFigure])\n for wF in weightFigureList:\n f.write(wF[1]+\"\\n\")\n if option3 >= 0.26:\n write_file(\"./consequence/\"+foldername+\"/\"+neighborKeywords[0][0], folderName_of_file, wF[2])\n f.close()\n\n\n\ndef classify_mail():\n option1 = int(input(\"[option1] 1. avg, 2. sum : \"))\n option2 = int(input(\"[option2] 1. user category, 2. user category+neighbor word : \"))\n option3 = int(input(\"[option3] 1. title, 2. title+neibor word, 3. main+title, 4. main+title+freq : \"))\n\n model = KeyedVectors.load_word2vec_format(\"training_data/vector_clean_data_final_ver2w7_m15_iter1000\")\n\n wordlist = word_list(option2, list(keywordSet))\n print(wordlist)\n # 함수 파라미터: option1, wordlist, model로 통일1\n foldername = folder_name(option1,option2, option3)\n printResult(option1, option2, option3, wordlist, model, foldername)\n\n\ndef findSimilarityBySum(model, mailData, keyword, idx):\n sum = 0\n count = 0\n\n for neighborWords in mailData:\n for wordInfo in neighborWords:\n mWord = wordInfo[0]\n mFrequency = wordInfo[1]\n\n try:\n similarity = model.wv.similarity(mWord, keyword)\n # if similarity >= 0.5:\n # similarity = 1\n # if similarity < 0:\n # similarity = -1\n sum += similarity * mFrequency\n except KeyError:\n count += 1\n continue\n if idx == 1:\n return sum, count\n else:\n return sum\n\ndef findSimilarityByAvg(model, mailData, word):\n sum, count = findSimilarityBySum(model, mailData, word, 1)\n try:\n avg = sum / (len(mailData) - count)\n except ZeroDivisionError:\n avg = 0\n\n return avg\n \nif __name__ == \"__main__\":\n \n keywordSet = set(splitKeyword())\n\n while True:\n menu = print_menu()\n if menu == 1:\n add_keyword()\n print(keywordSet)\n elif menu == 2:\n del_keyword()\n elif menu == 3:\n lookup_keyword()\n elif menu == 4:\n classify_mail()\n elif menu == 5:\n keywordFileforUpdate = open(\"./visualizing_data/keyword.txt\", \"w\")\n for keyword in list(keywordSet):\n keywordFileforUpdate.write(\"{}\\n\".format(keyword))\n keywordFileforUpdate.close()\n break\n\n\n","sub_path":"visualization.py","file_name":"visualization.py","file_ext":"py","file_size_in_byte":13639,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"51521756","text":"# Copyright 2015 Google Inc. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\"\"\"Command to create a service account for a project.\"\"\"\n\n\nimport textwrap\n\nfrom googlecloudsdk.api_lib.iam import base_classes\nfrom googlecloudsdk.api_lib.iam import utils\nfrom googlecloudsdk.core import log\n\n\nclass Create(base_classes.BaseIamCommand):\n \"\"\"Create an service account for a project.\n\n This command creates a service account with the provided name. For\n subsequent commands regarding service accounts, this service account should be\n referred to by the email account in the response.\n \"\"\"\n\n detailed_help = {\n 'DESCRIPTION': '{description}',\n 'EXAMPLES': textwrap.dedent(\"\"\"\\\n To create an service account for your project, run:\n\n $ {command} some-account-name --display-name \"My Service Account\"\n\n To work with this service account in subsequent IAM commands, use the\n email resulting from this call as the IAM-ACCOUNT argument.\n \"\"\"),\n }\n\n @staticmethod\n def Args(parser):\n parser.add_argument('--display-name',\n help='A textual name to display for the account.')\n\n parser.add_argument('name',\n metavar='NAME',\n help='The internal name of the new service account. '\n 'Used to generate an IAM-ACCOUNT, which must be passed '\n 'to subsequent commands.')\n\n @utils.CatchHttpErrors\n def Run(self, args):\n if not utils.ValidateAccountId(args.name):\n raise ValueError('[{0}] is an invalid name'.format(args.name))\n\n if not self.project or not self.project.Get():\n log.error('no project id set')\n return\n\n return self.iam_client.projects_serviceAccounts.Create(\n self.messages.IamProjectsServiceAccountsCreateRequest(\n name=utils.ProjectToProjectResourceName(self.project.Get()),\n createServiceAccountRequest=\n self.messages.CreateServiceAccountRequest(\n accountId=args.name,\n serviceAccount=self.messages.ServiceAccount(\n displayName=args.display_name))))\n","sub_path":"google-cloud-sdk/lib/surface/iam/service_accounts/create.py","file_name":"create.py","file_ext":"py","file_size_in_byte":2663,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"193319242","text":"import turtle as tu\r\n\r\na = tu.Turtle()\r\na.penup()\r\na.goto(0, -150)\r\na.pendown()\r\na.left(90)\r\na.speed(0)\r\n\r\n\r\ndef drawn(l):\r\n if l < 5:\r\n return\r\n else:\r\n a.forward(l)\r\n a.left(30)\r\n drawn(4*l/5)\r\n a.right(60)\r\n drawn(4*l/5)\r\n a.left(30)\r\n a.backward(l)\r\n\r\ndrawn(100)","sub_path":"turtoise.py","file_name":"turtoise.py","file_ext":"py","file_size_in_byte":328,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"60875770","text":"import gym\nimport numpy as np\nimport random\nimport tensorflow as tf\nimport matplotlib.pyplot as plt\n\n\nenv = gym.make('FrozenLake-v0')\n\n# 상태를 표현하는 원-핫인코딩\nunit_matrix = np.identity(16)\n\n# 네트워크 만들기\n\ntf.reset_default_graph()\n\n# 액션을 선���하는데 사용되는 네트워크의 피드포워드 부분\nX = tf.placeholder(shape=[1, 16], dtype=tf.float32)\nW = tf.Variable(tf.random_uniform([16, 4], 0, 0.01)) # 균등분포, 액션에 대한 Q 값\nQpred = tf.matmul(X, W)\npredictQIndex = tf.argmax(Qpred, 1)\n\n# 타깃 Q 값과 예측 Q 값의 차의 제곱합을 구함으로써 비용을 얻는다.\nY = tf.placeholder(shape=[1, 4], dtype=tf.float32)\nloss = tf.reduce_sum(tf.square(Y - Qpred))\ntrainer = tf.train.GradientDescentOptimizer(learning_rate=0.1).minimize(loss)\n\n# 네트워크 학습\n\ninit = tf.global_variables_initializer()\n\n# 학습 매개변수를 설정한다.\ndisc = .99\ne = 0.1\nnum_episodes = 2000\n# 보상의 총계와 에피소드별 단계 수를 담을 리스트를 생성한다.\njList = []\nrList = []\n\nwith tf.Session() as sess:\n sess.run(init)\n for i in range(num_episodes):\n # 환경을 리셋하고 첫 번째 새로운 관찰을 얻는다.\n s = env.reset()\n rAll = 0\n d = False\n j = 0\n # Q 네트워크\n while j < 99:\n j += 1\n # Q 네트워크에서 (e의 확률로 랜덤한 액션과 함께) 그리디하게 액션을 선택\n a, Qs = sess.run([predictQIndex, Qpred], feed_dict={X: unit_matrix[s:s + 1]})\n if np.random.rand(1) < e:\n a[0] = env.action_space.sample()\n\n # 예측에서 최고의 값을 가진 액션을 구하고, 이 액션을 사용해 타깃 Q 값을 구한다.\n # 환경으로부터 새로운 상태와 보상을 얻는다.\n s1, r, d, _ = env.step(a[0])\n\n # 새로운 상태를 네트워크에 피드해줌으로써 Q' 값을 구한다.\n Qs1 = sess.run(Qpred, feed_dict={X: unit_matrix[s1:s1 + 1]})\n\n # maxQ' 값을 구하고 선택된 액션에 대한 타깃 값을 설정한다.\n Qs[0, a[0]] = r + disc * np.max(Qs1)\n # 타깃 및 예측 Q 값을 이용해 네트워크를 학습시킨다.\n _, W1 = sess.run([trainer, W], feed_dict={X: unit_matrix[s:s + 1], Y: Qs})\n rAll += r\n s = s1\n if d:\n # 모델을 학습해나감에 따라 랜덤 액션의 가능성을 줄여간다.\n e = 1 / ((i / 50) + 10)\n break\n jList.append(j)\n rList.append(rAll)\n\nprint('Percent of successful episodes: ', str(sum(rList) / num_episodes))\nplt.plot(rList)\nplt.plot(jList)\n","sub_path":"rl/q-network.py","file_name":"q-network.py","file_ext":"py","file_size_in_byte":2741,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"595291472","text":"from mpl_toolkits import mplot3d\nfrom scipy.optimize import *\nfrom scipy.integrate import *\nimport matplotlib\nimport numpy as np\nimport random\nimport sys\nfrom scipy.interpolate import griddata\nimport tkinter as tk\nimport matplotlib.pyplot as plt\n#matplotlib.use(\"TkAgg\")\nfrom matplotlib.figure import Figure\nfrom matplotlib.backends.backend_tkagg import (\n FigureCanvasTkAgg, NavigationToolbar2Tk)\n# Implement the default Matplotlib key bindings.\nfrom matplotlib.backend_bases import key_press_handler\n\nprint(\"You are using Python {}.{}.\".format(sys.version_info.major, sys.version_info.minor))\n\nglobal F, ISQ, ISW, error, I, J, Tries, Z\nF = 0\nerror = 4.0\nISW = 0\nISQ = 0\nI = 0\nJ = 0\nTries = 1000\n\nhButton = 2\nwButton = 5\nhInfo = 3\nwInfo = 6\n\nm = 'COBYLA' # 'SLSQP' #'COBYLA' # minimization method\neps = 0.01 # epsilon\nlVal = 5 # значение буквы\nN = 20 # grid size\nIG = 20\nroot = tk.Tk()\nRandom = tk.BooleanVar()\nRandom.set(0)\nZ = np.zeros((N - 1, N - 1))\n\n\n#errorLabel = tk.Label(root, width=wInfo, height=hInfo)\nerrorEntry = tk.Entry(root)\nmoreButton = tk.Button(root, text=\"+ 0.1\", width=wButton, height=hButton)\nlessButton = tk.Button(root, text=\"- 0.1\", width=wButton, height=hButton)\nretryButton = tk.Button(root, text=\"Retry\", width=wButton, height=hButton)\nrandomButton = tk.Checkbutton(text=\"New noise\", variable=Random, onvalue=1, offvalue=0)\n#errorLabel['text'] = str(error)\nfig = plt.figure(dpi=100)\n\ndef Sq(u):\n global ISQ\n return ((1 + u ** 2) ** (1 / 2))/2 + ISQ\n\n\ndef Sw(u):\n global ISW\n return ((1 + u ** 2) ** (1 / 2))/2 + ISW\n\n\ndef S(u):\n global I\n global J\n global F\n row = []\n row2 = []\n row4 = []\n F[I - 1, J - 1] = ((1 + u[0] ** 2 + u[1] ** 2) ** (1 / 2))\n for k in range(J):\n if k % 2 == 0:\n row.append(2)\n row2.append(4)\n row4.append(8)\n else:\n row.append(4)\n row2.append(8)\n row4.append(16)\n\n row[0] = 1\n row[-1] = 1\n row2[0] = 2\n row2[-1] = 2\n row4[0] = 4\n row4[-1] = 4\n\n lMatrix = [[]]\n\n for k in range(I):\n if k % 2 == 0:\n lMatrix.append(row4)\n else:\n lMatrix.append(row2)\n lMatrix.pop(0)\n lMatrix.insert(0, row)\n lMatrix.pop()\n lMatrix.append(row)\n f = 0\n for i in range(I):\n for j in range(J):\n f = f + (lMatrix[i][j] * F[i][j])\n\n return (1 / 9) * f\n\n\ndef AddError():\n global error\n error = round(error + 0.1, 1)\n errorEntry.delete(0, tk.END)\n errorEntry.insert(0, error)\n #errorLabel['text'] = error\n Run()\n\n\ndef SubtractError():\n global error\n error = round(error - 0.1, 1)\n #errorLabel['text'] = error\n errorEntry.delete(0, tk.END)\n errorEntry.insert(0, error)\n Run()\n\n\ndef errorEntryValueChanged(event):\n global error\n error = round(eval(errorEntry.get()), 1)\n errorEntry.delete(0, tk.END)\n errorEntry.insert(0, error)\n Run()\n\n\ndef Retry():\n Run()\n\ndef FillOrigin(): # fill letter\n Z = np.zeros((N - 1, N - 1))\n for i in range(4, N - 4):\n Z[i, 4] = lVal\n Z[i, N - 4] = lVal\n if i != 4 or i != N - 4:\n Z[i, i] = lVal\n return Z\n\n\ndef AddNoise(Z):\n for z in Z:\n for i in range(len(z)):\n if z[i] == 0:\n z[i] = random.randint(2, 4)\n return Z\n\n\ndef RestorationRun(N, Z, e):\n global F, ISQ, ISW, error, I, J, Tries\n U = np.empty([N - 1, N - 1], float)\n Q = np.empty([N - 1, N - 1], float)\n W = np.empty([N - 1, N - 1], float)\n U[0, 0] = 0 # U00\n sq = U[0, 0]/2\n sw = U[0, 0]/2\n\n # filling in boundary values\n for i in range(N - 1):\n aq = Z[i, 0]\n aw = Z[0, i]\n conq = {'type': 'ineq', 'fun': lambda x: error - abs(sq + x/2 - aq)}\n conw = {'type': 'ineq', 'fun': lambda x: error - abs(sw + x/2 - aw)}\n resq = minimize(Sq, x0=IG, constraints=conq, method=m, options={'maxiter': Tries})\n tryCount = 0\n\n while resq.success == False:\n #errorEntry['bg'] = 'red'\n print(\"ResQ :: \" + resq.message)\n #print(\"Resq Iterations == \" + str(resq.nit) + \" in \" + str(i) + \" \" + \"0\")\n #print(\"Tries count == \" + str(tryCount))\n tryCount = tryCount + 1\n if (tryCount > Tries):\n return []\n resq = minimize(Sq, x0=IG, constraints=conq, method=m, options={'maxiter': Tries})\n\n #print(\"Resq Iterations == \" + str(resq.nit) + \" in \" + str(i) + \" \" + str(0))\n resw = minimize(Sw, x0=IG, constraints=conw, method=m, options={'maxiter': Tries})\n tryCount = 1\n\n while resw.success == False:\n\n print(\"ResW :: \" + resw.message)\n #print(\"Resw Iterations == \" + str(resw.nit) + \" in \" + str(0) + \" \" + str(i))\n #print(\"Tries count == \" + str(tryCount))\n\n tryCount = tryCount + 1\n if (tryCount > Tries):\n return []\n resw = minimize(Sw, x0=IG, constraints=conw, method=m, options={'maxiter': Tries})\n\n # print(\"Resw Iterations == \" + str(resw.nit) + \" in \" + str(0) + \" \" + str(i))\n #print(\"conW == \" + str(error - abs(sw + resw.x - aw)))\n #print(\"conQ == \" + str(error - abs(sq + resq.x - aq)))\n\n if resq.x < e:\n resq.x = 0\n if resw.x < e:\n resw.x = 0\n\n ISW = ISW + (1 + resw.x ** 2) ** (1 / 2)\n ISQ = ISQ + (1 + resq.x ** 2) ** (1 / 2)\n Q[i, 0] = resq.x\n W[0, i] = resw.x\n U[i, 0] = sq + resq.x/2\n U[0, i] = sw + resw.x/2\n sq = sq + resq.x\n sw = sw + resw.x\n # print(res.x)\n # filling non-boundary main grid surface\n F = 0 * Z\n\n for i in range(1, N - 1):\n for j in range(1, N - 1):\n I = i + 1\n J = j + 1\n q = U[0, 0]\n w = U[0, 0]\n q = q + Q[0, j]/2\n w = w + W[i, 0]/2\n for k in range(1, i):\n q = q + Q[k, j]\n for k in range(1, j):\n w = w + W[i, k]\n a = Z[i, j]\n con = {'type': 'ineq',\n 'fun': lambda x: -abs((1 / 2) * (q + w + U[i, 0] + U[0, j] + x[0]/2 + x[1]/2) - a) + error}\n res = minimize(S, x0=(IG, IG), constraints=con, method=m, options={'maxiter': Tries})\n tryCount = 1\n while res.success == False:\n\n print(\"ResMain :: \" + res.message)\n #print(\"ResMain Iterations == \" + str(res.nit) + \" in \" + str(i) + \" \" + str(j))\n #print(\"Tries count == \" + str(tryCount))\n\n tryCount = tryCount + 1\n if (tryCount > Tries):\n return []\n res = minimize(S, x0=(IG, IG), constraints=con, method=m, options={'maxiter': Tries})\n\n #print(\"ResMain Iterations == \" + str(res.nit) + \" in \" + str(i) + \" \" + str(j))\n #print(\"conMain == \" + str(-abs((1 / 2) * (q + w + U[i, 0] + U[0, j] + res.x[0] + res.x[1]) - a) + error))\n #print(\"maxcv == \" + str(res.maxcv))\n\n if res.x[0] < eps:\n res.x[0] = 0.0\n if res.x[1] < eps:\n res.x[1] = 0.0\n\n Q[i, j] = res.x[0]\n W[i, j] = res.x[1]\n U[i, j] = (1 / 2) * (q + w + U[i, 0] + U[0, j] + res.x[0]/2 + res.x[1]/2)\n #errorEntry['bg'] = 'white'\n # q/2 + res.x[0]/2 + w/2 + res.x[1]/2 + U[i, 0] + U[0, j]\n print(error)\n return U\n\n\ndef Run():\n global Z\n root['bg'] = 'white'\n #errorEntry['bg'] = 'white'\n X, Y = np.meshgrid(np.linspace(0, N, N - 1), np.linspace(0, N, N - 1)) # x y grids\n O = FillOrigin()\n if Random.get() == 1:\n Z = AddNoise(O.copy())\n U = RestorationRun(N, Z, eps)\n fig.clf()\n ax1 = plt.subplot(1, 3, 1, projection='3d')\n ax1.plot_surface(X, Y, O, cmap='Spectral')\n ax2 = plt.subplot(1, 3, 2, projection='3d')\n ax2.plot_surface(X, Y, Z, cmap='Spectral')\n if len(U) > 1:\n ax3 = plt.subplot(1, 3, 3, projection='3d')\n ax3.plot_surface(X, Y, U, cmap='Spectral')\n else:\n root['bg'] = 'red'\n root.mainloop()\n\n\n\nroot.title(\"DATASURFACE\")\nroot.geometry(\"200x150\")\nroot.resizable(width=True, height=True)\nmoreButton.config(command=AddError)\nlessButton.config(command=SubtractError)\nretryButton.config(command=Retry)\nerrorEntry.bind(\"\", errorEntryValueChanged)\n\nerrorEntry.pack()\nretryButton.pack()\nrandomButton.pack()\nmoreButton.pack()\nlessButton.pack()\n\nerrorEntry.delete(0, tk.END)\nerrorEntry.insert(0, error)\n\nRun()\n# canvas = FigureCanvasTkAgg(fig, root)\n# toolbar = NavigationToolbar2Tk(canvas, root)\n# toolbar.update()\n#\n# def on_key_press(event):\n# print(\"you pressed {}\".format(event.key))\n# key_press_handler(event, canvas, toolbar)\n#\n# canvas.mpl_connect(\"key_press_event\", on_key_press)\n# canvas.get_tk_widget().pack(side=\"top\",fill='both',expand=True)\n# X = np.linspace(0, N, N-1)\n# Y = np.linspace(0, N, N-1)\n#ax3 = fig.add_subplot(1, 3, 1, projection='3d')\n#ax1 = fig.add_subplot(1, 3, 2, projection='3d')\n#ax2 = fig.add_subplot(1, 3, 3, projection='3d')\n","sub_path":"Trap.py","file_name":"Trap.py","file_ext":"py","file_size_in_byte":9114,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"337607074","text":"import math\nimport sys\nfrom PyQt5.QtWidgets import *\nfrom PyQt5.QtGui import *\nfrom PyQt5.QtCore import *\n\nclass DrawPoints(QWidget):\n def __init__(self):\n super(DrawPoints, self).__init__()\n self.setWindowTitle('窗口绘制')\n self.resize(300,200)\n self.text='bighu'\n def paintEvent(self, event) -> None:\n painter=QPainter(self)\n painter.begin(self)\n pen=QPen()\n painter.setPen(QColor(\"red\"))\n painter.setFont(QFont('SimSun',25))\n # painter.drawText(event.rect(),Qt.AlignCenter,self.text)\n size=self.size()\n for i in range(1000):\n x=100*(-1+2.0*i/1000)+size.width()/2.0\n y=50*math.sin((x-size.width()/2.0)*math.pi/50)+size.height()/2.0\n painter.drawPoint(x,y)\n painter.end()\n pass\nif __name__ == '__main__':\n app=QApplication(sys.argv)\n main=DrawPoints()\n main.show()\n\n sys.exit(app.exec_())","sub_path":"drwawing/DrawPoints.py","file_name":"DrawPoints.py","file_ext":"py","file_size_in_byte":947,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"503373300","text":"# -*- coding: utf-8 -*- \n\nfigur = raw_input(\"hvilken figur? \")\n\nif figur == \"kvadrat\": \n print (\"oki\")\n maal = int(input(\"hvilken str. har sidene?\"))\n kvadrat = maal**2\n print (\"....kvadratet er %d\") % (kvadrat) \n\nif figur == \"rektangel\":\n w = int(input(\"hva er lengden?\" ))\n h = int(input(\"hva er høyden? \" ))\n rektangel = w * h\n print (\"....rektangelet er %d\") % (rektangel) \n\nelse:\n print (\"oki, prøv igjen\") ","sub_path":"area.py","file_name":"area.py","file_ext":"py","file_size_in_byte":441,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"654105822","text":"import urllib.request\nimport urllib.error\nfrom bs4 import BeautifulSoup\nimport ast\nimport time\nimport sys\n\npath = sys.argv[1]\ndef getHtml(url):\n try:\n fp = urllib.request.urlopen(link)\n return fp\n except urllib.error.HTTPError as e:\n if e.getcode() == 429:\n time.sleep(5)\n return getHtml(url)\n \n\nfor line in open(path, \"r\").readlines():\n hsh = line.strip().split(\" \")[1]\n link = \"https://github.com/search?q={}&type=commits\".format(hsh)\n fp = getHtml(link)\n mybytes = fp.read()\n mystr = mybytes.decode(\"utf8\")\n fp.close()\n\n soup = BeautifulSoup(mystr, features=\"html.parser\")\n\n for hyper in soup.find_all(\"a\", {\"class\": \"message markdown-title js-navigation-open\"}):\n for attrib in hyper[\"data-hydro-click\"].split(\",\"):\n tokens = attrib.split(\":\")\n if tokens[0] == \"\\\"url\\\"\":\n print(\":\".join(tokens[1:]).replace(\"\\\"\",\"\").replace(\"}\",\"\"))\n break\n time.sleep(2)\n","sub_path":"scripts/getCommitLink.py","file_name":"getCommitLink.py","file_ext":"py","file_size_in_byte":1018,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"15329006","text":"from django.shortcuts import render, redirect\nfrom django.http import HttpResponse\nfrom django import forms\nfrom forms import *\nfrom api_methods import *\nfrom models import *\nfrom modelForms import *\nimport datetime, pytz, iso8601\n\n####################################################################################################\n################################ Authentication and setup methods ##################################\n####################################################################################################\n\n\"\"\"\nAuthentication view that fetches token object for using drchrono APIs and\nsets up a list of all the patients with an appointment on the present day\nin the database\n\"\"\"\n\ndef auth(request):\n response = get_token(request)\n response.raise_for_status()\n data = response.json()\n # Save these in your database associated with the user\n token = Token.objects.create(\n access_token = data['access_token'],\n refresh_token = data['refresh_token'],\n expires_timestamp = datetime.datetime.now(pytz.utc) + datetime.timedelta(seconds=data['expires_in'])\n )\n token.save()\n # Create an appointment list for the day and redirect to welcome page\n appointments = Appointment.objects.all()\n if appointments != None:\n appointments.delete()\n create_appointment_list(token)\n return redirect(\"/options\")\n\n\n\"\"\"\nCreates a complete list of all the patients\nwith an appointment today and stores that list\nin the database in the Appointment object tabel\n\"\"\"\ndef create_appointment_list(token):\n appointments, patients = get_patient_appointments(token)\n for a in appointments:\n first_name, last_name, ssn = patients[a['patient']]\n time = iso8601.parse_date(a['scheduled_time'])\n new_appointment = Appointment(pid = a['patient'], first_name = first_name, last_name = last_name, SSN = ssn.replace('-',''), time = time, check_in_time = time, duration = a['duration'])\n new_appointment.save()\n return\n\n\n####################################################################################################\n####################### Options, Status, Welcome, Error and Success Methods ########################\n####################################################################################################\n\n\"\"\"\nOptions Page\n\"\"\"\ndef options(request):\n return render(request, 'options.html')\n\n\"\"\"\nStatus Page\n\"\"\"\ndef status(request):\n appointments = Appointment.objects.all()\n wait_times = ['0m 0s'] * len(appointments)\n return render(request, 'status.html',{'appointments': zip(appointments, wait_times)})\n\n\"\"\"\nWelcome Page\n\"\"\"\ndef welcome(request):\n return render(request, 'welcome.html')\n\n\n\"\"\"\nError Page\n\"\"\"\ndef error(request):\n return render(request, 'error.html')\n\n\n\"\"\"\nSuccess Page\n\"\"\"\ndef success(request):\n return render(request, 'success.html')\n\n\n\n####################################################################################################\n############################## View methods used by the status page ################################\n####################################################################################################\n\n\"\"\"\nUsed by status page in an ajax call to update\npatient's appointment status to 'In Session'\n\"\"\"\ndef start_appointment(request):\n pid = request.GET.get('pid')\n appointments = Appointment.objects.filter(pid=pid)\n if appointments:\n for a in appointments:\n if a.status == 'AR':\n a.status = 'INS'\n a.wait_time = find_wait_time(a.check_in_time)\n a.save()\n break\n return HttpResponse('Patient status changed!')\n return HttpResponse('Looks like the patient is done!')\n\n\n\"\"\"\nUsed by status page in an ajax call to update\npatient's appointment status to 'Complete'\n\"\"\"\ndef end_appointment(request):\n pid = request.GET.get('pid')\n appointments = Appointment.objects.filter(pid=pid)\n if appointments:\n for a in appointments:\n if a.status == 'INS':\n a.status = 'COM'\n a.save()\n break\n return HttpResponse('Patient removed from list!')\n return HttpResponse('Looks like the patient is done!')\n\n\n\"\"\"\nUsed by status page in an ajax call to update\npatient's waiting time since his/her checking in\n\"\"\"\ndef update(request):\n appointments, wait_times = Appointment.objects.all(), []\n for a in appointments:\n if a.check_in_time != a.time:\n wait_times.append(find_wait_time(a.check_in_time))\n else:\n wait_times.append(\"0m 0s\")\n return render(request, 'update.html', {'appointments': zip(appointments, wait_times)})\n\n\"\"\"\nHelper method to find wait time of a patient\n\"\"\"\ndef find_wait_time(check_in_time):\n diff = datetime.datetime.now(pytz.UTC) - check_in_time\n diff = divmod(diff.days * 86400 + diff.seconds, 60)\n minutes, seconds = diff[0], diff[1]\n return \"\".join([str(minutes), 'm ', str(seconds), 's'])\n\n####################################################################################################\n############################## View methods used in check-in flow ##################################\n####################################################################################################\n\n\"\"\"\nView method used to validate a patient's appointment and\nsend him further in the check-in process\n\"\"\"\ndef check_in(request):\n if request.method == 'POST':\n ssn = request.POST.get('SSN')\n appointments = Appointment.objects.filter(SSN = ssn)\n if appointments:\n for a in appointments:\n if a.checked_in == False:\n return redirect(\"/demographics/\" + str(a.pid))\n else:\n #redirect to another page showing an error message\n return redirect(\"/error\")\n else:\n form = AppointmentForm()\n return render(request, 'check_in.html', {'form': form})\n\n\n\"\"\"\nView method used to render the DemographicInfoForm\nfor the logged-in patient.\n\"\"\"\ndef demographics(request, pid):\n if request.method == 'GET':\n token = Token.objects.get(pk = 1)\n info = get_demographics(token, pid)\n form = DemographicInfoForm({\n 'email' : info['email'],\n 'address' : info['address'],\n 'cell_phone' : info['cell_phone'],\n 'gender' : info['gender'],\n 'ethnicity' : info['ethnicity']\n })\n return render(request, 'demographics.html', {'form':form, 'pid': pid})\n\n\n\"\"\"\nView method used to update a patient's demographic info\nand let him complete the check-in process\n\"\"\"\ndef update_info(request, pid):\n form = DemographicInfoForm(request.POST)\n if form.is_valid():\n token = Token.objects.get(pk = 1)\n update_demographics(token, form.cleaned_data, pid)\n appointments = Appointment.objects.filter(pid=pid)\n if appointments:\n for a in appointments:\n if a.checked_in == False:\n a.status = 'AR'\n a.check_in_time = datetime.datetime.now(pytz.UTC)\n a.checked_in = True\n a.save()\n break\n return redirect(\"/success\")\n else:\n return redirect(\"/error\") #make this page\n","sub_path":"django_projects/check-in-kiosk/drchrono/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":7460,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"164291884","text":"import chainer\nfrom chainer import datasets\nfrom chainer import optimizers\nfrom chainer import training, iterators, serializers\nfrom chainer import Variable\nimport chainer.functions as F\nimport chainer.links as L\nfrom chainer.backends import cuda\nimport chainer\nfrom chainer import datasets\nfrom chainer import optimizers\nfrom chainer import training, iterators, serializers\nfrom chainer import Variable\nimport chainer.functions as F\nimport chainer.links as L\nfrom chainer.backends import cuda\nfrom chainer.training import extensions\nimport numpy as np\nimport subprocess\nimport collections\n\ncounter = 0\n\ninput_size = 128\n\nactivations = {}\ntarget_layers = set()\n\nxp = cuda.cupy\n\n\nclass cnn_rnn_5layer(chainer.Chain):\n def __init__(self):\n super(cnn_rnn_5layer,self).__init__()\n with self.init_scope():\n self.c1_1 = L.Convolution2D(in_channels=3,out_channels=10,ksize=5,pad=3)\n self.c1_2 = L.Convolution2D(in_channels=10,out_channels=20,ksize=5)\n self.c1_3 = L.Convolution2D(in_channels=20,out_channels=20,ksize=5)\n self.c2_1 = L.Convolution2D(in_channels=3,out_channels=10,ksize=5,pad=3)\n self.c2_2 = L.Convolution2D(in_channels=10,out_channels=20,ksize=5)\n self.c2_3 = L.Convolution2D(in_channels=20,out_channels=20,ksize=5)\n self.c3_1 = L.Convolution2D(in_channels=3,out_channels=10,ksize=5,pad=3)\n self.c3_2 = L.Convolution2D(in_channels=10,out_channels=20,ksize=5)\n self.c3_3 = L.Convolution2D(in_channels=20,out_channels=20,ksize=5)\n self.c4_1 = L.Convolution2D(in_channels=3,out_channels=10,ksize=5,pad=3)\n self.c4_2 = L.Convolution2D(in_channels=10,out_channels=20,ksize=5)\n self.c4_3 = L.Convolution2D(in_channels=20,out_channels=20,ksize=5)\n self.c5_1 = L.Convolution2D(in_channels=3,out_channels=10,ksize=5,pad=3)\n self.c5_2 = L.Convolution2D(in_channels=10,out_channels=20,ksize=5)\n self.c5_3 = L.Convolution2D(in_channels=20,out_channels=20,ksize=5)\n \n self.fc1_1 = L.Linear(None,500)\n self.fc2_1 = L.Linear(None,500)\n self.fc3_1 = L.Linear(None,500)\n self.fc4_1 = L.Linear(None,500)\n self.fc5_1 = L.Linear(None,500)\n self.lstm = L.LSTM(500,out_size=500)\n \n #self.lstm = L.LSTM(2880,2880)\n self.fc_1 = L.Linear(None,500)\n self.fc_2 = L.Linear(None,2)\n\n self.func_list = collections.OrderedDict([\n ('c1_1',[self.c1_1, F.relu]),\n ('pool1_1', [_max_pooling_2d]),\n ('c1_2',[self.c1_2, F.relu]),\n ('pool1_2', [_max_pooling_2d]),\n ('c1_3',[self.c1_3, F.relu]),\n ('pool1_3', [_max_pooling_2d]),\n ('fc1', [self.fc1_1, F.dropout]),\n ('c2_1',[self.c2_1, F.relu]),\n ('pool2_1', [_max_pooling_2d]),\n ('c2_2',[self.c2_2, F.relu]),\n ('pool2_2', [_max_pooling_2d]),\n ('c2_3',[self.c2_3, F.relu]),\n ('pool2_3', [_max_pooling_2d]),\n ('fc2', [self.fc2_1, F.dropout]),\n ('c3_1',[self.c3_1, F.relu]),\n ('pool3_1', [_max_pooling_2d]),\n ('c3_2',[self.c3_2, F.relu]),\n ('pool3_2', [_max_pooling_2d]),\n ('c3_3',[self.c3_3, F.relu]),\n ('pool3_3', [_max_pooling_2d]),\n ('fc3', [self.fc3_1, F.dropout]),\n ('c4_1',[self.c4_1, F.relu]),\n ('pool4_1', [_max_pooling_2d]),\n ('c4_2',[self.c4_2, F.relu]),\n ('pool4_2', [_max_pooling_2d]),\n ('c4_3',[self.c4_3, F.relu]),\n ('pool4_3', [_max_pooling_2d]),\n ('fc4', [self.fc4_1, F.dropout]),\n ('c5_1',[self.c5_1, F.relu]),\n ('pool5_1', [_max_pooling_2d]),\n ('c5_2',[self.c5_2, F.relu]),\n ('pool5_2', [_max_pooling_2d]),\n ('c5_3',[self.c5_3, F.relu]),\n ('pool5_3', [_max_pooling_2d]),\n ('fc5', [self.fc5_1, F.dropout]),\n ('lstm1', [self.lstm]),\n ('lstm2', [self.lstm]),\n ('lstm3', [self.lstm]),\n ('lstm4', [self.lstm]),\n ('lstm5', [self.lstm]),\n ('fc_2', [self.fc_2]),\n ('prob', [F.softmax]),\n ])\n \n\n def __call__(self,x,layers=['fc_2']): \n global activations\n global target_layers\n self.lstm.reset_state()\n\n x = (x - 220)/100\n x1 = x[:,:,:,:,0]\n x2 = x[:,:,:,:,1]\n x3 = x[:,:,:,:,2] \n x4 = x[:,:,:,:,3]\n x5 = x[:,:,:,:,4] \n\n activations = {'input': x}\n target_layers = set(layers)\n print(target_layers)\n h1 = self.execute('c1_1',x1) \n h1 = self.execute('pool1_1',h1)\n h1 = self.execute('c1_2',h1)\n h1 = self.execute('pool1_2',h1)\n h1 = self.execute('c1_3',h1)\n h1 = self.execute('pool1_3',h1)\n h1 = self.execute('fc1',h1)\n\n h2 = self.execute('c2_1',x2) \n h2 = self.execute('pool2_1',h2)\n h2 = self.execute('c2_2',h2)\n h2 = self.execute('pool2_2',h2)\n h2 = self.execute('c2_3',h2)\n h2 = self.execute('pool2_3',h2)\n h2 = self.execute('fc2',h2)\n \n h3 = self.execute('c3_1',x3) \n h3 = self.execute('pool3_1',h3)\n h3 = self.execute('c3_2',h3)\n h3 = self.execute('pool3_2',h3)\n h3 = self.execute('c3_3',h3)\n h3 = self.execute('pool3_3',h3)\n h3 = self.execute('fc3',h3)\n\n h4 = self.execute('c4_1',x4) \n h4 = self.execute('pool4_1',h4)\n h4 = self.execute('c4_2',h4)\n h4 = self.execute('pool4_2',h4)\n h4 = self.execute('c4_3',h4)\n h4 = self.execute('pool4_3',h4)\n h4 = self.execute('fc4',h4)\n\n h5 = self.execute('c5_1',x5) \n h5 = self.execute('pool5_1',h5)\n h5 = self.execute('c5_2',h5)\n h5 = self.execute('pool5_2',h5)\n h5 = self.execute('c5_3',h5)\n h5 = self.execute('pool5_3',h5)\n h5 = self.execute('fc5',h5)\n\n h1 = self.execute('lstm1',h1)\n h1 = self.execute('lstm2',h2)\n h1 = self.execute('lstm3',h3)\n h1 = self.execute('lstm4',h4)\n h = self.execute('lstm5',h5)\n print(h.shape)\n h = self.execute('fc_2',h)\n h = self.execute('prob',h)\n \n return activations\n\n def execute(self,key,x):\n global activations\n global target_layers\n\n h = chainer.Variable(x)\n funcs = self.func_list[key]\n for func in funcs:\n h = func(h)\n\n if key in target_layers:\n activations[key] = h\n #target_layers.remove(key)\n return h\n\ndef _max_pooling_2d(self,x):\n return F.max_pooling_2d(x, ksize=4, stride=2)\n\ncounter = 0\n\ninput_size = 128\nsize_batch = 100\nnum_epoch = 40\n\narg_test = True\n\nxp = cuda.cupy\n\n#outdir='result_cnn_enn'\n#outdir='result_cnn_rnn'\n#outdir='result_cnn_enn_5layer'\noutdir='result_cnn_rnn_5layer'\n\ndef lossfun(x, t):\n h = F.softmax_cross_entropy(x, t)\n #print(h)\n return h\n\n\ndef main():\n print(\"start main\")\n # initialize\n\n model = L.Classifier(cnn_rnn_5layer()['fc_2'],lossfun=lossfun)\n optimizer = optimizers.Adam()\n optimizer.setup(model) \n #optimizer.add_hook(chainer.optimizer.GradientClipping(10.0))\n \n # load training data and test data\n\n # GPU setting\n cuda.get_device(0).use()\n model.to_gpu()\n\n data_h = xp.load('HeLa_128_patch_5layer.npz')\n data_s = xp.load('SiHa_128_patch_5layer.npz')\n \n #registraite training and test data \n data_HeLa = data_h['HeLa_128_patch']\n data_SiHa = data_s['SiHa_128_patch']\n\n X_train = data_HeLa[8000:9000,:,:,:,:]\n X_train = xp.concatenate(( X_train, data_SiHa[8000:9000,:,:,:,:]), axis = 0)\n X_test = data_HeLa[9900:10000,:,:,:,:]\n X_test = xp.concatenate(( X_test, data_SiHa[9900:10000,:,:,:,:]), axis = 0)\n \n Y_train = xp.zeros(1000, dtype=xp.int)\n Y_train = xp.concatenate((Y_train, xp.ones(1000, dtype=xp.int)))\n Y_test = xp.zeros(100, dtype=xp.int)\n Y_test = xp.concatenate((Y_test, xp.ones(100, dtype=xp.int)))\n\n #print(\"x:{0}__Y:{1}\".format(X_train.shape,Y_train.shape))\n\n train = datasets.tuple_dataset.TupleDataset(X_train.astype(xp.float32), Y_train.astype(xp.int32))\n test = datasets.tuple_dataset.TupleDataset(X_test.astype(xp.float32), Y_test.astype(xp.int32))\n\n train_iter = iterators.SerialIterator(train, batch_size=size_batch, repeat=True, shuffle=True)\n test_iter = iterators.SerialIterator(test, batch_size=size_batch, repeat=False, shuffle=False)\n\n print(\"data loaded\")\n\n # Set up a trainer\n updater = training.StandardUpdater(train_iter, optimizer, device=0)\n trainer = training.Trainer(updater, (num_epoch, 'epoch'), out=outdir) \n\n\n trainer.extend(extensions.Evaluator(test_iter, model, device=0))\n\n #trainer.extend(extensions.dump_graph('main/loss'))\n\n # Take a snapshot at each epoch\n trainer.extend(extensions.snapshot(),trigger=(10,'epoch'))\n\n # Write a log of evaluation statistics for each epoch\n trainer.extend(extensions.LogReport())\n\n \n trainer.extend(extensions.PrintReport(\n ['epoch', 'main/loss', 'validation/main/loss',\n 'main/accuracy', 'validation/main/accuracy']),trigger=(100,'iteration'))\n \n trainer.extend(extensions.PlotReport(\n ['main/accuracy', 'validation/main/accuracy'],trigger=(20,'iteration'),file_name='acc.png'))\n\n trainer.extend(extensions.PlotReport(\n ['main/loss' ,'validation/main/loss'],trigger=(20,'iteration'),file_name='loss.png'))\n\n # Print a progress bar to stdout\n trainer.extend(extensions.ProgressBar())\n\n #serializers.load_npz(\"cnn_savedata.npz\", model)\n\n # Run the training\n trainer.run()\n\n model.to_cpu()\n\n # save CNN\n serializers.save_npz(\"cnn_savedata.npz\",model)\n\n\nif __name__ == '__main__':\n main()","sub_path":"sam.py","file_name":"sam.py","file_ext":"py","file_size_in_byte":9887,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"27393499","text":"\nimport dateutil.parser\nimport calendar\nimport csv\n\ndef is_float(val) :\n try :\n tmp = float(val)\n return True\n except:\n return False\n\n\n\ndef get_date_str(str) :\n date = dateutil.parser.parse(str)\n if date is None :\n return ''\n\n return date.strftime('%Y-%m-%d')\n\n\n\ndef is_weekend(date) :\n val = calendar.weekday(date.year, date.month, date.day)\n return val != 5 and val != 6\n\n\n\ndef read_file(file, skip_rows = 0):\n with open(file, 'r') as f:\n data = [row for row in csv.reader(f.read().splitlines())]\n return data[ skip_rows : ]\n","sub_path":"p3/parse_helper.py","file_name":"parse_helper.py","file_ext":"py","file_size_in_byte":589,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"397540286","text":"\"\"\"fancybin URL Configuration\n\nThe `urlpatterns` list routes URLs to views. For more information please see:\n https://docs.djangoproject.com/en/3.1/topics/http/urls/\nExamples:\nFunction views\n 1. Add an import: from my_app import views\n 2. Add a URL to urlpatterns: path('', views.home, name='home')\nClass-based views\n 1. Add an import: from other_app.views import Home\n 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')\nIncluding another URLconf\n 1. Import the include() function: from django.urls import include, path\n 2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))\n\"\"\"\nfrom django.urls import path\nfrom django.views.generic import TemplateView\nfrom pastes.views import home, newPaste, viewPaste, editPaste, savePaste, deletePaste\n\nurlpatterns = [\n path('', home, name=\"home\"),\n path('paste/new', newPaste, name=\"newpaste\"),\n path('paste/view/', viewPaste, name=\"viewpaste\"),\n path('paste/edit/', editPaste, name=\"editpaste\"),\n path('paste/save/', savePaste, name=\"savepaste\"),\n path('paste/delete/', deletePaste, name=\"deletepaste\"),\n]\n","sub_path":"fancybin/pastes/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1129,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"633097710","text":"# 손님에게 거슬러 줘야 할 돈이 N원일 때, 거슬러 줘야 할 동전의 최소 개수를 구하라.\n\nN = int(input(\"거스름돈을 입력하세요: \"))\ncount = 0\ncoin_type=[500, 100, 50, 10]\nfor coin in coin_type:\n count += N // coin\n N %= coin # N을 coin으로 나누고 난 후 나머지\n\nprint(\"거슬러 줘야 할 동전의 개수: \" + str(count) + \"개\")","sub_path":"개념 공부/Greedy Algorithms/거스름돈.py","file_name":"거스름돈.py","file_ext":"py","file_size_in_byte":383,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"242601101","text":"from math import sqrt\ndef isprime(x):\n if x == 1: # 没有考虑到x=1的情况\n return False\n k = int(sqrt(x)) # 没有考虑到k需要时整数\n for j in range(2,k+1): # 记错range的用法\n if x % j == 0:\n return False # 对true和false的理解反了\n return True #如果在这一步骤用if-else做判断,就变成指判断了%2是否为零,判断奇偶性了\nfor i in range(1,101):\n if isprime(i):\n print(i,end=' ')","sub_path":"playwith/2.5 function_.py","file_name":"2.5 function_.py","file_ext":"py","file_size_in_byte":478,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"630980700","text":"import torch\nfrom matplotlib import pyplot as plt\n\nx = torch.linspace(0, 5, 100, requires_grad=True)\nprint(x.grad)\ny = (x**2).cos()\ny.sum().backward()\nprint(x.grad)\n\nplt.plot(x.detach(), y.detach(), label='y')\nplt.plot(x.detach(), x.grad, label='dy/dx')\nplt.legend()\nplt.show()","sub_path":"pytorch/Basic/Autograd/backprop.py","file_name":"backprop.py","file_ext":"py","file_size_in_byte":277,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"621361664","text":"import numpy as np\nimport matplotlib.pyplot as plt\nimport sys\n\nfilename = sys.argv[1]\n\npdata = []\nvirdata = []\nsetdata = []\nversdata = []\n\n\n# 1: sepal length in cm\n# 2: sepal width in cm\n# 3: petal length in cm\n# 4: petal width in cm\n# 5: class\n\nwith open(filename) as f:\n\tfor line in f.readlines():\n\t\tline = line.replace(\"\\n\", \"\")\n\t\tif line == \"\":\n\t\t\tbreak\n\t\tattr = line.split(',')\n\t\tflower = []\n\t\tcount = 0\n\t\tfor a in attr:\n\t\t\tflower.append(a) if count == 4 else flower.append(float(a))\n\t\t\tcount += 1\n\t\tpdata.append(flower)\n\n\n\ndata = np.array(pdata)\n\n\nfor entry in pdata:\n if entry[4] == \"Iris-versicolor\":\n versdata.append(entry)\n elif entry[4] == \"Iris-setosa\":\n setdata.append(entry)\n else:\n virdata.append(entry)\n\nwith open(\"setosa_data.txt\", 'w') as f:\n for entry in setdata:\n for attr in entry:\n f.write(str(attr))\n f.write(',')\n f.write('\\n')\n\nwith open(\"virginica_data.txt\", 'w') as f:\n for entry in virdata:\n for attr in entry:\n f.write(str(attr))\n f.write(',')\n f.write('\\n')\n\nwith open(\"versicolor_data.txt\", 'w') as f:\n for entry in versdata:\n for attr in entry:\n f.write(str(attr))\n f.write(',')\n f.write('\\n')\nbinsize = abs(min(data[:,3].astype(float)) - max(data[:,3].astype(float)))\nbbins=np.arange(min(data[:,3].astype(float)), max(data[:,3].astype(float)) + binsize/10.0, binsize/10.0)\n\nplt.hist( data[:,3].astype(float), bins = bbins )\nplt.xlabel(\"Petal Length in cm\")\nplt.ylabel(\"Frequency\")\nplt.title(\"Histogram of petal length\")\n\nplt.show()\n\nx = data[:,0].astype(float)\ny = data[:,1].astype(float)\n\n\nmarkerType = np.array(150)\n\n# for i in range(0,150):\n# \tif data[i,4] == \"Iris-versicolor\":\n# markerType[i] = 'x'\n# elif data[i,4] == \"Iris-setosa\":\n# markerType[i] = 'o'\n# else:\n# markerType[i] = '*' \n\n\nxvir = np.array(virdata)[:,0].astype(float)\nyvir = np.array(virdata)[:,1].astype(float)\n\nxset = np.array(setdata)[:,0].astype(float)\nyset = np.array(setdata)[:,1].astype(float)\n\nxver = np.array(versdata)[:,0].astype(float)\nyver = np.array(versdata)[:,1].astype(float)\n\nvirscat = plt.scatter(xvir, yvir, marker='x', c='red')\nsetscat = plt.scatter(xset, yset, marker='o', c='blue')\nverscat = plt.scatter(xver, yver, marker='*', c='green')\n\n\nplt.xlabel(\"Sepal Length in cm\")\nplt.ylabel(\"Sepal Width in cm\")\nplt.title(\"Scatter plot of sepal length vs width\")\nplt.legend((virscat, setscat, verscat),\n\t('Virginica', 'Setosa', 'Versicolor'),\n\tscatterpoints = 1)\n\n\nplt.show()","sub_path":"HW2/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2574,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"39009906","text":"from keras.preprocessing.image import ImageDataGenerator, img_to_array, load_img\r\nfrom keras.utils.np_utils import to_categorical\r\nfrom keras.models import Sequential\r\nfrom keras.layers import Dropout, Activation, Flatten, Dense\r\nfrom keras.layers import Conv2D, MaxPooling2D, AveragePooling2D\r\nfrom keras import applications\r\nfrom datetime import datetime\r\nimport numpy as np\r\nimport cv2\r\nimport os\r\n\r\n\r\ndef read_image(img_path, image_size):\r\n print('Reading image...')\r\n original_image = cv2.imread(img_path)\r\n image = load_img(image_path, target_size=(image_size, image_size))\r\n image = img_to_array(image)\r\n image = image / 255\r\n image = np.expand_dims(image, axis=0)\r\n return original_image, image\r\n\r\n\r\ndef predict_to_image(image, class_num, weights_path):\r\n print('Making prediction...')\r\n model = applications.InceptionV3(include_top=False, weights='imagenet')\r\n start = datetime.now()\r\n prediction = model.predict(image)\r\n\r\n model = Sequential()\r\n model.add(Conv2D(400, (3, 3), padding='same', input_shape=prediction.shape[1:]))\r\n model.add(Activation('relu'))\r\n model.add(Dropout(0.2))\r\n model.add(Conv2D(400, (3, 3), padding='same'))\r\n model.add(Activation('relu'))\r\n model.add(Dropout(0.2))\r\n model.add(AveragePooling2D(pool_size=(2, 2), padding='same'))\r\n\r\n model.add(Conv2D(200, (3, 3), padding='same'))\r\n model.add(Activation('relu'))\r\n model.add(Dropout(0.2))\r\n model.add(Conv2D(200, (3, 3), padding='same'))\r\n model.add(Activation('relu'))\r\n model.add(Dropout(0.2))\r\n model.add(AveragePooling2D(pool_size=(2, 2), padding='same'))\r\n\r\n model.add(Flatten())\r\n model.add(Dense(64))\r\n model.add(Dropout(0.2))\r\n model.add(Dense(class_num, activation='sigmoid'))\r\n\r\n model.load_weights(weights_path)\r\n class_predicted = model.predict_classes(prediction)\r\n class_id = class_predicted[0]\r\n inv_map = {v: k for k, v in class_dictionary.items()}\r\n label = inv_map[class_id]\r\n proba = model.predict_proba(prediction)\r\n end = datetime.now()\r\n analysistime = round((end - start).total_seconds(), 2)\r\n acc = round((proba.max()) * 100, 2)\r\n return acc, label, proba, analysistime\r\n\r\n\r\nif __name__ == \"__main__\":\r\n model_weights_path = 'modelweightsAcc1.0.h5'\r\n\r\n img_size = 400\r\n\r\n class_dictionary = {\r\n \"obj1\": 0,\r\n \"obj2\": 1,\r\n \"obj3\": 2,\r\n \"obj4\": 3,\r\n \"obj5\": 4\r\n }\r\n num_classes = class_dictionary.__len__()\r\n\r\n img_count = 5\r\n test_images_directory = 'data/testimages'\r\n test_images_paths = [os.path.join(test_images_directory, 'obj{}5.png'.format(i)) for i in range(1, img_count + 1)]\r\n\r\n j = 1\r\n\r\n for img_path in test_images_paths:\r\n print(\"\\n{} ...\".format(j))\r\n org_img, img = read_image(img_path, img_size)\r\n accuracy, img_class, probabilities, analysis_time = predict_to_image(img, num_classes, model_weights_path)\r\n\r\n print(\"Analysis Time: {} ms\".format(analysis_time))\r\n print(\"Probabilities: {}\".format(probabilities))\r\n print(\"Class: {}\".format(img_class))\r\n print(\"Accuracy: %{}\\n\".format(accuracy))\r\n\r\n cv2.putText(org_img, \"Predicted: {}\".format(img_class), (10, 30), cv2.FONT_HERSHEY_PLAIN, 1.5, (255, 255, 255), 2)\r\n cv2.putText(org_img, \"Accuracy: %{}\".format(accuracy), (10, 50), cv2.FONT_HERSHEY_PLAIN, 1.5, (255, 255, 255), 2)\r\n\r\n cv2.imshow(\"ImageOutput-{} Predicted: {}\".format(j, img_class) + \" / Accuracy: %{}\".format(accuracy), org_img)\r\n\r\n j = j + 1\r\n\r\n cv2.waitKey(0)\r\n cv2.destroyAllWindows()\r\n","sub_path":"coil-20_iterational_prediction.py","file_name":"coil-20_iterational_prediction.py","file_ext":"py","file_size_in_byte":3587,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"115882521","text":"# -*- coding: UTF-8 -*-\n\nimport sys\nimport numpy as np\nimport pandas as pd\nimport os\nimport nltk\nimport string\nimport xlrd\n\nfrom pandas import Series, DataFrame\nfrom nltk.corpus import stopwords\nfrom rake_test import Metric, Rake\n# from rake_nltk import Metric, Rake\n\n\n## get file path\ndir_path = r'E:\\Learning Resources\\CASIA\\word frequency\\test_file' # direct path\nfile_name = os.listdir(dir_path) # return all the files and filenames\nfile_list = [os.path.join(dir_path, x) for x in file_name] # return all the file path\n\n## get column name\ncol_name = '内容'\n\n\n\ndef foo():\n file_i = []\n for file in file_list:\n df = pd.read_excel(file)\n # book = xlrd.open_workbook(file)\n # # xlrd用于获取每个sheet的sheetname\n # for sheet in book.sheets():\n # df = pd.read_excel(file, sheet.name)\n # if df.empty:\n # continue\n file_i.append(df)\n return file_i\n\ndef find_key_words_from_text(content, Compare):\n r = Rake(ranking_metric=Metric.TF_IDF, COMP_FLAG=Compare)\n r.extract_keywords_from_list(content)\n return r.get_ranked_phrases_with_scores()\n\ndef self_excel_writer(COMP, fileName, content):\n s = 'keywords_{a}.xlsx'\n writer = pd.ExcelWriter(s.format(a=fileName.split('.')[0]))\n if COMP:\n entities_list, words_list, whole_list = find_key_words_from_text(content, COMP)\n ## unzip data\n entities_list = list(zip(*entities_list))\n words_list = list(zip(*words_list))\n whole_list = list(zip(*whole_list))\n ## write data into excel files\n if whole_list:\n # whole keywords list\n whole_dict = {'热词': list(whole_list[0]),\n 'TF-IDF': list(whole_list[1]),\n '词频': list(whole_list[2])\n }\n data_whole = DataFrame(whole_dict)\n data_whole.to_excel(writer, 'keywords', index=False)\n if entities_list:\n # entities keywords list\n entities_dict = {'实体热词': list(entities_list[0]),\n 'TF-IDF-实体': list(entities_list[1]),\n '词频-实体': list(entities_list[2])\n }\n data_entities = DataFrame(entities_dict)\n data_entities.to_excel(writer, 'entities', index=False)\n if words_list:\n # non-entities keywords list\n words_dict = {'非实体热词': list(words_list[0]),\n 'TF-IDF-非实体': list(words_list[1]),\n '词频-非实体': list(words_list[2])\n }\n data_words = DataFrame(words_dict)\n data_words.to_excel(writer, 'non-entities', index=False)\n else:\n if key_words_list:\n key_words_list = find_key_words_from_text(content, COMP)\n key_words_list = list(zip(*key_words_list))\n key_words_dict = {'热词': list(key_words_list[0]),\n 'TF-IDF': list(key_words_list[1]),\n '词频': list(key_words_list[2])\n }\n data_keywords = DataFrame(key_words_dict)\n data_keywords.to_excel(writer, 'keywords', index=False)\n writer.save()\n\n\nif __name__ == \"__main__\":\n COMP = True\n file_i = foo()\n for i,file in enumerate(file_i):\n head_data = file.head(200)\n content = DataFrame(head_data, columns=[col_name])\n fileName = file_name[i]\n self_excel_writer(COMP, fileName, content)\n\n\n\n\n\n","sub_path":"WF_test.py","file_name":"WF_test.py","file_ext":"py","file_size_in_byte":3590,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"98431909","text":"import csv\nimport os\nimport pprint\n\nfrom tqdm import tqdm\n\ncorrected_dict = {}\n\nwith open('../official_data/错误修订/train文件中题目错误修订.csv', 'r') as f:\n reader = csv.reader(f)\n for row in tqdm(reader):\n doc_index = row[0]\n question = row[1]\n ans = row[2]\n corrected_dict[doc_index] = {\n 'question': question,\n 'ans': ans,\n 'type': 0,\n }\n\nwith open('../official_data/错误修订/train文件中答案错误修订.csv', 'r') as f:\n reader = csv.reader(f)\n for row in tqdm(reader):\n doc_index = row[0]\n question = row[1]\n ans = row[2]\n corrected_dict[doc_index] = {\n 'question': question,\n 'ans': ans,\n 'type': 1,\n }\n\nprint('what the corrected_dict is:')\n# pprint.pprint(corrected_dict)\nprint('and its length is:')\npprint.pprint(len(corrected_dict))\nprint()\n\ntrain_corrected_f = open('train_corrected.csv', 'w', encoding='utf-8')\ncsv_writer_train_corrected = csv.writer(train_corrected_f)\n\n\nwith open('../official_data/train.csv', 'r') as f:\n reader = csv.reader(f)\n\n for row in tqdm(reader):\n doc_index = row[0]\n question = row[1]\n ans = row[2]\n # print(doc_index, question, ans)\n\n if int(doc_index) == 6886:\n csv_writer_train_corrected.writerow(\n [doc_index, '一本书一页有21行,每行28个字。估计一下,这一页大约有多少个字?', 588])\n elif int(doc_index) == 8662:\n csv_writer_train_corrected.writerow(\n [doc_index, '两袋白砂糖,甲袋的重量是乙袋的1.4倍,如果乙袋增加8千克,两袋糖就一样重,原来每袋糖共多少千克', 48])\n elif int(doc_index) == 10794:\n csv_writer_train_corrected.writerow(\n [doc_index, '小华带着自己的爱犬���姥姥家,已知小华步行的速度是每分钟80米,犬的速度每分钟300米。她和犬同时从家里出发,犬跑到姥姥家后马上调头找小华,和小华相遇后又马上调头跑向姥姥家,就这样犬来回的跑。小华到姥姥家共用时15分钟,由此可知小华家离姥姥家多少米,犬跑了多少米?', 4500])\n elif int(doc_index) == 10838:\n csv_writer_train_corrected.writerow(\n [doc_index, '甲乙两车同时从相距506千米的两地相向开出,甲车每小时行52千米,乙车每小时行40千米,那么几小时后两车相距158千米?', '87/23'])\n elif int(doc_index) == 7175:\n csv_writer_train_corrected.writerow(\n [doc_index, '一把椅子60元,250元最多能买几把椅子?', 4])\n elif doc_index in corrected_dict:\n csv_writer_train_corrected.writerow(\n [doc_index, corrected_dict[doc_index]['question'], corrected_dict[doc_index]['ans']])\n # print(doc_index, corrected_dict[doc_index]\n # ['question'], corrected_dict[doc_index]['ans'])\n else:\n csv_writer_train_corrected.writerow(\n [doc_index, question, ans])\n\nwith open('train_corrected.csv', 'r') as f:\n reader = csv.reader(f)\n\n for row in tqdm(reader):\n doc_index = row[0]\n question = row[1]\n ans = row[2]\n if ';' in f'{ans}':\n print(doc_index, question, ans)\n","sub_path":"Graph2Tree_submit/competition/data_process_questions_corrected_train_official.py","file_name":"data_process_questions_corrected_train_official.py","file_ext":"py","file_size_in_byte":3394,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"282412930","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Sun Nov 24 14:28:09 2019\r\n\r\n@author: Ahlam Hani\r\n\r\n\"\"\"\r\n\r\n#ex1:\r\no=lambda x=1,y=2,z=3:x+y+z\r\nprint(o())\r\nprint(o(10))\r\nprint(o(10,20))\r\n\r\n#########################\r\n#ex2:\r\nlist3=[1,2,3]\r\n\r\ndef multi(list3):\r\n mul=1\r\n for x in list3:\r\n mul=mul*x\r\n print (mul)\r\nmulti(list3)\r\n#########################\r\n#ex3:\r\nmultibly = lambda a,b : a *b \r\nprint (multibly(2,3 ))\r\n########################\r\n\r\n#ex4:\r\n\r\nList1=[1,-1,2,-2]\r\nnegative_numbers= list (filter(lambda x: x < 0, List1))\r\nprint(negative_numbers)\r\n###############################\r\n\r\n#ex5:\r\nx=lambda a,b,c : a+b+c\r\nprint(x(5,6,2))\r\n#ans: 13\r\n\r\nx=('Joey','Monica','Ross')\r\ny=('Chandler','Pheobe')\r\nz=('David','Rachel','Courtney')\r\nresult=list(zip(x,y,z))\r\nprint(result)\r\n#ans:[('Joey', 'Chandler', 'David'), ('Monica', 'Pheobe', 'Rachel')]\r\n\r\n\r\ncoin=('Bitcoin','Ether','Ripple','Litecoin')\r\ncode=('BTC','ETH','XRP','LTC')\r\nd=dict(zip(coin,code))\r\nprint(d)\r\n#ans:{'Bitcoin': 'BTC', 'Ether': 'ETH', 'Ripple': 'XRP', 'Litecoin': 'LTC'}\r\n\r\n############################\r\ndef fun(variable):\r\n letters = ['a','e','i','o','u']\r\n if (variable in letters):\r\n return True\r\n else:\r\n return False\r\nsequence = ['g','j','e','j','k','o','p','r']\r\nfiltered = list(filter(fun,sequence))\r\nprint(filtered)\r\n#ans:['e', 'o']\r\n1\r\nx=list(map(int,input(\"Enter a multiple value:\").split()))\r\nprint(\"List of students: \",x)\r\n#ans:List of students: [1, 20, 10]\r\n\r\n#########################################\r\ndef newfunc(a):\r\n return a*a\r\nx = list(map(newfunc,(1,2,3,4)))\r\nprint(x)\r\n#ans:[1, 4, 9, 16]\r\n\r\n#########################################\r\ndef func(a,b):\r\n return a+b\r\na=list(map(func,[2,4,5],[1,2,3,2,4]))\r\nprint(a)\r\n#ans:[3, 6, 8]\r\n\r\n#########################################\r\nc=map(lambda x: x+x,filter(lambda x: (x>=3),(1,2,3,4)))\r\nprint(list(c))\r\n#ans:[6, 8]\r\n\r\n#########################################\r\nc= filter(lambda x: (x>=3),map(lambda x: x+x,(1,2,3,4)))\r\nprint(list(c))\r\n#ans:[4, 6, 8]\r\n\r\n#########################################\r\nimport functools\r\nlis = [ 1 , 3, 5, 6, 2,15 ]\r\nprint (\"The minimum element of the list is : \",end=\"\")\r\nprint (functools.reduce(lambda a,b : a if a < b else b,lis))\r\n#ans:The minimum element of the list is : 1\r\n\r\n#########################################\r\nnumbers=[1,2,3]\r\nletters=['a','b','c']\r\nresults = list(zip(numbers,letters))\r\nprint(results)\r\n#ans:[(1, 'a'), (2, 'b'), (3, 'c')]\r\n","sub_path":"lesson 4 exercise.py","file_name":"lesson 4 exercise.py","file_ext":"py","file_size_in_byte":2446,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"522886241","text":"#10진수 정숫값을 입력받아 2~36 진수로 변환하여 출력\n\ndef card_conv(x: int, r: int) -> str:\n \"\"\"정수값 x를 r진수로 변환한 뒤 그 수를 나타내는 문자열을 반환\"\"\"\n\n d= ''\n dchar = '0123456789ABCDEFGHIJKLMNOPQRSTUWXYZ'\n\n while x>0 :\n d += dchar[x % r] #해당하는 문자를 꺼내 ���합\n x //= r\n\n return d[::-1] #역순으로 반환\n \nif __name__ == '__main__':\n print('10진수를 n진수로 변환')\n \n while True :\n while True :\n no = int(input('변환할 값으로 음이 아닌 정수 입력 : '))\n if no > 0 :\n break\n\n while True :\n cd = int(input('어떤 진수로 변환할까요? : '))\n if 2 <= cd <= 36 :\n break\n print(f'{cd}진수로는 {card_conv(no,cd)}입니다')\n\n retry = input('한번 더 변환할까요? (Y - 예 / N - 아니요) : ')\n if retry in {'N', 'n'} :\n break","sub_path":"kkxxh/basic/b92.py","file_name":"b92.py","file_ext":"py","file_size_in_byte":988,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"84370830","text":"#!/usr/bin/env python3\n\nimport csv\nimport math\nimport random\nimport argparse\nimport copy\nfrom sklearn import tree as sktree\nfrom sklearn import preprocessing\n\n\n\nclass Tree(object):\n def __init__(self, label):\n self.branches = {}\n\n\nclass DecisionTreeClassifier(object):\n def __init__(self):\n self.tree = {}\n self.targets = None\n\n def predict(self, x):\n curr_branch = self.tree\n while 'target' not in curr_branch:\n if curr_branch['index'] >= len(x):\n curr_branch = random.choice(curr_branch['branches'])\n continue\n\n val = x[curr_branch['index']]\n del x[curr_branch['index']]\n\n next_branch = None\n for branch in curr_branch['branches']:\n if branch['label'] == val:\n next_branch = branch\n break\n\n if next_branch is None:\n random.choice(curr_branch['branches'])\n else:\n curr_branch = next_branch\n\n return curr_branch['target']\n\n def next_feature_for_branch(self, dataset, targets):\n entropies = []\n for i in range(len(dataset[0])):\n e = self.entropy(i, dataset, targets)\n entropies.append((e, i))\n return min(entropies, key=lambda tup: tup[0])[1]\n\n def fit(self, dataset, targets, curr_branch=None):\n if curr_branch is None:\n curr_branch = self.tree\n\n if self.targets is None:\n self.targets = targets\n\n if len(self.unique_targets(targets)) == 1:\n curr_branch['target'] = targets[0]\n elif len(dataset[0]) > 0:\n feature_i = self.next_feature_for_branch(dataset, targets)\n new_branches = self.new_branches(feature_i, dataset, targets)\n\n curr_branch['branches'] = new_branches\n curr_branch['index'] = feature_i\n for branch in curr_branch['branches']:\n self.fit(branch['dataset'], branch['targets'], branch)\n else:\n target_freq = {}\n for target in targets:\n if target not in target_freq:\n target_freq[target] = 0\n target_freq[target] += 1\n\n print(target_freq)\n sorted_targets = sorted(target_freq, key=target_freq.get, reverse=True)\n print(sorted_targets)\n curr_branch['target'] = sorted_targets[0]\n\n def new_branches(self, feature_i, dataset, targets):\n datasets = []\n targetsets = []\n\n feature_values = []\n for i, data in enumerate(dataset):\n if data[feature_i] not in feature_values:\n feature_values.append(data[feature_i])\n datasets.append([])\n targetsets.append([])\n\n dataset_i = feature_values.index(data[feature_i])\n datasets[dataset_i].append(data)\n targetsets[dataset_i].append(targets[i])\n\n del datasets[dataset_i][-1][feature_i]\n\n branches = []\n for i, feature_value in enumerate(feature_values):\n branch = {}\n branch['label'] = feature_value\n branch['dataset'] = datasets[i]\n branch['targets'] = targetsets[i]\n\n branches.append(branch)\n return branches\n\n def add_branch(feature_i, dataset, targets):\n trimmed_dataset = []\n trimmed_targets = []\n\n return trimmed_dataset, trimmed_targets\n\n def entropy(self, feature_index, dataset, targets):\n feature_values = []\n branches = {}\n for i, data in enumerate(dataset):\n if data[feature_index] not in feature_values:\n feature_values.append(data[feature_index])\n j = feature_values.index(data[feature_index])\n if j not in branches:\n branches[j] = []\n branches[j].append(targets[i])\n\n entropy_sum = 0\n for i, branch in enumerate(branches):\n for target in self.unique_targets(targets):\n n = len([x for _, x in enumerate(branches[i]) if x == target])\n if n > 0:\n ratio = float(n) / float(len(branches[i]))\n entropy_sum += -ratio * math.log(ratio, 2)\n\n return entropy_sum / len(branches)\n\n def unique_targets(self, targets):\n\n u_targets = []\n for target in targets:\n if target not in u_targets:\n u_targets.append(target)\n\n return u_targets\n\n def dump_tree(self, tree=None, depth=0):\n if tree is None:\n tree = self.tree\n\n if 'branches' not in tree:\n print(\" \" * depth + tree['target'])\n return\n\n for branch in tree['branches']:\n if 'target' not in branch:\n print(\" \"*depth + str(branch['label']))\n self.dump_tree(branch, depth+1)\n else:\n print(\" \"*depth + str(branch['label']), \"->\",\n str(branch['target']))\n\n\ndef main():\n parser = argparse.ArgumentParser(description=\"Chris's Decision Tree\")\n parser.add_argument('--csv', type=str, help='dataset csv', required=True)\n args = parser.parse_args()\n\n f = open(args.csv, \"r\")\n csv_file = csv.reader(f)\n\n y = []\n X = []\n for row in csv_file:\n if len(row) != 17:\n print(row)\n y.append(row[-1])\n X.append(row[:-1])\n\n full_data = list(zip(X, y))\n random.shuffle(full_data)\n X, y = zip(*full_data)\n\n training_size = int(len(X) * .667)\n training_data = list(X[:training_size])\n training_targets = y[:training_size]\n testing_data = list(X[training_size:])\n testing_targets = y[training_size:]\n\n tree = DecisionTreeClassifier()\n tree.fit(copy.deepcopy(training_data), training_targets)\n\n tree.dump_tree()\n\n correct_guesses = 0\n for i, x in enumerate(testing_data):\n if tree.predict(copy.deepcopy(x)) == testing_targets[i]:\n correct_guesses += 1\n print(\"My Classifier: %0.2f%%\" % (100 * correct_guesses / len(testing_data)))\n\n le = preprocessing.LabelEncoder()\n for i, _ in enumerate(training_data):\n d = le.fit_transform(training_data[i])\n training_data[i] = d\n for i, _ in enumerate(testing_data):\n d = le.fit_transform(testing_data[i])\n testing_data[i] = d\n\n stree = sktree.DecisionTreeClassifier()\n stree.fit(training_data, training_targets)\n\n correct_guesses = 0\n predictions = stree.predict(testing_data)\n for i, p in enumerate(predictions):\n if p == training_targets[i]:\n correct_guesses += 1\n print(\"sklearn Classifier: %0.2f%%\" % (100 * correct_guesses / len(testing_data)))\n\n\nif '__main__' == __name__:\n main()\n","sub_path":"dtree.py","file_name":"dtree.py","file_ext":"py","file_size_in_byte":6755,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"420582028","text":"from automation.core.logger import handler as logger\nfrom automation.core.db.crud import Crud\nfrom automation.core.db import db as dbo\nfrom automation.core.src.environment import Environment\nfrom automation.integration.src.test_case_helper import TestCaseHelper\nfrom automation.integration.pve.model.task import Task\nfrom automation.integration.db import query_handler as qhandler\nfrom automation.integration.pve.db import query_handler as pve_qhandler\n\nclass TaskController:\n\n def __init__(self, id, uuid):\n self.task = Task()\n self.helper = TestCaseHelper()\n self.env = Environment()\n self.sql_server = self.env.pvedb.db_server\n self.sql_user = self.env.pvedb.db_user\n self.sql_pwd = self.env.pvedb.db_pwd\n self.sql_db = self.env.pvedb.db_name\n self.crud = Crud(dbo.PVEDB(self.sql_server, self.sql_user, self.sql_pwd, self.sql_db))\n self.id = id\n self.uuid = uuid\n self.list_create_task_values, self.dict_node_values = [], []\n\n def create(self, father_key, name='Task', encoding='utf-8'):\n logger.logs('\\n Creating PVE task \\n', 'info')\n description = self.helper.get_name(name)\n self.list_create_task_values = {'Description': description, 'FatherKey': father_key}\n self.task.create(self.list_create_task_values, encoding)\n task_key = self.task.verify_created_key\n status = self.verify_create(encoding)\n return description, task_key, status\n\n def update_old(self, task_key, father_key, milestone ='false', encoding='utf-8', **kwargs):\n logger.logs('\\n Updating PVE task \\n', 'info')\n update_desc = self.helper.get_name('Updated_Task')\n if milestone == 'true' and 'schedule_start' in kwargs:\n self.list_dict_node_values = [{r'ns1:Description': update_desc,\n r'ns1:Key': task_key,\n r'ns1:FatherKey': father_key,\n r'ns1:IsMilestone': milestone,\n r'ns1:ScheduleStartDate': kwargs['schedule_start'],\n r'ns1:EnterProgress': kwargs['enter_progress'], r'ns1:Duration': 0}]\n operation = 'update'\n\n else:\n if 'Actual_Finish' in kwargs and 'Actual_Start' in kwargs:\n self.list_dict_node_values = [{r'ns1:Description': update_desc,\n r'ns1:Key': task_key,\n r'ns1:FatherKey': father_key,\n r'ns1:IsMilestone': milestone,\n r'ns1:EnterProgress': kwargs['enter_progress'],\n r'ns1:ActualFinishDate': kwargs['Actual_Finish'],\n r'ns1:ActualStartDate' : kwargs['Actual_Start']}]\n operation = 'update_actual'\n\n elif 'Actual_Start' in kwargs and 'Schedule_start' in kwargs:\n self.list_dict_node_values = [{r'ns1:Description': update_desc,\n r'ns1:Key': task_key,\n r'ns1:FatherKey': father_key,\n r'ns1:EnterProgress': kwargs['enter_progress'],\n r'ns1:ActualStartDate' : kwargs['Actual_Start'],\n r'ns1:ScheduleStartDate': kwargs['Schedule_start'],\n r'ns1:ScheduleFinishDate' : kwargs['Schedule_Finish']}]\n\n operation = 'update_start_date'\n\n else:\n self.list_dict_node_values = [{r'ns1:Description': update_desc,\n r'ns1:Key': task_key,\n r'ns1:FatherKey': father_key,\n r'ns1:EnterProgress': kwargs['enter_progress'],\n r'ns1:ScheduleFinishDate' : kwargs['Schedule_Finish'],\n r'ns1:ScheduleStartDate': kwargs['Schedule_start']}]\n operation = 'update_schedule'\n self.task.update(self.list_dict_node_values, operation, encoding)\n status = self.verify_update(encoding)\n return update_desc, status\n\n def update(self, task_key, father_key, milestone='false', encoding='utf-8', **kwargs):\n logger.logs('\\n Updating PVE task \\n', 'info')\n update_desc = self.helper.get_name('Updated_Task')\n self.dict_node_values = {'Description': update_desc, 'Key': task_key, 'FatherKey': father_key,\n 'IsMilestone': milestone}\n self.dict_node_values.update(**kwargs)\n self.task.update(self.dict_node_values, 'update', encoding)\n status = self.verify_update(encoding)\n return update_desc, status\n\n def read(self, planning_code):\n return pve_qhandler.select_schedule_actual_dates(planning_code, self.crud)\n\n def verify_create(self, encoding='utf-8'):\n logger.logs('\\n Verifying the created task \\n', 'info')\n result, remarks = self.task.verify_create(encoding)\n\n step_desc = 'Creation and Verification of the Task'\n step_input = 'Task: %s' % self.list_create_task_values\n\n last_run = self.helper.get_time()\n create_status = False\n step_result = 0\n\n if result:\n step_result = 1\n create_status = True\n qhandler.insert_into_step_details(self.id, self.uuid, self.env.pve.name, self.env.pve.db_name,\n self.env.external_env.name, self.env.integ.name, step_desc, step_input, step_result,\n remarks, last_run)\n logger.logs('Task create verification: %s' % create_status, 'info')\n return create_status\n\n def verify_update(self, encoding='utf-8'):\n logger.logs('\\n Verifying the updated task \\n', 'info')\n result, remarks = self.task.verify_update(encoding)\n\n step_desc = 'Update and Verification of the Task'\n step_input = 'Task: %s' % self.dict_node_values\n last_run = self.helper.get_time()\n update_status = False\n step_result = 0\n\n if result:\n step_result = 1\n update_status = True\n qhandler.insert_into_step_details(self.id, self.uuid, self.env.pve.name, self.env.pve.db_name,\n self.env.external_env.name, self.env.integ.name, step_desc, step_input, step_result,\n remarks, last_run)\n logger.logs('Task update verification: %s' % update_status, 'info')\n return update_status\n","sub_path":"JinjaTask/controller/task.py","file_name":"task.py","file_ext":"py","file_size_in_byte":6899,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"154964510","text":"#!/usr/bin/env python3\n\nimport os\nimport csv\nimport numpy\n\n\"\"\"\nRecebe o path de um arquivo .csv e o numero de instancias do arquivo\na serem lidas.\nRetorna:\n\tsignals - lista com os valores numericos de cada instancia (sinais dos sensores)\n\tlabels - lista com os valores nominais de cada instancia. Index 0: source, index 1: label\n\"\"\"\ndef read_csv(filename, num_instances):\n\tsignals = numpy.zeros((num_instances,19), dtype = 'float')\n\tlabels = numpy.zeros((num_instances,2), dtype = (str, 11))\n\twith open(filename, 'r') as input_file:\n\t\t\tnext(input_file)\n\t\t\treader = csv.reader(input_file)\n\t\t\tfor i, row in enumerate(reader):\n\t\t\t\tdata = [float(datum) for datum in row[2:]]\n\t\t\t\tsignals[i] = data\n\t\t\t\tlabels[i] = row[0:2]\n\treturn signals, labels\n\n\"\"\"\nRecebe a lista de valores nominais (source e label) do train.\nRetorna:\n\tnum_instances_location - dicionario com o numero de exemplares de cada label\n\"\"\"\ndef get_locations(labels_train):\n\tnum_instances_location = {}\n\tfor label in labels_train:\n\t\tlocation = label[1]\n\t\tif not location in num_instances_location:\n\t\t\tnum_instances_location[location] = 1\n\t\telse:\n\t\t\tnum_instances_location[location] += 1\n\treturn num_instances_location\n\n\n\"\"\"\nRecebe duas listas de valores numericos e calcula a distancia euclidiana entre as duas.\nRetorna:\n\tdist - float representando a distancia euclidiana\n\"\"\"\ndef euclidean_distance(list1, list2):\n\tsoma = 0\n\tfor j in range(0, len(list1)):\n\t\tsoma += (list1[j] - list2[j]) ** 2\n\tdist = soma ** 0.5\n\treturn dist\n\n\"\"\"\nRecebe os valores nominais e numericos do arquivo csv e o numero de instancias por label.\nRetorna:\n\tcentroids - dicionario com os valores medios de cada atributo numerico para cada label\n\"\"\"\ndef get_centroids(signals_train, labels_train, num_instances_location):\n\tcentroids = {}\n\tfor key in num_instances_location:\n\t\tcentroids[key] = numpy.zeros(19)\n\tfor i, line in enumerate(signals_train):\n\t\tlocation = labels_train[i][1]\n\t\tn = num_instances_location[location]\n\t\tfor j, signal in enumerate(line):\n\t\t\tcentroids[location][j] += signal/n\n\treturn centroids\n\n\"\"\"\nRecebe os valores nominais e numericos do arquivo csv de teste, os centroides de cada label e o\nnumero de instancias do arquivo csv de teste.\nRetorna:\n\tlabels_predicted - dicionario contendo o label previsto para cada instancia do arquivo de\n\t\t\t\t\tteste. Calculado com base na distancia euclidiana minima aos centroides.\n\"\"\"\ndef predict_labels(signals_test, labels_test, centroids, num_instances):\n\tlabels_predicted = numpy.zeros((num_instances,2), dtype = (str, 11))\n\tfor i, line in enumerate(signals_test):\n\t\tmin_distance = float(\"inf\")\n\t\tlabels_predicted[i][0] = labels_test[i][0]\n\t\tfor key in centroids:\n\t\t\tdistance = euclidean_distance(line, centroids[key])\n\t\t\tif distance < min_distance:\n\t\t\t\tmin_distance = distance\n\t\t\t\tlabels_predicted[i][1] = key\n\treturn labels_predicted\n\nclass Classificador(object):\n\n\tdef __init__(self, train, test):\n\t\tself.train_file = train\n\t\tself.test_file = test\n\t\tself.centroids = {}\n\t\tself.num_instances_location = {}\n\t\tself.signals_train = {}\n\t\tself.labels_train = {}\n\t\tself.signals_test = {}\n\t\tself.labels_test = {}\n\t\tself.numinstances_train = sum(1 for line in open(train)) - 1 \n\t\tself.numinstances_test = sum(1 for line in open(test)) - 1\n\n\t\"\"\"\n\tLe o arquivo csv de treino e calcula os centroides.\n\t\"\"\"\n\tdef train(self):\n\t\tself.signals_train, self.labels_train = read_csv(self.train_file, self.numinstances_train)\n\t\tself.num_instances_location = get_locations(self.labels_train)\n\t\tself.centroids = get_centroids(self.signals_train, self.labels_train, self.num_instances_location)\n\n\t\"\"\"\n\tLe o arquivo csv de teste e faz a previsao dos labels (classificação).\n\t\"\"\"\n\tdef test(self):\n\t\tself.signals_test, self.labels_test = read_csv(self.test_file, self.numinstances_test)\n\t\tself.labels_predicted = predict_labels(self.signals_test, self.labels_test, self.centroids, self.numinstances_test)\n\n\t\"\"\"\n\tCompara os labels previstos aos reais e fornece a precisao.\n\tRetorna:\n\t\tright - numero de labels previstos corretamente\n\t\ttotal - numero de instancias do arquivo de teste\n\t\"\"\"\n\tdef get_accuracy(self):\n\t\tright = 0\n\t\ttotal = 0\n\t\tfor i, label in enumerate(self.labels_test):\n\t\t\tif label[1] == self.labels_predicted[i][1]:\n\t\t\t\tright += 1\n\t\t\ttotal += 1\n\t\treturn right, total","sub_path":"classificador.py","file_name":"classificador.py","file_ext":"py","file_size_in_byte":4252,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"145115407","text":"# -*- coding:utf-8 -*-\n\nimport sys\nfrom flask import Flask\nfrom multiprocessing import Queue\nfrom multiprocessing import Manager, Value\n\nfrom multiprocessing import Process\n\nimport sophon.sail as sail\n\nfrom pack import Pack\nfrom utils import *\nimport time\nimport signal\nimport threading\n\nimport cv2\nimport os\nimport multiprocessing as mp\n\nfrom websocket.utils import logger\nfrom websocket.pull_frame import PullFrameProcess\nfrom websocket.redis_websocket_srv import WebsocketProcess\n\nlog = logger.get_logger(__file__)\n\n\n\nglobal num\nnum = Value('d', 0.0)\n\nglobal exit\nexit = Value('d', 0.0)\n\nglobal global_start_t0\n\n# 任务列表\nservice_list = []\n\ndef service_start():\n for service in service_list:\n service.start()\n\ndef service_join():\n for service in service_list:\n service.join()\n\n\ndef exit_handler(signum, frame):\n os._exit(0)\n\ndef term_sig_handler(signum, frame):\n print(\"catched signal: \", signum)\n global exit\n exit.value = 1.0\n\ndef init_pack(detect_engine, num):\n pack_pocess_list = []\n if len(VIDEO_LIST) == 0:\n print('[init_pack] no video error return')\n return\n pack_num = int((len(VIDEO_LIST)-1)/4) + 1\n print('[init_pack] pack_num {}'.format(pack_num))\n upload_flage = True\n for i in range(pack_num):\n print('[init_pack] start {}'.format(i))\n start = i*4\n end = start + 4\n if end > len(VIDEO_LIST):\n handle_url = VIDEO_LIST[start:]\n else:\n handle_url = VIDEO_LIST[start: end]\n print('[init_pack] handle url {}'.format(handle_url))\n\n pack = Pack(handle_url, detect_engine, i, num, upload_flage)\n upload_flage = False\n pack_process = Process(target=pack.run, args=())\n pack_pocess_list.append(pack_process)\n return pack_pocess_list\n\nif __name__ == '__main__':\n\n \"\"\"\n 1、多进程获取视频流 写入queue\n 2、多进程消费queue调用retinaface检测人脸、sort人脸跟踪、写入queue\n 3、单进程从queue消费人脸图片进行人脸识别。\n 4、将人脸识别结果上传到云端。\n \"\"\"\n manager = Manager()\n\n detect_engine = sail.Engine(DETECTION_MODEL_PATH, DETECTION_TPU_ID, sail.SYSO) #检测引擎\n\n signal.signal(signal.SIGTERM, term_sig_handler)\n\n process_list = init_pack(detect_engine, num)\n\n\n web_srv = WebsocketProcess()\n web_srv.setport(WEBSOCKET_PORT)\n web_srv.daemon = True\n service_list.append(web_srv)\n\n # pull_srv = PullFrameProcess()\n # pull_srv.daemon = True\n # service_list.append(pull_srv)\n\n # 任务开启\n service_start()\n \n\n for i in range(len(process_list)):\n process_list[i].start()\n\n #global t\n t = time.time()\n while True:\n time.sleep(10)\n if num.value > 0 :\n print('detection per fps {} ms'.format((time.time() - t) * 1000/num.value))\n t = time.time()\n num.value = 0.0\n\n # 预留flask,后期增加视频流配置接口\n # app.run(host='0.0.0.0', port=SERVER_PORT, threaded=True)\n service_join()\n\n sys.exit(0)\n","sub_path":"samples/python/multiprocess_detection_yolox/server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":3058,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"649301959","text":"#encoding: utf-8\n\nnum = input('please input a number between one and four:')\n\nnum = int (num)\n\nif num == 1:\n\tprint('我是一号选手')\nelif num == 2:\n\tprint('我是二号选手')\nelif num == 3:\n\tprint('我是三号选手')\nelse:\n\tprint('我是四号选手')\n\n\n","sub_path":"06_if/if_elif_test.py","file_name":"if_elif_test.py","file_ext":"py","file_size_in_byte":262,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"456440728","text":"from cryptography.fernet import Fernet\nfrom cryptography.hazmat.primitives import hashes\nfrom cryptography.hazmat.backends import default_backend\nimport base64\nimport sys, os\nfrom tkinter import *\nfrom tkinter import messagebox\nfrom tkinter.filedialog import askopenfilename\n\nclass fileprotection():\n def __init__(self): # initialization\n self.root = Tk()\n self.root.withdraw()\n\n def init_target(self):\n self.target = self.tf1.get().replace('\\\\','/')\n self.path = '/'.join(self.target.split('/')[0:-1])\n self.input_filename = self.target.split('/')[-1]\n self.output_filename = '.'.join((self.target.split('/')[-1]).split('.')[0:-1])+'_output.'+(self.target.split('/')[-1]).split('.')[-1]\n self.key = self.generate_key(self.tf2.get().encode())\n\n def generate_key(self, password):\n digest = hashes.Hash(hashes.SHA256(), backend=default_backend())\n digest.update(password)\n return base64.urlsafe_b64encode(digest.finalize())\n\n def protect(self):\n try:\n self.init_target()\n fernet = Fernet(self.key)\n temp = fernet.encrypt(self.read_from_file())\n self.write_to_file(temp)\n messagebox.showinfo('Notice','Done')\n except:\n messagebox.showerror('Notice','Failed')\n\n def unprotect(self):\n try:\n self.init_target()\n fernet = Fernet(self.key)\n temp = fernet.decrypt(self.read_from_file())\n self.write_to_file(temp)\n messagebox.showinfo('Notice','Done')\n except:\n messagebox.showerror('Notice','Failed')\n\n def read_from_file(self):\n with open(self.path+'/'+self.input_filename, 'r+b') as file:\n return file.read()\n\n def write_to_file(self, filedata):\n with open(self.path+'/'+self.output_filename, 'w+b') as file:\n file.write(filedata)\n\n def open_file(self):\n self.target = askopenfilename(initialdir=os.getcwd(),title = \"Choose a file.\")\n self.tf1.delete(0,END)\n self.tf1.insert(0,self.target)\n\n def show_main_window(self):\n self.window = Toplevel()\n self.window.geometry('400x150')\n self.window.title('project - file-protection')\n self.window.configure(background='#ababab')\n self.lbl1 = Label(self.window, text='File', background='#ababab')\n self.lbl1.place(height=20, width=80, x=40, y=20)\n self.tf1 = Entry(self.window)\n self.tf1.place(height=20, width=180, x=110,y=20)\n self.btn1 = Button(self.window, text = 'select', command=lambda: self.open_file())\n self.btn1.place(height=20, width=50, x=290, y=20)\n self.lbl2 = Label(self.window, text='Password', background='#ababab')\n self.lbl2.place(height=20, width=80, x=40, y=50)\n self.tf2 = Entry(self.window)\n self.tf2.place(height=20, width=230, x=110,y=50)\n self.btn2 = Button(self.window, text = 'Protect', command=lambda: self.protect())\n self.btn2.place(height=30, width=80, x=50, y=100)\n self.btn3 = Button(self.window, text = 'Unrotect', command=lambda: self.unprotect())\n self.btn3.place(height=30, width=80, x=260, y=100)\n self.window.mainloop()\n\nif '__main__' == __name__:\n fp = fileprotection()\n fp.show_main_window()\n","sub_path":"source/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":3323,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"393226401","text":"\n# input 1 = \"programming is fun\"\n# input 2 = \"m\"\n# output = [6,7]\n\nsentance = \"we are all trying to lean programming and it is super fun\"\nletter = \" \"\noutput = []\n\nfor current_location, current_letter in enumerate(sentance):\n if current_letter == letter:\n output.append(current_location)\n\nprint(output)\n","sub_path":"week_1/day4_exercise.py","file_name":"day4_exercise.py","file_ext":"py","file_size_in_byte":314,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"467232735","text":"import re\n\nfile = open('AOTC2015_5.txt', 'r')\n\ntext = []\n\nfor i in file:\n text.append(i.rstrip())\n\nfile.close()\n\n\npattern4 = re.compile(r\"(..)(.*)\\1\")\npattern5 = re.compile(r\"(.)(.)\\1\")\nnice = {}\nniceCount = 0\nfor x in text:\n\n print(\"\\n\")\n print(x)\n if re.search(pattern4, x) :\n nice[x] = \"Nice\"\n print(\" Matches Pattern 4\")\n\n else: \n nice[x] = \"Naughty\"\n print(\"DOES NOT MATCH PATTERN 4\")\n continue\n \n \n if re.search(pattern5, x) :\n nice[x] = \"Nice\"\n print(\" Matches Pattern 5\")\n\n else: \n nice[x] = \"Naughty\"\n print(\"DOES NOT MATCH PATTERN 5\") \n continue\n\nfor k,v in nice.items():\n #print( str(k)+\": \"+str(v))\n if v == \"Nice\":\n niceCount += 1\n\nprint(\"\\n\" +\"PART 2 - Total number of Nice strings: \"+str(niceCount))\n","sub_path":"2015/AOTC2015_5_2.py","file_name":"AOTC2015_5_2.py","file_ext":"py","file_size_in_byte":828,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"320754171","text":"import csv\nimport unittest\nfrom time import sleep\nfrom automate_driver.automate_driver import AutomateDriver\nfrom model.assert_text import AssertText\nfrom model.connect_sql import ConnectSql\nfrom pages.base.base_page import BasePage\nfrom pages.base.base_paging_function import BasePagingFunction\nfrom pages.base.lon_in_base import LogInBase\nfrom pages.command_management.command_management_page import CommandManagementPage\nfrom pages.command_management.command_management_page_read_csv import CommandManagementPageReadCsv\n\n\nclass TestCase51IssuedCommandManagementSearch(unittest.TestCase):\n \"\"\" 下发指令管理页面的搜索 \"\"\"\n # author:邓肖斌\n\n driver = None\n base_url = None\n base_page = None\n log_in_page = None\n command_management_page = None\n base_paging_function = None\n\n def setUp(self):\n # 前置条件\n # 实例化对象\n self.driver = AutomateDriver(choose='firefox')\n self.base_url = self.driver.base_url\n self.base_page = BasePage(self.driver, self.base_url)\n self.command_management_page = CommandManagementPage(self.driver, self.base_url)\n self.base_paging_function = BasePagingFunction(self.driver, self.base_url)\n self.command_management_page_read_csv = CommandManagementPageReadCsv()\n self.connect_sql = ConnectSql()\n self.log_in_base = LogInBase(self.driver, self.base_url)\n self.assert_text = AssertText()\n\n # 打开页面,填写用户名、密码、点击登录\n self.base_page.open_page()\n self.driver.set_window_max()\n self.driver.implicitly_wait(5)\n self.driver.clear_cookies()\n self.log_in_base.log_in_jimitest()\n self.log_in_base.click_account_center_button()\n self.current_account = self.log_in_base.get_log_in_account()\n\n # 登录之后点击控制台,然后点击指令管理\n self.command_management_page.click_control_after_click_command_management()\n sleep(3)\n\n def tearDown(self):\n self.driver.quit_browser()\n\n def test_case_issued_command_management_search(self):\n # 断言url\n expect_url_after_click_command_management = self.base_url + '/custom/toTemplate'\n self.assertEqual(expect_url_after_click_command_management,\n self.command_management_page.actual_url_click_command_management())\n # 断言左侧列表的title文本\n expect_title_text_after_click_command_management = self.assert_text.command_manager_page_command_type()\n self.assertEqual(expect_title_text_after_click_command_management,\n self.command_management_page.actual_title_text_after_click_command_management())\n\n # 点击下发指令管理\n self.command_management_page.click_lift_list('issued_command_management')\n # 断言\n expect_title_text = self.assert_text.command_manager_page_issued_command_manager()\n self.assertEqual(expect_title_text, self.command_management_page.actual_text_after_click_look_equipment())\n\n # 读csv\n csv_file = self.command_management_page_read_csv.read_csv('issued_command_management_search_data.csv')\n csv_data = csv.reader(csv_file)\n\n is_header = True\n for row in csv_data:\n if is_header:\n is_header = False\n continue\n search_data = {\n 'imei': row[0],\n 'batch': row[1],\n 'statue': row[2]\n }\n # 添加搜索添加搜索\n self.command_management_page.issued_command_management_search_data(search_data)\n\n # 连接数据库\n connect = self.connect_sql.connect_tuqiang_sql()\n # 建立游标\n cursor = connect.cursor()\n # 查询登录用户的ID 和 父ID\n get_current_user_id_sql = \\\n \"select o.userId,o.fullParentId from user_info o where o.account = '\" + self.current_account + \"';\"\n # 执行\n cursor.execute(get_current_user_id_sql)\n user = cursor.fetchall()\n print(user)\n for row1 in user:\n user_info = {\n 'id': row1[0],\n 'fullparent': row1[1]\n }\n\n # 判断搜索条件\n get_sql = self.command_management_page. \\\n search_sql_for_issued_command_management_search(user_info['id'], search_data)\n # 执行sql\n print(get_sql)\n cursor.execute(get_sql)\n\n current_total = cursor.fetchall()\n total_list = []\n for range1 in current_total:\n for range2 in range1:\n total_list.append(range2)\n total_num = len(total_list)\n web_total = self.command_management_page.search_total_number_issued_command_management()\n print(\"网页搜索数量:'%s'\" % web_total)\n print(\"数据库搜索结果:'%s'\" % total_num)\n self.assertEqual(total_num, web_total)\n\n cursor.close()\n connect.close()\n","sub_path":"testcases/command_management/test_case_51_issued_command_management_search.py","file_name":"test_case_51_issued_command_management_search.py","file_ext":"py","file_size_in_byte":5184,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"30969037","text":"#coding:utf-8\n\nfrom math import log\n\n'''\n海洋生物数据集合\n不浮出水面是否可以生存、是否有脚蹼、是否属于鱼类\n'''\ndataset = [\n\t[1,1,'yes'],\n\t[1,1,'yes'],\n\t[1,0,'no'],\n\t[0,1,'no'],\n\t[0,1,'no'],\n]\n\n#特征标签\nlabels = ['no surfacing','flippers']\n\n#计算给定数据集的香农熵\ndef calcShannonEnt(dataset):\n\tnumEntries = len(dataset)#计算数据集中实例总数\n\tlabelCounts = {}\n\n\tfor featVec in dataset:\n\t\tcurrentLabel = featVec[-1]\n\t\tif currentLabel not in labelCounts.keys():\n\t\t\t#如果当前类别暂时没有被统计则初始化为1\n\t\t\tlabelCounts[currentLabel] = 1\n\t\telse:\n\t\t\t#否则在以前的统计数据上递增1\n\t\t\tlabelCounts[currentLabel] += 1\t\n\n\tshannonEnt = 0.0#香农熵\n\n\tfor key in labelCounts:\n\t\tprob = float(labelCounts[key])/numEntries\n\t\tshannonEnt -= prob * log(prob,2)\n\n\treturn shannonEnt\n\n\n#选取特征axis为value的数据\ndef splitDataSet(dataset,axis,value):\n\tretDataset = []\n\tfor featVec in dataset:\n\t\t#如果当前元素复合\n\t\tif featVec[axis] == value:\n\t\t\treducedFeatVec = featVec[:axis]\n\t\t\treducedFeatVec.extend(featVec[axis+1:])\n\t\t\tretDataset.append(reducedFeatVec)\n\n\treturn retDataset\n\n#选取最好的信息划分特征\ndef chooseBestFeatureToSplit(dataset):\n\tnumFeatures = len(dataset[0])-1#根据第一项样本数据获取特征数\n\tbaseEntropy = calcShannonEnt(dataset)\n\tbestInfoGain = 0.0\n\tbestFeature = -1#最好的划分特征序号\n\n\tfor i in range(numFeatures):\n\t\tfeatList = [example[i] for example in dataset]#获取样本数据中的第i项特征\n\t\tuniqueVals = set(featList)\n\t\tnewEntropy = 0.0\n\n\t\tfor value in uniqueVals:\n\t\t\tsubDataSet = splitDataSet(dataset,i,value)\n\t\t\tprob = len(subDataSet)/float(len(dataset))\n\t\t\tnewEntropy += prob*calcShannonEnt(subDataSet)\n\n\t\tinfoGain = baseEntropy - newEntropy#信息增益\n\t\tif(infoGain > bestFeature):\n\t\t\tbestInfoGain = infoGain\n\t\t\tbestFeature = i\n\n\treturn bestFeature\t\t\t\n\n\n#测试计算香农熵\n#print(calcShannonEnt(dataset))\n\n#测试特征选取\n#print(splitDataSet(dataset,0,1))#选取序号为0的特征,值为1的数据项\n#print(splitDataSet(dataset,0,0))#选取序号为0的特征,值为0的数据项\n\nprint(chooseBestFeatureToSplit(dataset))","sub_path":"decision-tree/decision-tree-fish.py","file_name":"decision-tree-fish.py","file_ext":"py","file_size_in_byte":2187,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"28585989","text":"import sys\nfrom wsgiref.simple_server import make_server\n\nsys.path.append('..')\n\nimport handlers\nfrom pypedream import file_dispatcher, rewriter, rule\n\nif __name__ == '__main__':\n try:\n httpd = make_server(\n host='',\n port=8888,\n app=rewriter(\n rule(r'/hello/(?P.*)', r'/hello'),\n app=file_dispatcher(handlers_package=handlers)\n )\n )\n print('Serving on port 8888...')\n httpd.serve_forever()\n except KeyboardInterrupt:\n print('Goodbye.')\n","sub_path":"example/server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":558,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"71573199","text":"import time\nimport importlib\n\nimport pytest\n\nfrom misttests import config\nfrom misttests.integration.api.helpers import *\nfrom misttests.integration.api.mistrequests import MistRequests\n\nDELETE_KEYWORDS = ['delete', 'destroy', 'remove']\n\nresource_name = 'CloudsController'.replace('Controller', '').lower()\ntry:\n _setup_module = importlib.import_module(\n f'misttests.integration.api.main.v2.setup.{resource_name}')\nexcept ImportError:\n SETUP_MODULE_EXISTS = False\nelse:\n SETUP_MODULE_EXISTS = True\n\n\n@pytest.fixture(autouse=True)\ndef conditional_delay(request):\n yield\n method_name = request._pyfuncitem._obj.__name__\n if method_name == 'test_create_cluster':\n time.sleep(200)\n\n\nclass TestCloudsController:\n \"\"\"CloudsController integration test stubs\"\"\"\n\n def test_add_cloud(self, pretty_print, mist_core, owner_api_token):\n \"\"\"Test case for add_cloud\n\n Add cloud\n \"\"\"\n add_cloud_request = {\n \"name\" : \"example-cloud\",\n \"provider\" : \"google\",\n \"credentials\" : {\n \"projectId\" : \"projectId\",\n \"privateKey\" : \"privateKey\",\n \"email\" : \"email\"\n }\n}\n config.inject_vault_credentials(add_cloud_request)\n uri = mist_core.uri + '/api/v2/clouds' \n request = MistRequests(api_token=owner_api_token, uri=uri, json=add_cloud_request)\n request_method = getattr(request, 'POST'.lower())\n response = request_method()\n assert_response_ok(response)\n print('Success!!!')\n\n def test_edit_cloud(self, pretty_print, mist_core, owner_api_token):\n \"\"\"Test case for edit_cloud\n\n Edit cloud\n \"\"\"\n edit_cloud_request = {\n \"name\" : \"renamed-example-cloud\"\n}\n config.inject_vault_credentials(edit_cloud_request)\n uri = mist_core.uri + '/api/v2/clouds/{cloud}'.format(cloud='example-cloud') \n request = MistRequests(api_token=owner_api_token, uri=uri, json=edit_cloud_request)\n request_method = getattr(request, 'PUT'.lower())\n response = request_method()\n assert_response_ok(response)\n print('Success!!!')\n\n def test_get_cloud(self, pretty_print, mist_core, owner_api_token):\n \"\"\"Test case for get_cloud\n\n Get cloud\n \"\"\"\n query_string = [('sort', '-name'),\n ('only', 'id'),\n ('deref', 'auto')]\n uri = mist_core.uri + '/api/v2/clouds/{cloud}'.format(cloud='example-cloud') \n request = MistRequests(api_token=owner_api_token, uri=uri, params=query_string)\n request_method = getattr(request, 'GET'.lower())\n response = request_method()\n assert_response_ok(response)\n print('Success!!!')\n\n def test_list_clouds(self, pretty_print, mist_core, owner_api_token):\n \"\"\"Test case for list_clouds\n\n List clouds\n \"\"\"\n query_string = [('search', 'provider:amazon'),\n ('sort', '-name'),\n ('start', '50'),\n ('limit', '56'),\n ('only', 'id'),\n ('deref', 'auto')]\n uri = mist_core.uri + '/api/v2/clouds' \n request = MistRequests(api_token=owner_api_token, uri=uri, params=query_string)\n request_method = getattr(request, 'GET'.lower())\n response = request_method()\n assert_response_ok(response)\n print('Success!!!')\n\n def test_remove_cloud(self, pretty_print, mist_core, owner_api_token):\n \"\"\"Test case for remove_cloud\n\n Remove cloud\n \"\"\"\n uri = mist_core.uri + '/api/v2/clouds/{cloud}'.format(cloud='example-cloud') \n request = MistRequests(api_token=owner_api_token, uri=uri)\n request_method = getattr(request, 'DELETE'.lower())\n response = request_method()\n assert_response_ok(response)\n print('Success!!!')\n\n\n# Mark delete-related test methods as last to be run\nfor key in vars(TestCloudsController):\n attr = getattr(TestCloudsController, key)\n if callable(attr) and any(k in key for k in DELETE_KEYWORDS):\n setattr(TestCloudsController, key, pytest.mark.order('last')(attr))\n\nif SETUP_MODULE_EXISTS:\n # Add setup and teardown methods to test class\n class_setup_done = False\n\n @pytest.fixture(scope='class')\n def setup(owner_api_token):\n global class_setup_done\n if class_setup_done:\n yield\n else:\n _setup_module.setup(owner_api_token)\n yield\n _setup_module.teardown(owner_api_token)\n class_setup_done = True\n TestCloudsController = pytest.mark.usefixtures('setup')(TestCloudsController)\n","sub_path":"mist_api_v2/test/test_clouds_controller.py","file_name":"test_clouds_controller.py","file_ext":"py","file_size_in_byte":4632,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"444621607","text":"import json\n\nstudent={\n \"name\":\"Hajara\",\n \"id\":36,\n 43:\"check\",\n \"address\":\"navalur\"\n}\n\nprint(student)\nstudent_asjson=json.dumps(student)\nprint(student_asjson)\nfor x,y in student.items():\n print(x,\"\\t\",y)\n\n","sub_path":"Basics/dictionary/dict_ex_prog.py","file_name":"dict_ex_prog.py","file_ext":"py","file_size_in_byte":221,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"354563551","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Mar 27 12:45:53 2019\n\n@author: batuhan\n\"\"\"\nimport numpy as np\nimport os\nimport cv2\nfrom PIL import Image\nimport keras\nfrom keras.layers import Conv2D, MaxPooling2D, Dense, Flatten, Dropout\nfrom keras.models import Sequential\nfrom keras.models import load_model\n# Getting Dataset ready and save it for later usage\ndata = []\nlabels = []\ninfected = os.listdir(\"cell_images/Parasitized/\")\nuninfected = os.listdir(\"cell_images/Uninfected/\")\n\nfor imageOne in infected:\n try:\n img = cv2.imread(\"cell_images/Parasitized/\" + imageOne)\n img_from_array = Image.fromarray(img, \"RGB\")\n size_image = img_from_array.resize((50, 50))\n data.append(np.array(size_image))\n labels.append(0)\n except AttributeError:\n print(\"infected data loading\")\n\nfor imageTwo in uninfected:\n try:\n img = cv2.imread(\"cell_images/Uninfected/\" + imageTwo)\n img_from_array = Image.fromarray(img, \"RGB\")\n size_image = img_from_array.resize((50, 50))\n data.append(np.array(size_image))\n labels.append(1)\n except AttributeError:\n print(\"Uninfected data loading\")\n\nDataset = np.array(data)\nLabels = np.array(labels)\n\nnp.save(\"50by50Dataset\", Dataset)\nnp.save(\"50by50Labels\", Labels)\n# Loading Dataset and preparing for cnn\nloaded_dataset = np.load(\"50by50Dataset.npy\")\nloaded_labels = np.load(\"50by50Labels.npy\")\n\ns = np.arange(loaded_dataset.shape[0])\nnp.random.shuffle(s)\nloaded_dataset = loaded_dataset[s]\nloaded_labels = loaded_labels[s]\n\nnum_classes = len(np.unique(loaded_labels))\nlen_data = len(loaded_dataset)\n\n(x_train, x_test) = loaded_dataset[(int)(0.1 * len_data):], loaded_dataset[:(int)(0.1 * len_data)]\nx_train = x_train.astype('float32') / 255 # Normalize\nx_test = x_test.astype('float32') / 255\ntrain_len = len(x_train)\ntest_len = len(x_test)\n\n(y_train, y_test) = loaded_labels[(int)(0.1 * len_data):], loaded_labels[:(int)(0.1 * len_data)]\n\ny_train = keras.utils.to_categorical(y_train, num_classes)\ny_test = keras.utils.to_categorical(y_test, num_classes)\n# Create cnn\nmodel = Sequential()\nmodel.add(Conv2D(filters=16, kernel_size=2, padding=\"same\", activation=\"relu\", input_shape=(50, 50, 3)))\nmodel.add(MaxPooling2D(pool_size=2))\nmodel.add(Conv2D(filters=32, kernel_size=2, padding=\"same\", activation=\"relu\"))\nmodel.add(MaxPooling2D(pool_size=2))\nmodel.add(Conv2D(filters=64, kernel_size=2, padding=\"same\", activation=\"relu\"))\nmodel.add(MaxPooling2D(pool_size=2))\nmodel.add(Flatten())\nmodel.add(Dense(500, activation=\"relu\"))\nmodel.add(Dropout(0.2))\nmodel.add(Dense(2, activation=\"softmax\")) # 2 represent output layer neurons\nmodel.summary()\n# Fit CNN\n\n# compile the model with loss as categorical_crossentropy and using\n# adam optimizer you can test result by trying RMSProp as well as Momentum\nmodel.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])\n# Fit the model with min batch size as 50[can tune batch size to some factor of 2^power ]\nfitted = model.fit(x_train, y_train, batch_size=50, epochs=20, verbose=1)\n\naccuracy = model.evaluate(x_test, y_test, verbose=1)\nprint('\\n', 'Test_Accuracy:-', accuracy[1])\n\nmodel.save('weights_for_50px.h5')\n\n# prediction func\n\n\ndef convert_to_array(img):\n im = cv2.imread(img)\n im = cv2.resize(im, (50, 50))\n return np.array(im)\n\n\ndef get_cell_name(label):\n if label == 0:\n return \"Paracitized\"\n if label == 1:\n return \"Uninfected\"\n\n\ndef predict_image(file):\n model = load_model('weights_for_50px.h5')\n print(\"Predicting Image.................................\")\n ar = convert_to_array(file)\n ar = ar / 255\n a = []\n a.append(ar)\n a = np.array(a)\n score = model.predict(a, verbose=1)\n print(score)\n label_index = np.argmax(score)\n print(label_index)\n acc = np.max(score)\n Cell = get_cell_name(label_index)\n return \"The predicted Image is a \" + Cell + \" with accuracy = \" + str(acc)\n","sub_path":"MaleriaDetectionWithKeras/keras_playground.py","file_name":"keras_playground.py","file_ext":"py","file_size_in_byte":3968,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"120153371","text":"from roll.node import Node, Node2D\nfrom roll.math import Vector2\nfrom roll.physics import Collision\nfrom roll.input import Input\nfrom roll.network import Server, Client\n\n\nclass Player:\n ONE = 1\n TWO = 2\n\n\nclass PlayerState:\n def __init__(self, player: int, health=10, position=Vector2(0, 0)):\n self.player = player\n self.health = health\n self.position = position\n self.frames_invincible_after_damage = 0\n\n def __str__(self):\n data = {\n \"player\": self.player,\n \"health\": self.health,\n \"position\": self.position,\n \"frames_invincible_after_damage\": self.frames_invincible_after_damage,\n }\n return f\"{data}\"\n\n def __repr__(self):\n data = {\n \"player\": self.player,\n \"health\": self.health,\n \"position\": self.position,\n \"frames_invincible_after_damage\": self.frames_invincible_after_damage,\n }\n return f\"{data}\"\n\n\nclass FrameState:\n def __init__(\n self, frame, player_one_state: PlayerState, player_two_state: PlayerState\n ) -> None:\n self.frame = frame\n self.player_states = {\n Player.ONE: player_one_state,\n Player.TWO: player_two_state,\n }\n\n def __str__(self):\n data = {\"frame\": self.frame, \"player_states\": self.player_states}\n return f\"{data}\"\n\n def __repr__(self):\n data = {\"frame\": self.frame, \"player_states\": self.player_states}\n return f\"{data}\"\n\n\nclass PlayState:\n def __init__(self):\n self.player_one = PlayerState(player=Player.ONE)\n self.player_two = PlayerState(player=Player.TWO)\n self.current_frame = 0\n self.frames = {}\n self.frame_retention = 7\n\n def __str__(self):\n return f\"{self.frames}\"\n\n def __repr__(self):\n return f\"{self.frames}\"\n\n def save_state(self, player_one_node: Node2D, player_two_node: Node2D) -> None:\n self.player_one.position = player_one_node.position\n self.player_two.position = player_two_node.position\n self.frames[self.current_frame] = FrameState(\n frame=self.current_frame,\n player_one_state=self.player_one,\n player_two_state=self.player_two,\n )\n if self.current_frame - self.frame_retention in self.frames:\n del self.frames[self.current_frame - self.frame_retention]\n\n\nclass Battle(Node2D):\n def _start(self) -> None:\n self.play_state = PlayState()\n self.player_one = self.get_node(name=\"PlayerOne\")\n self.player_two = self.get_node(name=\"PlayerTwo\")\n\n self.player_one_health_text_label = self.get_node(name=\"PlayerOneHealthText\")\n self.player_two_health_text_label = self.get_node(name=\"PlayerTwoHealthText\")\n print(\"Battle created!\")\n\n self._update_player_health_text(player=Player.ONE)\n self._update_player_health_text(player=Player.TWO)\n\n self.server_started = True\n Server.start(port=55555)\n # Client.connect(endpoint=\"127.0.0.1\", port=55555)\n self.time = 0\n\n def _update_player_health_text(self, player: int) -> None:\n if player == Player.ONE:\n self.player_one_health_text_label.text = (\n f\"Player {player}: {self.play_state.player_one.health} HP\"\n )\n elif player == Player.TWO:\n self.player_two_health_text_label.text = (\n f\"Player {player}: {self.play_state.player_two.health} HP\"\n )\n\n def _physics_process(self, delta_time: float) -> None:\n # if self.time % 60 == 0:\n # Client.send_message_to_server(message=\"Message from client!\")\n # self.time += 1\n # if Input.is_action_just_pressed(action_name=\"quit\"):\n # if self.server_started:\n # Server.stop()\n # self.server_started = False\n # else:\n # Server.start(port=55555)\n # self.server_started = True\n\n # Update state\n self.play_state.player_two.frames_invincible_after_damage = max(\n 0, self.play_state.player_two.frames_invincible_after_damage - 1\n )\n\n for collided_node in Collision.get_collided_nodes(self.player_one):\n if (\n collided_node == self.player_two\n and self.play_state.player_two.frames_invincible_after_damage <= 0\n ):\n if Input.is_action_just_pressed(action_name=\"weak_punch\"):\n self.play_state.player_two.health -= 1\n self.play_state.player_two.frames_invincible_after_damage = 60\n self._update_player_health_text(player=Player.TWO)\n\n # Save state\n self.play_state.save_state(\n player_one_node=self.player_one, player_two_node=self.player_two\n )\n # if self.play_state.current_frame % 60 == 0:\n # print(f\"seconds = {self.play_state.current_frame / 60}, frame = {self.play_state.current_frame}\")\n self.play_state.current_frame += 1\n # print(self.play_state)\n","sub_path":"assets/game_projects/test/src/battle.py","file_name":"battle.py","file_ext":"py","file_size_in_byte":5095,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"210018810","text":"import json\nimport sys\n\n# Bitfield used to designate pitch of a note:\n# 0 = A, 1 = A#, 2 = H, 3 = C, 4 = C#, 5 = D, 6 = D#, 7 = E, 8 = F, 9 = F#, 10 = G, 11 = G#\nnoteToNumber = {'A': 0, 'Ax': 1, 'H': 2, 'C': 3, 'Cx': 4, 'D': 5, 'Dx': 6, 'E': 7, 'F': 8, 'Fx': 9, 'G': 10, 'Gx': 11}\n\n# 16 bit with the following structure:\n# note = 4;\n# octave = 4;\n# amplitude = 3;\n# duration = 5;\n\n# number is an int value\n# but return value is in bit as a string\ndef decimalToBin(number):\n\treturn bin(number)[2:]\n\n# takes in binary number as a string and returns hex number as a string\ndef binToHex(number):\n\treturn hex(int(number, 2))\n\n# Each part has a given number of bits. The number will not generate correct number of 0's in front.\n# Fill missing 0's at the beginning.\ndef fillBitsIfMissing(number, numberOfBits):\n\twhile numberOfBits > len(number):\n\t\tnumber = '0' + number\n\treturn number\n\ndef noteToBin(note):\n\tbinaryNumber = decimalToBin(noteToNumber[note])\n\tbinaryNumber = fillBitsIfMissing(binaryNumber, 4)\n\treturn binaryNumber\n\ndef octaveToBin(octave):\n\tbinaryNumber = decimalToBin(octave)\n\tbinaryNumber = fillBitsIfMissing(binaryNumber, 4)\n\treturn binaryNumber\n\ndef amplitudeToBin(amplitude):\n\tbinaryNumber = decimalToBin(amplitude)\n\tbinaryNumber = fillBitsIfMissing(binaryNumber, 3)\n\treturn binaryNumber\n\ndef durationToBin(duration):\n\tbinaryNumber = decimalToBin(duration)\n\tbinaryNumber = fillBitsIfMissing(binaryNumber, 5)\n\treturn binaryNumber\n\ndef writeHexArrayToFile(outfile, hexArray, partName):\n\tsize = len(hexArray)\n\t\n\toutfile.write('uint16_t ' + partName + '_notes[' + str(size) + '] = {')\n\t\n\tfor hexNumber in hexArray:\n\t\toutfile.write(hexNumber + ',')\n\t\n\toutfile.write('}; \\n')\n\ndef writePartToFile(songName, partName, partNumber, part, outfile):\n\twriteHexArrayToFile(outfile, part, partName)\n\toutfile.write('synth_part ' + partName + ' = { ')\n\toutfile.write('.start = (synth_note*) &' + partName + '_notes[0], ')\n\toutfile.write('.n_notes = ' + str(len(part)) + ', ')\n\toutfile.write('.channel = ' + str(partNumber) + ' };\\n')\n\n\ndef writeSongToFile(songName, durationUnit, part0, part1, outfile):\n\t\n\t# Write song name in comments\n\toutfile.write('//-------------------------------\\n')\n\toutfile.write('// ' + songName + '\\n')\n\toutfile.write('//-------------------------------\\n')\n\n\t# Write code declaring part 0\n\twritePartToFile(songName, songName + '_part0', 0, part0, outfile) \n\toutfile.write('\\n')\n\t\n\t# Write code declaring part 1\n\twritePartToFile(songName, songName + '_part1', 1, part1, outfile) \n\toutfile.write('\\n')\n\n\t# Write declarations to make song globally available\n\toutfile.write('extern synth_song ' + songName + '; \\n')\n\toutfile.write('synth_song ' + songName + ' = { ')\n\toutfile.write('.default_duration_unit = ' + str(durationUnit) + ', ')\n\toutfile.write('.part0 = &' + songName + '_part0, ')\n\toutfile.write('.part1 = &' + songName + '_part1 };\\n')\n\toutfile.write('\\n')\n\ndef createHexArray(note, octave, amplitude, duration):\n\tsongArray = []\n\tsize = len(note)\n\n\tfor i in xrange(size):\n\t\tbinaryNumber = ''\n\t\t\n\t\t# Append all bits\n\t\tbinaryNumber += durationToBin(duration[i])\n\t\tbinaryNumber += amplitudeToBin(amplitude[i])\n\t\tbinaryNumber += octaveToBin(octave[i])\n\t\tbinaryNumber += noteToBin(note[i])\n\n\t\t# Convert to hex\n\t\thexNumber = binToHex(binaryNumber)\n\n\t\tsongArray.append(hexNumber)\n\n\treturn songArray\n\ndef jsonPartToHexArray(part):\n note = part[\"note\"]\n octave = part[\"octave\"]\n amplitude = part[\"amplitude\"]\n duration = part[\"duration\"]\n return createHexArray(note, octave, amplitude, duration)\n\ndef main():\n\t\n\t# Write include statements to output header\n\toutfile = open('synthSongs.c', 'w')\n\toutfile.write('#include \\n')\n\toutfile.write('#include \"synth.h\" \\n')\n\toutfile.write('\\n')\n\n\t# Write a file comment\n\toutfile.write('// AUTOMATICALLY GENERATED SOURCE: \\n')\n\toutfile.write('// This file was automatically generated by the python script \"' + sys.argv[0] + '\".\\n')\n\toutfile.write('\\n')\n\t\n\t# Read songs from files specified by input arguments, and write songs to the song header.\n\tfor i in range(1, len(sys.argv)):\n\t\t\n\t\t# Read and decode next json song file\n\t\tf = open(sys.argv[i], 'r')\n\t\tsong = json.loads(f.read())\n\t\tf.close()\n\t\t\n\t\t# Get values from json song \n\t\tsongName = song[\"songName\"]\n\t\tdurationUnit = song[\"durationUnit\"]\n\t\tpart0 = jsonPartToHexArray(song[\"part0\"])\n\t\tpart1 = jsonPartToHexArray(song[\"part1\"])\n\n\t\t# Write song file\n\t\twriteSongToFile(songName, durationUnit, part0, part1, outfile)\n\n\toutfile.close()\n\nmain()\n","sub_path":"exercise2/src/noteGenerator/generateSong.py","file_name":"generateSong.py","file_ext":"py","file_size_in_byte":4483,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"147095246","text":"import os\nimport subprocess\nfrom self_locator import *\nimport yaml\nimport math\nimport json\nimport time\nimport signal\nimport sys\nimport csv\nimport requests\nimport numpy as numpy \nCONFIG = yaml.load(open(\"../config.yaml\"))\n\n# (Column, Row)\nGRID_COLUMNS = CONFIG[\"grid\"][\"columns\"]\nGRID_ROWS = CONFIG[\"grid\"][\"columns\"]\n\n# BEACON_COLORS = [0, 1, 2, 3, 4]\nBEACON_COLUMNS = CONFIG[\"grid\"][\"beacons_columns\"]\nBEACON_ROWS = CONFIG[\"grid\"][\"beacons_rows\"]\nCELL_SIZE = CONFIG[\"grid\"][\"cell_size\"]\n\nORIENT_REF_ROW = CONFIG[\"grid\"][\"orientation_reference_row\"] # Red Beacon\noffload_dijkstra = CONFIG[\"offload_path_planning\"]\nS1 = str(CONFIG[\"camera\"][\"vertical_servo_pin\"])\n\n\n# Return estimated AlphaBot's position in grid (column, row, orientation)\ndef self_localize(self_locator):\n b_distance, b_angle, b_color = self_locator.dna_from_beacons()\n x, y, column, row = detect_position_in_grid(b_distance, b_color)\n # angle from the first beacon is enough\n orientation = detect_orientation(x, y, b_distance[0], b_angle[0], b_color[0]) \n # print x, y, column, row, orientation\n return x, y, column, row, orientation, b_color\n\n# Detect AlphaBot's orientation (degrees) relevant to a reference point in grid\ndef detect_orientation(ax, ay, distance, theta_beac, color):\n rx = ORIENT_REF_ROW * CELL_SIZE + CELL_SIZE / 2\n ry = ay\n bx = BEACON_ROWS[color] * CELL_SIZE + CELL_SIZE / 2\n by = BEACON_COLUMNS[color] * CELL_SIZE + CELL_SIZE / 2 \n\n # beacon - alphabot distance\n bad = round(distance)\n print(\"Beacon - AlphaBot distance: \" + str(bad) + \"cm.\")\n # beacon - ref distance\n brd = round(math.sqrt((bx - rx) ** 2 + (by - ry) ** 2))\n print(\"Beacon - Reference Point distance: \" + str(brd) + \"cm.\")\n # alphabot - ref distance\n ard = round(math.sqrt((ax - rx) ** 2 + (ay - ry) ** 2))\n print(\"AlphaBot - Reference Point distance: \" + str(ard) + \"cm.\")\n\n # Cosine Rule\n a = round(math.degrees(math.acos((bad ** 2 + ard ** 2 - brd ** 2) / (2 * bad * ard))), 2)\n print(\"Cosine Rule Angle: \" + str(a) + \"deg.\")\n \n # theta_or < 0 if the reference point is on the right of the alphabot, > 0 otherwise \n # if ((by < ry) and (theta_beac > 0)):\n # theta_or = theta_beac + a\n # elif ((by < ry) and (theta_beac < 0)):\n # theta_or = theta_beac + a \n # elif ((by > ry) and (theta_beac > 0)):\n # theta_or = theta_beac - a\n # elif ((by > ry) and (theta_beac < 0)):\n # theta_or = theta_beac - a\n theta_or = theta_beac - ((by-ry)/math.fabs(by-ry)) * a\n print(\"Orientation Angle: \" + str(-theta_or) + \"deg.\")\n\n return theta_or\n\n# Detect AlphaBot's position in grid (columns, rows)\ndef detect_position_in_grid(distance, color):\n r0 = distance[0]\n print(\"R0 = \" + str(r0))\n r1 = distance[1]\n print(\"R1 = \" + str(r1))\n x0 = BEACON_ROWS[color[0]] * CELL_SIZE + CELL_SIZE / 2 # because it sits in the cell centre\n print(\"x0 = \" + str(x0))\n y0 = BEACON_COLUMNS[color[0]] * CELL_SIZE + CELL_SIZE / 2\n print(\"y0 = \" + str(y0))\n x1 = BEACON_ROWS[color[1]] * CELL_SIZE + CELL_SIZE / 2\n print(\"x1 = \" + str(x1)) \n y1 = BEACON_COLUMNS[color[1]] * CELL_SIZE + CELL_SIZE / 2\n print(\"y1 = \" + str(y1))\n \n # Circle - Circle Intersection calculation\n d = math.sqrt((x1 - x0) ** 2 + (y1 - y0) ** 2)\n a = (r0 ** 2 - r1 ** 2 + d ** 2) / (2 * d)\n h = math.sqrt(r0 ** 2 - a ** 2)\n x2 = x0 + a * (x1 - x0) / d \n y2 = y0 + a * (y1 - y0) / d \n x3a = round(x2 + h * (y1 - y0) / d, 2) \n print(\"IP1 x = \" + str(x3a))\n x3b = round(x2 - h * (y1 - y0) / d, 2)\n print(\"IP2 x = \" + str(x3b))\n y3a = round(y2 - h * (x1 - x0) / d, 2)\n print(\"IP1 y = \" + str(y3a))\n y3b = round(y2 + h * (x1 - x0) / d, 2)\n print(\"IP2 y = \" + str(y3b))\n\n if ((x3a > GRID_ROWS*CELL_SIZE) or (y3a > GRID_COLUMNS*CELL_SIZE)): \n if ((x3b <= GRID_ROWS*CELL_SIZE) or (y3b <= GRID_COLUMNS*CELL_SIZE)): \n x3 = x3b \n y3 = y3b\n else:\n print(\"Invalid Intersection Point found!\")\n \n elif ((x3a < GRID_ROWS*CELL_SIZE) and (y3a < GRID_COLUMNS*CELL_SIZE)): \n x3 = x3a\n y3 = y3a\n else:\n print(\"Invalid Intersection Point found\")\n\n print(\"IP x = \" + str(x3))\n print(\"IP y = \" + str(y3))\n row = x3 // CELL_SIZE\n column = y3 // CELL_SIZE\n \n return x3, y3, column, row\n\ndef signal_handler(sig, frame):\n print(' was pressed! Fixing camera position and terminating...\\n')\n with open(os.devnull, 'wb') as devnull:\n subprocess.check_call(['sudo', 'python', 'turn_head.py', '-s', S1, '-w', '1600'], \n stdout=devnull, stderr=subprocess.STDOUT)\n sys.exit(0)\n\ndef main():\n os.system('clear')\n signal.signal(signal.SIGINT, signal_handler)\n sl = SelfLocator(300)\n c = 0\n \n ## dummy values\n xreal = 150\n yreal = 150 \n orreal = 0\n while True : # While current tile is different from target's tile:\n c += 1\n if c==5:\n break;\n #raw_input(\"Press Enter to continue...\\n\")\n \n try:\n x, y, i, j, co, beacons = self_localize(sl)\n co=-co\n filename = \"./statsclient\"\n with open(filename, 'a') as myfile:\n wr = csv.writer(myfile, quoting=csv.QUOTE_ALL)\n # If opened for the first time, insert header row\n if os.path.getsize(filename) == 0: \n wr.writerow([\"xreal\",\"yreal\",\"orreal\",\"xmeas\",\"ymeas\",\"ormeas\",\"beacons\"])\n wr.writerow([xreal,yreal,orreal,x,y,co,beacons])\n\n except (InsufficientLocalizationInfoError, ValueError):\n print(\"I have no information regarding where I am. Quiting...\\n\")\n continue\n \n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"alphabot-ppl/experiments.py","file_name":"experiments.py","file_ext":"py","file_size_in_byte":5793,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"140265598","text":"# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved\n\n\"\"\"\nCoordinates common operations on banks. Conceptually midway between the API and\nthe DB Layer. \n\"\"\"\nimport typing as t\n\nfrom threatexchange.content_type.content_base import ContentType\n\nfrom hmalib.common.models.bank import BankMember, BanksTable\n\n\ndef add_bank_member(\n banks_table: BanksTable,\n bank_id: str,\n content_type: t.Type[ContentType],\n storage_bucket: t.Optional[str],\n storage_key: t.Optional[str],\n raw_content: t.Optional[str],\n notes: str,\n) -> BankMember:\n \"\"\"\n WIP: As of now, just writes the bank member to the database. Once\n functionality for signal extraction, adding-to-index is written, this should\n be the callsite.\n \"\"\"\n return banks_table.add_bank_member(\n bank_id=bank_id,\n content_type=content_type,\n storage_bucket=storage_bucket,\n storage_key=storage_key,\n raw_content=raw_content,\n notes=notes,\n )\n","sub_path":"hasher-matcher-actioner/hmalib/banks/bank_operations.py","file_name":"bank_operations.py","file_ext":"py","file_size_in_byte":989,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"612696277","text":"from django.core.exceptions import ValidationError\nfrom django.db import models\nfrom dcim.choices import *\nfrom utilities.utils import to_grams\n\n\nclass WeightMixin(models.Model):\n weight = models.DecimalField(\n max_digits=8,\n decimal_places=2,\n blank=True,\n null=True\n )\n weight_unit = models.CharField(\n max_length=50,\n choices=WeightUnitChoices,\n blank=True,\n )\n # Stores the normalized weight (in grams) for database ordering\n _abs_weight = models.PositiveBigIntegerField(\n blank=True,\n null=True\n )\n\n class Meta:\n abstract = True\n\n def save(self, *args, **kwargs):\n\n # Store the given weight (if any) in grams for use in database ordering\n if self.weight and self.weight_unit:\n self._abs_weight = to_grams(self.weight, self.weight_unit)\n else:\n self._abs_weight = None\n\n super().save(*args, **kwargs)\n\n def clean(self):\n super().clean()\n\n # Validate weight and weight_unit\n if self.weight and not self.weight_unit:\n raise ValidationError(\"Must specify a unit when setting a weight\")\n","sub_path":"netbox/dcim/models/mixins.py","file_name":"mixins.py","file_ext":"py","file_size_in_byte":1169,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"329671942","text":"import os\nfrom config.config import MyConfig\nfrom manage.fileCreate.apiCreation import ApiCreation\nfrom manage.fileCreate.baseCreation import BaseCreation\nfrom manage.fileCreate.configCreation import ConfigCreation\nfrom manage.fileCreate.controllerCreation import ControllerCreation\nfrom manage.fileCreate.documentCreation import DocumentCreation\nfrom manage.fileCreate.methodCreation import MethodCreation\nfrom manage.fileCreate.modelCreation import ModelCreation\nfrom manage.fileCreate.objectCreation import ObjectCreation\nfrom manage.manage import MyManage\nfrom model.directory import MyDir\nfrom model.message import Msg\nfrom model.name import Name\nfrom model.status import FileSync\n\n\nclass MyHandle:\n\n @staticmethod\n def handle(path: str, project: str, detail: dict):\n\n # create directory\n if MyManage.makeDirectory(path, project):\n\n # copy default file\n if MyManage.copyFileDefault(MyConfig.fileDefaultPath, project, path):\n\n fileKey = detail.keys()\n\n # create base api file\n fileConfigName, contentConfig = ConfigCreation.create(project)\n configSetting = FileSync.replace\n pathConfig = os.path.join(path, project, MyDir.src, MyDir.config, fileConfigName)\n if MyManage.makeFile(pathConfig, contentConfig, configSetting):\n\n # create base api file\n fileBaseName, contentBase = BaseCreation.create(fileKey)\n baseSetting = FileSync.replace\n pathBase = os.path.join(path, project, MyDir.src, MyDir.api, fileBaseName)\n if MyManage.makeFile(pathBase, contentBase, baseSetting):\n\n # create object file\n fileObjectName, contentObject = ObjectCreation.create(fileKey)\n objectSetting = FileSync.replace\n pathObject = os.path.join(path, project, MyDir.src, MyDir.service, fileObjectName)\n if MyManage.makeFile(pathObject, contentObject, objectSetting):\n\n # create method file\n fileMethodName, contentMethod = MethodCreation.create(detail)\n methodSetting = FileSync.replace\n pathMethod = os.path.join(path, project, MyDir.src, MyDir.service, fileMethodName)\n if MyManage.makeFile(pathMethod, contentMethod, methodSetting):\n\n for className in fileKey:\n myDataField = detail[className][Name.field]\n apiSetting = detail[className][Name.setting][Name.apiSync]\n controllerSetting = detail[className][Name.setting][Name.controllerSync]\n modelSetting = detail[className][Name.setting][Name.modelSync]\n myDataFunction = detail[className][Name.function]\n\n # create model file\n fileModelName, contentModel = ModelCreation.create(className, myDataField)\n pathModel = os.path.join(path, project, MyDir.src, MyDir.model, fileModelName)\n if not MyManage.makeFile(pathModel, contentModel, modelSetting):\n print(Msg.makeFileFail.format(fileModelName))\n break\n\n # create controller file\n fileControllerName, contentController = ControllerCreation.create(className, myDataFunction, myDataField, detail)\n pathController = os.path.join(path, project, MyDir.src, MyDir.controller, fileControllerName)\n if not MyManage.makeFile(pathController, contentController, controllerSetting):\n print(Msg.makeFileFail.format(fileControllerName))\n break\n\n # create api file\n fileApiName, contentApi = ApiCreation.create(className, myDataFunction)\n pathApi = os.path.join(path, project, MyDir.src, MyDir.api, fileApiName)\n if not MyManage.makeFile(pathApi, contentApi, apiSetting):\n print(Msg.makeFileFail.format(fileApiName))\n break\n\n # create controller file\n fileDocumentName, contentDocument = DocumentCreation.create(className, myDataFunction, myDataField)\n documentSetting = FileSync.replace\n pathController = os.path.join(path, project, MyDir.src, MyDir.doc, fileDocumentName)\n if not MyManage.makeFile(pathController, contentDocument, documentSetting):\n print(Msg.makeFileFail.format(fileControllerName))\n break\n\n # install project and open\n pathModule = os.path.join(path, project, MyDir.node_modules)\n if not os.path.exists(pathModule):\n npmProject = os.path.join(path, project)\n os.system(f\"start \\\"\\\" cmd /k \\\"cd {npmProject} & npm install . & code . & exit;\\n \\\\ & color 07\\\"\")\n print(Msg.success.format(project))\n\n else:\n print(Msg.makeFileFail.format(fileMethodName))\n else:\n print(Msg.makeFileFail.format(fileObjectName))\n else:\n print(Msg.makeFileFail.format(fileBaseName))\n else:\n print(Msg.makeFileFail.format(fileConfigName))\n else:\n print(Msg.copyFileDefaultFail)\n else:\n print(Msg.makeDirectoryFail)\n","sub_path":"manage/handle.py","file_name":"handle.py","file_ext":"py","file_size_in_byte":6291,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"303402054","text":"# coding: utf-8 \nimport socketserver\nimport os\n# Copyright 2020 Daniel Dick\n# \n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n# \n# http://www.apache.org/licenses/LICENSE-2.0\n# \n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n#\n# This is derived from the code that is Copyright 2013 Abram Hindle, \n# Eddie Antonio Santos. This code can be found here:\n# \n# http://github.com/abramhindle/CMPUT404-assignment-webserver\n#\n# Basis for list_dir function derived from answers on stackoverflow\n# (modified to suit the scenario). Credit to user badcOre.\n#\n# https://stackoverflow.com/questions/18510733/python-mapping-all-files-inside-a-folder\n#\n# Furthermore it is derived from the Python documentation examples thus\n# some of the code is Copyright © 2001-2013 Python Software\n# Foundation; All Rights Reserved\n#\n# http://docs.python.org/2/library/socketserver.html\n#\n# run: python3 freetests.py\n\n# try: curl -v -X GET http://127.0.0.1:8080/\n\ndef list_dir(dir_name, traversed = [], results = []): \n dirs = os.listdir(dir_name)\n results.append(dir_name)\n if dirs:\n for f in dirs:\n new_dir = dir_name + f + '/'\n if os.path.isdir(new_dir) and new_dir not in traversed:\n traversed.append(new_dir)\n list_dir(new_dir, traversed, results)\n else:\n results.append(new_dir[:-1]) \n return results\n\n\n\nclass MyWebServer(socketserver.BaseRequestHandler):\n \n def handle(self):\n dirs = []\n dirs = list_dir('www/',[],[])\n self.data = self.request.recv(1024).strip()\n #print (\"Got a request of: %s\\n\" % self.data)\n inData = self.data.split()\n #print(inData)\n if (len(inData) < 2):\n return\n req = inData[1]\n req = str(req.decode('UTF-8'))\n req_url = 'www'+ req\n #print(\"req url = \"+str(req_url))\n if inData[0] != b'GET':\n #print(\"405 Sent!\")\n self.send_405()\n elif (req_url+'/') in dirs or 'HTTP' in str(inData[1]) or '/' not in str(inData[1]):\n #print(\"301 Sent!\")\n self.send_301(req_url)\n elif req_url in dirs and req_url[-1] == '/':\n #print(\"200 Sent!\")\n self.send_200_loc(req_url,dirs)\n elif req_url in dirs:\n #print(\"200 Sent!\")\n self.send_200_file(req_url,dirs)\n else:\n #print(\"404 Sent!\")\n self.send_404()\n #print(fxn)\n #print('*******************************************')\n\n def send_200_loc(self,req,dirs):\n length = 0\n reqs = []\n reqs = [x for x in dirs if req in x]\n reqs = [x for x in reqs if (x.count('/')==req.count('/') or (x.count('/')==(req.count('/')+1) and x[-1] == '/'))]\n reqs_link = [x[3:] for x in reqs if x != req and x[0] != '.']\n reqs_show = [x[len(req)-1:] for x in reqs if x != req and x[0] != '.']\n #print(reqs)\n payload = '''\n\n\n\n\t
\n\t\t
    '''\n for i in range(len(reqs_link)):\n payload += '''\n
  • '''+reqs_show[i]+'''
  • '''\n payload += '''\n\t\t
\n\t
\n\n \n'''\n length = len(payload)\n \n \n response = 'HTTP/1.1 200 OK\\r\\nContent-type:text/html\\r\\nContent-length:'+str(length)+'\\r\\nConnection: close\\r\\n\\r\\n'\n if length != 0:\n response = response + payload + '\\r\\n\\r\\n'\n self.request.sendall(bytearray(response,'utf-8'))\n\n def send_200_file(self,req,dirs):\n length = 0\n type_file = 'text/html'\n if 'css' in req:\n type_file = 'text/css'\n with open(req, 'r') as file:\n payload = file.read()\n length = len(payload)\n response = 'HTTP/1.1 200 OK\\r\\nContent-type:'+type_file+'\\r\\nContent-length:'+str(length)+'\\r\\nConnection: close\\r\\n\\r\\n'\n if length != 0:\n response = response + payload + '\\r\\n\\r\\n' \n self.request.sendall(bytearray(response,'utf-8'))\n\n\n def send_404(self):\n response = 'HTTP/1.1 404 Not Found\\r\\nContent-type:text/html\\r\\nContent-length:0\\r\\nConnection: close\\r\\n\\r\\n'\n self.request.sendall(bytearray(response,'utf-8'))\n \n def send_405(self):\n response = 'HTTP/1.1 405 Method Not Allowed\\r\\nContent-type:text/html\\r\\nContent-length:0\\r\\nConnection: close\\r\\n\\r\\n'\n self.request.sendall(bytearray(response,'utf-8'))\n\n def send_301(self,req):\n new = req[3:]+'/'\n response = 'HTTP/1.1 301 Moved Permanently\\r\\nLocation:http://127.0.0.1:8080'+new+'\\r\\nContent-type:text/html\\r\\nContent-length:0\\r\\nConnection:close\\r\\n\\r\\n'\n self.request.sendall(bytearray(response,'utf-8'))\n \n\nif __name__ == \"__main__\":\n HOST, PORT = \"localhost\", 8080\n\n socketserver.TCPServer.allow_reuse_address = True\n # Create the server, binding to localhost on port 8080\n server = socketserver.TCPServer((HOST, PORT), MyWebServer)\n\n # Activate the server; this will keep running until you\n # interrupt the program with Ctrl-C\n server.serve_forever()\n","sub_path":"server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":5530,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"389239925","text":"#!/usr/bin/env python\n#\n# Copyright 2016 - The Android Open Source Project\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\"\"\"A client that talks to Android Build APIs.\"\"\"\n\nimport io\nimport logging\nimport os\n\nimport apiclient\n\nfrom acloud.internal.lib import base_cloud_client\nfrom acloud.public import errors\n\nlogger = logging.getLogger(__name__)\n\n\nclass AndroidBuildClient(base_cloud_client.BaseCloudApiClient):\n \"\"\"Client that manages Android Build.\"\"\"\n\n # API settings, used by BaseCloudApiClient.\n API_NAME = \"androidbuildinternal\"\n API_VERSION = \"v2beta1\"\n SCOPE = \"https://www.googleapis.com/auth/androidbuild.internal\"\n\n # other variables.\n DEFAULT_RESOURCE_ID = \"0\"\n # TODO(fdeng): We should use \"latest\".\n DEFAULT_ATTEMPT_ID = \"0\"\n DEFAULT_CHUNK_SIZE = 20 * 1024 * 1024\n NO_ACCESS_ERROR_PATTERN = \"does not have storage.objects.create access\"\n\n # Message constant\n COPY_TO_MSG = (\"build artifact (target: %s, build_id: %s, \"\n \"artifact: %s, attempt_id: %s) to \"\n \"google storage (bucket: %s, path: %s)\")\n\n def DownloadArtifact(self,\n build_target,\n build_id,\n resource_id,\n local_dest,\n attempt_id=None):\n \"\"\"Get Android build attempt information.\n\n Args:\n build_target: Target name, e.g. \"gce_x86-userdebug\"\n build_id: Build id, a string, e.g. \"2263051\", \"P2804227\"\n resource_id: Id of the resource, e.g \"avd-system.tar.gz\".\n local_dest: A local path where the artifact should be stored.\n e.g. \"/tmp/avd-system.tar.gz\"\n attempt_id: String, attempt id, will default to DEFAULT_ATTEMPT_ID.\n \"\"\"\n attempt_id = attempt_id or self.DEFAULT_ATTEMPT_ID\n api = self.service.buildartifact().get_media(\n buildId=build_id,\n target=build_target,\n attemptId=attempt_id,\n resourceId=resource_id)\n logger.info(\"Downloading artifact: target: %s, build_id: %s, \"\n \"resource_id: %s, dest: %s\", build_target, build_id,\n resource_id, local_dest)\n try:\n with io.FileIO(local_dest, mode=\"wb\") as fh:\n downloader = apiclient.http.MediaIoBaseDownload(\n fh, api, chunksize=self.DEFAULT_CHUNK_SIZE)\n done = False\n while not done:\n _, done = downloader.next_chunk()\n logger.info(\"Downloaded artifact: %s\", local_dest)\n except OSError as e:\n logger.error(\"Downloading artifact failed: %s\", str(e))\n raise errors.DriverError(str(e))\n\n def CopyTo(self,\n build_target,\n build_id,\n artifact_name,\n destination_bucket,\n destination_path,\n attempt_id=None):\n \"\"\"Copy an Android Build artifact to a storage bucket.\n\n Args:\n build_target: Target name, e.g. \"gce_x86-userdebug\"\n build_id: Build id, a string, e.g. \"2263051\", \"P2804227\"\n artifact_name: Name of the artifact, e.g \"avd-system.tar.gz\".\n destination_bucket: String, a google storage bucket name.\n destination_path: String, \"path/inside/bucket\"\n attempt_id: String, attempt id, will default to DEFAULT_ATTEMPT_ID.\n \"\"\"\n attempt_id = attempt_id or self.DEFAULT_ATTEMPT_ID\n copy_msg = \"Copying %s\" % self.COPY_TO_MSG\n logger.info(copy_msg, build_target, build_id, artifact_name,\n attempt_id, destination_bucket, destination_path)\n api = self.service.buildartifact().copyTo(\n buildId=build_id,\n target=build_target,\n attemptId=attempt_id,\n artifactName=artifact_name,\n destinationBucket=destination_bucket,\n destinationPath=destination_path)\n try:\n self.Execute(api)\n finish_msg = \"Finished copying %s\" % self.COPY_TO_MSG\n logger.info(finish_msg, build_target, build_id, artifact_name,\n attempt_id, destination_bucket, destination_path)\n except errors.HttpError as e:\n if e.code == 503:\n if self.NO_ACCESS_ERROR_PATTERN in str(e):\n error_msg = \"Please grant android build team's service account \"\n error_msg += \"write access to bucket %s. Original error: %s\"\n error_msg %= (destination_bucket, str(e))\n raise errors.HttpError(e.code, message=error_msg)\n raise\n","sub_path":"tools/acloud/internal/lib/android_build_client.py","file_name":"android_build_client.py","file_ext":"py","file_size_in_byte":5201,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"92522346","text":"#\n# dataset.py\n# dabnet\n# dab dataset \n#\n\nimport os\nimport numpy as np\nimport pandas as pd\nimport cv2\n\n\n\n# Dataset path constants\nPATH = \"data\"\nIMG_PATH = os.path.join(PATH, \"images\")\nMETA_PATH = os.path.join(PATH, \"meta.csv\")\n\n# Loads the dataset from disk\n# Returns features and labels np arrays\ndef load():\n # read dataset metadata\n df = pd.read_csv(META_PATH)\n labels = df.loc[:, \"label\"].values\n img_paths = df.loc[:, \"img_path\"].values\n \n # read dataset images\n images = [ cv2.imread(p) for p in img_paths ]\n\nif __name__ == \"__main__\":\n load()\n","sub_path":"src/data/dataset.py","file_name":"dataset.py","file_ext":"py","file_size_in_byte":576,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"59623154","text":"# structure configuration for datacard\n\nstructure = {}\n\nnominal=['WWewk', 'ZZ', 'Fake_ee', 'Fake_mm', 'Fake_em', 'WW', 'DY', 'WZhad', 'DATA', 'Wg', 'qqH_hww', 'VVV', 'top', 'ZgS', 'ttV', 'ggWW', 'ZH_hww', 'WgS', 'ggZH_hww', 'WZ', 'ggH_hww', 'qqH_htt', 'ggH_htt', 'Zg', 'WH_htt', 'ZH_htt', 'ttH_hww']\nstxs=['WH_hww_PTV_LT150' , 'WH_hww_PTV_GT150' , 'WH_hww_FWDH']\n\n# keys here must match keys in samples.py\nfor iproc in nominal+stxs:\n structure[iproc] = {\n 'isSignal' : 1 if any(substring in iproc for substring in ['H_hww','H_htt']) else 0,\n 'isData' : 1 if iproc == 'DATA' else 0,\n }\n","sub_path":"Configurations/WH_SS/STXS_nanoAOD/v6/Full2018nano_STXS_1p1/structure.py","file_name":"structure.py","file_ext":"py","file_size_in_byte":607,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"452128329","text":"import scipy.io as sio\nimport tensorflow as tf\nimport numpy as np\nimport math\nfrom tensorflow import keras\nfrom tensorflow.keras import layers\nfrom tensorflow.keras.models import Model\n\n\"\"\"\nDate created: December 10, 2020\nDate Modified: December 10, 2020\n---- Inputs to this code ----\ncurrent_data -- vector [#states - 136]\nnum_time_steps prediction -- positive integer\n\n---- Content of this code ----\nTakes the current state space data, transforms to latent space,\nforwards num_time_steps with states inclusive\n\n---- Outputs of this code ----\npredicted_data -- vector [#states x #time - 136xnum_time_steps]\n\n---- Assumptions ----\nThe input data to this code is normalized and the output data\nof this code is normalized as well\n\"\"\"\n\ndir_name = 'trained_deepDMD_model'\nmat_file_contents = sio.loadmat(dir_name+'/Robust_deepDMD.mat')\nK = mat_file_contents['K']\nencoder_weights = mat_file_contents['Weights'][0]\n\nencoder_weights[1] = np.reshape(encoder_weights[1],(encoder_weights[1].shape[1],))\nencoder_weights[3] = np.reshape(encoder_weights[3],(encoder_weights[3].shape[1],))\nencoder_weights[5] = np.reshape(encoder_weights[5],(encoder_weights[5].shape[1],))\nencoder_weights[7] = np.reshape(encoder_weights[7],(encoder_weights[7].shape[1],))\nencoder_weights[9] = np.reshape(encoder_weights[9],(encoder_weights[9].shape[1],))\n\nclass DenseLayer(layers.Layer):\n\n def __init__(self, initial_weights, initial_bias):\n super(DenseLayer, self).__init__(dtype = 'float64')\n self.w = tf.Variable(initial_value=tf.convert_to_tensor(initial_weights, dtype=tf.float64),trainable=False)\n self.b = tf.Variable(initial_value=tf.convert_to_tensor(initial_bias, dtype=tf.float64),trainable=False)\n\n def call(self, inputs):\n x = tf.matmul(inputs, self.w) + self.b\n return tf.nn.elu(x)\n\nclass LinearLayer(layers.Layer):\n\n def __init__(self, initial_weights, initial_bias):\n super(LinearLayer, self).__init__(dtype = 'float64')\n self.w = tf.Variable(initial_value=tf.convert_to_tensor(initial_weights, dtype=tf.float64),trainable=False)\n self.b = tf.Variable(initial_value=tf.convert_to_tensor(initial_bias, dtype=tf.float64),trainable=False)\n\n def call(self, inputs):\n return tf.matmul(inputs, self.w) + self.b\n\n\n# Neural Network\nclass Encoder(tf.keras.layers.Layer):\n def __init__(self):\n super(Encoder, self).__init__(dtype = 'float64', name = 'Encoder')\n self.input_layer = DenseLayer(encoder_weights[0], encoder_weights[1])\n self.hidden_layer1 = DenseLayer(encoder_weights[2], encoder_weights[3])\n self.hidden_layer2 = DenseLayer(encoder_weights[4], encoder_weights[5])\n self.hidden_layer3 = DenseLayer(encoder_weights[6], encoder_weights[7])\n self.output_layer = LinearLayer(encoder_weights[8], encoder_weights[9])\n \n def call(self, input_data):\n fx = self.input_layer(input_data)\n fx = self.hidden_layer1(fx)\n fx = self.hidden_layer2(fx)\n fx = self.hidden_layer3(fx)\n return self.output_layer(fx)\n\nclass NeuralNetworkModel(tf.keras.Model):\n def __init__(self):\n super(NeuralNetworkModel, self).__init__(dtype = 'float64')\n self.EN = Encoder()\n \n def call(self, inputs):\n X = inputs[0]\n Y = inputs[1]\n \n Psi_X = self.EN(X)\n Psi_Y = self.EN(Y)\n \n PSI_X = tf.concat([X, Psi_X], 1)\n PSI_Y = tf.concat([Y, Psi_Y], 1)\n return PSI_X, PSI_Y\n \nclass SurrogateModel:\n def __init__(self):\n # load neural network model\n self.Model = NeuralNetworkModel()\n \n def predict(self, X0, num_time_steps):\n # Transform the current_data (which is in state space) to Latent space\n PSI_X, PSI_Y = self.Model([X0, X0])\n\n X_pred = np.zeros((num_time_steps, K.shape[0]))\n X_pred[0,:] = PSI_X\n\n for k in range(num_time_steps-1):\n X_pred[k+1, :] = np.matmul(X_pred[k, :], K)\n\n return X_pred\n","sub_path":"Models/deepDMD/deepDMD_model.py","file_name":"deepDMD_model.py","file_ext":"py","file_size_in_byte":4032,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"197458350","text":"# coding = utf-8\n__author__ = \"Yufeng Yang\"\n\n\"\"\"\nGiven an n-ary tree, return the preorder traversal of its nodes' values.\n\nFor example, given a 3-ary tree:\n\n 1\n / | \\\n 3 2 4\n / \\\n 5 6\n\n \n\nReturn its preorder traversal as: [1,3,5,6,2,4].\n\"\"\"\n\n\n# Time: O(n) n is the number of the TreeNode\n# Space: O(n) n is the number of the TreeNode\nclass Solution(object):\n def __init__(self):\n self.ans = []\n\n def preorder(self, root):\n \"\"\"\n :param root: Node\n :return: List[int]\n\n Recursive solution\n \"\"\"\n\n if root:\n self.ans.append(root.val)\n\n for child in root.children:\n self.preorder(child)\n\n return self.ans\n\n\n# Iterative solution\nclass Solution2(object):\n def __init__(self):\n self.ans = []\n self.stack = []\n\n def preorder(self, root):\n \"\"\"\n :param root: Node\n :return: List[int]\n \"\"\"\n if not root:\n return self.ans\n\n self.stack.append(root)\n\n while self.stack:\n root = self.stack.pop()\n self.ans.append(root.val)\n\n # from right to left\n for child in root.children[::-1]:\n self.stack.append(child)\n\n return self.ans\n\n","sub_path":"code/589. N-ary Tree Preorder Traversal.py","file_name":"589. N-ary Tree Preorder Traversal.py","file_ext":"py","file_size_in_byte":1310,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"281907120","text":"stepResponseFile = open(\"step-response.txt\", \"r\")\n\ntempValues = stepResponseFile.read().split(\"\\n\")\nnewTempValues = []\n\nfor temp in range(len(tempValues)):\n if temp % 7 == 0:\n newTempValues.append(tempValues[temp])\n\nnewStepResponses = open(\"shortened-step-response.txt\", \"w+\")\nnewStepResponses.write(str(\"\\n\".join(newTempValues)))\nnewStepResponses.close()\n","sub_path":"pidTuning/shortenStepResponse.py","file_name":"shortenStepResponse.py","file_ext":"py","file_size_in_byte":366,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"257701345","text":"\nimport string\nimport re\nfrom nltk import tokenize # evt ændr tokenizer\n\nclass Text():\n def __init__(self, text):\n assert isinstance(text, str), \"'text' must have type str.\"\n self.text = text\n self.text_without_punctuation = Text.remove_punct(self.text)\n self.tokens = self.text.split()\n self.tokens_without_punctuation = self.text_without_punctuation.split()\n self.sentences = tokenize.sent_tokenize(text)\n self.num_tokens = len(self.tokens)\n self.num_tokens_without_punctuation = len(self.tokens_without_punctuation)\n self.num_sentences = len(self.sentences)\n\n @staticmethod\n def remove_punct(text):\n return text.translate(str.maketrans('', '', string.punctuation))\n\n def __newline_to_period(self, text):\n text = re.sub(r\"\\n\", '.', text)\n text = re.sub(r\"\\.\\.+\", '. ', text)\n return text\n\n @staticmethod\n def to_text(text):\n \"\"\"\n If not of type Text, convert to Text object and return\n Otherwise, return as is.\n \"\"\"\n if not isinstance(text, Text):\n if not isinstance(text, str):\n raise TypeError(f\"'text' must have type str, not {type(text)}\")\n text = Text(text)\n return text\n","sub_path":"textdescriptives/text.py","file_name":"text.py","file_ext":"py","file_size_in_byte":1267,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"279111624","text":"#!/usr/bin/env\n\n\ndef snapfile_to_readargs(snapfile):\n \"\"\"\n given the name of a snapshot file or \n snapshot directory, return snapdir, \n snapnum, and snapshot_name for the pfh\n readers\n \"\"\"\n\n snapfile = snapfile.rstrip('/')\n if '/' not in snapfile:\n snapfile = './'+snapfile\n from os import path\n if path.isdir(snapfile):\n dodir = True\n else:\n dodir = False\n\n snapdir, snapshot_name = snapfile.rsplit('/', 1)\n snapshot_name, snapnum = snapshot_name.rsplit('_', 1)\n snapnum = int(snapnum.split('.')[0])\n\n if dodir:\n snapshot_name = 'snapshot' # otherwise, tries to open the folder as a binary\n\n return snapdir, snapnum, snapshot_name\n\n\ndef read_part_wetzel(fname, types, assign_host_coordinates=False, subselect=False, quiet=False, **kwargs):\n \"\"\"\n wrapper around :meth:`gizmo_analysis.gizmo_io.Read.read_snapshots` that takes \n in a specific filename/snapshot directory instead of the usual snapshot_values.\n\n useful for when the snapshots are unusual names or are in an unusual output \n folder. also makes sure that particle masses are always in float64, even if \n everything else is 32 bit. any kwargs are passed on to the \n :meth:`gizmo_analysis.gizmo_io.Read.read_snapshots` function.\n\n finally, has support for subselecting to a sepecific region of space:\n if subselect is not False/None, then it should be a dictionary that contains\n * type \n either \"box\" or \"sphere\" -- specifies whether you cut particles \n within a sphere or particles within a box\n * radius \n a number in the units of part that gives either half the box length \n or the radius (depending on type)\n * center \n a length 3 list-type that gives the center you want to select from. \n if not given, then assign_host_coordinates must be true.\n \n \"\"\"\n\n import gizmo_analysis as gizmo\n import utilities as ut\n from os import path, getcwd\n import numpy as np\n\n if subselect != None and subselect != False:\n assert type(subselect) == dict\n assert 'type' in subselect.keys()\n assert 'radius' in subselect.keys()\n if assign_host_coordinates == False:\n assert 'center' in subselect.keys()\n assert type(subselect['center']) == list or type(\n subselect['center']) == np.ndarray\n assert len(subselect['center']) == 3\n\n snapdir, snum, snapshot_name = snapfile_to_readargs(fname)\n if len(snapdir.split('/')) > 1:\n simulation_directory, snapshot_directory = snapdir.rsplit('/', 1)\n if not simulation_directory.startswith('/'):\n simulation_directory = getcwd() + '/' + simulation_directory\n else:\n simulation_directory = getcwd() + '/'\n snapshot_directory = snapdir\n\n if path.isfile(fname):\n myRead = gizmo.io.ReadClass(\n snapshot_name_base=snapshot_name.rsplit('_', 1)[0], quiet=quiet)\n part = myRead.read_snapshots(\n types, snapshot_values=snum, snapshot_value_kind='index',\n snapshot_directory=snapshot_directory, simulation_directory=simulation_directory,\n assign_host_coordinates=assign_host_coordinates, **kwargs)\n elif path.isdir(fname):\n myRead = gizmo.io.ReadClass(quiet=quiet)\n part = myRead.read_snapshots(\n types, snapshot_values=snum, snapshot_value_kind='index',\n snapshot_directory=snapshot_directory, simulation_directory=simulation_directory,\n assign_host_coordinates=assign_host_coordinates, **kwargs)\n else:\n raise IOError(\"{} doesn't exist\".format(fname))\n\n if subselect:\n nkept = 0\n ntossed = 0\n if subselect['type'] == 'box':\n print(\n \"Subselecting particles within a cube w/ half a side length of {}\".format(subselect['radius']))\n else:\n print(\"Subselecting particles within a sphere of radius {}\".format(\n subselect['radius']))\n\n if assign_host_coordinates:\n cen = part.host_positions[0]\n else:\n cen = subselect['center']\n\n r = subselect['radius']\n for k in part.keys():\n if subselect['type'] == 'box':\n msk = boxmsk(part[k]['position'], cen, r)\n else:\n msk = fast_dist(part[k]['position'], cen) <= r\n\n tn = np.count_nonzero(msk)\n nkept += tn\n ntossed += msk.shape[0] - tn\n\n for prop in part[k].keys():\n part[k][prop] = part[k][prop][msk]\n\n if 'convert_float32' in kwargs:\n # transform the mass back into float64 cause those have to be summed and that can cause problems\n for ptype in part:\n if 'mass' in part[ptype]:\n part[ptype]['mass'] = part[ptype]['mass'].astype(np.float64)\n return part\n\n\ndef readhead_wrapper(snapfile, verbose=False, docosmoconvert=1):\n \"\"\"\n uses :meth:`gadget_lib.readsnap.readsnap` to read a gadget file header\n\n :param string snapfile: The name of the snapshot/snapdir to read from\n :param bool verbose: Print the parsed info or not\n :param bool docosmoconvert: Passed to readsnap as cosmological, which \n tells it to convert from cosmological (comoving) coordinates to \n physical ones, and to deal with the h's as well\n\n Returns:\n dictionary read by readsnap with header information\n \"\"\"\n\n from gadget_lib.readsnap import readsnap\n snapdir, snapnum, snapshot_name = snapfile_to_readargs(snapfile)\n if verbose:\n print(\"snapdir\", snapdir)\n print(\"snapnum\", snapnum)\n print(\"snapshot_name\", snapshot_name)\n\n return readsnap(snapdir, snapnum, 1, snapshot_name=snapshot_name, h0=1, header_only=1, cosmological=docosmoconvert)\n\n\ndef readsnap_wrapper(snapfile, dmo, dogasT=False, verbose=False, docosmoconvert=1):\n \"\"\"\n uses gadget_lib.readsnap.readsnap to read the header from a gadget files\n\n :param snapfile: The name of the snapshot/snapdir to read from\n :param bool dmo: Whether to read only the dark matter or not.\n :param bool dogasT: whether or not to also return the gas temperature\n :param bool verbose: Print the parsed info or not\n :param docosmoconvert: Passed to readsnap as cosmological, which tells it to\n convert from cosmological (comoving) coordinates to physical ones, and to\n deal with the h's as well\n\n :returns:\n pos,vel, and mass for DM, gas, and stars in that order, then also gastemp if asked for\n always return gas and star data, but returns None if dmo is True\n \"\"\"\n\n from gadget_lib.readsnap import readsnap\n snapdir, snapnum, snapshot_name = snapfile_to_readargs(snapfile)\n\n if verbose:\n print(\"snapdir\", snapdir)\n print(\"snapnum\", snapnum)\n print(\"snapshot_name\", snapshot_name)\n\n if dmo:\n gpos, gvel, gmass, spos, svel, smass = None, None, None, None, None, None\n if dogasT:\n gastemp = None\n else:\n gas = readsnap(snapdir, snapnum, 0, snapshot_name=snapshot_name,\n h0=1, cosmological=docosmoconvert)\n print(\"Read gas\")\n star = readsnap(snapdir, snapnum, 4, snapshot_name=snapshot_name,\n h0=1, cosmological=docosmoconvert)\n print(\"Read star\")\n\n spos = star['p'][:]\n svel = star['v'][:]\n smass = star['m'][:]*1e10\n\n gpos = gas['Coordinates'][:]\n gvel = gas['Velocity'][:]\n gmass = gas['Masses'][:]*1e10\n if dogasT:\n gastemp = gas_temperature(gas['InternalEnergy'][:], gas['ne'][:])\n\n print(\"Starting dark read...\")\n dark = readsnap(snapdir, snapnum, 1, snapshot_name=snapshot_name,\n h0=1, cosmological=docosmoconvert)\n print(\"Read DM\")\n dpos = dark['p'][:]\n dvel = dark['v'][:]\n dmass = dark['m'][:]*1e10\n\n if dogasT:\n # then gas temperature is expected. if dmo, then I return None for it anyway\n return dpos, dvel, dmass, gpos, gvel, gmass, spos, svel, smass, gastemp\n else:\n # then gas temperature is (as default) not expected\n return dpos, dvel, dmass, gpos, gvel, gmass, spos, svel, smass\n","sub_path":"sgklibs/particle_io.py","file_name":"particle_io.py","file_ext":"py","file_size_in_byte":8318,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"317168406","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sun Sep 1 15:15:44 2019\n\n@author: yangjiang\n\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport gin\nimport tensorflow as tf\nimport tensorflow_probability as tfp\nfrom tf_agents.trajectories import policy_step\nfrom tf_agents.policies import tf_policy\n\ntfd = tfp.distributions\n\n\nclass DiscreteBoltzmannPolicyStep(policy_step.PolicyStep):\n \n def __new__(cls, policy, action_logits):\n \n self = super(DiscreteBoltzmannPolicyStep, cls).__new__(cls, policy.action, policy.state, policy.info)\n self.action_logits = action_logits\n \n return self\n\n\n@gin.configurable\nclass DiscreteBoltzmannPolicy(tf_policy.Base):\n \"\"\"Returns boltzmann samples of a given policy.\n\n The wrapped policy must expose a distribution parameterized by logits.\n \"\"\"\n\n def __init__(self, policy, temperature=1.0, name=None):\n \"\"\"Builds a BoltzmannPolicy wrapping the given policy.\n\n Args:\n policy: A policy implementing the tf_policy.Base interface, using\n a distribution parameterized by logits.\n temperature: Tensor or function that returns the temperature for sampling\n when `action` is called. This parameter applies when the action spec is\n discrete. If the temperature is close to 0.0 this is equivalent to\n calling `tf.argmax` on the output of the network.\n name: The name of this policy. All variables in this module will fall\n under that name. Defaults to the class name.\n \"\"\"\n super(DiscreteBoltzmannPolicy, self).__init__(\n policy.time_step_spec,\n policy.action_spec,\n policy.policy_state_spec,\n policy.info_spec,\n emit_log_probability=policy.emit_log_probability,\n clip=False,\n name=name)\n self._temperature = temperature\n self._wrapped_policy = policy\n\n def _variables(self):\n return self._wrapped_policy.variables()\n\n def _get_temperature_value(self):\n if callable(self._temperature):\n return self._temperature()\n return self._temperature\n\n def _apply_temperature(self, dist):\n \"\"\"Change the action distribution to incorporate the temperature.\"\"\"\n logits = dist.logits / self._get_temperature_value()\n return dist.copy(logits=logits)\n\n\n def _action(self, time_step, policy_state, seed):\n \"\"\"Implementation of `action`.\n Args:\n time_step: A `TimeStep` tuple corresponding to `time_step_spec()`.\n policy_state: A Tensor, or a nested dict, list or tuple of Tensors\n representing the previous policy_state.\n seed: Seed to use if action performs sampling (optional).\n Returns:\n A `PolicyStep` named tuple containing:\n `action`: An action Tensor matching the `action_spec()`.\n `state`: A policy state tensor to be fed into the next call to action.\n `info`: Optional side information such as action log probabilities.\n \"\"\"\n seed_stream = tfd.SeedStream(seed=seed, salt='ppo_policy')\n distribution_step = self._distribution(time_step, policy_state)\n \n action_distribution = distribution_step.action\n # distribution_step = DiscreteBoltzmannPolicyStep(distribution_step, action_distribution) \n \n actions = tf.nest.map_structure(lambda d: d.sample(seed=seed_stream()),\n distribution_step.action)\n \n info = distribution_step.info\n if self.emit_log_probability:\n try:\n log_probability = tf.nest.map_structure(lambda a, d: d.log_prob(a),\n actions,\n distribution_step.action)\n info = policy_step.set_log_probability(info, log_probability)\n except:\n raise TypeError('%s does not support emitting log-probabilities.' %\n type(self).__name__)\n \n actions = tf.concat([tf.cast(actions, tf.float32), tf.squeeze(action_distribution.probs, axis=1)], axis=-1)\n \n return distribution_step._replace(action=actions, info=info)\n\n\n\n def _distribution(self, time_step, policy_state):\n distribution_step = self._wrapped_policy.distribution(\n time_step, policy_state)\n if self._temperature is None:\n return distribution_step\n\n action_dist = tf.nest.map_structure(self._apply_temperature,\n distribution_step.action)\n return distribution_step._replace(action=action_dist)\n","sub_path":"tf_agents/policies/discrete_boltzmann_policy.py","file_name":"discrete_boltzmann_policy.py","file_ext":"py","file_size_in_byte":4511,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"447306028","text":"import numpy as np \nfrom scipy.spatial import cKDTree\nimport functools\nimport plotly.graph_objects as go \nimport math\nimport itertools\n\nPLOTTING = False\n_pi = math.pi\n\ntry:\n functools.cache\nexcept AttributeError:\n functools.cache = functools.lru_cache(None)\n\ndef _pairs(iterable):\n \"s -> (0, s0), (s0,s1), (s1,s2), (s2, s3), ...\"\n a, b = itertools.tee(iterable)\n yield 0, next(b)\n yield from zip(a, b)\n\ndef _sphere_volume(r):\n return 4 / 3 * _pi * r ** 3\n\ndef _shell_volume(r_pair):\n return _sphere_volume(r_pair[1]) - _sphere_volume(r_pair[0])\n\nclass Volume():\n def __init__(self, boundary, resolution): \n self.boundary = boundary\n self.resolution = resolution\n\n def get_shells(self, r, dr, points_per_shell):\n # TODO: use particle_per_shell quantities and not hard-coded values\n radii = np.arange(dr / 2, r, dr)\n particles_pos = []\n d_phi = np.linspace(0, _pi, 10)\n d_theta = np.linspace(0, 2*_pi, 10)\n shells = [[] for _ in range(len(radii))]\n for shell, radius in enumerate(radii):\n for n in d_theta:\n for m in d_phi:\n x = radius * np.sin(m) * np.cos(n)\n y = radius * np.sin(m) * np.sin(n)\n z = radius * np.cos(m)\n shells[shell].append([x, y, z])\n\n shell_pairs = _pairs(iter(radii))\n shell_volumes = np.fromiter(map(_shell_volume, shell_pairs), dtype=float)\n\n return [np.array(shell) for shell in shells], shell_volumes\n \n def hit_function(self, x):\n raise NotImplementedError(\n \"Volumes should implement a `hit_function`.\"\n + \" Given a point, return whether it is in the volume or not.\"\n )\n \n def _get_hit_function(self):\n return np.vectorize(self.hit_function, signature=\"(d)->()\")\n \n def total_volume(self):\n raise NotImplementedError(\n \"Volumes should implement a `total_volume`\"\n + \" which returns the global count of all the points in the grid.\"\n )\n\n\nclass Box(Volume):\n def __init__(self, side, resolution=0.2):\n self._side = side\n self._resolution = resolution\n super().__init__([[0, side]] * 3, resolution)\n\n def hit_function(self, pos):\n return np.all((pos >= 0) & (pos <= self._side))\n \n def total_volume(self):\n return self._side ** 3\n\n\nclass Sphere(Volume):\n def __init__(self, radius, resolution=0.2):\n self._resolution = resolution\n self.radius = radius\n super().__init__([[-radius, radius]] * 3, resolution)\n \n def hit_function(self, x):\n return np.sum(x ** 2) < self.radius ** 2\n\n def total_volume(self):\n return _sphere_volume(self.radius) \n\n\ndef inner_rdf(boundary, particles, r, dr):\n \"\"\"\n Computes the radial distribution function, showing the average density of other\n particles around each particle sampled in concentric shells of thickness ``dr`` within\n a maximum radius of ``r``. This function stays a distance of ``r`` away from all\n borders as it currently does not deal with border effects. It will calculate the RDF\n only for those particles located at least ``r`` away from each border.\n\n The ``particles`` argument should have an (n, k) shape where n is the amount of\n particles and k the number of dimensions.\n\n The ``boundary`` argument should have shape (k, 2) where each row is the mimimum and\n maximum of a dimension of the volume within which particles should have been placed.\n An example for 3d-data would be ``[[0, 100], [0, 200], [0, 100]]`` for a 100x200x100\n box.\n\n :param boundary: The limits for each dimension of the particles. Used to normalize to volume and exclude boundary particles.\n :type boundary: np.ndarray-like with shape (k, 2)\n :param particles: The particles to investigate.\n :type particles: np.ndarray-like with shape (n, k)\n :param r: The maximum search radius, and the boundary exclusion size\n :type r: float\n :param dr: Resolution of the RDF. Thickness of the radial shells whose particle density is the basis of the RDF.\n :type dr: float\n \"\"\"\n # We will transform the boundary to a numpy array to sanitize input and convenience,\n # but not for `particles` as this might copy this possibly very large array. Instead,\n # we expect `particles` to be given in an appropriate ndarray-like type already.\n boundary = np.array(boundary)\n if boundary.shape[0] != particles.shape[1]:\n raise Exception(\"The given boundaries do not match the dimensionality of the given particles.\")\n search_box = boundary.copy()\n # Shrink the search box to within the maximum search radius to avoid border effects\n # This does mean that the radial distribution of particles in this border region is\n # not examined. See #1 for future implementation of the overlap library to fix this.\n search_box[:, 0] += r\n search_box[:, 1] -= r\n # Find all the reference particles that fall within the shrunken bounds and won't\n ref = _within(particles, search_box)\n tree = cKDTree(particles)\n # Query the tree for the neighbours within radius r of all the reference particles.\n all_neighbours = tree.query_ball_point(particles[ref], r=r)\n # Create an iterator that turns the reference id into the particle id and the\n # neighbour list into a neighbour np.ndarray\n nbr_iter = map(lambda x: (ref[x[0]], np.array(x[1])), enumerate(all_neighbours))\n # A local function that turns neighbour ids into distances and excludes the query\n # particle with id `me`, using the `particles` of this function call scope.\n def dist_excl_self(me, my_nbr):\n offsets = particles[my_nbr[my_nbr != me]] - particles[me]\n return np.sqrt(np.sum(offsets ** 2, axis=1))\n # Concatenate all the distances of all the neighbours of all the reference points\n # together\n all_distances = np.concatenate(tuple(dist_excl_self(me, my_nbr) for me, my_nbr in nbr_iter))\n # Bin them in `dr` sized bins\n radial_bins = np.bincount(np.floor(all_distances / dr).astype(int))\n # Normalize the result to the amount of reference points were tested\n trials = len(ref)\n # Normalize the bins to the volume of the shell that corresponds to the radial bin\n radii = np.arange(0, len(radial_bins) * dr, dr)\n inner_volumes = 4 / 3 * np.pi * radii ** 3\n outer_volumes = 4 / 3 * np.pi * (radii + dr) ** 3\n bin_volumes = outer_volumes - inner_volumes\n # Normalize the result to the density of the particles\n density = len(particles) / np.product(np.abs(np.diff(boundary, axis=1)))\n # Return the normalized radial distribution\n return radial_bins / trials / bin_volumes / density\n\n\ndef volume_rdf(volume, particles, r, dr, shell_points=100):\n \"\"\"\n Computes the radial distribution function, showing the average density of other\n particles around each particle sampled in concentric shells of thickness ``dr`` within\n a maximum radius of ``r``. This function stays a distance of ``r`` away from all\n borders as it currently does not deal with border effects. It will calculate the RDF\n only for those particles located at least ``r`` away from each border.\n\n The ``particles`` argument should have an (n, k) shape where n is the amount of\n particles and k the number of dimensions.\n\n The ``boundary`` argument should have shape (k, 2) where each row is the mimimum and\n maximum of a dimension of the volume within which particles should have been placed.\n An example for 3d-data would be ``[[0, 100], [0, 200], [0, 100]]`` for a 100x200x100\n box.\n\n :param boundary: The limits for each dimension of the particles. Used to normalize to volume and exclude boundary particles.\n :type boundary: np.ndarray-like with shape (k, 2)\n :param particles: The particles to investigate.\n :type particles: np.ndarray-like with shape (n, k)\n :param r: The maximum search radius, and the boundary exclusion size\n :type r: float\n :param dr: Resolution of the RDF. Thickness of the radial shells whose particle density is the basis of the RDF.\n :type dr: float\n :param shell_points: Volume grid points to investigate per shell.\n :type shell_points: int\n \"\"\"\n tree = cKDTree(particles)\n # Query the tree for the neighbours within radius r of all the reference particles.\n print(\"Querying ball points\")\n all_neighbours = tree.query_ball_point(particles, r=r)\n print(\"Ball points retrieved\")\n density = len(particles) / volume.total_volume()\n\n radii = np.concatenate((np.arange(dr, r, dr), [r]))\n bin_densities = np.zeros(len(radii))\n shells, shell_volumes = volume.get_shells(r, dr, shell_points)\n hit_func = volume._get_hit_function()\n \n print(\"Shells retrieved: len {}\".format(len(shells)))\n\n print(\"Iterating over particles\")\n for index, (origin, neighbours) in enumerate(zip(particles, all_neighbours)):\n print(f\"Computing a new particle's density ({index}, {origin}) with {len(neighbours) - 1} neighbours.\")\n neighbours_pos = particles[neighbours]\n prev_n = 0\n bins = np.empty(len(radii))\n for id, sr, shell, shell_volume in zip(itertools.count(), radii, shells, shell_volumes):\n # Count how much of the volume around `origin` is inside the user volume.\n occupancy = np.count_nonzero(hit_func(shell + origin)) / shell_points\n # Multiply by the volume of the shell we are investigating, for normalization.\n shell_v = shell_volume * occupancy\n # Count how many of the points are within `shell` distance from `origin`.\n n = np.count_nonzero(np.sum((neighbours_pos - origin) ** 2, axis=1) < sr ** 2)\n # Don't count points that are members of the smaller (previous) shells.\n shell_n = n - prev_n\n if id == 0:\n # Exclude the query point itself, which will be found in the first bin.\n shell_n -= 1\n prev_n = n\n assert shell_n >= 0, \"negative neighbours\"\n assert shell_volume > 0, \"negative shell volume\"\n assert occupancy > 0 and occupancy <= 1, \"weird occupancy\"\n bins[id] = shell_n / shell_v\n\n bin_densities += bins\n\n # Normalize the accumulated results by amount of points investigated, and by global density.\n return np.array(bin_densities) / len(particles) / density\n\n\ndef _within(particles, boundary):\n within = None\n for _dim, (low, high) in enumerate(boundary):\n dim = particles[:, _dim]\n mask = (dim >= low) & (dim <= high)\n if within is not None:\n mask = mask & within\n within = mask\n return np.nonzero(within)[0]","sub_path":"radialdf/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":10769,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"116963323","text":"n, m = map(int, input().split())\n\nac = [0]*(n+1)\nwa = [0]*(n+1)\n\nfor _ in range(m):\n a, b = input().split()\n a = int(a)\n if b == 'AC':\n ac[a] = 1\n else: \n if ac[a] == 0:\n wa[a] = wa[a] + 1\n\nfor i in range(n+1):\n wa[i] = wa[i] * ac[i]\n\nprint(sum(ac), sum(wa))\n\n","sub_path":"atcoder.jp/abc151/abc151_c/Main.py","file_name":"Main.py","file_ext":"py","file_size_in_byte":300,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"251325645","text":"\"\"\"\nContains function relating to the lazy evaluation of the file tree.\n\"\"\"\nimport os\nimport fnmatch\n\nimport pypix\nfrom error_message import display_error_message\n\n# Maps a file extension to the filetype\nfiletype_table = {\".lsc\": \"lsc\", \".ascii\": \"ascii_matrix\", \".txt\": \"ascii_matrix\"}\n\ndef ext_pattern_to_filetype(extension_pattern):\n \"\"\"\n Returns a guess of the filetype of an extension patter\n \"\"\"\n for extension in filetype_table:\n if extension_pattern.endswith(extension):\n return filetype_table[extension]\n return None\n\nclass FolderNode():\n \"\"\"\n A folder node contains a number of FolderNodes (subfolders) and FrameNodes\n (frame files).\n \"\"\"\n def __init__(self, path):\n self.path = os.path.abspath(path)\n self.sub_folders = []\n self.sub_frames = []\n self.expanded = False\n self.aggregate_frame = None\n\n def get_children(self, extension_pattern):\n \"\"\"\n Queries the file system for child folders and child frames.\n\n Returns a 2-element tuple. The first element of the tuple contains a\n list of FolderNodes (subfolders) and the seconf element contains a list\n of FrameNodes (frames files).\n \"\"\"\n if not (self.sub_folders or self.sub_frames):\n for item in os.listdir(self.path):\n item_path = os.path.join(self.path, item)\n # If it is a folder add it to the tree\n if os.path.isdir(item_path):\n self.sub_folders.append(FolderNode(item_path))\n # If it is a frame with the correct extension pattern add it to the tree\n elif fnmatch.fnmatch(item, extension_pattern):\n new_frame = FrameNode(item_path, extension_pattern)\n if new_frame.loaded_correctly: # If it loaded correctly\n self.sub_frames.append(new_frame)\n return self.sub_folders, self.sub_frames\n\n def calculate_aggregate(self, extension_pattern):\n \"\"\"\n Calculates the aggregate frame from a depth-first inspection of the file\n tree.\n\n Returns the aggregate frame\n \"\"\"\n aggregate_frame = pypix.Frame(256, 256)\n self.get_children(extension_pattern)\n # For each sub_folder call its aggregate method and add its\n # clusters/pixels to the aggregate frame\n for folder_path in self.sub_folders:\n folder_frame = folder_path.calculate_aggregate(extension_pattern)\n aggregate_frame.clusters += folder_frame.clusters\n for pixel in folder_frame.hit_pixels:\n aggregate_frame[pixel] = pypix.Hit(aggregate_frame[pixel].value\n + folder_frame[pixel].value)\n # For each sub frame calculate its clusters if not already calculated\n # and add these clusters (and the frame's pixels) to the aggregate frame\n for frame_file in self.sub_frames:\n frame = frame_file.frame\n if not frame.clusters:\n frame.calculate_clusters()\n aggregate_frame.clusters += frame.clusters\n for pixel in frame.hit_pixels:\n aggregate_frame[pixel] = pypix.Hit(aggregate_frame[pixel].value\n + frame[pixel].value)\n return aggregate_frame\n\n @property\n def name(self):\n \"\"\"\n Returns the filename of the folder.\n \"\"\"\n return os.path.basename(self.path)\n\nclass FrameNode():\n \"\"\"\n Contains a frame and is responsible for its loading.\n \"\"\"\n def __init__(self, path, extension_pattern):\n self.path = path\n self.loaded_correctly = True\n try:\n self.frame = pypix.Frame.from_file(os.path.abspath(path), ext_pattern_to_filetype(extension_pattern))\n except:\n display_error_message(\"Error Reading File\", \"Couldn't read file: %s \\nPlease ensure that it is a correctly formatted file. You may need to map the extension to the file type in the `filetype` dict in folder.py.\" % path)\n raise\n self.loaded_correctly = False\n return\n\n @property\n def name(self):\n \"\"\"\n Returns the filename of the frame.\n \"\"\"\n return os.path.basename(self.path)\n","sub_path":"crayfish/folder.py","file_name":"folder.py","file_ext":"py","file_size_in_byte":4318,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"640695560","text":"n = int(input())\nprogram = []\nfor i in range(n):\n program.append([c for c in input()])\n\nx, y, exit_p, stack, con_out, dr, string_mode = 0, 0, False, [], \"\", 0, False\nd = [[0, 1], [1, 0], [0, -1], [-1, 0]]\n\nwhile not exit_p:\n c = program[x][y]\n if c == '\"':\n string_mode = not string_mode\n elif string_mode:\n stack.append(ord(c))\n elif c == ' ':\n pass\n elif c == 'E':\n exit_p = True\n elif c == '>':\n dr = 0\n elif c == '<':\n dr = 2\n elif c == '^':\n dr = 3\n elif c == 'v':\n dr = 1\n elif c == 'S':\n x, y = x + d[dr][0], y + d[dr][1]\n elif c.isdigit():\n stack.append(int(c))\n elif c == '+':\n b, a = stack.pop(), stack.pop()\n stack.append(a + b)\n elif c == '-':\n b, a = stack.pop(), stack.pop()\n stack.append(a - b)\n elif c == '*':\n b, a = stack.pop(), stack.pop()\n stack.append(a * b)\n elif c == 'P':\n stack.pop()\n elif c == 'X':\n b = stack.pop()\n a = stack.pop()\n stack.append(b)\n stack.append(a)\n elif c == 'D':\n stack.append(stack[-1])\n elif c == '_':\n if stack.pop() == 0:\n dr = 0\n else:\n dr = 2\n elif c == '|':\n if stack.pop() == 0:\n dr = 1\n else:\n dr = 3\n elif c == 'I':\n con_out += str(stack.pop())\n elif c == 'C':\n con_out += str(chr(stack.pop()))\n\n x, y = x + d[dr][0], y + d[dr][1]\n\nprint(con_out)\n","sub_path":"practice/puzzles/medium/CGFunge interpreter.py","file_name":"CGFunge interpreter.py","file_ext":"py","file_size_in_byte":1512,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"288627336","text":"'''\nCreated on Jan 13, 2016\n\n@author: rajeev.kumar\nDescription:While deploying a service, if the Admin selects Deploy Now, the \ndeployment starts immediately.\nTest Flow :1)Login as a Admin user\n 2)create Template & Deploy a service with Deploy now options.\n'''\nfrom tests.globalImports import *\n\ntc_id=utility.get_tc_data(__file__)\n\nclass Testcase(Manager.Manager): \n \"\"\"\n deploying a service, if the Admin selects Deploy Now, the deployment starts\n immediately.\n \"\"\"\n \n def __init__(self, *args, **kwargs):\n \"\"\"\n Initialization\n \"\"\"\n Manager.Manager.__init__(self, tc_id, *args, **kwargs)\n \n \n @BaseClass.TestBase.func_exec\n def test_functionality(self): \n \"\"\"\n This is the execution starting function\n \"\"\"\n self.browserObject = globalVars.browserObject\n \n #Check for current logged in user\n self.verifyCurrentUser(userRole='Administrator', loginAsUser=True)\n #check service device console\n status = self.get_check_DeployServices_Now(\"Administrator\")\n \n self.logout()","sub_path":"GUI/gui-automation-ASMvNext84UI/tests/rbac/Testcase_NGI_TC_3256.py","file_name":"Testcase_NGI_TC_3256.py","file_ext":"py","file_size_in_byte":1122,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"555012099","text":"from django.shortcuts import render\n\n# Create your views here.\nfrom django_redis import get_redis_connection\nfrom rest_framework.permissions import IsAuthenticated\nfrom rest_framework.response import Response\nfrom rest_framework.views import APIView\n\nfrom carts.serializers import CartsSerializer, TotalNumberSerializer, CartsDetailSerializer, CartsDeleteSerializer, SelestAllSerializer\nfrom goods.models import Goods\n\n\n\"\"\"\n由于前端发送了jwt验证,则执行视图前系统会调用perform_authentication函数进行登陆验证,没有登陆无法访问,所以后端不需要在验证,只需加权限即可\n\"\"\"\n\nclass CartsView(APIView):\n #登陆后才能访问\n permission_classes = (IsAuthenticated,)\n def post(self, request):\n # 获取请求参数\n user = request.user\n # 获取序列化对象\n # print(user)\n # print(request.data)\n cart_ser = CartsSerializer(data=request.data)\n # 调用序列化对象的方法检验数据(其实上一步跟着一步的意义就是检验数据,上一步是字段检验这一步是逻辑检验)\n cart_ser.is_valid(raise_exception=True)\n # 当前段传过来的数据没问题是就到redis中进行存储\n sku_id = cart_ser.validated_data.get('id')\n count = cart_ser.validated_data.get('count')\n selected = cart_ser.validated_data.get('selected')\n # 连接redis\n redis_conn = get_redis_connection('cart')\n # redis中存储数据\n redis_conn.hincrby('cart_%s' % user.id, sku_id, count)\n if selected:\n redis_conn.sadd('cart_selected_%s' % user.id, sku_id)\n\n data = {\n \"errno\":200,\n \"errmsg\":\"成功\"\n }\n return Response(data)\n\n # 展示购物车中数据\n def get(self, request):\n user = request.user\n # 连接redis\n redis_conn = get_redis_connection('cart')\n # 从集合中获取所有商品\n goods_dict = redis_conn.hgetall('cart_%s' % user.id)\n select_goods = redis_conn.smembers('cart_selected_%s' % user.id)\n carts = {}\n for sku_id, count in goods_dict.items():\n carts[int(sku_id)] = {\n 'count': int(count),\n 'selected': sku_id in select_goods\n }\n # 查询购物车中所有的商品\n all_goods = Goods.objects.filter(id__in=carts.keys())\n select_count = 0\n for goods in all_goods:\n goods.count = carts[goods.id]['count']\n goods.selected = carts[goods.id]['selected']\n goods.total_price = goods.sell_price*goods.count\n if goods.selected:\n select_count = select_count + goods.count\n cartdetailser = CartsDetailSerializer(all_goods, many=True)\n data = {\n 'goods':cartdetailser.data,\n 'total_count':select_count,\n 'freight':20\n }\n return Response(data)\n\n def put(self, request):\n \"\"\"\n 修改购物车数据\n \"\"\"\n # 校验参数\n serializer = CartsSerializer(data=request.data)\n serializer.is_valid(raise_exception=True)\n # 获取校验后的参数\n id = serializer.validated_data.get('id')\n count = serializer.validated_data.get('count')\n selected = serializer.validated_data.get('selected')\n user = request.user\n # 在redis中保存\n redis_conn = get_redis_connection('cart')\n # 修改商品数量\n redis_conn.hset('cart_%s' % user.id, id, count)\n # 修改商品的勾选状态\n if selected:\n redis_conn.sadd('cart_selected_%s' % user.id, id)\n else:\n redis_conn.srem('cart_selected_%s' % user.id, id)\n return Response(serializer.data)\n\n def delete(self, request):\n \"删除一条数据\"\n user = request.user\n delete_ser = CartsDeleteSerializer(data=request.data)\n delete_ser.is_valid(raise_exception=True)\n delete_all = delete_ser.validated_data.get('delete_all')\n if delete_all:\n redis_conn = get_redis_connection('cart')\n hkeys = redis_conn.hkeys('cart_%s' % user.id)\n skeys = redis_conn.smembers ('cart_selected_%s' % user.id)\n try:\n redis_conn.hdel('cart_%s' % user.id, *hkeys)\n redis_conn.srem('cart_selected_%s' % user.id, *skeys)\n errno = 204\n errmsg = \"删除成功\"\n except:\n errno = 401\n errmsg = \"删除失败\"\n data = {\n \"errno\": errno,\n \"errmsg\": errmsg\n }\n return Response(data=data)\n\n else:\n id = request.data['id']\n redis_conn = get_redis_connection('cart')\n try:\n redis_conn.hdel('cart_%s' % user.id, id)\n redis_conn.srem('cart_selected_%s' % user.id, id)\n errno = 204\n errmsg = \"删除成功\"\n except:\n errno = 401\n errmsg = \"删除失败\"\n data = {\n \"errno\":errno,\n \"errmsg\":errmsg\n }\n return Response(data=data)\n\n\n# 获取购物车中商品总数量\nclass TotalNumbersView(APIView):\n # 登陆后才能访问\n permission_classes = (IsAuthenticated,)\n def get(self, request):\n # 获取用户信息\n user = request.user\n # 连接redis\n redis_conn = get_redis_connection('cart')\n # redis中存储数据\n keys = redis_conn.hkeys('cart_%s' % user.id)\n sets = redis_conn.smembers('cart_selected_%s' % user.id)\n number = 0\n for key in sets:\n if key in keys:\n value = redis_conn.hget('cart_%s' % user.id, key)\n number = number + int(value.decode())\n data ={\n \"total\":number\n }\n total_ser = TotalNumberSerializer(data=data)\n total_ser.is_valid(raise_exception=True)\n return Response(total_ser.validated_data)\n\n# 全选与全不选\nclass SelectAllView(APIView):\n # 登陆后才能访问\n permission_classes = (IsAuthenticated,)\n def put(self, request):\n user = request.user\n select_all_ser = SelestAllSerializer(data=request.data)\n select_all_ser.is_valid(raise_exception=True)\n # is_selected = request.data[\"is_selected_all\"]\n # 这一这个跟上面那个得到的数据是有差别的,这个的得到的是bool值,上面得到的是字符串\n is_selected = select_all_ser.validated_data[\"is_selected_all\"]\n # 连接redis\n redis_conn = get_redis_connection('cart')\n # 获取哈希种所有键(即商品id)\n key_list = redis_conn.hkeys('cart_%s' % user.id)\n # 如果已经全部选择就不处理\n key_set = redis_conn.smembers('cart_selected_%s' % user.id)\n if len(key_set) == len(key_list):\n data = {\n \"errno\": 200,\n \"errmsg\": \"操作成功\"\n }\n return Response(data=data)\n if is_selected:\n redis_conn.sadd('cart_selected_%s' % user.id, *key_list)\n else:\n redis_conn.srem('cart_selected_%s' % user.id, *key_list)\n data = {\n \"errno\": 204,\n \"errmsg\": \"操作成功\"\n\n }\n return Response(data=data)\n\n","sub_path":"cms/cms/apps/carts/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":7435,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"33693666","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nimport networkx as nx\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n# 関数定義\n# 引数は隣接リスト(list),表示するノード数(int),ノードの大きさを決��る関数(func),ノード間の反発力(float:0~1.0), 保存するファイル名保存しない場合は'NULL'(char)\ndef OutputNGraph(network_list, max_size, weight_func, dist, file_name):\n # ネットワークの大きさ\n network_size = len(network_list)\n\n # グラフの宣言\n TestGraph = nx.Graph()\n\n # ノードの追加.属性はなしなのでリストによる番号指定.\n TestGraph.add_nodes_from(np.arange(network_size))\n\n # リスト内のエッジ情報を追加\n for i in np.arange(network_size):\n for j in network_list[i]:\n TestGraph.add_edge(i, j)\n\n # max_size個のノードを取り出しそのグラフを取得する\n # 今回はネットワーク成長開始からmax_size個のグラフとしている\n sample_list = range(max_size, network_size)\n for item in sample_list:\n TestGraph.remove_node(item)\n\n # ネットワークの大きさを更新\n network_size = max_size\n\n # 各ノードの次数を格納するリスト\n node_degree = []\n for i in range(network_size):\n node_degree.append(TestGraph.degree(i))\n\n DrawGraph(TestGraph, node_degree, weight_func, dist, file_name)\n\n\n\n# 次数が大きい順にグラフにかき出す関数\ndef OutputNGraphDescend(network_list, max_size, weight_func, dist, file_name):\n # ネットワークの大きさ\n network_size = len(network_list)\n #print(network_size)\n #print(max_size)\n # グラフの宣言\n TestGraph = nx.Graph()\n\n # ノードの追加.属性はなしなのでリストによる番号指定.\n TestGraph.add_nodes_from(np.arange(network_size))\n\n # リスト内のエッジ情報を追加\n for i in np.arange(network_size):\n for j in network_list[i]:\n TestGraph.add_edge(i, j)\n\n # 次数リスト作成\n # 各ノードの次数を格納するリスト\n node_degree = []\n for i in range(network_size):\n node_degree.append(TestGraph.degree(i))\n\n\n # 削除するノードを決める.\n # if (network_size != max_size):\n if (network_size > max_size):\n count = 1\n delite_node = []\n while True:\n for j in np.arange(network_size):\n if count == node_degree[j]:\n delite_node.append(j)\n if len(delite_node) == network_size - max_size:\n break\n else:\n count = count + 1\n continue\n break\n\n # ノード削除\n for item in delite_node:\n TestGraph.remove_node(item)\n\n # 次数リスト整形\n #dellist(node_degree, delite_node)\n\n # 各ノードの次数を格納するリスト\n node_degree = []\n for item in TestGraph.nodes():\n node_degree.append(TestGraph.degree(item))\n\n\n DrawGraph(TestGraph, node_degree, weight_func, dist, file_name)\n\n\n# 次数が小さい順にグラフにかき出す関数\ndef OutputNGraphAscend(network_list, max_size, weight_func, dist, file_name):\n # ネットワークの大きさ\n network_size = len(network_list)\n #print(network_size)\n #print(max_size)\n # グラフの宣言\n TestGraph = nx.Graph()\n\n # ノードの追加.属性はなしなのでリストによる番号指定.\n TestGraph.add_nodes_from(np.arange(network_size))\n\n # リスト内のエッジ情報を追加\n for i in np.arange(network_size):\n for j in network_list[i]:\n TestGraph.add_edge(i, j)\n\n # 次数リスト作成\n # 各ノードの次数を格納するリスト\n node_degree = []\n for i in range(network_size):\n node_degree.append(TestGraph.degree(i))\n\n\n # 削除するノードを決める.\n # if (network_size != max_size):\n if (network_size > max_size):\n count = np.max(node_degree)\n delite_node = []\n while True:\n for j in np.arange(network_size):\n if count == node_degree[j]:\n delite_node.append(j)\n if len(delite_node) == network_size - max_size:\n break\n else:\n count = count - 1\n continue\n break\n\n # ノード削除\n for item in delite_node:\n TestGraph.remove_node(item)\n\n # 次数リスト整形\n #dellist(node_degree, delite_node)\n\n # 各ノードの次数を格納するリスト\n node_degree = []\n for item in TestGraph.nodes():\n # 重み0に対応するため+1するよ\n node_degree.append(TestGraph.degree(item)+1)\n\n DrawGraph(TestGraph, node_degree, weight_func, dist, file_name)\n\n\n\ndef DrawGraph(Graph, node_degree, weight_func, dist, file_name):\n # ノードの重みを格納するリスト\n node_weight = weight_func(np.array(node_degree))\n # print(node_weight)\n node_weight = np.ndarray.tolist(node_weight)\n\n # グラフ定義.���きさは適宜変更可能\n plt.figure(figsize=(10,10))\n\n # ノードの位置決定.kでノードごとの反発力\n pos = nx.spring_layout(Graph, k = dist)\n\n # ノードを描画.色,透明度は適宜調整\n nx.draw_networkx_nodes(Graph, pos, alpha = 0.7,node_size=node_weight)\n # エッジを描画.色,透明度は適宜調整\n nx.draw_networkx_edges(Graph, pos, width=1, alpha = 0.7, edge_color = 'b')\n plt.axis(\"off\")\n\n if file_name != 'NULL':\n plt.savefig(file_name)\n plt.show()\n\n\n\ndef dellist(items, indexes):\n for index in sorted(indexes, reverse=True):\n del items[index]\n","sub_path":"distribution/src/networkx_func.py","file_name":"networkx_func.py","file_ext":"py","file_size_in_byte":5835,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"59817400","text":"import os\nimport csv\nimport numpy\nimport warnings\nimport ipaddress\nimport numpy as np\nfrom .flow import Flow\nfrom pickle import load\nfrom collections import defaultdict\nfrom scapy.sessions import DefaultSession\nfrom pathlib import Path, PureWindowsPath\nfrom tensorflow.keras.models import load_model\nfrom .features.context.packet_direction import PacketDirection\nfrom .features.context.packet_flow_key import get_packet_flow_key\n\nos.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'\n\nEXPIRED_UPDATE = 40\nMACHINE_LEARNING_API = \"http://localhost:8000/predict\"\n\n\nclass FlowSession(DefaultSession):\n \"\"\"Creates a list of network flows.\"\"\"\n\n def __init__(self, *args, **kwargs):\n self.flows = {}\n self.csv_line = 0\n\n if self.output_mode == \"flow\":\n output = open(self.output_file, \"w\")\n self.csv_writer = csv.writer(output)\n\n self.packets_count = 0\n\n self.clumped_flows_per_label = defaultdict(list)\n\n super(FlowSession, self).__init__(*args, **kwargs)\n\n def toPacketList(self):\n # Sniffer finished all the packets it needed to sniff.\n # It is not a good place for this, we need to somehow define a finish signal for AsyncSniffer\n self.garbage_collect(None)\n return super(FlowSession, self).toPacketList()\n\n def on_packet_received(self, packet):\n count = 0\n direction = PacketDirection.FORWARD\n\n if self.output_mode != \"flow\":\n if \"IP\" not in packet:\n return\n\n self.packets_count += 1\n\n # Creates a key variable to check\n packet_flow_key = get_packet_flow_key(packet, direction)\n flow = self.flows.get((packet_flow_key, count))\n\n # If there is no forward flow with a count of 0\n if flow is None:\n # There might be one of it in reverse\n direction = PacketDirection.REVERSE\n packet_flow_key = get_packet_flow_key(packet, direction)\n flow = self.flows.get((packet_flow_key, count))\n\n if flow is None:\n # If no flow exists create a new flow\n direction = PacketDirection.FORWARD\n flow = Flow(packet, direction)\n packet_flow_key = get_packet_flow_key(packet, direction)\n self.flows[(packet_flow_key, count)] = flow\n\n elif (packet.time - flow.latest_timestamp) > EXPIRED_UPDATE:\n # If the packet exists in the flow but the packet is sent\n # after too much of a delay than it is a part of a new flow.\n expired = EXPIRED_UPDATE\n while (packet.time - flow.latest_timestamp) > expired:\n count += 1\n expired += EXPIRED_UPDATE\n flow = self.flows.get((packet_flow_key, count))\n\n if flow is None:\n flow = Flow(packet, direction)\n self.flows[(packet_flow_key, count)] = flow\n break\n\n elif (packet.time - flow.latest_timestamp) > EXPIRED_UPDATE:\n expired = EXPIRED_UPDATE\n while (packet.time - flow.latest_timestamp) > expired:\n\n count += 1\n expired += EXPIRED_UPDATE\n flow = self.flows.get((packet_flow_key, count))\n\n if flow is None:\n flow = Flow(packet, direction)\n self.flows[(packet_flow_key, count)] = flow\n break\n\n flow.add_packet(packet, direction)\n\n if self.packets_count % 100 == 0 or (\n flow.duration > 120 and self.output_mode == \"flow\"\n ):\n # print(\"Packet count: {}\".format(self.packets_count))\n self.garbage_collect(packet.time)\n\n def get_flows(self) -> list:\n return self.flows.values()\n\n def garbage_collect(self, latest_time) -> None:\n # TODO: Garbage Collection / Feature Extraction should have a separate thread\n # print(\"Garbage Collection Began. Flows = {}\".format(len(self.flows)))\n keys = list(self.flows.keys())\n for k in keys:\n flow = self.flows.get(k)\n\n if (\n latest_time is None\n or latest_time - flow.latest_timestamp > EXPIRED_UPDATE\n or flow.duration > 90\n ):\n data = flow.get_data()\n data = predict(data)\n\n # POST Request to Model API\n # if self.url_model:\n # payload = {\n # \"columns\": list(data.keys()),\n # \"data\": [list(data.values())],\n # }\n # post = requests.post(\n # self.url_model,\n # json=payload,\n # headers={\n # \"Content-Type\": \"application/json; format=pandas-split\"\n # },\n # )\n # resp = post.json()\n # result = resp[\"result\"].pop()\n # if result == 0:\n # # benign_threshold = 0.9\n # # if resp[\"probability\"][0][result] < benign_threshold:\n # # result_print = \"Malicious\"\n # # else:\n # # result_print = \"Benign\"\n # result_print = \"Benign\"\n # else:\n # result_print = \"Malicious\"\n\n\n\n if self.csv_line == 0:\n self.csv_writer.writerow(data.keys())\n\n self.csv_writer.writerow(data.values())\n self.csv_line += 1\n #print(\"CIC: \" + str(data))\n\n\n\n del self.flows[k]\n # print(\"Garbage Collection Finished. Flows = {}\".format(len(self.flows)))\n\n\ndef predict(data):\n #data = request.get_json()\n features = ['flow_duration', 'fwd_pkt_len_max', 'fwd_pkt_len_min', 'fwd_pkt_len_std', 'flow_iat_mean',\n 'flow_iat_max', 'fwd_iat_mean', 'fwd_iat_max', 'fwd_header_len', 'fwd_pkts_s', 'pkt_len_min',\n 'pkt_len_max', 'pkt_len_std', 'ack_flag_cnt', 'pkt_size_avg', 'fwd_header_len', 'subflow_fwd_byts',\n 'init_fwd_win_byts', 'fwd_seg_size_min', ]\n labels = ['DNS', 'LDAP', 'MSSQL', 'NTP', 'NetBIOS', 'Portmap', 'SNMP', 'SSDP', 'Syn', 'TFTP', 'UDP', 'UDPLag',\n 'WebDDoS']\n\n xTest = []\n for feature in features:\n if feature in data:\n try:\n x = float(data[feature])\n xTest.append(data[feature])\n except:\n warnings.warn(\"Invalid type: Feature \"+feature+ \" = \"+data[feature]+\" has type \"+type(data[feature]))\n\n binary_model_path = PureWindowsPath('model/output/ML_binary_classifier_model')\n binary_model_path = Path(binary_model_path)\n\n category_model_path = PureWindowsPath('model/output/ML_category_classifier_model')\n category_model_path = Path(category_model_path)\n\n scaler_path = PureWindowsPath('model/scaler.pkl')\n scaler_path = Path(scaler_path)\n scaler = load(open(scaler_path, 'rb'))\n xTest = scaler.transform(numpy.array(xTest).reshape(1, -1))\n\n\n model = load_model(binary_model_path)\n\n prob = model(xTest).numpy()\n prediction = np.argmax(model(xTest), axis=1)\n if prediction == 0:\n data['MALICIOUS'] = None\n for i in range(len(labels)):\n data[labels[i]] = None\n return data\n elif prediction == 1:\n print(\"Phát hiện tấn công: \"+ str(round(prob[0][1]*100,2)) + \"%\")\n\n data['MALICIOUS'] = prob[0][1]\n model = load_model(category_model_path)\n prob = model(xTest).numpy()\n prediction = np.argmax(model(xTest), axis=1)\n\n if not len(prediction) == 1:\n warnings.warn(\"NOT SINGLE PREDICTION\")\n return data\n\n\n for i in range(len(labels)):\n data[labels[i]] = prob[0][i]\n print('\\x1b[6;30;42m' + labels[prediction[0]] + '\\x1b[0m')\n\n probs = prob[0]\n n = len(labels)\n idx = np.argsort(probs)[::-1][:n]\n\n probs = np.array(probs)[idx]\n labels = np.array(labels)[idx]\n\n for i in range(len(labels)):\n print(labels[i]+': '+str(round(probs[i]*100,2))+'%',end =\" \")\n print(\"Data\")\n print(data)\n print(\"**********************\")\n\n\n\n return data\n\ndef generate_session_class(output_mode, output_file, url_model):\n return type(\n \"NewFlowSession\",\n (FlowSession,),\n {\n \"output_mode\": output_mode,\n \"output_file\": output_file,\n \"url_model\": url_model,\n },\n )\n","sub_path":"cicflowmeter/request_url.py","file_name":"request_url.py","file_ext":"py","file_size_in_byte":8689,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"185502849","text":"# -*- coding: utf-8 -*-\n\"\"\"Exercise 3.\n\nRidge Regression\n\"\"\"\n\nimport numpy as np\n\n\ndef ridge_regression(y, tx, lambda_):\n \"\"\"implement ridge regression.\"\"\"\n weights = np.linalg.inv(tx.T @ tx + lambda_ * 2 * np.shape(y)[0]* np.eye(np.shape(tx)[1])) @ tx.T @ y\n loss = rms_error_ridge(weights, y, tx, lambda_)\n return loss, weights\n\ndef rms_error_ridge(weights, y, x, lambda_):\n loss = 1/np.shape(x)[0]*(y - x @ weights).T @ (y - x @ weights) + lambda_ * weights.T @ weights\n return np.sqrt(2*loss)\n\n\ndef ridge_regression_demo(x, y, degree, ratio, seed):\n \"\"\"ridge regression demo.\"\"\"\n # define parameter\n lambdas = np.logspace(-3, 0, 20)\n\n train_data, test_data = split_data(x, y, ratio)\n\n x_train_poly = build_poly(train_data[1], degree)\n x_test_poly = build_poly(test_data[1], degree)\n\n rmse_tr = []\n rmse_te = []\n for ind, lambda_ in enumerate(lambdas):\n rmse_train, weights = ridge_regression(train_data[0], x_train_poly, lambda_)\n rmse_tr.append(rmse_train)\n rmse_test = rms_error_ridge(weights, test_data[0], x_test_poly, lambda_)\n rmse_te.append(rmse_test)\n print(\n \"proportion={p}, degree={d}, lambda={l:.6f}, Training RMSE={tr:.3f}, Testing RMSE={te:.3f}\".format(\n p=ratio, d=degree, l=lambda_, tr=rmse_tr[ind], te=rmse_te[ind]))\n\n # Plot the obtained results\n plot_train_test(rmse_tr, rmse_te, lambdas, degree)\n\n","sub_path":"labs/ex04/template/ridge_regression.py","file_name":"ridge_regression.py","file_ext":"py","file_size_in_byte":1425,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"21791606","text":"# firkecs trace module\n\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nimport phenomics.traces.utils as phut\n\nMEASUREMENT_ID = 'firkecs'\n\ndef get_measurement_id():\n ''' Simply returns the MEASUREMENT_ID.\n Returns:\n str : MEASUREMENT_ID\n \n '''\n \n return MEASUREMENT_ID\n\ndef pull_file(t_file):\n ''' Function to read the correct data from a raw file.\n \n Receives: \n str : path to file\n Returns:\n dict : trace_data{time : floats, values : floats}\n \n For IDEAspec raw files this means the first and last\n columns.\n '''\n \n t_data = np.loadtxt(t_file)\n trace = {'time' : t_data[:,0], 'values' : t_data[:,-1] }\n return trace\n\ndef get_preprocess_order():\n ''' Function to simply return the names of preprocessing methods in order.\n \n '''\n \n return []\n\n\ndef show_trace(data, title):\n ''' Makes a plot of the firkecs data.\n \n Receives:\n numpy.array : data[time, values]\n str : title of figure\n Returns:\n True\n \n '''\n plt.plot(data[:,0], data[:,1])\n plt.title(title )\n plt.show()\n\n return True\n\ndef pull_trace_raw(data):\n '''Parses the raw data as appropriate.\n \n '''\n \n trace = {'time' : data[:,0], 'values' : data[:,-1] }\n \n return trace\n\ndef preprocess(trace, **kwargs):\n '''\n \n '''\n \n return trace, {}\n\ndef parse(trace_data, trace_spec):\n ''' Function to parse a firkecs trace into segments.\n \n Receives:\n dict : trace_data{time : floats, values : floats}\n spec dict : trace_spec\n \n Returns:\n trace dict : a dict of the trace parsed according to a\n convention\n \n '''\n \n point = 0\n for subroutine in trace_spec['subs']:\n subroutine = subroutine['subroutine']\n for measurement in subroutine['phases']:\n for segment in measurement['measurement']:\n segment = segment['segment']\n segment['time'] = trace_data['time'][point :(point + segment['pulses'])]\n segment['values'] = trace_data['values'][point :(point + segment['pulses'])]\n point = point + segment['pulses']\n \n return trace_spec\n \n \ndef calc_metrics(parsed_trace, **kwargs):\n '''\n \n '''\n \n #get the segment we need\n # a tt_pull with [] as key will return the segment\n r = phut.segment_traverse_pull(parsed_trace, [])\n \n #have to index a little bit on the segment traverse pull return to get segment\n dark_segment = r[MEASUREMENT_ID][0]['dark']\n light_segment = r[MEASUREMENT_ID][0]['flash_kinetics']\n \n before = np.median(dark_segment['values'] )\n after = max(light_segment['values'] )\n \n delta = after-before\n \n \n \n return parsed_trace, {'metrics':{'delta': delta}, '_metadata' : None}","sub_path":"phenomics/traces/firkecs.py","file_name":"firkecs.py","file_ext":"py","file_size_in_byte":2892,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"510567124","text":"import numpy as np\nnp.set_printoptions(threshold=np.inf)\nimport math\nimport time\nimport random\nimport matplotlib.pyplot as plt\nfrom new_dqn import DQN\nfrom memory import Memory\nfrom pysc2.lib import actions\n\n# Using Actions: Attack, Move, Select Rectangle\n_NO_OP = actions.FUNCTIONS.no_op.id\n_SELECT_RECT = actions.FUNCTIONS.select_rect.id\n_ATTACK_SCREEN = actions.FUNCTIONS.Attack_screen.id\n_MOVE_SCREEN = actions.FUNCTIONS.Move_screen.id\n\n# return actions.FunctionCall(_SELECT_RECT, [_NOT_QUEUED, top_left_coord, bottom_right_coord])\n# return actions.FunctionCall(_MOVE_SCREEN, [_NOT_QUEUED, [x, y]]) # x,y => col,row\n# return actions.FunctionCall(_ATTACK_SCREEN, [_NOT_QUEUED, [x, y]]) # x,y => col,row\n\n_PLAYER_SELF = 1\n_PLAYER_HOSTILE = 4\n\n_UNIT_ALLIANCE = 1\n_UNIT_HEALTH = 2\n_UNIT_SHIELD = 3\n_UNIT_X = 12\n_UNIT_Y = 13\n_UNIT_IS_SELECTED = 17\n_UNIT_COOLDOWN = 25\n\n_NOT_QUEUED = [0]\n_QUEUED = [1]\n\nATTACK_TARGET = 'attacktarget'\nMOVE_UP = 'moveup'\nMOVE_DOWN = 'movedown'\nMOVE_LEFT = 'moveleft'\nMOVE_RIGHT = 'moveright'\nACTION_SELECT_UNIT = 'selectunit'\n\nsmart_actions = [\n MOVE_UP,\n MOVE_DOWN,\n MOVE_LEFT,\n MOVE_RIGHT,\n ATTACK_TARGET\n]\n\n# Change this if using a different map\n# Currently running HK2V1\nDEFAULT_ENEMY_COUNT = 1\nDEFAULT_PLAYER_COUNT = 2\n\nENEMY_MAX_HP = 150\nPLAYER_MAX_HP = 60\n\n\nclass DQN_Agent(object):\n def __init__(self, FLAGS, sess):\n self.sess = sess\n self.max_steps = FLAGS.max_steps\n self.model = DQN(FLAGS)\n # Necessary\n self.obs_spec = None\n self.action_spec = None\n self.prev_action = None\n self.prev_state = None\n # Change this base on map\n self.prev_enemy_count = 1\n self.prev_player_count = 2\n self.channel_size = FLAGS.channel_size\n self.state_size = FLAGS.screen_resolution\n # Calculate the win\n self.win = 0\n self.memory = Memory(FLAGS)\n\n def step(self, obs, episode, step):\n # Get state\n rgb_screen = np.array(obs.observation['rgb_screen'])\n rgb_screen = np.transpose(rgb_screen, [1, 0, 2])\n\n if self.channel_size == 4:\n hp_ratio_screen = np.array(obs.observation['feature_screen']['unit_hit_points_ratio'])\n hp_ratio_screen = np.transpose(hp_ratio_screen, [1, 0])\n hp_ratio_screen = np.expand_dims(hp_ratio_screen, axis=2)\n features = np.concatenate((rgb_screen, hp_ratio_screen), axis=-1)\n elif self.channel_size == 3:\n features = rgb_screen\n else:\n print(\"Fail to create the correct state. Check channel_size\")\n features = rgb_screen\n\n curr_state = (features / 127.5) - 1\n # print(features, features.shape)\n\n # Choose action\n # Later on dqn picks action\n\n # For now random pick one\n if episode < 100:\n if np.random.rand(1)[0] > 0.3:\n curr_action = np.random.randint(self.channel_size, size=1)\n coords1 = np.random.randint(self.state_size, size=2)\n coords2 = np.random.randint(self.state_size, size=2)\n else:\n curr_action, coords1, coords2 = self.choose_action(curr_state)\n elif 100 <= episode < 1000:\n if np.random.rand(1)[0] > 0.8:\n curr_action = np.random.randint(self.channel_size, size=1)\n coords1 = np.random.randint(self.state_size, size=2)\n coords2 = np.random.randint(self.state_size, size=2)\n else:\n curr_action, coords1, coords2 = self.choose_action(curr_state)\n else:\n if np.random.rand(1)[0] > 0.95:\n curr_action = np.random.randint(self.channel_size, size=1)\n coords1 = np.random.randint(self.state_size, size=2)\n coords2 = np.random.randint(self.state_size, size=2)\n else:\n curr_action, coords1, coords2 = self.choose_action(curr_state)\n\n next_action = None\n if curr_action == 0:\n # print(\"Select {} {}\".format(coords1, coords2))\n next_action = actions.FunctionCall(_SELECT_RECT, [_NOT_QUEUED, coords1, coords2])\n elif curr_action == 1:\n if _MOVE_SCREEN in obs.observation[\"available_actions\"]:\n # print(\"Move \")\n next_action = actions.FunctionCall(_MOVE_SCREEN, [_NOT_QUEUED, coords1]) # x,y => col,row\n else:\n next_action = actions.FunctionCall(_NO_OP, [])\n elif curr_action == 2:\n if _ATTACK_SCREEN in obs.observation[\"available_actions\"]:\n # print(\"Attack \")\n next_action = actions.FunctionCall(_ATTACK_SCREEN, [_NOT_QUEUED, coords1]) # x,y => col,row\n else:\n next_action = actions.FunctionCall(_NO_OP, [])\n\n # Get Reward\n reward = self.get_reward(obs, step)\n\n # record the transitions to memory and learn by DQN\n if self.prev_action is not None:\n # print(step, self.memory.temp_count, reward, self.prev_reward)\n # store prev, curr instead of curr, next bc we cannot get next directly\n self.memory.store_temp_transition(self.prev_state, self.prev_action, self.prev_reward, curr_state)\n\n self.prev_state = curr_state\n self.prev_action = curr_action\n self.prev_reward = reward\n\n return next_action\n\n def choose_action(self, obs):\n feed_dict = {self.model.s: np.expand_dims(obs, axis=0), self.model.training: False}\n q_curr, coords_1, coords_2 = self.sess.run(\n [self.model.q_curr, self.model.coords_1, self.model.coords_2], feed_dict=feed_dict)\n action = np.argmax(q_curr, axis=-1)\n\n coords_1 = (coords_1[0] * self.state_size).astype(int)\n coords_2 = (coords_2[0] * self.state_size).astype(int)\n\n return action, coords_1, coords_2\n\n def get_reward(self, obs, step):\n curr_enemy_unit_count = 0\n curr_player_unit_count = 0\n units_features = obs.observation['feature_units']\n\n for unit_features in units_features:\n if unit_features[_UNIT_ALLIANCE] == _PLAYER_HOSTILE:\n curr_enemy_unit_count += 1\n else:\n curr_player_unit_count += 1\n\n # reward: 1 if an enemy is killed, 0 for other\n enemy_killed_reward = self.prev_enemy_count - curr_enemy_unit_count\n # reward: 0 if no unit is killed, -x for x number of unit killed\n player_unit_saved_reward = curr_player_unit_count - self.prev_player_count\n reward = enemy_killed_reward + player_unit_saved_reward\n\n self.prev_enemy_count = curr_enemy_unit_count\n self.prev_player_count = curr_player_unit_count\n # print(reward)\n\n # Probably not bc step_mul might skip the timestep\n if curr_enemy_unit_count == 0 and curr_player_unit_count > 0:\n self.win += 1\n\n # Tie (game didn't end before max_steps) => reward = -1\n if (step == self.max_steps - 1 and curr_enemy_unit_count != 0):\n reward = -1\n\n return reward\n\n\n # from the origin base.agent\n def setup(self, obs_spec, action_spec):\n self.obs_spec = obs_spec\n self.action_spec = action_spec\n\n # from the origin base.agent\n def reset(self):\n print(\"Reset Agent\")\n # Need to reset the following vars to its initial states\n self.obs_spec = None\n self.action_spec = None\n self.prev_action = None\n self.prev_state = None\n self.prev_enemy_count = 1\n self.prev_player_count = 2\n\n\n\n","sub_path":"dqn/new_agent.py","file_name":"new_agent.py","file_ext":"py","file_size_in_byte":7574,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"222937600","text":"import itertools as it\nimport numpy as np\nimport scipy.stats as st\n\nimport clef as clf\nimport utilities as ut\n\n\n#############\n# Peng algo #\n#############\n\n\ndef peng(x_lgtc, delta, k, rho_min):\n \"\"\"Returns maximal faces s.t. eta pass the test.\"\"\"\n x_bin_k = ut.kth_largest_bin(x_lgtc, k)\n x_bin_kp = ut.kth_largest_bin(x_lgtc, k + int(k**(3./4)))\n x_bin_km = ut.kth_largest_bin(x_lgtc, k - int(k**(3./4)))\n x_bin_2k = ut.kth_largest_bin(x_lgtc, 2*k)\n faces_dict = find_faces_peng(x_bin_k, x_bin_2k, x_bin_kp,\n x_bin_km, delta, k, rho_min, verbose=0)\n faces = clf.find_maximal_faces(faces_dict)\n\n return faces\n\n\ndef peng_0(x_bin_k, x_bin_2k, x_bin_kp, x_bin_km, delta, k, rho_min=0, verbose=0):\n \"\"\"Returns maximal faces s.t. eta pass the test.\"\"\"\n faces_dict = find_faces_peng(x_bin_k, x_bin_2k, x_bin_kp,\n x_bin_km, delta, k, rho_min, verbose)\n faces = clf.find_maximal_faces(faces_dict)\n\n return faces\n\n\ndef faces_init_peng(x_bin_k, x_bin_2k, x_bin_kp, x_bin_km, delta, k, rho_min, verbose):\n \"\"\"Returns faces of size 2 s.t. eta pass the test.\"\"\"\n n_dim = np.shape(x_bin_k)[1]\n faces = []\n for (i, j) in it.combinations(range(n_dim), 2):\n face = [i, j]\n r_k = ut.rho_value(x_bin_k, face, k)\n if verbose and r_k <= rho_min:\n print(f'rho={r_k} for {face}')\n if r_k > rho_min:\n r_2k = ut.rho_value(x_bin_2k, face, k)\n if r_2k > r_k:\n eta = np.log(2)/np.log(r_2k/float(r_k))\n var = var_eta_peng(x_bin_k, x_bin_2k,\n x_bin_kp, x_bin_km, face, k)\n if var > 0:\n test = 1 - st.norm.ppf(1 - delta) * np.sqrt(var/float(k))\n if eta > test:\n faces.append(face)\n\n return faces\n\n\ndef find_faces_peng(x_bin_k, x_bin_2k, x_bin_kp, x_bin_km, delta, k, rho_min, verbose):\n \"\"\"Returns all faces s.t. eta pass the test.\"\"\"\n dim = x_bin_k.shape[1]\n faces_pairs = faces_init_peng(x_bin_k, x_bin_2k, x_bin_kp, x_bin_km,\n delta, k, rho_min, verbose)\n size = 2\n faces_dict = {}\n faces_dict[size] = faces_pairs\n # print('face size : nb faces')\n while len(faces_dict[size]) > size:\n # print(size, ':', len(faces_dict[size]))\n faces_dict[size + 1] = []\n faces_to_try = ut.candidate_faces(faces_dict[size], size, dim)\n if faces_to_try:\n for face in faces_to_try:\n r_k = ut.rho_value(x_bin_k, face, k)\n if verbose and r_k <= rho_min:\n print(f'rho={r_k} for {face}')\n if r_k > rho_min:\n r_2k = ut.rho_value(x_bin_2k, face, k)\n if r_2k > r_k:\n eta = np.log(2)/np.log(r_2k/float(r_k))\n var = var_eta_peng(x_bin_k, x_bin_2k, x_bin_kp,\n x_bin_km,\n face, k)\n if var > 0:\n test = 1 - \\\n st.norm.ppf(1 - delta) * np.sqrt(var/float(k))\n if eta > test:\n faces_dict[size + 1].append(face)\n size += 1\n\n return faces_dict\n\n\n##################\n# Peng estimator #\n##################\n\n\ndef eta_peng(x_bin_k, x_bin_2k, face, k):\n \"\"\"Returns Peng estimator of eta.\"\"\"\n r_k = ut.rho_value(x_bin_k, face, k)\n r_2k = ut.rho_value(x_bin_2k, face, k)\n if (r_k == 0 or r_2k == 0):\n eta_face = 0.\n elif r_k == r_2k:\n eta_face = 0.\n else:\n eta_face = np.log(2)/np.log(r_2k/float(r_k))\n\n return eta_face\n\n\ndef var_eta_peng(x_bin_k, x_bin_2k, x_bin_kp, x_bin_km,\n face, k):\n \"\"\"Returns the variance of the Peng estimator.\"\"\"\n rho = ut.rho_value(x_bin_k, face, k)\n rhos = ut.rhos_face_pairs(x_bin_k, face, k)\n r_p = ut.r_partial_derv_centered(x_bin_k, x_bin_kp, x_bin_km,\n face, k)\n r_ij = {(i, j): ut.rho_value(ut.partial_matrix(x_bin_2k, x_bin_k, j),\n [i, j], k)\n for (i, j) in it.combinations(face, 2)}\n r_ji = {(i, j): ut.rho_value(ut.partial_matrix(x_bin_k, x_bin_2k, j),\n [i, j], k)\n for (i, j) in it.combinations(face, 2)}\n var = ((2 * (rho * np.log(2))**2)**-1 *\n (rho +\n sum([r_p[j] * (-4*rho +\n 2*ut.rho_value(ut.partial_matrix(x_bin_k,\n x_bin_2k, j),\n face, k)) for j in face]) +\n sum([r_p[i]*r_p[j] * (3*rhos[i, j] - 2*r_ij[i, j])\n for (i, j) in it.combinations(face, 2)]) +\n sum([r_p[i]*r_p[j] * (3*rhos[i, j] - 2*r_ji[i, j])\n for (i, j) in it.combinations(face, 2)]) +\n sum([r_p[i]**2 for i in face])))\n\n return var\n\n\ndef peng_test(x_bin_k, x_bin_2k, x_bin_kp, x_bin_km, face, k, delta):\n var = var_eta_peng(x_bin_k, x_bin_2k, x_bin_kp, x_bin_km, face, k)\n eta = eta_peng(x_bin_k, x_bin_2k, face, k)\n\n return (eta - (1 - st.norm.ppf(1 - delta) * np.sqrt(var/float(k))),\n np.sqrt(var/float(k)))\n","sub_path":"peng.py","file_name":"peng.py","file_ext":"py","file_size_in_byte":5378,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"73791269","text":"# from selenium import webdriver\n#\n# driver = webdriver.Chrome(\"C:\\chromedriver.exe\")\n# driver.get('https://web.whatsapp.com/')\n# name = input('Enter with name of user or group: ')\n# msg = input('Enter with your message: ')\n# count = int(input('Enter the count: '))\n#\n# input('Enter anything after scanning QR code')\n# user = driver.find_element_by_xpath('//span[@title = \"{}\"]'.format(name))\n# user.click()\n#\n# msg_box = driver.find_element_by_class_name('input-container')\n#\n# for i in range(count):\n# msg_box.send_keys(msg)\n# button = driver.find_element_by_class_name('compose-btn-send')\n# button.click()\n\nimport time\nfrom selenium import webdriver\nfrom selenium.webdriver.chrome.options import Options\n\nmsg = [\"Mensagem 1\", \"Mensagem 2\"]\n\noptions = Options()\noptions.add_argument(\"--user-data-dir=chrome-data\")\noptions.add_experimental_option(\"excludeSwitches\", [\"enable-automation\"])\noptions.add_experimental_option('useAutomationExtension', False)\n\ndriver = webdriver.Chrome('C:\\\\chromedriver\\\\chromedriver.exe', options=options)\ndriver.maximize_window()\ndriver.get('https://web.whatsapp.com/') # Already authenticated\n\ntime.sleep(6)\ndriver.find_element_by_xpath(\"//*[@title='+55 32 9194-7650']\").click()\n\nfor i in msg:\n driver.find_element_by_xpath('//*[@id=\"main\"]/footer/div[1]/div[2]/div/div[2]').send_keys(msg)\n driver.find_element_by_xpath('//*[@id=\"main\"]/footer/div[1]/div[3]/button/span').click()\n time.sleep(3)\n\ntime.sleep(10)\ndriver.close()\n","sub_path":"whatsapp_automate.py","file_name":"whatsapp_automate.py","file_ext":"py","file_size_in_byte":1481,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"555041517","text":"#\n# Stripping selections job (DST output)\n#\n# @author J. Palacios/A. Poluektov\n# @date 2009-09-14\n#\n\nfrom Gaudi.Configuration import *\nfrom Configurables import SelDSTWriter, DaVinci\nfrom StrippingConf.Configuration import StrippingConf\n\nsc = StrippingConf()\nsc.OutputType = \"DST\"\n\n# Dirac should modify OutputFilePrefix.\n# SelDSTWriter(\"StripMC09DSTWriter\").OutputFileSuffix = '012345'\ndstWriter = SelDSTWriter(\"StripMC09DSTWriter\",\n SelectionSequences = sc.activeStreams(),\n OutputPrefix = 'Strip',\n ExtraItems = ['/Event/DAQ/RawEvent']\n )\n\nDaVinci().DataType = \"MC09\" # Default is \"MC09\"\nDaVinci().UserAlgorithms = [ dstWriter.sequence() ]\nDaVinci().Hlt2Requires = 'L0+Hlt1'\nDaVinci().HltType = 'Hlt1'\nDaVinci().HltThresholdSettings = 'Charm_320Vis_300L0_10Hlt1_Aug09'\nDaVinci().L0 = True\nDaVinci().ReplaceL0BanksWithEmulated = True\nfrom Configurables import L0Conf\nL0Conf().TCK = '0xFF68'\n","sub_path":"DBASE/AppConfig/options/DaVinci/DVStrippingDST-MC09.py","file_name":"DVStrippingDST-MC09.py","file_ext":"py","file_size_in_byte":1013,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"415699404","text":"from random import shuffle\n\nfrom .log import LOG\n\nclass BatchIndicesGenerator():\n \n def _random_shuffle(self):\n shuffle(self.list_indices)\n \n def __init__(self, batch_size, train_examples, num_examples):\n self.train_examples = train_examples\n self.num_examples = num_examples\n self.list_indices = list(range(0, train_examples))\n self.batch_size = batch_size\n self.batch_num = 0\n self._random_shuffle()\n LOG.debug(f\"Initialized BatchIndicesGenerator object\")\n\n def gen_train_batch(self):\n start = self.batch_num * self.batch_size\n end = (self.batch_num + 1) * self.batch_size\n batch_indices = self.list_indices[start:end]\n self.batch_num += 1\n if end >= self.num_examples:\n self.batch_num = 0\n self._random_shuffle() \n LOG.debug(f\"Generated BatchIndices {batch_indices}\")\n return batch_indices\n\n def gen_train(self):\n return list(range(0, self.train_examples))\n\n def gen_validate(self):\n return list(range(self.train_examples, self.num_examples))\n","sub_path":"2-layer-nn-300hu-mse-none-4p7/utils/batch_generate.py","file_name":"batch_generate.py","file_ext":"py","file_size_in_byte":1108,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"253266886","text":"from utilities import *\n\ndef poly_x_n(x, n):\n \"\"\"\n calculate [1,x,x^2,...,x^n]\n \"\"\"\n result = np.ones(x.shape)\n for i in range(1, (n + 1)):\n result = np.c_[result, np.power(x, i)]\n return(result)\n\ndef predict(x, a):\n \"\"\"\n calculate predicted_errord y\n \"\"\"\n y = a[0]\n for i in range(1, a.size):\n y = y + a[i]*x[:,i]\n return y\n\ndef fourier_x(x):\n \"\"\"\n basic fourier x\n \"\"\"\n return np.c_[np.ones(x.shape), np.sin(x)]\n\ndef solve_by_least_square_error(x, y):\n \"\"\"\n Ax = y\n A = x^-1 * y / (||x||^2)\n \"\"\"\n # transpose\n x_t = x.transpose()\n # A = x^-1 * y / (||x||^2)\n return np.linalg.inv(np.dot(x_t, x)).dot(x_t).dot(y)\n\ndef sum_square_error(y, yh):\n \"\"\"\n calculate sum square error\n \"\"\"\n return np.power((yh - y), 2).sum()\n\ndef main():\n \"\"\"\n the main function\n \"\"\"\n # the command parameters\n args = sys.argv[1:]\n # read points from file\n xs, ys = load_points_from_file(args[0])\n # the re-construction error\n reconstruction_error = 0\n # 20 points each\n for i in range(0, int(xs.size/20)):\n # the sub data\n x = xs[i*20:(i + 1)*20]\n y = ys[i*20:(i + 1)*20]\n # 3 type x(linear poly unknown) prepare\n linear_x = poly_x_n(x, 1)\n poly_x = poly_x_n(x, 3)\n unknown_x = fourier_x(x)\n # 3 type solve\n linear_A = solve_by_least_square_error(linear_x, y)\n poly_A = solve_by_least_square_error(poly_x, y)\n unknown_A = solve_by_least_square_error(unknown_x, y)\n # 3 type predict\n linear_predict = predict(linear_x, linear_A)\n poly_predict = predict(poly_x, poly_A)\n unknown_predict = predict(unknown_x, unknown_A)\n # the errors\n errors = [sum_square_error(y, linear_predict), sum_square_error(y, poly_predict), sum_square_error(y, unknown_predict)]\n reconstruction_error += np.min(errors)\n # the function choosed\n choice = np.argmin(errors)\n if (len(args) == 2 and args[1] == \"--plot\"):\n xp = (np.linspace(x.min(), x.max(), 50))\n if (choice == 0):\n x_ = poly_x_n(xp, 1)\n y_ = predict(x1p, al)\n if (choice == 1):\n x_ = poly_x_n(xp, 3)\n y_ = predict(x1p, ac)\n if (choice == 2):\n x_ = fourier_x(xp)\n y_ = predict(x1p, at)\n plt.plot(x_, y_)\n # draw the original data\n if (len(args) == 2 and args[1] == \"--plot\"):\n view_data_segments(xs, ys)\n print(reconstruction_error)\n\nmain()\n","sub_path":"my_lsr.py","file_name":"my_lsr.py","file_ext":"py","file_size_in_byte":2593,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"160599011","text":"# -*- coding: utf-8 -*-\nimport os\nimport sys\nimport json\nimport time\nfrom datetime import datetime\n\nimport requests\nfrom flask import jsonify\nfrom flask import Flask, request\nimport threading\n\nif sys.version_info[0] >= 3:\n unicode = str\n\napp = Flask(__name__)\n\nplaid_server = \"https://peaceful-fortress-19275.herokuapp.com/liabilities\"\n\n# hardcoding this token for now\n# TODO - use cookies to pass this back to messenger\naccess_token = \"access-sandbox-28e8315a-845e-42bb-8848-6683411cfc9f\"\n\n\n\n\n@app.route('/', methods=['GET'])\ndef verify():\n # when the endpoint is registered as a webhook, it must echo back\n # the 'hub.challenge' value it receives in the query arguments\n if request.args.get(\"hub.mode\") == \"subscribe\" and request.args.get(\"hub.challenge\"):\n if not request.args.get(\"hub.verify_token\") == os.environ[\"VERIFY_TOKEN\"]:\n return \"Verification token mismatch\", 403\n return request.args[\"hub.challenge\"], 200\n\n return \"Hello world\", 200\n\n\n@app.route('/', methods=['POST'])\ndef webhook():\n\n # endpoint for processing incoming messaging events\n\n data = request.get_json()\n log(data) # you may not want to log every incoming message in production, but it's good for testing\n\n if data[\"object\"] == \"page\":\n\n for entry in data[\"entry\"]:\n for messaging_event in entry[\"messaging\"]:\n\n log(messaging_event)\n\n if messaging_event.get(\"message\"): # someone sent us a message\n\n sender_id = messaging_event[\"sender\"][\"id\"] # the facebook ID of the person sending you the message\n recipient_id = messaging_event[\"recipient\"][\"id\"] # the recipient's ID, which should be your page's facebook ID\n message_text = messaging_event[\"message\"][\"text\"] # the message's text\n\n if 'options' in message_text:\n log('called options')\n send_all_options(sender_id)\n elif 'add account' in message_text:\n add_bank_account(sender_id)\n elif 'refinance' in message_text:\n refinance_loan(sender_id)\n elif 'insights' in message_text:\n insights(sender_id)\n elif 'spend' in message_text:\n habit_forming(sender_id)\n elif 'new debt' in message_text:\n updated_debt(sender_id)\n elif 'yes' in message_text:\n send_message_with_picture('https://media1.tenor.com/images/04052e9d28831ce512093906edec28f6/tenor.gif')\n send_message('Pixy will process your payment accordingly.')\n elif 'demo' in message_text:\n thread1 = threading.Thread(target=workflow, args=(sender_id,))\n thread1.start()\n log('called workflow')\n else:\n send_message(sender_id, \"Welcome to Pixy. 😀\")\n send_message(sender_id, \"I will find the best ways to help you manage you student debt 💰. I can recommend the optimal payment amounts, remind you of upcoming payments, help you manage your expenses and increase savings\")\n add_bank_account(sender_id)\n \n\n if messaging_event.get(\"delivery\"): # delivery confirmation\n pass\n\n if messaging_event.get(\"optin\"): # optin confirmation\n pass\n\n if messaging_event.get(\"postback\"): # user clicked/tapped \"postback\" button in earlier message\n log('received postback')\n if messaging_event['payload'] is not None:\n \n event = messaging_event['postback']['payload']\n sender_id = messaging_event['sender_id']\n \n if event == 'analyze':\n insights(sender_id)\n elif event == 'habits':\n habit_forming(sender_id)\n elif event == 'refinance':\n log('refinance')\n refinance_loan(sender_id)\n else:\n pass\n\n\n return \"ok\", 200\n\ndef send_all_options(recipient_id):\n params = {\n \"access_token\": os.environ[\"PAGE_ACCESS_TOKEN\"]\n }\n \n headers = {\n \"Content-Type\": \"application/json\"\n }\n\n data = json.dumps({\n \"recipient\": {\n \"id\": recipient_id\n },\n \"message\":{\n \"attachment\":{\n \"type\":\"template\",\n \"payload\":{\n \"template_type\":\"generic\",\n \"elements\":[\n {\n \"title\":\"Here are some ways we can help you! Select an option.\",\n \"buttons\":[\n {\n \"type\":\"postback\",\n \"title\":\"Analyze expenses\",\n \"payload\": \"analyze\",\n },\n {\n \"type\":\"postback\",\n \"title\":\"Show spending habits\",\n \"payload\": \"habits\",\n },\n {\n \"type\":\"postback\",\n \"title\":\"Refinance Debt\",\n \"payload\": \"refinance\",\n }\n ]\n }]\n }\n }\n }\n })\n\n r = requests.post(\"https://graph.facebook.com/v4.0/me/messages\", params=params, headers=headers, data=data)\n if r.status_code != 200:\n log(r.status_code)\n print(r.text)\n #log(r.text)\n\ndef add_bank_account(recipient_id):\n params = {\n \"access_token\": os.environ[\"PAGE_ACCESS_TOKEN\"]\n }\n \n headers = {\n \"Content-Type\": \"application/json\"\n }\n\n data = json.dumps({\n \"recipient\": {\n \"id\": recipient_id\n },\n \"message\":{\n \"attachment\":{\n \"type\":\"template\",\n \"payload\":{\n \"template_type\":\"generic\",\n \"elements\":[{\n \"title\":\"Link your bank accounts to get started\",\n \"image_url\":\"https://s3.amazonaws.com/gethyped.io/pixycover.png\",\n \"subtitle\":\"We help you manage your student loans and credit card debt.\",\n \"default_action\": {\n \"type\": \"web_url\",\n \"url\": \"https://peaceful-fortress-19275.herokuapp.com/\",\n \"webview_height_ratio\": \"tall\",\n },\n \"buttons\":[{\n \"type\":\"web_url\",\n \"url\":\"https://peaceful-fortress-19275.herokuapp.com/\",\n \"title\":\"Link bank accounts\",\n \"webview_height_ratio\": \"tall\",\n }]\n }]\n }\n }\n }\n })\n\n r = requests.post(\"https://graph.facebook.com/v4.0/me/messages\", params=params, headers=headers, data=data)\n if r.status_code != 200:\n log(r.status_code)\n log(r.text)\n\n# TODO - show liabilities\n# TODO - show workflows \n\n# {\n# \"type\":\"web_url\",\n# \"url\":\"https://www.nerdwallet.com/blog/pay-off-debt/\",\n# \"title\":\"Credit Card Guide\",\n# \"webview_height_ratio\": \"tall\",\n# },\n# {\n# \"type\":\"web_url\",\n# \"url\":\"https://www.creditkarma.com/advice/i/student-loans-101/\",\n# \"title\":\"Student Loan Guide\",\n# \"webview_height_ratio\": \"tall\",\n# }\n\ndef show_current_liabilities(recipient_id):\n response = json.loads(requests.get(plaid_server))\n credit_card_debt = list(response['liabilities']['credit'])[0]\n student_debt = list(response['liabilities']['student'])[0]\n\n # student debt data\n expected_payoff_date = student_debt[\"expected_payoff_date\"]\n guarantor = student_debt[\"guarantor\"]\n interest_rate_percentage = float(student_debt[\"interest_rate_percentage\"])\n last_payment_amount = float(student_debt[\"last_payment_amount\"])\n loan_name = student_debt[\"loan_name\"]\n minimum_payment_amount = float(student_debt[\"minimum_payment_amount\"])\n origination_date = student_debt[\"origination_date\"]\n origination_principal_amount = float(student_debt[\"origination_principal_amount\"])\n outstanding_interest_amount = float(student_debt[\"outstanding_interest_amount\"])\n ytd_interest_paid = float(student_debt[\"ytd_interest_paid\"])\n ytd_principal_paid = float(student_debt[\"ytd_principal_paid\"])\n\n # credit card debt\n aprs = list(credit_card_debt[\"aprs\"])\n last_statement_balance = float(credit_card_debt[\"last_statement_balance\"])\n last_payment_amount = float(credit_card_debt[\"last_payment_amount\"])\n minimum_payment_amount = float(credit_card_debt[\"minimum_payment_amount\"])\n\n cc_list = []\n cc_debt = 0\n\n for cc_balance in aprs:\n apr_percentage = float(cc_balance[\"apr_percentage\"])\n apr_type = cc_balance[\"apr_type\"]\n balance_subject_to_apr = float(cc_balance[\"balance_subject_to_apr\"])\n interest_charge_amount = float(cc_balance[\"interest_charge_amount\"])\n total_debt += balance_subject_to_apr\n\n total_debt = cc_debt + (origination_principal_amount - ytd_principal_paid)\n\n send_message(\n recipient_id,\n \"Your current credit card debt is \" + \n str(cc_debt) + \n \" and your student loan is \" + \n str(origination_principal_amount - ytd_principal_paid)\n )\n\ndef refinance_loan(recipient_id):\n params = {\n \"access_token\": os.environ[\"PAGE_ACCESS_TOKEN\"]\n }\n \n headers = {\n \"Content-Type\": \"application/json\"\n }\n\n data = json.dumps({\n \"recipient\": {\n \"id\": recipient_id\n },\n \"message\":{\n \"attachment\":{\n \"type\":\"template\",\n \"payload\":{\n \"template_type\":\"button\",\n \"text\":\"I found some refinancing options based on your current payments, payoff date and expenditures. Select to learn more.\",\n \"buttons\":[{\n \"type\":\"web_url\",\n \"url\":\"https://www.sofi.com/refinance-student-loan/\",\n \"title\":\"SoFi 2.05-6.48%\",\n \"webview_height_ratio\": \"tall\",\n },\n {\n \"type\":\"web_url\",\n \"url\":\"https://www.earnest.com/refinance-student-loans\",\n \"title\":\"Earnest 2.14-7.49%\",\n \"webview_height_ratio\": \"tall\",\n },\n {\n \"type\":\"web_url\",\n \"url\":\"https://www.commonbond.co/affiliate/student-loan-hero\",\n \"title\":\"CommonBond 2.14-8.24%\",\n \"webview_height_ratio\": \"tall\",\n }]\n }\n }\n }\n })\n\n r = requests.post(\"https://graph.facebook.com/v4.0/me/messages\", params=params, headers=headers, data=data)\n if r.status_code != 200:\n log(r.status_code)\n log(r.text)\n\ndef workflow(recipient_id):\n\n send_message(recipient_id, \"Your account has been successfully connected! 🎉\")\n\n send_message(recipient_id, \"You can add more accounts anytime by sending \\\"add account\\\"\")\n time.sleep(10)\n send_message_with_picture(recipient_id, \"https://media.giphy.com/media/zNSX3G2LztEyY/giphy.gif\")\n\n send_message(recipient_id, \"Building your financial picture...\")\n\n time.sleep(20)\n\n insights(recipient_id)\n\n time.sleep(20)\n\n habit_forming(recipient_id)\n time.sleep(20)\n\n updated_debt(recipient_id)\n\n time.sleep(20)\n\n refinance_loan(recipient_id)\n\n\ndef habit_forming(recipient_id):\n send_message(\n recipient_id,\n \"Hey there, hope your day is going great! It looks like you spent $98 on amazon.com this month. You can save $5 in total interest if you pay $98 towards your loan. Would you like me to save some money towards your student loan?\"\n )\n\ndef updated_debt(recipient_id):\n send_message(recipient_id, \n \"You paid $300.35 this month towards your student loan. Oustanding loan amount is now $24,328! Keep up the good work!! 🎊\"\n )\n\n debt_breakdown(recipient_id, 300.35)\n\ndef debt_breakdown(recipient_id, minus):\n send_message(recipient_id, \n \"Average monthly income: $3320\\n\" +\n \"Average monthly expenses: $2020\\n\" +\n \"Breakdown of your debt: {:.2f}\\n\\n\".format((27503.9-minus)) + \n \"Credit cards: 2775.55\\n\" + \n \" APR: 15.24\\n\" + \n \" Amount: 1562.32\\n\" + \n \" APR: 27.95\\n\"+\n \" Amount: 56.22\\n\"+\n \" APR: 12.5\\n\"+\n \" Amount: 157.01\\n\"+\n \" APR: 0\\n\"+\n \" Amount: 1000\\n\\n\" + \n \"Student Loans: {:.2f}\\n\".format((24728.35-minus)) + \n \"Interest rate: 5.25%\\n\"\n )\n\ndef insights(recipient_id):\n # Monthly payments\n # Total debt remaining\n # Credit cards\n # APR \n # Amount\n # Student Loan\n # Interest\n # Amount remaining\n\n # Balance so far\n # Suggested amount to pay\n\n debt_breakdown(recipient_id, 0)\n\n send_message_with_picture(recipient_id, \"https://s3.amazonaws.com/gethyped.io/pixydebt2.jpg\")\n\n send_message(\n recipient_id,\n \"We found that you can save $983 in interest by making $102 additional monthly payment towards your Chase student loan. Do you want me to increase your monthly payment?\"\n )\n\ndef send_message_with_picture(recipient_id, url):\n params = {\n \"access_token\": os.environ[\"PAGE_ACCESS_TOKEN\"]\n }\n \n headers = {\n \"Content-Type\": \"application/json\"\n }\n\n data = json.dumps({\n \"recipient\": {\n \"id\": recipient_id\n },\n \"message\":{\n \"attachment\": {\n \"type\": \"image\",\n \"payload\": {\n \"url\": url,\n }\n } \n }\n })\n\n r = requests.post(\"https://graph.facebook.com/v4.0/me/messages\", params=params, headers=headers, data=data)\n if r.status_code != 200:\n log(r.status_code)\n log(r.text)\n\n\ndef send_message_with_button(recipient_id, message_text, button_url, button_text):\n params = {\n \"access_token\": os.environ[\"PAGE_ACCESS_TOKEN\"]\n }\n \n headers = {\n \"Content-Type\": \"application/json\"\n }\n\n data = json.dumps({\n \"recipient\": {\n \"id\": recipient_id\n },\n \"message\":{\n \"attachment\":{\n \"type\":\"template\",\n \"payload\":{\n \"template_type\":\"button\",\n \"text\":message_text,\n \"buttons\":[{\n \"type\":\"web_url\",\n \"url\":button_url,\n \"title\":button_text,\n \"webview_height_ratio\": \"tall\",\n }]\n }\n }\n }\n })\n\n r = requests.post(\"https://graph.facebook.com/v4.0/me/messages\", params=params, headers=headers, data=data)\n if r.status_code != 200:\n log(r.status_code)\n log(r.text)\n\n\ndef send_message(recipient_id, message_text):\n\n log(\"sending message to {recipient}: {text}\".format(recipient=recipient_id, text=message_text))\n\n params = {\n \"access_token\": os.environ[\"PAGE_ACCESS_TOKEN\"]\n }\n headers = {\n \"Content-Type\": \"application/json\"\n }\n data = json.dumps({\n \"recipient\": {\n \"id\": recipient_id\n },\n \"message\": {\n \"text\": message_text\n },\n })\n r = requests.post(\"https://graph.facebook.com/v4.0/me/messages\", params=params, headers=headers, data=data)\n if r.status_code != 200:\n log(r.status_code)\n log(r.text)\n\n data = json.dumps({\n \"recipient\": {\n \"id\": recipient_id\n },\n \"sender_action\": \"mark_seen\",\n })\n\n r = requests.post(\"https://graph.facebook.com/v4.0/me/messages\", params=params, headers=headers, data=data)\n if r.status_code != 200:\n log(r.status_code)\n log(r.text)\n\n\ndef log(msg, *args, **kwargs): # simple wrapper for logging to stdout on heroku\n try:\n if type(msg) is dict:\n msg = json.dumps(msg)\n else:\n msg = unicode(msg).format(*args, **kwargs)\n print(u\"{}: {}\".format(datetime.now(), msg))\n except UnicodeEncodeError:\n pass # squash logging errors in case of non-ascii text\n sys.stdout.flush()\n\n\nif __name__ == '__main__':\n app.run(debug=True, port=3000)\n\n","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":17387,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"90887417","text":"from telegram.ext import Updater\nupdater = Updater(token='2065572942:AAF5bgFxR4phDBQXvwFI9fcQ9-F7eQs6sJM')\ndispatcher = updater.dispatcher\nimport logging\nlogging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',\n level=logging.INFO)\ndef start(update, context):\n context.bot.send_message(chat_id=update.effective_chat.id, text=\"I'm a bot, please talk to me!\")\nfrom telegram.ext import CommandHandler\nstart_handler = CommandHandler('start', start)\ndispatcher.add_handler(start_handler)\nupdater.start_polling()\n\n\ndef echo(update, context):\n context.bot.send_message(chat_id=update.effective_chat.id, text=update.message.text)\nfrom telegram.ext import MessageHandler, Filters\necho_handler = MessageHandler(Filters.text & (~Filters.command), echo)\ndispatcher.add_handler(echo_handler)\n\n\ndef admin_login_operation(update, context):\n context.bot.send_message(chat_id=update.effective_chat.id, text=\"I'm a bot, please talk to me!\")\nfrom telegram.ext import CommandHandler\nstart_handler = CommandHandler('admin_login_operation', start)\ndispatcher.add_handler(start_handler)\nupdater.start_polling()\n#ddddddd\n\ndef unknown(update, context): #добавлять последним!\n context.bot.send_message(chat_id=update.effective_chat.id, text=\"Извините, эта команда мне ещё неизвестна\")\n\nunknown_handler = MessageHandler(Filters.command, unknown)\ndispatcher.add_handler(unknown_handler)","sub_path":"Python_Bot/Одноразовый_бот.py","file_name":"Одноразовый_бот.py","file_ext":"py","file_size_in_byte":1468,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"187677482","text":"# ARQUIVO DE TESTE PARA A ATIVIDADE CONTÍNUA 02\r\n# Este arquivo não deve ser modificado.\r\n\r\n\r\n# Importa as classes do módulo ac02\r\nfrom ac02 import Socio, Clube\r\n\r\n\r\n# Testa a criação dos objetos da classe Sócio\r\ntry:\r\n # Criação do primeiro Sócio\r\n m1 = Socio('Paulo', '10/09/1990', '649.943.670-43', 1, 2020)\r\n assert m1.nome == 'Paulo'\r\n assert m1.nascimento == '10/09/1990'\r\n assert m1.cpf == '649.943.670-43'\r\n assert m1.mes == 1\r\n assert m1.ano == 2020\r\n\r\n # Criação do segundo Sócio\r\n m2 = Socio('Ana', '14/12/1995', '918.199.320-01', 2, 2020)\r\n assert m2.nome == 'Ana'\r\n assert m2.nascimento == '14/12/1995'\r\n assert m2.cpf == '918.199.320-01'\r\n assert m2.mes == 2\r\n assert m2.ano == 2020\r\n\r\n # Criação dos outros Sócios do clube\r\n m3 = Socio('Maria', '14/01/2002', '770.046.380-81', 3, 2020)\r\n m4 = Socio('Vinicius', '14/05/1989', '682.194.070-34', 4, 2020)\r\n m5 = Socio('Guilherme', '14/02/1987', '001.655.780-84', 3, 2020)\r\n m6 = Socio('Ruan', '14/10/2000', '157.550.560-64', 1, 2019)\r\n m7 = Socio('Caroline', '14/09/2001', '548.428.380-94', 1, 2018)\r\n m8 = Socio('Fernanda', '14/09/2005', '023.126.550-63', 3, 2020)\r\n m9 = Socio('Zé', '14/07/1990', '012.308.030-41', 3, 2020)\r\nexcept AssertionError:\r\n print('ERRO...: valor dos atributos dos objetos da classe Socio')\r\nexcept Exception:\r\n print('ERRO...: criação dos objetos da classe Socio')\r\nelse:\r\n print('CORRETO: criação dos objetos da classe Socio')\r\n\r\n\r\n# Testa a criação do objeto Clube\r\ntry:\r\n clube = Clube()\r\n # Verifica se a lista de sócios foi inicializada como vazia\r\n assert clube.socios == []\r\nexcept AssertionError:\r\n print('ERRO...: lista de socios do clube deve iniciar vazia')\r\nexcept Exception:\r\n print('ERRO...: criação do objeto da classe Clube')\r\nelse:\r\n print('CORRETO: criação do objeto da classe Clube')\r\n\r\n\r\n# Testa a associação dos sócios ao clube\r\ntry:\r\n clube.associar(m1)\r\n assert len(clube.socios) == 1 # clube possui 1 sócio\r\n # verifica se armazenou objeto do tipo correto na lista\r\n assert type(clube.socios[0]) == Socio\r\n assert clube.socios[0].nome == 'Paulo'\r\n\r\n clube.associar(m2)\r\n assert len(clube.socios) == 2 # clube possui 2 sócios\r\n # verifica se armazenou objeto do tipo correto na lista\r\n assert type(clube.socios[1]) == Socio\r\n assert clube.socios[1].nome == 'Ana'\r\n\r\n clube.associar(m3)\r\n clube.associar(m4)\r\n clube.associar(m5)\r\n clube.associar(m6)\r\n clube.associar(m7)\r\n clube.associar(m8)\r\n clube.associar(m9)\r\n assert len(clube.socios) == 9 # clube possui 9 sócios\r\nexcept AssertionError:\r\n print('ERRO...: método associar')\r\nexcept Exception:\r\n print('ERRO...: método associar implementado com erro')\r\nelse:\r\n print('CORRETO: método associar')\r\n\r\n\r\n# Testa o método numero_de_socios\r\ntry:\r\n # clube possui 9 sócios\r\n assert clube.numero_de_socios() == 9\r\n\r\n # insere um novo sócio\r\n m10 = Socio('Pedro', '091.974.110-00', '14/12/1999', 7, 2018)\r\n clube.associar(m10)\r\n\r\n # clube possui 10 sócios\r\n assert clube.numero_de_socios() == 10\r\nexcept AssertionError:\r\n print('ERRO...: método numero_de_socios não retornou resultado correto')\r\nexcept Exception:\r\n print('ERRO...: método numero_de_socios implementado com erro')\r\nelse:\r\n print('CORRETO: método numero_de_socios')\r\n\r\n\r\n# Testa o método mes_associacao\r\ntry:\r\n assert clube.mes_associacao(3, 2020) == 4\r\n assert clube.mes_associacao(1, 2019) == 1\r\n assert clube.mes_associacao(10, 2020) == 0\r\nexcept AssertionError:\r\n print('ERRO...: método mes_associacao não retornou resultado correto')\r\nexcept Exception:\r\n print('ERRO...: método mes_associacao implementado com erro')\r\nelse:\r\n print('CORRETO: método mes_associacao')\r\n\r\n\r\n# Testa validação do mês no método mes_associacao\r\ntry:\r\n clube.mes_associacao(0, 2020)\r\n clube.mes_associacao(13, 2020)\r\nexcept ValueError:\r\n print('CORRETO: gerou exceção ValueError para mês inválido no \\\r\nmétodo mes_associacao')\r\nexcept Exception:\r\n print('ERRO...: não gerou exceção ValueError para mês inválido no \\\r\nmétodo mes_associacao')\r\nelse:\r\n print('ERRO...: não gerou exceção ValueError para mês inválido no \\\r\nmétodo mes_associacao')\r\n\r\n\r\n# Testa validação do ano no método mes_associacao\r\ntry:\r\n clube.mes_associacao(3, 20)\r\n clube.mes_associacao(3, 9)\r\n clube.mes_associacao(3, 20201)\r\nexcept TypeError:\r\n print('CORRETO: gerou exceção TypeError para ano inválido no \\\r\nmétodo mes_associacao')\r\nexcept Exception:\r\n print('ERRO...: não gerou exceção TypeError para ano inválido no \\\r\nmétodo mes_associacao')\r\nelse:\r\n print('ERRO...: não gerou exceção TypeError para ano inválido no \\\r\nmétodo mes_associacao')\r\n\r\n\r\n# Testa o método expulsar\r\ntry:\r\n assert clube.expulsar(3, 2020) == ('Fernanda', 'Guilherme', 'Maria', 'Zé')\r\n assert clube.numero_de_socios() == 6\r\n\r\n assert clube.expulsar(1, 2018) == ('Caroline',)\r\n assert clube.numero_de_socios() == 5\r\n\r\n assert clube.expulsar(10, 2020) == ()\r\n assert clube.numero_de_socios() == 5\r\nexcept AssertionError:\r\n print('ERRO...: método expulsar não retornou tupla correta ou não \\\r\nremoveu socios corretamente')\r\nexcept Exception:\r\n print('ERRO...: método expulsar implementado com erro')\r\nelse:\r\n print('CORRETO: método expulsar')\r\n\r\n\r\n# Testa validação do mês no método expulsar\r\ntry:\r\n assert clube.expulsar(0, 2020) == []\r\n assert clube.expulsar(13, 2020) == []\r\nexcept ValueError:\r\n print('CORRETO: gerou exceção ValueError para mês inválido no \\\r\nmétodo expulsar')\r\nexcept Exception:\r\n print('ERRO...: não gerou exceção ValueError para mês inválido no \\\r\nmétodo expulsar')\r\nelse:\r\n print('ERRO...: não gerou exceção ValueError para mês inválido no \\\r\nmétodo expulsar')\r\n\r\n\r\n# Testa validação do ano no método expulsar\r\ntry:\r\n assert clube.expulsar(3, 20) == []\r\n assert clube.expulsar(3, 9) == []\r\n assert clube.expulsar(3, 20201) == []\r\nexcept TypeError:\r\n print('CORRETO: gerou exceção TypeError para ano inválido no \\\r\nmétodo expulsar')\r\nexcept Exception:\r\n print('ERRO...: não gerou exceção TypeError para ano inválido no \\\r\nmétodo expulsar')\r\nelse:\r\n print('ERRO...: não gerou exceção TypeError para ano inválido no \\\r\nmétodo expulsar')\r\n","sub_path":"teste ac2.py","file_name":"teste ac2.py","file_ext":"py","file_size_in_byte":6477,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"575048658","text":"''' Utilities for PyTorch implementaion of \"Beyond a Gaussian Denoiser:\nResidual Learning of Deep CNN for Image Denoising\" (TIP2017)\nInspired from https://github.com/SaoYan/DnCNN-PyTorch '''\n\nimport math\nimport torch\nimport torch.nn as nn\nimport numpy as np\nfrom skimage.measure.simple_metrics import compare_psnr\nimport scipy.io\nfrom skimage.transform import iradon\n\n\n\ndef weights_init_kaiming(m):\n classname = m.__class__.__name__\n if classname.find('Conv') != -1:\n nn.init.kaiming_normal_(m.weight.data, a=0, mode='fan_in')\n elif classname.find('Linear') != -1:\n nn.init.kaiming_normal_(m.weight.data, a=0, mode='fan_in')\n elif classname.find('BatchNorm') != -1:\n # nn.init.uniform(m.weight.data, 1.0, 0.02)\n m.weight.data.normal_(mean=0, std=math.sqrt(2./9./64.)).clamp_(-0.025,0.025)\n nn.init.constant_(m.bias.data, 0.0)\n\n\ndef batch_PSNR(img, imclean, data_range):\n Img = img.data.cpu().numpy().astype(np.float32)\n Iclean = imclean.data.cpu().numpy().astype(np.float32)\n PSNR = 0\n for i in range(Img.shape[0]):\n PSNR += compare_psnr(Iclean[i,:,:,:], Img[i,:,:,:], data_range=data_range)\n return (PSNR/Img.shape[0])\n\n\n\ndef load_projection_matrix(path):\n mat = scipy.io.loadmat(path)\n return mat['H'].todense()\n\n\ndef noisy_fbp(x, A, noise_min=1e2, noise_max=1e3):\n # Gray scale\n x = x.convert('LA')\n x = 1 - np.array(x)[:,:,0]\n # Projection\n p = np.matmul(A, x.flatten())\n # Add noise\n noises = np.random.uniform(noise_min, noise_max, size=p.shape)\n p = p + np.random.normal(np.zeros(p.shape), noises)\n return np.rot90(iradon(p.reshape(90, 90).T, output_size=64, circle=False)).copy()\n\n","sub_path":"plug_and_play_admm/denoiser/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":1691,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"127685814","text":"\n\"\"\"Design a semantic segmentation model with Keras API\n\"\"\"\n\nimport keras as K\n\nfrom deeposlandia.network import ConvolutionalNeuralNetwork\n\nclass SemanticSegmentationNetwork(ConvolutionalNeuralNetwork):\n \"\"\"Class that encapsulates semantic segmentation network creation\n\n Inherits from `ConvolutionalNeuralNetwork`\n\n Attributes\n ----------\n network_name : str\n Name of the network\n image_size : integer\n Input image size (height and width are equal)\n nb_channels : integer\n Number of input image channels (1 for greyscaled images, 3 for RGB images)\n nb_labels : integer\n Number of classes in the dataset glossary\n X : tensor\n (batch_size, image_size, image_size, nb_channels)-shaped input tensor; input image data\n Y : tensor\n (batch_size, image_size, image_size, nb_classes)-shaped output tensor, built as the output of the\n last network layer\n \"\"\"\n\n def __init__(self, network_name=\"mapillary\", image_size=512, nb_channels=3,\n nb_labels=65, dropout=1.0, architecture=\"simple\"):\n super().__init__(network_name, image_size, nb_channels, nb_labels, dropout)\n self.Y = self.simple()\n\n def output_layer(self, x, depth):\n \"\"\"Build an output layer to a neural network, as a dense layer with sigmoid activation\n function as the point is to detect multiple labels on a single image\n\n Parameters\n ----------\n x : tensor\n Previous layer within the neural network (last hidden layer)\n depth : integer\n Dimension of the previous neural network layer\n\n Returns\n -------\n tensor\n 2D output layer\n \"\"\"\n y = K.layers.Conv2DTranspose(depth, kernel_size=2, padding=\"same\", name='output_trconv')(x)\n y = K.layers.Activation('softmax', name='output_activation')(y)\n return y\n\n def simple(self):\n \"\"\"Build a simple default convolutional neural network composed of 3 convolution-maxpool\n blocks and 1 fully-connected layer\n\n Returns\n -------\n tensor\n (batch_size, image_size, image_size, nb_labels)-shaped output predictions, that have to\n be compared with ground-truth values\n \"\"\"\n layer = self.convolution(self.X, nb_filters=32, kernel_size=3, block_name='conv1')\n layer = self.maxpool(layer, pool_size=2, strides=2, block_name='pool1')\n layer = self.convolution(layer, nb_filters=64, kernel_size=3, block_name='conv2')\n layer = self.maxpool(layer, pool_size=2, strides=2, block_name='pool2')\n layer = self.convolution(layer, nb_filters=128, kernel_size=3, block_name='conv3')\n layer = self.maxpool(layer, pool_size=2, strides=2, block_name='pool3')\n layer = self.transposed_convolution(layer, nb_filters=128, strides=2, kernel_size=3, block_name=\"trconv1\")\n layer = self.transposed_convolution(layer, nb_filters=64, strides=2, kernel_size=3, block_name=\"trconv2\")\n layer = self.transposed_convolution(layer, nb_filters=32, strides=2, kernel_size=3, block_name=\"trconv3\")\n return self.output_layer(layer, depth=self.nb_labels)\n","sub_path":"deeposlandia/semantic_segmentation.py","file_name":"semantic_segmentation.py","file_ext":"py","file_size_in_byte":3180,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"305585260","text":"import os\nimport sys\nimport time\nimport traceback\nfrom contextlib import ExitStack\nfrom threading import Thread\nfrom typing import List\n\nimport numpy as np\nimport pytest\nimport requests\nfrom requests.exceptions import ConnectionError\nfrom urllib3.exceptions import ReadTimeoutError, NewConnectionError\n\nfrom jina import Document, Client\nfrom jina.logging import JinaLogger\n\ncur_dir = os.path.dirname(os.path.abspath(__file__))\ndbms_flow_yml = os.path.join(cur_dir, 'flow_dbms.yml')\nquery_flow_yml = os.path.join(cur_dir, 'flow_query.yml')\ncompose_yml = os.path.join(cur_dir, 'docker-compose.yml')\n\nJINAD_PORT_DBMS = '8001'\nJINAD_PORT_QUERY = '8001'\nREST_PORT_DBMS = '9000'\nREST_PORT_QUERY = '9001'\n\nDUMP_PATH_DOCKER = '/tmp/dump'\n\nlogger = JinaLogger('test-dump')\n\nSHARDS = 3\nEMB_SIZE = 10\n\n# global between threads\nKEEP_RUNNING = True\nINDEX_TIMES = 0\nQUERY_TIMES = 0\nDUMP_ROLL_UPDATE_TIME = 0\n\n\nclass MyThread(Thread):\n def run(self) -> None:\n try:\n super().run()\n except Exception as e:\n logger.error(sys.exc_info())\n raise e\n\n\ndef _index_client(nr_docs_index):\n global INDEX_TIMES\n logger.info(f'starting index thread. KEEP_RUNNING = {KEEP_RUNNING}')\n while KEEP_RUNNING:\n docs = list(\n _get_documents(\n nr=nr_docs_index,\n index_start=INDEX_TIMES * nr_docs_index,\n emb_size=EMB_SIZE,\n )\n )\n Client.check_input(docs)\n logger.info(f'indexing {len(docs)} docs...')\n _send_rest_request(\n REST_PORT_DBMS, 'index', 'post', [doc.dict() for doc in docs]\n )\n INDEX_TIMES += 1\n time.sleep(7)\n\n\ndef _query_client(nr_docs_query):\n global QUERY_TIMES\n logger.info(f'starting query thread. KEEP_RUNNING = {KEEP_RUNNING}')\n prev_len_matches = 0\n docs = list(_get_documents(nr=nr_docs_query, index_start=0, emb_size=EMB_SIZE))\n Client.check_input(docs)\n query_docs = [doc.dict() for doc in docs]\n while KEEP_RUNNING:\n try:\n logger.info(f'querying...')\n r = _send_rest_request(\n REST_PORT_QUERY,\n 'search',\n 'post',\n query_docs,\n timeout=8,\n )\n for doc in r['search']['docs']:\n len_matches = len(doc.get('matches'))\n assert len_matches >= prev_len_matches\n logger.info(f'got {len_matches} matches')\n if len_matches != prev_len_matches:\n # only count queries after a change in index size\n QUERY_TIMES += 1\n prev_len_matches = len_matches\n time.sleep(3)\n except (ConnectionError, ReadTimeoutError) as e:\n logger.error(f'querying failed: {e}. trying again...')\n logger.error(traceback.format_exc())\n except (NewConnectionError, Exception) as e:\n logger.error(f'error in query thread: {e!r}')\n raise e\n\n\ndef _dump_roll_update(dbms_flow_id, query_flow_id):\n global DUMP_ROLL_UPDATE_TIME\n logger.info(f'starting _dump_roll_update thread. KEEP_RUNNING = {KEEP_RUNNING}')\n folder_id = 10\n while KEEP_RUNNING:\n this_dump_path = os.path.join(DUMP_PATH_DOCKER, f'dump-{folder_id}')\n # jinad is used for ctrl requests\n logger.info(f'dumping...')\n _jinad_dump(\n 'indexer_dbms',\n this_dump_path, # the internal path in the docker container\n SHARDS,\n f'http://localhost:{JINAD_PORT_DBMS}/flows/{dbms_flow_id}',\n )\n\n logger.info(f'checking size...')\n dir_size = _path_size_remote(this_dump_path)\n assert dir_size > 0\n logger.info(f'dump path size: {dir_size}')\n\n # jinad is used for ctrl requests\n logger.info(f'rolling update...')\n _jinad_rolling_update(\n 'indexer_query',\n this_dump_path, # the internal path in the docker container\n f'http://localhost:{JINAD_PORT_QUERY}/flows/{query_flow_id}',\n )\n folder_id += 1\n logger.info(f'rolling update done!')\n DUMP_ROLL_UPDATE_TIME += 1\n time.sleep(10)\n\n\ndef _path_size_remote(this_dump_path):\n os.system(\n f'docker exec jina_jinad_1 /bin/bash -c \"du -sh {this_dump_path}\" > dump_size.txt'\n )\n contents = open('dump_size.txt').readline()\n dir_size = float(contents.split('K')[0].split('M')[0])\n return dir_size\n\n\n@pytest.mark.parametrize('docker_compose', [compose_yml], indirect=['docker_compose'])\ndef test_dump_dbms_remote_stress(docker_compose, reraise):\n def _inner_query_client(nr_docs_search):\n with reraise:\n _query_client(nr_docs_search)\n\n def _inner_index_client(nr_docs_index):\n with reraise:\n _index_client(nr_docs_index)\n\n def _inner_dump_rolling_update(dbms_flow_id, query_flow_id):\n with reraise:\n _dump_roll_update(dbms_flow_id, query_flow_id)\n\n global KEEP_RUNNING\n nr_docs_index = 20\n nr_docs_search = 3\n\n time.sleep(2)\n dbms_flow_id, query_flow_id = _create_flows()\n time.sleep(4)\n\n query_thread = MyThread(\n target=_inner_query_client,\n name='_query_client',\n args=(nr_docs_search,),\n daemon=True,\n )\n query_thread.start()\n\n index_thread = MyThread(\n target=_inner_index_client,\n name='_index_client',\n args=(nr_docs_index,),\n daemon=True,\n )\n index_thread.start()\n\n # give it time to index\n time.sleep(2)\n dump_roll_update_thread = MyThread(\n target=_inner_dump_rolling_update,\n name='_dump_roll_update',\n args=(dbms_flow_id, query_flow_id),\n daemon=True,\n )\n dump_roll_update_thread.start()\n\n threads = [query_thread, index_thread, dump_roll_update_thread]\n\n logger.info('sleeping')\n time.sleep(60)\n KEEP_RUNNING = False\n\n for t in threads:\n if not t.is_alive():\n logger.warning(f'something went wrong in thread {t.name}')\n t.join()\n assert False, f'check error from thread {t.name}'\n\n assert INDEX_TIMES > 3\n assert QUERY_TIMES > 3\n assert DUMP_ROLL_UPDATE_TIME > 2\n\n logger.info(f'ending and exit threads')\n\n\ndef _create_flows():\n # create dbms flow\n dbms_deps = [os.path.join(cur_dir, 'indexer_dbms.yml')]\n dbms_flow_id = _create_flow(\n dbms_flow_yml,\n dbms_deps,\n flow_url=f'http://localhost:{JINAD_PORT_DBMS}/flows',\n ws_url=f'http://localhost:{JINAD_PORT_DBMS}/workspaces',\n )\n # create query flow\n query_deps = [os.path.join(cur_dir, 'indexer_query.yml')]\n query_flow_id = _create_flow(\n query_flow_yml,\n query_deps,\n flow_url=f'http://localhost:{JINAD_PORT_QUERY}/flows',\n ws_url=f'http://localhost:{JINAD_PORT_QUERY}/workspaces',\n )\n return dbms_flow_id, query_flow_id\n\n\ndef _create_flow(\n flow_yaml: str,\n deps: List[str],\n flow_url: str,\n ws_url: str,\n) -> str:\n workspace_id = _create_workspace(deps, url=ws_url)\n with open(flow_yaml, 'rb') as f:\n r = requests.post(\n flow_url, data={'workspace_id': workspace_id}, files={'flow': f}\n )\n logger.info(f'Checking if the flow creation has succeeded: {r.json()}')\n assert r.status_code == 201\n return r.json()\n\n\ndef _create_workspace(filepaths: List[str], url: str) -> str:\n with ExitStack() as file_stack:\n files = [\n ('files', file_stack.enter_context(open(filepath, 'rb')))\n for filepath in filepaths\n ]\n logger.info(f'uploading {files}')\n r = requests.post(url, files=files)\n assert r.status_code == 201\n\n workspace_id = r.json()\n logger.info(f'Got workspace_id: {workspace_id}')\n return workspace_id\n\n\ndef _send_rest_request(port_expose, endpoint, method, data, timeout=13):\n json = {'data': data}\n url = f'http://0.0.0.0:{port_expose}/{endpoint}'\n r = getattr(requests, method)(url, json=json, timeout=timeout)\n\n if r.status_code != 200:\n # TODO status_code should be 201 for index\n raise Exception(\n f'api request failed, url: {url}, status: {r.status_code}, content: {r.content} data: {data}'\n )\n return r.json()\n\n\ndef _get_documents(nr=10, index_start=0, emb_size=7):\n for i in range(index_start, nr + index_start):\n with Document() as d:\n d.id = i\n d.text = f'hello world {i}'\n d.embedding = np.random.random(emb_size)\n d.tags['tag_field'] = f'tag data {i}'\n yield d\n\n\ndef _jinad_dump(pod_name, dump_path, shards, url):\n params = {\n 'kind': 'dump',\n 'pod_name': pod_name,\n 'dump_path': dump_path,\n 'shards': shards,\n }\n # url params\n logger.info(f'sending PUT req to dump')\n r = requests.put(url, params=params)\n assert r.status_code == 200\n\n\ndef _jinad_rolling_update(pod_name, dump_path, url):\n params = {\n 'kind': 'rolling_update',\n 'pod_name': pod_name,\n 'dump_path': dump_path,\n }\n # url params\n logger.info(f'sending PUT to roll update')\n r = requests.put(url, params=params)\n assert r.status_code == 200\n","sub_path":"tests/distributed/test_remote_flow_dump_rolling_update_stress/test_dumb_dbms_remote.py","file_name":"test_dumb_dbms_remote.py","file_ext":"py","file_size_in_byte":9236,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"515176020","text":"import numpy as np\n\nfrom ctranslate2.specs import common_spec, model_spec\n\n\nclass MultiHeadAttentionSpec(model_spec.LayerSpec):\n def __init__(\n self,\n self_attention=False,\n relative_position=False,\n relative_attention_bias=False,\n rms_norm=False,\n rotary_dim=None,\n rotary_interleave=True,\n num_heads_kv=None,\n ):\n self.queries_scale = model_spec.OPTIONAL\n\n self.layer_norm = common_spec.LayerNormSpec(rms_norm=rms_norm)\n self.linear = [\n common_spec.LinearSpec() for _ in range(2 if self_attention else 3)\n ]\n\n if relative_position:\n self.relative_position_keys = None\n self.relative_position_values = None\n\n if relative_attention_bias:\n self.relative_attention_bias = None\n self.relative_attention_max_distance = None\n\n if rotary_dim is not None:\n self.rotary_dim = np.dtype(\"int32\").type(rotary_dim)\n self.rotary_interleave = rotary_interleave\n\n if num_heads_kv is not None:\n self.num_heads_kv = np.dtype(\"int32\").type(num_heads_kv)\n","sub_path":"python/ctranslate2/specs/attention_spec.py","file_name":"attention_spec.py","file_ext":"py","file_size_in_byte":1143,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"308746309","text":"# uncompyle6 version 3.7.4\n# Python bytecode 2.5 (62131)\n# Decompiled from: Python 3.6.9 (default, Apr 18 2020, 01:56:04) \n# [GCC 8.4.0]\n# Embedded file name: /Users/Jon/Documents/TiddlyWiki/Trunk/contributors/JonRobson/TiddlyWeb/plugins/voting/test/test_increment.py\n# Compiled at: 2010-04-26 06:55:09\nfrom tiddlyweb.config import config\nfrom tiddlywebplugins import voting\nfrom tiddlyweb.model.tiddler import Tiddler\nfrom tiddlyweb.model.bag import Bag\nfrom tiddlyweb.model.user import User\nfrom tiddlyweb.model.policy import Policy\nfrom tiddlyweb.model.tiddler import Tiddler\nfrom tiddlyweb.store import Store, NoTiddlerError, NoBagError, NoRecipeError\nfrom tiddlyweb import control\nimport selector\nfrom test_config import setup, votebag\n\ndef setup_module(module):\n module.store = Store(config['server_store'][0], config['server_store'][1], environ={'tiddlyweb.config': config})\n module.environ = {'tiddlyweb.store': module.store, 'tiddlyweb.config': config}\n\n\ndef test_string_to_float():\n actual = voting.string_to_float(None)\n assert actual == 0\n return\n\n\ndef test_read_slices():\n setup(store)\n actual = voting.read_slices('config::snow white', 'tiddlyvoting')\n expected = {'increment.range': '-5,30', 'increment.limit': '2'}\n for i in actual:\n assert i in expected\n assert expected[i] == actual[i]\n\n\ndef test_vote_log():\n setup(store)\n config['tiddlyweb.usersign'] = {'name': 'jon'}\n config['tiddlyweb.query'] = {'bag': ['mr_and_mrs'], 'tiddler': ['little miss naughty']}\n config['tiddlyweb.query']['value'] = ['10']\n (vote1, code1) = voting.perform_action(config)\n config['tiddlyweb.query']['value'] = ['14']\n (vote2, code2) = voting.perform_action(config)\n tiddler = store.get(Tiddler('little miss naughty', 'mr_and_mrs'))\n tiddler.fields['tiddlyvoting.total'] = '2000000'\n store.put(tiddler)\n config['tiddlyweb.query']['value'] = [\n '-2']\n (vote3, code3) = voting.perform_action(config)\n assert vote1 is True\n assert vote2 is True\n assert vote3 is True\n try:\n voteLog = store.get(Tiddler('data::little miss naughty in mr_and_mrs', 'tiddlyvoting'))\n expected = ['-2::1', '10::1', '14::1', 'tiddlyvoting.total::22', 'tiddlyvoting.frequency::3', 'tiddlyvoting.average::7.33']\n actual = voteLog.text.split('\\n')\n for i in expected:\n assert i in actual\n\n except NoTiddlerError:\n assert False is True\n\n try:\n tiddler = store.get(Tiddler('little miss naughty', 'mr_and_mrs'))\n revision = tiddler.revision\n value = tiddler.fields['tiddlyvoting.total']\n except KeyError:\n value = False\n revision = False\n\n assert revision == 5\n assert value == '22'\n\n\ndef test_alloweduser_increments():\n setup(store)\n config['tiddlyweb.usersign'] = {'name': 'jon'}\n config['tiddlyweb.query'] = {'bag': ['mr_and_mrs'], 'tiddler': ['mr strong']}\n (result, code) = voting.perform_action(config)\n assert result is True\n try:\n tiddler = store.get(Tiddler('mr strong', 'mr_and_mrs'))\n value = tiddler.fields[('%s.total' % votebag)]\n except KeyError:\n value = False\n\n assert value == '1'\n try:\n tiddler = store.get(Tiddler('jon increment mr strong in mr_and_mrs', votebag))\n except NoTiddlerError:\n tiddler = False\n\n assert tiddler is not False\n\n\ndef test_unauthenticated_user_increments():\n setup(store)\n config['tiddlyweb.usersign'] = {'name': 'GUEST'}\n config['tiddlyweb.query'] = {'bag': ['mr_and_mrs'], 'tiddler': ['mr strong']}\n (result, code) = voting.perform_action(config)\n assert result is False\n try:\n tiddler = store.get(Tiddler('mr strong', 'mr_and_mrs'))\n value = tiddler.fields[('%s.total' % votebag)]\n except KeyError:\n value = False\n\n assert value == '923'\n\n\ndef test_unprivileged_user_increments():\n setup(store)\n config['tiddlyweb.usersign'] = {'name': 'FND'}\n config['tiddlyweb.query'] = {'bag': ['mr_and_mrs'], 'tiddler': ['mr strong']}\n (result, code) = voting.perform_action(config)\n assert result is False\n try:\n tiddler = store.get(Tiddler('mr strong', 'mr_and_mrs'))\n value = tiddler.fields[('%s.total' % votebag)]\n except KeyError:\n value = False\n\n assert value == '923'\n\n\ndef test_multiple_votes():\n \"\"\"\n test 1 no limit\n \n \"\"\"\n setup(store)\n config['tiddlyweb.usersign'] = {'name': 'jon'}\n config['tiddlyweb.query'] = {'bag': ['mr_and_mrs'], 'tiddler': ['mr small']}\n for i in range(1, 5):\n value = i * 10\n config['tiddlyweb.query']['value'] = ['%s' % value]\n voting.perform_action(config)\n\n try:\n tiddler = store.get(Tiddler('mr small', 'mr_and_mrs'))\n value = tiddler.fields[('%s.total' % votebag)]\n except KeyError:\n value = False\n\n assert value == '100'\n try:\n tiddler = store.get(Tiddler('jon increment mr small in mr_and_mrs', votebag))\n assert tiddler.revision == 4\n except NoTiddlerError:\n tiddler = False\n\n assert tiddler is not False\n config['tiddlyweb.usersign'] = {'name': 'jon'}\n config['tiddlyweb.query'] = {'bag': ['snow white'], 'tiddler': ['grumpy']}\n for i in range(1, 5):\n value = i * 10\n config['tiddlyweb.query']['value'] = ['%s' % value]\n voting.perform_action(config)\n\n try:\n tiddler = store.get(Tiddler('grumpy', 'snow white'))\n value = tiddler.fields[('%s.total' % votebag)]\n except KeyError:\n value = False\n\n assert value == '30'\n try:\n tiddler = store.get(Tiddler('jon increment grumpy in snow white', votebag))\n assert tiddler.revision == 2\n except NoTiddlerError:\n tiddler = False\n\n assert tiddler is not False\n\n\ndef test_minmax_votes():\n setup(store)\n config['tiddlyweb.usersign'] = {'name': 'jon'}\n config['tiddlyweb.query'] = {'bag': ['snow white'], 'tiddler': ['grumpy']}\n for i in range(-25, 10):\n value = i\n config['tiddlyweb.query']['value'] = ['%s' % value]\n voting.perform_action(config)\n\n try:\n tiddler = store.get(Tiddler('grumpy', 'snow white'))\n value = tiddler.fields[('%s.total' % votebag)]\n except KeyError:\n value = False\n\n assert value == '-9'","sub_path":"pycfiles/tiddlywebplugins.voting-0.441.tar/test_increment.py","file_name":"test_increment.py","file_ext":"py","file_size_in_byte":6295,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"236006598","text":"from mpl_toolkits.mplot3d.art3d import Poly3DCollection\r\nimport matplotlib.pyplot as plt\r\n\r\n\r\ndef visualize_mesh(faces, color='blue'):\r\n fig = plt.figure()\r\n ax = fig.add_subplot(111, projection='3d')\r\n ax.add_collection3d(Poly3DCollection(faces, facecolors=color, linewidths=1))\r\n ax.set_xlim(-0.1,0.1)\r\n ax.set_ylim(-0.1,0.1)\r\n ax.set_zlim(-0.1,0.1)\r\n plt.show()\r\n\r\ndef visualize_voxel(voxel, size=32, c1='blue', c2='red'):\r\n fig = plt.figure()\r\n ax = fig.add_subplot(111, projection='3d')\r\n ax.voxels(voxel[:,:,:,0], facecolors=c1)\r\n ax.voxels(voxel[:,:,:,1], facecolors=c2)\r\n ax.set_xlim(-1,size+1)\r\n ax.set_ylim(-1,size+1)\r\n ax.set_zlim(-1,size+1)\r\n plt.show()","sub_path":"viz.py","file_name":"viz.py","file_ext":"py","file_size_in_byte":710,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"290729439","text":"'''\nLinks:\nhttps://twiki.cern.ch/twiki/bin/view/CMSPublic/CRAB3ConfigurationFile\nhttps://twiki.cern.ch/twiki/bin/view/CMSPublic/WorkBookCRAB3Tutorial#Setup_the_environment\n'''\n\n#================================================================================================\n# Import Modules\n#================================================================================================\nfrom WMCore.Configuration import Configuration\nfrom CRABClient.UserUtilities import getUsernameFromSiteDB\n\n# Definitions\njecDB = ['Summer16_23Sep2016AllV4_DATA_JEC.db','Summer16_23Sep2016V4_MC_JEC.db','Summer16_25nsV1_80X_MC_JER.db']\n\n#================================================================================================\n# General Section: The user specifies generic parameters about the request (e.g. request name).\n#================================================================================================\nconfig = Configuration()\nconfig.section_(\"General\")\nconfig.General.requestName = rName\nconfig.General.workArea = dirName\nconfig.General.transferOutputs = True\nconfig.General.transferLogs = True\n# options:\n#config.General.failureLimit\n#config.General.instance\n#config.General.activity\n\n\n#================================================================================================\n# JobType Section: Contains all the parameters of the user job type and related configurables\n#================================================================================================\nconfig.section_(\"JobType\")\nconfig.JobType.pluginName = 'Analysis'\nconfig.JobType.psetName = 'miniAOD2TTree_cfg.py'\nconfig.JobType.pyCfgParams = ''\nconfig.JobType.outputFiles = ['miniaod2tree.root']\nconfig.JobType.inputFiles = ['jec']\nconfig.JobType.inputFiles.extend(jecDB)\n\n\n# options:\n#config.JobType.generator\n#config.JobType.inputFiles\n#config.JobType.disableAutomaticOutputCollection\n#config.JobType.eventsPerLumi\n#config.JobType.allowUndistributedCMSSW\nconfig.JobType.maxMemoryMB = 4000\n#config.JobType.maxJobRuntimeMin\n#config.JobType.numCores\n#config.JobType.priority\n#config.JobType.scriptExe\n#config.JobType.scriptArgs\n#config.JobType.sendPythonFolde\n#config.JobType.externalPluginFile\n\n\n#================================================================================================\n# Data Section: Contains all parameters related to the data to be analyzed (incl. splitting params)\n#================================================================================================\nconfig.section_(\"Data\")\nconfig.Data.inputDataset = dataset\nconfig.Data.inputDBS = 'global' #'phys03'\nconfig.Data.splitting = 'FileBased'\n#config.Data.totalUnits = 10\nconfig.Data.unitsPerJob = 5\nconfig.Data.publication = False\nconfig.Data.outLFNDirBase = '/store/user/%s/CRAB3_TransferData' % (getUsernameFromSiteDB())\n# testing:\n# config.Data.totalUnits = 100000\n# config.Data.unitsPerJob = 10000 \n# options:\n# config.Data.allowNonValidInputDatase\n# config.Data.outputPrimaryDataset\n# config.Data.inputDBS\n# config.Data.unitsPerJob\n# config.Data.useParent\n# config.Data.secondaryInputDataset\n# config.Data.lumiMask\n# config.Data.runRange\n# config.Data.outLFNDirBase\n# config.Data.publication\n# config.Data.publishDBS\n# config.Data.outputDatasetTag\n# config.Data.publishWithGroupName\n# config.Data.ignoreLocality\n# config.Data.userInputFiles\n\n\n#================================================================================================\n# Site Section: Contains the Grid site parameters (incl. stage out information)\n#================================================================================================\nconfig.section_(\"Site\")\nconfig.Site.storageSite = 'T2_FI_HIP' #'T2_CH_CERN' \n# options:\n# config.Site.blacklist = ['T2_US_Florida']\n# config.Site.whitelist = ['T2_CH_CERN', 'T2_FI_HIP']\n\n\n#================================================================================================\n# Debug Section: For experts use only\n#================================================================================================\n# config.section_(\"Debug\")\n# config.Debug.oneEventMode = True\n# config.Debug.ASOURL = ''\n# config.Debug.scheddName = ''\n# config.Debug.extraJDL = ''\n# config.Debug.collector = ''\n","sub_path":"MiniAOD2TTree/test/crabConfig.py","file_name":"crabConfig.py","file_ext":"py","file_size_in_byte":4229,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"617421148","text":"'''\nclass TEST(object):\n a = 121\n def __init__(self,b):\n self.b=b\n\n @classmethod\n def eee(self,b):\n #print TEST.a\n print a\n\n\n\nif __name__ == '__main__':\n print TEST.a\n test = TEST(3)\n TEST.eee(222)\n print TEST.a\n TEST.a =232\n print TEST.a\n print test.a\n #print test.b\n'''\nclass TianyaSpider(object):\n\n def init_start():\n url_l = u'http://search.tianya.cn/s?tn=sty&rn=10&pn='\n url_r = u'&s=0&pid=&f=0&h=1&ma=0&q=%B8%DF%BF%BC%D6%BE%D4%B8'\n urls = []\n for i in range(0,75,1):\n tem = url_l + str(i) + url_r\n urls.append(tem)\n return urls\n\n\n name = 'tianya'\n allowed_domains = ['tianya.cn']\n start_urls = init_start()","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":740,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"216677197","text":"import sys\nimport joblib\nimport numpy as np\nimport pandas as pd\nimport lightgbm as lgb\nfrom scipy.stats import uniform\nfrom sklearn.model_selection import GridSearchCV, RandomizedSearchCV\n\ndef model_train_random():\n X = joblib.load('../data_files/X_train.pkl')\n y = joblib.load('../data_files/y_train_reg.pkl')\n\n lgb_parameters = {\n 'boosting_type': ['gbdt', 'dart', 'goss'],\n 'max_depth': [-1, 2, 3, 4, 5],\n 'learning_rate': uniform(),\n 'n_estimators': [10, 50, 100],\n 'min_child_weight': uniform(),\n 'colsample_bytree': uniform(),\n 'reg_lambda': uniform()\n }\n\n grid_search = RandomizedSearchCV(\n lgb.LGBMRegressor(objective='regression'),\n lgb_parameters,\n n_iter=100,\n scoring='neg_mean_absolute_error',\n verbose=10,\n n_jobs=-1,\n cv=5\n )\n grid_search.fit(X, y)\n print(grid_search.best_params_)\n print(grid_search.best_score_)\n\nif __name__ == '__main__':\n model_train_random()\n","sub_path":"estimation/prediction/machine learning/regression/lightgbm_example.py","file_name":"lightgbm_example.py","file_ext":"py","file_size_in_byte":1007,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"468979029","text":"\n'''\nCreated on Mar 31, 2016\n\n@author: trbarret\n'''\n\nimport sys\nimport os\nfrom argparse import ArgumentParser \nfrom argparse import RawDescriptionHelpFormatter\nimport logging\nimport bcl2validation, runbcl2, bcl2testrun\n\ndef setupConsoleLogger(loglevel):\n # create logger\n consolelogger = logging.getLogger('bcl2run')\n consolelogger.setLevel(loglevel)\n # create console handler and set level to loglevel\n handler = logging.StreamHandler()\n handler.setLevel(loglevel)\n # create formatter\n formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')\n # add formatter to handler\n handler.setFormatter(formatter)\n # add handler to logger\n consolelogger.addHandler(handler)\n consolelogger.info('logger is setup')\n return consolelogger\n\ndef setupFileLogger(loglevel,rf):\n filepath = rf + '/' + 'bcl2runlog.log'\n filelogger = logging.getLogger(__name__)\n filelogger.setLevel(loglevel)\n handler = logging.FileHandler(filepath, mode='w', encoding=None, delay=True)\n handler.setLevel(loglevel)\n formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')\n handler.setFormatter(formatter)\n filelogger.addHandler(handler)\n return filelogger\n\ndef main():\n\n programdescription = '''\n This program runs bcl2 conversion on the provided run folder.\n Requirements to run this script for bcl conversion are:\n Runner must provide a valid path runfolder,\n Runner's $UID must have write privileges to the the runfolder provided and the sequence repository,\n Runner's $UID must have a mios_config json formatted connection file in the user's .ssh directory with permissions set to 600.\n Options to run this script are:\n --validation\n Providing the --validation flag will:\n Create a symlinked version of the runfolder in the validation directory at /mctp/mioncoseq/validation/bclconversion/runs,\n Run the bcl conversion,\n Move the converted sequence to a seqrepo folder in the symlinked folder,\n Test the converted sequence against the sequence in the sequence repository,\n Write a result.txt file in the seqrepo folder of the symlinked folder with:\n the file names, the md5sums and the test value,\n and a final validation passed or validation failed value.\n --testrun and --workfolder\n --testrun and --workfolder must be provided together and workfolder must be a vailid path.\n Providing the --testrun and --workfolder plus valid path will:\n Create a symlinked version of the runfolder in the workfolder directory,\n Run the bcl conversion,\n Move the converted sequence to a seqrepo folder in the symlinked folder.\n '''\n \n # Setup argument parser\n parser = ArgumentParser(description= programdescription, formatter_class=RawDescriptionHelpFormatter)\n parser.add_argument('--runfolder', dest='runfolder', action='store', required=True,\n help='provide path to run folder for bclconversion')\n group = parser.add_mutually_exclusive_group()\n group.add_argument(\"--validation\", dest=\"validation\", action=\"store_true\", default=False, \n help=\"run in validation mode add --validation\")\n group.add_argument(\"--testrun\", dest=\"testrun\", action=\"store_true\", default=False, \n help=\"run in test mode add --test and --workfolder with a valid folder path as destination\")\n parser.add_argument(\"--workfolder\", dest=\"workfolder\", action=\"store\", \n help=\"run in test mode add --test and --workfolder with a valid folder path as destination\")\n parser.add_argument('--loglevel', dest='loglevel', action='store',default='INFO',\n help=\"set loglevel to INFO or DEBUG\")\n\n # Process arguments\n args = parser.parse_args()\n rf = args.runfolder\n validation = args.validation\n testrun = args.testrun\n wf = args.workfolder\n loglevel = args.loglevel\n\n consolelogger = setupConsoleLogger(loglevel)\n\n if ( not os.path.isdir(rf) ):\n consolelogger.info('--runfolder must have a valid path to a directory')\n consolelogger.debug(rf)\n \n elif os.path.isdir(rf) and validation:\n consolelogger.info('validation true')\n consolelogger.info('command bcl2validation.main ' + rf)\n bcl2validation.main(rf,loglevel)\n \n elif os.path.isdir(rf) and not validation and testrun:\n consolelogger.info('testrun')\n if not wf:\n consolelogger.info('--testrun requires a --workfolder that must have a valid path to a directory')\n elif ( not os.path.isdir(wf) ):\n consolelogger.info('--workfolder must have a valid path to a directory')\n consolelogger.debug(wf)\n else:\n consolelogger.info('command bcl2testrun.main ' + rf + ' ' + wf + ' ' + loglevel)\n bcl2testrun.main(rf,wf,loglevel)\n \n elif os.path.isdir(rf) and not validation:\n consolelogger.info('validation false')\n repopath = '/mctp/instruments/sequencers/seq' #prod link\n #repopath = '/mctp/users/trbarret/temp/repo' #dev link\n consolelogger.info('command runbcl2.main ' + rf + ' ' + repopath)\n runbcl2.main(rf,repopath,loglevel)\n \n else:\n consolelogger.info('unhandled case')\n consolelogger.debug(sys.argv)\n\nif __name__ == \"__main__\" :\n main()\n #sys.exit(main())\n ","sub_path":"bcl2/bcl2run.py","file_name":"bcl2run.py","file_ext":"py","file_size_in_byte":5429,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"556854865","text":"\"\"\"hunter_toy.api.messages.\n\nThis module provides the API method available for the Message entity.\n\"\"\"\n\nimport flask\nimport uuid \nimport jsonschema\nfrom flask import request\nfrom flask import jsonify\nfrom flask import Response\nfrom hunter_toy.models.game import Game\nfrom hunter_toy.models.user import User\nfrom hunter_toy.models.message import Message\nfrom hunter_toy.api.validators import message as message_schemas\n\n\nmessage_bp = flask.Blueprint('message', __name__)\n\n@message_bp.route('/', methods=['POST'])\ndef create():\n \"\"\"create a message.\n json expected:\n {\n \"message\": string,\n \"sender\": string,\n \"game\": string\n }\n\n Returns:\n dict: the created message.\n \"\"\"\n payload = request.get_json()\n try:\n jsonschema.validate(payload, message_schemas.create_message_schema)\n except jsonschema.ValidationError as e:\n error_response = {\n 'errors': {\n 'msg': str(e)\n },\n }\n return (jsonify(error_response), 400)\n\n user = User.get_by_key_name(payload['sender'])\n if user is None:\n errors_response = {\n 'errors': {\n 'msg': 'User not found.'\n },\n }\n return (jsonify(errors_response), 400)\n\n game = Game.get_by_key_name(payload['game'])\n if game is None:\n errors_response = {\n 'errors': {\n 'msg': 'Game not found.'\n },\n }\n return (jsonify(errors_response), 400)\n\n message_id = str(uuid.uuid4())\n new_message = Message(\n key_name=message_id,\n message_id=message_id,\n sender=user,\n game = game,\n message = payload['message'])\n new_message.put()\n response = {\n 'data': new_message.encode(), \n }\n \n return (jsonify(response), 200)\n\n\n\n \n\n@message_bp.route('/', methods=['DELETE'])\ndef delete(message_id):\n \"\"\"delete the message with the given id_message.\n\n Args:\n message_id (str): the message identifier.\n\n Returns:\n dict: contains errors if needed.\n \"\"\"\n if message_id=='':\n error_response = {\n 'errors': {\n 'msg': 'Message not found.'\n },\n }\n return (jsonify(error_response), 404)\n \n message = Message.get_by_key_name(message_id)\n if message is None:\n error_response = {\n 'errors': {\n 'msg': 'Message not found.'\n },\n }\n return (jsonify(error_response), 404)\n\n message.delete()\n\n return (jsonify({}), 200)\n\n\n@message_bp.route('/', methods=['PATCH'])\ndef update():\n \"\"\"update the message with the given message_id.\n\n json expected:\n {\n \"message\": string,\n \"message_id\": string\n }\n \n Returns:\n dict: the updated message.\n \"\"\"\n payload = request.get_json()\n try:\n jsonschema.validate(payload, message_schemas.update_message_schema)\n except jsonschema.ValidationError as e:\n error_response = {\n 'errors': {\n 'msg': str(e)\n },\n }\n return (jsonify(error_response), 400)\n\n message_id = payload.get('message_id')\n if message_id is None or message_id=='':\n error_response = {\n 'errors': {\n 'msg': 'Message not found.'\n },\n }\n return (jsonify(error_response), 404)\n\n message = Message.get_by_key_name(message_id)\n if message is None:\n error_response = {\n 'errors': {\n 'msg': 'Message not found.'\n },\n }\n return (jsonify(error_response), 404)\n\n new_message = payload.get('message')\n\n if new_message is not None:\n message.message = new_message\n\n message.put()\n response = {\n 'data': message.encode()\n }\n\n return (jsonify(response), 200)","sub_path":"hunter_toy/api/message.py","file_name":"message.py","file_ext":"py","file_size_in_byte":3536,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"579303768","text":"def maximumFacts(suspects):\n\tif len(suspects) == 1:\n\t\treturn 0\n\telse:\n\t\tsetlist = []\n\t\tfor i in range(0,len(suspects)):\n\t\t\tfor j in range(0,len(suspects)):\n\t\t\t\tif i != j:\n\t\t\t\t\tsetlist.append(len(set(suspects[i].split(\",\")).intersection(set(suspects[j].split(\",\")))))\n\t\treturn max(setlist)\n\n","sub_path":"PositiveID.py","file_name":"PositiveID.py","file_ext":"py","file_size_in_byte":290,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"567581632","text":"from random import uniform as rnd\r\nfrom scipy.sparse import dok_matrix\r\n\r\ndef bak_ost(V, K, a):\r\n n = V // K\r\n graph = dok_matrix((V // K, V // K))\r\n numbers = [0] * (V // K)\r\n graph[0, 0] = 1\r\n vertex = [1] + [0] * (V - 1)\r\n for i in range(1, V):\r\n if a == rnd(1, (a + 1) * (i + 1) - 1):\r\n j = i\r\n else:\r\n mark = True\r\n for j in range(i):\r\n f = rnd(1, (a + 1) * (i + 1) - 1)\r\n if f <= vertex[i] - 1 + a:\r\n j = i\r\n mark = False\r\n if mark:\r\n j = i - 1\r\n vertex[j] += 1\r\n graph[j // K, i // K] += 1\r\n numbers[j // K] += 1\r\n for i in graph.keys():\r\n graph[i[0], i[1]] /= numbers[i[0]]\r\n return graph\r\n","sub_path":"prlib_for_100k/bo.py","file_name":"bo.py","file_ext":"py","file_size_in_byte":791,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"553930366","text":"import asyncio\nimport time\nimport sys\nimport os\nimport json\nimport logging\nimport typing\nimport aiohttp\n\n__all__ = ['Websocket']\n\nimport openhivenpy.types as types\nfrom .. import exception as errs\nfrom ..utils import utils as utils\nfrom ..events import EventHandler\nfrom ..settings import load_env\n\nlogger = logging.getLogger(__name__)\n\n# Loading the environment variables\nload_env()\n# Setting the default values to the currently set defaults in the openhivenpy.env file\n_default_host = os.getenv(\"HIVEN_HOST\")\n_default_api_version = os.getenv(\"HIVEN_API_VERSION\")\n_default_connection_heartbeat = int(os.getenv(\"CONNECTION_HEARTBEAT\"))\n_default_close_timeout = int(os.getenv(\"CLOSE_TIMEOUT\"))\n\n\nclass Websocket(types.Client):\n \"\"\"\n Websocket Class that will listen to the Hiven Swarm and handle server-sent message and trigger events if received!\n Uses an instance of `openhivenpy.EventHandler` for EventHandling and will execute registered functions.\n \"\"\"\n\n # Websocket Events\n EVENT = 0\n CONNECTION_START = 1\n\n def __init__(\n self,\n token: str,\n *,\n restart: bool = False,\n log_ws_output: bool = False,\n host: str = _default_host,\n api_version: str = _default_api_version,\n heartbeat: int = _default_connection_heartbeat,\n close_timeout: int = _default_close_timeout,\n event_handler: EventHandler,\n event_loop: typing.Optional[asyncio.AbstractEventLoop] = asyncio.get_event_loop(),\n **kwargs):\n \"\"\"\n Object Instance Construction\n :param token: Authorisation Token for Hiven\n :param restart: If set to True the process will restart if an exception occurred\n :param host: Url for the API which will be used to interact with Hiven.\n Defaults to the pre-set environment host (api.hiven.io)\n :param api_version: Version string for the API Version. Defaults to the pre-set environment version (v1)\n :param heartbeat: Intervals in which the bot will send heartbeats to the Websocket.\n Defaults to the pre-set environment heartbeat (30000)\n :param close_timeout: Seconds after the websocket will timeout after the end handshake didn't complete\n successfully. Defaults to the pre-set environment close_timeout (40)\n :param event_loop: Event loop that will be used to execute all async functions. Will use 'asyncio.get_event_loop()' to fetch the EventLoop. Will create a new one if no one was created yet\n :param event_handler: Handler for Websocket Events\n \"\"\"\n\n self._host = host\n self._api_version = api_version\n\n self._WEBSOCKET_URL = \"wss://swarm-dev.hiven.io/socket?encoding=json&compression=text_json\"\n self._ENCODING = \"json\"\n\n # In milliseconds\n self._HEARTBEAT = heartbeat\n self._TOKEN = token\n self._close_timeout = close_timeout\n self._event_handler = event_handler\n self._event_loop = event_loop\n self._restart = restart\n self._log_ws_output = log_ws_output\n self._CUSTOM_HEARTBEAT = False if self._HEARTBEAT == int(os.getenv(\"CONNECTION_HEARTBEAT\")) else True\n self._ws_session = None\n self._ws = None\n self._connection_task = None\n self._lifesignal = None\n\n # Websocket and Connection Attribute\n self._open = False\n self._connection_start = None\n self._startup_time = None\n self._initialised = False\n self._ready = False\n self._connection_start = None\n self._connection_status = \"CLOSED\"\n\n self.EVENT_PARSERS = {\n \"USER_UPDATE\": \"user_update_handler\",\n \"HOUSE_JOIN\": 'house_join_handler',\n \"HOUSE_LEAVE\": 'house_leave_handler',\n \"HOUSE_UPDATE\": 'house_update_handler',\n \"HOUSE_DOWN\": 'house_down_handler',\n \"HOUSE_MEMBERS_CHUNK\": 'member_chunk_handler',\n \"HOUSE_MEMBER_JOIN\": 'house_member_join_handler',\n \"HOUSE_MEMBER_ENTER\": 'house_member_enter',\n \"HOUSE_MEMBER_LEAVE\": 'house_member_leave',\n \"HOUSE_MEMBER_EXIT\": 'house_member_exit_handler',\n \"HOUSE_MEMBER_UPDATE\": 'house_member_update_handler',\n \"ROOM_CREATE\": 'room_create_handler',\n \"PRESENCE_UPDATE\": 'presence_update_handler',\n \"MESSAGE_CREATE\": 'message_create_handler',\n \"MESSAGE_DELETE\": 'message_delete_handler',\n \"MESSAGE_UPDATE\": 'message_update_handler',\n \"TYPING_START\": 'typing_start_handler',\n \"BATCH_HOUSE_MEMBER_UPDATE\": 'batch_house_member_handler',\n \"HOUSE_ENTITIES_UPDATE\": 'house_entity_update_handler',\n \"RELATIONSHIP_UPDATE\": 'relationship_update_handler'\n }\n\n # Initialising the parent class Client which handles the data\n super().__init__()\n\n @property\n def open(self):\n return getattr(self, '_open', False)\n\n @property\n def closed(self):\n return not getattr(self, 'open', False)\n\n @property\n def close_timeout(self) -> int:\n return getattr(self, '_close_timeout', None)\n\n @property\n def websocket_url(self) -> str:\n return getattr(self, '_WEBSOCKET_URL', None)\n\n @property\n def encoding(self) -> str:\n return getattr(self, '_ENCODING', None)\n\n @property\n def heartbeat(self) -> int:\n return getattr(self, '_HEARTBEAT', None)\n\n @property\n def ws_session(self) -> aiohttp.ClientSession:\n return getattr(self, '_ws_session', None)\n\n @property\n def ws(self) -> aiohttp.ClientWebSocketResponse:\n return getattr(self, '_ws', None)\n\n @property\n def ws_connection(self) -> asyncio.Task:\n return getattr(self, '_connection', None)\n\n @property\n def connection_status(self) -> str:\n return getattr(self, '_connection_status', 'CLOSED')\n\n @property\n def event_handler(self) -> EventHandler:\n return getattr(self, '_event_handler', None)\n\n @property\n def ready(self) -> bool:\n return getattr(self, '_ready', False)\n\n @property\n def initialised(self) -> bool:\n return getattr(self, '_initialised', False)\n\n # Starts the connection over a new websocket\n async def ws_connect(self, session: aiohttp.ClientSession, heartbeat: int = None) -> None:\n \"\"\"\n Creates a connection to the Hiven API.\n\n Not Intended for User Usage\n \"\"\"\n self._HEARTBEAT = heartbeat if heartbeat is not None else self._HEARTBEAT\n self._ws_session = session\n\n async def ws_connection():\n \"\"\"\n Connects to Hiven using the http-session that was created prior during\n startup. The websocket will then interact with Hiven and await responses\n and react with pongs on pings. Will send lifesignals over the pre-set\n Heartbeat to ensure the connection stays alive and does not time-out.\n\n \"\"\"\n try:\n async with session.ws_connect(\n url=self._WEBSOCKET_URL,\n timeout=self._close_timeout,\n autoping=True,\n autoclose=True,\n heartbeat=self._HEARTBEAT,\n receive_timeout=None,\n max_msg_size=0) as ws:\n\n self._ws = ws\n self._connection_status = \"OPEN\"\n self._open = True\n\n # Waits until the Connection Start event has finished\n await self.event_handler.dispatch_on_connection_start()\n\n # Running the lifesignal and response handling parallel\n await asyncio.gather(self.lifesignal(ws), self.message_handler(ws=ws))\n\n except KeyboardInterrupt:\n raise KeyboardInterrupt\n\n except Exception as ws_e:\n utils.log_traceback(level='critical',\n msg=\"[WEBSOCKET] Traceback:\",\n suffix=f\"[WEBSOCKET] The connection to Hiven failed to be kept alive or started:\\n\"\n f\"{sys.exc_info()[0].__name__}, {str(ws_e)}\")\n\n # Closing\n close = getattr(self, \"close\", None)\n if callable(close):\n await close(\n close_exec_loop=True,\n reason=\"WebSocket encountered an error!\",\n block_restart=not self._restart\n )\n\n return\n\n finally:\n self._open = False\n return\n\n # Creating a task that wraps the coroutine\n self._connection_task = asyncio.create_task(ws_connection())\n\n # Running the task in the background\n try:\n await self._connection_task\n except KeyboardInterrupt:\n pass\n\n # Avoids that the user notices that the task was cancelled!\n except asyncio.CancelledError:\n logger.debug(\"[WEBSOCKET] << The websocket Connection to Hiven unexpectedly stopped and was cancelled! \"\n \"Likely caused due to an error or automatic/forced closing!\")\n\n except Exception as e:\n logger.debug(\"[WEBSOCKET] << The websocket Connection to Hiven unexpectedly stopped and failed to process! \"\n f\"> {sys.exc_info()[0].__name__}: {e}!\")\n\n raise errs.HivenGatewayError(f\"[WEBSOCKET] << Exception in main-websocket process!\"\n f\"> {sys.exc_info()[0].__name__}: {e}!\")\n\n # Loop for receiving messages from Hiven\n async def message_handler(self, ws) -> None:\n \"\"\"\n Message Handler for the websocket that will handle messages received over the websocket connection\n and if needed trigger an event using the function text_based_message_handler(), which triggers events\n if needed. The incoming messages in this case are handled when they arrive meaning that a loop will\n await a new message and if one is received handle the message and pass it as a dict to the\n text_based_message_handler() if the type is correct json. If it's not it will log a warning containing\n that message!\n\n :param ws: The aiohttp websocket instance needed for interaction with Hiven\n :return: None - Only returns if the process failed or the websocket was forced to close!\n \"\"\"\n # This process will break if a close frame was received, which automatically\n # closes the connection. This is then only way the connection should normally close\n # except a user forced the ws to close or a exception was raised while processing.\n while self.open:\n ws_msg = await ws.receive()\n if ws_msg is not None:\n # Logging the Received Type\n logger.debug(f\"[WEBSOCKET] << Got Type {ws_msg.type} - {repr(ws_msg.type)}\")\n\n # Checking if the msg type is text and therefore can be used\n if ws_msg.type == aiohttp.WSMsgType.TEXT:\n if ws_msg.data is not None:\n try:\n json_data = json.loads(ws_msg.data)\n except ValueError:\n json_data = None\n else:\n json_data = None\n\n # If the data is in json format it can be handled as event\n if json_data is not None:\n op = json_data.get('op')\n event = json_data.get('e')\n data = json_data.get('d')\n\n if self._log_ws_output:\n logger.debug(f\"[WEBSOCKET] << Received: {json_data}\")\n\n # If the op-code is 1 the server expects the client to authorise\n if op == self.CONNECTION_START:\n # Authorizing with token\n logger.info(\"[WEBSOCKET] >> Authorizing with token\")\n json_auth = str(json.dumps({\"op\": 2, \"d\": {\"token\": self._TOKEN}}))\n await ws.send_str(json_auth)\n\n if self._CUSTOM_HEARTBEAT is False:\n self._HEARTBEAT = data.get('hbt_int', _default_connection_heartbeat)\n ws.heartbeat = self._HEARTBEAT\n\n logger.debug(f\"[WEBSOCKET] >> Heartbeat set to {ws.heartbeat}\")\n logger.info(\"[WEBSOCKET] << Connection to Hiven Swarm established\")\n\n elif op == self.EVENT:\n if event == \"INIT_STATE\":\n try:\n # Initialising the data of the Client\n await super().initialise_hiven_client_data(json_data.get('d'))\n except Exception as e:\n utils.log_traceback(msg=\"Traceback of failed Initialisation: \",\n suffix=f\"Failed to initialise and load data of the Client: \\n\"\n f\"{sys.exc_info()[0].__name__}: {e}\")\n raise errs.InitializationError()\n\n # init_time = Time it took to initialise\n init_time = time.time() - self._connection_start\n self._initialised = True\n\n # Calling the event 'on_init()'\n await self.event_handler.dispatch_on_init(time=init_time)\n else:\n # Calling the websocket message handler for handling the incoming ws message\n await self.text_based_message_handler(op, event, data)\n\n else:\n logger.warning(f\"[WEBSOCKET] Received unexpected op code: '{op}' with event {event}\")\n else:\n logger.warning(f\"[WEBSOCKET] Received unexpected non-json text type: '{ws_msg.data}'\")\n\n elif ws_msg.type == aiohttp.WSMsgType.CLOSE or ws_msg.type == aiohttp.WSMsgType.CLOSING:\n # Close Frame can be received because of these issues:\n # - Faulty token\n # - Error occurred while handling a ws message => aiohttp automatically stops\n # - Server unreachable\n # - Hiven send one back because faulty authorisation!\n logger.debug(f\"[WEBSOCKET] << Received close frame with msg='{ws_msg.extra}'!\")\n break\n\n elif ws_msg.type == aiohttp.WSMsgType.CLOSED:\n logger.debug(f\"[WEBSOCKET] << Websocket closed due to aiohttp CLOSE call!\")\n break\n\n elif ws_msg.type == aiohttp.WSMsgType.ERROR:\n logger.critical(f\"[WEBSOCKET] Failed to handle response >> {ws.exception()} >>{ws_msg}\")\n raise errs.WebSocketMessageError(ws_msg.data)\n\n # Closing the websocket instance if it wasn't closed\n if not ws.closed:\n await ws.close()\n\n logger.info(f\"[WEBSOCKET] << Connection to Remote ({self._WEBSOCKET_URL}) closed!\")\n self._open = False\n\n # Trying to fetch the close method of the Connection class which stops the currently running processes\n close = getattr(self, \"close\", None)\n if callable(close):\n await close(close_exec_loop=True, reason=\"Response Handler stopped!\", block_restart=not self._restart)\n\n return\n\n async def lifesignal(self, ws) -> None:\n \"\"\"\n Lifesignal Task sending lifesignal messages to the Hiven Swarm\n\n Not Intended for User Usage\n\n :param ws: The aiohttp websocket instance needed for interaction with Hiven\n :return: None - Only returns if the process failed or the websocket was forced to close!\n \"\"\"\n try:\n # Life Signal that sends an op-code to Hiven to signalise the client instance is still alive!\n # Will automatically break if the connection status is CLOSING or CLOSED\n async def _lifesignal():\n while self._open and self.connection_status not in [\"CLOSING\", \"CLOSED\"]:\n await asyncio.sleep(self._HEARTBEAT / 1000) # Converting the Heartbeat to seconds from ms\n\n logger.debug(f\"[WEBSOCKET] >> Lifesignal at {time.time()}\")\n await ws.send_str(str(json.dumps({\"op\": 3})))\n return\n\n self._connection_status = \"OPEN\"\n\n # Wrapping the lifesignal into a task so it can be easily stopped if needed\n self._lifesignal = asyncio.create_task(_lifesignal())\n await self._lifesignal\n return\n\n # If the task is cancelled it will return without logging\n except asyncio.CancelledError:\n return\n\n except Exception as e:\n utils.log_traceback(level='critical',\n msg=\"[WEBSOCKET] Traceback:\",\n suffix=f\"[WEBSOCKET] << Failed to keep lifesignal alive!: \\n\"\n f\"{sys.exc_info()[0].__name__}: {e}\")\n\n async def wait_for_ready(self):\n \"\"\"\n Returns when the WebSocket is ready. Will be used to make sure events that happen while initialisation\n wait until the Client has loaded successfully.\n\n :return: None when the Websocket is ready\n \"\"\"\n while True:\n if self.ready:\n return\n await asyncio.sleep(0.05)\n\n async def wait_for_initialised(self):\n \"\"\"\n Returns when the WebSocket is initialised. Will be used to make sure events that happen while initialisation\n wait until the Client has initialised successfully.\n\n :return: None when the Websocket is initialised\n \"\"\"\n while True:\n if self.initialised:\n return\n await asyncio.sleep(0.05)\n\n # Event Triggers\n async def text_based_message_handler(self, op: int, event: str, data: dict):\n \"\"\"\n Handler for the Websocket events and the message data.\n\n Triggers based on the passed data an event\n\n :param op: Send op-code\n :param event: Event-key identifier\n :param data: JSON-Data for the event\n \"\"\"\n try:\n logger.debug(f\"Received Event {event}\")\n\n event_handler = self.EVENT_PARSERS.get(event)\n if event_handler:\n coro = getattr(self, event_handler, None)\n\n # HOUSE_JOIN events must always be prioritised since they are needed for initialisation!\n if event == 'HOUSE_JOIN':\n await asyncio.wait_for(self.wait_for_initialised(), 30)\n else:\n coro_ = coro\n\n async def waiting_task(data_):\n await asyncio.wait_for(self.wait_for_ready(), 30)\n await coro_(data_)\n return\n\n # Updating the coro to the waiting coroutine\n coro = waiting_task\n asyncio.create_task(coro(data))\n else:\n logger.error(f\"[WEBSOCKET] << Unknown Event {event} without Handler!\")\n return\n\n except Exception as e:\n utils.log_traceback(level='debug',\n msg=\"[WEBSOCKET] Traceback:\",\n suffix=f\"Failed to handle incoming json-type text message in the websocket: \\n\"\n f\"{sys.exc_info()[0].__name__}: {e}\")\n\n async def user_update_handler(self, data: dict):\n \"\"\"\n Handler for User Account Updates\n\n :param data: The incoming ws text msg - Should be in correct python dict format\n \"\"\"\n try:\n cached_user = utils.get(self._users, id=utils.convert_value(int, data.get('id')))\n if cached_user is not None:\n # Removing the older cached user\n self._users.remove(cached_user)\n\n user = await types.User.from_dict(data, self.http)\n if user:\n self._users.append(user)\n else:\n logger.warning(\"[USER_UPDATE] Failed to create User instance of user with id \"\n f\"{data.get('id')}\")\n else:\n user = None\n logger.warning(f\"[USER_UPDATE] Failed to update user data of \"\n f\"{data.get('name')} in client cache: Member not found locally!\")\n\n await self.event_handler.dispatch_on_user_update(old=cached_user, new=user)\n\n except Exception as e:\n utils.log_traceback(msg=\"[USER_UPDATE] Traceback:\",\n suffix=\"Failed to handle the event due to an exception occurring: \\n\"\n f\"> {sys.exc_info()[0].__name__}: {e}\")\n\n async def house_update_handler(self, data: dict):\n \"\"\"\n Handler for the update of a house. Dispatches the handler `on_house_update`\n and returns as parameter the updated House instance\n\n :param data: The incoming ws text msg - Should be in correct python dict format\n \"\"\"\n try:\n cached_house = utils.get(self.houses, id=utils.convert_value(int, data.get('id')))\n # Fetching the old data to overwrite the new house\n members = list(cached_house.members)\n rooms = list(cached_house.rooms)\n data['members'] = []\n data['rooms'] = []\n\n # Creating a new instance\n house = await types.House.from_dict(data, self.http, self.rooms, client_id=self.user.id)\n house._members = members\n house._rooms = rooms\n house._client_member = self.user\n\n self._houses.remove(cached_house)\n self._houses.append(house)\n\n await self.event_handler.dispatch_on_house_update(old=cached_house, new=house)\n\n except Exception as e:\n utils.log_traceback(msg=\"[HOUSE_UPDATE] Traceback:\",\n suffix=\"Failed to handle the event due to an exception occurring: \\n\"\n f\"> {sys.exc_info()[0].__name__}: {e}\")\n\n async def house_down_handler(self, data: dict):\n \"\"\"\n Handler for downtime of a house! Triggers on_house_down and\n returns as parameter the time of downtime and the house\n\n If the property unavailable of the message is false\n\n :param data: The incoming ws text msg - Should be in correct python dict format\n \"\"\"\n try:\n house = utils.get(self._houses, id=utils.convert_value(int, data.get('house_id')))\n if data.get('unavailable'):\n logger.debug(f\"[HOUSE_DOWN] << Downtime of '{house.name}' reported! \"\n \"House was either deleted or is currently unavailable!\")\n await self.event_handler.dispatch_on_house_down_time(house_id=house.id)\n else:\n # Removing the deleted house\n self._houses.remove(house)\n await self.event_handler.dispatch_on_house_delete(house_id=house.id)\n\n except Exception as e:\n utils.log_traceback(msg=\"[HOUSE_DOWN] Traceback:\",\n suffix=\"Failed to handle the event due to an exception occurring: \\n\"\n f\"> {sys.exc_info()[0].__name__}: {e}\")\n\n async def member_chunk_handler(self, data: dict):\n \"\"\"\n In Work!\n\n Handler for a house member chunk update which updates for every\n sent member object the object in the house list. Triggers\n on_house_member_chunk and returns as parameter the changed\n members, the raw data and the house object.\n\n :param data: The incoming ws text msg - Should be in correct python dict format\n \"\"\"\n try:\n # Fetching the house based on the ID\n house = utils.get(self.houses, id=utils.convert_value(int, data.get('house_id')))\n\n # Member data that was sent with the request\n sent_member_data = data.get('members')\n updated_members = []\n\n # For every member that was sent and their data the stored cached data will be replaced\n for mem_id, mem_data in sent_member_data.items():\n cached_member = utils.get(house.members, id=utils.convert_value(int, mem_id))\n if cached_member is not None:\n # Removing the older cached member\n house._members.remove(cached_member)\n\n # Creating a new Member Class and appending the new data\n member = await types.Member.from_dict(mem_data, self.http, house=house)\n\n if member is not None:\n # Appending the new member\n house._members.append(member)\n\n # Appending to the 'changelog' list the member\n updated_members.append(member)\n else:\n logger.warning(\"[HOUSE_MEMBERS_CHUNK] Failed to create Member instance of user with id \"\n f\"{mem_data.get('id')}\")\n else:\n logger.warning(f\"[HOUSE_MEMBERS_CHUNK] Failed to update member data of \"\n f\"{mem_data.get('name')} in house {house.name}: Member not found locally!\")\n\n cached_user = utils.get(self._users, id=utils.convert_value(int, mem_id))\n if cached_user is not None:\n # Removing the older cached user\n self._users.remove(cached_user)\n\n user = await types.User.from_dict(sent_member_data.get(mem_id), self.http)\n if user:\n self._users.append(user)\n else:\n logger.warning(\"[HOUSE_MEMBERS_CHUNK] Failed to create User instance of user with id \"\n f\"{mem_data.get('id')}\")\n else:\n logger.warning(f\"[HOUSE_MEMBERS_CHUNK] Failed to update user data of \"\n f\"{mem_data.get('name')} in client cache: Member not found locally!\")\n\n await self.event_handler.dispatch_on_house_member_chunk(members=updated_members, data=data, house=house)\n\n except Exception as e:\n utils.log_traceback(msg=\"[HOUSE_MEMBERS_CHUNK] Traceback:\",\n suffix=\"Failed to handle the event due to an exception occurring: \\n\"\n f\"{sys.exc_info()[0].__name__}: {e}\")\n\n async def house_member_enter(self, data: dict):\n \"\"\"\n Handler for a member going online in a mutual house. Trigger on_house_enter\n and returns as parameters the member obj and house obj.\n\n :param data: The incoming ws text msg - Should be in correct python dict format\n \"\"\"\n try:\n house_id = data.get('house_id')\n if house_id is None:\n house_id = data.get('house', {}).get('id')\n\n # Fetching the house\n house = utils.get(self.houses, id=utils.convert_value(int, house_id))\n\n # Fetching the cached_member\n cached_member = utils.get(house.members, user_id=utils.convert_value(int, data.get('user_id')))\n\n await self.event_handler.dispatch_on_house_member_enter(member=cached_member, house=house)\n\n except Exception as e:\n utils.log_traceback(msg=\"[HOUSE_MEMBER_ENTER] Traceback:\",\n suffix=\"Failed to handle the event due to an exception occurring: \\n\"\n f\"{sys.exc_info()[0].__name__}: {e}\")\n\n async def house_member_update_handler(self, data: dict):\n \"\"\"\n Handler for a house member update which will trigger on_member_update and return\n as parameter the old member obj, the new member obj and the house.\n\n :param data: The incoming ws text msg - Should be in correct python dict format\n \"\"\"\n try:\n house = utils.get(self.houses, id=utils.convert_value(int, data.get('house_id')))\n\n cached_user = utils.get(self.users, id=utils.convert_value(int, data.get('user_id')))\n user = await types.User.from_dict(data, self.http)\n\n # Removing the old user\n if cached_user:\n self._users.remove(cached_user)\n # Appending the new user\n self._users.append(user)\n\n # Getting the cached member in the house if it exists\n cached_member = utils.get(house.members, user_id=utils.convert_value(int, data.get('user_id')))\n member = await types.Member.from_dict(data, self.http, house=house)\n\n if cached_member:\n # Removing the old member\n house._members.remove(cached_member)\n # Appending the new member\n house._members.append(member)\n\n await self.event_handler.dispatch_on_member_update(old=cached_member, new=member, house=house)\n\n except Exception as e:\n utils.log_traceback(msg=\"[HOUSE_MEMBER_UPDATE] Traceback:\",\n suffix=\"Failed to handle the event due to an exception occurring: \\n\"\n f\"{sys.exc_info()[0].__name__}: {e}\")\n\n async def house_member_join_handler(self, data: dict):\n \"\"\"\n Handler for a House Join Event where a user joined a house. Triggers on_member_join and passes the house and\n the member as arguments.\n\n :param data: The incoming ws text msg - Should be in correct python dict format\n \"\"\"\n try:\n # Fetching the ID of the house\n house_id = data.get('house_id')\n # Fetching the house from the cache\n house = utils.get(self.houses, id=utils.convert_value(int, house_id))\n\n id_ = data.get('user', {}).get('id')\n user_id = utils.convert_value(int, id_ if id_ is not None else data.get('id'))\n\n # Fetching the user from the cache\n cached_user = utils.get(self.users, id=user_id)\n\n if cached_user is None:\n # Requesting full data of the user\n raw_data = self.http.request(f\"/users/{user_id}\")\n\n if raw_data:\n user = await types.User.from_dict(raw_data.get('data'), self.http)\n # Appending the newly created user-object\n self._users.append(user)\n\n else:\n raise errs.HTTPReceivedNoDataError()\n\n cached_member = utils.get(house.members, user_id=user_id)\n if cached_member is None:\n # Removing the cached_data\n house._members.remove(cached_member)\n\n member = await types.Member.from_dict(data, self.http, house=house)\n # Appending the newly created member-object\n house._members.append(member)\n\n await self.event_handler.dispatch_on_house_member_join(member=cached_member, house=house)\n\n except Exception as e:\n utils.log_traceback(msg=\"[HOUSE_MEMBER_JOIN] Traceback:\",\n suffix=\"Failed to handle the event due to an exception occurring: \\n\"\n f\"{sys.exc_info()[0].__name__}: {e}\")\n\n async def room_create_handler(self, data: dict):\n \"\"\"\n Handler for Room creation in a house. Triggers on_room_create() and passes the room as argument\n\n :param data: The incoming ws text msg - Should be in correct python dict format\n \"\"\"\n try:\n # House Room\n if data.get('house_id'):\n house = utils.get(self._houses, id=utils.convert_value(int, data.get('house_id')))\n\n # Creating a new room\n room = await types.Room.from_dict(data, self.http, house=house)\n\n # Appending the updated room\n self._rooms.append(room)\n house._rooms.append(room)\n else:\n # Private Group Room\n room = await types.PrivateGroupRoom.from_dict(data, self.http, users=self.users, client_user=self.user)\n self._private_rooms.append(room)\n\n await self.event_handler.dispatch_on_room_create(room=room)\n\n except Exception as e:\n utils.log_traceback(msg=\"[ROOM_CREATE] Traceback:\",\n suffix=\"Failed to handle the event due to an exception occurring: \\n\"\n f\"{sys.exc_info()[0].__name__}: {e}\")\n\n async def house_member_exit_handler(self, data: dict):\n \"\"\"\n Handler for a house member exit event. Removes the member\n from the house members list and triggers on_house_exit and\n returns as parameter the user obj and house obj.\n\n :param data: The incoming ws text msg - Should be in correct python dict format\n \"\"\"\n try:\n house = utils.get(self._houses, id=utils.convert_value(int, data.get('house_id')))\n cached_mem = utils.get(house.members, user_id=utils.convert_value(int, data.get('id')))\n\n await self.event_handler.dispatch_on_house_member_exit(member=cached_mem, house=house)\n\n except Exception as e:\n utils.log_traceback(msg=\"[HOUSE_MEMBER_EXIT] Traceback:\",\n suffix=\"Failed to handle the event due to an exception occurring: \\n\"\n f\"{sys.exc_info()[0].__name__}: {e}\")\n\n async def presence_update_handler(self, data: dict):\n \"\"\"\n Handler for a User Presence update\n\n :param data: The incoming ws text msg - Should be in correct python dict format\n \"\"\"\n try:\n user = await types.User.from_dict(data, self.http)\n presence = user.presence\n\n await self.event_handler.dispatch_on_presence_update(presence, user)\n\n except Exception as e:\n utils.log_traceback(msg=\"[PRESENCE_UPDATE] Traceback:\",\n suffix=\"Failed to handle the event due to an exception occurring: \\n\"\n f\"{sys.exc_info()[0].__name__}: {e}\")\n\n async def message_create_handler(self, data: dict):\n \"\"\"\n Handler for a user-created messages which will trigger the 'on_message_create' event.\n Will return as parameter the created msg object.\n\n :param data: The incoming ws text msg - Should be in correct python dict format\n \"\"\"\n try:\n if data.get('house_id'):\n house = utils.get(self.houses, id=utils.convert_value(int, data.get('house_id')))\n else:\n house = None\n\n if house:\n # Updating the last message ID in the Room\n room = utils.get(self.rooms, id=utils.convert_value(int, data.get('room_id')))\n if room is not None:\n # Updating the last message_id\n room._last_message_id = utils.convert_value(int, data.get('id'))\n else:\n logger.warning(\"[MESSAGE_CREATE] Unable to find room in the cache! \"\n f\"ROOM_ID={data.get('room_id')}\")\n\n # It's a private_room with no existing house\n else:\n # Updating the last message ID in the Private-Room\n private_room = utils.get(self.private_rooms, id=utils.convert_value(int, data.get('room_id', 0)))\n if private_room is not None:\n # Updating the last message_id\n private_room._last_message_id = utils.convert_value(int, data.get('id'))\n\n # Room where the message was sent => private_room\n room = private_room\n else:\n room = None\n logger.warning(\"[MESSAGE_CREATE] Unable to find private-room in the cache! \"\n f\"ROOM_ID={data.get('room_id')}\")\n\n msg = await types.Message.from_dict(data, self.http, house_=house, room_=room, users=self.users)\n\n await self.event_handler.dispatch_on_message_create(msg)\n\n except Exception as e:\n utils.log_traceback(msg=\"[MESSAGE_CREATE] Traceback:\",\n suffix=\"Failed to handle the event due to an exception occurring: \\n\"\n f\"{sys.exc_info()[0].__name__}: {e}\")\n\n async def message_delete_handler(self, data: dict):\n \"\"\"\n Handler for a deleted message which will trigger the on_message_delete event\n and return as parameter a DeletedMessage object.\n\n :param data: The incoming ws text msg - Should be in correct python dict format\n \"\"\"\n try:\n msg = await types.DeletedMessage.from_dict(data)\n\n # Creating a new task for handling the event\n await self.event_handler.dispatch_on_message_delete(msg)\n\n except Exception as e:\n utils.log_traceback(msg=\"[MESSAGE_DELETE] Traceback:\",\n suffix=\"Failed to handle the event due to an exception occurring: \\n\"\n f\"> {sys.exc_info()[0].__name__}: {e}\")\n\n async def message_update_handler(self, data: dict):\n \"\"\"\n Handler for a deleted message which will create a new msg object\n and return as parameter the object.\n\n :param data: The incoming ws text msg - Should be in correct python dict format\n \"\"\"\n try:\n # Removes old data in the client cache if possible and reuses older data since\n # no new data is getting sent with the event.\n\n if data.get('house_id') is not None:\n house = utils.get(self._houses, id=utils.convert_value(int, data.get('house_id', 0)))\n else:\n house = None\n\n if house:\n # Updating the last message ID in the Room\n room = utils.get(self._rooms, id=utils.convert_value(int, data.get('room_id', 0)))\n if room in self._rooms:\n self._rooms.remove(room)\n room._last_message_id = utils.convert_value(int, data.get('id'))\n self._rooms.append(room)\n else:\n room = None\n logger.warning(\"[MESSAGE_UPDATE] Unable to find private-room in the cache! \"\n f\"ROOM_ID={data.get('room_id')}\")\n\n else:\n # Updating the last message ID in the Private-Room\n private_room = utils.get(self._private_rooms, id=utils.convert_value(int, data.get('room_id', 0)))\n if private_room:\n self._private_rooms.remove(private_room)\n private_room._last_message_id = utils.convert_value(int, data.get('id'))\n self._private_rooms.append(private_room)\n\n room = private_room\n else:\n logger.warning(\"[MESSAGE_UPDATE] Unable to find private-room in the cache! \"\n f\"ROOM_ID={data.get('room_id')}\")\n room = None\n\n message = await types.Message.from_dict(data, self.http, house_=house, room_=room, users=self.users)\n\n await self.event_handler.dispatch_on_message_update(message)\n\n except Exception as e:\n utils.log_traceback(msg=\"[MESSAGE_UPDATE] Traceback:\",\n suffix=\"Failed to handle the event due to an exception occurring: \\n\"\n f\"{sys.exc_info()[0].__name__}: {e}\")\n\n async def relationship_update_handler(self, data: dict):\n \"\"\"\n Handler for a relationship update. Triggers on_relationship_update\n and returns as parameter the relationship obj.\n\n :param data: The incoming ws text msg - Should be in correct python dict format\n \"\"\"\n try:\n cache_relationship = utils.get(self._relationships, id=utils.convert_value(int, data.get('id')))\n relationship = await types.Relationship.from_dict(data, self.http, self.users)\n if cache_relationship:\n # Removing the old data\n self._relationships.remove(cache_relationship)\n\n # Adding the new data\n self._relationships.append(relationship)\n\n await self.event_handler.dispatch_on_relationship_update(relationship=relationship)\n\n except Exception as e:\n utils.log_traceback(msg=\"[RELATIONSHIP_UPDATE] Traceback:\",\n suffix=\"Failed to handle the event due to an exception occurring: \\n\"\n f\"{sys.exc_info()[0].__name__}: {e}\")\n\n async def house_join_handler(self, data: dict):\n \"\"\"\n Handler for the dispatch_on_house_add event of the connected client which will trigger\n the on_house_join event and return as parameter the house.\n\n :param data: The incoming ws text msg - Should be in correct python dict format\n \"\"\"\n try:\n # Creating a house object that will then be appended\n house = await types.House.from_dict(data, self.http, client_id=self.id, rooms=self.rooms, users=self.users)\n\n # Adding all new cached users\n for d in data['members']:\n if hasattr(d, 'id'):\n user_id = utils.convert_value(int, d.get('id'))\n else:\n # Falling back to the nested user object and the ID that is stored there\n user_id = utils.convert_value(int, d.get('user').get('id'))\n\n # Getting the user from the list if it exists\n cached_user = utils.get(self._users, id=user_id)\n\n # If it doesn't exist it needs to be added to the list\n if cached_user is None:\n # Appending the new user\n user = await types.User.from_dict(d, self.http)\n if user is not None:\n self._users.append(user)\n else:\n logger.warning(f\"[WEBSOCKET] Failed to validate and create user with id {d.get('id')}\")\n\n # Appending to the client houses list\n self._houses.append(house)\n\n await self.event_handler.dispatch_on_house_add(house)\n\n except Exception as e:\n utils.log_traceback(msg=\"[HOUSE_JOIN] Traceback:\",\n suffix=\"Failed to handle the event due to an exception occurring: \\n\"\n f\"{sys.exc_info()[0].__name__}: {e}\")\n\n async def house_leave_handler(self, data: dict):\n \"\"\"\n Handler for the event on_house_remove, which will return as parameter the removed house.\n\n :param data: The incoming ws text msg - Should be in correct python dict format\n \"\"\"\n try:\n house = utils.get(self._houses, id=utils.convert_value(int, data.get('house_id')))\n\n if house:\n # Removing the house\n self._houses.remove(house)\n else:\n logger.debug(\"[HOUSE_LEAVE] Unable to locate left house in house cache! \"\n \"Possibly faulty Client data!\")\n\n await self.event_handler.dispatch_on_house_remove(house=house)\n\n except Exception as e:\n utils.log_traceback(msg=\"[HOUSE_LEAVE] Traceback:\",\n suffix=\"Failed to handle the event due to an exception occurring: \\n\"\n f\"{sys.exc_info()[0].__name__}: {e}\")\n\n async def house_entity_update_handler(self, data: dict):\n \"\"\"\n Handler for a house entity update. Triggers on_house_entity_update and\n returns as parameter the house obj, the entity obj and the raw data\n\n :param data: The incoming ws text msg - Should be in correct python dict format\n \"\"\"\n try:\n house = utils.get(self.houses, id=utils.convert_value(int, data.get('house_id')))\n\n for d in data.get('entities'):\n entity = await types.Entity.from_dict(d, self.http, house=house)\n\n # Removing the old entity if they exist\n cached_entity = utils.get(house.entities, id=utils.convert_value(int, d.get('id')))\n if cached_entity:\n house._entities.remove(cached_entity)\n\n house._entities.append(entity)\n\n await self.event_handler.dispatch_on_house_entity_update(house=house)\n\n except Exception as e:\n utils.log_traceback(msg=\"[HOUSE_ENTITIES_UPDATE] Traceback:\",\n suffix=\"Failed to handle the event due to an exception occurring: \\n\"\n f\"{sys.exc_info()[0].__name__}: {e}\")\n\n async def batch_house_member_handler(self, data: dict):\n \"\"\"\n In Work!\n\n Handler for a batch house member update that includes a list of\n members that were updated. Triggers on_batch_house_member_update\n and returns as parameters the members list, the raw data and the house obj\n\n :param data: The incoming ws text msg - Should be in correct python dict format\n \"\"\"\n try:\n house = utils.get(self._houses, id=utils.convert_value(int, data.get('house_id')))\n\n # Creating a list of all updated members\n members = list([await types.Member.from_dict(data, self.http, house=house) for data in data.get('data')])\n\n # For every created member the local member data will be replaced\n for member in members:\n mem_id = getattr(member, \"id\")\n\n # Checking whether the ID exists and the object was created correctly\n if mem_id:\n cached_mem = utils.get(house.members, id=utils.convert_value(int, mem_id))\n if cached_mem is not None:\n # Replacing the cached member with the newly created member object\n house._members.remove(cached_mem)\n house._members.append(member)\n else:\n logger.warning(f\"[BATCH_HOUSE_MEMBER_UPDATE] Failed to update member data \"\n f\"of {member.name} in house {house.name}\")\n else:\n logger.warning(f\"[BATCH_HOUSE_MEMBER_UPDATE] Failed to update member data of \"\n f\"unknown member in house {house.name} because of faulty user data! \"\n \"Possibly faulty client data!\")\n\n users = []\n # Creating a list of all updated users\n for d in data.get('data'):\n users.append(await types.User.from_dict(d, self.http))\n\n # For every created user the local user data will be replaced\n for user in users:\n usr_id = getattr(user, \"id\")\n # Checking whether the ID exists and the object was created correctly\n if usr_id:\n cached_user = utils.get(self._users, id=utils.convert_value(int, usr_id))\n if cached_user is not None:\n # Replacing the cached user with the newly created user object\n self._users.remove(cached_user)\n self._users.append(user)\n else:\n logger.warning(f\"[BATCH_HOUSE_MEMBER_UPDATE] Failed to update user data \"\n \"of {user.name} in house {house.name}! Possibly faulty client data!\")\n else:\n logger.warning(f\"[BATCH_HOUSE_MEMBER_UPDATE] Failed to update user data \"\n f\"of unknown user in house {house.name} because of faulty user data!\"\n \" Possibly faulty client data!\")\n\n await self.event_handler.dispatch_on_batch_house_member_update(members=members, data=data, house=house)\n\n except Exception as e:\n utils.log_traceback(msg=\"[BATCH_HOUSE_MEMBER_UPDATE] Traceback:\",\n suffix=\"Failed to handle the event due to an exception occurring: \\n\"\n f\"{sys.exc_info()[0].__name__}: {e}\")\n\n async def typing_start_handler(self, data: dict):\n \"\"\"\n Handler for the typing_start event that will trigger the event\n on_typing_start and return as parameter the typing object with\n the room, house and member as attributes.\n\n :param data: The incoming ws text msg - Should be in correct python dict format\n \"\"\"\n try:\n # recipient_ids only exists in private room typing so it is a house if it does not exist!\n if data.get('recipient_ids') is None:\n room = utils.get(self.rooms, id=utils.convert_value(int, data.get('room_id')))\n house = utils.get(self.houses, id=utils.convert_value(int, data.get('house_id')))\n author = utils.get(house.members, id=utils.convert_value(int, data.get('author_id')))\n else:\n room = utils.get(self._private_rooms, id=utils.convert_value(int, data.get('room_id')))\n house = None\n author = utils.get(self.users, id=utils.convert_value(int, data.get('author_id')))\n\n typing_ = await types.UserTyping.from_dict(data, self.http, author, room, house)\n\n await self.event_handler.dispatch_on_typing_start(typing_)\n\n except Exception as e:\n utils.log_traceback(msg=\"[TYPING_START] Traceback:\",\n suffix=\"Failed to handle the event due to an exception occurring: \\n\"\n f\"{sys.exc_info()[0].__name__}: {e}\")\n\n async def house_member_leave(self, data):\n \"\"\"\n Event for a member leaving a house. Triggers on_house_member_leave()\n\n :param data: The incoming ws text msg - Should be in correct python dict format\n \"\"\"\n try:\n house = utils.get(self._houses, id=utils.convert_value(int, data.get('house_id')))\n cached_mem = utils.get(house.members, user_id=utils.convert_value(int, data.get('id')))\n\n # Removing the cached member\n house._members.remove(cached_mem)\n\n await self.event_handler.dispatch_on_house_member_leave(member=cached_mem, house=house)\n\n except Exception as e:\n utils.log_traceback(msg=\"[HOUSE_MEMBER_LEAVE] Traceback:\",\n suffix=\"Failed to handle the event due to an exception occurring: \\n\"\n f\"{sys.exc_info()[0].__name__}: {e}\")\n","sub_path":"openhivenpy/gateway/ws.py","file_name":"ws.py","file_ext":"py","file_size_in_byte":51761,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"362953862","text":"\"\"\"\nJackCompiler\n\nGiven the path for a single .jack file or directory of .jack files:\n- Create a JackTokenizer for each .jack file\n- Use SymbolTable, CompilationEngine, and VMWriter to write the VM code into the output .vm file\n\"\"\"\n\n\nimport os\nimport re\n\nfrom jack_tokenizer import JackTokenizer\nfrom vm_writer import VMWriter\nfrom compilation_engine import CompilationEngine\n\n\nclass JackCompiler:\n def __init__(self, argv1):\n self.jack_files = self.handle_file_vs_dir(argv1)\n\n for jack_file in self.jack_files:\n self.jack_input = \"\"\n self.xml_output = \"\"\n\n with open(jack_file) as file:\n for line in file.readlines():\n self.jack_input += self.strip_comment_from_line(line)\n\n self.strip_newlines()\n self.strip_multiline_comments()\n\n self.build_tokenizer()\n self.build_vm_writer(jack_file)\n\n self.run_compilation_engine()\n\n self.vm_writer.close()\n\n\n # Given a Jack file name or a directory of Jack files,\n # return an array of Jack file names.\n def handle_file_vs_dir(self, argv1):\n if os.path.isdir(argv1):\n return [\n f\"{argv1}/{file}\"\n for file in os.listdir(argv1)\n if len(file) > 5 and file[-5:] == '.jack'\n ]\n else:\n return [argv1]\n\n\n # Remove comments from a given line of Jack code.\n def strip_comment_from_line(self, line):\n # Strip everything after //\n line = re.sub(r\"//(.*)\", \"\", line)\n\n # Strip everything between /* */ and /** */\n return re.sub(r\"/\\*\\*?(.*)\\*/\", \"\", line)\n\n\n # Remove multiline comments.\n def strip_multiline_comments(self):\n self.jack_input = re.sub(r\"/\\*\\*?(.*?)\\*/\", \"\", self.jack_input)\n\n\n # Remove newlines.\n def strip_newlines(self):\n self.jack_input = re.sub(\"\\n\", \"\", self.jack_input)\n\n\n # Initialize the JackTokenizer.\n def build_tokenizer(self):\n self.tokenizer = JackTokenizer(self.jack_input)\n\n\n # Initialize the JackTokenizer.\n def build_vm_writer(self, jack_file):\n self.vm_writer = VMWriter(jack_file)\n\n\n # Run the CompilationEngine.\n def run_compilation_engine(self):\n CompilationEngine(self.tokenizer, self.vm_writer).run()\n\n\n\n\n\n\n","sub_path":"src/jack_compiler.py","file_name":"jack_compiler.py","file_ext":"py","file_size_in_byte":2128,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"207556594","text":"# encoding: utf-8\n# Economic of co-firing in two power plants in Vietnam\n#\n# (c) Minh Ha-Duong, An Ha Truong 2016-2019\n# minh.haduong@gmail.com\n# Creative Commons Attribution-ShareAlike 4.0 International\n#\n\"\"\"Define the class System used to instantiate a run of the model.\"\"\"\nfrom collections import namedtuple\n\nfrom pandas import Series, DataFrame, set_option, concat\n\nfrom model.utils import t, kt, npv, np_sum\nfrom model.utils import year_1, display_as, safe_divide, after_invest, isclose_all\nfrom model.powerplant import PowerPlant\nfrom model.cofiringplant import CofiringPlant\nfrom model.farmer import Farmer\nfrom model.reseller import Reseller\n\nPrice = namedtuple(\"Price\", \"biomass_plantgate, biomass_fieldside, coal, electricity\")\n\nMiningParameter = namedtuple(\n \"MiningParameter\", \"productivity_surface, productivity_underground, wage_mining\"\n)\n\n\n# We should pass the parameters as an object\n# pylint: disable=too-many-instance-attributes\n#\n# Refectoring needed:\n# We should split the class into a System that knows only about one type of plant,\n# and a comparison class that holds a system_ex_ante and a system_ex_post\n# pylint: disable=R0904\nclass System:\n \"\"\"The system model of the cofiring economic sector.\n\n Instance variables: plant, cofiring plant, supply_chain, reseller, farmer.\n The class is designed immutable, don't change the members after initialization.\n \"\"\"\n\n # pylint: disable=too-many-arguments\n def __init__(\n self,\n plant_parameter,\n cofire_parameter,\n supply_chain_potential,\n price,\n farm_parameter,\n transport_parameter,\n mining_parameter,\n emission_factor,\n ):\n \"\"\"Instantiate the system actors.\"\"\"\n self.plant = PowerPlant(plant_parameter, emission_factor)\n self.cofiring_plant = CofiringPlant(\n plant_parameter, cofire_parameter, emission_factor\n )\n self.quantity_plantgate = self.cofiring_plant.cofuel_used\n self.supply_chain = supply_chain_potential.fit(self.quantity_plantgate[1])\n\n self.quantity_fieldside = after_invest(self.supply_chain.straw_sold())\n # Transport losses negligible\n assert isclose_all(self.quantity_fieldside, self.quantity_plantgate)\n\n self.farmer = Farmer(self.supply_chain, farm_parameter, emission_factor)\n self.reseller = Reseller(\n self.supply_chain, transport_parameter, emission_factor\n )\n self.mining_parameter = mining_parameter\n self.clear_market(price)\n\n def clear_market(self, price):\n \"\"\"Realize the payments between actors.\"\"\"\n self.price = price\n\n electricity_sales = self.plant.power_generation * price.electricity\n display_as(electricity_sales, \"kUSD\")\n\n self.plant.revenue = electricity_sales\n self.plant.mainfuel_cost = self.plant.mainfuel_used * price.coal\n\n self.cofiring_plant.revenue = electricity_sales\n self.cofiring_plant.mainfuel_cost = (\n self.cofiring_plant.mainfuel_used * price.coal\n )\n\n # Transaction at the plant gate\n payment_plantgate = self.quantity_plantgate * price.biomass_plantgate\n display_as(payment_plantgate, \"kUSD\")\n self.cofiring_plant.cofuel_cost = self.reseller.revenue = payment_plantgate\n\n # Transaction at the field side\n payment_fieldside = self.quantity_fieldside * price.biomass_fieldside\n display_as(payment_fieldside, \"kUSD\")\n self.farmer.revenue = self.reseller.merchandise = payment_fieldside\n\n @property\n def transport_cost_per_t(self):\n \"\"\"Return technical cost to transport the straw, including labor, fuel and truck rental.\"\"\"\n return safe_divide(self.reseller.operating_expenses(), self.quantity_fieldside)\n\n @property\n def labor(self):\n \"\"\"Return total work time created from co-firing.\"\"\"\n time = (\n self.farmer.labor()\n + self.reseller.labor()\n + self.cofiring_plant.cofuel_om_work()\n - self.coal_work_lost\n )\n return display_as(time, \"hr\")\n\n @property\n def wages(self):\n \"\"\"Return total benefit from job creation from biomass co-firing.\"\"\"\n amount = (\n self.farmer.labor_cost()\n + self.reseller.labor_cost()\n + self.cofiring_plant.cofuel_om_wages()\n - self.coal_wages_lost\n )\n return display_as(amount, \"kUSD\")\n\n def wages_npv(self, discount_rate, horizon):\n amount = npv(self.wages, discount_rate, horizon)\n return display_as(amount, \"kUSD\")\n\n @property\n def coal_saved(self):\n mass = self.plant.mainfuel_used - self.cofiring_plant.mainfuel_used\n _ = kt # Quiet pylint and the spyder codechecker\n return display_as(mass, \"kt\")\n\n @property\n def coal_work_lost(self):\n time = self.coal_saved / self.mining_parameter.productivity_underground\n return display_as(time, \"hr\")\n\n @property\n def coal_wages_lost(self):\n value = self.coal_work_lost * self.mining_parameter.wage_mining\n return display_as(value, \"kUSD\")\n\n def emissions_baseline(self):\n \"\"\"Tabulate system atmospheric emissions in year 1 ex ante (no cofiring).\"\"\"\n baseline = DataFrame(columns=[\"CO2\", \"NOx\", \"PM10\", \"PM2.5\", \"SO2\"])\n baseline = baseline.append(year_1(self.plant.emissions()))\n baseline = baseline.append(year_1(self.plant.fuel_reseller().emissions()))\n baseline = baseline.append(year_1(self.farmer.emissions_exante))\n baseline.loc[\"Total\"] = baseline.sum()\n baseline.loc[\"Total_plant\"] = baseline.iloc[0]\n baseline.loc[\"Total_transport\"] = baseline.iloc[1]\n baseline.loc[\"Total_field\"] = baseline.iloc[2]\n return baseline\n\n def emissions_cofiring(self):\n \"\"\"Tabulate system atmospheric emissions in year 1 ex post (with cofiring).\"\"\"\n cofiring = DataFrame(columns=[\"CO2\", \"NOx\", \"PM10\", \"PM2.5\", \"SO2\"])\n cofiring = cofiring.append(year_1(self.cofiring_plant.emissions()))\n cofiring = cofiring.append(\n year_1(self.cofiring_plant.fuel_reseller().emissions())\n )\n cofiring = cofiring.append(year_1(self.farmer.emissions()))\n cofiring = cofiring.append(year_1(self.reseller.emissions()))\n cofiring.loc[\"Total\"] = cofiring.sum()\n cofiring.loc[\"Total_plant\"] = cofiring.iloc[0] + cofiring.iloc[1]\n cofiring.loc[\"Total_transport\"] = cofiring.iloc[2] + cofiring.iloc[4]\n cofiring.loc[\"Total_field\"] = cofiring.iloc[3]\n return cofiring\n\n def emissions_exante(self):\n \"\"\"Tabulate atmospheric emissions ex ante.\n\n Return a dataframe of time series, indexed by segment and pollutant.\n \"\"\"\n plant_emissions = self.plant.emissions(total=True)[\"Total\"]\n ship_coal_emissions = self.plant.fuel_reseller().emissions(total=True)[\"Total\"]\n field_emissions = self.farmer.emissions_exante[\"Straw\"]\n transport_emissions = field_emissions * 0 # No logistics\n total_emissions = plant_emissions + ship_coal_emissions + field_emissions\n return DataFrame(\n [\n plant_emissions,\n ship_coal_emissions,\n transport_emissions,\n field_emissions,\n total_emissions,\n ],\n index=[\"Plant\", \"Ship coal\", \"Transport\", \"Field\", \"Total\"],\n )\n\n def emissions_expost(self):\n \"\"\"Tabulate atmospheric emissions ex post.\n\n Return a dataframe of time series, indexed by segment and pollutant.\n \"\"\"\n plant_emissions = self.cofiring_plant.emissions(total=True)[\"Total\"]\n ship_coal_emissions = self.cofiring_plant.fuel_reseller().emissions(total=True)[\n \"Total\"\n ]\n transport_emissions = self.reseller.emissions(total=True)[\"Total\"]\n field_emissions = self.farmer.emissions(total=True)[\"Total\"]\n total_emissions = (\n plant_emissions\n + ship_coal_emissions\n + transport_emissions\n + field_emissions\n )\n return DataFrame(\n [\n plant_emissions,\n ship_coal_emissions,\n transport_emissions,\n field_emissions,\n total_emissions,\n ],\n index=[\"Plant\", \"Ship coal\", \"Transport\", \"Field\", \"Total\"],\n )\n\n def emissions_reduction(self):\n \"\"\"Tabulate atmospheric emissions reductions.\n\n Return a dataframe of time series, indexed by segment and pollutant.\n \"\"\"\n reduction = self.emissions_exante() - self.emissions_expost()\n is_null_year0 = reduction.applymap(lambda sequence: sequence[0] == 0 * t)\n assert is_null_year0.all(\n axis=None\n ), \"Expecting zero emission reduction in year 0\"\n return reduction\n\n def emissions_reduction_benefit(self, external_cost):\n \"\"\"Tabulate external benefits of reducing atmospheric emissions from cofiring.\n\n Return a dataframe of time series, indexed by segment and pollutant.\n We disregard PM10 externalities, impact of dust quantified using PM2.5 only\n \"\"\"\n baseline = self.emissions_exante().loc[\"Total\"]\n reduction = self.emissions_reduction().loc[\"Total\"]\n # baseline = self.emissions_exante().loc[\"Total\"].drop(\"PM10\")\n # reduction = self.emissions_reduction().loc[\"Total\"].drop(\"PM10\")\n relative = reduction / baseline\n benefit = reduction * external_cost\n for pollutant in benefit:\n display_as(pollutant, \"kUSD\")\n for pollutant in external_cost:\n display_as(pollutant, \"USD / t\")\n return DataFrame(\n [baseline, reduction, relative, benefit],\n index=[\"Baseline\", \"Reduction\", \"Relative reduction\", \"Value\"],\n )\n\n def coal_saved_benefits(self, coal_import_price):\n \"\"\"Tabulate the quantity and value of coal saved by cofiring.\"\"\"\n baseline = self.plant.mainfuel_used\n reduction = self.coal_saved\n relative = reduction / baseline\n benefit = reduction * coal_import_price\n display_as(benefit, \"MUSD\")\n return DataFrame(\n [baseline, reduction, relative, benefit],\n index=[\"Baseline\", \"Reduction\", \"Relative reduction\", \"Value\"],\n )\n\n def mitigation_npv(self, external_cost, discount_rate, horizon):\n df = self.emissions_reduction_benefit(external_cost)\n annual_mitigation_value = df.loc[\"Value\", \"CO2\"]\n value = npv(annual_mitigation_value, discount_rate, horizon)\n return display_as(value, \"kUSD\")\n\n def health_npv(self, external_cost, discount_rate, horizon):\n df = self.emissions_reduction_benefit(external_cost)\n annual_health_benefit = df.loc[\"Value\"].drop(\"CO2\").sum()\n value = npv(annual_health_benefit, discount_rate, horizon)\n return display_as(value, \"kUSD\")\n\n def parameters_table(self):\n \"\"\"Tabulate arguments defining the system, except supply chain. Return a Pandas Series.\"\"\"\n set_option(\"display.max_colwidth\", 80)\n legend_a = Series(\"----------\", index=[\"*** Farmer ***\"])\n a = self.farmer.parameters_table()\n legend_b = Series(\"----------\", index=[\"*** Reseller***\"])\n b = self.reseller.parameters_table()\n legend_c = Series(\"----------\", index=[\"*** Cofiring plant ***\"])\n c = self.cofiring_plant.parameters_table()\n legend_d = Series(\"----------\", index=[\"*** Mining ***\"])\n d = Series(self.mining_parameter, self.mining_parameter._fields)\n display_as(d.loc[\"wage_mining\"], \"USD / hr\")\n legend_e = Series(\"----------\", index=[\"*** Prices ***\"])\n e = Series(self.price, self.price._fields)\n display_as(e.loc[\"biomass_plantgate\"], \"USD / t\")\n display_as(e.loc[\"biomass_fieldside\"], \"USD / t\")\n display_as(e.loc[\"coal\"], \"USD / t\")\n display_as(e.loc[\"electricity\"], \"USD / kWh\")\n return concat([legend_c, c, legend_a, a, legend_b, b, legend_d, d, legend_e, e])\n\n def benefits(self, discount_rate, horizon, external_cost):\n \"\"\"Tabulate the present value of various benefits from co-firing.\"\"\"\n table = [\"\"]\n table.append(self.cofiring_plant.name)\n table.append(\"-------------------\")\n row2 = \"{:30}\" + \"{:20.0f}\"\n table.append(\n row2.format(\n \"Health\", self.health_npv(external_cost, discount_rate, horizon)\n )\n )\n table.append(\n row2.format(\n \"Emission reduction\",\n self.mitigation_npv(external_cost, discount_rate, horizon),\n )\n )\n table.append(row2.format(\"Wages\", self.wages_npv(discount_rate, horizon)))\n table.append(\n row2.format(\n \"Farmer earnings before tax\",\n self.farmer.net_present_value(discount_rate, horizon),\n )\n )\n table.append(\n row2.format(\n \"Trader earnings before tax\",\n self.reseller.net_present_value(discount_rate, horizon),\n )\n )\n return \"\\n\".join(table)\n\n def plant_npv_cash_change(\n self, discount_rate, horizon, tax_rate, depreciation_period\n ):\n \"\"\"Return the NPV change table for the power plant.\n\n Cofiring profit is positive if its benefits (reducing the operating expenses)\n exceeds its costs (the investment).\n \"\"\"\n name = self.plant.name\n exante = self.plant.npv_cash(\n discount_rate, horizon, tax_rate, depreciation_period, name\n )\n expost = self.cofiring_plant.npv_cash(\n discount_rate, horizon, tax_rate, depreciation_period, name\n )\n return expost - exante\n\n def plant_npv_opex_change(self, discount_rate, horizon):\n \"\"\"Return the Operating expenses changes for the power plant, as NPV.\n\n Ex post compared to ex ante:\n the coal costs are lower\n the biomass costs are higher\n the total Operations and Maintenance are higher\n and if the biomass is cheap enough, then the operating expenses decrease.\n \"\"\"\n name = self.plant.name\n npv_opex_exante = self.plant.npv_opex(discount_rate, horizon, name)\n table = self.cofiring_plant.npv_opex(discount_rate, horizon, name)\n table.loc[\"Fuel cost, main fuel\"] -= npv_opex_exante.loc[\"Fuel cost, main fuel\"]\n table.loc[\"O&M, main fuel\"] -= npv_opex_exante.loc[\"Operation & Maintenance\"]\n table.loc[\"= Operating expenses\"] -= npv_opex_exante.loc[\"= Operating expenses\"]\n return table\n\n # df = self.plant_opex_change()\n # return df.apply(lambda s: npv(s, discount_rate), axis=1)\n\n def plant_om_change(self):\n exante = self.plant.operation_maintenance_cost()\n expost = self.cofiring_plant.operation_maintenance_cost()\n return expost - exante\n\n def table_business_value(self, discount_rate, horizon):\n \"\"\"Tabulate cofiring business value: technical costs vs. value of coal saved.\"\"\"\n data = [\n npv(self.farmer.operating_expenses(), discount_rate, horizon),\n npv(self.reseller.operating_expenses(), discount_rate, horizon),\n npv(self.cofiring_plant.investment(), discount_rate, horizon),\n ]\n\n table_opex = self.plant_npv_opex_change(discount_rate, horizon)\n extra_OM = table_opex.loc[\"O&M, main fuel\"] + table_opex.loc[\"O&M, cofuel\"]\n data.append(display_as(extra_OM, \"kUSD\"))\n\n technical_cost = np_sum(data)\n data.append(technical_cost)\n\n coal_saved = npv(self.coal_saved, discount_rate, horizon)\n coal_price = display_as(self.price.coal, \"USD/t\")\n savings = display_as(coal_saved * coal_price, \"kUSD\")\n data.append(coal_saved)\n data.append(coal_price)\n data.append(savings)\n\n data.append(savings - technical_cost)\n\n index = [\n \"Farmer opex\",\n \"Reseller opex\",\n \"Investment\",\n \"Extra O&M\",\n \"Total technical costs\",\n \"Coal saved\",\n \"Coal price\",\n \"Value of coal saved\",\n \"Business value of cofiring\",\n ]\n table = Series(data, index=index)\n table.name = self.plant.name\n return table\n\n # Code really smell, will change result to DataFrame now.\n # pylint: disable=too-many-locals\n def job_changes(self):\n \"\"\"Tabulate the number of full time equivalent (FTE) jobs created/destroyed by cofiring.\"\"\"\n cols = \"{:25}{:12.1f}\"\n cols2 = \"{:25}{:12.1f}{:12.1f}\"\n\n lines = [\"Benefit from job creation: \" + self.plant.name + \"\\n\"]\n\n row7 = self.farmer.labor()[1]\n row1 = self.farmer.labor_cost()[1]\n row8 = self.reseller.driving_work()[1]\n row2 = self.reseller.driving_wages()[1]\n row11 = self.reseller.loading_work()[1]\n row12 = self.reseller.loading_wages()[1]\n row9 = self.cofiring_plant.cofuel_om_work()[1]\n row3 = self.cofiring_plant.cofuel_om_wages()[1]\n row6 = -self.coal_work_lost[1]\n row5 = -self.coal_wages_lost[1]\n row10 = self.labor[1]\n row4 = self.wages[1]\n\n display_as(row6, \"FTE\")\n display_as(row7, \"FTE\")\n display_as(row8, \"FTE\")\n display_as(row9, \"FTE\")\n display_as(row10, \"FTE\")\n display_as(row11, \"FTE\")\n\n lines.append(cols2.format(\"Biomass collection\", row7, row1))\n lines.append(cols2.format(\"Biomass transportation\", row8, row2))\n lines.append(cols2.format(\"Biomass loading\", row11, row12))\n lines.append(cols2.format(\"O&M\", row9, row3))\n lines.append(cols2.format(\"Mining\", row6, row5))\n lines.append(cols2.format(\"Total\", row10, row4))\n lines.append(\"\")\n lines.append(cols.format(\"Area collected\", self.supply_chain.area()))\n lines.append(\n cols.format(\"Collection radius\", self.supply_chain.collection_radius())\n )\n lines.append(\n cols.format(\"Maximum transport time\", self.reseller.max_trip_time())\n )\n lines.append(cols.format(\"Number of truck trips\", self.reseller.truck_trips[1]))\n lines.append(\"\")\n lines.append(\"Mining job lost from co-firing at \" + self.plant.name + \"\\n\")\n lines.append(cols.format(\"Coal saved\", self.coal_saved[1]))\n lines.append(\n cols.format(\"Productivity\", self.mining_parameter.productivity_underground)\n )\n lines.append(cols.format(\"Job lost\", self.coal_work_lost[1]))\n lines.append(cols.format(\"Job lost\", display_as(self.coal_work_lost[1], \"FTE\")))\n lines.append(\n cols.format(\"Wage\", display_as(self.mining_parameter.wage_mining, \"USD/hr\"))\n )\n lines.append(cols.format(\"Wage lost\", self.coal_wages_lost[1]))\n return \"\\n\".join(lines)\n","sub_path":"model/system.py","file_name":"system.py","file_ext":"py","file_size_in_byte":19053,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"96819188","text":"import os\nimport re\nimport mimetypes\nimport uuid\nimport io\n\nimport falcon\nimport msgpack\n\n\nALLOWED_IMAGE_TYPES = (\n 'image/gif',\n 'image/jpeg',\n 'image/png',\n)\n\ndef validate_image_type(req, resp, resource, params):\n if req.content_type not in ALLOWED_IMAGE_TYPES:\n msg = 'Image type not allowed. Guess again!'\n raise falcon.HTTPBadRequest('Bad request', msg)\n\n\nclass Collection(object):\n\n def __init__(self, image_store):\n self._image_store = image_store\n\n\n def on_get(self, req, resp):\n images = [\n {\n 'href': 'http://i0.kym-cdn.com/photos/images/facebook/001/365/839/24d.png'\n }\n ]\n resp.data = msgpack.packb(images, use_bin_type=True)\n resp.content_type = falcon.MEDIA_MSGPACK\n resp.status = falcon.HTTP_200\n\n\n @falcon.before(validate_image_type)\n def on_post(self, req, resp):\n name = self._image_store.save(req.stream, req.content_type)\n resp.status = falcon.HTTP_201\n resp.location = '/images/' + name\n\n\nclass Item(object):\n\n def __init__(self, image_store):\n self._image_store = image_store\n\n\n def on_get(self, req, resp, name):\n resp.content_type = mimetypes.guess_type(name)[0]\n try:\n resp.stream, resp.stream_len = self._image_store.open(name)\n except IOError:\n raise falcon.HTTPNotFound()\n\n\nclass Store(object):\n\n _CHUNK_SIZE_BYTES = 4096\n _IMAGE_NAME_PATTERN = re.compile(\n '[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\\.[a-z]{2,4}$'\n )\n \n def __init__(self, storage_path, uuidgen=uuid.uuid4, fopen=io.open):\n self._storage_path = storage_path\n self._uuidgen = uuidgen\n self._fopen = fopen\n\n\n def save(self, stream, content_type):\n ext = mimetypes.guess_extension(content_type)\n name = '{uuid}{ext}'.format(uuid=self._uuidgen(), ext=ext)\n image_path = os.path.join(self._storage_path, name)\n\n with self._fopen(image_path, 'wb') as image_file:\n while True:\n chunk = stream.read(self._CHUNK_SIZE_BYTES)\n if not chunk:\n break\n image_file.write(chunk)\n\n return name\n\n\n def open(self, name):\n if not self._IMAGE_NAME_PATTERN.match(name):\n raise IOError('File not found')\n\n image_path = os.path.join(self._storage_path, name)\n stream = self._fopen(image_path, 'rb')\n stream_len = os.path.getsize(image_path)\n return stream, stream_len\n","sub_path":"look/look/images.py","file_name":"images.py","file_ext":"py","file_size_in_byte":2556,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"55013667","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Jan 8 23:02:02 2018\n\n@author: sw\n\"\"\"\nimport tensorflow as tf\nimport glob\nimport os\nimport numpy as np\nimport time\nimport gc\nimport sys\nclass Reader():\n def __init__(self, tfrecords_file, height=17, width=17,\n min_queue_examples=5000, batch_size=500, num_threads=3, name = ''):\n \"\"\"\n Args:\n tfrecords_file: string, tfrecords file path\n min_queue_examples: integer, minimum number of samples to retain in the queue that provides of batches of examples\n batch_size: integer, number of images per batch\n num_threads: integer, number of preprocess threads\n \"\"\"\n self.tfrecords_file = tfrecords_file\n self.height = height\n self.width =width\n self.min_queue_examples = min_queue_examples\n self.batch_size = batch_size\n self.num_threads = num_threads\n self.reader = tf.TFRecordReader()\n self.name = name\n def feed(self, train_data = True):\n \"\"\"\n Returns:\n images: 4D tensor [batch_size, image_width, image_height, image_depth]\n \"\"\"\n with tf.name_scope(self.name):\n filename_queue = tf.train.string_input_producer([self.tfrecords_file])\n _, serialized_example = self.reader.read(filename_queue)\n \n features = tf.parse_single_example(\n serialized_example,\n features={\n 'label_raw': tf.FixedLenFeature([], tf.string),\n 'HSI_raw': tf.FixedLenFeature([], tf.string)\n \n })\n \n HSI = tf.decode_raw(features['HSI_raw'], tf.float32) \n HSI.set_shape([self.height * self.width * 48])\n HSI = tf.cast(HSI, tf.float32) \n \n label = tf.decode_raw(features['label_raw'], tf.int8)\n label = tf.reshape(tf.cast(label, tf.int32),shape=(1,))\n reshape_HSI = tf.reshape(HSI, [self.height, self.width, 48]) \n \n#-------------------------------------------------------------------------------- \n\n \n if train_data:\n reshape_HSI = tf.image.random_flip_left_right(reshape_HSI)\n reshape_HSI = tf.image.random_flip_up_down(reshape_HSI)\n# reshape_HSI = tf.image.rot90(reshape_HSI, k = np.random.randint(0,4))\n \n HSIs, labels = tf.train.shuffle_batch([reshape_HSI, label], batch_size=self.batch_size, num_threads=self.num_threads,\n capacity=self.min_queue_examples + 3*self.batch_size, min_after_dequeue=self.min_queue_examples)\n \n else:\n \n HSIs, labels = tf.train.batch([reshape_HSI, label],\n batch_size = self.batch_size,\n num_threads=3, capacity=2000 + 3*self.batch_size)\n \n# tf.summary.image('record_inputs', images)\n labels = tf.squeeze(labels)\n return HSIs, labels\n\ndef read_train():\n# train_reader = Reader('valid.tfrecord',name='train_data')\n# images_op, labels_op = train_reader.feed(train_data=False)\n \n records = glob.glob('data/*.tfrecord') \n train_readers = []\n for record in records: \n record_name = 'train_data' + os.path.basename(record).split('.')[0] \n train_reader = Reader(record, name = record_name, batch_size=50)\n train_readers.append(train_reader) \n \n train_imgs_and_labels = [train_reader_.feed(train_data = False) for train_reader_ in train_readers]\n \n init = tf.global_variables_initializer()\n sess = tf.Session()\n sess.run(init)\n coord = tf.train.Coordinator()\n threads = tf.train.start_queue_runners(sess=sess, coord=coord)\n train_images = []\n train_labels = []\n \n for i in range(3000):\n start_time = time.time() \n images_and_labels = sess.run(train_imgs_and_labels)\n# images,labels=sess.run([images_op, labels_op])\n HSIs = []\n VISs = []\n LIDARs = []\n labels = []\n for hsi, vis, lidar, label in images_and_labels:\n HSIs.extend(hsi)\n VISs.extend(vis)\n LIDARs.extend(lidar)\n labels.extend(label)\n \n HSIs = np.array(HSIs)\n VISs = np.array(VISs)\n LIDARs = np.array(LIDARs)\n labels = np.array(labels)\n \n coord.request_stop()\n coord.join(threads)\n sess.close() \n \ndef view_bar(message, num, total):\n rate = num / total\n rate_num = int(rate * 40)\n rate_nums = np.ceil(rate * 100)\n r = '\\r%s:[%s%s]%d%%\\t%d/%d' % (message, \">\" * rate_num, \" \" * (40 - rate_num), rate_nums, num, total,)\n sys.stdout.write(r)\n sys.stdout.flush()\n \ndef read_valid():\n train_reader = Reader('data/1.tfrecord',name='valid_data', batch_size=500)\n images_op, labels_op = train_reader.feed(train_data=False)\n \n init = tf.global_variables_initializer()\n sess = tf.Session()\n sess.run(init)\n coord = tf.train.Coordinator()\n threads = tf.train.start_queue_runners(sess=sess, coord=coord)\n valid_images = []\n valid_labels = []\n valid_examples = 1413248\n steps_per_epoch = valid_examples // 500 \n# indexes = np.split(np.load('index.npy'),steps_per_epoch)\n \n for i in range(steps_per_epoch):\n# view_bar('valid ', i, steps_per_epoch)\n start_time = time.time() \n images,labels=sess.run([images_op, labels_op]) \n view_bar('valid ', i, steps_per_epoch)\n# temp = indexes[i]\n# temp_images = images[temp]\n# temp_labels = labels[temp]\n# \n# temp1 = ((temp_labels==1) | (temp_labels==2) | (temp_labels==3) | (temp_labels==6) | (temp_labels==8) | (temp_labels==18))\n# valid_images.extend(temp_images[temp1])\n# valid_labels.extend(temp_labels[temp1])\n# print('processed label = {} {}/{}'.format(labels[0],i,len(valid_labels)))\n \n duration = time.time() - start_time\n# np.save('valid_images',valid_images)\n# np.save('valid_labels',valid_labels)\n print('cost time = {:.3f}'.format(duration))\n del valid_images\n gc.collect()\n time.sleep(1)\n \n coord.request_stop()\n coord.join(threads)\n sess.close() \n \nif __name__ == '__main__':\n read_valid()\n","sub_path":"training_method_2/read_record.py","file_name":"read_record.py","file_ext":"py","file_size_in_byte":5837,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"157675251","text":"import numpy as np\nimport matplotlib.pyplot as plt\n\nfig, axs = plt.subplots(nrows=3, ncols=1, sharex=True)\n\nN = 10\nD = 3\nX = np.zeros((N, D))\nX[:,0] = 1 # bias term\nX[:5,1] = 1\nX[5:,2] = 1\nY = np.array([0]*5 + [1]*5)\n\n# print X so you know what it looks like\nprint(\"X:\", X)\n\n# won't work!\n# w = np.linalg.solve(X.T.dot(X), X.T.dot(Y))\n\n# let's try gradient descent\ncosts = [] # keep track of squared error cost\nw = np.random.randn(D) / np.sqrt(D) # randomly initialize w\nlearning_rate = 0.001\nfor t in range(1000):\n # update w\n Yhat = X.dot(w)\n delta = Yhat - Y\n w = w - learning_rate*X.T.dot(delta)\n\n # find and store the cost\n mse = delta.dot(delta) / N\n costs.append(mse)\n\n# plot the costs\nplt.plot(costs)\nplt.show()\n\nprint(\"final w:\", w)\n\n# plot prediction vs target\nplt.plot(Yhat, label='prediction')\nplt.plot(Y, label='target')\nplt.legend()\n\n# save plots\nfor i in range(1, plt.gcf().number + 1):\n plt.figure(i)\n # tighten up layout\n plt.tight_layout()\n plt.savefig('l2_regularization_figure_' + str(i) + '.png')\n plt.close()","sub_path":"Deep Learning and Visual Series/Linear Regression/gradient_descent.py","file_name":"gradient_descent.py","file_ext":"py","file_size_in_byte":1052,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"221664913","text":"# Слито на @Oblako_sxem\r\n# Слито на @Oblako_sxem\r\n# Слито на @Oblako_sxem\r\nimport telebot\r\nimport sqlite3\r\nfrom qiwi_payments.kassa import QiwiKassa\r\n\r\ncashier = QiwiKassa(\"e74c00791c075ea5005b2daf6827b8a3\")\r\n\r\nbot = telebot.TeleBot(\"1431744138:AAEuZSuRhxWf8ChBtFDcIxc0XgvaYliEAZw\")\r\n\r\ncon = sqlite3.connect(\"dannie_2.db\")\r\ncur = con.cursor()\r\n\r\nadmin_1 = 1353097202\r\nadmin_2 = 1353097202\r\n\r\nbot_name = \"Worldoffortune_bot\"\r\nfake_number = \"88005553535\"\r\nmin_summa = 100\r\n# Слито на @Oblako_sxem\r\n# Слито на @Oblako_sxem\r\n# Слито на @Oblako_sxem\r\n# Слито на @Oblako_sxem\r\n# Работа с бд\r\ndef get_status(message):\r\n con = sqlite3.connect(\"dannie_2.db\")\r\n cur = con.cursor()\r\n cur.execute(f\"SELECT status FROM users WHERE id = {message.chat.id}\")\r\n status = cur.fetchone()[0]\r\n return status\r\n\r\n\r\ndef get_balance(message):\r\n con = sqlite3.connect(\"dannie_2.db\")\r\n cur = con.cursor()\r\n cur.execute(f\"SELECT balance FROM users WHERE id = {message.chat.id}\")\r\n balance = cur.fetchone()[0]\r\n return balance\r\n\r\n\r\ndef get_last_popolnenie(message):\r\n con = sqlite3.connect(\"dannie_2.db\")\r\n cur = con.cursor()\r\n cur.execute(f\"SELECT last_popolnenie FROM users WHERE id = {message.chat.id}\")\r\n last_popolnenie = cur.fetchone()[0]\r\n return last_popolnenie\r\n\r\n\r\ndef get_referals(message):\r\n con = sqlite3.connect(\"dannie_2.db\")\r\n cur = con.cursor()\r\n cur.execute(f\"SELECT referals FROM users WHERE id = {message.chat.id}\")\r\n referals = cur.fetchone()[0]\r\n return referals\r\n\r\n\r\ndef get_ref_balance(message):\r\n con = sqlite3.connect(\"dannie_2.db\")\r\n cur = con.cursor()\r\n cur.execute(f\"SELECT ref_balance FROM users WHERE id = {message.chat.id}\")\r\n ref_balance = cur.fetchone()[0]\r\n return ref_balance\r\n\r\n\r\ndef get_ref_link(message):\r\n ref_link = f\"http://t.me/{bot_name}?start={message.chat.id}\"\r\n return ref_link\r\n\r\n\r\ndef get_inf_profil(balance, referals, ref_balance, ref_link):\r\n inf_profil = f\"✅ ЛИЧНЫЙ КАБИНЕТ Слито на @Oblako_sxem ✅\\n\\n\" \\\r\n f\"💵 БАЛАНС 💵\\n\" \\\r\n f\"{balance}₽\\n\\n\" \\\r\n f\"👥 Ваши рефералы 👥\\n\" \\\r\n f\"{referals}\\n\\n\" \\\r\n f\"💰 Ваш реферальный баланс 💰\\n\" \\\r\n f\"{ref_balance}₽\\n\\n\" \\\r\n f\"👤 Ваша реферальная ссылка 👤\\n\" \\\r\n f\"{ref_link}\"\r\n return inf_profil\r\n","sub_path":"1/casino_config.py","file_name":"casino_config.py","file_ext":"py","file_size_in_byte":2540,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"483459341","text":"import numpy as np\nimport math\nimport tkinter as tk\nfrom pynput.mouse import Controller\nimport clickINFO\nimport time\nimport random\nimport location\nimport winsound\n\n\n\nDELAY = 50\nCIRCULAR_PATH_INCR = 5\nWIDTH = 1540\nHEIGHT = 864\nSPACE = 0xA\nSOUND_TIME = 3000\nEND_OF_GAME = 8000\nCLOCK_X = 70\nCLOCK_Y = 30\nCLOCK_SIZE = 680\nHALF_CLOCK = 340\nCENTER_X = 375\nCENTER_Y = 355\n\nsin = lambda degs: math.sin(math.radians(degs))\ncos = lambda degs: math.cos(math.radians(degs))\n\n\nclass Celestial(object):\n # Constants\n COS_0, COS_180 = cos(0), cos(180)\n SIN_90, SIN_270 = sin(90), sin(270)\n\n def __init__(self, x, y, radius):\n self.x, self.y = x, y\n self.radius = radius\n\n def bounds(self):\n \"\"\" Return coords of rectangle surrounding circlular object. \"\"\"\n return (self.x + self.radius*self.COS_0, self.y + self.radius*self.SIN_270,\n self.x + self.radius*self.COS_180, self.y + self.radius*self.SIN_90)\n\n def get_position(self):\n x = self.x\n y = self.y\n return x, y\n\n\ndef circular_path(x, y, radius, delta_ang, start_ang=0):\n \"\"\" Endlessly generate coords of a circular path every delta angle degrees. \"\"\"\n ang = start_ang % 360\n while True:\n yield x + radius*cos(ang), y + radius*sin(ang)\n ang = (ang+delta_ang) % 360\n\n\ndef update_position(canvas, id, celestial_obj, path_iter):\n celestial_obj.x, celestial_obj.y = next(path_iter) # iterate path and set new position\n # update the position of the corresponding canvas obj\n x0, y0, x1, y1 = canvas.coords(id) # coordinates of canvas oval object\n oldx, oldy = (x0+x1) // 2, (y0+y1) // 2 # current center point\n dx, dy = celestial_obj.x - oldx, celestial_obj.y - oldy # amount of movement\n canvas.move(id, dx, dy) # move canvas oval object that much\n # repeat after delay\n canvas.after(DELAY, update_position, canvas, id, celestial_obj, path_iter)\n\n\ndef clicker(i):\n mouse = Controller()\n x_loc, y_loc = mouse.position\n currT = time.time()\n curr_click = clickINFO.clickINFO(x_loc, y_loc, currT - start_t)\n clicks.append(curr_click)\n top.destroy()\n return\n\n\ndef play_sound(planet_obj1):\n winsound.Beep(2500, 100)\n x, y = planet_obj1.get_position()\n curr_location = location.location(x, y)\n locations.append(curr_location)\n return\n\n\ndef my_dest(top):\n circular = False\n top.destroy()\n\n\ndef main(client, iters, is_prac):\n result = []\n global clicks\n clicks = []\n global locations\n locations = []\n global circular\n circular = True\n global root\n global top\n global curr_client\n curr_client = client\n global start_t\n\n for i in range(iters):\n sound_time = random.randint(1200, 3200)\n end_time = random.randint(1000, 3000)\n top = tk.Tk()\n top.title('Baseline_Beep')\n canvas = tk.Canvas(top, bg='grey', height=HEIGHT, width=WIDTH)\n canvas.pack()\n clock = canvas.create_oval(CLOCK_X, CLOCK_Y, CLOCK_SIZE+CLOCK_X, CLOCK_SIZE+CLOCK_Y, width=4)\n if circular:\n sol_obj = Celestial(410, 370, 1)\n planet_obj1 = Celestial(640, 600, 10) # the blue circle that moves\n planet1 = canvas.create_oval(planet_obj1.bounds(), fill='blue', width=0)\n orbital_radius = math.hypot(sol_obj.x - planet_obj1.x, sol_obj.y - planet_obj1.y)\n path_iter = circular_path(sol_obj.x, sol_obj.y, orbital_radius, CIRCULAR_PATH_INCR)\n next(path_iter) # prime generator\n top.after(DELAY, update_position, canvas, planet1, planet_obj1, path_iter)\n top.after(sound_time, play_sound, planet_obj1)\n top.after(sound_time + end_time, my_dest, top)\n circular = False\n else:\n start_t = time.time()\n canvas_text = canvas.create_text(1100, 400, font=\"Times 28 bold\", text=\"סמן את המקום שבו הייתה הנקודה \\n כאשר שמעת את הצפצוף\", fill='blue')\n canvas.bind(\"\", lambda x: clicker(x))\n circular = True\n top.mainloop()\n distances = calc_dist(locations, clicks)\n for i in range(len(distances)):\n final_curr_result = [clicks[i].timing, distances[i]]\n result.append(final_curr_result)\n if is_prac:\n client.blocks['baseline_beep_practice'] = result\n else:\n client.blocks['baseline_beep_task'] = result\n\n\ndef slider_click(x):\n mouse = Controller()\n x_loc, y_loc = mouse.position\n in_scale = ((x_loc-WIDTH*0.3)/400 * 10)\n curr_client.blocks['baseline_beep_slider'] = in_scale\n root.destroy()\n return\n\n\ndef angle_between(x1, x2, y1, y2):\n new_y2 = CLOCK_SIZE+CLOCK_Y-y2\n new_y1 = CLOCK_SIZE+CLOCK_Y-y1\n angle = math.atan2(new_y1 - new_y2, x1 - x2)\n angle = np.degrees(angle)\n if angle < 0:\n angle = 360+angle\n return angle\n\n\ndef check_validility(ball_angle, click_angle, is_right):\n if is_right:\n fst = (ball_angle + 90)\n snd = ball_angle-90\n if snd <= 0:\n snd = 360+snd\n if click_angle >= snd or click_angle <= fst:\n return True\n else:\n fst = ball_angle - 90\n if fst < 0:\n fst = 360+fst\n snd = (ball_angle + 90) % 360\n if (click_angle >= fst) and (click_angle <= snd):\n return True\n if (click_angle >= 0) and (click_angle <= snd):\n return True\n return False\n\n\ndef calc_dist(curr_locations, curr_clicks):\n dists = []\n for i in range(len(curr_clicks)):\n if curr_clicks[i] is not None and curr_locations[i] is not None:\n ball_x = int(curr_locations[i].x_loc)\n ball_y = int(curr_locations[i].y_loc)\n click_x = int(curr_clicks[i].x_loc)\n click_y = int(curr_clicks[i].y_loc)\n if ball_x > HALF_CLOCK + CLOCK_X:\n is_right = True\n else:\n is_right = False\n ball_angle = angle_between(ball_x, CENTER_X, ball_y, CENTER_Y)\n click_angle = angle_between(click_x, CENTER_X, click_y, CENTER_Y)\n is_valid_click = check_validility(ball_angle, click_angle, is_right)\n if is_valid_click:\n if (click_y >= CENTER_Y) and (ball_y >= CENTER_Y):\n if click_x < ball_x:\n sign = 1\n else:\n sign = -1\n elif (click_y <= CENTER_Y) and (ball_y <= CENTER_Y):\n if click_x < ball_x:\n sign = -1\n else:\n sign = 1\n else:\n if is_right and (click_y < ball_y):\n sign = -1\n elif is_right and (click_y >= ball_y):\n sign = 1\n else:\n if click_y > ball_y:\n sign = -1\n else:\n sign = 1\n curr_destination = sign * (math.sqrt((math.pow((ball_x - click_x), 2)) + (math.pow((ball_y - click_y), 2))))\n dists.append(curr_destination)\n else:\n dists.append('error')\n return dists\n\n","sub_path":"baseline_beep.py","file_name":"baseline_beep.py","file_ext":"py","file_size_in_byte":7220,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"408619989","text":"from settings import *\n\nDEM = os.path.join(RASTER_DIR, \"ra_dem.tif\")\n\ndef flow_acc_month():\n fill_dem = arcpy.gp.Fill_sa(DEM, \"in_memory\\\\fill_dem\", '#')\n flow_dir = arcpy.gp.FlowDirection_sa(fill_dem, \"in_memory\\\\flow_dir\", 'NORMAL', '#')\n contour = arcpy.gp.Contour_sa(fill_dem, os.path.join(SHP_DIR, \"gpl_curvas.shp\"), '50', '0', '1')\n for i in range(1,433):\n name = str(i).zfill(3)\n arcpy.gp.FlowAccumulation_sa(\n flow_dir,\n os.path.join(RASTER_DIR, \"facc_{}.tif\".format(name)),\n os.path.join(RASTER_DIR, \"q_{}.tif\".format(name)),\n 'FLOAT')\n print(name)\n\n\ndef main():\n flow_acc_month()\n\n# if __name__ == '__main__':\n# main()\n","sub_path":"scripts/s02_generar_flowacc_mensual.py","file_name":"s02_generar_flowacc_mensual.py","file_ext":"py","file_size_in_byte":713,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"425023745","text":"# -*-coding:utf-8 -*-\nfrom db_operation import db_connect\nfrom weibo_decorator.decorators import dbtimeout_decorator, save_decorator\n\n\n@dbtimeout_decorator(2)\ndef get_crawl_urls():\n \"\"\"\n :return: is_crawled = 0的字段,即需要进行扩散分析的字段\n \"\"\"\n # 以下代码是为了测试反爬虫机制注释掉的\n # sql = 'select se_userid,se_sid, se_mid from weibo_search_data where is_crawled = 0 and ' \\\n # 'se_sourcetype = \\'新浪微博\\' order by se_createtime desc'\n\n sql = 'select se_userid,se_sid, se_mid from weibo_search_data where is_new = 1 and ' \\\n 'se_sourcetype = \\'新浪微博\\' order by se_createtime desc'\n con = db_connect.get_con()\n rs = db_connect.db_queryall(con, sql)\n db_connect.db_close(con)\n datas = []\n for r in rs:\n data = {'url': 'http://weibo.com/' + r[0] + '/' + r[1], 'mid': r[2]}\n datas.append(data)\n return datas\n\n\n@dbtimeout_decorator(1)\ndef update_weibo_url(mid):\n sql = \"update weibo_search_data set is_crawled = 1 where se_mid = :mid\"\n args = {'mid': str(mid)}\n con = db_connect.get_con()\n db_connect.db_dml_parms(con, sql, args)\n db_connect.db_close(con)\n\n\n@dbtimeout_decorator(0)\ndef update_weibo_repost(mid, reposts_count):\n sql = 'select se_repost_count from weibo_search_data where se_mid = :mid'\n args = {'mid': str(mid)}\n con = db_connect.get_con()\n rs = db_connect.db_queryone_params(con, sql, args)\n if reposts_count != rs[0]:\n update_sql = 'update weibo_search_data set se_repost_count = :reposts_count where se_mid = :mid'\n update_args = {'mid': mid, 'reposts_count': reposts_count}\n db_connect.db_dml_parms(con, update_sql, update_args)\n db_connect.db_close(con)\n\n\n@save_decorator\ndef add_search_cont(search_list):\n save_sql = 'insert into weibo_search (mk_primary,mid,murl,create_time,praise_count,repost_count,comment_count,' \\\n 'content,device,user_id,username,uheadimage,user_home,keyword) values(:mk_primary, :mid, ' \\\n ':murl, :create_time, :praise_count,:repost_count, :comment_count, :content, :device, ' \\\n ':user_id, :username,:uheadimage, :user_home, :keyword)'\n\n con = db_connect.get_con()\n\n for search_cont in search_list:\n search_info = {\n 'mk_primary': search_cont.mk_primary,\n 'mid': search_cont.mid,\n 'murl': search_cont.murl,\n 'create_time': search_cont.create_time,\n 'praise_count': search_cont.praise_count,\n 'repost_count': search_cont.repost_count,\n 'comment_count': search_cont.comment_count,\n 'content': search_cont.content,\n 'device': search_cont.device,\n 'user_id': search_cont.user_id,\n 'username': search_cont.username,\n 'uheadimage': search_cont.uheadimage,\n 'user_home': search_cont.user_home,\n 'keyword': search_cont.keyword\n }\n try:\n db_connect.db_dml_parms(con, save_sql, search_info)\n except Exception as why:\n print('插入出错,具体原因为:{why}'.format(why=why))\n print(search_info.__dict__)\n db_connect.db_close(con)\n\n\ndef get_seed_ids():\n \"\"\"\n 操作weibo_search_data表,获取待爬取用户id队列\n :return:\n \"\"\"\n truncate_sql = 'truncate table weibo_sinausers_cache'\n insert_sql = 'insert into weibo_sinausers_cache (select se_userid from weibo_search_data where is_new = 1 ' \\\n 'and se_sourcetype=\\'新浪微博\\' group by se_userid)'\n delelte_sql = 'delete from weibo_sinausers_cache where dsu_id in (select su_id from weibo_sina_users)'\n update_sql = 'update weibo_search_data set is_new = 0 where is_new = 1 and se_sourcetype = \\'新浪微博\\''\n select_sql = 'select dsu_id from weibo_sinausers_cache'\n con = db_connect.get_con()\n db_connect.db_dml(con, truncate_sql)\n print('-----------临时表已清空--------------')\n db_connect.db_dml(con, insert_sql)\n print('-----------临时表数据插入完成--------------')\n db_connect.db_dml(con, delelte_sql)\n print('-----------临时表已去重--------------')\n db_connect.db_dml(con, update_sql)\n print('-----------search表已更新--------------')\n rs = db_connect.db_queryall(con, select_sql)\n print('获取到{num}条需要爬取的id'.format(num=len(rs)))\n db_connect.db_close(con)\n ids = []\n for r in rs:\n ids.append(r[0])\n return ids\n\n\n","sub_path":"db_operation/weibosearch_dao.py","file_name":"weibosearch_dao.py","file_ext":"py","file_size_in_byte":4497,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"624938448","text":"# ##############################################################################\n# Usage: python Emph.py Subj Emphysema_threshold \n# Time: ~ 40s\n# Ref: [Computed tomography–based biomarker provides unique signature...]\n# ##############################################################################\n# 03/22/2021, In Kyu Lee\n# Calculate Emphy% only\n# ##############################################################################\n# Input: \n# - IN CT image, ex) PMSN03001_IN0.img.gz\n# - IN lobe mask, ex) PMSN03001_IN0_vida-lobes.img\n# Output:\n# - Emphysema statistics, ex) PMSN03001_EX0-TO-PMSN03001_IN0-SSTVD_lobar_Emph.txt\n# - Emphysema image, ex) PMSN03001_EX0-TO-PMSN03001_IN0-SSTVD_Emph.img\n# ##############################################################################\n\n# import libraries\nimport os\nimport sys\nfrom medpy.io import load, save\nimport numpy as np\nimport pandas as pd\nimport time\nimport SimpleITK as sitk\nsitk.ProcessObject_SetGlobalWarningDisplay(False)\n\nstart = time.time()\nSubj = str(sys.argv[1]) # Subj = 'PMSN03001'\nI1 = str(sys.argv[2]) # I1 = 'IN0'\nI2 = str(sys.argv[3]) # I2 = 'EX0'\nif len(sys.argv)==3:\n emphy_threshold = -950\nelse:\n emphy_threshold = int(sys.argv[4])\n\n# Input Path\nIN_path = f'{Subj}_{I1}.img.gz'\nIN_lobe_path = f'{Subj}_{I1}_vida-lobes.img'\nif not os.path.exists(IN_lobe_path):\n IN_lobe_path = f'{Subj}_{I1}_vida-lobes.img.gz'\n\n# Output Path\nemphy_stat_path = f'{Subj}_{I2}-TO-{Subj}_{I1}-SSTVD_lobar_Emph.txt'\nemphy_img_path = f'{Subj}_{I2}-TO-{Subj}_{I1}-SSTVD_Emph.img'\n\n# Data Loading . . .\nIN_img,IN_header = load(IN_path)\nIN_lobe_img, IN_lobe_header = load(IN_lobe_path)\n# get .hdr from IN.hdr\nemphy_h = IN_header\n\n# prepare .img\nemphy_img = np.zeros((IN_img.shape),dtype='uint8')\n# 2 if Emphysema\nemphy_img[(IN_img\",\n \"pdc_verify_cert\": true,\n \"pdc_component_df_label\": \"com.redhat.component\",\n \"pdc_contact_role\": \"Devel_Owner\"\n }\n }]\n \"\"\"\n key = \"sendmail\"\n\n # symbolic constants for states\n MANUAL_SUCCESS = 'manual_success'\n MANUAL_FAIL = 'manual_fail'\n AUTO_SUCCESS = 'auto_success'\n AUTO_FAIL = 'auto_fail'\n AUTO_CANCELED = 'auto_canceled'\n\n allowed_states = set([MANUAL_SUCCESS, MANUAL_FAIL, AUTO_SUCCESS, AUTO_FAIL, AUTO_CANCELED])\n\n PDC_TOKEN_FILE = 'pdc.token'\n PDC_CONTACT_ROLE = 'Devel_Owner'\n\n def __init__(self, tasker, workflow, send_on=None, url=None, submitter='unknown', pdc_url=None,\n pdc_verify_cert=True, pdc_component_df_label=\"com.redhat.component\", pdc_secret_path=None,\n pdc_contact_role=None, smtp_uri=None, from_address=None,\n error_addresses=None):\n \"\"\"\n constructor\n\n :param tasker: DockerTasker instance\n :param workflow: DockerBuildWorkflow instance\n :param send_on: list of build states when a notification should be sent\n :param url: URL to OSv3 instance where the build logs are stored\n :param submitter: name of user who submitted a build (plain string)\n :param pdc_url: URL of PDC to query for contact information\n :param pdc_verify_cert: whether or not to verify SSL cert of PDC (defaults to True)\n :param pdc_component_df_label: name of Dockerfile label to use as PDC global_component\n :param pdc_secret_path: path to pdc.token file; $SOURCE_SECRET_PATH otherwise\n :param pdc_contact_role: name of PDC role to contact\n :param smtp_uri: URL of SMTP server to use to send the message (e.g. \"foo.com:25\")\n :param from_address: the \"From\" of the notification email\n :param error_addresses: list of email addresses where to send an email if there's an error\n (e.g. if we can't find out who to notify about the failed build)\n \"\"\"\n super(SendMailPlugin, self).__init__(tasker, workflow)\n self.send_on = send_on\n self.url = url\n self.submitter = submitter\n self.pdc_url = pdc_url\n self.pdc_verify_cert = pdc_verify_cert\n self.pdc_component_df_label = pdc_component_df_label\n self.pdc_secret_path = pdc_secret_path\n self.pdc_contact_role = pdc_contact_role or self.PDC_CONTACT_ROLE\n self.smtp_uri = smtp_uri\n self.from_address = from_address\n self.error_addresses = error_addresses\n\n def _should_send(self, rebuild, success, canceled):\n \"\"\"Return True if any state in `self.send_on` meets given conditions, thus meaning\n that a notification mail should be sent.\n \"\"\"\n should_send = False\n\n should_send_mapping = {\n self.MANUAL_SUCCESS: not rebuild and success,\n self.MANUAL_FAIL: not rebuild and not success,\n self.AUTO_SUCCESS: rebuild and success,\n self.AUTO_FAIL: rebuild and not success,\n self.AUTO_CANCELED: rebuild and canceled\n }\n\n for state in self.send_on:\n should_send |= should_send_mapping[state]\n return should_send\n\n def _render_mail(self, rebuild, success, canceled):\n \"\"\"Render and return subject and body of the mail to send.\"\"\"\n subject_template = 'Image %(image)s; Status %(endstate)s; Submitted by %(user)s'\n body_template = '\\n'.join([\n 'Image: %(image)s',\n 'Status: %(endstate)s',\n 'Submitted by: %(user)s',\n 'Logs: %(logs)s',\n ])\n\n endstate = None\n if canceled:\n endstate = 'canceled'\n else:\n endstate = 'successful' if success else 'failed'\n url = None\n if self.url and self.workflow.openshift_build_selflink:\n url = urljoin(self.url, self.workflow.openshift_build_selflink + '/log')\n\n formatting_dict = {\n 'image': self.workflow.image,\n 'endstate': endstate,\n 'user': '' if rebuild else self.submitter,\n 'logs': url\n }\n return (subject_template % formatting_dict, body_template % formatting_dict)\n\n def _get_pdc_token(self):\n # we want to allow pdc_secret_path to be None in __init__ - I'm assuming that in future\n # we'll want different sources of contact info, so we only want to raise when\n # the plugin actually tries to authenticate against PDC and doesn't have pdc_secret_path\n if self.pdc_secret_path is None:\n raise PluginFailedException('Getting PDC token, but pdc_secret_path is unspecified')\n token_file = os.path.join(self.pdc_secret_path, self.PDC_TOKEN_FILE)\n\n self.log.debug('getting PDC token from file %s', token_file)\n\n with open(token_file, 'r') as f:\n return f.read().strip()\n\n def _get_component_label(self):\n \"\"\"Get value of Dockerfile label that is to be used as `global_component` to query\n PDC release-components API endpoint.\n \"\"\"\n labels = df_parser(self.workflow.builder.df_path, workflow=self.workflow).labels\n if self.pdc_component_df_label not in labels:\n raise PluginFailedException('No %s label in Dockerfile, can\\'t get PDC component',\n self.pdc_component_df_label)\n return labels[self.pdc_component_df_label]\n\n def _get_receivers_list(self):\n \"\"\"Return list of receivers of the notification.\n\n :raises RuntimeError: if PDC can't be contacted or doesn't provide sufficient data\n :raises PluginFailedException: if there's a critical error while getting PDC data\n \"\"\"\n\n # TODO: document what this plugin expects to be in Dockerfile/where it gets info from\n global_component = self._get_component_label()\n # this relies on bump_release plugin configuring source.git_commit to actually be\n # branch name, not a commit\n if not isinstance(self.workflow.source, GitSource):\n raise PluginFailedException('Source is not of type \"GitSource\", panic!')\n git_branch = self.workflow.source.git_commit\n try:\n r = requests.get(urljoin(self.pdc_url, 'rest_api/v1/release-component-contacts/'),\n headers={'Authorization': 'Token %s' % self._get_pdc_token()},\n params={'global_component': global_component,\n 'dist_git_branch': git_branch,\n 'role': self.pdc_contact_role},\n verify=self.pdc_verify_cert)\n except requests.RequestException as e:\n self.log.error('failed to connect to PDC: %s', str(e))\n raise RuntimeError(e)\n\n if r.status_code != 200:\n self.log.error('PDC returned status code %s, full response: %s',\n r.status_code, r.text)\n raise RuntimeError('PDC returned non-200 status code (%s), see referenced build log' %\n r.status_code)\n\n contacts = r.json()\n\n if contacts['count'] == 0:\n self.log.error('no %s role for the component', self.pdc_contact_role)\n raise RuntimeError('no %s role for the component' % self.pdc_contact_role)\n\n send_to = []\n for contact in contacts['results']:\n send_to.append(contact['contact']['email'])\n\n return send_to\n\n def _send_mail(self, receivers_list, subject, body):\n \"\"\"Actually sends the mail with `subject` and `body` to all members of `receivers_list`.\"\"\"\n msg = MIMEText(body)\n msg['Subject'] = subject\n msg['From'] = self.from_address\n msg['To'] = ', '.join(receivers_list)\n\n s = None\n try:\n s = smtplib.SMTP(self.smtp_uri)\n s.sendmail(self.from_address, receivers_list, msg.as_string())\n except (socket.gaierror, smtplib.SMTPException) as e:\n raise PluginFailedException('Error communicating with SMTP server: %s' % str(e))\n finally:\n if s is not None:\n s.quit()\n\n def run(self):\n # verify that given states are subset of allowed states\n unknown_states = set(self.send_on) - self.allowed_states\n if len(unknown_states) > 0:\n raise PluginFailedException('Unknown state(s) \"%s\" for sendmail plugin' %\n '\", \"'.join(sorted(unknown_states)))\n\n rebuild = is_rebuild(self.workflow)\n success = not self.workflow.build_result.is_failed()\n canceled = self.workflow.autorebuild_canceled\n\n self.log.info('checking conditions for sending notification ...')\n if self._should_send(rebuild, success, canceled):\n self.log.info('notification about build result will be sent')\n subject, body = self._render_mail(rebuild, success, canceled)\n try:\n self.log.debug('getting list of receivers for this component ...')\n receivers = self._get_receivers_list()\n except RuntimeError as e:\n self.log.error('couldn\\'t get list of receivers, sending error message ...')\n # TODO: maybe improve the error message/subject\n body = '\\n'.join([\n 'Failed to get contact for %s, error: %s' % (str(self.workflow.image), str(e)),\n 'Since your address is in \"error_addresses\", this email was sent to you to '\n 'take action on this.',\n 'Wanted to send following mail:',\n '',\n body\n ])\n receivers = self.error_addresses\n self.log.info('sending notification to %s ...', receivers)\n self._send_mail(receivers, subject, body)\n else:\n self.log.info('conditions for sending notification not met, doing nothing')\n","sub_path":"atomic_reactor/plugins/exit_sendmail.py","file_name":"exit_sendmail.py","file_ext":"py","file_size_in_byte":11513,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"478631893","text":"from django.urls import path\nfrom . import views\nfrom .views import (PostListView,\n PostDetailView,\n PostCreateView,\n PostUpdateView,\n PostDeleteView,\n UserPostListView)\n\nurlpatterns=[\n path('',views.index,name='index'),\n #path('',views.intro)\n path('',PostListView.as_view(),name = 'mainapp-home'),\n path('user/',UserPostListView.as_view(),name = 'user-posts'),\n path('post//',PostDetailView.as_view(),name = 'post-detail'),\n path('post/new/',PostCreateView.as_view(),name = 'post-create'),\n path('post//update/', PostUpdateView.as_view(), name='post-update'),\n path('post//delete/', PostDeleteView.as_view(), name='post-delete'),\n path('intro/',views.intro,name = 'mainapp-intro'),\n]","sub_path":"travelhacks/mainapp/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":852,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"57040127","text":"#!/usr/bin/env python3\nimport json\nimport os\nimport sys\n\nfrom elasticsearch import Elasticsearch\n\n\nif __name__ == \"__main__\":\n# if os.environ.get('ES_HOSTS'):\n# ELASTICSEARCH_HOSTS = \\\n# [{'host': es_host, 'port': 9200}\n# for es_host in os.environ.get('ES_HOSTS').split(\",\")]\n# else:\n# ELASTICSEARCH_HOSTS = None\n\n# try:\n# if ELASTICSEARCH_HOSTS:\n# es = Elasticsearch(ELASTICSEARCH_HOSTS)\n# else:\n# raise Exception\n# except Exception as e:\n# print(e)\n# sys.exit(1)\n \n ELASTICSEARCH_HOSTS = [{'host': \"127.0.0.1\", 'port': 9200}]\n es = Elasticsearch(ELASTICSEARCH_HOSTS)\n\n flist = range(512)\n fields = {}\n\n for f in flist:\n fields[\"F\" + str(f)] = {\"type\": \"double\"}\n\n request_body = {'mappings': {'image': {'properties': fields}}}\n\n print(\"Initializing elasticsearch\")\n es.indices.create(index='visimil', body=request_body, ignore=400)\n","sub_path":"elasticsearch_init.py","file_name":"elasticsearch_init.py","file_ext":"py","file_size_in_byte":971,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"645366934","text":"import data\nimport config\nfrom sklearn.feature_extraction.text import TfidfVectorizer\nfrom sklearn.feature_extraction.text import TfidfTransformer\nfrom sklearn.metrics.pairwise import linear_kernel\n\nprint(config.content_ml_rec_output_file)\n\nmat = data.read_and_create_term_frequency()\ntf_transformer = TfidfTransformer().fit(mat)\ntf_idf_mat = tf_transformer.transform(mat)\ntf_arr = tf_idf_mat.toarray()\nprint('tf_idf_mat......')\nprint(tf_idf_mat.shape)\ncosine_similarities = linear_kernel(tf_idf_mat, tf_idf_mat)\nprint('Cosine Similarites calculated')\nprint(cosine_similarities.shape)\nresults = {}\n\nfor id in range(0, 16980):\n similar_indices = cosine_similarities[id].argsort()[:-50:-1]\n similar_items = [(cosine_similarities[id][i], i) for i in similar_indices]\n\n\t# First item is the item itself, so remove it.\n\t# Each dictionary entry is like: [(1,2), (3,4)], with each tuple being (score, item_id)\n results[id] = similar_items[1:]\n\nprint('Done calculating the similar ones')\nprint('----'*8)\nprint(results[0])\nprint('----'*8)\n\ncontent_ml_rec_details_output_file = open(config.content_ml_rec_details_output_file, \"w\")\ncontent_ml_rec_output_file = open(config.content_ml_rec_output_file, \"w\")\nprint(\"-------\"*5)\n\nfor i in range(0, 16980):\n item_id = i\n recs = results[item_id][:config.top_k_products]\n user_rec = []\n user_rec_papers = []\n for rec in recs:\n user_rec.append((rec[1],rec[0]))\n user_rec_papers.append(rec[1])\n print(\"u : {0} rec_papers {1}\".format(item_id, str(user_rec_papers)))\n content_ml_rec_details_output_file.write(\"u : {0} rec_papers {1}\\n\".format(item_id, str(user_rec)))\n docs = \" \".join(str(d) for d in user_rec_papers)\n content_ml_rec_output_file.write(\"{0} {1}\\n\".format(len(user_rec_papers), docs))\n\ncontent_ml_rec_details_output_file.close()\ncontent_ml_rec_output_file.close()\n\n######################################################\n\n######################################################","sub_path":"submission/ContentML_+_SVD_+_AutoencoSVD/content_ml.py","file_name":"content_ml.py","file_ext":"py","file_size_in_byte":1939,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"584639286","text":"import requests\nfrom attr import attrs, attrib\n\n\n@attrs\nclass BiliBili(object):\n target_utl = attrib(default='https://t.bilibili.com')\n data_save_path = attrib(default=r'C:\\Users\\10248\\Desktop\\test.txt')\n headers = attrib(default={'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) '\n 'AppleWebKit/537.36 '\n '(KHTML, like Gecko)'})\n\n def save_ul_data(self):\n with open(self.data_save_path, 'wb') as f:\n f.write(requests.get(self.target_utl, headers=self.headers).content)\n\n\n\nif __name__ == '__main__':\n b = BiliBili()\n b.save_ul_data()\n","sub_path":"自动化/Bili.py","file_name":"Bili.py","file_ext":"py","file_size_in_byte":664,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"396897388","text":"\"\"\"List of colors / IPs for domains\"\"\"\nimport socket\n\nalt_problem_path = ('/ravens_volume/test_data/TR85_Ethiopia_zone_mon_sub'\n '/TRAIN/problem_TRAIN/problemDoc.json')\nalt_problem_args = dict(D3MPROBLEMPATH=alt_problem_path,)\n\nGCE_DEMO_INFO = [('demo', '35.193.45.98', {})]\n\nxAZURE_DEMO_INFO = [\n #('apricot', '40.76.171.8', {}),\n #('demo', '20.62.216.240', {}),\n ('testing', '20.62.247.224', {}),\n ]\n\n\nGCE_COLOR_DOMAIN_PAIRS = [\\\n #('apricot', '34.69.254.93', {}), # apricot.2ravens.org (GCE)\n #('testing', '35.223.87.48', {}), # cyan.2ravens.org (GCE)\n #('demo', '35.193.45.98', {}), # cyan.2ravens.org (GCE)\n #('cyan', '104.154.189.22', {}), # cyan.2ravens.org (GCE)\n\n #('blue', '35.222.247.157', {}), # blue.2ravens.org (GCE) raven-ip-blue\n #('lime', '35.222.64.114', {}), # lime.2ravens.org (GCE) raven-ip-lime\n #('magenta', '35.192.35.125', {}), # magenta.2ravens.org (GCE) raven-ip-magenta\n #('mint', '35.225.129.2', {}), # mint.2ravens.org (GCE) raven-ip-mint\n #('navy', '34.72.175.15', {}), # navy.2ravens.org (GCE) raven-ip-navy\n\n #('olive', '35.232.148.148', {}), # olive.2ravens.org (GCE) raven-ip-olive\n #('orange', '35.223.135.139', {}), # orange.2ravens.org (GCE) raven-ip-orange\n #('purple', '34.71.71.11', {}), # purple.2ravens.org (GCE) raven-ip-purple\n #('red', '104.197.86.199', {}), # red.2ravens.org (GCE) raven-ip-red\n #('yellow', '34.72.173.46', {}), # red.2ravens.org (GCE) raven-ip-yellow\n\n #('pink', ''),\n #('white', ''),\n\n ]\n\n# see https://datadrivendiscovery.org/wiki/pages/viewpage.action?spaceKey=gov&title=Creating+Services\nDM_COLOR_DOMAIN_PAIRS = [\\\n # ('2ravens', '10.108.29.7', {}), # https://2ravens.datadrivendiscovery.org/ (DM)\n\n #('2ravens-summer', '10.108.34.30', {}), # https://2ravens.datadrivendiscovery.org/ (DM)\n ('', '10.108.34.30', {}), # EVAL!! # https://2ravens.datadrivendiscovery.org/ (DM)\n\n #('red-2ravens', '10.108.29.15', {}), # 10.108.29.9 tworavens1.datadrivendiscovery.org (GCE)\n #('blue-2ravens', '10.108.29.10', {}), # tworavens1.datadrivendiscovery.org (GCE)\n #('lime-2ravens', '10.108.29.11'), # tworavens1.datadrivendiscovery.org (GCE)\n #('maroon-2ravens', '10.108.29.12'), # tworavens1.datadrivendiscovery.org (GCE)\n #('white-2ravens', '10.108.29.13'), # tworavens1.datadrivendiscovery.org (GCE)\n #('orange-2ravens', '10.108.29.14'), # tworavens1.datadrivendiscovery.org (GCE)\n #('lime', '34.67.169.83'), # lime.2ravens.org (GCE)\n #('', '104.197.235.238'), # 2ravens.org (GCE)\n #\n ]\n\n#COLOR_DOMAIN_PAIRS = DM_COLOR_DOMAIN_PAIRS\n#COLOR_DOMAIN_PAIRS = GCE_COLOR_DOMAIN_PAIRS\n\ndef is_domain_set(dcolor, ip_address, cnt=''):\n \"\"\"\n Check if the subdomain as been set\n > socket.gethostbyname_ex('red.2ravens.org')\n ('red.2ravens.org', [], ['35.224.128.61'])\n \"\"\"\n hostname = f'{dcolor}.2ravens.org'\n if cnt:\n cnt = f'({cnt})'\n print(f'\\n-- {cnt} {hostname}: {ip_address} --')\n #\n try:\n domain_info = socket.gethostbyname_ex(hostname)\n except socket.gaierror as err_obj:\n print(' > ERROR! ', err_obj)\n return\n #\n if len(domain_info) >= 3:\n ip_list = domain_info[2]\n if ip_list and ip_address == ip_list[0]:\n print(' > looks good!')\n else:\n print(' > ERROR!')\n print('domain_info', domain_info)\n\ndef check_domains(color_pairs=GCE_COLOR_DOMAIN_PAIRS):\n \"\"\"Check if the domain is set to the expected IP\"\"\"\n cnt = 0\n for dcolor, ip_address in color_pairs:\n #print(f'{dcolor}.2ravens.org')\n cnt += 1\n is_domain_set(dcolor, ip_address, cnt=cnt)\n\n\nif __name__ == '__main__':\n check_domains()\n","sub_path":"gce_ips/color_ip_table.py","file_name":"color_ip_table.py","file_ext":"py","file_size_in_byte":4003,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"510694926","text":"from django.urls import include, path\n\nfrom rest_framework import routers\n\nfrom .views import (\n registration,\n registration_done,\n participants,\n contributions,\n ManagementView,\n ParticipantExportView,\n AbstractExportView,\n EmailExportView\n)\nfrom .viewsets import (\n MeetingViewSet,\n ParticipantViewSet,\n ContributionViewSet,\n ContributionTypeViewSet,\n StatusViewSet,\n PaymentViewSet\n)\n\n\napp_name = 'meetings'\n\nrouter = routers.DefaultRouter()\nrouter.register(r'meetings', MeetingViewSet, base_name='meeting')\nrouter.register(r'participants', ParticipantViewSet, base_name='participant')\nrouter.register(r'contributions', ContributionViewSet, base_name='contribution')\nrouter.register(r'contributiontypes', ContributionTypeViewSet, base_name='contributiontype')\nrouter.register(r'statuses', StatusViewSet, base_name='status')\nrouter.register(r'payments', PaymentViewSet, base_name='payment')\n\nurlpatterns = [\n path('api/', include(router.urls)),\n path('/registration/', registration, name='registration'),\n path('/registration/done/', registration_done, name='registration_done'),\n path('/participants/', participants, name='participants'),\n path('/contributions/', contributions, name='contributions'),\n path('/management/', ManagementView.as_view(), name='management'),\n path('/export/participants//', ParticipantExportView.as_view(), name='export_participants'),\n path('/export/abstracts/', AbstractExportView.as_view(), name='export_abstracts'),\n path('/export/emails/', EmailExportView.as_view(), name='export_emails'),\n]\n","sub_path":"daiquiri/meetings/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1698,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"150050317","text":"from django.db import models\n\nfrom edc_constants.choices import YES_NO\nfrom edc.subject.code_lists.models import DxCode\n\nfrom .base_death import BaseDeath\n\n\nclass BaseDeathReport(BaseDeath):\n\n \"\"\"\n Death form / AF005\n \"\"\"\n illness_duration = models.IntegerField(\n verbose_name=\"Duration of acute illness directly causing death \",\n help_text=\"in days (If unknown enter -1)\",\n )\n\n perform_autopsy = models.CharField(\n max_length=3,\n choices=YES_NO,\n verbose_name=\"Will an autopsy be performed later \",\n help_text=\"\",\n )\n\n dx_code = models.ForeignKey(DxCode,\n max_length=25,\n verbose_name=\"Please code the cause of death as one of the following:\",\n help_text=\"Use diagnosis code from Diagnosis Reference Listing\",\n )\n\n class Meta:\n abstract = True\n","sub_path":"edc/subject/adverse_event/models/base_death_report.py","file_name":"base_death_report.py","file_ext":"py","file_size_in_byte":860,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"91577233","text":"def test_defect_finder(test_dir):\n from pymatgen.core import IStructure\n\n from pymatgen.analysis.defects.finder import DefectSiteFinder\n\n base = IStructure.from_file(test_dir / \"GaN.vasp\")\n\n # Vacancy\n sc = base * [2, 2, 2]\n frac_pos_rm = sc.sites[9].frac_coords\n sc.remove_sites([9])\n finder = DefectSiteFinder()\n frac_pos_guess = finder.get_native_defect_position(sc, base)\n dist, _ = sc.lattice.get_distance_and_image(frac_pos_guess, frac_pos_rm)\n assert dist < 0.5\n\n # Interstitial\n sc = base * [2, 2, 2]\n frac_pos_insert = [0.666665, 0.333335, 0.31206]\n sc.insert(0, \"Ga\", frac_pos_insert)\n frac_pos_guess = finder.get_native_defect_position(sc, base)\n dist, _ = sc.lattice.get_distance_and_image(frac_pos_guess, frac_pos_insert)\n assert dist < 0.5\n\n # Anti-site\n sc = base * [2, 2, 2]\n Ga_pos = sc.sites[12].frac_coords\n N_pos = sc.sites[16].frac_coords\n dist, _ = sc.lattice.get_distance_and_image(Ga_pos, N_pos)\n assert dist < 2\n # swapping two sites that are close to each other\n sc.remove_sites([16])\n sc.remove_sites([12])\n # have the distort slightly to the midpoint\n mid_point = (N_pos + Ga_pos) / 2\n sc.insert(0, \"N\", 0.99 * Ga_pos + 0.01 * mid_point)\n sc.insert(0, \"Ga\", 0.99 * N_pos + 0.01 * mid_point)\n\n frac_pos_guess = finder.get_native_defect_position(sc, base)\n dist, _ = sc.lattice.get_distance_and_image(frac_pos_guess, mid_point)\n assert dist < 0.5\n","sub_path":"tests/test_finder.py","file_name":"test_finder.py","file_ext":"py","file_size_in_byte":1475,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"328976557","text":"#!/usr/bin/python\n\nimport math\n\ndef recipe_batches(recipe, ingredients):\n\t# BASE CASES\n\tif len(ingredients) != len(recipe):\n\t\treturn 0\n\t# we need a counter to keep a track of how many batches can be done\n\tbatches = 0\n\n\t# we need to iterate to access key/value for both recipe and ingredients\n\tfor ingredient in recipe:\n\t\t# as long as we have enough ingredients, keep going!\n\t\twhile ingredients[ingredient] >= recipe[ingredient]:\n\t\t\t# we check if ingredients current value is greater than recipe current value\n\t\t\tif(ingredients[ingredient] >= recipe[ingredient]):\n\t\t\t\t# if it is, we subtract ingredients value and the recipe value and increase counter by 1.\n\t\t\t\tingredients[ingredient] -= recipe[ingredient]\n\t\t\t\tbatches += 1\n\t\t\t# we check if the number of batches is equal/greater than the length of the recipe, if it is we divide by the length of the recipe\n\t\t\tif(batches >= len(recipe)):\n\t\t\t\tbatches //= len(recipe)\n\treturn batches\n \n\n\nif __name__ == '__main__':\n # Change the entries of these dictionaries to test \n # your implementation with different inputs\n recipe = { 'milk': 100, 'butter': 50, 'flour': 5 }\n ingredients = { 'milk': 132, 'butter': 48, 'flour': 51 }\n print(\"{batches} batches can be made from the available ingredients: {ingredients}.\".format(batches=recipe_batches(recipe, ingredients), ingredients=ingredients))","sub_path":"recipe_batches/recipe_batches.py","file_name":"recipe_batches.py","file_ext":"py","file_size_in_byte":1341,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"385707348","text":"'''\nGiven an integer array nums, return all the triplets [nums[i], nums[j], nums[k]] \nsuch that i != j, i != k, and j != k, \nand nums[i] + nums[j] + nums[k] == 0.\nNotice that the solution set must not contain duplicate triplets.\nEx:\nInput: nums = [-1,0,1,2,-1,-4]\nOutput: [[-1,-1,2],[-1,0,1]]\n'''\n\ndef threeSum(nums):\n res = []\n nums.sort()\n\n for idx, num in enumerate(nums):\n if idx > 0 and num == nums[idx - 1]:\n continue\n\n l, r = idx + 1, len(nums) - 1\n while l < r:\n threeSum = num + nums[l] + nums[r]\n if threeSum > 0:\n r -= 1\n elif threeSum < 0:\n l += 1\n else:\n res.append([num, nums[l], nums[r]])\n l += 1\n while nums[l] == nums[l - 1] and l < r:\n l += 1\n\n return res\n\n\n","sub_path":"15.three_sum.py","file_name":"15.three_sum.py","file_ext":"py","file_size_in_byte":758,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"360430623","text":"class TreeNode:\n def __init__(self, x):\n self.val = x\n self.left = None\n self.right = None\n\nclass Utils:\n \n def build_tree_from_list(self, l):\n\n def build(r, i=0):\n if i < len(r) and r[i]:\n node = TreeNode(r[i])\n node.left = build(r, 2 * i + 1)\n node.right = build(r, 2 * i + 2)\n return node\n \n return build(l)\n\n def bst_find(self, root, x):\n while root and root.val != x:\n if root.val > x:\n root = root.left\n else:\n root = root.right\n return root\n","sub_path":"utils/tree.py","file_name":"tree.py","file_ext":"py","file_size_in_byte":639,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"92704146","text":"\nimport glob, os, string, array, binascii\nfrom string import *\n\n\nrawFile = open('rawimage.dat',\"wb\")\nFile = open('inputs.txt',\"rb\")\nfor line in File:\n for word in line.split():\n bytestring=int(float(word)*127).to_bytes(1, 'big')\n print (\"{}\".format(bytestring))\n rawFile.write(bytestring)\nrawFile = open('rawweight.dat',\"wb\")\nFile = open('weights.txt',\"rb\")\nfor line in File:\n for word in line.split():\n bytestring=int(float(word)*127).to_bytes(1, 'big')\n print (\"{}\".format(bytestring))\n rawFile.write(bytestring)\nrawFile = open('tvmout.txt',\"w\")\nFile = open('output.txt',\"rb\")\nfor line in File:\n for word in line.split():\n #bytestring=int(word*127).to_bytes(1, 'big')\n #print (\"{}\".format(float(word)*127))\n rawFile.write(str(int(float(word)*127*127)))\n rawFile.write(\" \")\n rawFile.write(\"\\n\")\n","sub_path":"dev_tools/convert_raw.py","file_name":"convert_raw.py","file_ext":"py","file_size_in_byte":878,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"549601262","text":"# Assume text is a variable that\n# holds a string. Write Python code\n# that prints out the position\n# of the second occurrence of 'zip'\n# in text, or -1 if it does not occur\n# at least twice.\n\n# The Python code should be general enough\n# to pass every possible case where 'zip'\n# can occur in a string\n\n# Here are two example test cases:\n# text = 'all zip files are zipped'\n# >>> 18\n# text = 'all zip files are compressed'\n# >>> -1\n\ntext = \"all zip files are zipped\"\n\n# ENTER CODE BELOW HERE\n\nn_text = text.find('zip')\nprint(text.find('zip', n_text + 1))\n\n\nx = 6.349838\n\nprint(str(x).find('.'))\n# print(round(x))\n\n\n\n\n\n\n\n\n\n","sub_path":"thought-provoking/substring_word_occurence.py","file_name":"substring_word_occurence.py","file_ext":"py","file_size_in_byte":622,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"411998375","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Nov 11 13:32:13 2019\n\n@author: matthew-bailey\n\"\"\"\n\nimport copy\nfrom typing import Dict, NewType\n\nfrom collections import defaultdict\n\nimport matplotlib.pyplot as plt\nimport networkx as nx\nimport numpy as np\n\ntry:\n from .ring_finder import RingFinder\n from .shape import Shape, node_list_to_edges\nexcept ImportError:\n from ring_finder import RingFinder\n from shape import Shape, node_list_to_edges\n\n\nNode = NewType(\"Node\", int)\nGraph = NewType(\"Graph\", nx.Graph)\nCoord = NewType(\"Coord\", np.array)\n\n\nclass PeriodicRingFinder(RingFinder):\n def __init__(\n self,\n graph: Graph,\n coords_dict: Dict[Node, Coord],\n cell=None,\n missing_policy=\"add\",\n ):\n self.graph: Graph = copy.deepcopy(graph)\n self.missing_policy = missing_policy\n periodic_graph = copy.deepcopy(graph)\n periodic_coords = copy.deepcopy(coords_dict)\n self.cell = cell\n self.cutoffs = cell / 2.0\n self.coords_dict: Dict[Node, Coord] = copy.deepcopy(coords_dict)\n self.original_nodes = {key for key in self.coords_dict.keys()}\n self.perimeter_rings = None\n # First, do the aperiodic computation.\n super().__init__(\n graph=self.graph,\n coords_dict=self.coords_dict,\n cutoffs=cell / 2.0,\n find_perimeter=True,\n missing_policy=self.missing_policy,\n )\n self.aperiodic_graph = self.graph\n self.graph = periodic_graph\n self.coords_dict = periodic_coords\n # Tidying up stage -- remove the long edges,\n # and remove the single coordinate sites.\n self.add_periodic_images()\n self.add_periodic_edges()\n self.graph = self.remove_long_edges()\n self.remove_single_coordinate_sites()\n self.removable_edges = None\n # Now triangulate the graph and do the real heavy lifting.\n self.tri_graph, self.simplices = self.triangulate_graph()\n self.current_rings = {\n Shape(node_list_to_edges(simplex), self.coords_dict)\n for simplex in self.simplices\n }\n\n self.identify_rings()\n self.current_rings = self.find_unique_rings()\n\n def add_ring_images(self, original_coords):\n \"\"\"\n Ensure that the rings occupy the right periodic images.\n \n Walks around each ring and checks if the edges are greater\n than the periodic cutoff. In that case, checks all periodic\n images and tries to find an 'image node' that is less than\n one cutoff away. If we can't, print an error.\n \n :param original_coords: the original coordinates before the periodicity\n was applied to look for node images.\n \"\"\"\n cell_offsets = [\n (0, 0),\n (1, 1),\n (1, 0),\n (1, -1),\n (0, 1),\n (0, -1),\n (-1, 1),\n (-1, 0),\n (-1, -1),\n ]\n\n def _edge_is_too_long(_u_of_edge, _v_of_edge):\n \"\"\"\n Return if an edge is too long.\n \n Takes two nodes, u and v, making up one edge, and\n checks if the distance between them is greater than the cutoff.\n This is not sensitive to order.\n \n :param _u_of_edge: a node key of u, the first node in the edge\n :param _v_of_edge: a node key of the other node in the edge\n :return: whether the edge is longer than cutoffs in x or y.\n \"\"\"\n distance = np.abs(\n self.coords_dict[_u_of_edge] - self.coords_dict[_v_of_edge]\n )\n return np.any(distance > self.cutoffs)\n\n rings_to_remove = set()\n rings_to_add = set()\n edges_to_remove = set()\n edges_to_add = set()\n num_nodes = len(self.original_nodes)\n for ring in self.current_rings:\n rings_to_remove.add(ring)\n node_list = ring.to_node_list()\n edges_to_remove.update(ring.edges)\n iters = 0\n while True:\n unchanged = True\n for i in range(2 * len(node_list)):\n u_of_edge = node_list[i % len(node_list)]\n v_of_edge = node_list[(i + 1) % len(node_list)]\n \n # If we can't find this in the coordinates dictionary,\n # add in an entry copied from the original coordinates.\n if u_of_edge not in self.coords_dict:\n original_u = u_of_edge % num_nodes\n u_cell_offset = u_of_edge // num_nodes\n self.coords_dict[u_of_edge] = original_coords[original_u] + (\n np.array(cell_offsets[u_cell_offset]) * 2 * self.cutoffs\n )\n\n # If we can't find this in the coordinates dictionary,\n # add in an entry copied from the original coordinates.\n if v_of_edge not in self.coords_dict:\n original_v = v_of_edge % num_nodes\n v_cell_offset = v_of_edge // num_nodes\n self.coords_dict[v_of_edge] = original_coords[original_v] + (\n np.array(cell_offsets[v_cell_offset]) * 2 * self.cutoffs\n )\n\n # If it's too long, check each possible node image\n # and see if we can draw an edge that is not too\n # long.\n if _edge_is_too_long(u_of_edge, v_of_edge):\n option_v_poses = [\n self.coords_dict[v_of_edge]\n + (np.array(cell_offsets[j]) * 2 * self.cutoffs)\n for j in range(9)\n ]\n distances = [\n np.abs(self.coords_dict[u_of_edge] - option_v_pos)\n for option_v_pos in option_v_poses\n ]\n hypot_distances = [\n np.hypot(*distance) for distance in distances\n ]\n min_arg = np.argmin(hypot_distances)\n new_v = v_of_edge + (min_arg * num_nodes)\n self.coords_dict[new_v] = option_v_poses[min_arg]\n node_list[(i + 1) % len(node_list)] = new_v\n if new_v != v_of_edge:\n unchanged = False\n # If we haven't had to change any edges, we can\n # leave.\n if unchanged:\n break\n iters += 1\n if iters > 10:\n # We can't seem to find a valid walk around this ring.\n # Print a warning and go about our lives merrily --\n # there is something wrong in the network.\n print(\n \"Could not find a periodic walk around\"\n + str([tuple(item) for item in ring.edges])\n )\n break\n new_ring = Shape(\n node_list_to_edges(node_list, is_ring=True),\n self.coords_dict,\n ring._is_self_interacting,\n )\n edges_to_add.update(new_ring.edges)\n rings_to_add.add(new_ring)\n self.current_rings = self.current_rings - rings_to_remove\n self.current_rings.update(rings_to_add)\n self.graph.remove_edges_from([tuple(item) for item in edges_to_remove])\n self.graph.add_edges_from([tuple(item) for item in edges_to_add])\n return self.current_rings\n\n def find_unique_rings(self):\n \"\"\"\n Each ring in self.current_shapes has 8 periodic images.\n Identify just one of each, and keep that.\n \"\"\"\n num_nodes = len(self.original_nodes)\n unique_rings = defaultdict(set)\n for ring in self.current_rings:\n modulo_edges = set()\n for edge in ring.edges:\n modulo_edge = frozenset({item % num_nodes for item in edge})\n modulo_edges.add(modulo_edge)\n new_ring = Shape(modulo_edges)\n unique_rings[new_ring].add(ring)\n\n # The \"perimeter ring\" is misidentified as a consequence\n # of the images we use. Thankfully, we know that\n # other rings can appear 1x, 2x, 4x, 6x or 9x.\n # Thus, a ring that appears 8x is always spurious.\n to_remove = set()\n for ring, ring_copies in unique_rings.items():\n if len(ring_copies) == 8:\n to_remove.add(ring)\n if to_remove:\n for ring in to_remove:\n del unique_rings[ring]\n # Now, from this set of unique rings we pick just\n # one to plot -- the one that has the most nodes\n # in the original periodic image.\n canonical_rings = set()\n for unique_ring, copy_rings in unique_rings.items():\n copy_rings = list(copy_rings)\n num_shared_edges = []\n num_shared_nodes = []\n nodes_unique = {item for edge in unique_ring.edges for item in edge}\n for copy_ring in copy_rings:\n shared_edges = unique_ring.edges.intersection(copy_ring.edges)\n nodes_copy = {item for edge in copy_ring.edges for item in edge}\n shared_nodes = nodes_unique.intersection(nodes_copy)\n\n num_shared_edges.append(len(shared_edges))\n num_shared_nodes.append(len(shared_nodes))\n max_shared_edges = max(num_shared_edges)\n # If none of the mirror rings share a node with\n # the 'original ring', it means that the original\n # ring doesn't really exist. It's spurious.\n # I can probably rectify that some other way,\n # but throwing it out seems the best away for now.\n if max(num_shared_nodes) == 0:\n continue\n max_shared_idx = num_shared_edges.index(max_shared_edges)\n canonical_rings.add(copy_rings[max_shared_idx])\n return canonical_rings\n\n def add_link_between(self, node_a, node_b, image_a, image_b):\n \"\"\"\n Adds edges between all combinations of node_a and node_b\n across two periodic images (i.e. (a_a, b_b), (a_b, b_a)\n (a_a, b_a), (a_b, b_b)). Then we let remove_long_edges\n sort them out.\n :param node_a:\n :param node_b:\n :param image_a: a tuple in the form (x, y) indicating the offset of this image from the centre\n :param image_b: a tuple in the form (x, y) indicating the offset of this image from the centre.\n \"\"\"\n\n # Make sure (0, 0) is the first offset, so we don't duplicate\n # the central nodes. The rest can be in any order as we\n # look them up later.\n num_nodes = len(self.original_nodes)\n cell_offsets = [\n (0, 0),\n (1, 1),\n (1, 0),\n (1, -1),\n (0, 1),\n (0, -1),\n (-1, 1),\n (-1, 0),\n (-1, -1),\n ]\n assert image_a in cell_offsets, f\"{image_a} not in {cell_offsets}\"\n assert image_b in cell_offsets, f\"{image_b} not in {cell_offsets}\"\n assert (\n 0 <= node_a and node_a <= num_nodes\n ), f\"{node_a} must be a non-image index (0 <= node_a <= {num_nodes})\"\n assert (\n 0 <= node_b and node_b <= num_nodes\n ), f\"{node_b} must be a non-image index (0 <= node_b <= {num_nodes})\"\n\n image_a_offset = num_nodes * cell_offsets.index(image_a)\n image_b_offset = num_nodes * cell_offsets.index(image_b)\n self.graph.add_edge(node_a + image_a_offset, node_b + image_b_offset)\n self.graph.add_edge(node_a + image_b_offset, node_b + image_a_offset)\n\n def add_periodic_images(self):\n \"\"\"\n Remove any edges that are longer than\n a set of cutoffs, useful to make a periodic cell\n aperiodic.\n :param graph: the networkx graph to detect single-coordinate\n nodes in\n :param coords_dict: a dictionary, keyed by nodes,\n with values being the [x, y] coordinates of the nodes, which\n we use to remove long bonds.\n :param cutoffs: an [max_x, max_y] sequence, removing any edges\n with a component longer than max_x or max_y. For the minimum\n image convention, we want these to be half the both length.\n :return graph: a graph minus the edges that are too long. Note\n that this mutates the original graph, so the return value can\n be ignored.\n \"\"\"\n periodic_coords_dict = dict()\n num_nodes = len(self.coords_dict)\n cell_offsets = [\n (0, 0),\n (1, 1),\n (1, 0),\n (1, -1),\n (0, 1),\n (0, -1),\n (-1, 1),\n (-1, 0),\n (-1, -1),\n ]\n\n to_add = set()\n perimeter_nodes = set()\n for ring in self.perimeter_rings:\n perimeter_nodes.update(ring.nodes)\n perimeter_nodes.update(self.removed_nodes)\n edge_images = set()\n for node in perimeter_nodes:\n edge_images.update(\n frozenset([node, item])\n for item in set(self.graph.neighbors(node))\n if node != item\n )\n for edge_a, edge_b in edge_images:\n a_pos = self.coords_dict[edge_a]\n b_pos = self.coords_dict[edge_b]\n for i, cell_offset in enumerate(cell_offsets):\n offset = np.array(cell_offset) * self.cell\n new_edge_a = (i * num_nodes) + edge_a\n new_edge_b = (i * num_nodes) + edge_b\n new_a_pos = a_pos + offset\n new_b_pos = b_pos + offset\n periodic_coords_dict[new_edge_a] = new_a_pos\n periodic_coords_dict[new_edge_b] = new_b_pos\n to_add.add((new_edge_a, new_edge_b))\n self.graph.add_edges_from(to_add)\n self.coords_dict.update(periodic_coords_dict)\n\n def add_periodic_edges(self):\n \"\"\"\n Turns periodic edges into minimum-image convention\n edges. Finds the edges that are longer than\n half a unit cell, and turns them into edges\n between neighbouring images.\n TODO: remove abhorrent kafkaesque arithmetic 2019-11-13\n \"\"\"\n perimeter_nodes = set()\n for ring in self.perimeter_rings:\n perimeter_nodes.update(ring.nodes)\n perimeter_nodes.update(self.removed_nodes)\n\n edge_images = set()\n for node in perimeter_nodes:\n edge_images.update(\n frozenset([node, item]) for item in set(self.graph.neighbors(node))\n )\n handled_nodes = set(self.aperiodic_graph.nodes())\n handled_nodes = handled_nodes.difference(perimeter_nodes)\n num_nodes = len(self.original_nodes)\n for edge in edge_images:\n edge = tuple(edge)\n if (\n edge[0] % num_nodes in handled_nodes\n and edge[1] % num_nodes in handled_nodes\n ):\n continue\n pos_a = self.coords_dict[edge[0]]\n pos_b = self.coords_dict[edge[1]]\n distance = np.abs(pos_b - pos_a)\n if distance[0] > self.cutoffs[0] and distance[1] > self.cutoffs[1]:\n if np.all(pos_a < pos_b) or np.all(pos_a > pos_b):\n # This is a bottom-left top-right link. Add in a\n # link from (0, 0) to (1, 1) and (0, 0) to (-1, -1).\n self.add_link_between(edge[0], edge[1], (0, 0), (1, 1))\n self.add_link_between(edge[0], edge[1], (0, 0), (-1, -1))\n self.add_link_between(edge[0], edge[1], (-1, 0), (0, 1))\n self.add_link_between(edge[0], edge[1], (0, -1), (1, 0))\n else:\n # This is a top-left bottom-right link. Add in a\n # link from (0, 0) to (-1, 1) and (0, 0) to (-1, 1).\n self.add_link_between(edge[0], edge[1], (0, 0), (-1, 1))\n self.add_link_between(edge[0], edge[1], (0, 0), (1, -1))\n self.add_link_between(edge[0], edge[1], (1, 0), (0, 1))\n self.add_link_between(edge[0], edge[1], (0, -1), (-1, 0))\n elif distance[1] > self.cutoffs[1]:\n # There is an edge that spans the y-coordinate.\n # Remove it, and add in the six new edges\n self.add_link_between(edge[0], edge[1], (-1, 0), (-1, -1))\n self.add_link_between(edge[0], edge[1], (0, 0), (0, -1))\n self.add_link_between(edge[0], edge[1], (1, 0), (1, -1))\n\n self.add_link_between(edge[0], edge[1], (-1, 1), (-1, 0))\n self.add_link_between(edge[0], edge[1], (0, 1), (0, 0))\n self.add_link_between(edge[0], edge[1], (1, 1), (1, 0))\n\n elif distance[0] > self.cutoffs[0]:\n # There is an edge that spans the x-coordinate.\n # Remove it, and add in the six new edges.\n self.add_link_between(edge[0], edge[1], (1, -1), (0, -1))\n self.add_link_between(edge[0], edge[1], (1, 0), (0, 0))\n self.add_link_between(edge[0], edge[1], (1, 1), (0, 1))\n\n self.add_link_between(edge[0], edge[1], (0, -1), (-1, -1))\n self.add_link_between(edge[0], edge[1], (0, 0), (-1, 0))\n self.add_link_between(edge[0], edge[1], (0, 1), (-1, 1))\n\n\nif __name__ == \"__main__\":\n G: Graph = nx.Graph()\n with open(\"./data/coll_edges.dat\", \"r\") as fi:\n fi.readline() # Skip header\n for line in fi.readlines():\n x, y = [int(item) for item in line.split(\",\")]\n G.add_edge(x, y)\n\n COORDS_DICT: Dict[Node, Coord] = {}\n with open(\"./data/coll_coords.dat\", \"r\") as fi:\n fi.readline() # Skip header\n for line in fi.readlines():\n line = line.split(\",\")\n node_id, x, y = int(line[0]), float(line[1]), float(line[2])\n COORDS_DICT[node_id] = np.array([x, y])\n XS = [item[0] for item in COORDS_DICT.values()]\n YS = [item[1] for item in COORDS_DICT.values()]\n ring_finder = PeriodicRingFinder(\n G, COORDS_DICT, np.array([max(XS) - min(XS), max(YS) - min(YS)])\n )\n\n FIG, AX = plt.subplots()\n FIG.patch.set_visible(False)\n AX.axis(\"off\")\n ring_finder.draw_onto(AX)\n AX.set_xlim(-95, 180)\n AX.set_ylim(-95, 180)\n FIG.savefig(\"./periodic-graph.pdf\")\n","sub_path":"periodic_ring_finder.py","file_name":"periodic_ring_finder.py","file_ext":"py","file_size_in_byte":18783,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"204447633","text":"# this file calculates the string lengths given a certain position\n# on a white board.\n# the position on the white board is defined with the top left corner\n# being (0,0) and the positive x direction being to the right, positive\n# y direction being down.\n#\n# I guess the units that I'm using are centimeters\n#\n# note: this assumes that strings meet up at a singular point on the robot\nimport math\n\n\nclass StringLengths:\n def __init__(self):\n self.left = 0\n self.right = 0\n\n\nclass Rotations:\n def __init__(self):\n self.left = 0\n self.right = 0\n\n\nWIDTH = 1000 # constant which keeps track of width - distance between motors of canvas\nHEIGHT = 1000 # constant which keeps track of height of canvas\n\nCIRCUMFERENCE = 1.3 # 13 millimeters\n\nglobal_string_lengths = StringLengths\nglobalX = 0 # global variable to hold x coordinate of robot\nglobalY = 0 # global variable to hold y coordinate of robot\n\n\n# function to calculate left and right string lengths given an x and a y coordinate.\ndef coordinate_to_string_length(x, y):\n string_pair = StringLengths()\n string_pair.left = math.sqrt(math.pow(x,2) + math.pow(y,2))\n string_pair.right = math.sqrt(math.pow(WIDTH,2) - 2*WIDTH*x + math.pow(x,2) + math.pow(y,2))\n return string_pair\n\n\n# gets the string movement change between two string lengths\ndef get_string_length_change(current_string_lengths, desired_string_lengths):\n string_length_change = StringLengths()\n string_length_change.left = desired_string_lengths.left - current_string_lengths.left\n string_length_change.right = desired_string_lengths.right - current_string_lengths.right\n return string_length_change\n\n\ndef get_rotations_in_degrees(current_string_lengths, desired_string_lengths):\n strings_change = get_string_length_change(current_string_lengths, desired_string_lengths)\n rotations_change = Rotations()\n rotations_change.left = strings_change.left/CIRCUMFERENCE * 360\n rotations_change.right = strings_change.right/CIRCUMFERENCE * 360\n return rotations_change\n\n\nglobal_string_lengths.left = 0\nglobal_string_lengths.right = 0\n#while 1:\nnewX = float(input(\"what x coordinate do you want to go to? (from 0 to {}) \".format(WIDTH)))\nnewY = float(input(\"y coordinate? (from 0 to {}) \".format(HEIGHT)))\nnew_string_pair = coordinate_to_string_length(newX, newY)\n\n#print(\"Your left string should have length\", new_string_pair.left)\n#print(\"Your right string should have length\", new_string_pair.right)\n\nstring_pair_change = get_string_length_change(global_string_lengths, new_string_pair)\n\n#print(\"Your left string change should be\", string_pair_change.left)\n#print(\"Your right string change should be\", string_pair_change.right)\n\nrotations_pair_change = get_rotations_in_degrees(global_string_lengths, new_string_pair)\n\nprint(\"Your left motor change should be (in degrees)\", rotations_pair_change.left)\nprint(\"Your right motor change should be (in degrees)\", rotations_pair_change.right)\n\nprint(\"------------------------- end --------------------------\")\n\nglobal_string_lengths = new_string_pair\n","sub_path":"stringLengthCalculator.py","file_name":"stringLengthCalculator.py","file_ext":"py","file_size_in_byte":3072,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"455073537","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# @Time : 2019/5/1 3:25 PM\n# @Author : zhongch4g\n# @Site : \n# @File : subsets.py\n# @Software: IntelliJ IDEA\n\nclass Solution:\n \"\"\"\n @param nums: A set of numbers\n @return: A list of lists\n \"\"\"\n def subsets(self, nums):\n nums = sorted(nums)\n combinations = []\n nums.sort()\n self.dfs(nums, 0, [], combinations)\n return combinations\n\n def dfs(self, nums, index, combination, combinations):\n combinations.append(list(combination))\n\n for i in range(index, len(nums)):\n combination.append(nums[i])\n self.dfs(nums, i + 1, combination, combinations)\n combination.pop()\n\n def subsets1(self, nums: 'List[int]') -> 'List[List[int]]':\n res = [[]]\n for n in nums:\n res += [[n] + r for r in res]\n return res\n\n\nsolution = Solution()\ncombination = solution.subsets1([1, 2, 3])\nprint(combination)","sub_path":"extra/subsets.py","file_name":"subsets.py","file_ext":"py","file_size_in_byte":969,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"86503437","text":"from django.http import HttpResponseRedirect\nfrom django.shortcuts import render, reverse\n\nfrom blog.models import Post, Author, Category, ImageForm, Image, PostForm\n\n\ndef index(request):\n return render(request, 'manager/base.html')\n\n\ndef create_post(request):\n if request.method == \"POST\":\n p = Post()\n f = PostForm(request.POST, instance=p)\n if f.is_valid():\n post.save()\n return HttpResponseRedirect(reverse('manager:create_post'))\n\n form = PostForm()\n return render(request, 'manager/create_post.html', {'form': form})\n\n\ndef create_image(request):\n if request.method == \"POST\":\n i = Image()\n f = ImageForm(request.POST, request.FILES, instance=i)\n if f.is_valid():\n f.save()\n return HttpResponseRedirect(reverse('manager:create_image'))\n\n form = ImageForm()\n return render(request, 'manager/create_image.html', {'form': form})\n","sub_path":"manager/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":938,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"654013095","text":"import random\n\nvalues = [\"A\", \"K\", \"Q\", \"J\", \"T\", \"9\"]\nsuits = {\"S\": [\"spades\", \"black\"], \"C\": [\"clubs\", \"black\"], \"D\": [\"diamonds\", \"red\"], \"H\": [\"hearts\", \"red\"]}\n\n\nclass Card(object):\n def __init__(self, value, suit):\n self.value = value\n self.suit = suit\n self.color = suits[suit][1]\n self.is_trump = False\n # may or may not be necessary\n self.display_value = value + suit\n\n\ndeck = [Card(i, j) for i in values for j in list(suits.keys())]\n\n\nclass Player(object):\n def __init__(self, name):\n self.name = name\n self.hand = []\n self.display_hand = []\n self.team = None\n # definitely a better way to do this one but I'm lazy\n\n def remove_card(self, card_to_remove):\n self.display_hand.remove(card_to_remove.display_value)\n self.hand.remove(card_to_remove)\n\n def discard(self, display_message, reprint_message, legal_choice, conditions):\n # conditions should be a list of game conditions.\n # conditions is ordered as [suit to follow, trump suit, left_bauer, add more things as needed here]\n if self.name == \"you\":\n card_in_hand = True\n legal = True\n test_card = None\n while test_card is None:\n if card_in_hand is not True:\n input(\"You must type a card that is in your hand\\n hit enter to continue\")\n print('\\033c')\n print(reprint_message)\n elif not legal:\n input(legal_choice.__doc__ + \"\\n hit enter to continue\")\n print('\\033c')\n print(reprint_message)\n # should this be an input? (hit enter to continue?)\n # probably dangerous to use the docstring as an error message but who cares really\n print(\"\\nYour cards: \", self.display_hand, \"\\n\")\n card_choice = input(display_message + \" and hit enter\\n\")\n for x in self.hand:\n if x.display_value == card_choice.upper():\n # checks if the card is actually in the hand\n # test_card will no longer be none breaking it out of the loop\n test_card = x\n break\n if test_card is None:\n card_in_hand = False\n elif legal_choice(self, test_card, conditions) is False:\n legal = False\n test_card = None\n # the card was in the hand but it was not a legal play so test_card has to be reset\n self.remove_card(test_card)\n return test_card\n else:\n # make it real sometime?\n while True:\n test_card = random.choice(self.hand)\n if legal_choice(self, test_card, conditions):\n break\n self.remove_card(test_card)\n return test_card\n\n\nclass Team(object):\n def __init__(self, name, team_mate1, team_mate2):\n self.team_players = [team_mate1, team_mate2]\n for i in self.team_players:\n i.team = self\n self.name = name\n self.points = 0\n self.handScore = 0\n self.is_winning_hand = False\n\n\nuser = Player(\"you\")\nleft_player = Player(\"Left Computer\")\ncross_player = Player(\"Cross Computer\")\nright_player = Player(\"Right Computer\")\nplayers = [user, left_player, cross_player, right_player] * 10\n\nuser_team = Team(\"your team\", user, cross_player)\nother_team = Team(\"the other team\", left_player, right_player)\n\nteams = [user_team, other_team]\n\n\ndef shuffle_and_deal(dealer):\n # also chooses the first dealer from the first black jack rule\n random.shuffle(deck)\n # and index for players, not a player object\n cards_dealt = {\n 0: [0, 1, 2, 10, 11],\n 1: [3, 4, 12, 13, 14],\n 2: [5, 6, 7, 15, 16],\n 3: [8, 9, 17, 18, 19]\n }\n extras = deck[20:23]\n for i in range(4):\n for x in range(5):\n players[players.index(dealer) + i].hand.append(deck[cards_dealt[i][x]])\n players[players.index(dealer) + i].display_hand.append(deck[cards_dealt[i][x]].display_value)\n return extras\n\n\ndef card_rank_creator(trump, color_inpt, suit_to_follow):\n # could definitely be more efficient, but not enough to notice or care for this\n ranked_cards = []\n pre_sorted = []\n # used to pre sort the non bauer cards before added into ranked cards\n for i in deck:\n if i.suit == trump and i.value == \"J\":\n # right bauer\n ranked_cards.append(i)\n for i in deck:\n if i.color == color_inpt and i.value == \"J\" and i not in ranked_cards:\n # left bauer\n left_bauer = i\n ranked_cards.append(i)\n for i in deck:\n if i.suit == trump and i.value != \"J\":\n # trump cards\n pre_sorted.append(i)\n pre_sorted.sort(key=lambda x: values.index(x.value))\n for i in pre_sorted:\n ranked_cards.append(i)\n pre_sorted = []\n if suit_to_follow != trump:\n for i in deck:\n if i.suit == suit_to_follow:\n # cards of the suit that was led\n pre_sorted.append(i)\n pre_sorted.sort(key=lambda x: values.index(x.value))\n for i in pre_sorted:\n ranked_cards.append(i)\n for i in deck:\n if i not in ranked_cards:\n # the rest of the cards. the order doesn't matter for these.\n ranked_cards.append(i)\n for i in range(7):\n ranked_cards[i].is_trump = True\n # necessary?\n return ranked_cards, left_bauer\n\n\ndef ai_trump_chooser(_chooser, dealer, card_up):\n pick_up_chance = 0\n if _chooser.team == dealer.team and card_up.value == \"J\":\n pick_up_chance += .75\n elif _chooser.team != dealer.team and card_up.value == \"J\":\n pick_up_chance -= .75\n same_suit_cards = 0\n none_of = {\"spades\": \"S\", \"hearts\": \"H\", \"diamonds\": \"D\", \"clubs\": \"C\"}\n for i in _chooser.hand:\n none_of.pop(i.suit, None)\n if i.color == card_up.color and i.value == \"J\":\n pick_up_chance += .625\n if i.suit == card_up.suit:\n if i.value == \"j\":\n pick_up_chance += .5\n same_suit_cards += 1\n if len(none_of) != 0 and card_up.suit not in none_of.keys():\n pick_up_chance += .75\n if card_up.suit in none_of.keys():\n pick_up_chance -= 1\n if same_suit_cards >= 4:\n pick_up_chance += 1\n elif same_suit_cards <= 1:\n pick_up_chance -= .25\n elif (3 >= same_suit_cards >= 2) and _chooser.team == dealer.team:\n pick_up_chance += .25\n return pick_up_chance\n\n\ndef trump_chooser(dealer):\n # 115 lines of pure unreadable nonsense, but it works, so I'm not changing it.\n # future kip is fixing it though\n choices_dict = {\"y\": \"told the dealer to pick it up\", \"n\": \"passed\"}\n who_did_what = []\n kitty = shuffle_and_deal(dealer)\n print(\"The dealer is\", dealer.name, \"(\" + dealer.team.name + \")\")\n print(\"The card on the table is \\n\\n\", kitty[0].display_value, \"\\n\")\n suits_left = [i[0] for i in suits.values()]\n suits_left.remove(suits[kitty[0].suit][0])\n for i in range(1, 9):\n chooser = players[players.index(dealer) + i]\n if i < 5:\n # we're in the process of choosing whether or not to pick up the kitty card\n # this part of the loop will run first (i<4)\n if chooser == user:\n while True:\n print(\"\\nYour cards\", user.display_hand)\n if user == dealer:\n pickup = input(\"\\nWould you like to pick it up? Y/N\\n\").lower()\n else:\n pickup = input(\"\\nWould you like \" + dealer.name + \" to pick it up? Y/N\\n\").lower()\n if pickup == \"y\" or pickup == \"n\":\n who_did_what.append([chooser, choices_dict[pickup]])\n # so that we can reprint it\n print()\n break\n else:\n input(\"Please either type 'Y', 'N'\\n Hit enter to continue\")\n # clear the terminal\n print('\\033c')\n print(\"The dealer is \" + dealer.name + \" (\" + dealer.team.name + \")\")\n print(\"The Card on the table is \\n\\n\", kitty[0].display_value, \"\\n\")\n for j in who_did_what:\n print(j[0].name, j[1])\n continue\n else:\n ai_choice = ai_trump_chooser(chooser, dealer, kitty[0])\n # print(chooser.name, \"cards:\", chooser.display_hand)\n if ai_choice > 1:\n pickup = \"y\"\n who_did_what.append([chooser, \"told you to pick it up\"])\n else:\n pickup = \"n\"\n who_did_what.append([chooser, \"passed\"])\n if pickup == \"y\":\n if user != chooser:\n print(chooser.name, \"told\", dealer.name, \"to pick it up\")\n trump_choice = kitty[0].suit\n thing_to_print = \"The dealer is \" + dealer.name + \" (\" + dealer.team.name + \")\" + \\\n \"\\nThe Card on the table is \\n\\n\" + kitty[0].display_value + \"\\n\" + \\\n \"\\n\".join([i[0].name + \" \" + i[1] for i in who_did_what]) + \"\\n\"\n dealer.discard(\"Please select a card to discard\", thing_to_print, lambda a, b, c: True, [None] * 10)\n # lambda: True should just return true. meaning any card is ok to choose\n dealer.hand.append(kitty[0])\n dealer.display_hand.append(kitty[0].display_value)\n who_called = chooser.team\n break\n elif pickup == \"n\" and chooser != user:\n print(chooser.name, \"passed\")\n else:\n if i == 5:\n who_did_what = []\n input(\"hit enter again to continue\")\n for x in range(9):\n # why is it added 9 times?\n # is it more likely for the computer to choose pass?\n suits_left.append(\"pass\")\n elif i == 8:\n suits_left = list(filter(lambda a: a != \"pass\", suits_left))\n if chooser == user:\n while True:\n print('\\033c')\n print(\"the Card that was passed on was\", kitty[0].display_value, \"\\n\\n\")\n for j in who_did_what:\n print(j[0], j[1])\n print(\"\\nYour cards:\", user.display_hand, \"\\n\")\n trump_input = input(\"choose a suit as trump or type 'pass'\").lower()\n if trump_input in suits_left:\n break\n input(\"Please type a real suit or the word \\\"pass\\\"\\n\"\n \"Remember you cannot pick the suit that was previously passed on\\n\\n\"\n \"If you are the dealer, you can't type pass\\n\"\n \" hit enter to try again\")\n else:\n trump_input = random.choice(suits_left)\n who_did_what.append([chooser.name, \"passed\"])\n if trump_input != \"pass\":\n who_called = chooser.team\n for j, k in suits.items():\n if k[0] == trump_input:\n trump_choice = j\n break\n break\n trump_choice_color = suits[trump_choice][1]\n return trump_choice, trump_choice_color, who_called\n\n\ndef legal_play(player, card_input, conditions):\n \"\"\"please follow suit if you can\"\"\"\n suit_to_follow = conditions[0]\n trump_suit = conditions[1]\n left_bauer = conditions[2]\n playable_cards = []\n for card in player.hand:\n if card.suit == suit_to_follow and card != left_bauer:\n playable_cards.append(card)\n if trump_suit == suit_to_follow:\n if card == left_bauer:\n playable_cards.append(card)\n if not playable_cards:\n playable_cards = player.hand\n if card_input in playable_cards:\n return True\n return False\n\n\ndef play_trick(dealer, last_trick_winner, trump_suit, trump_color):\n cards_played = []\n null, left_bauer = card_rank_creator(trump_suit, trump_color, None)\n # I just need the left bauer but can't get the ranked cards\n # This will do just that half of the function with none as an input for suit to follow\n discard_message = \"The trump suit is \" + suits[trump_suit][0] + \\\n \"\\n\\nYour team has \" + str(user_team.handScore) + \" tricks\" + \\\n \"\\nThe other team has \" + str(other_team.handScore) + \" tricks\\n\"\n if dealer is None:\n first_player = last_trick_winner\n elif last_trick_winner is None:\n first_player = players[players.index(dealer) + 1]\n print(discard_message)\n first_card_throw = first_player.discard(\"please type a card to play from your hand\", discard_message, lambda a, b, c: True, [None] * 10)\n if first_card_throw != left_bauer:\n suit_to_follow = first_card_throw.suit\n else:\n opposite_suit = {\"H\": \"D\", \"D\": \"H\", \"S\": \"C\", \"C\": \"S\"}\n suit_to_follow = opposite_suit[first_card_throw.suit]\n cards_played.append([first_card_throw, first_player])\n print(first_player.name, \" played: \", first_card_throw.display_value)\n discard_message += str(\"\\n\\n\" + first_player.name + \" played: \" + first_card_throw.display_value)\n card_rank, null = card_rank_creator(trump_suit, trump_color, suit_to_follow)\n for i in range(1, 4):\n next_player = players[players.index(first_player) + i]\n next_player_card_throw = next_player.discard(\"please type a card to play from your hand\", discard_message, legal_play, [suit_to_follow, trump_suit, left_bauer])\n cards_played.append([next_player_card_throw, next_player])\n print(next_player.name, \"played: \", next_player_card_throw.display_value)\n discard_message += str(\"\\n\" + next_player.name + \"played: \" + next_player_card_throw.display_value)\n cards_played.sort(key=lambda x: card_rank.index(x[0]))\n print()\n # for i in cardsPlayed:\n # print(i[0].display_value, i[1].name)\n trick_winner = cards_played[0][1]\n print(trick_winner.name, \"won this trick with the\", cards_played[0][0].display_value, \", and will go first next hand\\n\")\n input(\"hit enter to continue\")\n print('\\033c')\n return trick_winner\n\n\ndef play_hand(dealer):\n for i in players:\n i.hand = []\n i.display_hand = []\n trump_suit, trump_color, team_that_called = trump_chooser(dealer)\n print(team_that_called.name, \"called\", suits[trump_suit][0], \"\\n\")\n input(\"hit enter to continue\")\n print('\\033c')\n last_winner = None\n for i in range(5):\n if i == 0:\n last_winner = play_trick(dealer, last_winner, trump_suit, trump_color)\n elif i > 0:\n last_winner = play_trick(None, last_winner, trump_suit, trump_color)\n last_winner.team.handScore += 1\n for i in teams:\n if i.handScore >= 3:\n print(i.name, \"won this hand. the next dealer is \", players[players.index(dealer) + 1].name, \"(\" + players[players.index(dealer) + 1].team.name + \")\")\n # I'm sorry about commas and +'s in the same statement. It's to get rid of the spaces with the ('s\n i.points += 1\n if i.handScore == 5:\n i.points += 1\n if i != team_that_called:\n i.points += 1\n # figure out going alone?\n i.handScore = 0\n print(\"your Team has\", user_team.points, \"points\")\n print(\"the other Team has\", other_team.points, \"points\")\n input(\"hit Enter to continue\")\n print('\\033c')\n new_dealer = players[players.index(dealer) + 1]\n return new_dealer\n\n\ndef play_game():\n for i in range(20):\n dealer = random.choice(players)\n play_hand(dealer)\n for x in teams:\n if x.points >= 5:\n print(x.name, \"won, would you like to play again? Y/N\")\n play_again = input().lower()\n while True:\n if play_again == \"y\" or play_again == \"n\":\n user_team = Team(\"your team\", user, cross_player)\n other_team = Team(\"the other team\", left_player, right_player)\n break\n print(\"please either type 'y' or 'n'\")\n if play_again == \"y\":\n play_game()\n else:\n quit()\n\n\nplay_game()\n\n","sub_path":"Euchre.py","file_name":"Euchre.py","file_ext":"py","file_size_in_byte":16800,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"451817476","text":"import pygame\n\npygame.init()\n\ndisplay_width = 800\ndisplay_height = 600\n\nblack = (0, 0, 0)\nwhite = (255, 255, 255)\nred = (255, 0, 0)\ngreen = (0, 255, 0)\nblue = (0, 0, 255)\n\ngameDisplay = pygame.display.set_mode((display_width, display_height))\npygame.display.set_caption('Sneaky Santa')\nclock = pygame.time.Clock()\n\nsantaImg = pygame.image.load('santa.png')\n\ndef santa(x,y):\n gameDisplay.blit(santaImg, (x,y))\n\n\n\n\n\ndef game_loop():\n\n \n x = (display_width * 0.5)\n y = (display_height * 0.5)\n\n x_change = 0\n y_change = 0\n\n\n gameExit = False\n\n while not gameExit:\n \n for event in pygame.event.get():\n \n if event.type == pygame.QUIT:\n gameExit = True\n \n if event.type == pygame.KEYDOWN:\n if event.key == pygame.K_LEFT:\n x_change = -5\n \n if event.key == pygame.K_RIGHT:\n x_change = 5\n\n if event.key == pygame.K_UP:\n y_change = -5\n\n if event.key == pygame.K_DOWN:\n y_change = 5\n \n if event.type == pygame.KEYUP:\n if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT:\n x_change = 0\n\n if event.key == pygame.K_UP or event.key == pygame.K_DOWN:\n y_change = 0\n\n\n x += x_change\n y += y_change\n \n gameDisplay.fill(white) \n santa(x,y) \n pygame.display.update()\n\n clock.tick(60)\n\ngame_loop()\npygame.quit()\nquit()\n \n","sub_path":"sneaky_santa.py","file_name":"sneaky_santa.py","file_ext":"py","file_size_in_byte":1632,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"264002354","text":"import numpy as np\r\nimport os.path\r\nimport data_utils\r\nimport matplotlib.pyplot as plt\r\nimport matplotlib.cm as colormap\r\nimport cv2\r\nfrom mpl_toolkits.mplot3d import Axes3D\r\nimport torch\r\nimport torch.nn as nn\r\nimport torch.optim as optim\r\nimport torch.utils.data\r\nimport torch.nn.functional as F\r\nfrom sklearn.cluster import SpectralClustering, KMeans\r\nfrom autoencoder_mod import autoencoder\r\n\"\"\"\r\nNicolas Castano \r\nLast revision: 6/17/18\r\n\r\nRun k-means cluster off of autoencoded data. Indicate model_name and adjust\r\npath in model_file\r\n\r\n\"\"\"\r\n# will we be using GPUs?\r\nUSE_GPU = False\r\nif USE_GPU and torch.cuda.is_available(): device = torch.device('cuda')\r\nelse: device = torch.device('cpu')\r\n# float values used\r\ndtype = torch.float32\r\n\r\ndef encode_data(loader, model,ret_n_params=3):\r\n # set model to evaluation mode\r\n model.eval()\r\n dims = np.empty((0,ret_n_params), float) \r\n classes = np.empty((0,1), int) \r\n index = 0\r\n with torch.no_grad():\r\n for X, y in loader:\r\n # move to device, e.g. GPU or CPU\r\n X = X.to(device=device, dtype=dtype) \r\n y = y.to(device=device, dtype=torch.long)\r\n # cv2.imshow('decoded im',model.get_decoded_im(X))\r\n # cv2.waitKey(1000)\r\n encoded = model.encode_to_n_dims(X,n=ret_n_params)[0]\r\n dims = np.append(dims, [np.array(encoded)],axis=0)\r\n classes = np.append(classes, [[np.array(y)[0][0]]], axis=0)\r\n index += 1\r\n if index % 20 == 0: print('encoding dataset', index)\r\n return (dims,classes)\r\n\r\nmodel_name = 'auto_encode_v4'\r\nmodel_file = 'C:/Users/nicas/Documents/CS231N-ConvNNImageRecognition/' + \\\r\n 'Project/' + model_name + '.pt'\r\n\r\n# to avoid memory problems partition data calls and loop over frame ranges\r\ndef chunks(l, n):\r\n \"\"\"yield successive n-sized chunks from l\"\"\"\r\n for i in range(0, len(l), n):\r\n yield l[i:i + n]\r\n\r\nprint('loading existing model...')\r\nmy_model = torch.load(model_file)\r\nencoded_vals = []\r\n\r\nn_params = 50\r\n\r\ndata = np.empty((0,n_params), float)\r\ndata_3d = np.empty((0,3), float)\r\nclasses = np.empty((0,1), int)\r\n\r\nclass_names = ['no break', 'break'] # 0 is no break and 1 is break\r\nframe_range = list(range(0,56,4))\r\nnum_classes = len(class_names)\r\npart_frame_range = list(chunks(frame_range,2))\r\nfor i, sub_range in enumerate(part_frame_range):\r\n print()\r\n print('PULLING PARTITION %d OF %d' % (i,len(part_frame_range)-1))\r\n num_train = 34*len(sub_range) # 3400\r\n num_val = 2*len(sub_range) # 200\r\n num_test = 10*len(sub_range) # 188\r\n (X_train, y_train,\r\n X_val, y_val, X_test, y_test) = \\\r\n data_utils.get_data(frame_range=sub_range,\r\n num_train=num_train,\r\n num_validation=num_val,\r\n num_test=num_test,\r\n feature_list=None,\r\n reshape_frames=False,\r\n crop_at_constr=True,\r\n blur_im=True)\r\n \r\n # create tesor objects, normalize and zero center and pass into data \r\n #loaders\r\n # hardcoded means and standard deviation of pixel values\r\n #data\r\n X_train = torch.from_numpy(X_train)\r\n y_train = torch.from_numpy(y_train)\r\n X_val = torch.from_numpy(X_val)\r\n y_val = torch.from_numpy(y_val)\r\n X_test = torch.from_numpy(X_test)\r\n y_test = torch.from_numpy(y_test)\r\n\r\n \r\n X_all = torch.cat((X_train,X_val,X_test),0)\r\n y_all = torch.cat((y_train,y_val,y_test),0)\r\n all_data = torch.utils.data.TensorDataset(X_all, y_all)\r\n print('data shape: ', X_all.shape)\r\n print()\r\n loader_all_data = torch.utils.data.DataLoader(all_data, shuffle=False)\r\n # pull out encoded dims\r\n print('ENCODING TO %d PARAMS' % (n_params))\r\n params,out_classes = encode_data(loader_all_data,my_model,\r\n ret_n_params=n_params)\r\n print('ENCODING TO 3 PARAMS')\r\n params_3d,_ = encode_data(loader_all_data,my_model,\r\n ret_n_params=3)\r\n data = np.append(data,params,axis=0)\r\n classes = np.append(classes,out_classes)\r\n# print(len(classes),np.count_nonzero(classes),len(classes)-np.count_nonzero(classes))\r\n data_3d = np.append(data_3d,params_3d,axis=0)\r\n \r\n \r\n# zero center and normalize\r\nmeans = np.mean(data, axis=0)\r\nsd = np.std(data, axis=0)\r\ndata = (data - means) / sd\r\n\r\nmeans_3d = np.mean(data_3d, axis=0)\r\nsd_3d = np.std(data_3d, axis=0)\r\ndata_3d = (data_3d - means_3d) / sd_3d\r\n\r\n \r\n# CLUSTER\r\nN_CLUSTER = 2\r\nspecCluster = SpectralClustering(n_clusters=N_CLUSTER, random_state=1, \r\n n_init=30)\r\nspecLabels = specCluster.fit_predict(data)\r\n\r\nkMeansCluster = KMeans(n_clusters=N_CLUSTER, random_state=1, n_init=30)\r\nkMeansLabels = kMeansCluster.fit_predict(data)\r\n\r\nu_labels_spec = np.unique(specLabels)\r\nu_labels_kMeans = np.unique(kMeansLabels)\r\nprint(u_labels_spec)\r\nprint(u_labels_kMeans)\r\n\r\nplt.close('all')\r\n\r\n# break and no break color maps\r\ncmap_break = colormap.get_cmap('winter')\r\ncmap_nobreak = colormap.get_cmap('autumn')\r\nbreak_colors = []\r\nnobreak_colors = []\r\nfor c in np.arange(1,N_CLUSTER+1):\r\n pull_color = float(c/N_CLUSTER)\r\n break_colors.append(cmap_break(pull_color))\r\n nobreak_colors.append(cmap_nobreak(pull_color))\r\n \r\n\r\nfig2D_spec = plt.figure('2D_spec')\r\nfig2D_kMeans = plt.figure('2D_kMeans')\r\nfig3D_spec = plt.figure('3D_spec')\r\nax_spec = fig3D_spec.add_subplot(111, projection='3d')\r\nfig3D_kMeans = plt.figure('3D_kMeans')\r\nax_kMeans = fig3D_kMeans.add_subplot(111, projection='3d')\r\n\r\nmy_clusters = []\r\n\r\nfor cluster in np.arange(N_CLUSTER):\r\n my_clusters.append('cluster ' + str(cluster))\r\n # plot spectral clusters with o markers for no break and * for break\r\n rows_spec = [d == u_labels_spec[cluster] for d in specLabels]\r\n x = data_3d[rows_spec, 0]\r\n y = data_3d[rows_spec, 1]\r\n z = data_3d[rows_spec, 2]\r\n c = classes[rows_spec]\r\n x_nobreak, y_nobreak, z_nobreak = [], [], []\r\n x_break, y_break, z_break = [], [], []\r\n for (i,x,y,z) in zip(c,x,y,z):\r\n if classes[i] == 1:\r\n x_nobreak.append(x)\r\n y_nobreak.append(y)\r\n z_nobreak.append(z)\r\n elif classes[i] == 0:\r\n x_break.append(x)\r\n y_break.append(y)\r\n z_break.append(z)\r\n plt.figure('2D_spec')\r\n plt.scatter(x_nobreak, y_nobreak, \r\n marker='o', color=nobreak_colors[cluster])\r\n plt.scatter(x_break, y_break, \r\n marker='*', color=break_colors[cluster])\r\n \r\n plt.figure('3D_spec')\r\n ax_spec.scatter(x_nobreak, y_nobreak, z_nobreak, \r\n marker='o', color=nobreak_colors[cluster])\r\n ax_spec.scatter(x_break, y_break, z_break, \r\n marker='*',color=break_colors[cluster])\r\n \r\n # plot k means clusters\r\n rows_kMeans = [d == u_labels_kMeans[cluster] for d in kMeansLabels]\r\n x = data_3d[rows_kMeans, 0]\r\n y = data_3d[rows_kMeans, 1]\r\n z = data_3d[rows_kMeans, 2]\r\n c = classes[rows_kMeans]\r\n x_nobreak, y_nobreak, z_nobreak = [], [], []\r\n x_break, y_break, z_break = [], [], []\r\n for (i,x,y,z) in zip(c,x,y,z):\r\n if classes[i] == 1:\r\n x_nobreak.append(x)\r\n y_nobreak.append(y)\r\n z_nobreak.append(z)\r\n elif classes[i] == 0:\r\n x_break.append(x)\r\n y_break.append(y)\r\n z_break.append(z)\r\n plt.figure('2D_kMeans')\r\n plt.scatter(x_nobreak, y_nobreak, \r\n marker='o', color=nobreak_colors[cluster])\r\n plt.scatter(x_break, y_break,\r\n marker='*', color=break_colors[cluster])\r\n \r\n plt.figure('3D_kMeans')\r\n ax_kMeans.scatter(x_nobreak, y_nobreak, z_nobreak, \r\n marker='o', color=nobreak_colors[cluster])\r\n ax_kMeans.scatter(x_break, y_break, z_break, \r\n marker='*', color=break_colors[cluster])\r\n\r\n\r\nplt.figure('2D_spec')\r\nplt.legend(my_clusters, fontsize=18)\r\nplt.xlabel('dimension 1', fontsize=18)\r\nplt.ylabel('dimension 2', fontsize=18)\r\nplt.title('2D spectral clustering', fontsize=22)\r\n\r\nplt.figure('2D_kMeans')\r\nplt.legend(my_clusters, fontsize=18)\r\nplt.xlabel('dimension 1', fontsize=18)\r\nplt.ylabel('dimension 2', fontsize=18)\r\nplt.title('2D k-means clustering', fontsize=22)\r\n\r\nplt.figure('3D_spec')\r\nax_spec.set_xlabel('dimension 1')\r\nax_spec.set_ylabel('dimension 2')\r\nax_spec.set_ylabel('dimension 3')\r\nax_spec.set_title('2D spectral clustering')\r\n\r\nplt.figure('3D_kMeans')\r\nax_kMeans.set_xlabel('dimension 1')\r\nax_kMeans.set_ylabel('dimension 2')\r\nax_kMeans.set_ylabel('dimension 3')\r\nax_kMeans.set_title('2D k-means clustering')\r\n\r\n","sub_path":"MachineLearning/k_means_cluster_autoencoder_data.py","file_name":"k_means_cluster_autoencoder_data.py","file_ext":"py","file_size_in_byte":8776,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"238534513","text":"import dj_database_url\nimport django_on_heroku\nfrom .production import *\n\n\nALLOWED_HOSTS.append('.herokuapp.com')\n\n\nif os.environ.get('DEBUG'):\n DEBUG=True\n\n\n## Installed apps\nINSTALLED_APPS.append('whitenoise.runserver_nostatic')\n\n\n## Middlewares\ntemp = ['whitenoise.middleware.WhiteNoiseMiddleware']\nfor i in range(len(MIDDLEWARE)):\n temp.append(MIDDLEWARE[i])\nMIDDLEWARE = temp\n\n\nWSGI_APPLICATION = 'RobotixWeb.wsgi.application'\n\n\n# Database\nif os.environ.get('DEBUG'):\n DATABASES = {\n 'default': {\n 'ENGINE': 'django.db.backends.postgresql',\n 'NAME': os.environ.get('POSTGRES_DB'),\n 'USER': os.environ.get('POSTGRES_USER'),\n 'PASSWORD' :os.environ.get('POSTGRES_PASSWORD'),\n 'HOST' : os.environ.get('POSTGRES_HOST'),\n 'PORT' : os.environ.get('POSTGRES_PORT')\n }\n }\nelse:\n db_from_env = dj_database_url.config(conn_max_age=500)\n DATABASES['default'].update(db_from_env)\n WHITENOISE_USE_FINDERS = True\n STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage'\n\n","sub_path":"RobotixWeb/settings.py","file_name":"settings.py","file_ext":"py","file_size_in_byte":1090,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"629594521","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Jan 10 15:37:22 2018\n\n@author: charlie\n\"\"\"\n### Plot \n\nimport numpy as np\nimport pandas as pd \nimport matplotlib.pyplot as plt\n \nN = [100, 1000]\nmax_inter = np.zeros( 2 )\nmax_error = np.zeros( 2 )\n\nline_color = ['r', 'b']\ntitle_file = 'data_N_'\n\nfig, ax = plt.subplots(2, sharex = True)\nplt.xlabel('x')\nplt.ion()\n\n\ndef Plot_Get_error(N_in):\n flag = int(np.log10(N_in)-2)\n df = pd.read_csv(title_file + str(N_in) + '.csv', sep = ',', header = None, error_bad_lines=False)\n data = df.values[1:, 1:]\n \n error = data[3, 1:]\n inter = data[0, 1:] - data[0, 0:-1]\n error_norm = error**2\n error_norm_l0 = error_norm.dot(inter.T)\n ax[0].plot(np.log10(data[0, :]), np.log10(data[1, :]), line_color[flag] + '--', label = 'Numerical N = ' + str(N_in))\n ax[0].plot(np.log10(data[0, :]), np.log10(data[2, :]), line_color[flag] + '-', label = 'Theoretical N = ' + str(N_in))\n ax[1].plot(np.log10(data[0, :]), np.log10(data[3, :]), line_color[flag], label = 'Approxi Errors N = ' + str(N_in))\n max_interval = max( inter )\n# max_error \t = max( error )\n return max_interval, error_norm_l0\n \nmax_inter[0], max_error[0] = Plot_Get_error(N[0])\nmax_inter[1], max_error[1] = Plot_Get_error(N[1])\n\nax[0].legend(loc = 'best')\nax[1].legend(loc = 'best')\nax[0].set_ylabel('$u(x)$')\nax[1].set_ylabel('$e(x)$')\nfig.text(0.5, 1, '$u(x)$ and $e(x)$ under Different grids', \\\n verticalalignment = 'top', \\\n horizontalalignment = 'center', fontsize=16)\n#\n#fig.savefig('u_x_e_x_2_grids.png', format = 'png')\n\nplt.figure()\nplt.plot(np.log10(max_inter), np.log10(max_error))\nplt.ylabel('$log_{10} (||e(x)||_{0, \\Omega})$')\nplt.xlabel('$log_{10} (h) $ ')\nplt.title( '$log_{10} (h) - log_{10} (||e(x)||_{0, \\Omega})$' )\nplt.savefig('log-log.png', format = 'png')\n\n#n_in = 1000\n#df = pd.read_csv(title_file + str(n_in) + '.csv', sep = ',', header = None, error_bad_lines=False)\n#data = df.values[1:, 1:]\n#plt.figure()\n#plt.plot(data[0, :], data[3, :] )\n#plt.xlabel('$x$')\n#plt.ylabel('$e(x)$')\n#plt.title('Approxi Errors N = ' + str(n_in))\n#plt.savefig('Approximation_errors_N_' + str(n_in) + '.png', format = 'png')\n","sub_path":"1D_FEM_Poisson/Charlie_HW7_MPDE_plot_log_log_new.py","file_name":"Charlie_HW7_MPDE_plot_log_log_new.py","file_ext":"py","file_size_in_byte":2183,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"290360739","text":"\"\"\"\n{This script carries out HAM and SHAM using baryonic and stellar masses of \n groups and individual galaxies and compares to the values from RESOLVE A}\n\"\"\"\n\n# Libs\nfrom cosmo_utils.utils.stats_funcs import Stats_one_arr\nfrom Corrfunc.utils import convert_rp_pi_counts_to_wp\nfrom Corrfunc.mocks.DDrppi_mocks import DDrppi_mocks\nfrom cosmo_utils.utils import work_paths as cwpaths\nfrom progressbar import ProgressBar\nimport matplotlib.pyplot as plt\nfrom scipy import interpolate\nfrom matplotlib import rc\nfrom numpy import random\nimport pandas as pd\nimport numpy as np\nimport math\n\n__author__ = '{Mehnaaz Asad}'\n\ndef num_bins(data_arr):\n q75, q25 = np.percentile(data_arr, [75 ,25])\n iqr = q75 - q25\n num_points = len(data_arr)\n h =2*iqr*(num_points**(-1/3))\n n_bins = math.ceil((max(data_arr)-min(data_arr))/h) #Round up number \n return n_bins\n\ndef cumu_num_dens(data,bins,weights,volume,bool_mag):\n if weights is None:\n weights = np.ones(len(data))\n else:\n weights = np.array(weights)\n #Unnormalized histogram and bin edges\n freq,edg = np.histogram(data,bins=bins,weights=weights)\n bin_centers = 0.5*(edg[1:]+edg[:-1])\n bin_width = edg[1] - edg[0]\n if not bool_mag:\n N_cumu = np.cumsum(freq[::-1])[::-1] \n else:\n N_cumu = np.cumsum(freq)\n n_cumu = N_cumu/volume\n err_poiss = np.sqrt(N_cumu)/volume\n return bin_centers,edg,n_cumu,err_poiss,bin_width\n\n# Paths\ndict_of_paths = cwpaths.cookiecutter_paths()\npath_to_raw = dict_of_paths['raw_dir']\npath_to_interim = dict_of_paths['int_dir']\npath_to_figures = dict_of_paths['plot_dir']\n\nrc('font',**{'family':'sans-serif','sans-serif':['Helvetica']},size=18)\nrc('text', usetex=True)\n\ncolumns = ['name','radeg','dedeg','cz','grpcz','logmstar','logmgas','grp',\\\n 'grpn','logmh','logmh_s','fc','grpmb','grpms','f_a','f_b',\\\n 'grpabsrmag','absrmag']\n\n# 2286 galaxies\nresolve_live18 = pd.read_csv(path_to_raw + \"RESOLVE_liveJune2018.csv\", \\\n delimiter=\",\", header=0, usecols=columns)\n\ngrps = resolve_live18.groupby('grp') #group by group ID\ngrp_keys = grps.groups.keys()\n\n# Isolating groups that don't have designated central\ngrp_id_no_central_arr = []\nfor key in grp_keys:\n group = grps.get_group(key)\n if 1 not in group.fc.values:\n grp_id = group.grp.values\n grp_id_no_central_arr.append(np.unique(grp_id)[0])\n\nresolve_live18 = resolve_live18.loc[~resolve_live18['grp'].\\\n isin(grp_id_no_central_arr)]\n\n#633 galaxies\nra_nobuff = resolve_live18.loc[(resolve_live18.grpcz.values >= 4500) & \\\n (resolve_live18.grpcz.values <= 7000) & \\\n (resolve_live18.absrmag.values <= -17.33) &\\\n (resolve_live18.logmstar.values >= 8.9) &\\\n (resolve_live18.f_a.values == 1)]\n\ncolumns = ['name', 'radeg', 'dedeg', 'cz', 'grpcz', 'grpabsrmag', 'absrmag', \n 'logmstar', 'logmgas', 'grp', 'grpn', 'logmh', 'logmh_s', \n 'fc', 'grpmb', 'grpms']\n\n# 13878 galaxies\neco_buff = pd.read_csv(path_to_raw+'eco_all.csv',delimiter=\",\", header=0, \\\n usecols=columns)\n\neco_nobuff = eco_buff.loc[(eco_buff.grpcz.values >= 3000) & \\\n (eco_buff.grpcz.values <= 7000) & (eco_buff.absrmag.values <= -17.33) & \\\n (eco_buff.logmstar.values >= 8.9)]\n\ngrps = eco_nobuff.groupby('grp') #group by group ID\ngrp_keys = grps.groups.keys()\n\n# Isolating groups that don't have designated central\ngrp_id_no_central_arr = []\nfor key in grp_keys:\n group = grps.get_group(key)\n if 1 not in group.fc.values:\n grp_id = group.grp.values\n grp_id_no_central_arr.append(np.unique(grp_id)[0])\n\neco_nobuff = eco_nobuff.loc[~eco_nobuff['grp'].isin(grp_id_no_central_arr)]\n#################################### (HAM) ################################\ngrps = eco_nobuff.groupby('grp') \ngrp_keys = grps.groups.keys()\n\n# Get integrated baryonic and stellar mass and have one entry per group\ngrpmb_arr = np.zeros(len(grp_keys))\ngrpms_arr = np.zeros(len(grp_keys))\nlogmh_s_arr = np.zeros(len(grp_keys))\nlogmh_arr = np.zeros(len(grp_keys))\ngrprmag_arr = np.zeros(len(grp_keys))\ncenmstar_arr = np.zeros(len(grp_keys))\nra_arr = np.zeros(len(grp_keys))\ndec_arr = np.zeros(len(grp_keys))\ncz_arr = np.zeros(len(grp_keys))\nfor idx,key in enumerate(grp_keys):\n group = grps.get_group(key)\n grpmb = np.unique(group.grpmb.values)[0]\n grpms = np.unique(group.grpms.values)[0]\n logmh_s = np.unique(group.logmh_s.values)[0] # same number for all\n logmh = np.unique(group.logmh.values)[0] # same number for all\n grprmag = np.unique(group.grpabsrmag.values)[0]\n cenmstar = group.logmstar.loc[group.fc.values == 1].values[0]\n ra = group.radeg.loc[group.fc.values == 1].values[0] # central\n dec = group.dedeg.loc[group.fc.values == 1].values[0] # central\n cz = np.unique(group.grpcz.values)[0]\n grpms_arr[idx] = grpms\n grpmb_arr[idx] = grpmb\n logmh_s_arr[idx] = logmh_s\n logmh_arr[idx] = logmh\n grprmag_arr[idx] = grprmag\n cenmstar_arr[idx] = cenmstar\n ra_arr[idx] = ra\n dec_arr[idx] = dec\n cz_arr[idx] = cz\n\n# Create cumulative baryonic and stellar mass functions\nbins_sm = np.linspace(8.9, 12.2, 12)\nbins_bm = np.linspace(9.4, 12.2, 12)\nv_resolve_a = 13172.384 * 2.915 # Survey volume without buffer [Mpc/h]^3 h=0.7\nv_eco = 151829.26 * 2.915\nbin_centers_grpmb,bin_edges_grpmb,n_grpmb,err_poiss_grpmb,bin_width_grpmb = \\\n cumu_num_dens(grpmb_arr,bins_bm,None,v_eco,False)\nbin_centers_grpms,bin_edges_grpms,n_grpms,err_poiss_grpms,bin_width_grpms = \\\n cumu_num_dens(grpms_arr,bins_sm,None,v_eco,False)\n\n# Load halo catalog\nhalo_table = pd.read_csv(path_to_interim + 'id_macc.csv',header=0)\nv_sim = 130**3 * 2.915 # Vishnu simulation volume (Mpc/h)^3 h=0.7\n\n# Use only host halos for HAM (PID and UPID of -1) with masses in h=0.7\nhalo_mass_hh = halo_table.halo_macc.loc[halo_table.C_S.values==1] * 1.429 \n\n# Create HMF\nbins = num_bins(halo_mass_hh)\nbin_centers_hmass,bin_edges_hmass,n_hmass,err_poiss_hmass,\\\n bin_width_hmass = cumu_num_dens(halo_mass_hh,bins,None,v_sim,False)\n\n# Interpolating between grpmb and n\ngrpmb_n_interp_func = interpolate.interp1d(bin_centers_grpmb,n_grpmb,\\\n fill_value='extrapolate')\n\n# Interpolating between grpmstar and n\ngrpms_n_interp_func = interpolate.interp1d(bin_centers_grpms,n_grpms,\\\n fill_value='extrapolate')\n\n# Interpolating between central hmass and n and reversing it so you can pass \n# an n and get central hmass value\nhmass_n_interp_func = interpolate.interp1d(n_hmass,bin_centers_hmass, \\\n fill_value='extrapolate')\n\npbar = ProgressBar(maxval=len(grpmb_arr))\nn_grpmb_arr = [grpmb_n_interp_func(val) for val in pbar(grpmb_arr)]\npbar = ProgressBar(maxval=len(n_grpmb_arr))\nhmass_grpmb_ham = [hmass_n_interp_func(val) for val in pbar(n_grpmb_arr)]\n\npbar = ProgressBar(maxval=len(grpms_arr))\nn_grpms_arr = [grpms_n_interp_func(val) for val in pbar(grpms_arr)]\npbar = ProgressBar(maxval=len(n_grpms_arr))\nhmass_grpms_ham = [hmass_n_interp_func(val) for val in pbar(n_grpms_arr)]\n\n### Convert to log\nhmass_loggrpmb = np.log10(hmass_grpmb_ham)\nhmass_loggrpms = np.log10(hmass_grpms_ham)\n\ndf_halomasses = {'baryonic': hmass_loggrpmb, 'stellar': hmass_loggrpms, 'absmag': logmh_arr,\n'resolve_stellar': logmh_s_arr}\ndf_halomasses = pd.DataFrame(data=df_halomasses)\n\n### Get error bars\nx_grpmb,y_grpmb,y_std_grpmb,y_std_err_grpmb = Stats_one_arr(hmass_loggrpmb,\\\n cenmstar_arr,base=0.3)\n\nx_grpms,y_grpms,y_std_grpms,y_std_err_grpms = Stats_one_arr(hmass_loggrpms,\\\n cenmstar_arr,base=0.3)\n\nx_mhs,y_mhs,y_std_mhs,y_std_err_mhs = Stats_one_arr(logmh_s_arr,cenmstar_arr,\\\n base=0.3)\n\nx_mh,y_mh,y_std_mh,y_std_err_mh = Stats_one_arr(logmh_arr,cenmstar_arr,base=0.3)\n\ny_std_err_grpmb = np.sqrt(y_std_err_grpmb**2 + (0.30**2))\ny_std_err_grpms = np.sqrt(y_std_err_grpms**2 + (0.30**2))\ny_std_err_mhs = np.sqrt(y_std_err_mhs**2 + (0.30**2))\ny_std_err_mh = np.sqrt((y_std_err_mh**2) + (0.30**2))\n\nfig1 = plt.figure(figsize=(10,10))\nplt.errorbar(x_grpmb,y_grpmb,yerr=y_std_err_grpmb,\\\n color='#1baeab',fmt='--s',ecolor='#1baeab',markersize=4,capsize=5,\\\n capthick=0.5,label=r'$M_{bary,grp}$')\nplt.errorbar(x_grpms,y_grpms,yerr=y_std_err_grpms,\\\n color='#f6a631',fmt='--s',ecolor='#f6a631',markersize=4,capsize=5,\\\n capthick=0.5,label=r'$M_{\\star ,grp}$')\nplt.errorbar(x_mhs,y_mhs,yerr=y_std_err_mhs,\\\n color='#a0298d',fmt='--s',ecolor='#a0298d',markersize=4,capsize=5,\\\n capthick=0.5,label=r'RESOLVE stellar mass derived')\nplt.errorbar(x_mh,y_mh,yerr=y_std_err_mh,\\\n color='k',fmt='--s',ecolor='k',markersize=4,capsize=5,\\\n capthick=0.5,label=r'RESOLVE r-band mag derived')\n\nplt.xlabel(r'\\boldmath$\\log\\ M_h \\left[M_\\odot \\right]$')\nplt.ylabel(r'\\boldmath$\\log\\ M_{\\star,c} \\left[M_\\odot \\right]$')\nplt.legend(loc='best',prop={'size': 10})\nplt.show()\n\n################################### Corrfunc ###################################\ndict_corrfunc = {'RA':ra_arr, 'DEC':dec_arr, 'grpcz':cz_arr, \\\n 'logmh_s':logmh_s_arr, 'logmh':logmh_arr, 'logmh_grpmb':hmass_loggrpmb, \\\n 'logmh_grpms':hmass_loggrpms}\ndf_corrfunc = pd.DataFrame(dict_corrfunc)\n\nidx = int(10/100*(len(df_corrfunc)))\ndf_corrfunc = df_corrfunc.sort_values('logmh', ascending=False)\nlogmh_high10 = df_corrfunc[:idx]\nlogmh_low10 = df_corrfunc[-idx:]\ndf_corrfunc = df_corrfunc.sort_values('logmh_s', ascending=False)\nlogmhs_high10 = df_corrfunc[:idx]\nlogmhs_low10 = df_corrfunc[-idx:]\ndf_corrfunc = df_corrfunc.sort_values('logmh_grpmb', ascending=False)\nlogmhgrpb_high10 = df_corrfunc[:idx]\nlogmhgrpb_low10 = df_corrfunc[-idx:]\ndf_corrfunc = df_corrfunc.sort_values('logmh_grpms', ascending=False)\nlogmhgrps_high10 = df_corrfunc[:idx]\nlogmhgrps_low10 = df_corrfunc[-idx:]\n\n# Real galaxies\nRA = logmhs_high10.RA.values\nDEC = logmhs_high10.DEC.values\nCZ = logmhs_high10.grpcz.values\nN = len(RA)\nweights = np.ones_like(RA)\n\n# Random points\nrand_num = ra_nobuff.size*5\nrand_RA = np.round(random.uniform(ra_nobuff.radeg.min(),ra_nobuff.radeg.max(),\\\n rand_num), 5)\nrand_DEC = np.round(random.uniform(ra_nobuff.dedeg.min(),ra_nobuff.dedeg.max(),\\\n rand_num), 7)\nrand_CZ = np.round(random.uniform(ra_nobuff.grpcz.min(),ra_nobuff.grpcz.max(),\\\n rand_num), 1)\nrand_N = len(rand_RA)\nrand_weights = np.ones_like(rand_RA)\n\nnbins = 10\nbins = np.logspace(np.log10(0.1), np.log10(20.0), nbins + 1)\ncosmology = 2 # Planck\nnthreads = 2\npimax = 25.0\n\n# Auto pair counts in DD\nautocorr = 1\nDD_counts = DDrppi_mocks(autocorr, cosmology, nthreads, pimax, bins, RA, \\\n DEC, CZ, weights1=weights, weight_type='pair_product')\n\n# Auto pair counts in RR\nRR_counts = DDrppi_mocks(autocorr, cosmology, nthreads, pimax, bins, rand_RA, \\\n rand_DEC, rand_CZ, weights1=rand_weights, weight_type='pair_product')\n\n# Cross pair counts in DR\nautocorr=0\nDR_counts = DDrppi_mocks(autocorr, cosmology, nthreads, pimax, bins, RA, DEC, \\\n CZ, RA2=rand_RA, DEC2=rand_DEC, CZ2=rand_CZ, weights1=weights, \\\n weights2=rand_weights, weight_type='pair_product')\n\nwp = convert_rp_pi_counts_to_wp(N, N, rand_N, rand_N, DD_counts, DR_counts, \\\n DR_counts, RR_counts, nbins, pimax)\n\n\"\"\"\nfracdiff_bary_arr = np.zeros(460)\nfor idx,predicted in enumerate(halomass_df.baryonic.values):\n truth = halomass_df.resolve_stellar.values[idx]\n fracdiff_bary = 100*((predicted/truth)-1)\n fracdiff_bary_arr[idx] = fracdiff_bary\n\nfracdiff_stellar_arr = np.zeros(460)\nfor idx,predicted in enumerate(halomass_df.stellar.values):\n truth = halomass_df.resolve_stellar.values[idx]\n fracdiff_stellar = 100*((predicted/truth)-1)\n fracdiff_stellar_arr[idx] = fracdiff_stellar\n\nfracdiff_absmag_arr = np.zeros(460)\nfor idx,predicted in enumerate(halomass_df.absmag.values):\n truth = halomass_df.resolve_stellar.values[idx]\n fracdiff_absmag = 100*((predicted/truth)-1)\n fracdiff_absmag_arr[idx] = fracdiff_absmag\n\nfracdiff_rstellar_arr = np.zeros(460)\nfor idx,predicted in enumerate(halomass_df.resolve_stellar.values):\n truth = halomass_df.resolve_stellar.values[idx]\n fracdiff_rstellar = 100*((predicted/truth)-1)\n fracdiff_rstellar_arr[idx] = fracdiff_rstellar\n\n\n### Use stats_one_arr with true halo mass and fractional difference\nx_grpmb,y_grpmb,y_std_grpmb,y_std_err_grpmb = Stats_one_arr(hmass_loggrpmb,\\\n fracdiff_bary_arr,base=0.3,bin_statval='left')\nx_grpms,y_grpms,y_std_grpms,y_std_err_grpms = Stats_one_arr(hmass_loggrpms,\\\n fracdiff_stellar_arr,base=0.3,bin_statval='left')\nx_grpabsmag,y_grpabsmag,y_std_grpabsmag,y_std_err_grpabsmag = Stats_one_arr(logmh_arr,\\\n fracdiff_absmag_arr,base=0.3,bin_statval='left')\nx_grprs,y_grprs,y_std_grprs,y_std_err_grprs = Stats_one_arr(logmh_s_arr,\\\n fracdiff_rstellar_arr,base=0.3,bin_statval='left')\n\nfig1 = plt.figure(figsize=(10,10))\nplt.errorbar(x_grpmb,y_grpmb,yerr=y_std_err_grpmb,\\\n color='#1baeab',fmt='--s',ecolor='#1baeab',markersize=4,capsize=5,\\\n capthick=0.5,label=r'$M_{bary,grp}$')\nplt.errorbar(x_grpms,y_grpms,yerr=y_std_err_grpms,\\\n color='#f6a631',fmt='--s',ecolor='#f6a631',markersize=4,capsize=5,\\\n capthick=0.5,label=r'$M_{\\star ,grp}$')\nplt.errorbar(x_grpabsmag,y_grpabsmag,yerr=y_std_err_grpabsmag,\\\n color='#a0298d',fmt='--s',ecolor='#a0298d',markersize=4,capsize=5,\\\n capthick=0.5,label=r'RESOLVE r-band mag derived')\nplt.errorbar(x_grprs,y_grprs,yerr=y_std_err_grprs,\\\n color='k',fmt='--s',ecolor='k',markersize=4,capsize=5,\\\n capthick=0.5,label=r'RESOLVE stellar mass derived')\n\nplt.xlabel(r'\\boldmath$\\log\\ M_h \\left[M_\\odot \\right]$')\nplt.ylabel(r'Fractional difference')\nplt.legend(loc='best',prop={'size': 10})\nplt.show()\n\"\"\"","sub_path":"src/side_project/ham_sham_ra.py","file_name":"ham_sham_ra.py","file_ext":"py","file_size_in_byte":13534,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"524960982","text":"from pymysql.connections import Connection\nfrom pymysql.cursors import Cursor\nfrom utils.logger import Logger\n\nlogger = Logger.get_logger('bankdb')\n\n\ndef insert_branch(cursor: Cursor, bra_name: str, bra_city: str):\n query = \"\"\"\n insert into branch (bra_name, bra_city)\n values (%(bra_name)s, %(bra_city)s);\n \"\"\"\n cursor.execute(query, {'bra_name': bra_name, 'bra_city': bra_city})\n logger.info(f'insert branch {bra_name} in {bra_city}')\n\n","sub_path":"bankdb/branch.py","file_name":"branch.py","file_ext":"py","file_size_in_byte":464,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"2765136","text":"from django.contrib import admin\n\nfrom .models import Comment, Pin, Like, DeviceLocation, UserProfile\n\nadmin.site.register(Like)\nadmin.site.register(UserProfile)\nadmin.site.register(DeviceLocation)\n\n\n@admin.register(Comment)\nclass CommentAdmin(admin.ModelAdmin):\n list_display = ('id', 'pin', 'text', 'by_user')\n list_display_links = list_display\n readonly_fields = ('created_at',)\n\n\n@admin.register(Pin)\nclass PinAdmin(admin.ModelAdmin):\n list_display = ('id', 'pin_type', 'latitude', 'longitude', 'by_user')\n list_display_links = list_display\n readonly_fields = ('created_at',)\n","sub_path":"api/admin.py","file_name":"admin.py","file_ext":"py","file_size_in_byte":598,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"318972012","text":"from init import *\nimport math\nfrom bokeh.layouts import gridplot\nfrom bokeh.plotting import figure, show, output_file\nfrom bokeh.models import Legend\nfrom bokeh.models import Range1d\nimport numpy\nfrom compare_regions import *\ndic_id_name = {1: \"South Asia\", 2:\"Middle East & North Africa\", 3:\"Europe & Central Asia\",\n 4:\"Sub-Saharan Africa\", 5:\"Latin America & Caribbean\", 6:\"East Asia & Pacific\"}\n\ndef isNaN(num):\n return num != num\n\ndef food_data(country, item):\n food_data = {}\n data = pd_data.filter({'country_name':country, 'item_name':item})\n for index, row in data.iterrows():\n date = (row[\"month\"],row[\"year\"])\n if date in food_data.keys():\n food_data[date][0].append(row['price'])\n else:\n food_data[date] = [[row['price']],row['undernourishment']]\n for key, value in food_data.items():\n food_data[key][0] = sum(food_data[key][0])/ len(food_data[key][0])\n return food_data\n\n\ndef nodata_filter(data):\n newdata = {}\n for key,value in data.items():\n if value[1] != 'No Data' :\n newdata[key] = value\n return newdata\n\n\n\n# index is a tuple with your first index and second index of what you want to make a list of\n\n\ndef plot(plot, legend_names):\n plot.grid.grid_line_alpha=0.3\n plot.xaxis.axis_label = 'Date'\n plot.yaxis.axis_label = 'Price (usd)'\n legend = Legend(items=legend_names, location=(0, -30))\n plot.add_layout(legend, 'right')\n show(gridplot([[plot]], plot_width=1000, plot_height=600)) # open a browser\n\n\ndef plotundernourishment(plot, legend_names):\n plot.grid.grid_line_alpha=0.3\n plot.xaxis.axis_label = 'Datum'\n plot.yaxis.axis_label = 'Ondervoedingsindex'\n legend = Legend(items=legend_names, location=(0, -30))\n plot.add_layout(legend, 'right')\n\n show(gridplot([[plot]], sizing_mode='stretch_both')) # open a browser\n\ndef add_to_plot(plot,name, dates, values):\n return plot.line(datetime(dates), values, line_width = 2,color='#'+\"%06x\" % random.randint(0, 0xFFFFFF))\n\ndef add_to_plot_undernourish(plot, name, dates, values, color):\n return plot.line(datetimeyear(dates), values, line_width = 2, color=color)\n\n\ndef datetimeyear(dates):\n format = [str(x)+'-'+'01'+'-01' for x in dates]\n return np.array(format, dtype=np.datetime64)\n\ndef add_zero(x):\n if x < 10:\n return '0'+str(x)\n else:\n return str(x)\n\ndef get_most_product(country):\n products = pd_data.filter({'country_name':country})['item_name'].unique()\n for item in products:\n print(\"the coeff of \"+ item + \" is\")\n print(coeffmaker(country, item))\n\ndef sort_dates(dates):\n if dates == []: return []\n else:\n result = [dates[0]]\n del(dates[0])\n while dates != []:\n for i in range(len(result)):\n if dates[0][0][1] < result[i][0][1]:\n result.insert(i, dates[0])\n del(dates[0])\n break\n elif dates[0][0][1] == result[i][0][1]:\n if dates[0][0][0] < result[i][0][0]:\n result.insert(i, dates[0])\n del(dates[0])\n break\n if i == len(result) - 1:\n result.append(dates[0])\n del(dates[0])\n return result\n\ndef listconverter(dict1,index):\n outp = []\n for keys,values in dict1.items():\n outp.append((keys,(values[index])))\n return outp\n\ndef split_date_and_values(both):\n return [x[0] for x in both], [x[1] for x in both]\n\ndef country_product_plotter(country, item = None):\n if item == None:\n products = pd_data.filter({'country_name':country})['item_name'].unique()\n else:\n products = [item]\n plot1 = figure(x_axis_type=\"datetime\", title= 'Product Price '+ country)\n legend = []\n for item in products:\n itemdata = listconverter(nodata_filter(food_data(country,item)),0)\n sorteddates = sort_dates(itemdata)\n print(item)\n dates , data = split_date_and_values(sorteddates)\n legend.append((item,[add_to_plot(plot1,item +' ' + country,dates,data)]))\n plot(plot1,legend)\n\n# country_product_plotter(\"Guatemala\")\n\ndef checkEqual2(iterator):\n return len(set(iterator)) <= 1\n\n\ndef coeff_country_undernourish(country,limit):\n products = pd_data.filter({'country_name':country})['item_name'].unique()\n coeffs = {}\n counter = 0\n for item in products:\n data = nodata_filter(food_data(country,item))\n itemdata = listconverter(data,0)\n\n noudata = listconverter(data,1)\n dates, itemdata = split_date_and_values(itemdata)\n dates, noudata = split_date_and_values(noudata)\n itemdata = list(map(float,itemdata))\n noudata = list(map(float,noudata))\n if checkEqual2(noudata):\n coeffs[item] = 0\n elif len(itemdata) > limit:\n counter += 1\n coeffs[item] = np.corrcoef(itemdata,noudata)[0][1]\n return counter, coeffs\n\n\n# print(coeff_country_undernourish('Afghanistan', 0))\n\ndef undernourishmentlist(country):\n data = pd_data.filter({'country_name' : country})\n result = []\n for index, row in data.iterrows():\n if row['undernourishment'] != 'No Data':\n result.append(((row['month'],row[\"year\"]),row['undernourishment']))\n return list(set(result))\n\ndef undernourishmentplotter(country):\n plot1 = figure(x_axis_type=\"datetime\", title=country + 'undernourishment')\n legend = []\n data = undernourishmentlist(country)\n sorteddata = sort_dates(data)\n dates , data = split_date_and_values(sorteddata)\n legend.append(('name',[add_to_plot(plot1,'name',dates,data)]))\n plotundernourishment(plot1,legend)\n\ndef undernourishmentplotteryear(country):\n plot1 = figure(x_axis_type=\"datetime\", title=country + 'undernourishment')\n legend = []\n data = undernourishmentlist(country)\n sorteddata = sort_dates(data)\n dates , data = split_date_and_values(sorteddata)\n legend.append(('name',[add_to_plot_undernourish(plot1,'name',dates,data)]))\n plotundernourishment(plot1,legend)\n\n\ndef biggestcorrelator(limit):\n countries = pd_data['country_name'].unique()\n res = []\n fcounter = 0\n zerocounter = 0\n print(len(countries))\n for country in countries:\n print(country)\n counter, countrydict = coeff_country_undernourish(country,limit)\n fcounter += counter\n if counter == 0:\n zerocounter += 1\n for key, value in countrydict.items():\n res.append(((country,key),value))\n\n longenough = fcounter/len(countries)\n\n\n sortedlist = sorted(res,key=lambda x: x[1], reverse=True)\n\n ten = sortedlist[:10]\n for i in range(10):\n obj = ten[i]\n print(\"\" + str(obj[0][1]) + '' + str(obj[0][0]) + '' + str(obj[1]) + \"\")\n\n\nbiggestcorrelator(60)\n\ndef avgundernourishment(corrlist):\n cum = {}\n for corr in corrlist:\n if corr[0][1] in cum.keys():\n cum[corr[0][1]].append(corr[1])\n else:\n cum[corr[0][1]] = [corr[1]]\n print(cum)\n\n cumulative = []\n for key, value in cum.items():\n ans = numpy.count_nonzero(~np.isnan(value))\n cumulative.append((key,numpy.nansum(value)/(ans)))\n\n sortedcumulative = sorted(cumulative,key=lambda x: x[1], reverse=False)\n\n ten = sortedcumulative[:10]\n for i in range(10):\n obj = ten[i]\n print(str(obj[0]) + ',' + str(obj[1]))\n\n# avgundernourishment(biggestcorrelator(60))\n\n\n\n\ndef getundernourishment(country):\n result = []\n country = und_data.filter({\"Entity\":country})\n for index,row in country.iterrows():\n result.append((row['Year'],row['POU']))\n return result\n\ndef regionundernourishment():\n plot1 = figure(x_axis_type=\"datetime\", title='Ondervoedingsindex per regio', sizing_mode='stretch_both')\n legend = []\n regions = und_data[\"region\"].unique()\n colors = ['#511f8d', '#7eae2b', '#f308cf', '#7a0506', '#6a11cd', '#dfb3b4', '#c2531b', '#3683d0', '#43d7b1', '#c8bf13', '#2afa23', '#60a577', '#aad31d', '#09bdcd', '#d5fdad', '#1ea4a8', '#a7726d', '#4aecb5', '#7d0963', '#2f3d5a']\n i = 0\n for region in regions:\n print(region)\n if region == \"No Data\" or region == \"No Datastates \":\n continue\n #print(region)\n countries = und_data.filter({'region': region})[\"Entity\"].unique()\n regionundernourishment = []\n for country in countries:\n country = getundernourishment(country)\n regionundernourishment.extend(country)\n avgregion = {}\n for stat in regionundernourishment:\n if stat[0] not in avgregion:\n avgregion[stat[0]] = [stat[1]]\n if stat[0] in avgregion:\n avgregion[stat[0]].append(stat[1])\n for key, value in avgregion.items():\n avgregion[key] = sum(list(map(float,value)))/ len(list(map(float,value)))\n regionname = dic_id_name[int(region)]\n sorteddata = sorted(list(avgregion.items()), key=lambda x: x[0])\n dates , data = split_date_and_values(sorteddata)\n legend.append((regionname,[add_to_plot_undernourish(plot1, regionname,dates,data, colors[i])]))\n i += 1\n plotundernourishment(plot1,legend)\n \nregionundernourishment()\n\n","sub_path":"question3.py","file_name":"question3.py","file_ext":"py","file_size_in_byte":9341,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"75204146","text":"from Resources import config\n\nfrom PyCode.SharedFunctions import visual as shvis, sharedVars as svars\nfrom PyCode.Logging import pyLogging\nfrom PyCode.Visualisations import Visualisation as vis\n\nimport csv\nimport pandas as pd\nfrom datetime import datetime\nimport shutil\n\nfrom bokeh.layouts import column\nfrom bokeh.models import ColumnDataSource\nfrom bokeh.plotting import figure, show\nfrom bokeh.transform import factor_cmap\n\ndef showDefaultLogVisualisations(population):\n # Get log used for default graphs as defined in config or from most recent simulation\n if config.visLog:\n filepath = config.visLog\n else:\n # file may not exist if simulation has not been run\n filepath = 'Resources/Outputs/Logs/' + svars.loggingTimeStr + ' eventLog.csv'\n\n p1 = pIDNodeGraph(filepath, population)\n\n p2 = dateNodeGraph(filepath)\n\n p3 = pIDJourney(filepath, population)\n\n show(column(p1, p2, p3))\n\n # copy file to outputs\n shutil.copy('PyCode/mainPyCode.html', 'Resources/Outputs')\n\n\ndef pIDNodeGraph(filepath, population):\n\n # Dict for extracting data with counts from log file\n pIDNodeData = {}\n\n # open simulation log\n with open(filepath) as infile:\n reader = csv.reader(infile)\n for line in reader:\n if not line[5] == 'Pathway' and line[5] + ':' + line[6] in vis.pathwaynodesList:\n if line[5] + ':' + line[6] not in pIDNodeData:\n pIDNodeData[line[5] + ':' + line[6]] = {}\n if line[4] not in pIDNodeData[line[5] + ':' + line[6]]:\n pIDNodeData[line[5] + ':' + line[6]][line[4]] = 1\n else:\n pIDNodeData[line[5] + ':' + line[6]][line[4]] = pIDNodeData[line[5] + ':' + line[6]][line[4]] + 1\n\n # Dict in the correct form to become source for figure\n pIDNodeDict = {\"Pathway:Node\": [],\n \"Person\": [],\n \"Count\": [],\n \"ScaledSize\": []}\n\n PathwayNodes = []\n pIDs = []\n\n # Add in the data to new dict and create axis labels\n for pathwayNode in pIDNodeData:\n PathwayNodes.append(pathwayNode)\n for PID in pIDNodeData[pathwayNode]:\n if PID.zfill(2) + ': ' + population[int(PID)]['GivenName'] + ' ' + population[int(PID)]['Surname'] not in pIDs:\n pIDs.append(PID.zfill(2) + ': ' + population[int(PID)]['GivenName'] + ' ' + population[int(PID)]['Surname'])\n pIDNodeDict['Pathway:Node'].append(pathwayNode)\n pIDNodeDict['Person'].append(PID.zfill(2) + ': ' + population[int(PID)]['GivenName'] + ' ' + population[int(PID)]['Surname'])\n pIDNodeDict['Count'].append(pIDNodeData[pathwayNode][PID])\n\n maxValue = max(pIDNodeDict['Count'])\n scale = 30 / maxValue\n\n for count in pIDNodeDict['Count']:\n if count*scale > 2:\n pIDNodeDict['ScaledSize'].append(count * scale)\n else:\n pIDNodeDict['ScaledSize'].append(2)\n\n pIDNodeDF = pd.DataFrame(pIDNodeDict, columns=[\"Pathway:Node\",\n \"Person\",\n \"Count\",\n \"ScaledSize\"])\n\n # PathwayNodes = PathwayNodes.sort()\n pIDs.sort()\n pIDNodeDF = pIDNodeDF.sort_values(by=[\"Person\"])\n\n pIDNodeSource = ColumnDataSource(pIDNodeDF)\n\n if 1800/len(pIDs) > 35:\n width = 1800\n else:\n width = len(pIDs)*35\n\n plot = buildBokehHeatMap(pIDNodeSource, 'Count', 600, width, 'Individuals\\' Count of Events',\n pIDs, PathwayNodes, 'Person', 'Pathway:Node', 'ScaledSize', xLabelOri=1)\n\n return plot\n\n\ndef dateNodeGraph(filepath):\n # Dict for extracting data with counts from log file\n dateNodeData = {}\n\n # open simulation log\n with open(filepath) as infile:\n reader = csv.reader(infile)\n for line in reader:\n if not line[5] == 'Pathway' and line[5] + ':' + line[6] in vis.pathwaynodesList:\n if line[5] + ':' + line[6] not in dateNodeData:\n dateNodeData[line[5] + ':' + line[6]] = {}\n dateValue = str(int((int(line[3].split('/')[2]))/10)*10)\n if dateValue not in dateNodeData[line[5] + ':' + line[6]]:\n dateNodeData[line[5] + ':' + line[6]][dateValue] = []\n # Only add pID to list if not already there for unique count\n if line[4] not in dateNodeData[line[5] + ':' + line[6]][dateValue]:\n dateNodeData[line[5] + ':' + line[6]][dateValue].append(line[4])\n\n # Dict in the correct form to become source for figure\n dateNodeDict = {\"Pathway:Node\": [],\n \"Date\": [],\n \"UniqueCount\": [],\n \"ScaledSize\": []}\n\n pathwayNodes = []\n dates = []\n\n # Add in the data to new dict and create axis labels\n for pathwayNode in dateNodeData:\n pathwayNodes.append(pathwayNode)\n for date in dateNodeData[pathwayNode]:\n dateVal = date\n if dateVal not in dates:\n dates.append(dateVal)\n dateNodeDict['Pathway:Node'].append(pathwayNode)\n dateNodeDict['Date'].append(dateVal)\n dateNodeDict['UniqueCount'].append(len(dateNodeData[pathwayNode][date]))\n\n maxValue = max(dateNodeDict['UniqueCount'])\n scale = 30/maxValue\n\n for count in dateNodeDict['UniqueCount']:\n if count * scale > 2:\n dateNodeDict['ScaledSize'].append(count * scale)\n else:\n dateNodeDict['ScaledSize'].append(2)\n\n dateNodeDF = pd.DataFrame(dateNodeDict, columns=[\"Pathway:Node\",\n \"Date\",\n \"UniqueCount\",\n \"ScaledSize\"])\n\n dateNodeSource = ColumnDataSource(dateNodeDF)\n\n if 1800/len(dates) > 35:\n width = 1800\n else:\n width = len(dates)*35\n\n plot = buildBokehHeatMap(dateNodeSource, 'UniqueCount', 600, width, 'Events by Decade',\n dates, pathwayNodes, 'Date', 'Pathway:Node', 'ScaledSize')\n\n return plot\n\n\ndef pIDJourney(filepath, population):\n # Dict for extracting data with counts from log file\n pIDJourneyData = {}\n\n # open simulation log\n with open(filepath) as infile:\n reader = csv.reader(infile)\n for line in reader:\n if not line[5] == 'Pathway' and line[5] + ':' + line[6] in vis.pathwaynodesList:\n if line[5] + ':' + line[6] not in pIDJourneyData:\n pIDJourneyData[line[5] + ':' + line[6]] = {}\n dateValue = line[3]\n if dateValue not in pIDJourneyData[line[5] + ':' + line[6]]:\n pIDJourneyData[line[5] + ':' + line[6]][dateValue] = []\n # Only add pID to list if not already there for unique count\n if line[4] not in pIDJourneyData[line[5] + ':' + line[6]][dateValue]:\n pIDJourneyData[line[5] + ':' + line[6]][dateValue].append(line[4])\n\n # Dict in the correct form to become source for figure\n pIDJourneyDict = {\"Pathway:Node\": [],\n \"Date\": [],\n \"PID\": []}\n\n pathwayNodes = []\n dates = []\n pIDs = []\n\n # Add in the data to new dict and create axis labels\n for pathwayNode in pIDJourneyData:\n pathwayNodes.append(pathwayNode)\n for date in pIDJourneyData[pathwayNode]:\n dateVal = int((int(date.split('/')[2]))/10)*10\n if dateVal not in dates:\n dates.append(datetime(dateVal, 1, 1))\n for ID in pIDJourneyData[pathwayNode][date]:\n if ID not in pIDs:\n pIDs.append(ID)\n pIDJourneyDict['Pathway:Node'].append(pathwayNode)\n dateValue = datetime.strptime(date, '%d/%m/%Y')\n pIDJourneyDict['Date'].append(dateValue)\n pIDJourneyDict['PID'].append(ID)\n\n pIDJourneyDF = pd.DataFrame(pIDJourneyDict, columns=[\"Pathway:Node\",\n \"Date\",\n \"PID\"])\n\n pIDJourneySource = ColumnDataSource(pIDJourneyDF)\n\n colours = shvis.getColours(len(pIDs), 0.9)\n colourMap = {}\n\n ind = 0\n for id in pIDs:\n colourMap[id] = colours[ind]\n ind = ind + 1\n\n plot = buildBokehHeatMap(pIDJourneySource, 'PID', 600, 1800, 'Individuals\\' Events Over Time',\n None, pathwayNodes, 'Date', 'Pathway:Node', 10, xAxisType='datetime', colourMap=colourMap)\n\n return plot\n\n\ndef buildBokehHeatMap(dataSource, value, height, width, title, xLabels, yLabels, xVal, yVal, size, xAxisType = 'auto',\n colourMap = None, xLabelOri = None):\n # Tool tip appear when hovering over data points\n TOOLTIPS = [\n (\"Value\", \"@\" + value),\n (\"size\", \"@\" + str(size))\n ]\n\n # Figure on which data will plotted\n plot = figure(plot_width=width, plot_height=height, title=title, x_axis_type=xAxisType,\n x_range=xLabels, y_range=yLabels, x_axis_location=\"above\", tooltips=TOOLTIPS)\n\n if colourMap:\n graphColour = factor_cmap(value, palette=list(colourMap.values()), factors=list(colourMap.keys()))\n else:\n graphColour = 'navy'\n\n # Circles of size equal to count\n plot.circle(x=xVal, y=yVal, size=size, color=graphColour, source=dataSource)\n\n if xLabelOri:\n plot.xaxis.major_label_orientation = xLabelOri\n\n return plot\n","sub_path":"PyCode/Visualisations/LogVisualisations.py","file_name":"LogVisualisations.py","file_ext":"py","file_size_in_byte":9596,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"602770989","text":"# -*- coding: utf-8 -*-\nfrom __future__ import absolute_import, unicode_literals\n\nfrom lines.commands import get_commands, get_command_object, BaseCommand\n\n\nclass Command(BaseCommand):\n\n requires_output_directory = False\n run_on_all_command = False\n\n def execute(self):\n for command_name in get_commands():\n command = get_command_object(self.composition, command_name)\n if command.run_on_all_command:\n command.execute()\n","sub_path":"lines/commands/all.py","file_name":"all.py","file_ext":"py","file_size_in_byte":473,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"607896128","text":"import os\r\nimport sys\r\nfrom clear_screen import clear\r\nfrom lib.colors import style\r\nfrom lib.token import get_credentials\r\nfrom lib.ids import dump_ids\r\nfrom lib.phones import dump_phones\r\nfrom lib.emails import dump_emails\r\nfrom lib.user_info import dump_info\r\n\r\n\r\n# Main function\r\ndef main_function():\r\n while True:\r\n if os.path.isdir('Logs') == False:\r\n os.mkdir('Logs')\r\n else:\r\n None\r\n if os.path.isdir('lib/cache') == False:\r\n os.mkdir('lib/cache')\r\n else:\r\n None\r\n clear()\r\n print(' --- Welcome to FacebookHunter ---')\r\n print(' --- Author: @Proxy07 ---')\r\n\r\n # Menu options\r\n print(style.GREEN('\\n[1]') + style.RESET(' Generate access token.'))\r\n print(style.GREEN('[2]') + style.RESET(\" Dump all IDs.\"))\r\n print(style.GREEN('[3]') + style.RESET(\" Dump all phone numbers.\"))\r\n print(style.GREEN('[4]') + style.RESET(' Dump all email addresses.'))\r\n print(style.GREEN('[5]') + style.RESET(' Full information search by ID/Username.'))\r\n print(style.GREEN('[6]') + style.RED(' Exit FacebookHunter.'))\r\n try:\r\n mode_option = int(input(style.YELLOW('\\n[+]') + style.RESET(\" Enter your option number: \")))\r\n except:\r\n print(style.RED('\\n[!]') + style.RESET(' Error: User exited.'))\r\n sys.exit(0)\r\n\r\n if mode_option == 1:\r\n get_credentials()\r\n elif mode_option == 2:\r\n dump_ids()\r\n elif mode_option == 3:\r\n dump_phones()\r\n elif mode_option == 4:\r\n dump_emails()\r\n elif mode_option == 5:\r\n dump_info()\r\n elif mode_option == 6:\r\n print(style.RED('[!]') + style.RESET(' User exit, exiting...'))\r\n sys.exit(0)\r\n\r\n\r\nif __name__ == \"__main__\":\r\n clear()\r\n print(' --- Welcome to FacebookHunter ---')\r\n print(' --- Author: @Proxy07 ---')\r\n print(style.GREEN('\\n[+]') + style.RESET(' Notes:'))\r\n print(style.YELLOW(' [*]') + style.RESET(' I am not responsible for any damage caused by FacebookHunter!'))\r\n print(style.YELLOW(' [*]') + style.RESET(\" Read the readme.md page carefully before using FacebookHunter!\"))\r\n print(style.YELLOW(' [*]') + style.RESET(\" Abusing this script might end with locking up your Facebook account until you verify it again!\"))\r\n try:\r\n warning = str(input(style.RED('\\n[!]') + style.RESET(' Do you agree to use FacebookHunter for educational purposes only (y/n): ')))\r\n except KeyboardInterrupt:\r\n print(style.RED('\\n[!]') + style.RESET(' Error: User exited.'))\r\n sys.exit(0)\r\n main_function() if warning.lower() == \"y\" else sys.exit(0)\r\n","sub_path":"FacebookHunter.py","file_name":"FacebookHunter.py","file_ext":"py","file_size_in_byte":2757,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"79684349","text":"import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\n\nclass MNIST(nn.Module):\n\n def __init__(self):\n super(MNIST, self).__init__()\n self.conv0 = nn.Conv2d(in_channels=1, out_channels=6, kernel_size=3, bias=False)\n self.bn0 = nn.BatchNorm2d(num_features=6)\n self.relu0 = nn.ReLU()\n self.maxp0 = nn.MaxPool2d(kernel_size=(2, 2), stride=(2, 2))\n\n self.conv1 = nn.Conv2d(in_channels=6, out_channels=16, kernel_size=3, bias=False)\n self.bn1 = nn.BatchNorm2d(num_features=16)\n self.relu1 = nn.ReLU()\n self.maxp1 = nn.MaxPool2d(kernel_size=(2, 2), stride=(2, 2))\n\n self.dense2 = nn.Linear(in_features=16 * 6 * 6, out_features=120, bias=False)\n self.dp2 = nn.Dropout(p=0.5)\n self.relu2 = nn.ReLU()\n self.dense3 = nn.Linear(in_features=120, out_features=10, bias=False)\n\n def forward(self, x):\n x = self.conv0(x)\n x = self.bn0(x)\n x = self.relu0(x)\n x = self.maxp0(x)\n\n x = self.conv1(x)\n x = self.bn1(x)\n x = self.relu1(x)\n x = self.maxp1(x)\n\n x = x.view(-1, self.num_flat_features(x))\n\n x = self.dense2(x)\n x = self.dp2(x)\n x = self.relu2(x)\n\n x = self.dense3(x)\n\n return x\n \n def num_flat_features(self, x):\n size = x.size()[1:] # all dimensions except the batch dimension\n num_features = 1\n for s in size:\n num_features *= s\n return num_features\n\n\nif __name__ == '__main__':\n net = MNIST()\n data = torch.randn(2, 1, 32, 32)\n out = net(data)\n print(out)","sub_path":"applications/mnist/train/pytorch/train_mnist.py","file_name":"train_mnist.py","file_ext":"py","file_size_in_byte":1632,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"3047117","text":"import glob\nimport os\nimport random\nimport csv\nimport time\n\nimport tensorflow as tf\nimport numpy as np \nimport cv2\nimport matplotlib.pyplot as plt\nimport imageio\nimport imgaug as ia\nfrom imgaug import augmenters as iaa\n\nimport CONST\n\nfrom PIL import ImageFile\nImageFile.LOAD_TRUNCATED_IMAGES = True\n\n\n# -----------------------------------------------------------------------------\n# Constants\n# -----------------------------------------------------------------------------\nDATASET_PATH = \"../dataset/\"\n\nTRAIN_CSV_FILE = \"train\"\nVAL_CSV_FILE = \"val\"\nTEST_CSV_FILE = \"test\"\n\nCSV_FILE_EXTENSION = \".csv\"\n\nPATH_COL_IDX_IN_CSV = 0\nPATH_CLASS_IDX_IN_CSV = 1\n\nMINIMUM_NUMBER_OF_EXAMPLES_TRAIN = 20\nNUMBER_OF_EXAMPLES_VAL = 200\nNUMBER_OF_EXAMPLES_TEST = 300\n\nDATA_TYPE_INPUT = tf.dtypes.uint8\nANOMALOUS_SIZE = 500\n\n# Data augmentation\nBRIGHTNESS = \"brightness\"\nMIN_VAL_BRIGHTNESS = -0.10\nMAX_VAL_BRIGHTNESS = 0.20\nBRIGHTNESS_DEFAULT = 0.15\n\nCONTRAST = \"contrast\"\nMIN_VAL_CONTRAST = 0.80\nMAX_VAL_CONTRAST = 1.20\nCONTRAST_DEFAULT = 0.15\n\nGAMMA = \"gamma\"\nMIN_GAMMA_VALUE_GAMMA = 1.05\nMAX_GAMMA_VALUE_GAMMA = 1.25\nMIN_GAIN_VALUE_GAMMA = 1.0\nMAX_GAIN_VALUE_GAMMA = 1.0\nGAMMA_DEFAULT = 0.1\n\nHUE = \"hue\"\nMIN_VAL_HUE = -0.08\nMAX_VAL_HUE = 0.08\nHUE_DEFAULT = 0.15\n\nSATURATION = \"saturation\"\nMIN_VAL_SATURATION = 0.7\nMAX_VAL_SATURATION = 1.5\nSATURATION_DEFAULT = 0.15\n\nGAUSSIAN_NOISE = \"gaussian_noise\"\nGAUSSIAN_NOISE_DEFAULT = 0.15\n\nFLIP_VERTICAL = \"flip_vertical\"\nFLIP_VERTICAL_DEFAULT = 0.5\n\nFLIP_HORIZONTAL = \"flip_horizontal\"\nFLIP_HORIZONTAL_DEFAULT = 0.15\n\nROTATION = \"rotation\"\nROTATION_MIN_VALUE = -40\nROTATION_MAX_VALUE = 40\nROTATION_DEFAULT = 0.0\n\nBLUR = \"blur\"\nBLUR_FACTOR = 5\nBLUR_DEFAULT = 0.15\n\nSALT_AND_PEPPER = \"salt_and_pepper\"\nSALT_AND_PEPPER_RATIO_FACTOR = 0.005\nSALT_AND_PEPPER_DEFAULT = 0.9\n\nSHEAR = \"shear\"\nSHEAR_FACTOR = 40\nSHEAR_DEFAULT = 0.0\n\nEXPECTED_PROBABILITIES_KEYS = {BRIGHTNESS, CONTRAST, GAMMA, HUE, SATURATION,\n GAUSSIAN_NOISE, FLIP_VERTICAL, ROTATION,\n FLIP_HORIZONTAL, BLUR, SALT_AND_PEPPER,\n SHEAR}\n\n# imgaug probailities\nrotation_prob = 0.6\naffine_prob = 0.6\nflip_lr_prob = 0.5\nflip_ud_prob = 0.0\n\narithmetic_prob = 0.6\narithmetic_same_time_ops = 2\n\ncutout_prob = 0.6\nquality_prob = 0.6\n\n# Define the imgaug transformations\nseq = iaa.Sequential([\n iaa.Sometimes(rotation_prob, iaa.Affine(rotate=(-10, 10))),\n iaa.Sometimes(affine_prob, iaa.Affine(scale={\"x\": (0.9, 1.1), \"y\": (0.9, 1.1)}, \n translate_percent={\"x\": (-0.05, 0.05), \"y\": (-0.05, 0.05)},\n shear=(-16, 16))),\n iaa.Fliplr(flip_lr_prob),\n iaa.Flipud(flip_ud_prob),\n iaa.Sometimes(arithmetic_prob, iaa.SomeOf(arithmetic_same_time_ops, [\n iaa.Add((-20, 20), per_channel=0.5),\n iaa.Multiply((0.7, 1.3), per_channel=0.5),\n iaa.AdditiveGaussianNoise(scale=0.05*255)], random_order=True)),\n iaa.Sometimes(cutout_prob, iaa.SomeOf(1, [\n iaa.Cutout(fill_mode=\"constant\", cval=(0, 255),\n fill_per_channel=0.5, nb_iterations=(1, 4), size=(0.05,0.1)),\n iaa.Cutout(fill_mode=\"gaussian\", cval=(0, 255),\n fill_per_channel=0.5, nb_iterations=(1, 4), size=(0.05,0.1)),\n iaa.CoarseDropout(0.02, size_percent=0.5),\n iaa.CoarseDropout(0.02, size_percent=0.15, per_channel=0.5),\n iaa.SaltAndPepper(0.05),\n iaa.SaltAndPepper(0.05, per_channel=True),\n iaa.CoarseSaltAndPepper(0.02, size_percent=(0.01, 0.05), \n per_channel=True)])),\n iaa.Sometimes(quality_prob, iaa.SomeOf(1, [\n iaa.JpegCompression(compression=(70, 99)),\n iaa.BlendAlpha((0.0, 1.0), iaa.Grayscale(1.0)),\n iaa.BlendAlpha([0.25, 0.75], iaa.MedianBlur(5)),\n iaa.BlendAlphaElementwise((0, 1.0), iaa.AddToHue(20)),\n iaa.GaussianBlur(sigma=(0.0, 1.5)),\n iaa.MedianBlur(k=(3, 5)),\n iaa.MotionBlur(k=7),\n iaa.WithHueAndSaturation(\n iaa.WithChannels(0, iaa.Add((0, 20)))),\n iaa.MultiplyHue((0.85, 1.25)),\n iaa.MultiplySaturation((0.75, 1.35)),\n iaa.ChangeColorTemperature((3000, 10000)),\n iaa.GammaContrast((0.5, 2.0)),\n iaa.CLAHE(clip_limit=(1, 10)),\n iaa.AllChannelsHistogramEqualization(),\n iaa.Sharpen(alpha=(0.05, 0.2), lightness=(0.75, 1.0)),\n iaa.Emboss(alpha=(0.3, 0.6), strength=(0.5, 1.5)),\n iaa.AveragePooling(2),\n iaa.MedianPooling(2),\n iaa.Clouds(),\n iaa.Rain(speed=(0.1, 0.3))\n ]))\n ])\n\n\n# -----------------------------------------------------------------------------\n# Local functions\n# -----------------------------------------------------------------------------\ndef get_train_PIC_elements():\n \"\"\"Read the CSV TRAIN_FILE in DATASET_PATH\"\"\"\n\n with open(DATASET_PATH + TRAIN_CSV_FILE + CSV_FILE_EXTENSION) as csv_file:\n csv_reader = csv.reader(csv_file, delimiter=',')\n\n path_list = []\n class_list = []\n line_count = 0\n for row in csv_reader:\n if line_count > 0:\n path_list.append(row[PATH_COL_IDX_IN_CSV])\n class_list.append(row[PATH_CLASS_IDX_IN_CSV])\n\n line_count += 1\n\n idx_list = list(range(len(path_list)))\n \n return path_list, idx_list, class_list\n\n\ndef get_test_PIC_elements():\n \"\"\"Read the CSV TEST_CSV_FILE in DATASET_PATH\"\"\"\n\n with open(DATASET_PATH + TEST_CSV_FILE + CSV_FILE_EXTENSION) as csv_file:\n csv_reader = csv.reader(csv_file, delimiter=',')\n\n path_list = []\n class_list = []\n line_count = 0\n for row in csv_reader:\n if line_count > 0:\n path_list.append(row[PATH_COL_IDX_IN_CSV])\n class_list.append(row[PATH_CLASS_IDX_IN_CSV])\n\n line_count += 1\n\n idx_list = list(range(len(path_list)))\n \n return path_list, idx_list, class_list\n\n\ndef get_val_PIC_elements():\n \"\"\"Read the CSV VAL_CSV_FILE in DATASET_PATH\"\"\"\n\n with open(DATASET_PATH + VAL_CSV_FILE + CSV_FILE_EXTENSION) as csv_file:\n csv_reader = csv.reader(csv_file, delimiter=',')\n\n path_list = []\n class_list = []\n line_count = 0\n for row in csv_reader:\n if line_count > 0:\n path_list.append(row[PATH_COL_IDX_IN_CSV])\n class_list.append(row[PATH_CLASS_IDX_IN_CSV])\n\n line_count += 1\n\n idx_list = list(range(len(path_list)))\n \n return path_list, idx_list, class_list\n\n\ndef pathlabelidx_lists_to_PIC_format(path_lst, label_lst, idx_lst):\n \"\"\"This function transform the input list to the PIC format \n (each path is transformed in [path, index, Class])\n\n Keyword arguments:\n lst -- list of paths\n\n Restrictions:\n lst must not have duplicated elements\n \"\"\"\n assert len(set(path_lst)) == len(path_lst), \"There are duplicated path-elements\" + str(len(idx_lst))\n assert len(set(idx_lst)) == len(idx_lst), \"There are duplicated idx-elements\"\n assert np.min(idx_lst) == 0 and np.max(idx_lst) == len(idx_lst)-1, \"Bad range of idx-elements\"\n assert len(path_lst) == len(label_lst), \"path_lst and label_lst have different number of elements\"\n assert len(path_lst) == len(idx_lst), \"path_lst and idx_lst have different number of elements\"\n\n # Built the PIC list from lst\n PIC_lst = [[path_lst[i], idx_lst[i], CONST.CLASSES.index(label_lst[i])] for i in range(len(path_lst))]\n\n return PIC_lst\n\n\ndef replicate_PIC_list_by_number_of_replication(PIC_lst, replications_by_elements):\n \"\"\"This function replicate each element in the input list with the PIC format\n as times as is indicate in the same position in replications_by_elements argument.\n\n Keyword arguments:\n PIC_lst -- list with PIC format to be replicated\n replications_by_elements -- num of replications by position\n\n Restrictions:\n PIC_lst must not have duplicated elements and must have PIC format\n replications factor must be greather than 0\n \"\"\"\n\n assert len(set([PIC_lst[i][0] for i in range(len(PIC_lst))])) == len(PIC_lst), \\\n \"There are duplicated elements\"\n\n assert all([x > 0 for x in replications_by_elements]), \\\n \"There are replications factor less or equal than 0\"\n\n each_element_replicate_in_a_list = \\\n [[element] * replications_by_elements[idx] for idx, element in enumerate(PIC_lst)]\n\n each_element_replicate = \\\n [item for items in each_element_replicate_in_a_list for item in items]\n\n return each_element_replicate\n\n\ndef get_sample_by_class_from_PIC_list(pic, number_of_samples_by_class):\n \"\"\"This function obtain a random sub-pic list from pic where each class have\n numberOfSamplesByClass elements by class.\n\n Keyword arguments:\n pic -- [path, index, Class] list\n number_of_samples_by_class -- num of elements in each class\n \"\"\"\n auxiliar = [random.sample([x for x in pic if x[2] == i], number_of_samples_by_class) for i in\n range(len(CONST.CLASSES))]\n subpic = [item for items in auxiliar for item in items]\n\n return subpic\n\n\n# -----------------------------------------------------------------------------\n# Module functions: EXTRACT\n# -----------------------------------------------------------------------------\ndef parse_train(path_input, idx_src, idx_class):\n \"\"\"Get and return the tensors after reading the data based on the\n path_input for the train dataset and its one-hot class encoding.\n\n Keyword arguments:\n path_input -- list with the paths of images\n idx_src -- idx of the current path in the originial list\n idx_class -- the class index\n \"\"\"\n\n # Reading the data from the disk\n img_raw = tf.io.read_file(path_input)\n\n # Formatting the byte array to expected shapes\n img_decode = tf.io.decode_image(img_raw, channels=CONST.NUM_CHANNELS_INPUT)\n\n return img_decode, idx_src, tf.one_hot(idx_class, len(CONST.CLASSES))\n\n\ndef parse_val(path_input, idx_src, idx_class):\n \"\"\"Get and return the tensors after reading the data based on the\n path_input for the val dataset and its one-hot class encoding.\n\n Keyword arguments:\n path_input -- list with the paths of images\n idx_src -- idx of the current path in the originial list\n idx_class -- the class index\n \"\"\"\n\n # Reading the data from the disk\n img_raw = tf.io.read_file(path_input)\n\n # Formatting the byte array to expected shapes\n img_decode = tf.io.decode_image(img_raw, channels=CONST.NUM_CHANNELS_INPUT)\n\n return img_decode, idx_src, tf.one_hot(idx_class, len(CONST.CLASSES))\n\n\ndef parse_test(path_input, idx_src, idx_class):\n \"\"\"Get and return the tensors after reading the data based on the\n path_input for the test dataset and its one-hot class encoding.\n\n Keyword arguments:\n path_input -- list with the paths of images\n idx_src -- idx of the current path in the originial list\n idx_class -- the class index\n \"\"\"\n\n # Reading the data from the disk\n img_raw = tf.io.read_file(path_input)\n\n # Formatting the byte array to expected shapes\n img_decode = tf.io.decode_image(img_raw, channels=CONST.NUM_CHANNELS_INPUT)\n\n return img_decode, idx_src, tf.one_hot(idx_class, len(CONST.CLASSES))\n\n\n# -----------------------------------------------------------------------------\n# Module functions: TRANSFORM\n# -----------------------------------------------------------------------------\ndef preprocess_train(img_decode, idx_src, idx_class_one_hot):\n \"\"\"Get and return the tensors with the proper shape and type from the\n original tensor for images and keep the other data as it is.\n\n Keyword arguments:\n img_decode -- tensor of image/s\n idx_src -- idx of the image in the original path list\n class_one_hot -- expected class with one-hot encoding\n \"\"\"\n # Convert images to float\n img = tf.image.convert_image_dtype(img_decode, tf.float32)\n\n img = tf.image.resize_with_pad(img,\n target_height=CONST.HIGH_SIZE,\n target_width=CONST.WIDTH_SIZE,\n method=tf.image.ResizeMethod.BILINEAR,\n antialias=False)\n\n return img, idx_src, idx_class_one_hot\n\n\ndef preprocess_val(img_decode, idx_src, idx_class_one_hot):\n \"\"\"Get and return the tensors with the proper shape and type from the\n original tensor for images and keep the other data as it is.\n\n Keyword arguments:\n img_decode -- tensor of image/s\n idx_src -- idx of the image in the original path list\n class_one_hot -- expected class with one-hot encoding\n \"\"\"\n # Convert images to float\n img = tf.image.convert_image_dtype(img_decode, tf.float32)\n img = tf.image.resize_with_pad(img,\n target_height=CONST.HIGH_SIZE,\n target_width=CONST.WIDTH_SIZE,\n method=tf.image.ResizeMethod.BILINEAR,\n antialias=False)\n\n return img, idx_src, idx_class_one_hot\n\n\ndef preprocess_test(img_decode, idx_src, idx_class_one_hot):\n \"\"\"Get and return the tensors with the proper shape and type from the\n original tensor for images and keep the other data as it is.\n\n Keyword arguments:\n img_decode -- tensor of image/s\n idx_src -- idx of the image in the original path list\n class_one_hot -- expected class with one-hot encoding\n \"\"\"\n # Convert images to float\n img = tf.image.convert_image_dtype(img_decode, tf.float32)\n img = tf.image.resize_with_pad(img,\n target_height=CONST.HIGH_SIZE,\n target_width=CONST.WIDTH_SIZE,\n method=tf.image.ResizeMethod.BILINEAR,\n antialias=False)\n\n return img, idx_src, idx_class_one_hot\n\n\ndef data_augmentation(img, idx_src, idx_class_one_hot, probabilities):\n \"\"\"Get and return the tensors with the proper shape and type from the\n original tensor for images in train dataset and keep the other\n data as it is.\n\n Keyword arguments:\n img -- tensor of one image\n probabilities -- dict with probabilities € [0,1] of applying each data\n augmentation technique.\n \"\"\"\n\n # Checks probabilities before use\n assert all(0.0 <= value <= 1.0 for key, value in probabilities.items()), \\\n \"Probabilities must have in [0.0, 1.0]\"\n\n assert probabilities.keys() == EXPECTED_PROBABILITIES_KEYS, \\\n \"Probabilities must have only these keys: \" \\\n + str(EXPECTED_PROBABILITIES_KEYS)\n \n # Hue\n img = tf.cond(tf.less(tf.random.uniform(shape=[], minval=0, maxval=1),\n probabilities[HUE]),\n lambda: tf.image.adjust_hue(img, tf.random.uniform(\n shape=[], minval=MIN_VAL_HUE,\n maxval=MAX_VAL_HUE)),\n lambda: img)\n\n # Saturation\n img = tf.cond(tf.less(tf.random.uniform(shape=[], minval=0, maxval=1),\n probabilities[SATURATION]),\n lambda: tf.image.adjust_saturation(img, tf.random.uniform(\n shape=[], minval=MIN_VAL_SATURATION,\n maxval=MAX_VAL_SATURATION)),\n lambda: img)\n\n # Brightness\n appy_brightness = tf.less(tf.random.uniform(shape=[], minval=0, maxval=1),\n probabilities[BRIGHTNESS])\n img = tf.cond(appy_brightness,\n lambda: tf.image.adjust_brightness(img, tf.random.uniform(\n shape=[], minval=MIN_VAL_BRIGHTNESS,\n maxval=MAX_VAL_BRIGHTNESS)),\n lambda: img)\n\n # Contrast\n appy_contrast = tf.less(tf.random.uniform(shape=[], minval=0, maxval=1),\n probabilities[CONTRAST])\n img = tf.cond(appy_contrast,\n lambda: tf.image.adjust_contrast(img, tf.random.uniform(\n shape=[], minval=MIN_VAL_CONTRAST,\n maxval=MAX_VAL_CONTRAST)),\n lambda: img)\n\n # Gamma\n apply_gamma = tf.math.logical_not(tf.math.logical_or(appy_brightness,\n appy_contrast))\n img = tf.cond(tf.math.logical_and(tf.less(tf.random.uniform(shape=[],\n minval=0,\n maxval=1),\n probabilities[GAMMA]),\n apply_gamma),\n lambda: tf.image.adjust_gamma(img, tf.random.uniform(\n shape=[], minval=MIN_GAMMA_VALUE_GAMMA,\n maxval=MAX_GAMMA_VALUE_GAMMA), tf.random.uniform(\n shape=[], minval=MIN_GAIN_VALUE_GAMMA,\n maxval=MAX_GAIN_VALUE_GAMMA)),\n lambda: img)\n \n # Gaussian Noise\n img = tf.cond(tf.less(tf.random.uniform(shape=[], minval=0, maxval=1),\n probabilities[GAUSSIAN_NOISE]),\n lambda: img + tf.random.normal(tf.shape(img), mean=0.0,\n stddev=0.08,\n dtype=tf.dtypes.float32),\n lambda: img)\n \n # Flip vertical\n apply_flip_vertical = tf.less(tf.random.uniform(shape=[], minval=0,\n maxval=1),\n probabilities[FLIP_VERTICAL])\n\n img = tf.cond(apply_flip_vertical, lambda: tf.image.flip_up_down(img),\n lambda: img)\n\n # Flip horizontal\n apply_flip_horizontal = tf.less(tf.random.uniform(shape=[], minval=0,\n maxval=1),\n probabilities[FLIP_HORIZONTAL])\n\n img = tf.cond(apply_flip_horizontal, lambda: tf.image.flip_left_right(img),\n lambda: img)\n \n # Blur\n img = tf.cond(tf.less(tf.random.uniform(shape=[], minval=0, maxval=1),\n probabilities[BLUR]),\n lambda: tf.squeeze(tf.nn.avg_pool2d(input=tf.expand_dims(img, 0), ksize=BLUR_FACTOR, strides=1, padding='SAME')),\n lambda: img)\n\n # Limit pixel values to [0, 1]\n img = tf.minimum(img, 1.0)\n img = tf.maximum(img, 0.0)\n\n # Salt & Pepper\n mask = tf.random.uniform(shape=[int(CONST.HIGH_SIZE / 8), int(CONST.WIDTH_SIZE / 8)], minval=0.0, maxval=1.0, dtype=tf.float32)\n mask = tf.cast(mask > SALT_AND_PEPPER_RATIO_FACTOR, tf.dtypes.uint8)\n mask = tf.tile(tf.expand_dims(mask, -1), [1, 1, 3])\n\n mask = tf.nn.max_pool2d(tf.expand_dims(1 - mask, 0), ksize=(3, 3), strides=1, padding='SAME')\n mask = tf.squeeze(mask)\n mask = 1 - mask\n mask = tf.image.resize(mask, size=[CONST.HIGH_SIZE, CONST.WIDTH_SIZE], method='nearest', antialias=False)\n\n mask = tf.cast(mask, tf.dtypes.float32)\n\n img = tf.cond(tf.less(tf.random.uniform(shape=[], minval=0, maxval=1),\n probabilities[SALT_AND_PEPPER]),\n lambda: img * mask,\n lambda: img)\n\n \"\"\"\n # The following transformations work with the numpy object\n img = tf.keras.preprocessing.image.img_to_array(img)\n\n # Rotation\n apply_rotation = tf.less(tf.random.uniform(shape=[], minval=0,\n maxval=1),\n probabilities[ROTATION])\n\n img = tf.cond(apply_rotation,\n lambda: tf.keras.preprocessing.image.random_rotation(\n x=img, rg=ROTATION_ANGLE, row_axis=0, col_axis=1, channel_axis=2),\n lambda: img)\n\n # Shear\n apply_shear = tf.less(tf.random.uniform(shape=[], minval=0,\n maxval=1),\n probabilities[SHEAR])\n\n img = tf.cond(apply_shear,\n lambda: tf.keras.preprocessing.image.random_shear(\n x=img, intensity=SHEAR_FACTOR, row_axis=0, col_axis=1, channel_axis=2),\n lambda: img) \n\n # Transform to tensor before return the image\n img = tf.convert_to_tensor(img, dtype=tf.float32)\n \"\"\"\n\n return img, idx_src, idx_class_one_hot\n\n\ndef ETL_imgaug(path_input, idx_src, idx_class):\n \"\"\"Do the whole ETL training process with the imgaug library.\n \n Keyword arguments:\n path_input -- list with the paths of images\n idx_src -- idx of the current path in the originial list\n idx_class -- the class index\n \"\"\"\n\n # Reading the data from the disk (path_input is a tensor originally so we transform it to Python string)\n image = imageio.imread(path_input.numpy().decode(\"utf-8\"))\n\n # Resize the image\n image = tf.cast(tf.image.resize_with_pad(tf.cast(image, tf.dtypes.float32),\n target_height=CONST.HIGH_SIZE,\n target_width=CONST.WIDTH_SIZE,\n method=tf.image.ResizeMethod.BILINEAR,\n antialias=False), tf.dtypes.uint8).numpy()\n\n # Apply random transformation\n image_aug = seq(image=image)\n\n # Convert images to TensorFlow float32 tensor with values in [0, 1]\n image_aug = tf.convert_to_tensor(image_aug, dtype=tf.dtypes.float32) / 255.0\n\n # Get he one-hot encoding\n one_hot_encoding = tf.one_hot(idx_class, len(CONST.CLASSES))\n\n return image_aug, idx_src, one_hot_encoding\n\n\n# -----------------------------------------------------------------------------\n# Module functions: LOAD\n# -----------------------------------------------------------------------------\ndef build_train_dataset(batch_size, num_batches_preloaded, num_parallel_calls,\n allow_repetitions, probabilities, replications, shuffle=True, \n use_tensorflow_data_aug=False):\n \"\"\"Combine all functions to build train dataset\n\n Keyword arguments:\n batch_size -- batch size of training\n num_batches_preloaded -- num batches in memory\n num_parallel_calls -- num threads to work with dataset\n allow_repetitions -- allow to repeat batch in the dataset\n probabilities -- dict of probabilities for each data aumentation technique\n replications -- replication of each path\n shuffle -- do random permutations\n use_tensorflow_data_aug -- data augmentation with Tensorflow Ops or imgaug library\n \"\"\"\n # Get the paths\n path_lst, idx_lst, label_lst = get_train_PIC_elements()\n pic = pathlabelidx_lists_to_PIC_format(path_lst, label_lst, idx_lst)\n \n # Get the minimum number of element for all classes\n class_idx = [element[2] for element in pic]\n minimum_number_of_elements = min([class_idx.count(idx) for idx in range(len(CONST.CLASSES))])\n\n # Replicate the paths\n pic = replicate_PIC_list_by_number_of_replication(pic, replications)\n\n # Sample by the minimum number of elements\n subpic = get_sample_by_class_from_PIC_list(pic, minimum_number_of_elements)\n\n # Split each component\n paths = [element[0] for element in subpic]\n idx_srcs = [element[1] for element in subpic]\n idx_classes = [element[2] for element in subpic]\n\n # Build the dataset from the list of paths\n train_dataset = tf.data.Dataset.from_tensor_slices((paths,\n idx_srcs,\n idx_classes))\n\n # Shuffle the dataset by the number of examples\n if shuffle:\n train_dataset = train_dataset.shuffle(len(subpic))\n\n # Allow repetition to do more than one epoch\n if allow_repetitions:\n train_dataset = train_dataset.repeat()\n\n # Define the ETL proces by the data augmentation library to use\n if use_tensorflow_data_aug:\n # Now we can process the paths. First extract phase\n train_dataset = train_dataset.map(parse_train,\n num_parallel_calls=num_parallel_calls)\n\n # Now we can process the paths. Second transform phase\n train_dataset = train_dataset.map(preprocess_train,\n num_parallel_calls=num_parallel_calls)\n\n # Apply data aumentation function\n def data_aumentation_function(img, idx_src, idx_class_one_hot):\n return data_augmentation(img, idx_src, idx_class_one_hot, probabilities)\n\n train_dataset = train_dataset.map(data_aumentation_function,\n num_parallel_calls=num_parallel_calls)\n\n else:\n\n # Do the ETL process with the imgaug library\n train_dataset = train_dataset.map(lambda paths, idx_srcs, idx_classes: \\\n tf.py_function(ETL_imgaug, [paths, idx_srcs, idx_classes], [tf.float32, tf.int32, tf.float32]),\n num_parallel_calls=num_parallel_calls)\n\n # Tensorflow need to know the data shape to define the graph properly\n def define_final_shape(img, idx, one_hot):\n return tf.reshape(img, shape=(CONST.HIGH_SIZE, CONST.WIDTH_SIZE, CONST.NUM_CHANNELS_INPUT)), idx, one_hot\n \n train_dataset = train_dataset.map(define_final_shape)\n\n # Set the number of examples for each batch\n train_dataset = train_dataset.batch(batch_size, drop_remainder=True)\n\n # Set the number of batch loaded in memory\n train_dataset = train_dataset.prefetch(num_batches_preloaded)\n\n return train_dataset\n\n\ndef build_val_dataset(batch_size, num_batches_preloaded, num_parallel_calls):\n \"\"\"Combine all functions to build val dataset\n\n Keyword arguments:\n batch_size -- batch size of val\n num_batches_preloaded -- num batches in memory\n num_parallel_calls -- num threads to work with dataset\n \"\"\"\n # Get the paths\n path_lst, idx_lst, label_lst = get_val_PIC_elements()\n pic = pathlabelidx_lists_to_PIC_format(path_lst, label_lst, idx_lst)\n\n \n # Split each component\n paths = [element[0] for element in pic]\n idx_srcs = [element[1] for element in pic]\n idx_classes = [element[2] for element in pic]\n\n # Build the dataset from the list of paths\n val_dataset = tf.data.Dataset.from_tensor_slices((paths,\n idx_srcs,\n idx_classes))\n \n # Now we can process the paths. First extract phase\n val_dataset = val_dataset.map(parse_val,\n num_parallel_calls=num_parallel_calls)\n\n # Now we can process the paths. Second transform phase\n val_dataset = val_dataset.map(preprocess_val,\n num_parallel_calls=num_parallel_calls)\n\n def define_final_shape(img, idx, one_hot):\n return tf.reshape(img, shape=(CONST.HIGH_SIZE, CONST.WIDTH_SIZE, CONST.NUM_CHANNELS_INPUT)), idx, one_hot\n \n val_dataset = val_dataset.map(define_final_shape)\n\n # Set the number of examples for each batch\n val_dataset = val_dataset.batch(batch_size, drop_remainder=True)\n\n # Set the number of batch loaded in memory\n val_dataset = val_dataset.prefetch(num_batches_preloaded)\n \n return val_dataset\n\n\ndef build_test_dataset(batch_size, num_batches_preloaded, num_parallel_calls):\n \"\"\"Combine all functions to build test dataset\n\n Keyword arguments:\n batch_size -- batch size of test\n num_batches_preloaded -- num batches in memory\n num_parallel_calls -- num threads to work with dataset\n \"\"\"\n # Get the paths\n path_lst, idx_lst, label_lst = get_test_PIC_elements()\n pic = pathlabelidx_lists_to_PIC_format(path_lst, label_lst, idx_lst)\n \n # Split each component\n paths = [element[0] for element in pic]\n idx_srcs = [element[1] for element in pic]\n idx_classes = [element[2] for element in pic]\n\n # Build the dataset from the list of paths\n test_dataset = tf.data.Dataset.from_tensor_slices((paths,\n idx_srcs,\n idx_classes))\n \n # Now we can process the paths. First extract phase\n test_dataset = test_dataset.map(parse_test,\n num_parallel_calls=num_parallel_calls)\n\n # Now we can process the paths. Second transform phase\n test_dataset = test_dataset.map(preprocess_test,\n num_parallel_calls=num_parallel_calls)\n\n # Set the number of examples for each batch\n test_dataset = test_dataset.batch(batch_size)\n\n # Set the number of batch loaded in memory\n test_dataset = test_dataset.prefetch(num_batches_preloaded)\n \n return test_dataset\n\n\n# -----------------------------------------------------------------------------\n# Module functions: UTILS\n# -----------------------------------------------------------------------------\ndef to_human_output(img, one_hot_encoding):\n \"\"\"Transform the dataset format data to human interpretable format\"\"\"\n return img, CONST.CLASSES[tf.argmax(one_hot_encoding)]\n\n\ndef data_augmentation_calibration(probabilities):\n \"\"\"Show the result of the data_augmentation for the defined probabilities\"\"\"\n\n # Get all the paths\n path_lst, idx_lst, label_lst = get_train_PIC_elements()\n pic = pathlabelidx_lists_to_PIC_format(path_lst, label_lst, idx_lst)\n\n NUM_DATA = len(path_lst)\n for i, element in enumerate(pic):\n\n # Extract each component\n path, idx_src, idx_class = element\n\n # Call the function\n img_decode, idx_src_new, idx_class_one_hot = parse_train(path, idx_src, idx_class)\n\n img_transformed, idx_src_new, idx_class_one_hot = \\\n preprocess_train(img_decode, idx_src_new, idx_class_one_hot)\n\n img, idx_src_new, idx_class_one_hot_new = data_augmentation(img_transformed, idx_src_new, idx_class_one_hot,\n probabilities)\n\n img, class_human = to_human_output(img, idx_class_one_hot_new)\n\n print(\"Image\", i, \"of\", NUM_DATA, \":\", path)\n\n plt.figure(1)\n plt.title(\"Original image (B = \"\n + str(tf.round(tf.reduce_mean(img_transformed, axis=(0, 1)) * 255, 2).numpy())\n + \"): \" + class_human)\n plt.imshow(img_transformed)\n plt.draw()\n\n plt.figure(2)\n plt.title(\"Augmented image (B = \"\n + str(tf.round(tf.reduce_mean(img, axis=(0, 1)) * 255, 2).numpy())\n + \"): \" + class_human)\n plt.imshow(img)\n plt.draw()\n\n plt.show(block=False)\n\n # Wait break only with a keyboard press\n while not plt.waitforbuttonpress():\n pass\n\n plt.close()\n\n\ndef build_probabilities_dict(brightness=BRIGHTNESS_DEFAULT, contrast=CONTRAST_DEFAULT,\n gamma=GAMMA_DEFAULT, hue=HUE_DEFAULT, saturation=SATURATION_DEFAULT,\n gaussian_noise=GAUSSIAN_NOISE_DEFAULT, blur=BLUR_DEFAULT,\n flip_vertical=FLIP_VERTICAL_DEFAULT, flip_horizontal=FLIP_HORIZONTAL_DEFAULT,\n rotation=ROTATION_DEFAULT, salt_and_pepper=SALT_AND_PEPPER_DEFAULT,\n shear=SHEAR_DEFAULT):\n \"\"\"Build the dict of probabilities of the data augmentation params\"\"\"\n\n probabilities = {BRIGHTNESS: brightness, CONTRAST: contrast, GAMMA: gamma, HUE: hue,\n SATURATION: saturation, GAUSSIAN_NOISE: gaussian_noise, BLUR: blur,\n FLIP_VERTICAL: flip_vertical, FLIP_HORIZONTAL: flip_horizontal,\n ROTATION: rotation, SALT_AND_PEPPER: salt_and_pepper, SHEAR: shear}\n\n assert all(0.0 <= value <= 1.0 for key, value in probabilities.items()), \\\n \"Probabilities must have in [0.0, 1.0]\"\n\n assert probabilities.keys() == EXPECTED_PROBABILITIES_KEYS, \\\n \"Probabilities must have only these keys: \" \\\n + str(probabilities.keys()) + \"- \" + str(EXPECTED_PROBABILITIES_KEYS)\n\n return probabilities\n\n\ndef get_basic_training_variables(batch_size):\n \"\"\"Returns all the variables needed during the training\"\"\"\n\n # We need the data augmentation probabilities dic\n probabilities = build_probabilities_dict()\n\n # We need the paths to warn when we find a dificult image\n path_lst, idx_lst, label_lst = get_train_PIC_elements()\n pic = pathlabelidx_lists_to_PIC_format(path_lst, label_lst, idx_lst)\n\n # We need to modify the replication factor of each element by its classification result\n replications = [1 for _ in range(len(path_lst))]\n\n # We need the number of batches in the train dataset to print it\n class_idx = [element[2] for element in pic]\n minimum_number_of_elements = min([class_idx.count(idx) for idx in range(len(CONST.CLASSES))])\n batches_in_the_train_dataset = int(np.floor((minimum_number_of_elements * len(CONST.CLASSES)) / batch_size))\n\n return probabilities, path_lst, replications, batches_in_the_train_dataset\n\n\n# -----------------------------------------------------------------------------\n# Tests\n# -----------------------------------------------------------------------------\ndef test_get_train_PIC_elements():\n \"\"\"Test for get_train_paths()\"\"\"\n\n # Call the function\n train_paths, train_idx, train_labels = get_train_PIC_elements()\n\n # Test the length\n assert len(train_paths) > 0, \"There are no paths in the train set\"\n assert len(train_paths) == len(train_labels), \"There are different number of paths than labels\"\n assert len(train_paths) == len(train_idx), \"There are different number of paths than idx\"\n\n # Test the length of paths by classes\n paths_by_classes = \\\n [[path for path in train_paths if path.split(os.sep)[-2] == cls] for cls in CONST.CLASSES]\n assert all([len(cls_path) >= MINIMUM_NUMBER_OF_EXAMPLES_TRAIN for cls_path in paths_by_classes]), \\\n \"There are no paths for a/some class/classes: \" \\\n + str([i for i in list(zip(CONST.CLASSES, [len(i) for i in paths_by_classes])) if\n i[1] < MINIMUM_NUMBER_OF_EXAMPLES_TRAIN])\n\n # Test the length of labels by classes\n labels_by_classes = \\\n [[label for label in train_labels if label == cls] for cls in CONST.CLASSES]\n assert all([len(cls_label) >= MINIMUM_NUMBER_OF_EXAMPLES_TRAIN for cls_label in labels_by_classes]), \\\n \"There are no label for a/some class/classes: \" \\\n + str([i for i in list(zip(CONST.CLASSES, [len(i) for i in paths_by_classes])) if\n i[1] < MINIMUM_NUMBER_OF_EXAMPLES_TRAIN])\n \n # Test the file extension\n file_extensions = [\".\" + path.split(\".\")[-1] for path in train_paths]\n assert all([file_extension in CONST.IMG_EXTENSION for file_extension in file_extensions]), \\\n \"There are some files with non valid extension: \" \\\n + str([path for path in train_paths if \".\" + path.split(\".\")[-1] not in CONST.IMG_EXTENSION])\n\n # Test the elements are unique\n assert len(set(train_paths)) == len(train_paths), \\\n \"There are elements duplicated\"\n\n\ndef test_get_test_PIC_elements():\n \"\"\"Test for get_test_paths()\"\"\"\n\n # Call the function\n test_paths, test_idx, test_labels = get_test_PIC_elements()\n\n # Test the length\n assert len(test_paths) > 0, \"There are no paths in the test set\"\n assert len(test_paths) == len(test_labels), \"There are different number of paths than labels\"\n assert len(test_paths) == len(test_idx), \"There are different number of paths than idx\"\n\n\n # Test the length of paths by classes\n paths_by_classes = \\\n [[path for path in test_paths if path.split(os.sep)[-2] == cls] for cls in CONST.CLASSES]\n assert all([len(cls_path) >= NUMBER_OF_EXAMPLES_TEST for cls_path in paths_by_classes]), \\\n \"There are no paths for a/some class/classes: \" \\\n + str([i for i in list(zip(CONST.CLASSES, [len(i) for i in paths_by_classes])) if i[1] < NUMBER_OF_EXAMPLES_TEST])\n\n # Test the length of labels by classes\n labels_by_classes = \\\n [[label for label in test_labels if label == cls] for cls in CONST.CLASSES]\n assert all([len(cls_label) >= NUMBER_OF_EXAMPLES_TEST for cls_label in labels_by_classes]), \\\n \"There are no label for a/some class/classes: \" \\\n + str([i for i in list(zip(CONST.CLASSES, [len(i) for i in paths_by_classes])) if i[1] < NUMBER_OF_EXAMPLES_TEST])\n\n # Test the file extension\n file_extensions = [\".\" + path.split(\".\")[-1] for path in test_paths]\n assert all([file_extension in CONST.IMG_EXTENSION for file_extension in file_extensions]), \\\n \"There are some files with non valid extension: \" \\\n + str([path for path in test_paths if \".\" + path.split(\".\")[-1] not in CONST.IMG_EXTENSION])\n\n # Test the elements are unique\n assert len(set(test_paths)) == len(test_paths), \\\n \"There are elements duplicated\"\n\n\ndef test_get_val_PIC_elements():\n \"\"\"Test for get_test_paths()\"\"\"\n\n # Call the function\n val_paths, val_idx, val_labels = get_test_PIC_elements()\n\n # Test the length\n assert len(val_paths) > 0, \"There are no paths in the val set\"\n assert len(val_paths) == len(val_labels), \"There are different number of paths than labels\"\n assert len(val_paths) == len(val_idx), \"There are different number of paths than idx\"\n\n # Test the length of paths by classes\n paths_by_classes = \\\n [[path for path in val_paths if path.split(os.sep)[-2] == cls] for cls in CONST.CLASSES]\n assert all([len(cls_path) >= NUMBER_OF_EXAMPLES_VAL for cls_path in paths_by_classes]), \\\n \"There are no paths for a/some class/classes: \" \\\n + str([i for i in list(zip(CONST.CLASSES, [len(i) for i in paths_by_classes])) if i[1] < NUMBER_OF_EXAMPLES_VAL])\n\n # Test the length of labels by classes\n labels_by_classes = \\\n [[label for label in val_labels if label == cls] for cls in CONST.CLASSES]\n assert all([len(cls_label) >= NUMBER_OF_EXAMPLES_VAL for cls_label in labels_by_classes]), \\\n \"There are no label for a/some class/classes: \" \\\n + str([i for i in list(zip(CONST.CLASSES, [len(i) for i in paths_by_classes])) if i[1] < NUMBER_OF_EXAMPLES_VAL])\n\n # Test the file extension\n file_extensions = [\".\" + path.split(\".\")[-1] for path in val_paths]\n assert all([file_extension in CONST.IMG_EXTENSION for file_extension in file_extensions]), \\\n \"There are some files with non valid extension: \" \\\n + str([path for path in val_paths if \".\" + path.split(\".\")[-1] not in CONST.IMG_EXTENSION])\n\n # Test the elements are unique\n assert len(set(val_paths)) == len(val_paths), \\\n \"There are elements duplicated\"\n\n\ndef test_pathlabelidx_lists_to_PIC_format():\n \"\"\"Test for pathlabelidx_lists_to_PIC_formatt()\"\"\"\n\n # Call the function\n paths_lst, idx_lst, label_lst = get_val_PIC_elements()\n\n PIC_lst = pathlabelidx_lists_to_PIC_format(paths_lst, label_lst, idx_lst)\n\n # Test the length\n assert len(paths_lst) == len(PIC_lst), \" len(output) != len(input)\"\n\n\n # Test correspondence first row\n assert all([PIC_lst[i][0] == paths_lst[i] for i in range(len(paths_lst))]), \" unordered first row \"\n\n\n # Test the expected values\n for idx, element in enumerate(PIC_lst):\n assert element[0] == paths_lst[idx] \\\n and element[1] == idx \\\n and element[2] == CONST.CLASSES.index(paths_lst[idx].split(os.sep)[-2]), \\\n str(element) + \" XXX doesn't have the expected PIC format for \" + str(paths_lst[idx])\n\n\ndef test_replicate_PIC_list_by_number_of_replication():\n \"\"\"Test for replicate_PIC_list_by_number_of_replication()\"\"\"\n\n # Call the function\n path_lst, idx_lst, label_lst = get_test_PIC_elements()\n pic_train_paths = pathlabelidx_lists_to_PIC_format(path_lst, label_lst, idx_lst)\n\n replications_simulated = [random.randint(1, 10) for _ in range(len(pic_train_paths))]\n pic_train_paths_replicated = replicate_PIC_list_by_number_of_replication(pic_train_paths, replications_simulated)\n\n # Test the length\n assert len(pic_train_paths_replicated) == sum(replications_simulated), \\\n \"There is not the same element as is expected: \" \\\n + str(len(pic_train_paths_replicated)) \\\n + \" instead of \" + str(sum(replications_simulated))\n\n # Test each element is as time as is indicated\n offset = 0\n for idx, element in enumerate(pic_train_paths):\n element_replicate = pic_train_paths_replicated[offset:offset + replications_simulated[idx]]\n\n assert all([element_rep == element for element_rep in element_replicate]), \\\n \"There are elements which has not been replicated properly\"\n\n offset += replications_simulated[idx]\n\n\ndef test_get_sample_by_class_from_PIC_list():\n \"\"\"Test for get_sample_by_class_from_PIC_list()\"\"\"\n\n # Call the function\n path_lst, idx_lst, label_lst = get_test_PIC_elements()\n pic = pathlabelidx_lists_to_PIC_format(path_lst, label_lst, idx_lst)\n\n # Get the minimum number of element for all classes\n class_idx = [element[2] for element in pic]\n minimum_number_of_elements = min([class_idx.count(idx) for idx in range(len(CONST.CLASSES))])\n\n for number_of_samples_by_class in [int(x) for x in [minimum_number_of_elements / 2, minimum_number_of_elements / 3,\n minimum_number_of_elements]]:\n subpic = get_sample_by_class_from_PIC_list(pic, number_of_samples_by_class)\n\n # Test the length\n assert len(subpic) == len(CONST.CLASSES) * number_of_samples_by_class, \\\n \"len(output) != len(CONST.CLASSES) * number_of_samples_by_class\"\n\n # Test correspondence number of elements by class\n class_idx = [x[2] for x in subpic]\n assert set([class_idx.count(idx) for idx in range(len(CONST.CLASSES))]) == set([number_of_samples_by_class]), \\\n \"Wrong number of elements by class\"\n\n\ndef test_parse_train():\n \"\"\"Test for parse_train()\"\"\"\n\n # PIC training paths\n path_lst, idx_lst, label_lst = get_train_PIC_elements()\n pic = pathlabelidx_lists_to_PIC_format(path_lst, label_lst, idx_lst)\n\n # Checks for all paths\n NUM_TRAIN_DATA = len(path_lst)\n for i, element in enumerate(pic):\n\n # Extract each component\n path, idx_src, idx_class = element\n\n # Call the function\n try:\n input_data_tf, idx_src_new, idx_class_one_hot = parse_train(path, idx_src, idx_class)\n input_data_np = input_data_tf.numpy()\n except:\n print(path)\n\n # Do the tests\n assert input_data_tf.dtype == DATA_TYPE_INPUT, \\\n \"Input data type doesn't match\"\n\n assert len(input_data_tf.shape) == 3, \\\n \"output is not a 3-D tensor\"\n\n assert input_data_tf.shape[-1] == CONST.NUM_CHANNELS_INPUT and min(input_data_tf.shape[:-1]) > ANOMALOUS_SIZE, \\\n \"Input data values or shape doesn't match\"\n\n assert all(np.min(input_data_np[:, :, channel])\n != np.max(input_data_np[:, :, channel]) for channel in\n range(CONST.NUM_CHANNELS_INPUT)), \\\n \"Input min and max value are the same. Maybe it's all zeros\"\n\n assert idx_src_new == idx_src, \\\n \"idx_src have been modified\"\n\n assert len(idx_class_one_hot.shape) == 1 and idx_class_one_hot.shape[0] == len(CONST.CLASSES), \\\n \"idx_class_one_hot doesn't have the expected shape\"\n\n assert idx_class_one_hot.dtype == tf.dtypes.float32, \\\n \"idx_class_one_hot is not float32\"\n\n assert idx_class_one_hot[idx_class] == 1 and tf.reduce_sum(idx_class_one_hot) == 1, \\\n \"idx_class_one_hot is not a correct one-hot vector for the class\"\n\n if i % 500 == 0 or (i + 1) == len(path_lst):\n print(\"[test_parse_train()]:\", i, \"of\", NUM_TRAIN_DATA)\n\n\ndef test_parse_val():\n \"\"\"Test for parse_val()\"\"\"\n\n # PIC val paths\n path_lst, idx_lst, label_lst = get_val_PIC_elements()\n pic = pathlabelidx_lists_to_PIC_format(path_lst, label_lst, idx_lst)\n\n\n # Checks for all paths\n NUM_DATA = len(path_lst)\n for i, element in enumerate(pic):\n\n # Extract each component\n path, idx_src, idx_class = element\n\n # Call the function\n try:\n input_data_tf, idx_src_new, idx_class_one_hot = parse_val(path, idx_src, idx_class)\n input_data_np = input_data_tf.numpy()\n except:\n print(path)\n\n # Do the tests\n assert input_data_tf.dtype == DATA_TYPE_INPUT, \\\n \"Input data type doesn't match\"\n\n assert len(input_data_tf.shape) == 3, \\\n \"output is not a 3-D tensor\"\n\n assert input_data_tf.shape[-1] == CONST.NUM_CHANNELS_INPUT and min(input_data_tf.shape[:-1]) > ANOMALOUS_SIZE, \\\n \"Input data values or shape doesn't match\"\n\n assert all(np.min(input_data_np[:, :, channel])\n != np.max(input_data_np[:, :, channel]) for channel in\n range(CONST.NUM_CHANNELS_INPUT)), \\\n \"Input min and max value are the same. Maybe it's all zeros\"\n\n assert idx_src_new == idx_src, \\\n \"idx_src have been modified\"\n\n assert len(idx_class_one_hot.shape) == 1 and idx_class_one_hot.shape[0] == len(CONST.CLASSES), \\\n \"idx_class_one_hot doesn't have the expected shape\"\n\n assert idx_class_one_hot.dtype == tf.dtypes.float32, \\\n \"idx_class_one_hot is not float32\"\n\n assert idx_class_one_hot[idx_class] == 1 and tf.reduce_sum(idx_class_one_hot) == 1, \\\n \"idx_class_one_hot is not a correct one-hot vector for the class\"\n\n if i % 100 == 0 or (i + 1) == len(path_lst):\n print(\"[test_parse_val()]:\", i, \"of\", NUM_DATA)\n\n\ndef test_parse_test():\n \"\"\"Test for parse_test()\"\"\"\n\n # PIC test paths\n path_lst, idx_lst, label_lst = get_test_PIC_elements()\n pic = pathlabelidx_lists_to_PIC_format(path_lst, label_lst, idx_lst)\n\n # Checks for all paths\n NUM_DATA = len(path_lst)\n for i, element in enumerate(pic):\n\n # Extract each component\n path, idx_src, idx_class = element\n\n # Call the function\n try:\n input_data_tf, idx_src_new, idx_class_one_hot = parse_test(path, idx_src, idx_class)\n input_data_np = input_data_tf.numpy()\n except:\n print(path)\n\n\n # Do the tests\n assert input_data_tf.dtype == DATA_TYPE_INPUT, \\\n \"Input data type doesn't match\" + path\n\n assert len(input_data_tf.shape) == 3, \\\n \"output is not a 3-D tensor\"\n\n assert input_data_tf.shape[-1] == CONST.NUM_CHANNELS_INPUT and min(input_data_tf.shape[:-1]) > ANOMALOUS_SIZE, \\\n \"Input data values or shape doesn't match\"\n\n assert all(np.min(input_data_np[:, :, channel])\n != np.max(input_data_np[:, :, channel]) for channel in\n range(CONST.NUM_CHANNELS_INPUT)), \\\n \"Input min and max value are the same. Maybe it's all zeros\"\n\n assert idx_src_new == idx_src, \\\n \"idx_src have been modified\"\n\n assert len(idx_class_one_hot.shape) == 1 and idx_class_one_hot.shape[0] == len(CONST.CLASSES), \\\n \"idx_class_one_hot doesn't have the expected shape\"\n\n assert idx_class_one_hot.dtype == tf.dtypes.float32, \\\n \"idx_class_one_hot is not float32\"\n\n assert idx_class_one_hot[idx_class] == 1 and tf.reduce_sum(idx_class_one_hot) == 1, \\\n \"idx_class_one_hot is not a correct one-hot vector for the class\"\n\n if i % 100 == 0 or (i + 1) == len(path_lst):\n print(\"[test_parse_test()]:\", i, \"of\", NUM_DATA)\n\n\ndef test_preprocess_train():\n \"\"\"Tests for the function preprocess_train()\"\"\"\n # Get all the paths\n path_lst, idx_lst, label_lst = get_train_PIC_elements()\n pic = pathlabelidx_lists_to_PIC_format(path_lst, label_lst, idx_lst)\n\n NUM_DATA = len(path_lst)\n for i, element in enumerate(pic):\n\n # Extract each component\n path, idx_src, idx_class = element\n\n # Call the function\n try:\n img_decode, idx_src_new, idx_class_one_hot = parse_train(path, idx_src, idx_class)\n img_transformed, idx_src_new_new, idx_class_one_hot_new = \\\n preprocess_train(img_decode, idx_src_new, idx_class_one_hot)\n except:\n print(path)\n\n # Do the tests\n assert img_transformed.dtype == tf.dtypes.float32, \\\n \"Input data type doesn't match\"\n\n # print(img_decode.shape, img_transformed.shape) XXXXX\n #assert img_decode.shape == img_transformed.shape, \\ XXXX\n # \"Input shape doesn't match\"\n\n minimum = tf.reduce_min(img_transformed)\n maximum = tf.reduce_max(img_transformed)\n assert minimum >= 0.0 and maximum <= 1.0 and minimum != maximum, \\\n \"img_transformed values are not in [0,1]\"\n\n assert idx_src_new_new == idx_src and np.array_equal(idx_class_one_hot_new, idx_class_one_hot), \\\n \"idx_src and/or idx_class_one_hot have been modified\"\n\n if i % 500 == 0 or (i + 1) == NUM_DATA:\n print(\"[test_preprocess_train()]:\", i, \"of\", NUM_DATA)\n\n\ndef test_preprocess_val():\n \"\"\"Tests for the function preprocess_val()\"\"\"\n # Get all the paths\n path_lst, idx_lst, label_lst = get_val_PIC_elements()\n pic = pathlabelidx_lists_to_PIC_format(path_lst, label_lst, idx_lst)\n\n NUM_DATA = len(path_lst)\n for i, element in enumerate(pic):\n\n # Extract each component\n path, idx_src, idx_class = element\n\n # Call the function\n try:\n img_decode, idx_src_new, idx_class_one_hot = parse_val(path, idx_src, idx_class)\n img_transformed, idx_src_new_new, idx_class_one_hot_new = \\\n preprocess_val(img_decode, idx_src_new, idx_class_one_hot)\n except:\n print(path)\n\n # Do the tests\n assert img_transformed.dtype == tf.dtypes.float32, \\\n \"Input data type doesn't match\"\n\n # print(img_decode.shape, img_transformed.shape) XXXXX\n #assert img_decode.shape == img_transformed.shape, \\ XXXXX\n # \"Input shape doesn't match\"\n\n minimum = tf.reduce_min(img_transformed)\n maximum = tf.reduce_max(img_transformed)\n assert minimum >= 0.0 and maximum <= 1.0 and minimum != maximum, \\\n \"img_transformed values are not in [0,1]\"\n\n assert idx_src_new_new == idx_src and np.array_equal(idx_class_one_hot_new, idx_class_one_hot), \\\n \"idx_src and/or idx_class_one_hot have been modified\"\n\n if i % 100 == 0 or (i + 1) == NUM_DATA:\n print(\"[test_preprocess_val()]:\", i, \"of\", NUM_DATA)\n\n\ndef test_preprocess_test():\n \"\"\"Tests for the function preprocess_test()\"\"\"\n # Get all the paths\n path_lst, idx_lst, label_lst = get_test_PIC_elements()\n pic = pathlabelidx_lists_to_PIC_format(path_lst, label_lst, idx_lst)\n\n NUM_DATA = len(path_lst)\n for i, element in enumerate(pic):\n\n # Extract each component\n path, idx_src, idx_class = element\n\n # Call the function\n try:\n img_decode, idx_src_new, idx_class_one_hot = parse_test(path, idx_src, idx_class)\n img_transformed, idx_src_new_new, idx_class_one_hot_new = \\\n preprocess_test(img_decode, idx_src_new, idx_class_one_hot)\n except:\n print(path)\n\n # Do the tests\n assert img_transformed.dtype == tf.dtypes.float32, \\\n \"Input data type doesn't match\"\n\n # print(img_decode.shape, img_transformed.shape) XXXXX\n # assert img_decode.shape == img_transformed.shape, \\\n # \"Input shape doesn't match\"\n\n minimum = tf.reduce_min(img_transformed)\n maximum = tf.reduce_max(img_transformed)\n assert minimum >= 0.0 and maximum <= 1.0 and minimum != maximum, \\\n \"img_transformed values are not in [0,1]\"\n\n assert idx_src_new_new == idx_src and np.array_equal(idx_class_one_hot_new, idx_class_one_hot), \\\n \"idx_src and/or idx_class_one_hot have been modified\"\n\n if i % 100 == 0 or (i + 1) == NUM_DATA:\n print(\"[test_preprocess_test()]:\", i, \"of\", NUM_DATA)\n\n\ndef test_data_augmentation():\n \"\"\"Tests for the function data_augmentation()\"\"\"\n\n probabilities = {BRIGHTNESS: 0.15, CONTRAST: 0.15, GAMMA: 0.15, HUE: 0.15,\n SATURATION: 0.15, GAUSSIAN_NOISE: 0.15, BLUR: 0.15,\n FLIP_VERTICAL: 0.15, FLIP_HORIZONTAL: 0.25,\n ROTATION: 0.25, SALT_AND_PEPPER: 0.15,\n SHEAR: 0.15}\n\n # Get all the paths\n path_lst, idx_lst, label_lst = get_val_PIC_elements()\n pic = pathlabelidx_lists_to_PIC_format(path_lst, label_lst, idx_lst)\n\n\n NUM_DATA = len(path_lst)\n for i, element in enumerate(pic):\n\n # Extract each component\n path, idx_src, idx_class = element\n\n # Call the function\n try:\n img_decode, idx_src_new, idx_class_one_hot = parse_test(path, idx_src, idx_class)\n img_transformed, idx_src_new, idx_class_one_hot = \\\n preprocess_test(img_decode, idx_src_new, idx_class_one_hot)\n img, idx_src_new, idx_class_one_hot_new = data_augmentation(img_transformed, idx_src_new, idx_class_one_hot,\n probabilities)\n except:\n print(path)\n\n assert img.dtype == tf.dtypes.float32, \\\n \"Input data type doesn't match\"\n\n assert img.shape == img_transformed.shape, \\\n \"Input shape doesn't match\"\n\n minimum = tf.reduce_min(img)\n maximum = tf.reduce_max(img)\n assert minimum >= 0.0 and maximum <= 1.0 and minimum != maximum, \\\n \"img values are not in [0,1]\"\n\n assert idx_src_new == idx_src and np.array_equal(idx_class_one_hot_new, idx_class_one_hot), \\\n \"idx_src and/or idx_class_one_hot have been modified\"\n\n if i % 100 == 0 or (i + 1) == NUM_DATA:\n print(\"[test_data_augmentation()]:\", i, \"of\", NUM_DATA)\n\n # Test whether the function keep the original values\n probabilities = {BRIGHTNESS: 0.0, CONTRAST: 0.0, GAMMA: 0.0, HUE: 0.0,\n SATURATION: 0.0, GAUSSIAN_NOISE: 0.0, BLUR: 0.0,\n FLIP_VERTICAL: 0.0, FLIP_HORIZONTAL: 0.0,\n ROTATION: 0.0, SALT_AND_PEPPER: 0.0,\n SHEAR: 0.0}\n\n for i, element in enumerate(pic):\n\n # Extract each component\n path, idx_src, idx_class = element\n\n # Call the function\n try:\n img_decode, idx_src_new, idx_class_one_hot = parse_test(path, idx_src, idx_class)\n img_transformed, idx_src_new, idx_class_one_hot = \\\n preprocess_test(img_decode, idx_src_new, idx_class_one_hot)\n img, idx_src_new, idx_class_one_hot_new = data_augmentation(img_transformed, idx_src_new, idx_class_one_hot,\n probabilities)\n except:\n print(path)\n\n assert img.dtype == tf.dtypes.float32, \\\n \"Input data type doesn't match\"\n\n assert img.shape == img_transformed.shape, \\\n \"Input shape doesn't match\"\n\n assert np.array_equal(img, img_transformed), \\\n \"Images are not equal\"\n\n assert idx_src_new == idx_src and np.array_equal(idx_class_one_hot_new, idx_class_one_hot), \\\n \"idx_src and/or idx_class_one_hot have been modified\"\n\n if i % 100 == 0 or (i + 1) == NUM_DATA:\n print(\"[test_data_augmentation()]:\", i, \"of\", NUM_DATA)\n\n\ndef test_to_human_output():\n \"\"\"Tests for the function to_human_output()\"\"\"\n\n # Get all the paths\n path_lst, idx_lst, label_lst = get_val_PIC_elements()\n pic = pathlabelidx_lists_to_PIC_format(path_lst, label_lst, idx_lst)\n\n NUM_DATA = len(path_lst)\n for i, element in enumerate(pic):\n\n # Extract each component\n path, idx_src, idx_class = element\n\n # Call the function\n try:\n img_decode, idx_src_new, idx_class_one_hot = parse_test(path, idx_src, idx_class)\n img_transformed, idx_src_new, idx_class_one_hot = \\\n preprocess_test(img_decode, idx_src_new, idx_class_one_hot)\n img_human, class_human = to_human_output(img_transformed, idx_class_one_hot)\n except:\n print(path)\n\n assert tf.reduce_all(tf.equal(img_transformed, img_human)), \\\n \"Image has been modified\"\n\n assert class_human == CONST.CLASSES[idx_class], \\\n \"class_human is not the expected name\"\n\n if i % 100 == 0 or (i + 1) == NUM_DATA:\n print(\"[test_to_human_output()]:\", i, \"of\", NUM_DATA)\n\n\ndef test_build_train_dataset():\n \"\"\"Tests for the function build_train_dataset()\"\"\"\n\n probabilities = {BRIGHTNESS: 0.15, CONTRAST: 0.15, GAMMA: 0.15, HUE: 0.15,\n SATURATION: 0.15, GAUSSIAN_NOISE: 0.15, BLUR: 0.15,\n FLIP_VERTICAL: 0.15, FLIP_HORIZONTAL: 0.25,\n ROTATION: 0.25, SALT_AND_PEPPER: 0.15,\n SHEAR: 0.15}\n\n path_lst, idx_lst, label_lst = get_train_PIC_elements()\n pic = pathlabelidx_lists_to_PIC_format(path_lst, label_lst, idx_lst)\n\n NUM_DATA = len(path_lst)\n\n replications = [1 for _ in range(NUM_DATA)]\n\n # Get the minimum number of element for all classes\n class_idx = [element[2] for element in pic]\n minimum_number_of_elements = min([class_idx.count(idx) for idx in range(len(CONST.CLASSES))])\n num_examples_in_dataset = minimum_number_of_elements * len(CONST.CLASSES)\n\n # Call the function\n BATCH_SIZE = 1\n train_dataset = build_train_dataset(batch_size=BATCH_SIZE,\n num_batches_preloaded=5,\n num_parallel_calls=4,\n allow_repetitions=False,\n probabilities=probabilities,\n replications=replications,\n shuffle=True)\n\n # Test the dataset without repetitions\n expected_shape = [BATCH_SIZE, CONST.HIGH_SIZE, CONST.WIDTH_SIZE, CONST.NUM_CHANNELS_INPUT]\n count = 0\n idx_used = []\n start_time = time.time()\n for img, idx_src, idx_class_one_hot in train_dataset:\n\n\n assert count < num_examples_in_dataset, \\\n \"Images generated are over the expected number: \" + str(count) + \"/\" + str(num_examples_in_dataset)\n\n assert idx_src not in idx_used, \\\n \"Images are repited\"\n idx_used.append(idx_src)\n\n assert idx_src >= 0 and idx_src < NUM_DATA, \\\n \"idx_src has an unexpected value: \" + str(idx_src)\n\n assert idx_class_one_hot.ndim == 2 and idx_class_one_hot.shape[1] == len(CONST.CLASSES), \\\n \"idx_class_one_hot doesn't have the expected shape\"\n\n assert idx_class_one_hot.dtype == tf.dtypes.float32, \\\n \"idx_class_one_hot is not float32\"\n\n assert tf.reduce_sum(idx_class_one_hot) == 1 and idx_class_one_hot[0, pic[idx_src[0]][2]] == 1, \\\n \"idx_class_one_hot is not a correct one-hot vector for the class\"\n\n assert img.ndim == 4, \\\n \"img is not a 4-D tensor\"\n\n assert np.array_equal(img.shape, expected_shape), \\\n \"Image has not the expected shape: \" \\\n + str(img.shape) + \" - \" + str(expected_shape)\n\n assert img.dtype == tf.dtypes.float32, \\\n \"Input data type doesn't match\"\n\n minimum = tf.reduce_min(img)\n maximum = tf.reduce_max(img)\n assert minimum >= 0.0 and maximum <= 1.0 and minimum != maximum, \\\n \"img values are not in [0,1]\"\n\n if count % 500 == 0 or (count + 1) == NUM_DATA:\n elapsed_time = time.time() - start_time\n start_time = time.time()\n print(\"[test_build_train_dataset()]:\", count, \"of\", np.ceil(NUM_DATA/BATCH_SIZE),\"-- Elapsed time:\", elapsed_time)\n\n count += 1\n\n \"\"\"\n # Test the replication (NEED TO COMENT THE SAMPLE INSIDE THE FUNCTION)\n probabilities = {BRIGHTNESS: 0.0, CONTRAST: 0.0, GAMMA: 0.0, HUE: 0.0,\n SATURATION: 0.0, GAUSSIAN_NOISE: 0.0, BLUR: 0.15,\n FLIP_VERTICAL: 0.0, FLIP_HORIZONTAL: 0.0,\n ROTATION: 0.0, SALT_AND_PEPPER: 0.0, SHIFT: 0.0,\n SHEAR: 0.0}\n replications = [2 for _ in range(NUM_DATA)]\n\n # Call the function\n BATCH_SIZE = 1\n train_dataset = build_train_dataset(batch_size=BATCH_SIZE, \n num_batches_preloaded=5, \n num_parallel_calls=4,\n allow_repetitions=False, \n probabilities=probabilities,\n replications=replications,\n shuffle=False)\n count = 0\n for _, _, _ in train_dataset: \n count += 1\n if count % 100 == 0 or (count + 1) == NUM_DATA:\n print(\"[test_build_train_dataset()]:\", count, \"of\", NUM_DATA)\n\n assert count == NUM_DATA*2, \\\n \"Images has not been replicated\"\n \"\"\"\n\n\ndef test_build_val_dataset():\n \"\"\"Tests for the function build_val_dataset()\"\"\"\n\n path_lst, idx_lst, label_lst = get_val_PIC_elements()\n pic = pathlabelidx_lists_to_PIC_format(path_lst, label_lst, idx_lst)\n\n NUM_DATA = len(path_lst)\n\n # Get the minimum number of element for all classes\n\n # Call the function\n BATCH_SIZE = 1\n val_dataset = build_val_dataset(batch_size=BATCH_SIZE, \n num_batches_preloaded=5, \n num_parallel_calls=4)\n\n \n # Test the dataset without repetitions\n expected_shape = [BATCH_SIZE, CONST.HIGH_SIZE, CONST.WIDTH_SIZE, CONST.NUM_CHANNELS_INPUT]\n count = 0\n idx_used = []\n for img, idx_src, idx_class_one_hot in val_dataset: \n\n assert count < NUM_DATA, \\\n \"Images generated are over the expected number: \" + str(count) + \"/\" + str(NUM_DATA)\n\n assert idx_src not in idx_used, \\\n \"Images are repited\"\n idx_used.append(idx_src)\n\n assert idx_src >= 0 and idx_src < NUM_DATA, \\\n \"idx_src has an unexpected value: \" + str(idx_src)\n\n assert idx_class_one_hot.ndim == 2 and idx_class_one_hot.shape[1] == len(CONST.CLASSES), \\\n \"idx_class_one_hot doesn't have the expected shape\"\n \n assert idx_class_one_hot.dtype == tf.dtypes.float32, \\\n \"idx_class_one_hot is not float32\"\n\n assert tf.reduce_sum(idx_class_one_hot) == 1 and idx_class_one_hot[0, pic[idx_src[0]][2]] == 1, \\\n \"idx_class_one_hot is not a correct one-hot vector for the class\"\n\n assert img.ndim == 4, \\\n \"img is not a 4-D tensor\"\n\n assert np.array_equal(img.shape, expected_shape), \\\n \"Image has not the expected shape: \" \\\n + str(img.shape) + \" - \" + str(expected_shape)\n\n assert img.dtype == tf.dtypes.float32, \\\n \"Input data type doesn't match\"\n\n minimum = tf.reduce_min(img)\n maximum = tf.reduce_max(img)\n assert minimum >= 0.0 and maximum <= 1.0 and minimum != maximum, \\\n \"img values are not in [0,1]\"\n\n if count % 100 == 0 or (count + 1) == NUM_DATA:\n print(\"[test_build_val_dataset()]:\", count, \"of\", NUM_DATA)\n\n count += 1\n\n assert count == NUM_DATA, \\\n \"There are not the expected number of elements: \" + str(count) + \"/\" + str(NUM_DATA)\n\n\ndef test_build_test_dataset():\n \"\"\"Tests for the function build_test_dataset()\"\"\"\n\n path_lst, idx_lst, label_lst = get_test_PIC_elements()\n pic = pathlabelidx_lists_to_PIC_format(path_lst, label_lst, idx_lst)\n\n NUM_DATA = len(path_lst)\n\n # Get the minimum number of element for all classes\n\n # Call the function\n BATCH_SIZE = 1\n test_dataset = build_test_dataset(batch_size=BATCH_SIZE, \n num_batches_preloaded=5, \n num_parallel_calls=4)\n\n \n # Test the dataset without repetitions\n expected_shape = [BATCH_SIZE, CONST.HIGH_SIZE, CONST.WIDTH_SIZE, CONST.NUM_CHANNELS_INPUT]\n count = 0\n idx_used = []\n for img, idx_src, idx_class_one_hot in test_dataset: \n\n assert count < NUM_DATA, \\\n \"Images generated are over the expected number: \" + str(count) + \"/\" + str(NUM_DATA)\n\n assert idx_src not in idx_used, \\\n \"Images are repited\"\n idx_used.append(idx_src)\n\n assert idx_src >= 0 and idx_src < NUM_DATA, \\\n \"idx_src has an unexpected value: \" + str(idx_src)\n\n assert idx_class_one_hot.ndim == 2 and idx_class_one_hot.shape[1] == len(CONST.CLASSES), \\\n \"idx_class_one_hot doesn't have the expected shape\"\n \n assert idx_class_one_hot.dtype == tf.dtypes.float32, \\\n \"idx_class_one_hot is not float32\"\n\n assert tf.reduce_sum(idx_class_one_hot) == 1 and idx_class_one_hot[0, pic[idx_src[0]][2]] == 1, \\\n \"idx_class_one_hot is not a correct one-hot vector for the class\"\n\n assert img.ndim == 4, \\\n \"img is not a 4-D tensor\"\n\n assert np.array_equal(img.shape, expected_shape), \\\n \"Image has not the expected shape: \" \\\n + str(img.shape) + \" - \" + str(expected_shape)\n\n assert img.dtype == tf.dtypes.float32, \\\n \"Input data type doesn't match\"\n\n minimum = tf.reduce_min(img)\n maximum = tf.reduce_max(img)\n assert minimum >= 0.0 and maximum <= 1.0 and minimum != maximum, \\\n \"img values are not in [0,1]\"\n\n if count % 100 == 0 or (count + 1) == NUM_DATA:\n print(\"[test_build_test_dataset()]:\", count, \"of\", NUM_DATA)\n\n count += 1\n\n assert count == NUM_DATA, \\\n \"There are not the expected number of elements: \" + str(count) + \"/\" + str(NUM_DATA)\n\n\ndef do_tests():\n \"\"\"Launch all test avaiable in this module\"\"\"\n\n test_get_train_PIC_elements()\n \n test_get_test_PIC_elements()\n\n test_get_val_PIC_elements()\n \n test_pathlabelidx_lists_to_PIC_format()\n\n test_replicate_PIC_list_by_number_of_replication()\n \n test_get_sample_by_class_from_PIC_list()\n\n test_parse_train()\n \n test_parse_val()\n \n test_parse_test()\n\n test_preprocess_train()\n\n test_preprocess_val()\n\n test_preprocess_test()\n \n test_to_human_output()\n\n test_data_augmentation()\n\n test_build_train_dataset()\n\n test_build_val_dataset()\n\n test_build_test_dataset()\n\n\n# -----------------------------------------------------------------------------\n# Main\n# -----------------------------------------------------------------------------\nif __name__ == \"__main__\":\n\n # Only launch all tests\n do_tests()\n\n\n# -----------------------------------------------------------------------------\n# Information\n# -----------------------------------------------------------------------------\n\"\"\"\n - For each CSV file there are only two columns: Path and Class name\n - The first row is ignored\n - The class name have be in the variable CONST.CLASSES\n\"\"\"\n\n\n\n","sub_path":"dataset.py","file_name":"dataset.py","file_ext":"py","file_size_in_byte":67820,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"486713611","text":"import tcp\nimport time\n\nserver = tcp.TCP()\n\nserver.listen('127.0.0.1', 5009, timeout=1)\n\nfor i in range(0, 10):\n time.sleep(1)\n if server.isConnected:\n break\n\nfor i in range(0, 10):\n server.get()\n\nserver.close()\n","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":228,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"167972938","text":"import datetime\nfrom essentials_kit_management.presenters.presenter_implementation \\\n import PresenterImplementation\nfrom essentials_kit_management.interactors.storages.dtos \\\n import FormDetailsDto, SectionDto, ItemDto, BrandDto\nfrom essentials_kit_management.constants.enums import StatusEnum\n\n\ndef test_get_form_details_response_returns_dict():\n #Assert\n json_presenter = PresenterImplementation()\n form_details_dto = FormDetailsDto(\n form_id=1, form_description='This is snacks form',\n section_dtos=[\n SectionDto(\n section_id=1, form_id=1, product_title='Snack Items',\n product_description='SnacksSec'\n ),\n SectionDto(\n section_id=2, form_id=1, product_title='Biscuits',\n product_description='BiscuitsSec'\n )\n ],\n item_dtos=[\n ItemDto(\n item_id=1, section_id=1, item_name='Navaratna',\n item_description='50 mg'\n ),\n ItemDto(\n item_id=2, section_id=1, item_name='Moong Dal',\n item_description='100 mg'\n )\n ],\n brand_dtos=[\n BrandDto(\n item_id=1, brand_id=1, brand_name='XXXX', item_price=200.0,\n min_quantity=10, max_quantity=20\n ),\n BrandDto(\n item_id=1, brand_id=2, brand_name='YYYY', item_price=100.0,\n min_quantity=5, max_quantity=10\n ),\n BrandDto(\n item_id=1, brand_id=3, brand_name='ZZZZ',\n item_price=100.0, min_quantity=2, max_quantity=20\n )\n ]\n )\n expected_output = {}\n \n #Act\n output = json_presenter.get_form_details_response(form_)\n \n #Assert\n assert output == expected_output\n","sub_path":"essentials_kit_management/tests/presenters/.~c9_invoke_YrgEms.py","file_name":".~c9_invoke_YrgEms.py","file_ext":"py","file_size_in_byte":1844,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"275593758","text":"#!/hpcfs/juno/junogpu/fangwx/python/Python-3.6.6/python \nimport h5py\nimport numpy as np\nfrom keras.models import model_from_json\nfrom keras.models import model_from_yaml\nfrom keras.models import load_model\nfrom keras.models import Model\nimport math\nimport argparse\nimport sys\nsys.path.append('/hpcfs/juno/junogpu/fangwx/FastSim/JUNO/models/')\nfrom ops import roll_fn\nimport tensorflow as tf\n\n\ndef get_parser():\n parser = argparse.ArgumentParser(\n description='Run generator. '\n 'Sensible defaults come from ...',\n formatter_class=argparse.ArgumentDefaultsHelpFormatter\n )\n\n parser.add_argument('--nb-events', action='store', type=int, default=10,\n help='Number of events to be generatored.')\n parser.add_argument('--latent-size', action='store', type=int, default=512,\n help='size of random N(0, 1) latent space to sample')\n parser.add_argument('--output', action='store', type=str,\n help='output file.')\n parser.add_argument('--gen-model-in', action='store',type=str,\n default='',\n help='input of gen model')\n parser.add_argument('--gen-weight-in', action='store',type=str,\n default='',\n help='input of gen weight')\n parser.add_argument('--comb-model-in', action='store',type=str,\n default='',\n help='input of combined model')\n parser.add_argument('--comb-weight-in', action='store',type=str,\n default='',\n help='input of combined weight')\n parser.add_argument('--dis-model-in', action='store',type=str,\n default='',\n help='input of dis model')\n parser.add_argument('--exact-model', action='store',type=bool,\n default=False,\n help='use exact input to generate')\n parser.add_argument('--exact-list', action='store',type=str,\n default='',\n help='exact event list to generate')\n parser.add_argument('--datafile-temp', action='store', type=str,\n help='template file.')\n\n return parser\n\n\nif __name__ == '__main__':\n \n parser = get_parser()\n parse_args = parser.parse_args()\n \n gen_out = parse_args.output\n hf = h5py.File(gen_out, 'w')\n\n ### using generator model ############\n #print('gen model=',parse_args.gen_model_in)\n #gen_model = model_from_yaml(open(parse_args.gen_model_in).read())\n #print('gen weight=',parse_args.gen_weight_in)\n #gen_model.load_weights(parse_args.gen_weight_in)\n\n gen_model = load_model(parse_args.gen_model_in, custom_objects={'tf': tf, 'math':math})\n\n n_gen_images = parse_args.nb_events\n noise = np.random.normal ( 0 , 1, (n_gen_images, parse_args.latent_size))\n sampled_ptheta = np.random.uniform(0 , 1, (n_gen_images, 1))\n sampled_pphi = np.random.uniform(-1 , 1, (n_gen_images, 1))\n sampled_rtheta = np.random.uniform(0 , 1, (n_gen_images, 1))\n sampled_rphi = np.random.uniform(-1 , 1, (n_gen_images, 1))\n #sampled_r = np.random.uniform(0.99, 1, (n_gen_images, 1))\n sampled_info = np.concatenate((sampled_ptheta, sampled_pphi, sampled_rtheta, sampled_rphi),axis=-1)\n\n if parse_args.exact_model:\n f_info=open(parse_args.exact_list, 'r')\n index_line=0\n for line in f_info:\n (ptheta, pphi, rtheta, rphi) = line.split(',')\n ptheta = float(ptheta.split('=')[-1])/math.pi\n pphi = float(pphi .split('=')[-1])/math.pi\n rtheta = float(rtheta.split('=')[-1])/math.pi\n rphi = float(rphi .split('=')[-1])/math.pi\n print('exact input=', ptheta, ':', pphi, ':', rtheta, ':', rphi)\n sampled_info[index_line, 0]=ptheta\n sampled_info[index_line, 1]=pphi\n sampled_info[index_line, 2]=rtheta\n sampled_info[index_line, 3]=rphi\n index_line = index_line + 1\n if index_line >= n_gen_images:\n print('Error: more than nb_events to produce, ignore rest part')\n break\n f_info.close()\n #############\n d_temp = h5py.File(parse_args.datafile_temp, 'r')\n temp_time_de = np.expand_dims(d_temp['temp1_firstHitTimeByPMT'][0:1], -1)## default and 0\n temp_time_01 = np.expand_dims(d_temp['temp2_firstHitTimeByPMT'][0:1], -1)## 1 and 0\n temp_nPE_de = np.expand_dims(d_temp['temp1_nPEByPMT'][0:1], -1)\n temp_nPE_01 = np.expand_dims(d_temp['temp2_nPEByPMT'][0:1], -1)\n temp_time_de_ = temp_time_de.repeat(n_gen_images,axis=0)\n temp_time_01_ = temp_time_01.repeat(n_gen_images,axis=0)\n temp_nPE_de_ = temp_nPE_de.repeat (n_gen_images,axis=0)\n temp_nPE_01_ = temp_nPE_01.repeat (n_gen_images,axis=0)\n Temps_input = [temp_time_de_, temp_time_01_, temp_nPE_de_, temp_nPE_01_]\n d_temp.close()\n generator_inputs = [noise]+Temps_input+[sampled_info]\n images = gen_model.predict(generator_inputs, verbose=True)\n #### transfer to real parameters ##############################\n actual_info = sampled_info.copy()\n actual_info[:,0] = actual_info[:,0]*math.pi \n actual_info[:,1] = actual_info[:,1]*math.pi \n actual_info[:,2] = actual_info[:,2]*math.pi\n actual_info[:,3] = actual_info[:,3]*math.pi\n #print ('actual_info\\n:',actual_info[0:10])\n\n hf.create_dataset('firstHitTimeByPMT', data=images[0])\n hf.create_dataset('nPEByPMT' , data=images[1])\n hf.create_dataset('infoMuon' , data=actual_info)\n ### using combined model to check discriminator and regression part ############\n if parse_args.comb_model_in !='':\n comb_model = load_model(parse_args.comb_model_in, custom_objects={'tf': tf, 'roll_fn':roll_fn, 'math':math})\n results = comb_model.predict(generator_inputs, verbose=True)\n results[1][:,0] = results[1][:,0]*math.pi\n results[1][:,1] = results[1][:,1]*math.pi\n results[1][:,2] = results[1][:,2]*math.pi\n results[1][:,3] = results[1][:,3]*math.pi\n hf.create_dataset('Disc_fake_real' , data=results[0])\n hf.create_dataset('Reg' , data=results[1])\n if parse_args.dis_model_in:\n dis_model = load_model(parse_args.dis_model_in, custom_objects={'tf': tf, 'roll_fn':roll_fn, 'math':math})\n print('dis summary', dis_model.summary())\n layer_1 = 'lambda_1'\n layer_2 = 'lambda_2'\n intermediate_layer1_model = Model(inputs=dis_model.input, outputs=dis_model.get_layer(layer_1).output)\n intermediate_layer2_model = Model(inputs=dis_model.input, outputs=dis_model.get_layer(layer_2).output)\n dis_input = images \n intermediate_output_1 = intermediate_layer1_model.predict(dis_input)\n intermediate_output_2 = intermediate_layer2_model.predict(dis_input)\n print ('intermediate_output_1 shape:',intermediate_output_1.shape)\n print ('intermediate_output_2 shape:',intermediate_output_2.shape)\n hf.create_dataset('firstHitTimeByPMT_shifted' , data=intermediate_output_1)\n hf.create_dataset('nPEByPMT_shifted' , data=intermediate_output_2)\n ######## for real data check ###########\n hd = h5py.File('/hpcfs/juno/junogpu/fangwx/FastSim/JUNO/data/data_04211_batch0_N5000.h5', 'r')\n n1 = np.expand_dims(hd['firstHitTimeByPMT'], -1)\n n2 = np.expand_dims(hd['nPEByPMT'] , -1)\n n3 = hd['infoMuon'][:,0:4]\n n11 = hd['firstHitTimeByPMT'][0:n_gen_images]\n n21 = hd['nPEByPMT'] [0:n_gen_images]\n n31 = hd['infoMuon'] [0:n_gen_images]\n real_1 = n1 [0:n_gen_images]\n real_2 = n2 [0:n_gen_images]\n real_3 = n3 [0:n_gen_images]\n dis_input_real = [real_1, real_2, real_3] \n intermediate_output_1_real = intermediate_layer1_model.predict(dis_input_real)\n intermediate_output_2_real = intermediate_layer2_model.predict(dis_input_real)\n print ('real intermediate_output_1 shape:',intermediate_output_1_real.shape)\n print ('real intermediate_output_2 shape:',intermediate_output_2_real.shape)\n hf.create_dataset('real_firstHitTimeByPMT_shifted' , data=intermediate_output_1_real)\n hf.create_dataset('real_nPEByPMT_shifted' , data=intermediate_output_2_real)\n hf.create_dataset('real_firstHitTimeByPMT' , data=n11)\n hf.create_dataset('real_nPEByPMT' , data=n21)\n hf.create_dataset('real_infoMuon' , data=n31)\n\n ### save results ############\n hf.close()\n print ('Saved h5 file, done')\n","sub_path":"FastSim/JUNO/generator/generator_v5.py","file_name":"generator_v5.py","file_ext":"py","file_size_in_byte":8715,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"89784043","text":"def main():\n cases = int(input())\n for t in range(cases):\n pattern = [c for c in input()]\n flips = 0\n while '-' in pattern:\n flip(pattern)\n flips += 1\n print(\"Case #\"+str(t+1)+\": \"+str(flips))\n\n\ndef flip(pattern):\n # find the end of the first sequence and invert it\n char = pattern[0]\n end = 0\n while end < len(pattern) and pattern[end] == char:\n pattern[end] = '+' if char == '-' else '-'\n end += 1\n\n\nmain()","sub_path":"codes/CodeJamCrawler/CJ/16_0_2_baki_qb.py","file_name":"16_0_2_baki_qb.py","file_ext":"py","file_size_in_byte":490,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"202168258","text":"import os\nimport sys\n\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\n\nfrom matplotlib import cm\n\n# set plotting style\nimport mycolors\nmcol = mycolors.pub17\nmmark = mycolors.m_styles\nfcol = mycolors.f_colors\nplt.style.use(\"../style_pub17/cloak17_paper.mplstyle\")\n\n# make plot 1\nfig, axs = plt.subplots(2,1,figsize=(6,5),sharex=True)\n\n# mark cloak dimensions\naxs[0].axvline(-2.032, color=mcol[2], linestyle='-',alpha=0.5)\naxs[0].axvline(2.032, color=mcol[2], linestyle='-',alpha=0.5)\n\naxs[1].axvline(-2.032, color=mcol[2], linestyle='-',alpha=0.5)\naxs[1].axvline(2.032, color=mcol[2], linestyle='-',alpha=0.5)\n\n# Compare SC+FM and SC only at 450 mT 'in front of cloak', i.e. 1 cm away\ndf_bvx_cloak_1 = pd.read_csv('data-calib/DATA_MegaVIEW/DataFile_2016-12-09_12-12-19.csv')\ndf_bvx_sc_1 = pd.read_csv('data-calib/DATA_MegaVIEW/DataFile_2016-12-09_15-06-03.csv')\n\n# Compare SC+FM and SC only at 450 mT 'across cloak'\ndf_bvx_cloak_2 = pd.read_csv('data-calib/DATA_MegaVIEW/DataFile_2016-12-09_12-42-47.csv')\ndf_bvx_sc_2 = pd.read_csv('data-calib/DATA_MegaVIEW/DataFile_2016-12-09_15-09-34.csv')\n\n\n#axs[0].set_title(\"B vs X scans, 45 layer SC, fM = 0.618\")\naxs[0].plot( df_bvx_sc_1['x']/10, -1*df_bvx_sc_1['B3']/1000, marker=mmark[1], color=mcol[1], markerfacecolor=fcol[1], label='45-layer SC') \naxs[0].plot( df_bvx_cloak_1['x']/10, -1*df_bvx_cloak_1['B3']/1000, marker=mmark[0], color=mcol[0], markerfacecolor=fcol[0], label='cloak') \naxs[0].set_ylabel(\"$B_T$ (T)\")\n#axs[0].set_ylim((0.375,0.455))\n#axs[0].text(-120,420,'1 cm away')\naxs[0].legend(loc = 'lower left')\n\nselect_bvx_left = df_bvx_sc_2['x'] < -10\nselect_bvx_right = df_bvx_sc_2['x'] > 10\n\naxs[1].plot( df_bvx_sc_2.loc[select_bvx_left,'x']/10,\n -1*df_bvx_sc_2.loc[select_bvx_left,'B3']/1000,\n marker=mmark[1], color=mcol[1], markerfacecolor=fcol[1], label='45-layer SC') \naxs[1].plot( df_bvx_sc_2.loc[select_bvx_right,'x']/10,\n -1*df_bvx_sc_2.loc[select_bvx_right,'B3']/1000,\n marker=mmark[1], color=mcol[1], markerfacecolor=fcol[1], label='45-layer SC') \n\naxs[1].plot( df_bvx_cloak_2['x']/10, -1*df_bvx_cloak_2['B3']/1000, marker=mmark[0], color=mcol[0], markerfacecolor=fcol[0], label='cloak') \naxs[1].set_ylabel(\"$B_T$ (T)\")\naxs[1].set_xlabel(\"position (cm)\")\n#axs[1].set_ylim((0.440,0.485))\n#axs[1].text(-120,470,'across')\n\nplt.savefig(\"plots/eps/cloak_mri_450mT_1d_combined.eps\")\nplt.savefig(\"plots/png/cloak_mri_450mT_1d_combined.png\")\nplt.show()\n","sub_path":"pycloak/cloaking_pub17/cloak_mri_subplots_1d.py","file_name":"cloak_mri_subplots_1d.py","file_ext":"py","file_size_in_byte":2485,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"353264141","text":"from django.shortcuts import render\nfrom rest_framework.response import Response\nfrom rest_framework.permissions import IsAuthenticated, AllowAny\nfrom rest_framework.views import APIView\nfrom rest_framework.decorators import api_view, permission_classes\nfrom portal.serializers import StudentSerializer, TeacherSerializer\nfrom rest_framework.response import Response\nfrom rest_framework import status\nfrom portal.models import User\nfrom django.db import IntegrityError\nfrom rest_framework_simplejwt.tokens import RefreshToken, SlidingToken, UntypedToken, AccessToken\n\n# Create your views here.\n\nclass teacherSignUp(APIView):\n def post(self, request):\n serializer = StudentSerializer(data=request.data)\n if serializer.is_valid():\n try:\n user = serializer.save(is_teacher=True)\n except IntegrityError as e: \n return Response(data=\"Username exists!\")\n\n refresh = RefreshToken.for_user(user)\n access = AccessToken.for_user(user)\n res = {\n \"username\": str(user),\n \"refresh\": str(refresh),\n \"access\": str(access)\n }\n return Response(data=res, status=status.HTTP_201_CREATED)\n else:\n return Response(data=\"Enter valid data.\", status=status.HTTP_400_BAD_REQUEST)\n\nclass studentSignUp(APIView):\n\n def post(self, request):\n serializer = StudentSerializer(data=request.data)\n\n if serializer.is_valid():\n try:\n user = serializer.save(is_student=True)\n except IntegrityError as e:\n return Response(data=\"Username exists!\")\n\n refresh = RefreshToken.for_user(user)\n access = AccessToken.for_user(user)\n res = {\n \"username\": str(user),\n \"refresh\": str(refresh),\n \"access\": str(access)\n }\n return Response(data=res, status=status.HTTP_201_CREATED)\n\n else:\n return Response(data=\"Enter valid data.\", status=status.HTTP_400_BAD_REQUEST)\n\n\nclass student_list(APIView):\n permission_classes = (IsAuthenticated,)\n\n def get(self, request):\n try:\n if(request.user.is_student):\n return Response(\"Students are not allowed to visit this.\")\n all_students = User.objects.filter(is_student=True)\n serializers = StudentSerializer(all_students, many=True)\n return Response(serializers.data)\n except:\n return Response(\"Invalid request\")\n\n def post(self, request):\n try:\n if(request.user.is_student):\n return Response(\"Students are not allowed to visit this.\")\n serializers = StudentSerializer(data=request.data)\n if serializers.is_valid():\n try:\n user = serializers.save(is_student=True)\n except IntegrityError as e: \n return Response(data=\"Username exists!\")\n\n refresh = RefreshToken.for_user(user)\n access = AccessToken.for_user(user)\n res = {\n \"username\": str(user),\n \"refresh\": str(refresh),\n \"access\": str(access)\n }\n return Response(data=res, status=status.HTTP_201_CREATED)\n else:\n return Response(data=\"Enter valid data.\", status=status.HTTP_400_BAD_REQUEST)\n except:\n return Response(\"Invalid request\")\n \n\nclass studentDetail(APIView):\n permission_classes = (IsAuthenticated,)\n def get(self, request):\n user_username = request.user.username\n stud = User.objects.get(username=user_username)\n serializer = StudentSerializer(stud)\n return Response(serializer.data)","sub_path":"portal/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3847,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"314729242","text":"'''\na | 50 | 3 for 130\nb | 30 | 2 for 45\nc | 20\nd | 15\n\nti = total number of item in a category\ndu = discounted units (units at which discounts is available)\nsp = special price\nup = unit price\n'''\n\n#scanning the items\ncartstr = input().upper()\ncart = {k: cartstr.count(k) for k in cartstr}\n\n# AVAIABLE PRODUCTS\nprod = {'A': 50, 'B': 30, 'C': 20, 'D': 15}\n\n# THIS WEEKS DISCOUNT\ndiscounted_items = {\n 'A': {\n 'du': 3,\n 'sp': 130,\n },\n 'B': {\n 'du': 2,\n 'sp': 45,\n }\n}\n\n# CHECK IF PRODUCTED IS DISCOUNTED\ndef is_discounted(key):\n if key in discounted_items:\n return True\n\n# TO GET THE TOTAL PRICE FOR A PROD IF DISCOUNT IS APPLICATBLE\ndef discounted_group_total():\n discounted = ti//du*sp\n normal = (ti % du)*up\n return discounted+normal\n\n\ntotal_price=0\nfor k,v in cart.items(): \n #CHECKING IF WE HAVE A PRICE FOR SCANNED PROD\n if k in prod:\n #CHECKING IF THE PROD IS DISCOUNTED\n if is_discounted(k):\n ti = cart[k]\n up = prod[k]\n sp = discounted_items[k]['sp']\n du = discounted_items[k]['du']\n price = discounted_group_total()\n \n else:\n up = prod[k]\n ti = cart[k]\n price = ti*up\n total_price+=price\n \n else:\n print(\"Product {} is not available\".format(k))\n \n print(\"Item {} | Quantity {}\".format(k,v))\n \nprint(\"Total Price: \", total_price)\n","sub_path":"cart_sol.py","file_name":"cart_sol.py","file_ext":"py","file_size_in_byte":1459,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"98317077","text":"#!/usr/bin/python3\n# file: coroutine_3_生成器_1_fibonacci.py\n# Created by Guang at 19-7-21\n# description:\n\n# *-* coding:utf8 *-*\n\n\ndef create_num(all_num):\n print(\"----1---\")\n # a = 0\n # b = 1\n a, b = 0, 1\n current_num = 0\n while current_num < all_num:\n print(\"----2---\")\n # print(a)\n yield a # 如果一个函数中有yield语句,那么这个就不在是函数,而是一个生成器的模板\n print(\"----3---\")\n a, b = b, a+b\n current_num += 1\n print(\"----4---\")\n\n\n# 如果在调用create_num的时候,发现这个函数中有yield那么此时,不是调用函数,而是创建一个生成器对象\nobj = create_num(10)\n\nret = next(obj)\nprint(ret)\n\nret = next(obj)\nprint(ret)\n\nobj2 = create_num(2) # 创建另外一个生成器对象\n\nret = next(obj2)\nprint(ret)\n\n# for num in obj:\n# print(num)","sub_path":"multitask_coroutine/coroutine_3_生成器_1_fibonacci.py","file_name":"coroutine_3_生成器_1_fibonacci.py","file_ext":"py","file_size_in_byte":878,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"425896886","text":"import nltk\nimport getopt\nimport sys\n\nhelp_msg = '-i -o '\n\n\ntry:\n opts, args = getopt.getopt(sys.argv[1:], \"i:o:\")\nexcept getopt.GetoptError:\n print(help_msg)\n sys.exit(2)\nfor opt, arg in opts:\n if opt == '-h':\n print(help_msg)\n sys.exit()\n elif opt in (\"-i\"):\n input_file_name = arg\n elif opt in (\"-o\"):\n output_file_name = arg\n\n#input_file_name = \"/iesl/canvas/hschang/language_modeling/NSD_for_sentence_embedding/data/raw/wiki2016.txt\"\n#output_file_name = \"temp_POS\"\n#max_line_num = 1000000\n\nf_out = open(output_file_name,'w')\n\nwith open(input_file_name) as f_in:\n total_line_num = 0\n for line in f_in:\n \n line = line.rstrip()\n tokens = line.split()\n if len(tokens) > 0:\n sent_pos = nltk.pos_tag(tokens)\n #print(sent_pos)\n sent, pos = zip(*sent_pos)\n f_out.write(line + '\\t' + ' '.join(pos)+'\\n')\n else:\n f_out.write('\\n')\n total_line_num += 1\n if total_line_num % 10000 == 0:\n sys.stdout.write(str(total_line_num)+' ')\n sys.stdout.flush()\n #if total_line_num > max_line_num:\n # break\n\nf_out.close()\n","sub_path":"src/preprocessing/tools/add_POS_wiki.py","file_name":"add_POS_wiki.py","file_ext":"py","file_size_in_byte":1234,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"155964155","text":"from urllib.request import urlopen\nimport json\nwith urlopen('https://raw.githubusercontent.com/plotly/datasets/master/geojson-counties-fips.json') as response:\n counties = json.load(response)\n\nimport pandas as pd\ndf = pd.read_csv(\"https://raw.githubusercontent.com/plotly/datasets/master/fips-unemp-16.csv\",\n dtype={\"fips\": str})\n\ncolorscale = [\"#f7fbff\", \"#ebf3fb\", \"#deebf7\", \"#d2e3f3\", \"#c6dbef\", \"#b3d2e9\", \"#9ecae1\",\n \"#85bcdb\", \"#6baed6\", \"#57a0ce\", \"#4292c6\", \"#3082be\", \"#2171b5\", \"#1361a9\",\n \"#08519c\", \"#0b4083\", \"#08306b\"\n]\n\nimport plotly.express as px\nimport plotly.graph_objs as go\nfrom plotly.graph_objs import *\nimport chart_studio.plotly as py\nimport plotly.offline as offline\nimport data_loader as dl\nimport numpy as np\n\n\nPOP = dl.load_data('fips_populations.obj')\nFLOW = dl.load_data('FLOW2.obj')\nFLOW+=1\ncountyf = dl.load_data('fips_county.obj')\nidx_dict = dl.load_data('idx_dict2.obj')\nN = np.array(list(POP.values()))\nT=10\nS = np.zeros([N.shape[0],T+1])\nS[:,0] = N.__copy__()\n\nI = np.zeros(S.shape)\nR = np.zeros(S.shape)\nx = np.zeros(S.shape)\ny = np.zeros(S.shape)\nii = np.arange(0,len(S))\nnp.random.shuffle(ii)\n\n# CREATE RANDOM INFECTION SEEDS\n\n# I[ii[0:50], 0] = np.random.randint(0,10,50)\nn_seeds = 50\ntot = np.sum(N)\ncdf = np.cumsum(N/tot)\nU = np.random.rand(n_seeds)\nii = [np.argmin(np.abs(U[i] - cdf)) for i in range(len(U))]\npct = 0.0001*np.random.rand(n_seeds)\ninfected = np.int32(N[ii] * pct)\nI[ii,0] = infected\n\n# gamma=np.linspace(0.8, 1.0, T)\n# beta =np.linspace(1.2, 0.8, T)\n# alpha = np.linspace(0.9, 0.2, T)\n#\ngamma = 0.8 * np.ones(T)\nbeta = 0.9 * np.ones(T)\nalpha = 0.8 * np.ones(T)\n\nfor t in range(T):\n x[:,t] = I[:,t]/N\n y[:,t] = S[:,t]/N\n S[:,t+1] = S[:,t] - (beta[t]*S[:,t]*I[:,t])/N - (alpha[t] * S[:,t] * np.dot(FLOW, beta[t] * x[:,t]))/(N + np.sum(FLOW, axis=0))\n # S[:,t+1] = np.max([np.zeros(S[:,t+1].shape), S[:,t+1]])\n I[:,t+1] = I[:,t] + (beta[t]*S[:,t]*I[:,t])/N + (alpha[t] * S[:,t] * np.dot(FLOW, beta[t] * x[:,t]))/(N + np.sum(FLOW, axis=0)) - gamma[t]*I[:,t]\n # I[:, t + 1] = np.max([np.zeros(I[:, t + 1].shape), I[:, t + 1]])\n R[:,t+1] = R[:,t] + gamma[t]*I[:,t]\n # R[:, t + 1] = np.max([np.zeros(R[:, t + 1].shape), R[:, t + 1]])\n print(sum(N))\n\n\ndata_slider = []\n\ncolorbar=dict(tickvals = [-1,0,1,2,3,4,5],\n ticktext = ['0', '1', '10', '100', '1000', '10k','100k'])\nfor t in range(T):\n\n data_each_yr = dict(\n type='choropleth',\n geojson=counties,\n locations=list(countyf.keys()),\n z=np.max([np.log10(I[:, t] + 1e-1), -1 * np.ones(I[:, t].shape)], axis=0),\n colorbar=colorbar,\n colorscale='Jet',\n locationmode='geojson-id'\n )\n\n data_slider.append(data_each_yr)\n\nsteps = []\nfor i in range(len(data_slider)):\n step = dict(method='restyle',\n args=['visible', [False] * len(data_slider)],\n label='Day {}'.format(i))\n step['args'][1][i] = True\n steps.append(step)\n\nsliders = [dict(active=0, pad={\"t\": 1}, steps=steps)]\n\nlayout = dict(title ='Virus cases', geo=dict(scope='usa',\n projection={'type': 'albers usa'}),\n sliders=sliders)\n\nfig = dict(data=data_slider, layout=layout)\n# fig = dict(data=data_slider)\noffline.plot(fig)\n#\n# fig = px.choropleth(df, geojson=counties, locations='fips', color='unemp',\n# color_continuous_scale=\"Viridis\",\n# range_color=(0, 12),\n# scope=\"usa\",\n# labels={'unemp':'unemployment rate'}\n# )\n# fig.update_layout(margin={\"r\":0,\"t\":0,\"l\":0,\"b\":0})\n# fig.show()","sub_path":"map_generate.py","file_name":"map_generate.py","file_ext":"py","file_size_in_byte":3678,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"431507765","text":"import numpy as np\nimport matplotlib.pyplot as plt\nimport matplotlib.lines as mlines\nfrom PIL import Image\nimport sys\nimport random\nimport pickle\n\nfrom keypoint_detector import detect_keypoints\n\n# match features from img1 (P1) and img2 (P2), based on descriptor size l and ratio r\ndef match_features(img1, P1, img2, P2, l, r):\n matches = []\n size = int((l - 1)/2)\n\n for idx1, p1 in enumerate(P1):\n best_err = np.Inf\n best_pair = None\n second_err = np.Inf\n second_pair = None\n for idx2, p2 in enumerate(P2):\n # for each lxl img descriptor, compare each pixel, take total squared err\n err = 0\n for i in range(-size, size+1):\n for j in range(-size, size+1):\n pxl1 = get_pixel(img1, p1, i, j)\n pxl2 = get_pixel(img2, p2, i, j)\n err += (pxl1 - pxl2)**2\n # keep track of best matching err\n if (err < best_err):\n second_err = best_err\n second_pair = best_pair\n best_err = err\n best_pair = [p1, p2]\n elif (err < second_err):\n second_err = err\n second_pair = [p1, p2]\n # if difference between error is greater than ratio r, add to feature matches\n # print('best err:', best_err, second_err)\n if (best_err < second_err * r):\n matches.append(best_pair)\n return matches\n\n# get pixel value at [x+i, y+j] or nearest pixel\ndef get_pixel(img, pt, i, j):\n height, width = img.shape\n x,y = pt\n i += x\n j += y\n if i < 0:\n i = 0\n elif i >= height:\n i = height-1\n if j < 0:\n j = 0\n elif j >= height:\n j = width-1\n return img[i,j]\n\n\n#############################################################################\n############################## MAIN ###############################\n#############################################################################\n\n# import image and convert to grayscale\nimg1 = plt.imread('class_photo1.jpg')\nimg1 = img1.mean(axis=2)\nw1, h1 = img1.shape\n\nimg2 = plt.imread('class_photo2.jpg')\nimg2 = img2.mean(axis=2)\nw2, h2 = img2.shape\n\n# # get keypoints\n# print('detecting keypoints...')\n# P1 = detect_keypoints(img1)\n# P2 = detect_keypoints(img2)\n#\n# # save keypoints to file\n# print('keypoints detected. Saving...')\n# keypoints = [P1, P2]\n# keypoints_file = open('keypoints.pkl', 'wb')\n# pickle.dump(keypoints, keypoints_file)\n# keypoints_file.close()\n\n# # load keypoints from file\n# print('loading keypoints...')\n# keypoints_file = open('keypoints.pkl', 'rb')\n# keypoints = pickle.load(keypoints_file)\n# P1,P2 = keypoints\n#\n# # print('KEYPOINTS (img1): \\n', P1)\n# # print('KEYPOINTS (img2): \\n', P2)\n#\n# # descriptor size\n# l = 21\n# # required ratio of best-to-secondbest [suggested 0.5-0.7]\n# r = 0.5\n#\n# # get feature matches\n# print('getting matches...')\n# matches = match_features(img1, P1, img2, P2, l, r)\n#\n# # save matches to file\n# matches_file = open('matches.pkl', 'wb')\n# pickle.dump(matches, matches_file)\n\n# load matches from file\nprint('loading keypoints...')\nmatches_file = open('matches.pkl', 'rb')\nmatches = pickle.load(matches_file)\n\n# print('NUM MATCHES', len(matches))\n# print('MATCHES: \\n', matches)\n\nimg_pair = np.column_stack((img1, img2))\nplt.imshow(img_pair, cmap='gray')\n\n# plt.scatter(0, 0, c='r')\n# plt.scatter(h1, w1, c='r')\n# plt.scatter(h1+h2, w2, c='r')\n\nfor match in matches:\n x1,y1 = match[0]\n x2,y2 = match[1]\n y2 += h1\n plt.scatter(y1,x1, c='r')\n plt.scatter(y2,x2, c='b')\n plt.plot([y1,y2], [x1,x2], 'g--')\nplt.show()\n","sub_path":"feature_matching.py","file_name":"feature_matching.py","file_ext":"py","file_size_in_byte":3656,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"129529150","text":"import pandas as pd\nfrom sklearn.preprocessing import StandardScaler\n\ndef scaler(X_test):\n df = pd.read_csv('C:/Users/acer/Desktop/Web App/data/heart.csv')\n X = df.iloc[:,:-1]\n scaler = StandardScaler()\n X_scale = scaler.fit_transform(X)\n X_test_scale = scaler.transform(X_test)\n \n return X_test\n\n\n\n","sub_path":"DataTransformation.py","file_name":"DataTransformation.py","file_ext":"py","file_size_in_byte":320,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"350690535","text":"#!/usr/bin/python3\n\n'''\nURI Online Judge | 1099\nSum of Consecutive Odd Numbers II\n\nRead an integer N that is the number of test cases. Each test case is a line containing two\ninteger numbers X and Y. Print the sum of all odd values between them, not including X and Y.\n\nInput: The first line of input is an integer N that is the number of test cases that follow.\nEach test case is a line containing two integer X and Y.\nOutput: Print the sum of all odd numbers between X and Y.\n\n'''\n\nnum_casos = int(input())\nswitch = 1 #Iterator: 1=True. 0 for False.\nintervalo = []\n\naccumulator = [] \n#IMUTÁVEL. guarda os itens atuais de intervalo e reseta na próxima iteração\nsomatorio = 0 #variável somatório\n#IMUTÁVEL. recebe os ímpares\n\n\nguardador = []\n\nfor i in range(num_casos):\n\taccumulator = [] #IMUTÁVEL\n\tsomatorio = 0 #IMUTÁVEL\n\n\twhile switch == 1:\n\t\tintervalo.append([int(x) for x in input().split(' ')])\n\t\t#print(intervalo)\n\t\tbreak\n\n\tfor i in intervalo[len(intervalo)-1]: #retorna o ultimo index da lista e percorre a sublista:\n\t\taccumulator.append(i)\n\n\twhile (accumulator[0] > accumulator[1]):\n\t\tfor i in range(accumulator[1]+1,accumulator[0]): \n\t\t#o -1 no accumulador[0] torna ESSA SITUAÇÃO DE START, maiorque STOP, excludente.\n\t\t#o -1 no STEP faz com que a lista seja percorrida ao contrário, daí ela executa\n\t\t\twhile i % 2 != 0: #faz com que apenas numeros impares sejam retornados\n\t\t\t\tsomatorio += i\n\t\t\t\t#guardador.append(somatorio)\n\t\t\t\t#print(\"[0]>[1]\".format(i))\n\t\t\t\tbreak\n\t\tguardador.append(somatorio)\n\t\tbreak\n\n\n\t#somatorio=0\n\t\n\twhile accumulator[0] < accumulator[1]:\n\t\tfor i in range(accumulator[0]+1, accumulator[1]):\n\t\t\twhile i % 2 != 0:\n\t\t\t\tsomatorio += i\n\t\t\t\t#guardador.append(somatorio)\n\t\t\t\t#print(\"[1]>[0]\".format(i))\n\t\t\t\tbreak\n\t\tguardador.append(somatorio)\n\t\tbreak\n\t\n\n\twhile (accumulator[0] == accumulator[1]):# or (accumulator[0] < accumulator[1]):\n\t\tguardador.append(0)\n\t\tbreak\n\t\t#for i in range(accumulator[1],accumulator[0]): \n\t\t#o -1 no accumulador[0] torna ESSA SITUAÇÃO DE START, maiorque STOP, excludente.\n\t\t#o -1 no STEP faz com que a lista seja percorrida ao contrário, daí ela executa\n\t\t'''\n\t\t\twhile i % 2 == 0: #faz com que apenas numeros impares sejam retornados\n\t\t\t#somatorio += i\n\t\t\t#guardador.append(somatorio)\n\t\t\t#print(\"[0]>[1]\".format(i))\n\t\t\tbreak\n\t\t'''\n\t#print(\"Somatorio={}\".format(somatorio), end=' ')\n\n\t#print(\"{}\".format(guardador))\n\nfor i in guardador:\n\tprint(i)\n\n'''\nfor i in range(num_casos):\n\tfor x in range(len(accumulator)):\n\t\tfor index in range(len(accumulator[x])):\n\t\t\tprint(accumulator[x][index])\n\n'''","sub_path":"URI-VOAL/1099_2.py","file_name":"1099_2.py","file_ext":"py","file_size_in_byte":2565,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"181778054","text":"from django.conf.urls import include, url\nfrom django.contrib import admin\nfrom . import views\n\nurlpatterns = [\n url(r'^$', views.index_page, name='index_page'),\n url(r'^admin/', include(admin.site.urls)),\n url(r'^news/', include('news.urls', namespace=\"news\")),\n url(r'^account/', include('account.urls', namespace=\"account\")),\n url(r'^list/', include('category.urls', namespace=\"category\"))\n\n]\n","sub_path":"testme/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":411,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"454201457","text":"from math import sqrt, floor\nimport numpy as np\nfrom forces import f_pp\n\nkT = 4.11 * 10 ** (-21)\nD_T = 0.1\ndt = 0.001\nD_R = 0.1\nppType = 'WCA'\nepsilon = 10 ** (-18)\ndrag_N_sPum = kT / D_T * 10 ** 6\n\nradius = 1;\nBoxX = 200\nIntRange = 2 * radius * 2 ** (1 / 6)\nBoxY = 100\nNumberOfParticles = 2\n\ncoordsForRunning = np.array([[0, 199.5, 50, 0, 0.5, 50], [0, 0, 0, 0, 0, 0]])\n\nsigma = 2 * radius\nLcx = int(floor(BoxX / IntRange)) # Number of x cells, # BoxX is Region[0] in the original script;\nLcy = int(floor(BoxY / IntRange)) # Number of y cells, BoxY is Region[1] in the original script;\nIntRange_cx = BoxX / Lcx # edge in um of x cell. rc[0] in original script\nIntRange_cy = BoxY / Lcy # edge in um of y cell. rc[1] in original script\nlscl = np.zeros(NumberOfParticles, np.float_)\ncell_array_head = np.zeros((Lcx, Lcy),\n np.float_) # array with all cells. Will point to the first particle in each cell.\n# noise: initial noise for first 10000 steps\nx_noises_um = sqrt(2 * D_T * dt) * np.random.randn(10000, NumberOfParticles) + 0\ny_noises_um = sqrt(2 * D_T * dt) * np.random.randn(10000, NumberOfParticles) + 0\np_noises = sqrt(2 * D_R * dt) * np.random.randn(10000, NumberOfParticles) + 0\njo = 0\njn = 1\ni = 1;\n# Run over timesteps\ncell_array_head[:, :] = np.nan\nlscl[:] = np.nan\nfor particle in range(NumberOfParticles):\n # Build linked cell list for timestep i, to be used for inter-particle forces\n # http://cacs.usc.edu/education/cs596/01-1LinkedListCell.pdf\n X_cell_ind = int(floor(coordsForRunning[\n jo, particle * 3 + 1] / IntRange_cx)) # find x coordinate of the cell that contains the particle\n Y_cell_ind = int(floor(coordsForRunning[\n jo, particle * 3 + 2] / IntRange_cy)) # find y coordinate of the cell that contains the particle\n # link the previous occupant of the cell to the new. On the first iteration, the previous is empty\n lscl[particle] = cell_array_head[X_cell_ind, Y_cell_ind]\n # the new one goes to the top of the list, to the header:\n cell_array_head[X_cell_ind, Y_cell_ind] = particle\n # print(X_cell_ind, Y_cell_ind)\nLcx=89\nLcy=44\n\nfor X_cell_ind in range(Lcx):\n for Y_cell_ind in range(Lcy):\n # scan neighboring cells for each cell (including itself: X_cell_ind, Y_cell_ind)\n for X_cell_nn_ind in (X_cell_ind - 1,X_cell_ind, X_cell_ind + 1):\n for Y_cell_nn_ind in (Y_cell_ind - 1,Y_cell_ind, Y_cell_ind + 1):\n if ((Y_cell_ind == 21)&(X_cell_ind == 88)&(X_cell_nn_ind == 89)&(Y_cell_nn_ind == 21)):\n print('sdf')\n # skip if Y_cell_nn_ind is out of bounds, since these are outside of the box.\n if ((Y_cell_nn_ind >= 0) & (Y_cell_nn_ind < Lcy)): # -1 and Lcy are Out of bounds\n # periodic boundary conditions in x\n y_shift = 0\n x_shift = 0\n X_cell_nn_ind_use = 0+ X_cell_nn_ind\n if X_cell_nn_ind_use == -1: # out of bounds\n X_cell_nn_ind_use += Lcx\n x_shift = BoxX ######## changed sign\n if X_cell_nn_ind_use == Lcx: # out of bounds\n X_cell_nn_ind_use -= Lcx\n x_shift = -BoxX ######## changed sign\n # Scan first particle in cell X_cell_ind, Y_cell_ind\n l = (cell_array_head[X_cell_ind, Y_cell_ind])\n # scan all the particles in cell X_cell_ind, Y_cell_ind\n while ~np.isnan(l):\n # scan particle m in neighboring cell (including in cell X_cell_ind, Y_cell_ind)\n m = (cell_array_head[X_cell_nn_ind_use, Y_cell_nn_ind])\n while ~np.isnan(m):\n # m=int(m)\n if (l < m): # avoid double counting.\n # Get coordinates x and y.\n x_l = coordsForRunning[jo, int(l * 3 + 1)]\n x_m = coordsForRunning[jo, int(m * 3 + 1)]\n y_l = coordsForRunning[jo, int(l * 3 + 2)]\n y_m = coordsForRunning[jo, int(m * 3 + 2)]\n # Shift due to periodic conditions:\n x_lm = x_l - (x_m - x_shift)\n y_lm = y_l - (y_m - y_shift)\n r_lm_sqrd = x_lm ** 2 + y_lm ** 2\n if r_lm_sqrd < IntRange ** 2:\n # compute forces on pair (l,m):\n Force_X, Force_Y = f_pp((x_l, y_l), (x_m, y_m), epsilon, IntRange, radius,\n ppType=ppType, x_shift=x_shift,\n y_shift=y_shift) # will also shift due to periodic conditions\n print(Force_X,l,m)\n coordsForRunning[jn, int(l * 3 + 1)] += Force_X / drag_N_sPum * dt\n coordsForRunning[jn, int(l * 3 + 2)] += Force_Y / drag_N_sPum * dt\n coordsForRunning[jn, int(m * 3 + 1)] -= Force_X / drag_N_sPum * dt\n coordsForRunning[jn, int(m * 3 + 2)] -= Force_Y / drag_N_sPum * dt\n # apply periodic boundary conditions on updated particles- X axis ONLY.\n for int_prtcls in [l, m]:\n # if coordsForRunning[jn,int(int_prtcls*3+1)]<0:\n # coordsForRunning[jn,int(int_prtcls*3+1)]+=BoxX\n # if coordsForRunning[jn,int(int_prtcls*3+1)]>BoxX:\n # coordsForRunning[jn,int(int_prtcls*3+1)]-=BoxX\n # Useful warning flag on out of bounds cases. However, will not work with python2 and Numba. Wors in python3.\n if ((coordsForRunning[jn, int(int_prtcls * 3 + 2)] > BoxY) | (\n coordsForRunning[jn, int(int_prtcls * 3 + 2)] < 0)):\n print(i, 'y: ', coordsForRunning[jo, int(int_prtcls * 3 + 2)], 'x: ',\n coordsForRunning[jo, int(int_prtcls * 3 + 1)], 'r: ',\n sqrt(r_lm_sqrd), 'Y translation', Force_Y / drag_N_sPum * dt,\n 'X translation', Force_X / drag_N_sPum * dt, 'Particle', int_prtcls,\n 'Lcx', X_cell_nn_ind, X_cell_ind, 'X_shift', x_shift)\n # WarningStr=('timestep='+str(i)+' translationY_um= '+str(TranslationY_um)+\n # 'um. r_lm= '+ str(r_lm)+'g='+ str(g)+\n # 'y_12= '+ str(y_12)+'x_12= '+ str(x_12)+\n # 'epsilon'+ str(epsilon)+'drag_N_sPum'+str(drag_N_sPum)+\n # 'dt', str(dt))\n # print(WarningStr)\n m = lscl[int(m)] # get the next particle in the neighboring cell.\n l = lscl[int(l)] # get the next particle in X_cell_ind, Y_cell_ind cell.\n","sub_path":"tmp2.py","file_name":"tmp2.py","file_ext":"py","file_size_in_byte":7675,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"201769504","text":"from worker import *\n\nworker_connection: None\n\n## Used for testing handler ##\n\n\nclass FakeConn(object):\n\n bytes_buffer = None\n recv_buffer = b\"\"\n\n def send(self, x):\n self.bytes_buffer = x\n\n def setRecv(self, x):\n self.recv_buffer = x\n\n def recv(self, ln):\n output = self.recv_buffer[:ln]\n self.recv_buffer = self.recv_buffer[ln:]\n return output\n\n\ndef test_connectionClass():\n global worker_connection\n worker_connection = WorkerConnection(8969)\n\n assert worker_connection != None\n\n\ndef test_handler_auth():\n conn = FakeConn()\n\n # Send Auth\n conn.setRecv(b\"AUTH\")\n worker_connection._handle(conn, (\"0.0.0.0\", 8888), exec_always=False)\n\n assert conn.bytes_buffer != None\n\n # Send GET\n conn.setRecv(b\"GET\")\n worker_connection._handle(conn, (\"0.0.0.0\", 8888), exec_always=False)\n\n # No tasks should exist\n assert conn.bytes_buffer == b\"NOTASKS \"\n\n\n \n","sub_path":"backend/dispatcher/test_worker.py","file_name":"test_worker.py","file_ext":"py","file_size_in_byte":939,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"115158385","text":"from cs50 import get_string, get_int\nfrom sys import exit, argv\nfrom math import inf\n\nMAX_VOTERS = 100\nMAX_CANDIDATES = 9\n\n\nclass Candidate():\n def __init__(self, name, votes, eliminated):\n self.name = name\n self.votes = votes\n self.eliminated = eliminated\n\ncandidates = []\n\n\ndef main():\n\n # Check for invalid usage\n if len(argv) < 2:\n print(\"Usage: python runoff [candidate ...]\")\n exit(1)\n\n global candidate_count\n candidate_count = len(argv) - 1\n\n # Populate candidates dictionary\n if candidate_count > MAX_CANDIDATES:\n print(f\"Maximum number of candidates is {MAX_CANDIDATES}\")\n exit(2)\n\n for name in argv[1:]:\n candidate = Candidate(name, 0, False)\n candidates.append(candidate)\n\n global voter_count\n voter_count = get_int(\"Number of voters: \")\n if voter_count > MAX_VOTERS:\n print(f\"Maximum number of voters is {MAX_VOTERS}\")\n exit(3)\n\n # Initialize global preferences list\n global preferences\n preferences = []\n for i in range(voter_count):\n preferences.append([])\n for j in range(candidate_count):\n preferences[i].append(0)\n\n # Keep querying for votes\n for i in range(voter_count):\n\n # Query for each rank\n for j in range(candidate_count):\n name = get_string(f\"Rank {j + 1}: \")\n\n # Record vote, unless it's invalid\n if not vote(i, j, name):\n print(\"Invalid vote.\")\n exit(4)\n\n print()\n\n # Keep holding runoffs until winner exists\n while True:\n tabulate()\n\n # Check if election has been won\n won = print_winner()\n\n if won:\n break\n\n # Eliminate last-place candidates\n min_votes = find_min()\n tie = is_tie(min_votes)\n\n # If tie, everyone wins\n if tie:\n for candidate in candidates:\n if (not candidate.eliminated):\n print(candidate.name)\n break\n\n # Eliminate anyone with a minimum number of votes\n eliminate(min_votes)\n\n # Reset vote counts back to zero\n for candidate in candidates:\n candidate.votes = 0\n\n\n# Record preference if vote is valid\ndef vote(voter, rank, name):\n # TODO\n return False\n\n\n# Tabulate votes for non-eliminated candidates\ndef tabulate():\n # TODO\n return\n\n\n# Print the winner of the election, if there is one\ndef print_winner():\n # TODO\n return False\n\n\n# Return. the minimum number of votes any remaining candidate has\ndef find_min():\n # TODO\n return 0\n\n\n# Return True if the election is tied between all candidates\ndef is_tie(min_votes):\n # TODO\n return False\n\n\n# Eliminate the candidate (or candidates) in last place\ndef eliminate(min_votes):\n # TODO\n return\n\n\nif __name__ == \"__main__\":\n main()\n","sub_path":"distro/runoff.py","file_name":"runoff.py","file_ext":"py","file_size_in_byte":2873,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"598233742","text":"import fnmatch\nimport random\nimport sys\nimport time\nfrom functools import partial\nfrom multiprocessing import Pool\nfrom os.path import join, isdir, isfile, dirname, basename\n\nimport numpy as np\nfrom astropy.io import fits\nfrom astropy.modeling import models, fitting\nfrom ccdproc import cosmicray_lacosmic\nfrom dateutil.parser import parse\n\nfrom DirSearch_Functions import search_all_fits\nfrom constants import log, ModHDUList, natural_keys, find_dates, find_val, get_calibrations\nfrom constants import server_destination, find_dimensions, filter_fits\nfrom dirs_mgmt import validate_dirs\n\n# Fitter/Models\n_of = fitting.LinearLSQFitter()\npoly_model = models.Polynomial1D(3)\n\n\ndef find_imgtype(filepath_header, filename=None, ext=0, median_opt=False):\n \"\"\"\n Only for calibration files!!. Find the image type (flats,darks,bias)\n :param filepath_header: this must be the full address to file, or the header of the file\n :param filename: the file name. Only actually used when filepath_header is a header object\n :param ext: Optional, extension header to which check info\n :param median_opt: if True, this function will allow super calibration files to pass the test\n :return: the image type, returns None if image is not a calibration file\n \"\"\"\n mylist = [\"FLAT\", \"ZERO\", \"BIAS\", \"DARK\", \"BLANK\"]\n bias_labels = [\"ZERO\", \"BLANK\"]\n # Check object header\n option1 = find_val(filepath_header, \"object\", ext, raise_err=False).upper()\n # Check image type header\n option2 = find_val(filepath_header, \"imagety\", ext, raise_err=False).upper()\n # Check filename\n if isinstance(filepath_header, str):\n option3 = filename = basename(filepath_header).upper()\n else:\n if filename is None:\n option3 = filename = ''\n else:\n option3 = filename.upper()\n # a fourth one... make sure you're not getting an already median file\n option4 = True if median_opt else (\"MEDIAN\" not in filename.upper()) or (\"MEAN\" not in filename.upper())\n mylist2 = [option1, option2, option3]\n for key in mylist:\n # this loop checks for all options and see if there is a match\n truth_func = any([key in key2 for key2 in mylist2])\n if truth_func and option4:\n if key in bias_labels:\n return \"BIAS\"\n return key\n else:\n return None\n\n\ndef find_gain(filepath_header, namps=1):\n \"\"\"\n Assumes gain keys are in primary header are in order for amplifier\n :param filepath_header: filepath or header of FITS file\n :param namps: number of amplifiers\n :return: list with gains per amplifier in the order of amplifier\n \"\"\"\n hrd = get_header(filepath_header)\n comms = hrd.comments\n # HERE GAIN KEYS WILL BE IN ORDER, SO WE ASSUME GAIN KEYWORDS\n # HAVE SOME SORT OF ORDERING\n # Create filtering function for invalid gain values\n\n def filter_function(x):\n return 'GAIN' in x.upper() and ('VID' not in x.upper() and 'VIDEO' not in comms[x].upper())\n\n # filter and sort gain keywords\n gain_keys = sorted(filter(filter_function, hrd.keys()), key=natural_keys)\n # now with this order, get gains\n gains = [float(hrd[key]) for key in gain_keys if hrd[key]]\n if len(gains) == namps:\n return gains\n else:\n return None\n\n\ndef find_rdnoise(filepath_header, namps=1):\n \"\"\"\n Assumes read noise keys are in primary header are in order for amplifier\n :param filepath_header: filepath or header of FITS file\n :param namps: number of amplifiers\n :return: list with read noises per amplifier in the order of amplifier\n \"\"\"\n hrd = get_header(filepath_header)\n # filter and sort gain keywords\n rdnois_keys = sorted(filter(lambda x: 'RDNOIS' in x.upper(), hrd.keys()), key=natural_keys)\n # now with this order, get read noises\n rdnoises = [float(hrd[key]) for key in rdnois_keys if hrd[key]]\n if len(rdnoises) == namps:\n return rdnoises\n else:\n return None\n\n\ndef get_data(image, ext=0) -> np.ndarray:\n if isinstance(image, str):\n return fits.getdata(image, ext=ext)\n elif isinstance(image, fits.HDUList):\n return image[ext].data\n else:\n return image[ext]\n\n\ndef get_header(filename_hdu, ext=0):\n \"\"\"\n Get header from filepath of FITS file or HDUList object.\n :param filename_hdu: filepath to file (string) or HDUList object\n :param ext: extension; default [0]\n :return: return the header\n \"\"\"\n if isinstance(filename_hdu, fits.Header):\n header = filename_hdu\n else:\n with fits.open(filename_hdu) as hdul:\n header = hdul[ext].header\n return header\n\n\ndef get_secs(hdu: fits.ImageHDU, as_ref=False):\n # Return BIASSEC & DATASEC as numpy index.\n # Return DATASEC ONLY if BIASSEC doesn't exist.\n # Return None if neither keyword is found\n hdr = hdu.header\n naxis1 = find_val(hdr, 'NAXIS1')\n naxis2 = find_val(hdr, 'NAXIS2')\n if 'BIASSEC' in hdr:\n biassec = hdr['BIASSEC'].replace(':', ',').strip('][').split(',')\n else:\n biassec = None\n\n if 'DATASEC' in hdr:\n datasec = hdr['DATASEC'].replace(':', ',').strip('][').split(',')\n else:\n datasec = None\n\n # If neither exist, return None\n if not datasec and not biassec:\n return None\n elif datasec and not biassec:\n # FITS slice format -> Numpy slice format\n x1, x2, y1, y2 = [int(c) for c in datasec]\n x1, y1 = x1 - 1, y1 - 1\n\n # This indicates CAHA/CASSINI-LIKE FORMAT\n if y2 < y1 or x2 < x1 or x1 == x2:\n x1, y1, x2, y2 = [int(c) for c in datasec]\n\n # This indicates the slice is actually the whole image!\n whole_im = y2 - y1 == naxis2 and x2 - x1 == naxis1\n\n if not as_ref and whole_im:\n return np.s_[:, :]\n else:\n return np.s_[y1:y2, x1:x2]\n else:\n # Both exist!\n x1, x2, y1, y2 = [int(c) for c in datasec]\n x1, y1 = x1 - 1, y1 - 1\n\n # Indicates CAHA/CASSINI-LIKE FORMAT\n if y2 < y1 or x2 < x1:\n x1, y1, x2, y2 = [int(c) for c in datasec]\n\n # This indicates the slice is actually the whole image!\n whole_im = y2 - y1 == naxis2 and x2 - x1 == naxis1\n\n # If dataslice is the whole image then there can't be bias, return!\n if not as_ref and whole_im:\n return np.s_[:, :]\n\n # At this point I assume both dataslice and biaslice will be non-zero slices.\n dataslice = np.s_[y1:y2, x1:x2]\n\n x1, x2, y1, y2 = [int(c) for c in biassec]\n x1, y1 = x1 - 1, y1 - 1\n if y2 < y1 or x2 < x1:\n # Indicates CAHA/CASSINI-LIKE FORMAT\n x1, y1, x2, y2 = [int(c) for c in biassec]\n\n biasslice = np.s_[y1:y2, x1:x2]\n return dataslice, biasslice\n\n\ndef overscan_sub(hdul) -> ModHDUList:\n \"\"\"\n Subtract overscan region of frame\n \"\"\"\n hdul = ModHDUList(hdul)\n exts = len(hdul)\n trimmed_hdul = hdul.copy()\n for i in range(exts):\n if hdul[i].data is None:\n continue\n secs = get_secs(hdul[i])\n if isinstance(secs[0], tuple):\n dataslice, biasslice = secs\n bias = hdul[i].data[biasslice]\n axis = 0 if bias.shape[1] > bias.shape[0] else 1\n oscan = np.median(bias, axis=axis, overwrite_input=True)\n yarr = np.arange(len(oscan))\n # noinspection PyTypeChecker\n oscan = _of(poly_model, yarr, oscan)\n oscan = oscan(yarr)\n if axis == 1:\n oscan = np.reshape(oscan, (oscan.size, 1))\n else:\n oscan = np.reshape(oscan, (1, oscan.size))\n trimmed_hdul[i].data = hdul[i].data[dataslice] - oscan\n elif secs and secs != np.s_[:, :]:\n dataslice = secs\n trimmed_hdul[i].data = hdul[i].data[dataslice]\n return trimmed_hdul\n\n\ndef get_best_comb(telescope: str, date: str, *kinds, bins=None,\n filt=None, twilight=True, ndims=None, ret_none=False):\n \"\"\"\n Function to get best calibration file for a dataset of given types.\n This will return a file per each kind, in the same order as kinds.\n These files are the combined calibrations images.\n\n :param telescope: telescope for which to get calibration files\n :param date: date for which to find best cal\n :param kinds: any of types; FLAT, DARK, BIAS\n :param bins: bins to match calibration file with\n :param filt: filter to match calibration file with, only needed for flats\n :param twilight: whether twilight images are allowed.\n :param ndims: dimensions of dataset; tuple-like: (X, Y) OR (NAXIS1, NAXIS2)\n :param ret_none: if true, function will return if no such calibration file is found; otherwise it will raise Err.\n \"\"\"\n assert bins is not None, 'The parameter bins must be passed to match files'\n if 'FLAT' in kinds and filt is None:\n log('Warning. Using get_best_cal for FLAT file without passing filt arg.')\n log('Results may vary.')\n\n telescope = telescope.upper()\n date = parse(date)\n cals = []\n comb_tree = get_calibrations(telescope, combined=True)\n for kind in kinds:\n kind = kind.upper()\n root_dir = join(server_destination, 'COMBINED', telescope, kind)\n root_join = lambda *paths: join(root_dir, *paths)\n\n # Get all dates\n str_dates = list(comb_tree[kind])\n\n # Get all images!\n images = []\n for dt in str_dates:\n # Get full path to images\n imgs = map(lambda img: root_join(dt, img), comb_tree[kind][dt])\n images.append(list(imgs))\n\n # Decide filtering function for compatibility\n args = (twilight, bins, filt) if filt is not None and kind == 'FLAT' else (bins,)\n args = (args + (ndims,)) if ndims is not None else args\n check_func = lambda img: check_comp(img, *args)\n\n # filter out incompatible dates\n comps = [list(map(check_func, imgs)) for imgs in images]\n comp_dates = [str_dates[i] for i in range(len(comps)) if any(comps[i])]\n\n # get absolute differences from given date\n dates = [parse(dt) for dt in comp_dates]\n diff_dates = [abs(dt - date) for dt in dates]\n\n # if diff_dates is empty ==> No such calibration files, then return None\n if not diff_dates:\n if ret_none:\n log('No %s calibration files were found for %s, skipping...' % (kind, telescope))\n cals.append(None)\n continue\n else:\n raise ValueError('No compatible calibration files were found.')\n\n # find date closest to working date\n indx = diff_dates.index(min(diff_dates))\n best_date = comp_dates[indx]\n\n # We now must grab the compatible file in the best_date\n indx_orig = str_dates.index(best_date)\n indx_comp = comps[indx_orig].index(True)\n best_cal = images[indx_orig][indx_comp]\n\n cals.append(best_cal)\n\n # Return one object if only one kind was given.\n if len(cals) == 1:\n return cals[0]\n else:\n return cals\n\n\ndef _imcombine_help(im_list):\n \"\"\"\n Helper function that aids the imcombine functions for the calibration images.\n :param im_list: list of FITS path files\n \"\"\"\n # Find date for which to we're getting data\n date = find_dates(im_list[0])[0]\n\n log('Stacking data!')\n start = time.time()\n # Trim image and apply overscan subtraction if supported.\n images = [overscan_sub(ModHDUList(im, in_mmem=True)) for im in im_list]\n end = time.time() - start\n if end > 5.:\n log('Data stacking took %.3f secs' % end)\n\n # We assume binning and dimensions are the same across images.\n bins = 1 if 'CASSINI' in im_list[0] else find_val(images[0], \"bin\")\n ndims = find_dimensions(images[0])\n return images, date, bins, ndims\n\n\ndef _normalize_exptimes(images, all_exptime=None) -> list:\n \"\"\"\n Function that will normalize all given images using a randomly chosen exposure time from the list.\n This will only be done if images do vary in time exposure.\n :param images: list of ModHDULists\n :return: list of normalized ModHDULists\n \"\"\"\n if not all_exptime:\n all_exptime = [find_val(im, 'exptime') for im in images]\n if len(set(all_exptime)) > 1:\n log(\"Exposure time of darks varies, applying normalizing method\")\n exptime = random.choice(all_exptime)\n\n def normalize(im, exptimed):\n im[0].header['EXPTIME'] = exptime\n return im * exptime / exptimed\n\n images = [normalize(im, exptimed) for im, exptimed in zip(images, all_exptime)]\n return images\n\n\ndef imcombine_bias(*args):\n log('\\nStarting imcombine_darks')\n im_list = args[0]\n assert isinstance(im_list, list), 'Unexpected first positional argument: %r' % im_list\n log('SAMPLE IMAGE INPUT: %s' % im_list[0])\n\n log('Stacking data!')\n start = time.time()\n # Trim image and apply overscan subtraction if supported.\n images = [overscan_sub(ModHDUList(im, in_mmem=True)) for im in im_list]\n end = time.time() - start\n if end > 5.:\n log('Data stacking took %.3f secs' % end)\n\n # Modify args accordingly\n args = (images,) + args[1:]\n\n return imcombine(*args)\n\n\ndef imcombine_darks(*args, telescop=None):\n log('\\nStarting imcombine_darks')\n im_list = args[0]\n assert isinstance(im_list, list), 'Unexpected first positional argument: %r' % im_list\n log('SAMPLE IMAGE INPUT: %s' % im_list[0])\n\n images, date, bins, ndims = _imcombine_help(im_list)\n\n log('Subtracting bias frame')\n bias_im = get_best_comb(telescop, date, 'BIAS', bins=bins, ndims=ndims)\n log('Best BIAS frame found %s' % bias_im)\n bias_hdul = ModHDUList(bias_im)\n images = [hdul - bias_hdul for hdul in images]\n\n # As last step, normalize (if needed) all images to a exposure time; Making sure we combine equivalent darks\n images = _normalize_exptimes(images)\n\n # Modify args accordingly\n args = (images,) + args[1:]\n\n return imcombine(*args)\n\n\ndef imcombine_flats(*args, telescop=None, darks=False):\n log('\\nStarting imcombine_darks')\n im_list = args[0]\n assert isinstance(im_list, list), 'Unexpected first positional argument: %r' % im_list\n log('SAMPLE IMAGE INPUT: %s' % im_list[0])\n\n images, date, bins, ndims = _imcombine_help(im_list)\n all_exptime = [find_val(im, 'exptime') for im in images]\n multi_exptime = len(set(all_exptime)) > 1\n\n if darks:\n log('Subtracting bias/dark frame')\n bias_im, dark_im = get_best_comb(telescop, date, 'BIAS', 'DARK', bins=bins, ndims=ndims)\n log('Best BIAS frame found %s' % bias_im)\n log('Best DARK frame found %s' % dark_im)\n bias_hdul = ModHDUList(bias_im)\n dark_hdul = ModHDUList(dark_im)\n\n exptime_dark = float(find_val(dark_hdul, 'exptime'))\n # Now we must make sure that dark_hdul has same exposure time as all flat images\n if multi_exptime:\n images = [(im - bias_hdul - dark_hdul * exptime / exptime_dark) for im, exptime in zip(images, all_exptime)]\n else:\n exptime = random.choice(all_exptime)\n super_bias = bias_hdul - dark_hdul * exptime / exptime_dark\n images = [im - super_bias for im in images]\n print(f'Reference count for dark_hdul: %r ' % sys.getrefcount(dark_hdul))\n\n else:\n log('Subtracting bias frame')\n bias_im = get_best_comb(telescop, date, 'BIAS', bins=bins, ndims=ndims)\n log('Best BIAS frame found %s' % bias_im)\n bias_hdul = ModHDUList(bias_im)\n images = [hdul - bias_hdul for hdul in images]\n\n print(f'Reference count for bias_hdul: %r' % sys.getrefcount(bias_hdul))\n\n # Now we normalize so that we are combining images of same exposure time\n images = _normalize_exptimes(images)\n\n # And then we normalize them by their mean\n images = [hdul.flatten() for hdul in images]\n\n # Modify args accordingly\n args = (images,) + args[1:]\n\n return imcombine(*args)\n\n\ndef imcombine(images_list: list, root_dir=None, this_type=\"\",\n save_dir=None, combine='median', overwrite=True) -> str:\n \"\"\"\n Warning! This function is quite inefficient with memory handling. Use with caution!\n Function will create a median FITS image retaining all header information and save it, then return\n the filepath to median file.\n :param images_list: list of filepaths to FITS files, or a list of HDULists, or a list of lists\n with data (numpy array) per extension\n :param root_dir: Only Required when given image_list is a list of HDULists or numpy data AND save_dir is not given.\n :param this_type: this isn't required, it simply gives context to the file; stirng is appended to save_path\n :param save_dir: directory path to which save final image\n :param combine: combination method; 'mean' or 'median'\n :param overwrite: whether the final image should be overwritten\n :return: filepath to final image\n \"\"\"\n log('\\nStarting imcombine. Sample:\\n%s' % images_list[0])\n log('Saving to %s' % save_dir)\n\n combine = combine.lower()\n # make sure combine is either 'median' or 'mean'\n assert combine == 'median' or combine == 'mean', 'Incompatible parameter given for \"combine\" argument.'\n\n # find root dir for the given files (it will be used to save the mean_file)\n is_str = isinstance(images_list[-1], str)\n root_dir = dirname(images_list[-1]) if root_dir is None and is_str else root_dir\n save_dir = root_dir if save_dir is None else save_dir\n\n # Make sure these are actual paths\n assert isdir(save_dir) or isdir(root_dir), 'Given root_dir or save_dir are not actual paths!'\n\n # get save path for combined file\n combine_path = join(save_dir, '{}_{}.fits'.format(combine.upper(), this_type))\n\n # check if this file already exist\n exists = isfile(combine_path)\n if exists and not overwrite:\n log('File already exists! Skipping! %s' % combine_path)\n return combine_path\n elif exists and overwrite:\n log('Overwriting combined image: %s' % combine_path)\n\n # Use the last image as template, assumed to be random one, or newest frame\n template_hdul = ModHDUList(images_list[-1], in_mem=True)\n\n # add history/comment that it is a mean file\n template_hdul[0].header.add_history(\"Combined calibration image: \" + combine.upper())\n\n # number of extensions\n exts = len(template_hdul)\n log(\"About to loop over calibration files in imcombine\")\n for i in range(exts):\n if template_hdul[i].data is None:\n continue\n\n log(\"Getting %s for ext #%d\" % (combine, i))\n\n log('Stacking data!')\n start = time.time()\n # Stack data to get median across images for extension-i\n data_list = [get_data(image, i) for image in images_list]\n end = time.time() - start\n if end > 5.:\n log('Data stacking took %.3f secs' % end)\n\n try:\n if combine == 'median':\n template_hdul[i].data = np.median(data_list, axis=0, overwrite_input=True)\n else:\n template_hdul[i].data = np.mean(data_list, axis=0, dtype=np.float32)\n except ValueError as e:\n # This error can be thrown if shape mismatch; make sure this is the reason...\n if 'broadcast' not in e.args[0].lower():\n raise\n\n # get shapes info and update image list\n shapes = [im.shape for im in data_list]\n # the_shape will be the largest shape in shapes; assumed correct one.\n the_shape = sorted(shapes, reverse=True)[0]\n\n # log info\n log('WARNING! Shapes of images are different. Implementing mask for filtering....')\n log('Detection happened for extension #%d' % i)\n log('Chosen shape as correct CCD shape: {}'.format(the_shape))\n\n # modify images_list accordingly\n images_list = [images_list[k] for k in len(images_list) if the_shape == shapes[k]]\n\n # attempt again with modified images_list\n data_list = [get_data(image, i) for image in images_list]\n if combine == 'median':\n template_hdul[i].data = np.median(data_list, axis=0, overwrite_input=True)\n else:\n template_hdul[i].data = np.mean(data_list, axis=0, dtype=np.float32)\n data_list = None\n\n # if 'FLAT' in this_type.upper():\n # # flat tends to have negative values that (may) impact badly...\n # # results may vary!!!\n # template_hdul.interpolate()\n\n template_hdul.writeto(combine_path, overwrite=True)\n template_hdul.close()\n return combine_path\n\n\ndef check_comp(filepath, *args):\n \"\"\"\n Recursive solution to find compatibility of a FITS image against multiple given parameters.\n This function will return True only when attributes of given file match the ones given.\n\n Attributes rules:\n - Binning: A number/string digit must be given\n - Filter: A non-digit string must be given\n - Twilight: A boolean must be given indicating whether you allow twilight flats or not.\n - Dimensions: A tuple/list must be given (X, Y) or (NAXIS1, NAXIS2)\n :param filepath: path to FITS image/file\n :param args: arguments that follow the attribute rules listed above\n :return:\n \"\"\"\n if not args:\n return True\n comp = args[0]\n if comp is True:\n return True and check_comp(filepath, *args[1:])\n elif comp is False:\n # assume we're getting asked about twilight_flats\n # check if it is a twilight_flats\n a = \"twilight\" in filepath.lower()\n b = \"twilight\" in find_val(filepath, \"object\").lower()\n z = a or b\n # this covers whether what happens if we are looking for twilight_flats\n return not z\n elif isinstance(comp, (list, tuple)):\n # assume we're getting asked about dimensions of data\n return find_dimensions(filepath) == comp and check_comp(filepath, *args[1:])\n elif isinstance(comp, (int, float)) or isinstance(comp, str) and all([c.isdigit() for c in comp.split()]):\n # assume we're getting asked about binning of data\n # hardcoded CASSINI exception; no binning keyword in headers\n actual_bin = 1 if 'CASSINI' in filepath else find_val(filepath, \"bin\")\n return str(comp) == str(actual_bin) and check_comp(filepath, *args[1:])\n else:\n # assume we're getting asked about filter\n actual_filter = find_val(filepath, \"filter\", is_str=True)\n return str(comp.upper()) == str(actual_filter.upper()) and check_comp(filepath, *args[1:])\n\n\ndef filter_objects(file_path, *args):\n \"\"\"\n This is only used for target frames!\n Filter out object files using the following attributes:\n \n 'FINAL' keyword in filename (an already calibrated file)\n Object fits has different binning/filter as given\n :param file_path: file path to frame\n :param args: arguments passed to check_comp\n :return: boolean determining whether this is an acceptable target frame\n \"\"\"\n filename = basename(file_path).lower()\n if 'final' in filename or 'calibrated' in filename:\n return False\n elif not check_comp(file_path, *args):\n return False\n elif any([key in filename for key in ['flat', 'zero', 'bias', 'dark']]):\n return False\n else:\n return True\n\n\ndef get_comp_info(obj_address):\n \"\"\"\n This function gets the compatibility parameters for the files from just one (random) file in the\n object file list. This function will also test if data doesn't have rdnoise/gain info.\n :param obj_address: this is the parsed address of the object files.\n :return: a list containing the BIN #, and the filter of the object.\n \"\"\"\n if isfile(obj_address):\n file_name = obj_address\n else:\n file_name = next(search_all_fits(obj_address))\n hdul = ModHDUList(file_name)\n num_amps = len(hdul)\n if num_amps > 1 and hdul[0].data is None:\n num_amps -= 1\n gains = find_gain(hdul[0].header, num_amps)\n rdnoises = find_rdnoise(hdul[0].header, num_amps)\n m = False if gains is None or rdnoises is None else True\n bins = 1 if 'CASSINI' in obj_address else find_val(file_name, \"bin\")\n y = [i for i in bins if i.isdigit()][0] if isinstance(bins, str) else bins\n x = find_val(file_name, \"filter\", is_str=True)\n z = find_val(file_name, \"exptime\")\n comp = [x, y, z, m]\n # log(comp)\n for i in comp[:-1]:\n if not i:\n raise Exception(\"The program could not find the necessary info, this file is not compatible\")\n return comp\n\n\ndef arguments_bd(kind, cals_tree, combs_tree, calpath):\n \"\"\"\n Helper function generator for update_calibrations function.\n\n Arguments function that generates the positional arguments needed\n to compute combination of bias/flats/darks.\n Arguments to yield for imcombine, see imcombine for args overview\n\n This is a helper function for the multiprocessing capability\n of update_calibrations.\n\n :param kind: type target to compute combination: bias/flat/darks\n :param cals_tree: dictionary representing the directory structure of Calibrations folder\n :param combs_tree: dictionary representing the directory structure of Calibrations folder\n :param calpath: calibrations directory folder up to telescope's choice.\n e.g '/home/Data/Calibrations/GUFI'\n :return: yields arguments\n \"\"\"\n kind = kind.upper()\n log('Executed arugments_bd for %s' % calpath)\n log('Looking for %s' % kind)\n\n # Get dates!\n cal_dates = {*cals_tree[kind]}\n comb_dates = {*combs_tree[kind]}\n\n # false positives; date folders that are empty from COMBINED\n false_positives = {date for date in comb_dates if combs_tree[kind][date] == {}}\n # extras; date folders from COMBINED that don't exist in Calibrations folder.\n extras = comb_dates - cal_dates\n # date folders that have more than one image from Calibrated\n true_cal_dates = {date for date in cal_dates if len(cals_tree[kind][date]) > 1}\n\n # missing; dates that need to be combined\n missing = (true_cal_dates - comb_dates | false_positives) - extras\n\n # Let there no mistake that missing are all dates\n missing = fnmatch.filter(missing, '*-*-*')\n\n log('Missing data sets:\\n%r' % (missing,))\n for date in missing:\n # Get rootdir and save dir, then validate\n rootdir = join(calpath, kind, date)\n save_dir = join(calpath.replace('Calibrations', 'COMBINED'), kind, date)\n validate_dirs(save_dir)\n\n # get pathfiles for all FITS in given date\n im_list = [join(rootdir, f) for f in filter_fits(cals_tree[kind][date])]\n imrange = range(len(im_list))\n\n # Get parallel list of bin numbers, and another of image dimensions\n if 'CASSINI' in calpath:\n bin_list = len(im_list) * [1]\n else:\n bin_list = [find_val(im, 'BIN') for im in im_list]\n\n dim_list = [find_dimensions(im) for im in im_list]\n\n # iterate over unique bin numbers!\n for bins in set(bin_list):\n # Check dimensions of this dataset, and make sure they match\n dims = [dim_list[i] for i in imrange if bin_list[i] == bins]\n max_dim = max(dims)\n\n imgs = [im_list[i] for i in imrange if bin_list[i] == bins and max_dim == dim_list[i]]\n imgsrange = range(len(imgs))\n\n if kind == 'FLAT':\n # get all filters of data\n filts = [find_val(im, \"filter\", is_str=True) for im in imgs]\n # iterate over unique filters\n for filt in set(filts):\n flats = [imgs[i] for i in imgsrange if filts[i] == filt]\n yield flats, 'Flats.BIN%d.%s.%s' % (bins, filt, date), save_dir\n else:\n yield imgs, kind + '.BIN%d.%s' % (bins, date), save_dir\n\n\ndef update_calibrations(telescope, method='median', processes=5):\n \"\"\"\n Perform combination of calibration files; bias, flats, darks\n A combination of calibration files is performed per date.\n :param telescope: telescope for which date to perform\n :param method: method to use for image combinations\n :param processes:\n \"\"\"\n global arg_wrapper\n assert method == 'median' or method == 'mean', 'Attribute method must be \"mean\" or \"median\"'\n log('\\nUpdating calibration data for %s' % telescope)\n\n # get calibrations folder for selected telescope\n cals = join(server_destination, 'Calibrations', telescope)\n comb = join(server_destination, 'COMBINED', telescope)\n\n # create directories for calibration files,\n validate_dirs(join(comb, 'FLAT'), join(comb, 'BIAS'), join(comb, 'DARK'))\n\n # get directory tree of telescope's calibrations\n cals_tree, combs_tree = get_calibrations(telescope, both=True)\n\n # define wrapper for argument generator to complete all args:\n def arg_wrapper(*args):\n args_gen = arguments_bd(*args)\n for images, this_type, save_dir in args_gen:\n yield images, None, this_type, save_dir, method\n\n # check if there are bias, if so perform combinations for bias per date\n if 'BIAS' in cals_tree:\n log('Performing combinations for bias files per date')\n # initialize multiprocessing pool in context manager\n with Pool(processes=processes) as pool:\n args_gen = arg_wrapper('Bias', cals_tree, combs_tree, cals)\n pool.starmap(imcombine_bias, args_gen)\n\n # check if there are darks, if so perform combinations for darks per date\n dark_flag = 'DARK' in cals_tree and len(cals_tree['DARK']) > 0\n if dark_flag:\n log('Performing combinations for darks files per date')\n partial_imcombine = partial(imcombine_darks, telescop=telescope)\n # initialize multiprocessing pool in context manager\n with Pool(processes=processes) as pool:\n args_gen = arg_wrapper('Dark', cals_tree, combs_tree, cals)\n pool.starmap(partial_imcombine, args_gen)\n\n # check if there are flats, if so perform combinations for flats per date\n if 'FLAT' in cals_tree:\n log('Performing combinations for flats files per date')\n partial_imcombine = partial(imcombine_flats, darks=dark_flag, telescop=telescope)\n # initialize multiprocessing pool in context manager\n with Pool(processes=processes) as pool:\n args_gen = arg_wrapper('Flat', cals_tree, combs_tree, cals)\n pool.starmap(partial_imcombine, args_gen)\n\n\ndef find_calibrations(calibrations, filters, bins, central_flag, recycle=False, twi_flat=False, debug=False):\n flats = []\n darks = []\n bias = []\n bias_median = darks_median = flats_median = super_cal_found = False\n\n if debug:\n log(\"Searching and filtering calibration files\")\n\n for filepath in calibrations:\n filename = basename(filepath)\n\n # check binning compatibility\n if not check_comp(filepath, bins):\n if debug:\n log(\"%s Not Compatible\" % filename)\n continue\n if debug:\n log(\"%s Compatible\" % filename)\n\n # check for type; FLAT/DARK/BIAS\n this_imagetype = find_imgtype(filepath)\n\n # check if is recyclable file\n if recycle and central_flag in filename:\n if debug:\n log(\"Super Calibration file found while filtering: %s\" % filename)\n if \"FLAT\" == this_imagetype:\n if check_comp(filepath, filters, twi_flat):\n flats_median = filepath\n elif \"BIAS\" == this_imagetype or \"ZERO\" == this_imagetype:\n bias_median = filepath\n elif \"DARK\" == this_imagetype:\n darks_median = filepath\n super_cal_found = flats_median and bias_median and darks_median\n\n # if we have all median/mean files, then no need to keep looking\n if super_cal_found:\n break\n else:\n continue\n\n # check type and append to corresponding list\n if \"DARK\" == this_imagetype:\n darks.append(filepath)\n continue\n elif \"BIAS\" == this_imagetype or \"ZERO\" == this_imagetype:\n bias.append(filepath)\n continue\n elif \"FLAT\" == this_imagetype:\n if check_comp(filepath, filters, twi_flat):\n flats.append(filepath)\n continue\n\n # if no dark frames, then set flag to False\n darks_flag = super_cal_found or len(darks) > 0\n return bias, flats, darks, bias_median, darks_median, flats_median, darks_flag\n\n\ndef trim_reference_image(image, image2) -> ModHDUList:\n \"\"\"\n Trim HDUList (image) according to reference window of other HDUList (image2)\n :param image: Image to be trimmed: HDUList\n :param image2: Image to use for reference trim section; HDUList\n :returns new_image: New HDUList of trimmed image(s)\n \"\"\"\n # Make sure these are ModHDULists\n image = ModHDUList(image)\n image2 = ModHDUList(image2)\n\n # copy the HDUList\n new_image = image.copy()\n for i in range(len(image)):\n if image[i].data is None:\n continue\n secs = get_secs(image2[i], as_ref=True)\n\n if secs is None:\n continue\n else:\n slc = secs if isinstance(secs[0], slice) else secs[0]\n new_image[i].data = image[i].data[slc]\n return new_image\n\n\ndef last_processing(obj, beta, flats_median, darks_median, bias_median, final_dir):\n \"\"\"\n New processing for images. Now instead of trying to reopen the FITS files in every 'process'\n :param obj: file path to object frame\n :param beta: normalizing value for dark frames ==> OBJ_EXPTIME / DARK_EXPTIME\n :param flats_median:\n :param darks_median:\n :param bias_median:\n :param final_dir:\n :return:\n \"\"\"\n filename = obj.split('/')[-1]\n this_filename = \"Calibrated_\" + filename\n log(\"Calibrating object frame: %s\" % filename)\n save_to_path = join(final_dir, this_filename)\n # Proceed with calibration!\n obj_image = overscan_sub(ModHDUList(obj))\n\n # Trim images as needed; if dimensios of obj_image are the same as calibrations, then nothing changes\n bias_im = trim_reference_image(bias_median, obj_image)\n if darks_median:\n super_bias = bias_im + trim_reference_image(darks_median, obj_image) * beta\n else:\n super_bias = bias_im\n\n final_image = (obj_image - super_bias) / trim_reference_image(flats_median, obj_image)\n # Perform cosmic ray removal...\n final_image = cosmic_ray(final_image)\n # try to get rid of infs/nans/zeroes\n final_image.interpolate()\n final_image[0].header.add_history(\"Calibrated Image: Bias subtracted, Flattened, and Cosmic Ray Cleansed\")\n final_image.writeto(save_to_path, overwrite=True)\n final_image.close()\n\n\ndef cosmic_ray(hdul):\n \"\"\"\n Cosmic Ray Removal function. Assumes gain/rdnoise info in headers.\n :param hdul: HDUList\n :return: new HDUList\n \"\"\"\n num_amps = len(hdul)\n if num_amps > 1 and hdul[0].data is None:\n num_amps -= 1\n gains = find_gain(hdul[0].header, num_amps)\n rdnoises = find_rdnoise(hdul[0].header, num_amps)\n kwargs = {'sigclip': 4.5, 'objlim': 6, 'gain': 2., 'readnoise': 6.,\n 'sepmed': True, 'cleantype': \"idw\", \"verbose\": False}\n if gains is None:\n gains = np.ones(num_amps) * 2.\n if rdnoises is None:\n rdnoises = np.ones(num_amps) * 6.\n\n amp_count = 0\n for i in range(len(hdul)):\n if hdul[i].data is None:\n continue\n # update keywords\n kwargs['gain'] = gains[amp_count]\n kwargs['readnoise'] = rdnoises[amp_count]\n\n data = hdul[i].data\n newdata, mask = cosmicray_lacosmic(data, **kwargs)\n hdul[i].data = newdata / gains[amp_count]\n amp_count += 1\n hdul[0].header.add_history('LaPlacian Cosmic Ray removal algorithm applied')\n hdul[0].header.add_history(f'Read Noise used: {rdnoises}')\n hdul[0].header.add_history(f'Gain used: {gains}')\n return hdul\n\n\nif __name__ == '__main__':\n sample = join(server_destination, 'RAW/CAHA/LP_412-31/2018-09-22/MPIA_0220.fits')\n bias = join(server_destination, 'Calibrations/CAHA/BIAS/2018-09-22/MPIA_0013.fits')\n\n hdul = ModHDUList(sample)\n bias_im = ModHDUList(bias)\n\n slcs = get_secs(hdul[0])\n","sub_path":"cal_data.py","file_name":"cal_data.py","file_ext":"py","file_size_in_byte":36494,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"165987917","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Wed Jan 16 10:55:38 2019\r\n\r\n@author: J554696\r\n\"\"\"\r\n\r\nimport numpy as np\r\nimport pandas as pd\r\nimport matplotlib.pyplot as plt\r\nimport seaborn as sns\r\nimport os\r\nfrom nltk import word_tokenize\r\nimport re\r\nfrom langdetect import detect\r\nfrom nltk.corpus import stopwords\r\nfrom nltk.stem import WordNetLemmatizer\r\n\r\n\r\n\r\ndef generalize_ratings(df):\r\n reviews_rating = [1.0 , 2.0 , 3.0 , 4.0 , 5.0]\r\n temp = []\r\n for i , row in df.iterrows():\r\n \r\n rating = row['reviews.rating']\r\n \r\n if rating not in reviews_rating:\r\n temp.append('T')\r\n else:\r\n temp.append('F')\r\n \r\n df['Flag'] = temp \r\n df.drop(df[df['Flag'] == 'T'].index, axis = 0, inplace = True)\r\n df.drop('Flag' , axis = 1, inplace = True)\r\n \r\n return df\r\n\r\ndef sentiment(rating):\r\n \r\n if rating >=4:\r\n sent = 'positive'\r\n else:\r\n sent = 'negative'\r\n \r\n return sent\r\n\r\ndef import_pos_neg_corpus():\r\n lexicon_path = \"C:\\\\Users\\\\J554696\\\\Desktop\\\\Sentiment Analysis\\\\Rahul_Data_exploration\\\\\"\r\n negative_file = os.path.join(lexicon_path,\"neg_words.txt\")\r\n positive_file = os.path.join(lexicon_path,\"pos_words.txt\")\r\n \r\n negative_corpus = [word.strip('\\n') for word in open(negative_file).readlines()]\r\n positive_corpus = [word.strip('\\n') for word in open(positive_file).readlines()]\r\n \r\n return negative_corpus , positive_corpus\r\n\r\ndef tokenize(text):\r\n temp= []\r\n lemmatizer = WordNetLemmatizer() \r\n word_list = word_tokenize(text)\r\n for word in word_list:\r\n temp.append(lemmatizer.lemmatize(word))\r\n return temp\r\n\r\ndef find_count(token):\r\n token = [word.lower() for word in token ]\r\n negative_corpus , positive_corpus = import_pos_neg_corpus()\r\n negative_words_count = len(list(set(token) & set(negative_corpus)))\r\n positive_words_count = len(list(set(token) & set(positive_corpus)))\r\n \r\n positive_words = list(set(token) & set(positive_corpus))\r\n negative_words = list(set(token) & set(negative_corpus))\r\n \r\n return negative_words_count,positive_words_count, positive_words , negative_words\r\n\r\ndef length_range(length):\r\n \r\n if length <= 50:\r\n return 50\r\n elif (length > 50 and length <= 100) :\r\n return 100\r\n elif (length > 100 and length <= 150) :\r\n return 150\r\n elif (length > 150 and length <= 200) :\r\n return 200\r\n elif (length > 200 and length <= 250) :\r\n return 250\r\n else:\r\n return 300\r\n\r\ndef check_Upper_Words(tokens):\r\n upper_words = [word for word in tokens if word.isupper()]\r\n upper_words = [word for word in upper_words if word.lower() not in stopwords.words('english')]\r\n return upper_words\r\n\r\ndef check_questions(string):\r\n result = re.findall(r'\\?+',string)\r\n return result\r\n\r\ndef check_exclamations(string):\r\n result = re.findall(r'\\!+',string)\r\n return result\r\n\r\ndef check_fullstop(string):\r\n result = re.findall(r'\\.+',string)\r\n return result \r\n\r\ndef main_handler():\r\n df = pd.read_csv(r'C:\\Users\\J554696\\Desktop\\Sentiment Analysis\\Clean_test.csv')\r\n df.dropna(inplace = True)\r\n df.drop(index = df[df[\"length\"] == \"#NAME?\"].index,inplace = True)\r\n df[\"length\"] = df[\"length\"].astype(\"int\")\r\n df = generalize_ratings(df)\r\n df['Sentiment'] = df['reviews.rating'].apply(sentiment)\r\n \r\n print(df.info())\r\n print(df.head())\r\n \r\n lang = []\r\n for i in df['reviews.text']:\r\n try:\r\n lang.append(detect(i))\r\n except:\r\n lang.append('No Lang')\r\n \r\n \r\n df['Language'] = lang\r\n df.drop(df[df['Language'] != 'en'].index , axis = 0 , inplace = True)\r\n df['Count_QuestionMarks'] = df['reviews.text'].apply(check_questions)\r\n df['Full_Stops'] = df['reviews.text'].apply(check_fullstop) \r\n df['length_range'] = df['length'].apply(length_range)\r\n df['tokenize'] = df['reviews.text'].apply(tokenize)\r\n \r\n df['Negative-Positive-Count'] = df['tokenize'].apply(find_count)\r\n df['Exclamation'] = df['reviews.text'].apply(check_exclamations)\r\n df['Upper_case'] = df['tokenize'].apply(check_Upper_Words)\r\n \r\n neg_count = []\r\n pos_count = []\r\n positive = []\r\n negative = []\r\n for i , j , k , l in df['Negative-Positive-Count']:\r\n try:\r\n neg_count.append(i)\r\n pos_count.append(j)\r\n positive.append(k)\r\n negative.append(l)\r\n except:\r\n neg_count.append(0)\r\n pos_count.append(0)\r\n positive.append(0)\r\n negative.append(0)\r\n \r\n df['Negative-count'] = neg_count\r\n df['positive-count'] = pos_count\r\n df['Positive_words'] = positive\r\n df['Negative_words'] = negative\r\n df.drop('Negative-Positive-Count', axis = 1 , inplace = True)\r\n \r\n \r\n ## Checking if positive or negative words are in Upper case\r\n ## Lemmatization of tokens\r\n \r\n negative_corpus , positive_corpus = import_pos_neg_corpus()\r\n pos_uc_words = []\r\n neg_uc_words = []\r\n for index , row in df.iterrows():\r\n list1 = row['Upper_case']\r\n pos_count = 0\r\n neg_count = 0\r\n \r\n for i in list1:\r\n \r\n if i.lower() in set(positive_corpus):\r\n pos_count+=1\r\n elif i.lower() in set(negative_corpus):\r\n neg_count+=1\r\n \r\n pos_uc_words.append(pos_count) \r\n neg_uc_words.append(neg_count)\r\n \r\n \r\n df['Positive_Upper_case_words'] = pos_uc_words\r\n df['Negative_Upper_case_words'] = neg_uc_words\r\n print(df.head())\r\n \r\nif __name__== \"__main__\":\r\n main_handler()\r\n \r\n","sub_path":"sentiment_Analysis.py","file_name":"sentiment_Analysis.py","file_ext":"py","file_size_in_byte":5734,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"638889808","text":"# autopep8: off\nimport json\nimport utils\n\nfrom django.http import JsonResponse\nfrom django.views import View\n\n\nfrom order.models import OrderStatus, Order, OrderProduct, WishProduct, ViewedProduct\nfrom user.models import User, Address\nfrom product.models import Product, ProductOption\n\n# Create your views here.\n\n# Add to cart\nclass CartView(View):\n\n # @utils.signin_decorator\n def post(self, request):\n try:\n data = json.loads(request.body)\n user_id = request.user.id\n chosen_products = data['chosen_product']\n\n target_cart, flag = Order.objects.get_or_create(user_id=user_id,\n order_status_id=1)\n target_options = [chosen_products[i][\"product_option_id\"]\n for i in range(0, len(chosen_products))]\n\n for option in target_options:\n if OrderProduct.objects.filter(order=target_cart.id,\n product_option=option).exists():\n\n return JsonResponse(\n {'message': 'ALREADY_EXISTS'},\n status=409)\n\n target_products = [ProductOption.objects.get(id=target_options[i]).product_id\n for i in range(0, len(target_options))]\n\n target_amount = [chosen_products[i]['amount']\n for i in range(0, len(chosen_products))]\n\n for j in range(0, len(target_options)):\n OrderProduct(\n product_amount=target_amount[j],\n order_id=target_cart.id,\n product_id=target_products[j],\n product_option_id=target_options[j]\n ).save()\n\n return JsonResponse(\n {\"message\": \"PRODUCT_ADDED\"},\n status=201\n )\n\n except KeyError:\n return JsonResponse(\n {\"message\": \"KEY_ERROR\"},\n status=400\n )\n\n # @utils.signin_decorator\n def get(self, request):\n user_id = request.user.id\n target_order = Order.objects.get(user=user_id, order_status=1)\n products_in_cart = [products for products in Order.objects.get(\n user=user_id, order_status=1\n ).orderproduct_set.all().values()]\n\n product_in_cart = [products['product_id']\n for products in products_in_cart]\n product_option_in_cart = [products[\"product_option_id\"]\n for products in products_in_cart]\n\n product_name_list = [Product.objects.get(id=p_id).name\n for p_id in product_in_cart]\n product_thumbnail_list = [Product.objects.get(id=p_id).thumb_nail\n for p_id in product_in_cart]\n product_bodycolor_list = [ProductOption.objects.get(id=p_id).body_color.name\n for p_id in product_option_in_cart]\n product_price_list = [Product.objects.get(id=p_id).price\n for p_id in product_in_cart]\n product_plusprice_list = [ProductOption.objects.get(id=p_id).plus_price\n for p_id in product_option_in_cart]\n product_company_list = [Product.objects.get(id=p_id).company\n for p_id in product_in_cart]\n\n list_per_product = []\n for i in range(0, len(products_in_cart)):\n product_price = product_price_list[i] + product_plusprice_list[i]\n product_amount = OrderProduct.objects.get(\n product_option=product_option_in_cart[i],\n order=target_order\n ).product_amount\n total_price = product_amount * product_price\n\n product_detail = {\n \"product_option_id\": product_option_in_cart[i],\n \"product_name\": product_name_list[i],\n \"product_thumbnail\": product_thumbnail_list[i],\n \"product_bodycolor\": product_bodycolor_list[i],\n \"product_price\": product_price,\n \"product_company\": product_company_list[i],\n \"product_amount\": product_amount,\n \"total_price\": total_price\n }\n list_per_product.append(product_detail)\n\n total_sum = 0\n for i in range(0, len(list_per_product)):\n total_sum = total_sum + int(list_per_product[i][\"total_price\"])\n\n return JsonResponse(\n {\"product_detail\": list_per_product,\n \"total_sum\": total_sum},\n status=200\n )\n # change the total amount\n\n @utils.signin_decorator\n def patch(self, request, product_option_id):\n try:\n data = json.loads(request.body)\n user_id = request.user.id\n target_cart = Order.objects.get(user=user_id, order_status=1)\n\n target_product = ProductOption.objects.get(id=product_option_id)\n product_in_cart = OrderProduct.objects.get(\n product_option=product_option_id,\n order=target_cart)\n product_price = (target_product.plus_price\n + Product.objects.get(id=target_product.product_id).price)\n product_in_cart.product_amount = data['amount']\n new_price = product_in_cart.product_amount * product_price\n\n return JsonResponse(\n {\"message\": \"AMOUNT_CHANGED\",\n \"total_price\": new_price},\n status=200\n )\n\n except KeyError:\n return JsonResponse(\n {\"message\": \"KEY_ERROR\"},\n status=400\n )\n\n @utils.signin_decorator\n def delete(self, request, product_option_id):\n user_id = request.user.id\n target_cart = Order.objects.get(user=user_id, order_status=1)\n\n OrderProduct.objects.filter(\n product_option=product_option_id, order=target_cart).delete()\n # to show the remaining items\n target_order = Order.objects.get(user=user_id, order_status=1)\n products_in_cart = [products for products in Order.objects.get(\n user=user_id, order_status=1\n ).orderproduct_set.all().values()]\n\n product_in_cart = [products['product_id']\n for products in products_in_cart]\n product_option_in_cart = [products[\"product_option_id\"]\n for products in products_in_cart]\n\n product_name_list = [Product.objects.get(id=p_id).name\n for p_id in product_in_cart]\n product_thumbnail_list = [Product.objects.get(id=p_id).thumb_nail\n for p_id in product_in_cart]\n product_bodycolor_list = [ProductOption.objects.get(id=p_id).body_color.name\n for p_id in product_option_in_cart]\n product_price_list = [Product.objects.get(id=p_id).price\n for p_id in product_in_cart]\n product_plusprice_list = [ProductOption.objects.get(id=p_id).plus_price\n for p_id in product_option_in_cart]\n product_company_list = [Product.objects.get(id=p_id).company\n for p_id in product_in_cart]\n\n list_per_product = []\n for i in range(0, len(products_in_cart)):\n product_detail = {\n \"product_option_id\": product_option_in_cart[i],\n \"product_name\" : product_name_list[i],\n \"product_thumbnail\": product_thumbnail_list[i],\n \"product_bodycolor\": product_bodycolor_list[i],\n \"product_price\" : product_price_list[i] + product_plusprice_list[i],\n \"product_company\" : product_company_list[i],\n \"product_amount\" : OrderProduct.objects.get(\n product_option=product_option_in_cart[i],\n order=target_order\n ).product_amount\n }\n list_per_product.append(product_detail)\n\n return JsonResponse(\n {\"message\": \"DELETED\",\n \"product_detail\": list_per_product},\n status=200\n )\n\n\n# class CheckoutView(View):\n\n# def patch(self, request, order_id):\n# delivery_address = Address.objects.get(id = data['address_id'])\n# order_status = 2\n\n# target_cart = Order.objects.get(id = order_id)\n# target_cart.address = delivery_address\n# target_cart.order_request = data['request']\n# target_cart.order_status = order_status\n# target_cart.save()\n\n# return JsonResponse(\n# {'message': 'ORDERED'},\n# status=200\n# )\n\n\n# class ShowOrdersView(View):\n# @utils.signin_decorator\n# def get(self, request):\n# data = json.loads(request.body)\n# user_id = request.user.id\n# all_orders = [order for order in Order.objects.filter(user = user_id).values()]\n\n# return JsonResponse(\n# {'order_list': all_orders},\n# status = 200\n# )\n\n\n# class DetailOrderView(View):\n\n# def get(self, request, order_id):\n# ordered_products = [product for product in OrderProduct.objects.filter(order = order_id).values()]\n\n# return JsonResponse(\n# {'product_list':ordered_products},\n# status = 200\n# )\n\n\nclass WishView(View):\n @utils.signin_decorator\n def post(self, request):\n try:\n data = json.loads(request.body)\n user_id = request.user.id\n\n if WishProduct.objects.filter(user=user_id, product=data['product_id']).exists():\n WishProduct.objects.get(\n user=user_id, product=data['product_id']).delete()\n\n return JsonResponse(\n {'message': 'REMOVED'},\n status=200\n )\n\n else:\n WishProduct(\n user_id=user_id,\n product_id=data['product_id']\n ).save()\n\n return JsonResponse(\n {\"message\": \"ADDED_TO_WISHLIST\"},\n status=201\n )\n\n except KeyError:\n return JsonResponse(\n {\"message\": \"KEY_ERROR\"},\n status=400\n )\n\n @utils.signin_decorator\n def get(self, request):\n user_id = request.user.id\n wish_products = [\n product for product in WishProduct.objects.filter(user=user_id).values()]\n wish_product = [products['product_id'] for products in wish_products]\n\n product_name_list = [Product.objects.get(\n id=p_id).name for p_id in wish_product]\n product_thumbnail_list = [Product.objects.get(\n id=p_id).thumb_nail for p_id in wish_product]\n product_price_list = [Product.objects.get(\n id=p_id).price for p_id in wish_product]\n product_company_list = [Product.objects.get(\n id=p_id).company for p_id in wish_product]\n\n list_per_product = []\n for i in range(0, len(wish_products)):\n product_detail = {\n \"product_id\": wish_product[i],\n \"product_name\": product_name_list[i],\n \"product_thumbnail\": product_thumbnail_list[i],\n \"product_price\": product_price_list[i],\n \"product_company\": product_company_list[i]\n }\n\n list_per_product.append(product_detail)\n\n return JsonResponse(\n {'wish_list': list_per_product},\n status=200\n )\n\n @utils.signin_decorator\n def delete(self, request, product_id):\n data = json.loads(request.body)\n user_id = request.user.id\n WishProduct.objects.get(user=user_id, product=product_id).delete()\n\n wish_products = [\n product for product in WishProduct.objects.filter(user=user_id).values()]\n wish_product = [products['product_id'] for products in wish_products]\n\n product_name_list = [Product.objects.get(\n id=p_id).name for p_id in wish_product]\n product_thumbnail_list = [Product.objects.get(\n id=p_id).thumb_nail for p_id in wish_product]\n product_price_list = [Product.objects.get(\n id=p_id).price for p_id in wish_product]\n product_company_list = [Product.objects.get(\n id=p_id).company for p_id in wish_product]\n\n list_per_product = []\n for i in range(0, len(wish_products)):\n product_detail = {\n \"product_id\": wish_product[i],\n \"product_name\": product_name_list[i],\n \"product_thumbnail\": product_thumbnail_list[i],\n \"product_price\": product_price_list[i],\n \"product_company\": product_company_list[i]\n }\n\n list_per_product.append(product_detail)\n\n return JsonResponse(\n {'message': 'DELETED',\n 'product_detail': list_per_product},\n status=204\n )\n\n\nclass RecentlyViewedView(View):\n @utils.signin_decorator\n def post(self, request):\n try:\n data = json.loads(request.body)\n user_id = request.user.id\n view_user = User.objects.get(id=user_id)\n viewed_product = Product.objects.get(id=data['product_id'])\n\n ViewedProduct(\n user=view_user,\n product=viewed_product\n ).save()\n\n return JsonResponse(\n {\"message\": \"ADDED_TO_VIEWED_LIST\"},\n status=200)\n\n except KeyError:\n return JsonResponse(\n {\"message\": \"KEY_ERROR\"},\n status=400\n )\n\n @utils.signin_decorator\n def get(self, request):\n user_id = request.user.id\n viewed_products = ViewedProduct.objects.filter(user=user_id).values()\n product_list = [product for product in viewed_products]\n\n if len(product_list) > 10:\n product_list_ten = product_list[len(product_list)-10:]\n\n else:\n product_list_ten = product_list\n\n print(product_list_ten)\n\n image_list = [Product.objects.get(id=product_list_ten[i]['product_id']).thumb_nail\n for i in range(0, len(product_list_ten))]\n name_list = [Product.objects.get(id=product_list_ten[i]['product_id']).name\n for i in range(0, len(product_list_ten))]\n price_list = [Product.objects.get(id=product_list_ten[i]['product_id']).price\n for i in range(0, len(product_list_ten))]\n\n showing_list = []\n for i in reversed(range(0, len(product_list_ten))):\n product_detail = {\n \"product_image\": image_list[i],\n \"product_name\": name_list[i],\n \"product_price\": price_list[i]\n }\n showing_list.append(product_detail)\n\n return JsonResponse(\n {\"viewed_list\": showing_list},\n status=200\n )\n","sub_path":"order/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":15250,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"628354896","text":"import re\nfrom bs4 import BeautifulSoup\nimport requests\nimport os\nimport sys\nimport pickle\nfrom operator import itemgetter\nfrom itertools import groupby\nfrom unittest import case\nimport pandas as pd\nimport numpy as np\n\n\n# fonction qui prend en parametre les categorie et leurs id et renvoi si oui ou non le mot en question a u pos unique\ndef pos_unique(ids):\n tabPOS = [146889, 171869, 150504, 147628, 171870, 146911, 147826, 212235, 2354314]\n # Ce tableau contient les eid pour adverbe 146889 / adjectif qualificatif 171869 / conjonction de coordination, conjonction de subordination 150504\n # déterminant, 147628\n # nom commun, nom propre, 171870\n # préposition, 146911\n # pronom, 147826\n # verbe. 212235\n # Cela va nous permettre de comparer les eid du tabPos et ceux du tableau_relation afin de déterminer si\n # c'est un pos unique (on ne rencontre qu'un seul elem du tabPOS ou multiple dans le cas contraire\n\n inter = [elt for elt in tabPOS if elt in ids]\n\n return inter\n\n\n# Prend le mot recherché et retourne la categorie gramaticale corespendante au mot, grace au code html correspondant depuis http://www.jeuxdemots.org/rezo-dump et on prendant pour l'instant la relation r_pos telque son poid avec le noeud du mot recercher est maximale.\n\ntableau_noeuds = []\ntableau_relations = []\n\n\ndef extraction(word: str, cache: bool):\n html = requests.get('http://www.jeuxdemots.org/rezo-dump.php?gotermsubmit=Chercher&gotermrel=' + word + '&rel=4')\n encoding = html.encoding if 'charset' in html.headers.get('content-type', '').lower() else None\n soup = BeautifulSoup(html.content, 'html.parser', from_encoding='iso-8859-1')\n texte_brut = soup.find_all('code')\n noeuds = re.findall('[e];[0-9]*;.*', str(texte_brut))\n relations = re.findall('[r];[0-9]*;.*', str(texte_brut))\n if ((not noeuds) and (not relations)):\n print(\"le mot \" + word + \" n'existe pas dans jeux de mots\")\n return None\n\n # print(texte_brut)\n\n for noeud in noeuds:\n tableau_noeuds.append(noeud.split(';'))\n for relation in relations:\n tableau_relations.append(relation.split(';'))\n\n id = []\n i = 0\n while i <= len(tableau_relations) - 1:\n if (int(tableau_relations[i][5]) >= 0):\n id.append(int(tableau_relations[i][3]))\n i += 1\n\n categorie = []\n for N in tableau_noeuds:\n\n if (int(N[1]) in id):\n categorie.append(N[2]);\n\n tableau_noeuds.clear()\n\n inter = pos_unique(id)\n\n # creation du cache pour la toute première fois\n if cache:\n chemin_absolu = os.path.dirname(os.path.abspath(__file__))\n if not os.path.isdir(chemin_absolu + '/cache'):\n try:\n os.mkdir(chemin_absolu + '/cache')\n except OSError:\n print('La création du dossier cache a échoué')\n\n fichier_cache = open(chemin_absolu + '/cache/' + word + '.pkl', 'wb')\n if (len(inter) == 1):\n pickle.dump(categorie[id.index(inter[0])], fichier_cache)\n else:\n result = []\n for x in inter:\n result.append(categorie[id.index(x)])\n pickle.dump(result, fichier_cache)\n fichier_cache.close()\n\n tableau_relations.clear()\n\n if (len(inter) == 1):\n return categorie[id.index(inter[0])]\n else:\n result = []\n for x in inter:\n result.append(categorie[id.index(x)])\n return result\n\n\ndef extraction_cache(word: str, cache: bool):\n chemin_absolu = os.path.dirname(os.path.abspath(__file__))\n if not cache:\n return extraction(word, cache)\n elif cache and (not os.path.isdir(chemin_absolu + '/cache') or not os.path.isfile(\n chemin_absolu + '/cache/' + word + '.pkl')):\n return extraction(word, cache)\n elif cache:\n fichier = open(chemin_absolu + '/cache/' + word + '.pkl', 'rb')\n categorie = pickle.load(fichier)\n fichier.close()\n return categorie\n\n\ndef analyse(phrase: str, cache: bool):\n words = phrase.split(\" \");\n for word in words:\n if (word[len(word) - 1] in ['.', ',', '!', ':', '?', ';']):\n print(word[:-1] + \" :: \")\n print(extraction_cache(str(word[:-1]), cache))\n print(word[len(word) - 1] + \" :: \")\n print(extraction_cache(str(word[len(word) - 1]), cache))\n else:\n print(word + \" :: \")\n print(extraction_cache(str(word), cache));\n\n\nphrase = input(\"Entrez la phrase: \\n\")\ncache = input(\"voulez vous utiliser le cache ? ('T' or 'F'?) \\n\")\nif (cache == 'T'):\n analyse(phrase, True);\nelif (cache == 'F'):\n analyse(phrase, False);\nelse:\n print(\"only: T for 'true' or F for 'false'\");\n exit();\n","sub_path":"oldversion/pos copie.py","file_name":"pos copie.py","file_ext":"py","file_size_in_byte":4738,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"649250319","text":"# -*- coding: utf-8 -*-\n\nfrom iprofile.core.models import ICommand\nfrom iprofile.cli import Create\nfrom iprofile.settings.models import Settings\nfrom tests.utils import set_up\nfrom tests.utils import settings\nfrom tests.utils import tear_down\nimport pytest\n\n\nmock_options = {\n 'profile': 'test'\n}\n\n\ndef test_run_not_implemented_error():\n with pytest.raises(NotImplementedError):\n ICommand()\n\n\ndef test_icommand_check_settings():\n cmd = ICommand(_autorun=False)\n cmd.settings = Settings()\n cmd.settings.clear()\n assert not cmd.check_settings()\n\n\ndef test_icommand_pred():\n assert ICommand(_autorun=False).pred('test') is None\n\n\ndef test_icommand_list_profiles():\n set_up()\n settings.update({\n 'path': 'append_test'\n }).save()\n Create.run(mock_options)\n settings.update({\n 'path': 'iprofiles'\n }).save()\n cmd = ICommand(_autorun=False)\n cmd.settings = settings\n cmd.list_profiles('iprofiles')\n tear_down()\n","sub_path":"tests/test_core/test_models.py","file_name":"test_models.py","file_ext":"py","file_size_in_byte":976,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"65324503","text":"#!/usr/bin/env python\n\nimport caffe\nimport sys\nfrom matplotlib import pyplot as plt\n\nimport numpy as np\nimport os\n\n\ndef main():\n data_path = '..' + os.sep + \"Data\" # This folder holds the csv files\n\n #caffe.set_device(int(sys.argv[1]))\n #caffe.set_mode_gpu()\n\n caffe.set_mode_cpu()\n\n model = 'deploy.prototxt'\n weights = 'snapshot' + os.sep + 'train_iter_10000.caffemodel'\n net = caffe.Classifier(model, weights, caffe.TEST)\n # solver.net.copy_from(weights)\n\n print (\"Net initialized\")\n print('Loading test data...')\n\n x_test = np.loadtxt(data_path + os.sep + \"x_test.csv\",\n delimiter = \",\", skiprows = 1)\n\n print ('Test data loaded')\n print ('Processing data...')\n\n x_test = x_test[:,1:]\n num_genes_test = x_test.shape[0] / 100\n x_test = np.split(x_test, num_genes_test)\n x_test = np.array(x_test)[:, np.newaxis, ...]\n\n # All data in same shape, reshape only once\n net.blobs['data'].reshape(1, *x_test[0].shape)\n\n # Container for results\n results = np.zeros((num_genes_test, 2), dtype=np.float64)\n\n print ('Data processed, start predicting!')\n\n for i, sample in enumerate(x_test):\n net.blobs['data'].data[...] = sample\n res = net.forward()\n result = res['prob'].squeeze()\n results[i, :] = result\n\n print ('Gene expressions predicted!')\n print ('Writing results to file...')\n with open('test_result.csv', 'w') as f:\n f.write('GeneId,Prediction\\n')\n for i in range(results.shape[0]):\n f.write('{:d},{:.6f}\\n'.format(i+1, results[i, 1]))\n print ('Results in file \"test_result.csv\"!')\n\n\nif __name__ == '__main__':\n main()","sub_path":"nn_train/deploy.py","file_name":"deploy.py","file_ext":"py","file_size_in_byte":1680,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"310229712","text":"import csv\nimport sys\nimport re\nimport datetime\n\nMONTH = { 'Jan':1, 'Feb':2, 'Mar':3, 'Apr':4, 'May':5, 'Jun':6, 'Jul':7, 'Aug':8, 'Sep':9, 'Oct':10, 'Nov':11, 'Dec':12 }\n\ndef normalize_date(s):\n m = re.match(r'(\\d+)/(\\d+)/(\\d+)',s)\n if m:\n # slash style\n mon = int(m.group(1))\n day = int(m.group(2))\n yr = int(m.group(3))\n if yr < 100: # short year\n if yr < 50: # assume current century\n yr += 2000\n else: # assume last century\n yr += 1900\n return datetime.datetime(yr,mon,day)\n \n m = re.match(r'(\\d+)-(\\w{3})-(\\d+)',s)\n if m:\n # full abbrv style\n day = int(m.group(1))\n mon = MONTH[m.group(2)]\n yr = int(m.group(3))\n if yr < 100: # short year\n if yr < 50: # assume current century\n yr += 2000\n else: # assume last century\n yr += 1900\n return datetime.datetime(yr,mon,day)\n m = re.match(r'(\\w{3})-(\\d+)',s)\n if m:\n # short abbrv style... Mon-DD?\n # These have ambiguous years. Assume the most recent past\n day = int(m.group(2))\n mon = MONTH[m.group(1)]\n now = datetime.datetime.utcnow()\n ret = datetime.datetime(now.year,mon,day)\n if ret > now:\n ret = datetime.datetime(now.year-1,mon,day)\n return ret\n\ndef process_tag(tagval,asset_tag):\n tagval = tagval.strip()\n (tc,tl) = tagval.split(\":\")\n return \"INSERT into security_tags (level_fk, compartment_fk, asset_fk) SELECT level_pk, compartment_pk, asset_pk FROM sec_levels l,sec_compartments c,assets a WHERE l.abbrv='%s' and c.abbrv='%s' and a.asset_tag=%s;\\n\"%(tl,tc,asset_tag)\n \ndef process_inventory(outf,inf):\n with open(inf) as f:\n data = csv.DictReader(f)\n for r in data:\n # Normalize date\n if not r['intake date']=='':\n r['intake date'] = normalize_date(r['intake date']).isoformat()\n if not r['expunged date']=='':\n r['expunged date'] = normalize_date(r['expunged date']).isoformat()\n # Prep for query gen\n for k in r.keys():\n if k=='compartments':\n pass\n elif r[k]=='':\n r[k]='NULL'\n else:\n r[k]=\"'%s'\"%r[k] # if single quotes are in the data this will fail\n\n # Add the asset, use product as description\n outf.write(\"INSERT INTO assets (asset_tag,description) VALUES (%s,%s);\\n\"%(r['asset tag'],r['product']))\n # Attach the asset to the facility\n # Will fail if there is no preexisting facility record\n outf.write(\"INSERT INTO asset_at (asset_fk,facility_fk,arrive_dt,depart_dt) SELECT asset_pk,facility_pk,%s,%s FROM assets a, facilities f WHERE a.asset_tag=%s and f.fcode=%s;\\n\"%(r['intake date'],r['expunged date'],r['asset tag'],r['fcode']))\n # Attach the asset to its tags\n if not r['compartments']=='':\n for t in r['compartments'].split(','):\n outf.write(process_tag(t,r['asset tag']))\n \n # Add product_fks if there is something sensible to add\n outf.write(\"UPDATE assets SET product_fk=product_pk FROM products p WHERE assets.description=p.product_name;\\n\")\n\ndef main():\n with open('inv_load.sql','w') as f:\n process_inventory(f,sys.argv[1])\n\nif __name__=='__main__':\n main()\n","sub_path":"sql/prep_inv.py","file_name":"prep_inv.py","file_ext":"py","file_size_in_byte":3487,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"219068005","text":"'''\nThis code estimates the number of self-avoding-walks in a 10*10 grid (i.e., N=11)\nIt's for [[UCLA class 202C Monte Carlo methods - homework 1, problem 2]]\nIt applies the first two g(x) design for sampling.\nIt uses the first g(x) design when pstop=0\nAuthor: Shirley Chen (shirleychen@cs.ucla.edu)\n'''\n\nimport numpy as np\nimport time\nfrom saw_helper import tryPath\nfrom saw_helper import update_len_distr\n\nN = 11 # 10*10 grid when N=11\n\nstart = time.time()\n\n# M: sample size\nM_max = 3 * 10 ** 7\nM_set = [10, 50, 100, 500, 1000, 5000, 10000, 50000, 10 ** 5, 5 * 10 ** 5,\n 10 ** 6, 3 * 10 ** 6, 5 * 10 ** 6, 7 * 10 ** 6]\nfor i in range(10 ** 7, M_max + 1, 10 ** 7):\n M_set.append(i)\n\nCount_set = []\nlen_distribution = {}\nlongest_path_x = []\nlongest_path_y = []\n\n# USER SETT\npstop = 0 # early termination rate, set g(x)=0 for first g(x) design\n# END OF USER SET\n\n# different from computing count for every M independently\n# to save time, we only run the maximum M and save the counts in this process\nsum = 0\nn_samples = 0;\ni_next_M = 0;\nwhile n_samples < M_max:\n [inverse_g, path_x, path_y] = tryPath(pstop) # 1/g(xi) = multiplication of kj\n # 1. update path length distribution\n path_len = len(path_x)\n update_len_distr(len_distribution, path_len)\n\n # 2. update the longest path if needed\n if path_len > len(longest_path_x):\n longest_path_x = path_x\n longest_path_y = path_y\n\n # 3. update sum for estimating SAW count\n if inverse_g < 0:\n print(inverse_g)\n sum += inverse_g\n n_samples += 1\n\n # 4. save at the appropriate sample size\n M = M_set[i_next_M] # sample size goal\n if n_samples == M:\n # estimate count\n # print and save\n count = sum / n_samples\n print(\"M:\")\n print(M)\n print(\"count:\")\n print(count)\n\n end = time.time()\n print(\"time:\")\n print(end - start)\n\n with open(\"./result12.txt\", 'a') as fout:\n fout.write(str(M) + \"\\t\")\n fout.write(str(count) + \"\\t\")\n fout.write(str(end - start) + \"\\n\")\n\n with open(\"./len_distribution12.txt\", 'a') as flen:\n flen.write(str(M) + \"\\t\")\n flen.write(str(len_distribution))\n flen.write(\"\\n\")\n\n with open(\"./longest12.txt\", 'a') as fpath:\n fpath.write(str(M) + \"\\t\")\n fpath.write(str(len(longest_path_x)) + \"\\t\")\n fpath.write(str(longest_path_x) + \"\\t\")\n fpath.write(str(longest_path_y) + \"\\n\")\n\n i_next_M += 1\n\nprint(Count_set)\n","sub_path":"saw_design12.py","file_name":"saw_design12.py","file_ext":"py","file_size_in_byte":2555,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"344496424","text":"import os\nimport sys\n\n# -- Path setup --------------------------------------------------------------\n\ndir_path = os.path.dirname(os.path.realpath(__file__)) # directory for conf.py\nsys.path.insert(0,dir_path) # add to Python path\ndoc_path = os.path.dirname(dir_path) # path to docs dir\nroot_path = os.path.dirname(doc_path) # root dir of project\nbuild_path = os.path.join(doc_path, 'build') # doc build directory\n\n# -- Project Info ------------------------------------------------------------\ncopyright = u'2019, CMakePP Team'\nauthor = u'CMakePP Team'\nproject = 'CMakePPCore'\nversion = '1.0.0'\nrelease = '1.0.0alpha'\n\n# -- General configuration ---------------------------------------------------\nhighlight_language = 'cmake'\ntemplates_path = ['.templates']\nsource_suffix = '.rst'\nmaster_doc = 'index'\nlanguage = None\nexclude_patterns = []\npygments_style = 'sphinx'\nhtml_theme = 'sphinx_rtd_theme'\nhtml_static_path = []\nhtmlhelp_basename = project + 'doc'\nextensions = [\n 'sphinx.ext.mathjax',\n 'sphinx.ext.githubpages',\n 'sphinx.ext.autosectionlabel'\n]\n","sub_path":"docs/source/conf.py","file_name":"conf.py","file_ext":"py","file_size_in_byte":1140,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"643144085","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Feb 19 10:57:58 2020\n\n@author: Javier\n\"\"\"\n\nimport PyqtTools.DaqInterface as DaqInt\nimport numpy as np\n\n\n\n# Daq card connections mapping 'Chname':(DCout, ACout)\n\n############################################ Main Board\nMainBoard = ({'Ch01': ('ai0', 'ai8'),\n 'Ch02': ('ai1', 'ai9'),\n 'Ch03': ('ai2', 'ai10'),\n 'Ch04': ('ai3', 'ai11'),\n 'Ch05': ('ai4', 'ai12'),\n 'Ch06': ('ai5', 'ai13'),\n 'Ch07': ('ai6', 'ai14'),\n 'Ch08': ('ai7', 'ai15'),\n 'Ch09': ('ai16', 'ai24'),\n 'Ch10': ('ai17', 'ai25'),\n 'Ch11': ('ai18', 'ai26'),\n 'Ch12': ('ai19', 'ai27'),\n 'Ch13': ('ai20', 'ai28'),\n 'Ch14': ('ai21', 'ai29'),\n 'Ch15': ('ai22', 'ai30'),\n 'Ch16': ('ai23', 'ai31')},\n\n {'Col05': ('line0', 'line1'),\n 'Col06': ('line2', 'line3'),\n 'Col08': ('line4', 'line5'),\n 'Col07': ('line6', 'line7'),\n 'Col02': ('line8', 'line9'),\n 'Col04': ('line10', 'line11'),\n 'Col01': ('line12', 'line13'),\n 'Col03': ('line14', 'line15'),\n 'Col16': ('line16', 'line17'),\n 'Col15': ('line18', 'line19'),\n 'Col13': ('line20', 'line21'),\n 'Col14': ('line22', 'line23'),\n 'Col11': ('line24', 'line25'),\n 'Col09': ('line26', 'line27'),\n 'Col12': ('line28', 'line29'),\n 'Col10': ('line30', 'line31'),\n })\n\n\n############################################ MB4.1\nMB41 = ({'Ch09': ('ai0', 'ai8'),\n 'Ch10': ('ai1', 'ai9'),\n 'Ch11': ('ai2', 'ai10'),\n 'Ch12': ('ai3', 'ai11'),\n 'Ch13': ('ai4', 'ai12'),\n 'Ch14': ('ai5', 'ai13'),\n 'Ch15': ('ai6', 'ai14'),\n 'Ch16': ('ai7', 'ai15'),\n 'Ch01': ('ai16', 'ai24'),\n 'Ch02': ('ai17', 'ai25'),\n 'Ch03': ('ai18', 'ai26'),\n 'Ch04': ('ai19', 'ai27'),\n 'Ch05': ('ai20', 'ai28'),\n 'Ch06': ('ai21', 'ai29'),\n 'Ch07': ('ai22', 'ai30'),\n 'Ch08': ('ai23', 'ai31'),\n },\n\n {'Col10': ('line0', 'line1'),\n 'Col09': ('line2', 'line3'),\n 'Col12': ('line4', 'line5'),\n 'Col11': ('line6', 'line7'),\n 'Col15': ('line8', 'line9'),\n 'Col16': ('line10', 'line11'),\n 'Col13': ('line12', 'line13'),\n 'Col14': ('line14', 'line15'),\n 'Col02': ('line16', 'line17'),\n 'Col01': ('line18', 'line19'),\n 'Col04': ('line20', 'line21'),\n 'Col03': ('line22', 'line23'),\n 'Col07': ('line24', 'line25'),\n 'Col08': ('line26', 'line27'),\n 'Col05': ('line28', 'line29'),\n 'Col06': ('line30', 'line31'),\n },\n )\n\n\n##############################################################################\n\n\nclass ChannelsConfig():\n\n # DCChannelIndex[ch] = (index, sortindex)\n DCChannelIndex = None\n ACChannelIndex = None\n ChNamesList = None\n AnalogInputs = None\n DigitalOutputs = None\n\n # Events list\n DataEveryNEvent = None\n DataDoneEvent = None\n\n ClearSig = np.zeros((1, len(MB41[1])), dtype=np.bool).astype(np.uint8)\n ClearSig = np.hstack((ClearSig, ClearSig))\n\n def _InitAnalogInputs(self):\n print('InitAnalogInputs')\n self.DCChannelIndex = {}\n self.ACChannelIndex = {}\n InChans = []\n index = 0\n sortindex = 0\n for ch in self.ChNamesList:\n if self.AcqDC:\n InChans.append(self.aiChannels[ch][0])\n self.DCChannelIndex[ch] = (index, sortindex)\n index += 1\n print(ch, ' DC -->', self.aiChannels[ch][0])\n print('SortIndex ->', self.DCChannelIndex[ch])\n if self.AcqAC:\n InChans.append(self.aiChannels[ch][1])\n self.ACChannelIndex[ch] = (index, sortindex)\n index += 1\n print(ch, ' AC -->', self.aiChannels[ch][1])\n print('SortIndex ->', self.ACChannelIndex[ch])\n sortindex += 1\n print('Input ai', InChans)\n\n self.AnalogInputs = DaqInt.ReadAnalog(InChans=InChans)\n # events linking\n self.AnalogInputs.EveryNEvent = self.EveryNEventCallBack\n self.AnalogInputs.DoneEvent = self.DoneEventCallBack\n\n def _InitDigitalOutputs(self):\n print('InitDigitalOutputs')\n print(self.DigColumns)\n DOChannels = []\n\n for digc in sorted(self.doColumns):\n print(digc)\n DOChannels.append(self.doColumns[digc][0])\n# DOChannels.append(doColumns[digc][0])\n DOChannels.append(self.doColumns[digc][1])\n print(DOChannels)\n\n# DOChannels = []\n#\n# for digc in self.DigColumns:\n# DOChannels.append(doColumns[digc][0])\n# DOChannels.append(doColumns[digc][1])\n\n self.DigitalOutputs = DaqInt.WriteDigital(Channels=DOChannels)\n\n def _InitAnalogOutputs(self, ChVds, ChVs):\n print('ChVds ->', ChVds)\n print('ChVs ->', ChVs)\n self.VsOut = DaqInt.WriteAnalog((ChVs,))\n self.VdsOut = DaqInt.WriteAnalog((ChVds,))\n\n def __init__(self, Channels, DigColumns,\n AcqDC=True, AcqAC=True,\n ChVds='ao0', ChVs='ao1',\n ACGain=1.1e5, DCGain=10e3, Board='MainBoard'):\n print('InitChannels')\n self._InitAnalogOutputs(ChVds=ChVds, ChVs=ChVs)\n\n self.ChNamesList = sorted(Channels)\n self.AcqAC = AcqAC\n self.AcqDC = AcqDC\n self.ACGain = ACGain\n self.DCGain = DCGain\n print('Board---->', Board)\n if Board == 'MainBoard':\n self.aiChannels = MainBoard[0]\n self.doColumns = MainBoard[1]\n else:\n self.aiChannels = MB41[0]\n self.doColumns = MB41[1]\n\n self._InitAnalogInputs()\n\n self.DigColumns = sorted(DigColumns)\n self._InitDigitalOutputs()\n\n MuxChannelNames = []\n for Row in self.ChNamesList:\n for Col in self.DigColumns:\n MuxChannelNames.append(Row + Col)\n self.MuxChannelNames = MuxChannelNames\n print(self.MuxChannelNames)\n\n if self.AcqAC and self.AcqDC:\n self.nChannels = len(self.MuxChannelNames)*2\n else:\n self.nChannels = len(self.MuxChannelNames)\n\n def StartAcquisition(self, Fs, nSampsCo, nBlocks, Vgs, Vds, **kwargs):\n print('StartAcquisition')\n self.SetBias(Vgs=Vgs, Vds=Vds)\n self.SetDigitalOutputs(nSampsCo=nSampsCo)\n print('DSig set')\n self.nBlocks = nBlocks\n self.nSampsCo = nSampsCo\n# self.OutputShape = (nColumns * nRows, nSampsCh, nblocs)\n self.OutputShape = (len(self.MuxChannelNames), nSampsCo, nBlocks)\n EveryN = len(self.DigColumns)*nSampsCo*nBlocks\n self.AnalogInputs.ReadContData(Fs=Fs,\n EverySamps=EveryN)\n\n def SetBias(self, Vgs, Vds):\n print('ChannelsConfig SetBias Vgs ->', Vgs, 'Vds ->', Vds)\n self.VdsOut.SetVal(Vds)\n self.VsOut.SetVal(-Vgs)\n self.BiasVd = Vds-Vgs\n self.Vgs = Vgs\n self.Vds = Vds\n\n def SetDigitalOutputs(self, nSampsCo):\n print('SetDigitalOutputs')\n DOut = np.array([], dtype=np.bool)\n\n for nCol, iCol in zip(range(len(self.doColumns)), sorted(list(self.doColumns.keys()))):\n Lout = np.zeros((1, nSampsCo*len(self.DigColumns)), dtype=np.bool)\n for i, n in enumerate(self.DigColumns):\n if n == iCol:\n Lout[0, nSampsCo * i: nSampsCo * (i + 1)] = True\n Cout = np.vstack((Lout, ~Lout))\n DOut = np.vstack((DOut, Cout)) if DOut.size else Cout\n\n SortDInds = []\n for line in DOut[0:-1:2, :]:\n if True in line:\n SortDInds.append(np.where(line))\n\n self.SortDInds = SortDInds\n self.DigitalOutputs.SetContSignal(Signal=DOut.astype(np.uint8))\n\n def _SortChannels(self, data, SortDict):\n # Sort by aianalog input\n (samps, inch) = data.shape\n aiData = np.zeros((samps, len(SortDict)))\n for chn, inds in sorted(SortDict.items()):\n aiData[:, inds[1]] = data[:, inds[0]]\n\n # Sort by digital columns\n aiData = aiData.transpose()\n MuxData = np.ndarray(self.OutputShape)\n\n nColumns = len(self.DigColumns)\n for indB in range(self.nBlocks):\n startind = indB * self.nSampsCo * nColumns\n stopind = self.nSampsCo * nColumns * (indB + 1)\n Vblock = aiData[:, startind: stopind]\n ind = 0\n for chData in Vblock[:, :]:\n for Inds in self.SortDInds:\n MuxData[ind, :, indB] = chData[Inds]\n ind += 1\n return aiData, MuxData\n\n def EveryNEventCallBack(self, Data):\n # print('EveryNEventCallBack')\n _DataEveryNEvent = self.DataEveryNEvent\n\n if _DataEveryNEvent is not None:\n if self.AcqDC:\n aiDataDC, MuxDataDC = self._SortChannels(Data,\n self.DCChannelIndex)\n aiDataDC = (aiDataDC-self.BiasVd) / self.DCGain\n MuxDataDC = (MuxDataDC-self.BiasVd) / self.DCGain\n if self.AcqAC:\n aiDataAC, MuxDataAC = self._SortChannels(Data,\n self.ACChannelIndex)\n aiDataAC = aiDataAC / self.ACGain\n MuxDataAC = MuxDataAC / self.ACGain\n\n if self.AcqAC and self.AcqDC:\n aiData = np.vstack((aiDataDC, aiDataAC))\n MuxData = np.vstack((MuxDataDC, MuxDataAC))\n _DataEveryNEvent(aiData, MuxData)\n elif self.AcqAC:\n _DataEveryNEvent(aiDataAC, MuxDataAC)\n elif self.AcqDC:\n _DataEveryNEvent(aiDataDC, MuxDataDC)\n\n def DoneEventCallBack(self, Data):\n print('Done callback')\n\n def Stop(self):\n print('Stopppp')\n self.SetBias(Vgs=0, Vds=0)\n self.AnalogInputs.StopContData()\n if self.DigitalOutputs is not None:\n print('Clear Digital')\n# self.DigitalOutputs.SetContSignal(Signal=self.ClearSig)\n self.DigitalOutputs.ClearTask()\n self.DigitalOutputs = None\n\n\n# def __del__(self):\n# print('Delete class')\n# self.Inputs.ClearTask()\n#","sub_path":"PyCharMux/PyCharAcqCore/PyCharAcqCore.py","file_name":"PyCharAcqCore.py","file_ext":"py","file_size_in_byte":10608,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"247347018","text":"from operator import pos\nimport datajoint as dj\nimport numpy as np\nimport pynwb\n\nfrom .common_ephys import Raw # noqa: F401\nfrom .common_interval import IntervalList, interval_list_contains\nfrom .common_nwbfile import Nwbfile\nfrom .common_session import Session # noqa: F401\nfrom .common_task import TaskEpoch\nfrom .dj_helper_fn import fetch_nwb\nfrom .nwb_helper_fn import get_data_interface, get_valid_intervals, estimate_sampling_rate, get_nwb_file, get_all_spatial_series\n\nschema = dj.schema('common_behav')\n\n\n@schema\nclass PositionSource(dj.Manual):\n definition = \"\"\"\n -> Session\n -> IntervalList\n ---\n source : varchar(40) # source of data; current options are \"trodes\" and \"dlc\" (deep lab cut)\n import_file_name: varchar(200) # path to import file if importing position data\n \"\"\"\n\n def get_nwbf_position_source(self, nwb_file_name):\n \"\"\"Given an nwb file name, gets the spatial series and Interval lists from the file, adds the interval \n lists to the interval list table, and populates RawPosition if possible\n\n :param nwb_file_name: the name of the nwb_file\n :type nwb_file_name: string\n \"\"\"\n nwb_file_abspath = Nwbfile.get_abs_path(nwb_file_name)\n nwbf = get_nwb_file(nwb_file_abspath)\n\n pos_dict = get_all_spatial_series(nwbf, verbose=True)\n key = dict()\n if pos_dict is not None:\n for epoch in pos_dict:\n pdict = pos_dict[epoch]\n # create the interval list and insert it\n pos_interval_list_name = self.get_pos_interval_name(epoch)\n interval_dict = dict()\n interval_dict['nwb_file_name'] = nwb_file_name\n interval_dict['interval_list_name'] = pos_interval_list_name \n interval_dict['valid_times'] = pdict['valid_times']\n IntervalList().insert1(interval_dict, skip_duplicates=True)\n # add this interval list to the table\n key['nwb_file_name'] = nwb_file_name\n key['interval_list_name'] = pos_interval_list_name\n key['source'] = 'trodes'\n key['import_file_name'] = ''\n self.insert1(key)\n\n @staticmethod\n def get_pos_interval_name(pos_epoch_num):\n return f'pos {pos_epoch_num} valid times'\n\n\n@schema\nclass RawPosition(dj.Imported):\n definition = \"\"\"\n -> PositionSource\n ---\n raw_position_object_id: varchar(80) # the object id of the spatial series for this epoch in the NWB file\n \"\"\"\n\n def make(self, key):\n nwb_file_name = key['nwb_file_name']\n nwb_file_abspath = Nwbfile.get_abs_path(nwb_file_name)\n nwbf = get_nwb_file(nwb_file_abspath)\n\n pos_dict = get_all_spatial_series(nwbf)\n for epoch in pos_dict:\n if key['interval_list_name'] == PositionSource.get_pos_interval_name(epoch):\n pdict = pos_dict[epoch]\n key['raw_position_object_id'] = pdict['raw_position_object_id']\n self.insert1(key)\n break\n\n def fetch_nwb(self, *attrs, **kwargs):\n return fetch_nwb(self, (Nwbfile, 'nwb_file_abs_path'), *attrs, **kwargs)\n\n\n@schema\nclass StateScriptFile(dj.Imported):\n definition = \"\"\"\n -> TaskEpoch\n ---\n file_object_id: varchar(40) # the object id of the file object\n \"\"\"\n\n def make(self, key):\n nwb_file_name = key['nwb_file_name']\n nwb_file_abspath = Nwbfile.get_abs_path(nwb_file_name)\n nwbf = get_nwb_file(nwb_file_abspath)\n associated_files = nwbf.processing.get('associated_files') or nwbf.processing.get('associated files')\n if associated_files is not None:\n # TODO type checking that associated_file_obj is of type ndx_franklab_novela.AssociatedFiles\n for associated_file_obj in associated_files.data_interfaces.values():\n # parse the task_epochs string\n epoch_list = associated_file_obj.task_epochs.split(',')\n # find the file associated with this epoch\n if str(key['epoch']) in epoch_list:\n key['file_object_id'] = associated_file_obj.object_id\n self.insert1(key)\n\n def fetch_nwb(self, *attrs, **kwargs):\n return fetch_nwb(self, (Nwbfile, 'nwb_file_abs_path'), *attrs, **kwargs)\n\n\n@schema\nclass VideoFile(dj.Imported):\n definition = \"\"\"\n -> TaskEpoch\n video_file_num = 0: int\n ---\n video_file_object_id: varchar(40) # the object id of the file object\n \"\"\"\n\n def make(self, key):\n nwb_file_name = key['nwb_file_name']\n nwb_file_abspath = Nwbfile.get_abs_path(nwb_file_name)\n nwbf = get_nwb_file(nwb_file_abspath)\n video = get_data_interface(nwbf, 'video')\n\n # get the interval for the current TaskEpoch\n interval_list_name = (TaskEpoch() & key).fetch1('interval_list_name')\n valid_times = (IntervalList & {'nwb_file_name': key['nwb_file_name'],\n 'interval_list_name': interval_list_name}).fetch1('valid_times')\n\n for video_obj in video.time_series.values():\n # check to see if the times for this video_object are largely overlapping with the task epoch times\n if len(interval_list_contains(valid_times, video_obj.timestamps) > .9 * len(video_obj.timestamps)):\n key['video_file_object_id'] = video_obj.object_id\n self.insert1(key)\n\n def fetch_nwb(self, *attrs, **kwargs):\n return fetch_nwb(self, (Nwbfile, 'nwb_file_abs_path'), *attrs, **kwargs)\n\n\n@schema\nclass HeadDir(dj.Imported):\n definition = \"\"\"\n -> Session\n ---\n nwb_object_id: int # the object id of the data in the NWB file\n -> IntervalList # the list of intervals for this object\n \"\"\"\n\n def make(self, key):\n nwb_file_name = key['nwb_file_name']\n nwb_file_abspath = Nwbfile.get_abs_path(nwb_file_name)\n nwbf = get_nwb_file(nwb_file_abspath)\n # position data is stored in the Behavior module\n try:\n behav_mod = nwbf.get_processing_module('Behavior')\n headdir = behav_mod.data_interfaces['Head Direction'] # noqa: F841 TODO: make use of headdir\n except Exception: # TODO: use more precise error check\n print(f'Unable to import HeadDir: no Behavior module found in {nwb_file_name}')\n return\n key['nwb_object_id'] = -1\n # this is created when we populate the Task schema\n key['interval_list_name'] = 'task epochs'\n self.insert1(key)\n\n\n@schema\nclass Speed(dj.Imported):\n definition = \"\"\"\n -> Session\n ---\n nwb_object_id: int # the object id of the data in the NWB file\n -> IntervalList # the list of intervals for this object\n \"\"\"\n\n def make(self, key):\n nwb_file_name = key['nwb_file_name']\n nwb_file_abspath = Nwbfile.get_abs_path(nwb_file_name)\n nwbf = get_nwb_file(nwb_file_abspath)\n # position data is stored in the Behavior module\n try:\n behav_mod = nwbf.get_processing_module('Behavior')\n speed = behav_mod.data_interfaces['Speed'] # noqa: F841 TODO: make use of speed\n except Exception: # TODO: use more precise error check\n print(f'Unable to import Speed: no Behavior module found in {nwb_file_name}')\n return\n key['nwb_object_id'] = -1\n # this is created when we populate the Task schema\n key['interval_list_name'] = 'task epochs'\n self.insert1(key)\n \n\n@schema\nclass LinPos(dj.Imported):\n definition = \"\"\"\n -> Session\n ---\n nwb_object_id: int # the object id of the data in the NWB file\n -> IntervalList # the list of intervals for this object\n \"\"\"\n\n def make(self, key):\n nwb_file_name = key['nwb_file_name']\n nwb_file_abspath = Nwbfile.get_abs_path(nwb_file_name)\n nwbf = get_nwb_file(nwb_file_abspath)\n # position data is stored in the Behavior module\n try:\n behav_mod = nwbf.get_processing_module(\"Behavior\")\n linpos = behav_mod.data_interfaces['Linearized Position'] # noqa: F841 TODO: make use of speed\n except Exception: # TODO: use more precise error check\n print(f'Unable to import LinPos: no Behavior module found in {nwb_file_name}')\n return\n key['nwb_object_id'] = -1\n # this is created when we populate the Task schema\n key['interval_list_name'] = 'task epochs'\n self.insert1(key)\n","sub_path":"src/nwb_datajoint/common/common_behav.py","file_name":"common_behav.py","file_ext":"py","file_size_in_byte":8538,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"278238171","text":"# -*- coding: utf-8 -*-\nfrom __future__ import division\ndef lecker (lista):\n contador = 0\n for i in range (0,len(lista),1):\n if i==0:\n if lista[i]>lista[i+1]:\n contador = contador+1\n elif i == (len(lista)-1):\n if lista[i]>lista[i-1]:\n contador = contador +1\n else:\n if lista[i]> lista[i+1] and lista[i]>lista[i-1]:\n contador = contador +1\n if contador !=0:\n print ('s')\n else:\n print ('N')\n \nn = input ('Digite a quantidade de termos:')\na = []\nb = []\nfor i in range (0,n,1):\n a.append (input('Digite um número para lista a:'))\nfor j in range (0,n,1):\n b.append (input('Digite um número para lista b:'))\n\nprint (lecker(a))\nprint (lecker(b))","sub_path":"moodledata/vpl_data/47/usersdata/106/16829/submittedfiles/lecker.py","file_name":"lecker.py","file_ext":"py","file_size_in_byte":787,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"576911102","text":"import winsound\r\nfrequency=2500\r\nduration=1000\r\nimport numpy as np\r\nimport pandas as pd\r\nimport matplotlib.pyplot as plt\r\nimport cv2\r\nimport tensorflow as tf\r\nimport tkinter as tk\r\nfrom PIL import ImageTk,Image \r\nfrom flask import Flask,redirect, url_for,render_template,request\r\n\r\ndef func():\r\n root = tk.Tk() \r\n canvas = tk.Canvas(root, width = 400, height = 200) \r\n canvas.pack() \r\n img = ImageTk.PhotoImage(Image.open(\"images/driver1.jpg\")) \r\n canvas.create_image(15, 20, anchor=\"nw\", image=img)\r\n l = tk.Label(root, text = \"Click Run to take the test!\")\r\n l.config(font =(\"Georgia\", \"18\"))\r\n l.pack(side=tk.TOP, pady= 10)\r\n\r\n def run_program():\r\n new_model = tf.keras.models.load_model('models/my_model2.h5')\r\n\r\n path= \"haarcascade_frontalface_default.xml\"\r\n faceCascade = cv2.CascadeClassifier(cv2.data.haarcascades + 'haarcascade_frontalface_default.xml')\r\n cap = cv2.VideoCapture(1)\r\n\r\n if not cap.isOpened():\r\n cap= cv2.VideoCapture(0)\r\n if not cap.isOpened():\r\n raise IOError(\"Cannot open webcam\")\r\n counter=0\r\n eyes_roi=0\r\n\r\n while True:\r\n ret,frame =cap.read()\r\n eye_cascade = cv2.CascadeClassifier(cv2.data.haarcascades + 'haarcascade_eye_tree_eyeglasses.xml')\r\n gray= cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)\r\n #print(faceCascade.empty())\r\n eyes = eye_cascade.detectMultiScale(gray, 1.1,4)\r\n for x,y,w,h in eyes:\r\n roi_gray = gray[y:y+h, x:x+w]\r\n roi_color = frame[y:y+h, x:x+w]\r\n cv2.rectangle(frame, (x,y), (x+w, y+h), (0, 255, 0), 2)\r\n eyess = eye_cascade.detectMultiScale(roi_gray)\r\n if len(eyess) ==0:\r\n print(\"eyes are not detected\")\r\n continue\r\n else:\r\n for(ex,ey,ew,eh) in eyess:\r\n eyes_roi = roi_color[ey: ey+eh, ex:ex+ew]\r\n gray= cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)\r\n print(faceCascade.empty())\r\n faces = faceCascade.detectMultiScale(gray,1.1,4)\r\n \r\n for (x,y,w,h) in faces:\r\n cv2.rectangle(frame, (x,y), (x+w, y+h), (0, 255, 0), 2)\r\n font =cv2.FONT_HERSHEY_SIMPLEX\r\n final_image =cv2.resize(eyes_roi, (224, 224))\r\n final_image = np.expand_dims(final_image, axis=0)\r\n final_image=final_image/255.0\r\n \r\n print(final_image.shape)\r\n if len(final_image.shape)!=4:\r\n continue\r\n #final_image = final_image.reshape(1, 224, 224, 3)\r\n \r\n Predictions = new_model.predict(final_image)\r\n if (Predictions>=0.8 and Predictions<=1.0):\r\n status = \"Open eyes\"\r\n cv2.putText(frame,\r\n status,\r\n (150,150),\r\n font,3,\r\n (0,255,0),\r\n 2, cv2.LINE_4)\r\n x1, y1, w1, h1 = 0, 0, 175, 75\r\n #draw black bg rectangle\r\n cv2.rectangle(frame,(x1, x1), (x1+w1, y1 + h1), (0,0,0), -1)\r\n #add text\r\n cv2.putText(frame, 'Active', (x1 + int(w1/10),y1 + int(h1/2)), cv2.FONT_HERSHEY_SIMPLEX, 0.7, (0,255,0), 2)\r\n\r\n else:\r\n counter= counter+1\r\n status= \"closed eyes\"\r\n cv2.putText(frame,\r\n status,\r\n (150,150),\r\n font,3,\r\n (0,0,255),\r\n 2, cv2.LINE_4)\r\n\r\n cv2.rectangle(frame,(x , y), (x +w , y + h), (0,0,255), 2)\r\n if counter>7:\r\n x1,y1,w1,h1 = 0,0,175,75\r\n cv2.rectangle(frame,(x1, x1), (x1+w1, y1 + h1), (0,0,0), -1)\r\n #add text\r\n cv2.putText(frame, 'Sleep Alert!!', (x1 + int(w1/10),y1 + int(h1/2)), cv2.FONT_HERSHEY_SIMPLEX, 0.7, (0,255,0), 2)\r\n winsound.Beep(frequency, duration)\r\n counter = 0\r\n \r\n cv2.imshow('Drowsiness Detection' , frame)\r\n if cv2.waitKey(2) & 0xFF == ord('q'):\r\n break\r\n cap.release()\r\n cv2.destroyAllWindows()\r\n\r\n\r\n frame = tk.Frame(root)\r\n frame.pack()\r\n root.title(\"Driver's drowsiness test\")\r\n root.geometry('400x300')\r\n\r\n \"\"\"\r\n b1 = tk.Button(frame, \r\n text=\"QUIT\", \r\n fg=\"red\",\r\n width=10,\r\n height=10,\r\n command=quit)\r\n b1.pack(side=tk.RIGHT, padx=5, pady=5)\r\n \"\"\"\r\n b2 = tk.Button(frame,\r\n text=\"RUN\",\r\n width=10,\r\n height=10,\r\n command=run_program)\r\n b2.pack(side=tk.RIGHT, padx=5, pady=5)\r\n\r\n root.mainloop()","sub_path":"index.py","file_name":"index.py","file_ext":"py","file_size_in_byte":4977,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"180078008","text":"##############################################################################\n#\n# Copyright (c) 2006 Zope Foundation and Contributors.\n# All Rights Reserved.\n#\n# This software is subject to the provisions of the Zope Public License,\n# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.\n# THIS SOFTWARE IS PROVIDED \"AS IS\" AND ANY AND ALL EXPRESS OR IMPLIED\n# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\n# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS\n# FOR A PARTICULAR PURPOSE.\n#\n##############################################################################\n\"\"\"Task Service Interfaces\n\n$Id$\n\"\"\"\n__docformat__ = 'restructuredtext'\nfrom zope import interface\nfrom zope import schema\nfrom zope.configuration import fields\nfrom zope.container.interfaces import IContained\n\nQUEUED = 'queued'\nPROCESSING = 'processing'\nCANCELLED = 'cancelled'\nERROR = 'error'\nCOMPLETED = 'completed'\nDELAYED = 'delayed'\nCRONJOB = 'cronjob'\nDELAYED = 'delayed'\nSTARTLATER = 'start later'\n\n\nclass ITask(interface.Interface):\n \"\"\"A task available in the task service\"\"\"\n\n inputSchema = schema.Object(\n title=u'Input Schema',\n description=u'A schema describing the task input signature.',\n schema=interface.Interface,\n required=False)\n\n outputSchema = schema.Object(\n title=u'Output Schema',\n description=u'A schema describing the task output signature.',\n schema=interface.Interface,\n required=False)\n\n def __call__(service, jobid, input):\n \"\"\"Execute the task.\n\n The ``service`` argument is the task service object. It allows access\n to service wide data and the system as a whole.\n\n Tasks do not live in a vacuum, but are tightly coupled to the job\n executing it. The ``jobid`` argument provides the id of the job being\n processed.\n\n The ``input`` object must conform to the input schema (if\n specified). The return value must conform to the output schema.\n \"\"\"\n\n\nclass ITaskService(IContained):\n \"\"\"A service for managing and executing tasks.\"\"\"\n\n jobs = schema.Object(\n title=u'Jobs',\n description=u'A mapping of all jobs by job id.',\n schema=interface.common.mapping.IMapping)\n\n taskInterface = fields.GlobalInterface(\n title=u'Task Interface',\n description=u'The interface to lookup task utilities',\n default=ITask,\n )\n\n def getAvailableTasks():\n \"\"\"Return a mapping of task name to the task.\"\"\"\n\n def add(task, input=None, startLater=False):\n \"\"\"Add a new job for the specified task.\n\n * task argument is a string specifying the task.\n * input are arguments for the task.\n * startLater, if True job will be added (gets a jobid) but needs\n to be started with startJob later\n \"\"\"\n\n def addCronJob(task, input,\n minute=(),\n hour=(),\n dayOfMonth=(),\n month=(),\n dayOfWeek=(),\n ):\n \"\"\"Add a new cron job.\"\"\"\n\n def startJob(jobid):\n \"\"\"Start a job previously added job with add(..., startLater=True)\n \"\"\"\n\n def reschedule(jobid):\n \"\"\"Rescheudle a cron job.\n\n This is neccessary if the cron jobs parameters are changed.\n \"\"\"\n\n def clean(status=[CANCELLED, ERROR, COMPLETED]):\n \"\"\"removes all jobs which are completed or canceled or have errors.\"\"\"\n\n def cancel(jobid):\n \"\"\"Cancel a particular job.\"\"\"\n\n def getStatus(jobid):\n \"\"\"Get the status of a job.\"\"\"\n\n def getResult(jobid):\n \"\"\"Get the result data structure of the job.\"\"\"\n\n def getError(jobid):\n \"\"\"Get the error of the job.\"\"\"\n\n def hasJobsWaiting(now=None):\n \"\"\"Determine whether there are jobs that need to be processed.\n\n Returns a simple boolean.\n \"\"\"\n\n def processNext():\n \"\"\"Process the next job in the queue.\"\"\"\n\n def process():\n \"\"\"Process all scheduled jobs.\n\n This call blocks the thread it is running in.\n \"\"\"\n\n def startProcessing():\n \"\"\"Start processing jobs.\n\n This method has to be called after every server restart.\n \"\"\"\n\n def stopProcessing():\n \"\"\"Stop processing jobs.\"\"\"\n\n def isProcessing():\n \"\"\"Check whether the jobs are being processed.\n\n Return a boolean representing the state.\n \"\"\"\n\n\nclass IJob(interface.Interface):\n \"\"\"An internal job object.\"\"\"\n\n id = schema.Int(\n title=u'Id',\n description=u'The job id.',\n required=True)\n\n task = schema.TextLine(\n title=u'Task',\n description=u'The task to be completed.',\n required=True)\n\n status = schema.Choice(\n title=u'Status',\n description=u'The current status of the job.',\n values=[QUEUED, PROCESSING, CANCELLED, ERROR,\n COMPLETED, DELAYED, CRONJOB, STARTLATER],\n required=True)\n\n input = schema.Object(\n title=u'Input',\n description=u'The input for the task.',\n schema=interface.Interface,\n required=False)\n\n output = schema.Object(\n title=u'Output',\n description=u'The output of the task.',\n schema=interface.Interface,\n required=False,\n default=None)\n\n error = schema.Object(\n title=u'Error',\n description=u'The error object when the task failed.',\n schema=interface.Interface,\n required=False,\n default=None)\n\n created = schema.Datetime(\n title=u'Creation Date',\n description=u'The date/time at which the job was created.',\n required=True)\n\n started = schema.Datetime(\n title=u'Start Date',\n description=u'The date/time at which the job was started.')\n\n completed = schema.Datetime(\n title=u'Completion Date',\n description=u'The date/time at which the job was completed.')\n\n\nclass ICronJob(IJob):\n \"\"\"Parameters for cron jobs\"\"\"\n\n minute = schema.Tuple(\n title=u'minute(s)',\n default=(),\n required=False,\n )\n\n hour = schema.Tuple(\n title=u'hour(s)',\n default=(),\n required=False,\n )\n\n dayOfMonth = schema.Tuple(\n title=u'day of month',\n default=(),\n required=False,\n )\n\n month = schema.Tuple(\n title=u'month(s)',\n default=(),\n required=False,\n )\n\n dayOfWeek = schema.Tuple(\n title=u'day of week',\n default=(),\n required=False,\n )\n\n delay = schema.Int(\n title=u'delay',\n default=0,\n required=False,\n )\n\n scheduledFor = schema.Datetime(\n title=u'scheduled',\n default=None,\n required=False,\n )\n\n def update(minute, hour, dayOfMonth, month, dayOfWeek, delay):\n \"\"\"Update the cron job.\n\n The job must be rescheduled in the containing service.\n \"\"\"\n\n def timeOfNextCall(now=None):\n \"\"\"Calculate the time for the next call of the job.\n\n now is a convenience parameter for testing.\n \"\"\"\n\n\nclass IProcessor(interface.Interface):\n \"\"\"Job Processor\n\n Process the jobs that are waiting in the queue. A processor is meant to\n be run in a separate thread. To complete a job, it simply calls back into\n the task server. This works, since it does not use up any Web server\n threads.\n\n Processing a job can take a long time. However, we do not have to worry\n about transaction conflicts, since no other request is touching the job\n object.\n \"\"\"\n\n running = schema.Bool(\n title=u\"Running Flag\",\n description=u\"Tells whether the processor is currently running.\",\n readonly=True)\n\n def __call__(db, servicePath):\n \"\"\"Run the processor.\n\n The ``db`` is a ZODB instance that is used to call back into the task\n service. The ``servicePath`` specifies how to traverse to the task\n service itself.\n \"\"\"\n","sub_path":"src/z3c/taskqueue/interfaces.py","file_name":"interfaces.py","file_ext":"py","file_size_in_byte":8182,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"425121756","text":"#!/usr/bin/env python\n#\n# ======================================================================\n#\n# Brad T. Aagaard, U.S. Geological Survey\n# Charles A. Williams, GNS Science\n# Matthew G. Knepley, University at Buffalo\n#\n# This code was developed as part of the Computational Infrastructure\n# for Geodynamics (http://geodynamics.org).\n#\n# Copyright (c) 2010-2022 University of California, Davis\n#\n# See LICENSE.md for license information.\n#\n# ======================================================================\n#\n\n## @file tests/pytests/mpi/TestCommunicator.py\n\n## @brief Unit testing of Communicator object.\n\nimport unittest\n\nimport pylith.mpi.Communicator as mpicomm\n\n# ----------------------------------------------------------------------\nclass TestCommunicator(unittest.TestCase):\n \"\"\"Unit testing of Communicator object.\n \"\"\"\n \n\n def test_petsc_comm_world(self):\n comm = mpicomm.petsc_comm_world()\n return\n\n\n def test_petsc_comm_self(self):\n comm = mpicomm.petsc_comm_self()\n return\n\n\n def test_mpi_comm_world(self):\n comm = mpicomm.mpi_comm_world()\n return\n\n\n def test_mpi_comm_self(self):\n comm = mpicomm.mpi_comm_self()\n return\n\n\n def test_rank(self):\n comm = mpicomm.petsc_comm_world()\n self.assertEqual(0, comm.rank)\n return\n\n\n def test_size(self):\n comm = mpicomm.petsc_comm_world()\n self.assertEqual(1, comm.size)\n return\n\n\n def test_barrier(self):\n comm = mpicomm.petsc_comm_world()\n comm.barrier()\n return\n\n\nif __name__ == \"__main__\":\n suite = unittest.TestSuite()\n suite.addTest(unittest.makeSuite(TestCommunicator))\n\n from pylith.utils.PetscManager import PetscManager\n petsc = PetscManager()\n petsc.initialize()\n\n success = unittest.TextTestRunner(verbosity=2).run(suite).wasSuccessful()\n\n petsc.finalize()\n\n\n# End of file \n","sub_path":"tests/pytests/mpi/TestCommunicator.py","file_name":"TestCommunicator.py","file_ext":"py","file_size_in_byte":1828,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"334826764","text":"# Chapter10_01\n# Hangman Mini Game\n# Basic Program Development and Test\n\nimport time\nimport csv\nimport random\nimport winsound\n\n# First Greetings\nname = input('What is your name? : ')\n\nprint('Hi ,'+name, 'Time to play hangman game!')\n\nprint()\n\ntime.sleep(1)\n\nprint('Start Loading...')\nprint()\ntime.sleep(0.5)\n\n# CSV Word List\nwords = []\n\n# Questions CSV File Load\nwith open('./resource/word_list.csv', 'r') as f:\n reader = csv.reader(f)\n # Header Skip\n next(reader)\n for c in reader:\n words.append(c)\n\n# Mix Lists\nrandom.shuffle(words)\nq = random.choice(words)\n\n# Answer\nword = q[0].strip()\n\n# Guessing Words\nguesses = ''\n\n# Chance\nturns = 10\n\n# While Loop\n# If Chance count left\nwhile turns > 0:\n # Fail Count\n failed = 0\n\n # Repeat the correct word\n for char in word:\n # The correct answer contains a guessing character.\n if char in guesses:\n # guess word output\n print(char, end=' ')\n else:\n # Process as _ if incorrect\n print('_', end=' ')\n failed += 1\n # a case of successful word guess\n if failed == 0:\n print()\n print()\n # Win Sound\n winsound.PlaySound('./sound/good.wav', winsound.SND_FILENAME)\n print('Congratulations ! The Guesses is correct')\n # Stop\n break\n print()\n\n # Enter guessing word character units\n print()\n print('Hint : {}'.format(q[1].strip()))\n guess = input('guess a charater : ')\n\n # Add words\n guesses += guess\n\n # The correct word does not contain any guessing characters.\n if guess not in word:\n turns -= 1\n # Error Message\n print('Oops! Wront')\n # Print left Chances\n print('You have', turns, 'more guesses!')\n\n if turns == 0:\n # Fail Message\n # Fail Sound\n winsound.PlaySound('./sound/bad.wav', winsound.SND_FILENAME)\n print('Your hangman game failed. Bye!')\n","sub_path":"10. Python Final Project/1. Chapter10_01.py","file_name":"1. Chapter10_01.py","file_ext":"py","file_size_in_byte":1964,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"478222459","text":"import matplotlib.pyplot as plt\nimport numpy as np\nimport pandas as pd\nfrom glob import glob\nfrom itertools import repeat\n\n\n#Import the data_\nfolname = '10mm_mixing_full_cosmo'\ndirname = '0_1mm_nonlinear'\nDataDirectory = '/exports/csce/datastore/geos/users/s0933963/github/LSDMixingModel/Runs/changing_base_level/'+dirname+'/'+folname+'/'\n\nprint('This is the input file directory: '+DataDirectory)\n#Load all the data\nprint('Load the flowtube data')\nft_out = pd.read_csv(DataDirectory+'ft_properties.out', sep=\" \",header=0,names=['s', 'b', 'A', 'zeta', 'eta', 'h'] )\nprint('Load the eroded particle data')\neroded_bins = pd.read_csv(DataDirectory+'ep_trans_out.pout', sep=\" \",names=['time', 'bn', 'pid','z_loc','s_loc','d_loc','buff','page','osl','be_conc','fallout_be_conc','c_conc','ne_conc'] )\nprint('Load the particle data')\nbins = pd.read_csv(DataDirectory+'p_trans_out.pout', sep=\" \",names=['time', 'bn', 'pid','z_loc','s_loc','d_loc','buff','page','osl','be_conc','fallout_be_conc','c_conc','ne_conc'] )\n\n\nft_pits = ft_out.s.unique()\nft_pits = np.array(ft_pits)\nft_pits = np.delete(ft_pits, np.where(ft_pits == '-99'))\nft_pits = np.delete(ft_pits, np.where(ft_pits == 's'))\nft_pits = ft_pits.astype(np.float)\n# print(ft_pits)\nft_data = ft_out\nft_data = ft_data.drop(ft_data[(ft_data.s == 's') | (ft_data.s == '-99')].index)\nft_data = np.array(ft_data)\nft_data = ft_data.astype(np.float)\n\n\n\n\n\n\ntimesteps = int(len(ft_data)/len(ft_pits))\npits = int(len(ft_pits))\n\n\n\ntime_unique = bins.time.unique()\ntime_unique = np.array(time_unique)\ntime_unique = time_unique/1000\ntimelabels = time_unique\nbins_unique = bins.bn.unique()\nbins_unique = np.array(bins_unique)\nbins['time'] = bins['time']/1000\neroded_bins['time'] = eroded_bins['time']/1000\ndiv = max(bins_unique)/max(ft_pits)\n\n\n\n\n\n\n# sed trans file\nsed_trans_in = pd.read_csv(DataDirectory+'sed_trans_param.stparam',header=None, sep=\" \")\nrho = sed_trans_in[1][0]/1000\n# model run\nmodel_run_in = pd.read_csv(DataDirectory+'model_run.param',header=None, sep=\" \")\nfinal_node = model_run_in[1][17]\n# CRN param\ncrn_param_in = pd.read_csv(DataDirectory+'CRN_trans_param.CRNparam',header=None, sep=\" \")\nlat = crn_param_in[1][21]\nlon = crn_param_in[1][22]\nelev = crn_param_in[1][23]\n\n# User defined variables \nthickness=0.1\nmthd = 'std'\nmineral = 'quartz'\nshielding= '1'\nerosion=0.001\nsample = 'test'\n\n\n\n\n\n\n# Write the first line\n\ncronus_fname = DataDirectory+'for_cronus_data_'+str(dirname)+'_'+str(folname)\nfile = open('%s' % cronus_fname, 'w')\nfile.write(str(sample) + ' ' + str(lat) + ' ' + str(lon) + ' ' + str(elev) + ' ' + str(mthd) + ' ' + str(thickness) + ' ' + str(rho) + ' ' + str(shielding) + ' ' + str(erosion) + ' '+ '2010' +';'+'\\n')\n\n# Set up the rest of the dataframe\n\n\n\n# Find the local (current) erosion rate\n\n\n\n# Loop through the data\nfor i in range(0,len(time_unique)):\n\n thick = ft_data[i*pits:i*pits+pits][:,5]\n \n for j in range(0,len(bins_unique)//2):\n \n temp_bins = bins[(bins['time'] == time_unique[i]) & (bins['bn'] >= bins_unique[j*2]) & (bins['bn'] <= bins_unique[j*2+1]) & (bins['d_loc'] > 0.0) & (bins['d_loc'] < 0.006)]\n \n mean_crn = temp_bins.mean().be_conc\n std_dv = temp_bins.std().be_conc\n file.write(str(sample) + ' ' + 'Be-10 ' + ' ' + str(mineral) + ' ' + str(mean_crn) + ' ' + str(std_dv) + ' '+ 'KNSTD' +';'+'\\n')\n\n\n\n\nfile.close()\n\n\n\n\n\n\n\n\n\n\n\n","sub_path":"model_visualisation_scripts/Catena_scripts/extracting_crn_erosion_rates_for_cronus.py","file_name":"extracting_crn_erosion_rates_for_cronus.py","file_ext":"py","file_size_in_byte":3377,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"597218969","text":"from tkinter import *\r\nfrom tkinter import messagebox\r\nimport maze_solving_algorithms\r\nimport quick_solve\r\nimport maze\r\nimport export_import_files\r\nimport build_maze\r\n\r\nclass Main:\r\n\r\n def __init__(self):\r\n self.__root = Tk()\r\n self.__MOVE_BY = 6.171875\r\n self.__NUMBER_OF_CELLS = 16\r\n SCREEN_WIDTH = self.__root.winfo_screenwidth()\r\n SCREEN_HEIGHT = self.__root.winfo_screenheight()\r\n \"\"\" Opens the correct images to use, and assigns correct value to\r\n self.__DIVISOR_UI. This is dependent on the resolution of the\r\n screen.\"\"\"\r\n if SCREEN_WIDTH*SCREEN_HEIGHT < 1280*1024:\r\n self.__DIVISOR_UI = 45/32\r\n self.__ARROW_RIGHT = PhotoImage(file = 'ArrowRightSmall.gif')\r\n self.__ARROW_LEFT = PhotoImage(file = 'ArrowLeftSmall.gif')\r\n self.__ARROW_UP = PhotoImage(file = 'ArrowUpSmall.gif')\r\n self.__ARROW_DOWN = PhotoImage(file = 'ArrowDownSmall.gif')\r\n else:\r\n self.__ARROW_RIGHT = PhotoImage(file = 'ArrowRightLarge.gif')\r\n self.__ARROW_LEFT = PhotoImage(file = 'ArrowLeftLarge.gif')\r\n self.__ARROW_UP = PhotoImage(file = 'ArrowUpLarge.gif')\r\n self.__ARROW_DOWN = PhotoImage(file = 'ArrowDownLarge.gif')\r\n self.__DIVISOR_UI = 1\r\n self.__WINDOW_HEIGHT = 800/self.__DIVISOR_UI\r\n self.__CELL_WIDTH = (self.__WINDOW_HEIGHT - 10)/self.__NUMBER_OF_CELLS\r\n self.__ALIGN_X = 30/self.__DIVISOR_UI\r\n self.__ALIGN_Y = 30/self.__DIVISOR_UI\r\n\r\n self.__root.resizable(width=False, height=False)\r\n menu = Menu(self.__root)\r\n frame_1 = Frame(self.__root)\r\n frame_2 = Frame(self.__root)\r\n frame_3 = Frame(self.__root)\r\n frame_4 = Frame(self.__root)\r\n self.__root.config(menu=menu)\r\n file_menu = Menu(menu)\r\n create_maze_menu = Menu(menu)\r\n menu.add_cascade(label='File',menu=file_menu)\r\n file_menu.add_command(label='Import Maze',command=lambda:\r\n export_import_files.import_maze(\r\n maze_object,self))\r\n file_menu.add_command(label='Export Maze',command=lambda:\r\n export_import_files.export_maze(\r\n maze_object))\r\n file_menu.add_separator()\r\n file_menu.add_command(label='Exit',command=self.__root.destroy)\r\n menu.add_cascade(label='Create/Edit Maze',\r\n menu = create_maze_menu)\r\n create_maze_menu.add_command(label='Generate',\r\n command=lambda: maze_object.design_maze(\r\n True,self))\r\n create_maze_menu.add_command(label='Build',command=lambda:\r\n build_maze.Build(self,maze_object))\r\n self.canvas = Canvas(self.__root,bg = 'white',width = self.__WINDOW_HEIGHT,\r\n height =self.__WINDOW_HEIGHT)\r\n algorithm_options_label = Label(frame_1,text='Show Solve For:')\r\n algorithms_list = ['Random mouse','Wall follower','Trémaux']\r\n self.__current_option = StringVar(frame_1)\r\n self.__current_option.set(algorithms_list[0])\r\n algorithm_options = OptionMenu(frame_1, self.__current_option,\r\n *algorithms_list)\r\n solve_maze_button = Button(frame_1,text='Solve maze',\r\n command=self.__start_solve,width=11)\r\n stop_button = Button(frame_1,text='Stop',command=self.__stop_solve)\r\n quick_solve_label = Label(frame_2,text='Quick solve for:')\r\n self.__quick_solve_var = IntVar()\r\n option_1 = Radiobutton(frame_2,text='This maze',\r\n variable=self.__quick_solve_var,value=1)\r\n option_2 = Radiobutton(frame_2,text='Other mazes',\r\n variable=self.__quick_solve_var,value=2)\r\n go_to_setup_button = Button(frame_2,text='Go to setup',\r\n command=self.__quick_solve_check_1)\r\n log_label = Label(frame_3,text='Log:')\r\n self.log_list = Listbox(frame_3,width=28,height=20)\r\n cells_traversed_label = Label(frame_4,text='Cells traversed')\r\n self.__cells_traversed_entry = Entry(frame_4,width=10,state='disabled')\r\n dead_ends_label = Label(frame_4,text='Dead ends reached')\r\n self.__dead_ends_entry = Entry(frame_4,width=10,state='disabled')\r\n\r\n # Places widgets in frame_1\r\n algorithm_options_label.grid(row=1,column=1)\r\n algorithm_options.grid(row=2,column=1,columnspan=2,sticky=W+E)\r\n solve_maze_button.grid(row=3,column=1, sticky=W+E)\r\n stop_button.grid(row=3,column=2, sticky=W+E)\r\n\r\n # Places widgets in frame_2\r\n quick_solve_label.grid(row=1,column=1,sticky=W)\r\n option_1.grid(row=2,column=1,sticky=W)\r\n option_2.grid(row=3,column=1,sticky=W)\r\n go_to_setup_button.grid(row=4,column=1)\r\n\r\n # Places widgets in frame_3\r\n log_label.grid(row=0,column=0,sticky=W)\r\n self.log_list.grid(row=1,column=0,sticky=W)\r\n\r\n # Places widgets in frame_4\r\n cells_traversed_label.grid(row=0,column=0,sticky=E)\r\n self.__cells_traversed_entry.grid(row=0,column=1,sticky=E)\r\n dead_ends_label.grid(row=1,column=0,sticky=W)\r\n self.__dead_ends_entry.grid(row=1,column=1,sticky=W)\r\n\r\n # Places frames in the window\r\n frame_1.grid(row=0,column=0,sticky=W,padx=22, pady=5)\r\n frame_2.grid(row=1,column=0,sticky=W,padx=22)\r\n frame_3.grid(row=2,column=0)\r\n frame_4.grid(row=3,column=0)\r\n self.canvas.grid(row=0,column=1,rowspan=4)\r\n\r\n self.__root.iconbitmap('Icon.ico')\r\n self.__root.wm_title('Maze Solver')\r\n self.__root.mainloop()\r\n\r\n \"\"\" Configures the entry box so that its contents can be altered,\r\n changes its contents, and then reconfigures the entry box so that its\r\n contents cannot be altered by the user.\"\"\"\r\n def update_entry(self,entry_id,value):\r\n if entry_id == 'dead ends':\r\n entry = self.__dead_ends_entry\r\n elif entry_id == 'cells traversed':\r\n entry = self.__cells_traversed_entry\r\n entry.configure(state='normal')\r\n entry.delete(0, END)\r\n entry.insert(0,value)\r\n entry.configure(state='disabled')\r\n\r\n \"\"\" This is the method called when the button solve_maze_button is\r\n clicked. If the maze is not already being navigated, and a maze\r\n is displayed on the canvas, the program will begin to display the\r\n specified algorithm solve the maze.\"\"\"\r\n def __start_solve(self):\r\n if not maze_object.get_navigating_maze() and maze_object.get_maze_generated():\r\n self.log_list.delete(0,END)\r\n maze_object.set_navigating_maze(True)\r\n selected_algorithm = self.__current_option.get()\r\n if selected_algorithm == 'Random mouse':\r\n maze_solving_algorithms.random_mouse(True,maze_object,self)\r\n elif selected_algorithm == 'Wall follower':\r\n maze_solving_algorithms.wall_follower(True,maze_object,self)\r\n elif selected_algorithm == 'Trémaux':\r\n maze_solving_algorithms.trem(True,maze_object,self)\r\n maze_object.set_navigating_maze(False)\r\n\r\n \"\"\" This is the function called when the button stop_button is\r\n clicked. If the maze is being navigated, the program will stop\r\n the navigation, redraw only the maze on the canvas, and clear the\r\n widgets self.__dead_ends_entry, self.__cells_traversed_entry, and\r\n self.log_list of all contents.\"\"\"\r\n def __stop_solve(self):\r\n if maze_object.get_maze_generated() and maze_object.get_navigating_maze():\r\n self.log_list.delete(0,END)\r\n maze_object.set_navigating_maze(False)\r\n self.__root.after(50, lambda: self.canvas.delete('all'))\r\n self.__root.after(50, lambda: maze_object.draw_maze(maze_object.get_maze(),\r\n self.canvas,\r\n maze_object.get_start_point(),\r\n maze_object.get_end_point(),\r\n self))\r\n self.update_entry('cells traversed','')\r\n self.update_entry('dead ends','')\r\n\r\n \"\"\" This method controls the animation of the arrow moving from one\r\n cell to another\"\"\"\r\n def move_arrow(self,row,column,new_row,new_column,arrow):\r\n old_x = (row*self.__CELL_WIDTH+self.__ALIGN_X)\r\n old_y = (column*self.__CELL_WIDTH+self.__ALIGN_Y)\r\n new_x = (new_row*self.__CELL_WIDTH+self.__ALIGN_X)\r\n new_y = (new_column*self.__CELL_WIDTH+self.__ALIGN_Y)\r\n x_difference = new_x - old_x\r\n y_difference = new_y - old_y\r\n current_x = (row*self.__CELL_WIDTH+self.__ALIGN_X)\r\n current_y = (column*self.__CELL_WIDTH+self.__ALIGN_Y)\r\n moving = True\r\n while moving and maze_object.get_navigating_maze():\r\n if x_difference>0:\r\n if current_x >= new_x:\r\n moving = False\r\n else:\r\n current_x+=self.__MOVE_BY/self.__DIVISOR_UI\r\n elif x_difference<0:\r\n if current_x <= new_x:\r\n moving = False\r\n else:\r\n current_x-=self.__MOVE_BY/self.__DIVISOR_UI\r\n if y_difference>0:\r\n if current_y >= new_y:\r\n moving = False\r\n else:\r\n current_y+=self.__MOVE_BY/self.__DIVISOR_UI\r\n elif y_difference<0:\r\n if current_y <= new_y:\r\n moving = False\r\n else:\r\n current_y-=self.__MOVE_BY/self.__DIVISOR_UI\r\n self.canvas.delete('all')\r\n maze_object.draw_maze(maze_object.get_maze(),self.canvas,\r\n maze_object.get_start_point(),maze_object.get_end_point(),\r\n self)\r\n self.canvas.create_image((current_x, current_y), image = arrow)\r\n self.__root.update()\r\n if not moving:\r\n #maze_object.manage_ALIGN_Y(row,new_row,column,new_column)\r\n #self.__draw_ALIGN_Y()\r\n self.canvas.create_image((current_x, current_y), image = arrow)\r\n\r\n \"\"\" This is the function called when go_to_setup_button is clicked.\r\n It validates if the user has provided all of the required\r\n information. If this is the case, the quick solve setup window will\r\n be initiated. If not, the user will be informed of what information\r\n is missing.\r\n \"\"\"\r\n def __quick_solve_check_1(self):\r\n if maze_object.get_navigating_maze() == False:\r\n choice_value = self.__quick_solve_var.get()\r\n self.__quick_solve_var.set(0)\r\n if choice_value == 0:\r\n messagebox.showinfo('Info', 'No option selected')\r\n elif choice_value == 1 and not maze_object.get_maze_generated():\r\n messagebox.showinfo('Info', 'No maze')\r\n else:\r\n quick_solve.QuickSolve(choice_value,maze_object,self)\r\n\r\n def update_root(self):\r\n self.__root.update()\r\n\r\n # Returns an arrow image. The image returned is dependent on the ID provided\r\n def get_arrow(self,arrow_id):\r\n if arrow_id == 'up':\r\n return self.__ARROW_UP\r\n elif arrow_id == 'down':\r\n return self.__ARROW_DOWN\r\n elif arrow_id == 'right':\r\n return self.__ARROW_RIGHT\r\n else:\r\n return self.__ARROW_LEFT\r\n\r\n def get_number_of_cells(self):\r\n return self.__NUMBER_OF_CELLS\r\n\r\n def get_cell_width(self):\r\n return self.__CELL_WIDTH\r\n\r\n def insert_into_log_list(self,text):\r\n self.log_list.insert(END,text)\r\n\r\n def get_window_height(self):\r\n return self.__WINDOW_HEIGHT\r\n\r\n\r\nif __name__ == '__main__':\r\n maze_solving_algorithms= maze_solving_algorithms.MazeSolvingAlgorithms()\r\n maze_object = maze.Maze()\r\n export_import_files = export_import_files.ExportImportFiles()\r\n main = Main()\r\n","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":12470,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"521809141","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import models, migrations\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ]\n\n operations = [\n migrations.CreateModel(\n name='Response',\n fields=[\n ('id', models.AutoField(verbose_name='ID', auto_created=True, serialize=False, primary_key=True)),\n ('name', models.CharField(max_length=16, verbose_name='名前')),\n ('comment', models.CharField(max_length=128, verbose_name='コメント')),\n ('date_written', models.DateTimeField(verbose_name='date written')),\n ],\n options={\n },\n bases=(models.Model,),\n ),\n migrations.CreateModel(\n name='Thread',\n fields=[\n ('id', models.AutoField(verbose_name='ID', auto_created=True, serialize=False, primary_key=True)),\n ('title', models.CharField(max_length=32, verbose_name='タイトル')),\n ('date_created', models.DateTimeField(verbose_name='date created')),\n ('date_last_mod', models.DateTimeField(verbose_name='date last modefied')),\n ],\n options={\n },\n bases=(models.Model,),\n ),\n migrations.AddField(\n model_name='response',\n name='thread',\n field=models.ForeignKey(to='bbs.Thread'),\n preserve_default=True,\n ),\n ]\n","sub_path":"bbs/migrations/0001_initial.py","file_name":"0001_initial.py","file_ext":"py","file_size_in_byte":1505,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"330489960","text":"#!/usr/bin/env python\n# coding: utf-8\nfrom tqdm import tqdm_notebook\nimport shutil\nimport tensorflow as tf\nfrom tqdm.notebook import tqdm\nfrom albumentations import Resize\nimport albumentations as albu\nfrom albumentations import (Blur, Compose, HorizontalFlip, HueSaturationValue,\n IAAEmboss, IAASharpen, IAAAffine, JpegCompression, OneOf,\n RandomBrightness, RandomBrightnessContrast,\n RandomContrast, RandomCrop, RandomGamma, Rotate,\n RandomRotate90, RGBShift, ShiftScaleRotate,\n Transpose, VerticalFlip, ElasticTransform, GridDistortion, OpticalDistortion)\nimport imageio\nfrom glob import glob\nfrom sklearn.utils import shuffle\nimport random\nfrom PIL import Image as imgop\nimport cv2\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport h5py\nimport os\nimport argparse\n\nTFIDEN = 'ScrewCTF'\n\ndef readh5(d_path):\n data = h5py.File(d_path, 'r')\n data = np.array(data['data'])\n return data\n\n\ndef create_dir(base_dir, ext_name):\n new_dir = os.path.join(base_dir, ext_name)\n if not os.path.exists(new_dir):\n os.mkdir(new_dir)\n return new_dir\n\ndef aug():\n return Compose([HorizontalFlip(p=0.5), # applied\n VerticalFlip(p=0.5), # applied\n ShiftScaleRotate(shift_limit=(0.1, 0.1), # width_shift_range=0.1,# height_shift_range=0.1,\n # zoom_range=[0.9,1.25]\n scale_limit=(0.9, 1.25),\n rotate_limit=20, p=0.5), # rotation_range=20,\n RandomBrightnessContrast(brightness_limit=(\n 0.4, 1.5), p=0.5), # brightness_range=[0.4,1.5]\n # shear_range=0.01,fill_mode='reflect'\n IAAAffine(shear=0.01, mode='reflect', p=0.5)\n ], p=1)\n\ndef fill_missing(source, nb_needed, iden):\n if nb_needed > 0:\n print('Filling:', iden)\n augmented = []\n for i in tqdm(range(nb_needed)):\n img = random.choice(source)\n img = aug()(image=img)\n img = img['image']\n img = img.astype(np.uint8)\n augmented.append(img)\n return source + augmented\n else:\n return source\n\n\ndef _bytes_feature(value):\n return tf.train.Feature(bytes_list=tf.train.BytesList(value=[value]))\n\n\ndef _int64_feature(value):\n return tf.train.Feature(int64_list=tf.train.Int64List(value=[value]))\n\n\ndef _float_feature(value):\n return tf.train.Feature(float_list=tf.train.FloatList(value=[value]))\n\n\ndef to_tfrecord(data, labels, save_dir, r_num):\n tfrecord_name = '{}.tfrecord'.format(r_num)\n tfrecord_path = os.path.join(save_dir, tfrecord_name)\n with tf.io.TFRecordWriter(tfrecord_path) as writer:\n for img, label in zip(data, labels):\n _, img_coded = cv2.imencode('.png', img)\n # Byte conversion\n image_png_bytes = img_coded.tobytes()\n data = {'image': _bytes_feature(image_png_bytes),\n 'label': _int64_feature(label)\n }\n features = tf.train.Features(feature=data)\n example = tf.train.Example(features=features)\n serialized = example.SerializeToString()\n writer.write(serialized)\n\n\ndef genTFRecords(_data, _labels, save_dir):\n for i in tqdm(range(0, len(_data), DATA_NUM)):\n data = _data[i:i + DATA_NUM]\n labels = _labels[i:i + DATA_NUM]\n r_num = i // DATA_NUM\n to_tfrecord(data, labels, save_dir, r_num)\n\n\ndef get_input_args():\n ''' \n 1. Read command line arguments and convert them into the apropriate data type. \n 2. Returns a data structure containing everything that have been read, or the default values \n for the paramater that haven't been explicitly specified.\n '''\n parser = argparse.ArgumentParser()\n \n parser.add_argument('--data_location', type = str, default=os.path.join(os.getcwd(),'data'), help = 'The h5 filed location')\n\n in_args = parser.parse_args()\n\n return in_args\nargs = get_input_args()\n\nDIM = (75, 75) # @param\nTRAIN_DATA_PER_CLASS = 10240 # @param\nroot = args.data_location if os.path.exists(args.data_location) else os.path.join(root, 'data')\nTRAIN_DIR = os.path.join(root, 'train')\nTEST_DIR = os.path.join(root, 'test')\n\nclass_names = ['ph1',\n 'slotted6.5',\n 'torx7',\n 'allen2.75',\n 'ph2',\n 'allen4',\n 'torx8',\n 'slotted4.5',\n 'torx9',\n 'torx6',\n 'slotted10',\n 'allen2.5']\n\n\n\n\nNEEDED_DATA = []\nDATA_LIST = []\n# training data\nfor class_name in class_names:\n # class h5\n try:\n h5path = os.path.join(TRAIN_DIR, f\"{class_name}.h5\")\n # class data\n class_data = list(readh5(h5path))\n DATA_LIST.append(class_data)\n # needed data\n needed_data = TRAIN_DATA_PER_CLASS - len(class_data)\n NEEDED_DATA.append(needed_data)\n print('Class_name:{} Found Data:{} Needed:{}'.format(class_name,\n len(class_data),\n needed_data))\n except:\n continue\n\n\n# record dir\ntf_dir = create_dir(os.getcwd(), TFIDEN)\ntf_train = create_dir(tf_dir, 'Train')\ntf_eval = create_dir(tf_dir, 'Eval')\n\n\n\n_DATA = []\n_LABELS = []\nfor class_data, class_name, needed_data, idx in zip(\n DATA_LIST, class_names, NEEDED_DATA, range(len(class_names))):\n class_data = fill_missing(class_data, needed_data, class_name)\n _DATA += class_data\n _labels = [idx for _ in range(len(class_data))]\n _LABELS += _labels\n\n_comb = list(zip(_DATA, _LABELS))\nrandom.shuffle(_comb)\nTraining_data, Training_labels = zip(*_comb)\n\n\n\nTesting_data = []\nTesting_labels = []\n# testing data\nfor class_name in tqdm(class_names):\n # class h5\n h5path = os.path.join(TEST_DIR, f\"{class_name}.h5\")\n # class data\n class_data = list(readh5(h5path))\n Testing_data += class_data\n labels = [class_names.index(class_name) for _ in range(len(class_data))]\n Testing_labels += labels\n\n_comb = list(zip(Testing_data, Testing_labels))\nrandom.shuffle(_comb)\nTesting_data, Testing_labels = zip(*_comb)\n\n\nDATA_NUM = 2048 # @param\n\n# train Data\nprint('Creating training tfrecords')\ngenTFRecords(Training_data, Training_labels, tf_train)\n# eval\nprint('Creating eval tfrecords')\ngenTFRecords(Testing_data, Testing_labels, tf_eval)\n\n","sub_path":"screw_classification/data.py","file_name":"data.py","file_ext":"py","file_size_in_byte":6629,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"510462331","text":"import re\nimport networkx as nx\nfrom networkx.algorithms import community\nimport matplotlib.pyplot as plt\nimport csv\nimport operator\nimport random\n\ndef is_integer(string):\n try: \n int(string)\n return True\n except ValueError:\n return False\n\ndef print_average_and_variance(hash_map, name):\n total = 0\n for val in hash_map:\n total += hash_map[val]\n\n average = total / len(hash_map)\n\n varianceSum = 0\n for val in hash_map:\n varianceSum += (hash_map[val] - average) ** 2\n\n variance = varianceSum / (len(hash_map) - 1)\n \n print (\"{} average: {}, variance: {}\".format(name, average, variance)) \n\nusers = dict()\n\nwith open('distinct_users_from_search_table_real_map.csv') as csvfile:\n reader = csv.DictReader(csvfile)\n for row in reader:\n users[row['user_id']] = row['indegree']\n\nmostFollowed = max(users.iteritems(),key=lambda x: int(operator.itemgetter(1)(x)))\nmostFollowedUID = int(mostFollowed[0])\n\nprint(mostFollowed)# we find britney spears. (Most followed in the follower sql dump.)\nfollowers = dict()\nstatus = False\nindex = 0\nwith open(\"active_follower_real.sql\") as myfile:\n for line in myfile:\n if status:\n break\n result = re.findall(r'\\(.*?\\)', line)\n for value in result:\n stripped = value.strip('()')\n values = stripped.split(',')\n if len(values) == 2 and is_integer(values[0]) and is_integer(values[1]) and int(values[1]) == mostFollowedUID:\n followers[values[0]] = []\n index += 1\n if index == 10:\n status = True\n break\n\nfollowerGraph = nx.Graph()\nprint(len(followers))\ntotal = 0\nwith open(\"active_follower_real.sql\") as myfile:\n for line in myfile:\n result = re.findall(r'\\(.*?\\)', line)\n for value in result:\n stripped = value.strip('()')\n values = stripped.split(',')\n if len(values) == 2 and is_integer(values[0]) and is_integer(values[1]) and followers.has_key(values[1]):\n followerGraph.add_edge(values[0], values[1])\n\nclique_1_list = nx.find_cliques(followerGraph)\nprint(\"1-Clique: \")\nlargest_1_clique = 0\ntotal_1_clique = 0\nfor val in clique_1_list:\n total_1_clique += 1\n if len(val) > largest_1_clique:\n largest_1_clique = len(val)\nprint(\"{} count: {}\".format(largest_1_clique, total_1_clique))\n\nclique_2_set = community.k_clique_communities(followerGraph, 2)\nclique_2_list = list()\nfor cset in clique_2_set:\n clique_2_list.append(list(cset))\n\nclique_3_set = community.k_clique_communities(followerGraph, 3)\n\nclique_3_list = list()\nfor cset in clique_3_set:\n clique_3_list.append(list(cset))\n\nprint(\"2-Clique: \")\nfor l in clique_2_list:\n print(len(l))\n\nprint(\"3-Clique: \")\nfor l in clique_3_list:\n print(len(l))\n\ndef club(graph, k, node):\n potentialNodes = list()\n lengthInfo = nx.single_source_shortest_path_length(graph, node, k)\n\n for node in lengthInfo:\n validNode = True \n for node_ in potentialNodes:\n lengthInfo_ = nx.single_source_shortest_path_length(graph, node_, k)\n if not lengthInfo_.has_key(node):\n validNode = False\n break\n\n if validNode:\n potentialNodes.append(node)\n\n if len(potentialNodes):\n potentialNodes.append(node)\n \n return potentialNodes\n\nclub_2_community = list()\nclub_3_community = list()\nclub_2_count = 0\nclub_3_count = 0\n\nfor node in followerGraph.nodes():\n club_2_community = club(followerGraph, 2, node)\n if len(club_2_community):\n print(\"2-club community: source node: {}, size: {}\".format(node, len(club_2_community)))\n club_2_count += 1\n \n club_3_community = club(followerGraph, 3, node)\n if len(club_3_community):\n print(\"3-club community: source node: {}, size: {}\".format(node, len(club_3_community)))\n club_3_count += 1\n\n if club_2_count >= 5 and club_3_count >= 5:\n break","sub_path":"Exercise_3.py","file_name":"Exercise_3.py","file_ext":"py","file_size_in_byte":4007,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"523992785","text":"\n\nfrom xai.brain.wordbase.verbs._bulldoze import _BULLDOZE\n\n#calss header\nclass _BULLDOZED(_BULLDOZE, ):\n\tdef __init__(self,): \n\t\t_BULLDOZE.__init__(self)\n\t\tself.name = \"BULLDOZED\"\n\t\tself.specie = 'verbs'\n\t\tself.basic = \"bulldoze\"\n\t\tself.jsondata = {}\n","sub_path":"xai/brain/wordbase/verbs/_bulldozed.py","file_name":"_bulldozed.py","file_ext":"py","file_size_in_byte":252,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"600374037","text":"import matplotlib.pyplot as plt\nfrom argparse import ArgumentParser\nimport pandas as pd\nfrom os.path import splitext\n\n\nplt.style.use('ggplot')\n\n\ndef plot(fpath):\n df = pd.read_csv(fpath, sep=',', names=['Step', 'batch_size', 'Speed', 'Accuracy', 'Loss', 'LR'])\n df[df.Step < 1e5].plot('Step', ['Accuracy', 'Loss', 'LR'], subplots=True, layout=(1, 3), figsize=(13, 3))\n plt.tight_layout()\n plt.savefig(splitext(fpath)[0] + '.pdf')\n\n\nif __name__ == '__main__':\n parser = ArgumentParser()\n parser.add_argument('--file', type=str)\n args = parser.parse_args()\n plot(args.file)\n","sub_path":"assignment_2/part2/plot.py","file_name":"plot.py","file_ext":"py","file_size_in_byte":596,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"344622439","text":"'''\ncrea esercizi in partita doppia come questo:\n\nhttps://aziendaitalia.altervista.org/esercizio-in-partita-doppia-sulle-vendite/\n\n\n'''\n\n\n\n\ndef esercizio(text, dati):\n ''' creates a text with a table with the account name and the 2 sections Dare Avere '''\n global testo, sol, darecount, averecount\n\n # Creazione del conto in html\n traccia(text)\n for conto in dati:\n titolo, dare, avere = conto\n testo += f\"\"\"\n\n \n\n \n \n \n
{titolo}
\n \n


\n\n\n\n \"\"\"\n sol += f\"{dare} {avere} | \"\n obj_input_name.append([f\"dare{darecount}.value\", f\"avere{averecount}.value\"])\n darecount +=1\n averecount +=1\n \n\n\ndef pulsante_di_verifica():\n ''' call this at the end of the conti(...) to see if the user inputs are right '''\n global testo, sol, stringa\n\n sol = sol[:-1]\n stringa = \"\"\n for d,a in obj_input_name:\n stringa += f\"{d} + ' ' + {a} + ' | ' + \"\n stringa = stringa[:-6]\n stringa = stringa + \"|'\"\n # stringa += \"'|'\"\n testo += f\"\"\"\n\n\n\n \"\"\"\n return stringa\n\n\ndef tag(_t, testo):\n ''' Easy create html tags\n\n Example\n\n tag('p', 'hello')\n\n output\n\n

hello

\n '''\n return f\"<{_t}>{testo}\"\n\n\nstringa = \"\"\ndarecount = 1\naverecount = 1\ntesto = \"\"\nsol = \"\"\nobj_input_name = []\n\n\nescount = 1\ndef traccia(testo_traccia):\n ''' prints the text to make the exercise, call this before conti(...) '''\n global testo, escount\n testo_puro = testo\n tracc = tag(\"p\", testo_traccia)\n tracc = tag(\"h3\", f\"Esercizio {escount}\") + tracc\n escount += 1\n testo = testo + tag(\"p\", tracc)\n \n \n\n# ==================== | ESERCIZIO 1 | ====================================== #\nesercizio(\"Emessa fattura per 250 € + 10% di IVA\",(\n (\"Crediti v/clienti\", \"275\", \"0\"),\n (\"Iva a debito\", \"0\", \"25\"),\n (\"Merci c/vendite\", \"0\", \"250\")))\n\n\n# ============= ESERCIZIO 2 ================== tutti i prossimi esercizi così\nesercizio(\"Ricevuto pagamento in contanti per fattura di vendita precedente\",(\n (\"Denaro in cassa\", \"275\", \"0\"),\n (\"Crediti v/clienti\", \"0\", \"275\")))\n\n\n# Pulsante finale di verifica\npulsante_di_verifica()\n\n# Copia questo testo in un file html\nprint(testo)\n\n# This is for the blog\n# print(\"[hoops name='all']\")\n","sub_path":"quizliveQuestions/vendita4_solo_vendita.py","file_name":"vendita4_solo_vendita.py","file_ext":"py","file_size_in_byte":2772,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"198087910","text":"import requests\nfrom pyquery import PyQuery\nfrom ebooks.provider.ebook import Ebook\nfrom ebooks.provider.ebook_provider import EbookProvider\n\n\nclass DuokanEbookProvider(EbookProvider):\n def __init__(self):\n self.url = 'https://www.duokan.com/search/{}/{}'\n\n def get_ebooks(self, title, last_book_index, page_index):\n url = self.url.format(title, page_index)\n response = requests.get(url)\n\n if response.status_code != requests.codes.ok:\n raise Exception(response.text)\n\n document = PyQuery(response.text)\n books = [PyQuery(book) for book in document.find('.u-list li')]\n\n return list(map(self.__convert_to_ebook, books))\n\n def __convert_to_ebook(self, book):\n ebook = Ebook()\n ebook.title = book.find('.title').text()\n ebook.author = book.find('.u-author').text()\n ebook.price = float(\n book.find('.u-price em').text().replace('¥', '').strip())\n ebook.cover = book.find('.cover img').attr('src')\n ebook.intro = book.find('.desc').text()\n\n return ebook\n","sub_path":"ebooks/provider/duokan.py","file_name":"duokan.py","file_ext":"py","file_size_in_byte":1081,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"100825670","text":"import os\r\nimport sys\r\nimport pathlib\r\nimport numpy as np\r\nfrom skimage import filters\r\nfrom quanfima import morphology as mrph\r\n#from quanfima import visualization as vis\r\nfrom quanfima import utils\r\n\r\ninput_dir = pathlib.Path(r\"D:\\Desktop\\quanfima\\data\")\r\ninput_file = \"polymer3d_8bit_128x128x128.raw\"\r\n\r\ninputImage = pathlib.Path(input_dir).joinpath(input_file)\r\noutput_dir = pathlib.Path(input_dir).joinpath(\"results\")\r\n\r\ndata = np.memmap(inputImage, shape=(128,128,128), dtype=np.uint8, mode='r')\r\n\r\ndata_seg = np.zeros_like(data, dtype=np.uint8)\r\nfor i in range(data_seg.shape[0]):\r\n th_val = filters.threshold_otsu(data[i])\r\n data_seg[i] = (data[i] > th_val).astype(np.uint8)\r\n\r\n# estimate porosity\r\npr = mrph.calc_porosity(data_seg)\r\nfor k,v in pr.items():\r\n print(f'Porosity ({k}): {v}')\r\n\r\n# prepare data and analyze fibers\r\npdata, pskel, pskel_thick = utils.prepare_data(data_seg)\r\n\r\noprops = mrph.estimate_tensor(name=\"test\",\r\n skel=pskel,\r\n data=pskel_thick,\r\n window_size=64,\r\n output_dir=output_dir,\r\n sigma=0.025,\r\n make_output=True,\r\n original=False)\r\n\r\noprops = mrph.estimate_tensor_parallel(name='polymer_orientation_w32',\r\n skel=pskel,\r\n data=pskel_thick,\r\n window_size=32,\r\n output_dir=output_dir,\r\n sigma=0.025,\r\n make_output=True,\r\n n_processes=8,\r\n original=False)\r\n\r\nodata = np.load(oprops['output_path'], allow_pickle=True).item()\r\nlat, azth, skel = odata['lat'], odata['azth'], odata['skeleton']\r\n\r\ndprops = mrph.estimate_diameter_single_run(name='polymer_diameter',\r\n output_dir=output_dir,\r\n data=pdata,\r\n skel=skel,\r\n lat_data=lat,\r\n azth_data=azth,\r\n n_scan_angles=32,\r\n make_output=True)\r\n\r\ndmtr = np.load(dprops['output_path'], allow_pickle=True).item()['diameter']\r\n\r\n# plot results\r\nvis.plot_3d_orientation_map('polymer_w32', lat, azth,\r\n output_dir='../../data/results',\r\n camera_azth=40.47,\r\n camera_elev=32.5,\r\n camera_fov=35.0,\r\n camera_loc=(40.85, 46.32, 28.85),\r\n camera_zoom=0.005124)\r\n\r\nvis.plot_3d_diameter_map('polymer_w32', dmtr,\r\n output_dir='../../data/results',\r\n measure_quantity='vox',\r\n camera_azth=40.47,\r\n camera_elev=32.5,\r\n camera_fov=35.0,\r\n camera_loc=(40.85, 46.32, 28.85),\r\n camera_zoom=0.005124,\r\n cb_x_offset=5,\r\n width=620)","sub_path":"quanfima/Thickness_orientation.py","file_name":"Thickness_orientation.py","file_ext":"py","file_size_in_byte":3377,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"22321884","text":"\"\"\"\nThis script takes both provider sources stored in `provider_sources`, removes items\nwhich do not represent actual providers (metadata from leaflet-providers-parsed and\ntemplates from xyzservices-providers), combines them together and saves as a compressed\nJSON to data/providers.json.\n\nThe compressed JSON is shipped with the package.\n\"\"\"\n\nimport json\n\nwith open(\"./leaflet-providers-parsed.json\", \"r\") as f:\n leaflet = json.load(f)\n # remove meta data\n leaflet.pop(\"_meta\", None)\n\nwith open(\"./xyzservices-providers.json\", \"r\") as f:\n xyz = json.load(f)\n # remove templates\n xyz.pop(\"single_provider_name\")\n xyz.pop(\"provider_bunch_name\")\n\n\n# combine both\nleaflet.update(xyz)\n\nwith open(\"../xyzservices/data/providers.json\", \"w\") as f:\n json.dump(leaflet, f, indent=4)\n","sub_path":"provider_sources/_compress_providers.py","file_name":"_compress_providers.py","file_ext":"py","file_size_in_byte":798,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"538586014","text":"import scrapy\n\n\nclass GoodsSpider(scrapy.Spider):\n name = \"goods\"\n start_urls = [\n 'https://www.goods.ph/category/online-shopping-mobiles-and-tablets-159.html',\n ]\n\n def parse(self, response):\n for elem in response.css('div.product-list div.item'):\n yield {\n 'title': elem.css('div.product-head a::text').extract_first().strip(),\n 'link': 'https://www.goods.ph' + elem.css('div.product-head a::attr(\"href\")').extract_first(),\n }\n next_page = response.css('div.product-bottom a::attr(\"href\")').extract()[-1]\n\n if next_page is not None:\n yield response.follow(next_page, self.parse)\n","sub_path":"siteUrlsScrappers/ScrapperGoods.py","file_name":"ScrapperGoods.py","file_ext":"py","file_size_in_byte":684,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"461025444","text":"import string\r\nfile=open(\"example.txt\",\"r\")\r\nd1=dict()\r\nfor line in file:\r\n line=line.strip()\r\n line = line.lower()\r\n line = line.translate(line.maketrans(\"\", \"\", string.punctuation))\r\n words = line.split(\" \") \r\n for word in words: \r\n if word in d1: \r\n d1[word] = d1[word] + 1\r\n else: \r\n d1[word] = 1\r\nfor key in d1:\r\n print(key,\":\",d1[key])\r\n ","sub_path":"Assignment 1/word count.py","file_name":"word count.py","file_ext":"py","file_size_in_byte":399,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"212708960","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\n\"\"\"a test module\"\"\"\nfrom __future__ import division\nimport re\nimport re as regex\nfrom collections import defaultdict, Counter\nimport random\nfrom functools import partial, reduce\n\n__author__ = '74581'\n\n# 空白形式\n\nfor i in [1, 2, 3, 4, 5]:\n print(i)\n for j in [1, 2, 3, 4, 5]:\n print(j)\n print(i + j)\n print(i)\n print(\"done looping\")\nlong_winded_computation = (1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10 + 11 + 12 + 13 + 14 + 15 + 16 + 17 + 18 + 19 + 20)\nlist_of_lists = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]\neasier_to_read_list_of_lists = [[1, 2, 3],\n [4, 5, 6],\n [7, 8, 9]]\ntwo_plus_three = 2 + \\\n 3\n\n# 模块\n\nmy_regx = re.compile(\"[0-9]+\", re.I)\nmy_regx = regex.compile(\"[0-9]+\", regex.I)\nlookup = defaultdict(int)\nmy_counter = Counter()\n\n\n# 函数\n\ndef double(x):\n \"\"\"this is where you put an optional docstring\n that explains what the function does.\n for example, this function multiplies its input by 2\"\"\"\n return x * 2\n\n\ndef apply_to_one(f):\n \"\"\"calls the function f with 1 as its argument\"\"\"\n return f(1)\n\n\nmy_double = double\nx = apply_to_one(my_double)\nprint(x) # 等于2\ny = apply_to_one(lambda x: x + 4)\nprint(y) # 等于5\n\n\ndef my_print(message=\"my default message\"):\n print(message)\n\n\nmy_print(\"hello\") # 打印\"hello\"\nmy_print() # 打印\"my default message\"\n\n\ndef subtract(a=0, b=0):\n return a - b\n\n\nsubtract(10, 5) # 返回5\nsubtract(0, 5) # 返回-5\nsubtract(b=5) # 和前一句一样\n\n# 字符串\n\nsingle_quoted_string = 'data science'\ndouble_quoted_string = \"data science\"\ntab_string = \"\\t\" # 表示tab字符\nlen(tab_string) # 是1\nnot_tab_string = r\"\\t\" # 表示字符'\\'和't'\nlen(not_tab_string) # 是2\nmulti_line_string = \"\"\"This is the first line.\nand this is the second line\nand this is the third line\"\"\"\nprint(multi_line_string)\n\n# 异常\n\ntry:\n print(0 / 0)\nexcept ZeroDivisionError:\n print(\"cannot divide by zero\")\n\n# 列表\n\ninteger_list = [1, 2, 3]\nheterogeneous_list = [\"string\", 0.1, True]\nlist_of_lists_second = [integer_list, heterogeneous_list, []]\nlist_length = len(integer_list) # 等于3\nlist_sum = sum(integer_list) # 等于6\nx = range(10) # 是列表[0, 1, ..., 9]\nx = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]\nzero = x[0] # 等于0,列表是0-索引的\none = x[1] # 等于1\nnine = x[-1] # 等于9,最后一个元素的Python惯用法\neight = x[-2] # 等于8,倒是第二个元素的Python惯用法\nx[0] = -1 # 现在是[-1, 1, 2, 3, ..., 9]\nfirst_three = x[:3] # [-1, 1, 2]\nthree_to_end = x[3:] # [3, 4, ..., 9]\none_to_four = x[1:5] # [1, 2, 3, 4]\nlast_three = x[-3:] # [7, 8, 9]\nwithout_first_and_last = x[1:-1] # [1, 2, ..., 8]\ncopy_of_x = x[:] # [-1, 1, 2, ..., 9]\nprint(1 in [1, 2, 3]) # True\nprint(0 in [1, 2, 3]) # False\nx = [1, 2, 3]\nx.extend([4, 5, 6]) # x现在是[1, 2, 3, 4, 5, 6]\nx = [1, 2, 3]\ny = x + [4, 5, 6] # y是[1, 2, 3, 4, 5, 6];x是不变的\nx.append(0) # x现在是[1, 2, 3, 0]\ny = x[-1] # 等于0\nz = len(x) # 等于4\nx, y = [1, 2] # 现在x是1,y是2\n_, y = [1, 2] # 现在y==2,不用关心第一个元素是什么\n\n# 元组\n\nmy_list = [1, 2]\nmy_tuple = (1, 2)\nother_tuple = 3, 4\nmy_list[1] = 3 # my_list现在是[1, 3]\ntry:\n my_tuple[1] = 3\nexcept TypeError:\n print(\"cannot modify a tuple\")\n\n\ndef sum_and_product(x, y):\n return (x + y), (x * y)\n\n\nsp = sum_and_product(2, 3) # 等于(5, 6)\ns, p = sum_and_product(5, 10) # s是15,p是50\nx, y = 1, 2 # 现在x是1,y是2\nx, y = y, x # Python风格的互换变量,现在x是2,y是1\n\n# 字典\n\nempty_dict = {} # Python风格\nempty_dict2 = dict() # 更少的Python风格\ngrades = {\"Joel\": 80, \"Tim\": 95}\njoels_grade = grades[\"Joel\"] # 等于80\ntry:\n kates_grade = grades[\"Kate\"]\nexcept KeyError:\n print(\"no grade for Kate!\")\njoel_has_grade = \"Joel\" in grades # 正确\nkate_has_grade = \"Kate\" in grades # 错误\njoels_grade = grades.get(\"Joel\", 0) # 等于80\nkates_grade = grades.get(\"Kate\", 0) # 等于0\nno_ones_grade = grades.get(\"No One\") # 默认的默认值为None\ngrades[\"Tim\"] = 99 # 替换了旧的值\ngrades[\"Kate\"] = 100 # 增加了第三个记录\nnum_students = len(grades) # 等于3\ntweet = {\n \"user\": \"joelgrus\",\n \"text\": \"Data Science is Awesome\",\n \"retweet_count\": 100,\n \"hashtags\": [\"#data\", \"#science\", \"#datascience\", \"#awesome\", \"#yolo\"]\n}\ntweet_keys = tweet.keys() # 键的列表\ntweet_values = tweet.values() # 值的列表\ntweet_items = tweet.items() # (键,值)元组的列表\n\"user\" in tweet_keys # True, 使用慢速的列表\n\"user\" in tweet # 更符合Python惯用法,使用快速的字典\n\"joelgrus\" in tweet_values # True\n\n# defaultdict\nword_counts = {}\ndocument = [\"a\", \"b\", \"b\"]\nfor word in document:\n if word in word_counts:\n word_counts[word] += 1\n else:\n word_counts[word] = 1\nfor word in document:\n try:\n word_counts[word] += 1\n except KeyError:\n word_counts[word] = 1\nfor word in document:\n previous_count = word_counts.get(word, 0)\n word_counts[word] = previous_count + 1\nword_counts = defaultdict(int) # int()生成0\nfor word in document:\n word_counts[word] += 1\ndd_list = defaultdict(list) # list()生成���个空列表\ndd_list[2].append(1) # 现在dd_list包含{2:[1]}\ndd_list = defaultdict(dict) # dict()产生一个新字典\ndd_list[\"Joel\"][\"City\"] = \"Seattle\" # {\"Joel\": {\"City\": \"Seattle\"}}\ndd_pair = defaultdict(lambda: [0, 0])\ndd_pair[2][1] = 1 # 现在dd_pair包含{2: [0,1]}\n\n# Counter\nc = Counter([0, 1, 2, 0]) # c是(基本的){0: 2, 1: 1, 2: 1}\nword_counts = Counter(document)\n# 打印10个最常见的词和它们的计数\nfor word, count in word_counts.most_common(10):\n print(word, count)\n\n# 集合\n\ns = set()\ns.add(1) # s现在是1\ns.add(2) # s现在是{1, 2}\ns.add(2) # s还是{1,2}\nx = len(s) # 等于2\ny = 2 in s # 等于True\nz = 3 in s # 等于False\nhundreds_of_other_words = []\nstopwords_list = [\"a\", \"an\", \"at\"] + hundreds_of_other_words + [\"yet\", \"you\"]\n\"zip\" in stopwords_list # False,但需要检查每个元素\nstopwords_set = set(stopwords_list)\n\"zip\" in stopwords_set # 非常快地检查\nitem_list = [1, 2, 3, 1, 2, 3]\nnum_items = len(item_list) # 6\nitem_set = set(item_list) # {1, 2, 3}\nnum_distinct_items = len(item_set) # 3\ndistinct_item_list = list(item_set) # [1, 2, 3]\n\n# 控制流\n\nif 1 > 2:\n message = \"if only 1 were greater than two...\"\nelif 1 > 3:\n message = \"elif stands for 'else if'\"\nelse:\n message = \"when all else fails use else (if you want to)\"\nparity = \"even\" if x % 2 == 0 else \"odd\"\nx = 0\nwhile x < 10:\n print(x, \"is less than 10\")\n x += 1\nfor x in range(10):\n print(x, \"is less than 10\")\nfor x in range(10):\n if x == 3:\n continue # 直接进入下次迭代\n if x == 5:\n break # 完全退出循环\n print(x)\n\n# 真和假\n\none_is_less_than_two = 1 < 2 # 等于True\ntrue_equals_false = True == False # 等于False\nx = None\nprint(x == None) # 打印True,但这并非Python的惯用法\nprint(x is None) # 打印True,符合Python的惯用法\n\n\ndef some_function_that_returns_a_string():\n return \"\"\n\n\ns = some_function_that_returns_a_string()\nif s:\n first_char = s[0]\nelse:\n first_char = \"\"\nfirst_char = s and s[0]\nsafe_x = x or 0\nall([True, 1, {3}]) # True\nall([True, 1, {}]) # False,{}为假\nany([True, 1, {}]) # True\nall([]) # True,列表里没有假的元素\nany([]) # False,列表里没有真的元素\n\n# 排序\n\nx = [4, 1, 2, 3]\ny = sorted(x) # 结果是[1, 2, 3, 4],但x没有变\nx.sort() # x变为[1, 2, 3, 4]\n# 通过绝对值对列表元素从最大到最小排血\nx = sorted([-4, 1, -2, 3], key=abs, reverse=True) # 是[-4, 3, -2, 1]\n# 从最高数到最低数排序单词和计数\nwc = sorted(word_counts.items(),\n key=lambda x: x[1],\n reverse=True)\n\n# 列表解析\n\neven_numbers = [x for x in range(5) if x % 2 == 0] # [0, 2, 4]\nsquares = [x * x for x in range(5)] # [0, 1, 4, 9, 16]\neven_squares = [x * x for x in even_numbers] # [0, 4, 16]\nsquare_dict = {x: x * x for x in range(5)} # {0:0, 1:1, 2:4, 3:9, 4:16}\nsquare_set = {x * x for x in [1, -1]} # {1}\nzeroes = [0 for _ in even_numbers] # 和even_numbers有相同的长度\npairs = [(x, y)\n for x in range(10)\n for y in range(10)] # 100个对(0,0)(0,1)...(9,8)(9,9)\nincreasing_pairs = [(x, y) # 只考虑x < y的对\n for x in range(10) # range(lo, hi)与之相等\n for y in range(x + 1, 10)] # [lo, lo + 1, ..., hi - 1]\n\n\n# 生成器和迭代器\n\ndef lazy_range(n):\n \"\"\"a lazy version of range\"\"\"\n i = 0\n while i < n:\n yield i\n i += 1\n\n\ndef do_something_with(x, y=0):\n pass\n\n\nfor i in lazy_range(10):\n do_something_with(i)\n\n\ndef natural_numbers():\n \"\"\"returns 1, 2, 3, ...\"\"\"\n n = 1\n while True:\n yield n\n n += 1\n\n\nlazy_evens_below_20 = (i for i in lazy_range(20) if i % 2 == 0)\n\n# 随机性\n\n# random.random()生成在0-1之间均匀分布的随机数,是最常用的随机函数\nfour_uniform_randoms = [random.random() for _ in range(4)]\nrandom.seed(10) # 设置随机数种子为10\nprint(random.random()) # 0.5714025946899135\nrandom.seed(10) # 重设随机数种子为10\nprint(random.random()) # 再次得到0.5714025946899135\nrandom.randrange(10) # 从range(10) = [0, 1, ..., 9]中随机选取\nrandom.randrange(3, 6) # 从range(3, 6) = [3, 4, 5]中随机选取\nup_to_ten = []\nfor i in range(10):\n up_to_ten.append(i)\nrandom.shuffle(up_to_ten)\nprint(up_to_ten)\nmy_best_friend = random.choice([\"Alice\", \"Bob\", \"Charlie\"])\nlottery_numbers = range(60)\nwinning_numbers = random.sample(lottery_numbers, 6)\nfour_with_replacement = [random.choice(range(10))\n for _ in range(4)]\n\n# 正则表达式\n\nprint(all([ # 所有这些语句都为true,因为\n not re.match(\"a\", \"cat\"), # *'cat'不以'a'开头\n re.search(\"a\", \"cat\"), # *'cat'里有一个字符'a'\n not re.search(\"c\", \"dog\"), # *'dog'里没有字符'c'\n 3 == len(re.split(\"[ab]\", \"carbs\")), # *分割掉a,b,剩余长度为3\n \"R-D-\" == re.sub(\"[0-9]\", \"-\", \"R2D2\") # 用虚线进行位的替换\n])) # 打印True\n\n\n# 面向对象的编程\n\n# 按惯例,我们给下面的类起个PascalCase的名字\nclass Set:\n # 这些是成员函数\n # 每个函数都取第一个参数\"self\"(另一种惯例)\n # 它表示所用到的特别的集合对象\n def __init__(self, values=None):\n \"\"\"This is the constructor.\n It gets called when you create a new Set.\n You would use it like\n s1 = Set() # 空集合\n s2 = Set([1, 2, 2, 3]) # 用值初始化\"\"\"\n self.dict = {} # Set的每一个实例都有自己的dict属性,我们会用这个属性来追踪成员关系\n if values is not None:\n for value in values:\n self.add(value)\n\n def __repr__(self):\n \"\"\"this is the string representation of a Set object\n if you type it at the Python prompt of pass it to str()\"\"\"\n return \"Set: \" + str(self.dict.keys())\n\n # 通过成为self.__dict__中对应值为True的键,来表示成员关系\n def add(self, value):\n self.dict[value] = True\n\n # 如果它在字典中是一个键,那么在集合中就是一个值\n def contains(self, value):\n return value in self.dict\n\n def remove(self, value):\n del self.dict[value]\n\n\ns = Set([1, 2, 3])\ns.add(4)\nprint(s.contains(4)) # True\ns.remove(3)\nprint(s.contains(3)) # False\n\n\n# 函数式工具\n\ndef exp(base, power):\n return base ** power\n\n\ndef two_to_the(power):\n return exp(2, power)\n\n\ntwo_to_the = partial(exp, 2) # 现在是一个包含一个变量的函数\nprint(two_to_the(3))\nsquare_of = partial(exp, power=2)\nprint(square_of(3)) # 9\n\n\ndef double(x):\n return 2 * x\n\n\nxs = [1, 2, 3, 4]\ntwice_xs = [double(x) for x in xs] # [2, 4, 6, 8]\ntwice_xs = map(double, xs) # 和上面一样\nlist_doubler = partial(map, double) # double了一个列表的*function*\ntwice_xs = list_doubler(xs) # 同样是[2, 4, 6, 8]\n\n\ndef multiply(x, y):\n return x * y\n\n\nproducts = map(multiply, [1, 2], [4, 5]) # [1 * 4, 2 * 5] = [4, 10]\n\n\ndef is_even(x):\n \"\"\"True if x is even, False if x is odd\"\"\"\n return x % 2 == 0\n\n\nx_evens = [x for x in xs if is_even(x)] # [2, 4]\nx_evens = filter(is_even, xs) # 和上面一样\nlist_evener = partial(filter, is_even) # filter了一个列表的*function*\nx_evens = list_evener(xs) # 同样是[2, 4]\n\nx_product = reduce(multiply, xs) # = 1 * 2 * 3 * 4 = 24\nlist_product = partial(reduce, multiply)\nx_product = list_product(xs) # 同样是24\n\n# 枚举\n\n# 非Python用法\nfor i in range(len(document)):\n documents = document[i]\n do_something_with(i, document)\n# 也非Python用法\ni = 0\nfor document in documents:\n do_something_with(i, document)\n i += 1\nfor i, document in enumerate(documents):\n do_something_with(i, documents)\nfor i in range(len(documents)):\n do_something_with(i) # 非Python用法\nfor i, _ in enumerate(documents):\n do_something_with(i) # Python用法\n\n# 压缩和参数拆分\n\nlist1 = ['a', 'b', 'c']\nlist2 = [1, 2, 3]\nzip(list1, list2) # 是[('a', 1), ('b', 2), ('c', 3)]\npairs = [('a', 1), ('b', 2), ('c', 3)]\nletters, numbers = zip(*pairs)\nzip(('a', 1), ('b', 2), ('c', 3)) # [('a', 'b', 'c'), ('1', '2', '3')]\n\n\ndef add(a, b):\n return a + b\n\n\nadd(1, 2) # 返回3\nadd(*[1, 2]) # 返回3\n\n\n# args和kwargs\n\ndef doubler(f):\n def g(x):\n return 2 * f(x)\n\n return g\n\n\ndef f1(x):\n return x + 1\n\n\ng = doubler(f1)\nprint(g(3)) # 8(== (3 + 1) * 2)\nprint(g(-1)) # 0(== (-1 + 1) * 2)\n\n\ndef magic(*args, **kwargs):\n print(\"unnamed args:\", args)\n print(\"keyword args:\", kwargs)\n\n\nmagic(1, 2, key=\"word\", key2=\"word2\")\n\n\ndef other_way_magic(x, y, z):\n return x + y + z\n\n\nx_y_list = [1, 2]\nz_dict = {\"z\": 3}\nprint(other_way_magic(*x_y_list, **z_dict)) # 6\n\n\ndef doubler_correct(f):\n \"\"\"works no matter what kind of inputs f expects\"\"\"\n\n def g(*args, **kwargs):\n \"\"\"whatever arguments g is supplied, pass them through to f\"\"\"\n return 2 * f(*args, **kwargs)\n\n return g\n\n\ndef f2(x, y):\n return x + y\n\n\ng = doubler_correct(f2)\nprint(g(1, 2)) # 6\n","sub_path":"2.Python_crash.py","file_name":"2.Python_crash.py","file_ext":"py","file_size_in_byte":14294,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"612879118","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Nov 18 14:21:49 2014\n\n@author: CTremblay\n\"\"\"\n\nclass Histories():\n \"\"\"\n This class gathers every histories on the Jace\n \"\"\"\n def __init__(self, session):\n self._allHistories = []\n self._filteredList = []\n self._his = {'name':'',\n 'id':''}\n \n for each in session.read(\"read?filter=his\")['rows']: \n self._his['name'] = each['id'].split(' ',1)[1]\n self._his['id'] = each['id'].split(' ',1)[0]\n self._allHistories.append(self._his.copy())\n \n def getListofIdsAndNames(self):\n return self._allHistories\n ","sub_path":"pyhaystack/history/Histories.py","file_name":"Histories.py","file_ext":"py","file_size_in_byte":678,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"468226899","text":"\nimport hashlib\nimport time\nimport numpy as np\nimport matplotlib.mlab as mlab\nimport matplotlib.pyplot as plt\nfrom scipy.ndimage.filters import maximum_filter\nfrom scipy.ndimage.morphology import (generate_binary_structure,\n iterate_structure, binary_erosion)\nfrom pydub import AudioSegment\nfrom pydub.utils import audioop\nfrom hashlib import sha1\nfrom operator import itemgetter\n\n#根据音乐文件名生成哈希字符串\ndef unique_hash(filepath, blocksize=2**20):\n\n s = sha1()\n with open(filepath , \"rb\") as f:\n while True:\n buf = f.read(blocksize)\n if not buf:\n break\n s.update(buf)\n return s.hexdigest().upper()\n\n#读取mp3文件,返回通道,取样数,文件名哈希字符串\ndef read(filename):\n \n audiofile = AudioSegment.from_mp3(filename)\n data = np.fromstring(audiofile._data, np.int16)\n channels = []\n for chn in range(audiofile.channels):\n channels.append(data[chn::audiofile.channels])\n fs = audiofile.frame_rate\n\n return channels, audiofile.frame_rate, unique_hash(filename)\n\nIDX_FREQ_I = 0#频率下标\nIDX_TIME_J = 1#时间下标\nDEFAULT_FS = 44100#采样率\nDEFAULT_WINDOW_SIZE = 4096#FFT窗口大小\nDEFAULT_OVERLAP_RATIO = 0.5#重叠率\nDEFAULT_FAN_VALUE = 10#每个点配对数\nDEFAULT_AMP_MIN = 20#峰值点最低最低振幅\nPEAK_NEIGHBORHOOD_SIZE = 20#峰值点邻域范围\nMIN_HASH_TIME_DELTA = 2\nMAX_HASH_TIME_DELTA = 200\nPEAK_SORT = True#临时为峰值点排序\nFINGERPRINT_REDUCTION = 20\n\ndef fingerprint(channel_samples, Fs=DEFAULT_FS,\n wsize=DEFAULT_WINDOW_SIZE,\n wratio=DEFAULT_OVERLAP_RATIO,\n fan_value=DEFAULT_FAN_VALUE,\n amp_min=DEFAULT_AMP_MIN):\n \n arr2D = mlab.specgram(\n channel_samples,\n NFFT=wsize,\n Fs=Fs,\n window=mlab.window_hanning,\n noverlap=int(wsize * wratio))[0]\n\n # apply log transform since specgram() returns linear array\n arr2D = 10 * np.log10(arr2D)\n arr2D[arr2D == -np.inf] = 0 # replace infs with zeros\n\n # find local maxima\n hash_list= get_2D_peaks(arr2D, plot=True, amp_min=amp_min)\n\n return hash_list\n # return hashes\n #phash = generate_hashes(peaks = local_maxima, fan_value=fan_value)\n #return phash\n\ndef get_2D_peaks(arr2D, plot=False, amp_min=DEFAULT_AMP_MIN):\n \n struct = generate_binary_structure(2, 1)\n neighborhood = iterate_structure(struct, PEAK_NEIGHBORHOOD_SIZE)\n\n # 寻找局部峰值点\n local_max = maximum_filter(arr2D, footprint=neighborhood) == arr2D\n background = (arr2D == 0)\n eroded_background = binary_erosion(background, structure=neighborhood, border_value=1)\n\n # Boolean mask of arr2D with True at peaks\n detected_peaks = local_max - eroded_background\n\n # 提取峰值点\n amps = arr2D[detected_peaks]\n j, i = np.where(detected_peaks)\n\n # filter peaks\n amps = amps.flatten()\n peaks = list(zip(i, j, amps))\n peaks_filtered = [x for x in peaks if x[2] > amp_min] # freq, time, amp\n\n # get indices for frequency and time\n frequency_idx = [x[1] for x in peaks_filtered]\n time_idx = [x[0] for x in peaks_filtered]\n\n if plot:\n # scatter of the peaks\n fig, ax = plt.subplots()\n ax.imshow(arr2D)\n ax.scatter(time_idx, frequency_idx)#在图上绘制散点\n ax.set_xlabel('Time')\n ax.set_ylabel('Frequency')\n ax.set_title(\"Spectrogram\")\n plt.gca().invert_yaxis()\n plt.show()\n\n peaklist = list(zip(frequency_idx, time_idx))\n h = []\n\n for i in range(len(peaklist)):\n for j in range(1, DEFAULT_FAN_VALUE):\n if (i + j) < len(peaklist):\n \n freq1 = peaklist[i][IDX_FREQ_I]\n freq2 = peaklist[i + j][IDX_FREQ_I]\n t1 = peaklist[i][IDX_TIME_J]\n t2 = peaklist[i + j][IDX_TIME_J]\n t_delta = t2 - t1\n\n if t_delta >= MIN_HASH_TIME_DELTA and t_delta <= MAX_HASH_TIME_DELTA:\n stmp = \"%s|%s|%s\" % (str(freq1), str(freq2), str(t_delta))\n h.append((hashlib.sha1(stmp.encode('utf-8')).hexdigest().upper(),t1))\n\n return h\n\ndef getsongprint(songname):\n channels, fs, fhash = read(songname)\n #只读取第一个声道\n phash = fingerprint(channel_samples = channels[0], Fs=fs)\n\n return songname, fhash, phash","sub_path":"genprint.py","file_name":"genprint.py","file_ext":"py","file_size_in_byte":4450,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"598020106","text":"# -*- coding: utf-8 -*-\n\"\"\"\nThis is part of WebScout software\nDocs EN: http://hack4sec.pro/wiki/index.php/WebScout_en\nDocs RU: http://hack4sec.pro/wiki/index.php/WebScout\nLicense: MIT\nCopyright (c) Anton Kuzmin (ru) (en)\n\nClass of module ParamsBruterDict\n\"\"\"\n\nfrom classes.modules.ParamsModules import ParamsModules\nfrom classes.generators.FileGenerator import FileGenerator\nfrom classes.modules.params.ParamsDictModuleParams import ParamsDictModuleParams\n\n\nclass ParamsDict(ParamsModules):\n model = None\n mode = 'dict'\n log_path = '/dev/null'\n time_count = True\n options = ParamsDictModuleParams().get_options()\n\n def load_objects(self, queue):\n \"\"\" Prepare generator for work \"\"\"\n generator = FileGenerator(\n self.options['dict'].value,\n int(self.options['parts'].value),\n int(self.options['part'].value)\n )\n queue.set_generator(generator)\n return {'all': generator.lines_count, 'start': generator.first_border, 'end': generator.second_border}\n","sub_path":"classes/modules/ParamsDict.py","file_name":"ParamsDict.py","file_ext":"py","file_size_in_byte":1083,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"165428162","text":"import argparse\nimport os\nimport shutil\nimport time\nimport random\n\nimport torch\nimport torch.nn as nn\nimport torch.nn.parallel\nimport torch.backends.cudnn as cudnn\nimport torch.optim\nimport torch.utils.data\nimport torchvision.transforms as transforms\nimport torchvision.datasets as datasets\nimport torchvision.models as models\nfrom MODELS.model_resnet import *\nfrom PIL import ImageFile\nimport datasets, logger\nimport pdb\nimport cv2\nimport numpy as np\n\n\nImageFile.LOAD_TRUNCATED_IMAGES = True\nmodel_names = sorted(name for name in models.__dict__\n if name.islower() and not name.startswith(\"__\")\n and callable(models.__dict__[name]))\n\nparser = argparse.ArgumentParser(description='PyTorch ImageNet Training')\nparser.add_argument('data', metavar='DIR',\n help='path to dataset')\nparser.add_argument('--arch', '-a', metavar='ARCH', default='resnet',\n help='model architecture: ' +\n ' | '.join(model_names) +\n ' (default: resnet18)')\nparser.add_argument('--depth', default=50, type=int, metavar='D',\n help='model depth')\nparser.add_argument('--ngpu', default=4, type=int, metavar='G',\n help='number of gpus to use')\nparser.add_argument('-j', '--workers', default=4, type=int, metavar='N',\n help='number of data loading workers (default: 4)')\nparser.add_argument('--epochs', default=90, type=int, metavar='N',\n help='number of total epochs to run')\nparser.add_argument('--start-epoch', default=0, type=int, metavar='N',\n help='manual epoch number (useful on restarts)')\nparser.add_argument('-b', '--batch-size', default=256, type=int,\n metavar='N', help='mini-batch size (default: 256)')\nparser.add_argument('--lr', '--learning-rate', default=0.1, type=float,\n metavar='LR', help='initial learning rate')\nparser.add_argument('--momentum', default=0.9, type=float, metavar='M',\n help='momentum')\nparser.add_argument('--weight-decay', '--wd', default=1e-4, type=float,\n metavar='W', help='weight decay (default: 1e-4)')\nparser.add_argument('--print-freq', '-p', default=10, type=int,\n metavar='N', help='print frequency (default: 10)')\nparser.add_argument('--resume', default='', type=str, metavar='PATH',\n help='path to latest checkpoint (default: none)')\nparser.add_argument(\"--seed\", type=int, default=1234, metavar='BS', help='input batch size for training (default: 64)')\nparser.add_argument(\"--prefix\", type=str, required=True, metavar='PFX', help='prefix for logging & checkpoint saving')\nparser.add_argument('--evaluate', dest='evaluate', action='store_true', help='evaluation only')\nparser.add_argument('--att-type', type=str, choices=['BAM', 'CBAM'], default=None)\nparser.add_argument('--out_dir', type=str, default='test/')\nbest_prec1 = 0\n\n\n\nCLASSES = ('aeroplane', 'bicycle', 'bird', 'boat',\n 'bottle', 'bus', 'car', 'cat', 'chair',\n 'cow', 'diningtable', 'dog', 'horse',\n 'motorbike', 'person', 'pottedplant',\n 'sheep', 'sofa', 'train', 'tvmonitor')\n\ndef main():\n global args, best_prec1\n global viz, train_lot, test_lot\n args = parser.parse_args()\n print (\"args\", args)\n\n saved_dir = os.path.join(args.out_dir, 'checkpoints')\n log_dir = os.path.join(args.out_dir, 'log')\n if not os.path.exists(args.out_dir):\n os.mkdir(args.out_dir)\n if not os.path.exists(saved_dir):\n os.mkdir(saved_dir)\n\n torch.manual_seed(args.seed)\n torch.cuda.manual_seed_all(args.seed)\n random.seed(args.seed)\n\n logger.configure(dir=log_dir)\n\n # Data loading code\n# traindir = os.path.join(args.data, 'train')\n# valdir = os.path.join(args.data, 'val')\n traindir = args.data\n valdir = args.data\n train_list = './VOCdevkit2007/VOC2007/ImageSets/Main/trainval.txt'\n val_list = './VOCdevkit2007/VOC2007/ImageSets/Main/test.txt'\n \n normalize = transforms.Normalize(mean=[0.485, 0.456, 0.406],\n std=[0.229, 0.224, 0.225])\n\n # import pdb\n # pdb.set_trace()\n val_loader = torch.utils.data.DataLoader(\n datasets.ImageFolder(valdir, val_list, transforms.Compose([\n # transforms.Scale(256),\n # transforms.CenterCrop(224),\n transforms.ToTensor(),\n normalize,\n ])),\n batch_size=args.batch_size, shuffle=False,\n num_workers=args.workers, pin_memory=True)\n if args.evaluate:\n validate(val_loader, model, criterion, 0)\n return\n\n train_dataset = datasets.ImageFolder(\n traindir, train_list,\n transforms.Compose([\n #transforms.RandomSizedCrop(size0),\n transforms.RandomHorizontalFlip(),\n transforms.ToTensor(),\n normalize,\n ]))\n\n train_sampler = None\n print(args.batch_size)\n train_loader = torch.utils.data.DataLoader(\n train_dataset, batch_size=args.batch_size, shuffle=(train_sampler is None),\n num_workers=args.workers, pin_memory=True, sampler=train_sampler)\n # create model\n if args.arch == \"resnet\":\n model = ResidualNet( 'ImageNet', args.depth, 20, args.att_type )\n\n # define loss function (criterion) and optimizer\n criterion = nn.CrossEntropyLoss().cuda()\n\n optimizer = torch.optim.SGD(model.parameters(), args.lr,\n momentum=args.momentum,\n weight_decay=args.weight_decay)\n model = torch.nn.DataParallel(model, device_ids=list(range(args.ngpu)))\n #model = torch.nn.DataParallel(model).cuda()\n model = model.cuda()\n print (\"model\")\n print (model)\n\n # get the number of model parameters\n print('Number of model parameters: {}'.format(\n sum([p.data.nelement() for p in model.parameters()])))\n\n\n\n\n # optionally resume from a checkpoint\n if args.resume:\n if os.path.isfile(args.resume):\n print(\"=> loading checkpoint '{}'\".format(args.resume))\n checkpoint = torch.load(args.resume)\n args.start_epoch = checkpoint['epoch']\n best_prec1 = checkpoint['best_prec1']\n model.load_state_dict(checkpoint['state_dict'])\n if 'optimizer' in checkpoint:\n optimizer.load_state_dict(checkpoint['optimizer'])\n print(\"=> loaded checkpoint '{}' (epoch {})\"\n .format(args.resume, checkpoint['epoch']))\n else:\n print(\"=> no checkpoint found at '{}'\".format(args.resume))\n\n\n cudnn.benchmark = True\n best_acc =0\n saved_value = (0,0,0,0,0,0, torch.cuda.FloatTensor(np.zeros(20)))\n for epoch in range(args.start_epoch, args.epochs):\n adjust_learning_rate(optimizer, epoch)\n \n # train for one epoch\n #train(train_loader, model, criterion, optimizer, epoch)\n acc, saved_value = train(train_loader, model, multi_class_cross_entropy_loss, optimizer, epoch, saved_value)\n \n # evaluate on validation set it does not needed\n #prec1 = validate(val_loader, model, criterion, epoch)\n #prec1 = validate(val_loader, model, multi_class_cross_entropy_loss, epoch)\n \n # remember best prec@1 and save checkpoint\n is_best = acc > best_acc\n best_acc = max(best_acc, acc)\n #best_prec1 = max(prec1, best_prec1)\n save_checkpoint(saved_dir, {\n 'epoch': epoch + 1,\n 'arch': args.arch,\n 'state_dict': model.state_dict(),\n 'acc':acc,\n 'optimizer' : optimizer.state_dict(),\n }, is_best, epoch+1)\n\ndef multi_class_cross_entropy_loss(preds, labels, eps=1e-6):\n cls_loss = labels * torch.log(preds +eps) + (1-labels) * torch.log(1-preds +eps)\n summed_cls_loss = torch.sum(cls_loss, dim=1)\n loss = -torch.mean(summed_cls_loss, dim=0)\n if torch.isnan(loss.sum()) :\n pdb.set_trace()\n return loss\n\n\ndef train(train_loader, model, criterion, optimizer, epoch, saved_value):\n# batch_time = 0#AverageMeter()\n# data_time = 0#AverageMeter()\n# losses = 0#AverageMeter()\n# all_accs = 0#AverageMeter()\n# cls_accs = 0#AverageMeter()\n# cnt = 0\n (batch_time, data_time, losses, all_accs, cls_accs, cnt,cls_cnt) = saved_value\n\n # switch to train mode\n model.train()\n\n end = time.time()\n for i, (input, target) in enumerate(train_loader):\n #pdb.set_trace()\n #img = input[0].cpu().numpy() + np.array([[[102.9801, 115.9465, 122.7717]]]).reshape(3,1,1)\n #img = np.ascontiguousarray(np.transpose(img,(1,2,0)))\n #cv2.imwrite('images.png',img)\n cnt += 1\n # measure data loading time\n data_time += (time.time() - end)\n \n target = target.cuda() #target.cuda(async=True)\n input_var = torch.autograd.Variable(input)\n target_var = torch.autograd.Variable(target)\n \n # compute output\n output = model(input_var)\n loss = criterion(output, target_var)\n \n # measure accuracy and record loss\n all_acc, cls_acc, cls_cnt = pascal_accuracy(output.data, target,cls_cnt)\n #prec1, prec5 = pascal_accuracy(output.data, target, topk=(1, 5))\n #pdb.set_trace()\n losses += loss\n all_accs += all_acc\n cls_accs += cls_acc\n \n # compute gradient and do SGD step\n optimizer.zero_grad()\n loss.backward()\n optimizer.step()\n \n # measure elapsed time\n batch_time += time.time() - end\n end = time.time()\n cnt \n if i % args.print_freq == 0:\n abs_batch_time = batch_time / cnt\n abs_data_time = data_time /cnt\n abs_losses = losses.item() / cnt\n abs_all_accs = all_accs/cnt\n abs_all_accs = abs_all_accs.item()\n abs_cls_accs = cls_accs / cls_cnt\n abs_cls_accs[abs_cls_accs != abs_cls_accs] = 0\n #abs_all_accs = all_accs.item() / cnt\n logger.log('Epoch: [{}][{}/{}]\\t Time {}\\t Data {}\\t Loss {}\\t All acs {} '.format(\n epoch, i, len(train_loader), abs_batch_time,\n abs_data_time, abs_losses, abs_all_accs))\n \n logger.log((cls_accs/(cnt)))\n \n logger.record_tabular('loss',loss.item())\n logger.record_tabular('loss_accum', abs_losses)\n logger.record_tabular('accum_all_acces', abs_all_accs)\n temp = output[0] >= 0.5\n print(\"PRED\",end=' ')\n for i in range(cls_acc.shape[0]):\n if temp[i].item() : \n print(CLASSES[i],end=' ')\n print(\"\\t\\t\\tGT\",end=' ')\n for i in range(cls_acc.shape[0]):\n if target[0,i] == 1: \n print(CLASSES[i],end=' ')\n print()\n\n for i in range(cls_accs.shape[0]):\n logger.record_tabular('accum_cls_accs_{:02d}'.format(i), abs_cls_accs[i].item()/(cnt))\n logger.record_tabular('cls_accs_{:02d}'.format(i), cls_acc[i].item())\n\n\n logger.dump_tabular()\n \n return all_accs.item()/cnt, (batch_time, data_time, losses, all_accs, cls_accs, cnt, cls_cnt)\n\n\ndef validate(val_loader, model, criterion, epoch):\n batch_time = 0#AverageMeter()\n data_time = 0#AverageMeter()\n losses = 0#AverageMeter()\n all_accs = 0#AverageMeter()\n cls_accs = 0#AverageMeter()\n\n # switch to evaluate mode\n model.eval()\n\n end = time.time()\n for i, (input, target) in enumerate(val_loader):\n target = target.cuda() #(async=True)\n #target = target.cuda(async=True)\n input_var = torch.autograd.Variable(input, volatile=True)\n target_var = torch.autograd.Variable(target, volatile=True)\n \n # compute output\n output = model(input_var)\n loss = criterion(output, target_var)\n \n # measure accuracy and record loss\n all_acc, cls_acc = pascal_accuracy(output.data, target)\n # prec1, prec5 = pascal_accuracy(output.data, target, topk=(1, 5))\n losses += loss\n all_accs += all_acc\n cls_accs += cls_acc\n \n # measure elapsed time\n batch_time.update(time.time() - end)\n end = time.time()\n if i % args.print_freq == 0:\n abs_batch_time = batch_time / (i+1)\n abs_data_time = data_time / (i+1)\n abs_losses = losses.item() / (i+1)\n abs_all_accs = all_accs.item() / (i+1)\n logger.log('Epoch: [{}][{}/{}]\\t Time {}\\t Data {}\\t Loss {}\\t All acs {} '.format(\n epoch, i, len(train_loader), abs_batch_time,\n abs_data_time, abs_losses, abs_all_accs))\n \n logger.log((cls_accs/(i+1)))\n \n logger.record_tabular('val/loss',loss.item())\n logger.record_tabular('val/accum_loss', abs_losses)\n logger.record_tabular('val/accum_all_acces', abs_all_accs)\n for i in range(cls_accs.shape[0]):\n logger.record_tabular('val/accum_cls_accs_{}'.format(i), cls_accs[i].item()/(i+1))\n logger.record_tabular('val/cls_accs_{}'.format(i), cls_acc[i].item())\n\n logger.dump_tabular()\n \n return all_accs.item()/(i+1)\n\n\ndef save_checkpoint(saved_dir,state, is_best, prefix):\n filename=os.path.join(saved_dir,'{:04d}.pth'.format(prefix))\n torch.save(state, filename)\n print(\"SAVE checkpoint {}\".format(filename))\n if is_best:\n print(\"BEST\")\n shutil.copyfile(filename, os.path.join(saved_dir, 'model_best_{:04d}.pth'.format(prefix)))\n\n\nclass AverageMeter(object):\n \"\"\"Computes and stores the average and current value\"\"\"\n def __init__(self):\n self.reset()\n\n def reset(self):\n self.val = 0\n self.avg = 0\n self.sum = 0\n self.count = 0\n\n def update(self, val, n=1):\n self.val = val\n self.sum += val * n\n self.count += n\n self.avg = self.sum / self.count\n\n\ndef adjust_learning_rate(optimizer, epoch):\n \"\"\"Sets the learning rate to the initial LR decayed by 10 every 30 epochs\"\"\"\n lr = args.lr * (0.1 ** (epoch // 30))\n for param_group in optimizer.param_groups:\n param_group['lr'] = lr\n\ndef pascal_accuracy(output, target, cls_cnt) :\n pred = output >= 0.5\n acc = pred.type(torch.cuda.FloatTensor) * target\n acc = acc.type(torch.cuda.FloatTensor)\n all_acc = acc.mean(dim=1)\n cls_acc = acc / target\n cls_acc[cls_acc != cls_acc] = 0 # NaN to 0\n\n cls_cnt += target.sum(dim=0)\n cls_acc = cls_acc.sum(dim=0)/ target.sum(dim=0)\n cls_acc[cls_acc != cls_acc] = 0 \n return all_acc.mean(dim=0), cls_acc, cls_cnt\n\ndef accuracy(output, target, topk=(1,)):\n \"\"\"Computes the precision@k for the specified values of k\"\"\"\n maxk = max(topk)\n batch_size = target.size(0)\n\n _, pred = output.topk(maxk, 1, True, True)\n pred = pred.t()\n pdb.set_trace()\n correct = pred.eq(target.view(1, -1).expand_as(pred))\n\n res = []\n for k in topk:\n correct_k = correct[:k].view(-1).float().sum(0, keepdim=True)\n res.append(correct_k.mul_(100.0 / batch_size))\n return res\n\n\nif __name__ == '__main__':\n main()\n","sub_path":"train_pascal.py","file_name":"train_pascal.py","file_ext":"py","file_size_in_byte":15368,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"590389343","text":"from second_level_model import config\nimport transformers\nimport torch \nimport pandas as pd\nfrom first_level_model import dataset, model as md, helper\nfrom tqdm import tqdm\nimport pickle\ndef run_inference(seed):\n df_test = pd.read_csv(config.TEST)\n df_test.loc[:, 'selected_text'] = df_test.text.values\n\n device = torch.device('cuda')\n model_config = transformers.RobertaConfig.from_pretrained(\n config.PRETRAINED_MODEL)\n model_config.output_hidden_states = True\n\n fold_models = []\n for i in range(config.N_FOLDS):\n model = md.TweetModel(conf=model_config)\n model.to(device)\n model.load_state_dict(torch.load(\n f'{config.LEVEL_ONE_MODEL_PATH}/model_{seed}{i}.bin'),\n strict=False)\n model.eval()\n fold_models.append(model)\n\n test_dataset = dataset.TweetDataset(\n tweets=df_test.text.values,\n sentiments=df_test.sentiment.values,\n selected_texts=df_test.selected_text.values)\n\n data_loader = torch.utils.data.DataLoader(\n test_dataset,\n shuffle=False,\n batch_size=config.VALID_BATCH_SIZE_ONE,\n num_workers=4)\n\n char_pred_test_start = []\n char_pred_test_end = []\n\n with torch.no_grad():\n tk0 = tqdm(data_loader, total=len(data_loader))\n for bi, d in enumerate(tk0):\n ids = d['ids']\n token_type_ids = d['token_type_ids']\n mask = d['mask']\n orig_tweet = d['orig_tweet']\n offsets = d['offsets']\n\n ids = ids.to(device, dtype=torch.long)\n token_type_ids = token_type_ids.to(device, dtype=torch.long)\n mask = mask.to(device, dtype=torch.long)\n\n outputs_start_folds = []\n outputs_end_folds = []\n for i in range(config.N_FOLDS):\n outputs_start, outputs_end = \\\n fold_models[i](ids=ids,\n mask=mask,\n token_type_ids=token_type_ids)\n outputs_start_folds.append(outputs_start)\n outputs_end_folds.append(outputs_end)\n\n outputs_start = sum(outputs_start_folds) / config.N_FOLDS\n outputs_end = sum(outputs_end_folds) / config.N_FOLDS\n\n outputs_start = torch.softmax(outputs_start, dim=-1).cpu().detach().numpy()\n outputs_end = torch.softmax(outputs_end, dim=-1).cpu().detach().numpy()\n\n for px, tweet in enumerate(orig_tweet):\n char_pred_test_start.append(\n helper.token_level_to_char_level(tweet, offsets[px], outputs_start[px]))\n char_pred_test_end.append(\n helper.token_level_to_char_level(tweet, offsets[px], outputs_end[px]))\n\n with open(f'./char_level/roberta{seed}-char_pred_test_start.pkl', 'wb') as handle:\n pickle.dump(char_pred_test_start, handle)\n with open(f'./char_level/roberta{seed}-char_pred_test_end.pkl', 'wb') as handle:\n pickle.dump(char_pred_test_end, handle)\n\nif __name__ == '__main__':\n for i in range(5):\n run_inference(i)","sub_path":"second_level_model/lo_inference.py","file_name":"lo_inference.py","file_ext":"py","file_size_in_byte":3098,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"140026068","text":"from collections import Counter\n# my_dict = {'T': 23, 'U': 22, 'T': 21,'O': 20, 'R': 32, 'S': 99}\nmy_dict = {\n 'a':50, \n 'b':58, \n 'c':56,\n 'd':40, \n 'e':100, \n 'f':20\n }\nk = Counter(my_dict)\n# 3 highest values\nhigh= k.most_common(4)\ns=[]\n#three hightest values\n# (\"Keys=0 : Values=1\")\nfor i in high:\n s.append(i[1])\n# print(i[0],\" : \",i[1],\" \")\nprint(i[1])\n# print(my_dict[i])\nprint(s) \n","sub_path":"DICTIONARY/dque13.py","file_name":"dque13.py","file_ext":"py","file_size_in_byte":418,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"608541164","text":"import os\nimport matplotlib.pyplot as plt\nimport itertools\nimport pickle\nimport imageio\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torch.optim as optim\nfrom torchvision import datasets, transforms\nfrom torch.autograd import Variable\nfrom Generator import generator\nfrom Discriminator import discriminator\nfrom Visualize import loss_plots\n\n# creating folders for results\nif not os.path.isdir('mnist_results'):\n os.mkdir('mnist_results')\nif not os.path.isdir('mnist_results/images'):\n os.mkdir('mnist_results/images')\n\n\ndef save_images(num_epoch, show = False, save = False, path = 'result.png'):\n z_ = torch.randn((4*4, 100))\n z_ = Variable(z_.cuda(), volatile=True)\n\n G.eval()\n test_images = G(z_)\n G.train()\n\n size_figure_grid = 4\n fig, ax = plt.subplots(size_figure_grid, size_figure_grid, figsize=(4, 4))\n for i, j in itertools.product(range(size_figure_grid), range(size_figure_grid)):\n ax[i, j].get_xaxis().set_visible(False)\n ax[i, j].get_yaxis().set_visible(False)\n for k in range(4*4):\n i = k // 4\n j = k % 4\n ax[i, j].cla()\n ax[i, j].imshow(test_images[k, :].cpu().data.view(28, 28).numpy(), cmap='Greys_r')\n\n label = 'Epoch {0}'.format(num_epoch)\n fig.text(0.5, 0.05, label, ha='center')\n plt.savefig(path)\n\n if show:\n plt.show()\n else:\n plt.close()\n\n################################### Main Code ######################################\nprint (\"training...\")\n\nlr = 0.0002\nepochs = 100\n\n# data_loader\n# transforms.ToTensor() = torch.FloatTensor of shape (C x H x W) in the range [0.0, 1.0].\n# Tensor image of size (C, H, W) to be normalized. i.e. input[channel] = (input[channel] - mean[channel]) / std[channel]\n\ntransform = transforms.Compose([\n transforms.ToTensor(),\n transforms.Normalize(mean=(0.5, 0.5, 0.5), std=(0.5, 0.5, 0.5))\n])\n# if data not present then it downloads, takes train part\ntrain_loader = torch.utils.data.DataLoader(\n datasets.MNIST('data', train=True, download=True, transform=transform),\n batch_size=64,shuffle=True)\n\n\n# networks\nG = generator(input_size=100, n_class=28*28)\nD = discriminator(input_size=28*28, n_class=1)\nG.cuda()\nD.cuda()\n\n# Adam optimizer\nG_optimizer = optim.Adam(G.parameters(), lr=lr)\nD_optimizer = optim.Adam(D.parameters(), lr=lr)\n\ntrain_hist = {}\ntrain_hist['D_losses'] = []\ntrain_hist['G_losses'] = []\nfor epoch in range(epochs):\n D_losses = []\n G_losses = []\n for load_data, _ in train_loader:\n\n # training discriminator ############\n # manually setting gradients to zero before mini batches \n D.zero_grad()\n\n # format\n load_data = load_data.view(-1, 28 * 28)\n # print load_data.size()[0]\n mini_batch = load_data.size()[0]\n\n D_real = torch.ones(mini_batch)\n D_fake = torch.zeros(mini_batch)\n\n # variables in pytorch can directly be accessed\n load_data = Variable(load_data.cuda())\n D_real = Variable(D_real.cuda())\n D_fake = Variable(D_fake.cuda())\n\n # first it takes real data \n D_result = D(load_data)\n # loss calculations due to real data : first term in eqn\n # comparing with ones labels\n D_real_loss = F.binary_cross_entropy(D_result, D_real)\n # D_real_scores = D_result\n\n ## for loss due to generated samples\n noise = torch.randn((mini_batch, 100))\n noise = Variable(noise.cuda())\n\n G_sample = G(noise)\n D_result = D(G_sample)\n # loss calculations due to generated data : second term in eqn\n # comparing with zero labels\n D_fake_loss = F.binary_cross_entropy(D_result, D_fake)\n # D_fake_scores = D_result\n # total D_loss\n D_train_loss = D_real_loss + D_fake_loss\n\n # training of network\n D_train_loss.backward()\n D_optimizer.step()\n\n D_losses.append(D_train_loss.data[0])\n\n # training generator ##############\n\n # manually setting gradients to zero before mini batches \n G.zero_grad()\n\n noise = torch.randn((mini_batch, 100))\n out = torch.ones(mini_batch)\n\n # variables in pytorch can directly be accessed\n noise = Variable(noise.cuda())\n out = Variable(out.cuda())\n # noise input to generator \n G_result = G(noise)\n D_result = D(G_result)\n # comparing with ones labels\n # loss calculations due to generated data : generator's loss\n G_train_loss = F.binary_cross_entropy(D_result, out)\n # training of network\n G_train_loss.backward()\n G_optimizer.step()\n\n G_losses.append(G_train_loss.data[0])\n\n print('[%d/%d]: loss_d: %.3f, loss_g: %.3f' % (\n (epoch + 1), epochs, torch.mean(torch.FloatTensor(D_losses)), torch.mean(torch.FloatTensor(G_losses))))\n\n p = 'mnist_results/images/' + str(epoch + 1)+ '.png'\n save_images((epoch+1), save=True, path=p)\n train_hist['D_losses'].append(torch.mean(torch.FloatTensor(D_losses)))\n train_hist['G_losses'].append(torch.mean(torch.FloatTensor(G_losses)))\n\n\nprint(\"Finished training!\")\n\n### showing and saving the results ###############\nloss_plots(train_hist, save=False, path='mnist_results/MNIST_GAN_train_hist.png')\ntorch.save(G.state_dict(), \"mnist_results/generator_param.pkl\")\ntorch.save(D.state_dict(), \"mnist_results/discriminator_param.pkl\")\nwith open('mnist_results/train_hist.pkl', 'wb') as f:\n pickle.dump(train_hist, f)\n\n# creating gif file \nimages = []\nfor i in range(epochs):\n img_name = 'mnist_results/images/' + str(i + 1) + '.png'\n images.append(imageio.imread(img_name))\nimageio.mimsave('mnist_results/gif_file.gif', images, fps=5)\n\n\n\n","sub_path":"mnist_gan.py","file_name":"mnist_gan.py","file_ext":"py","file_size_in_byte":5720,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"170535365","text":"from __future__ import print_function\nfrom datetime import datetime, timedelta\nfrom settings import gen_url, date_from, date_to\nfrom async_processors import AsyncProcessors\nfrom random import randint\nimport requests, json, re, time, asyncio\nimport sys, traceback, os, re, aiohttp, socket\n\nclass GoogleTrendsUpdate(AsyncProcessors):\n def __init__(self, _from, _to):\n self.processed_data = 0\n self.error_count = 0\n self.date_from = _from #date_from\n self.date_to = _to #date_to\n self.futures = []\n self.count = 0\n self.geo = ''\n self.locale = 'ru'\n self.hl = 'en-US'\n self.tz = '360'\n self.cat = 0\n self.geo=''\n self.gprop=''\n AsyncProcessors.__init__(self)\n\n def main(self):\n self.conn, self.cur = self.mysql_connect()\n self.get_proxies()\n self.get_all_dates()\n self.process_tickers()\n\n self.loop = asyncio.get_event_loop()\n self.loop.run_until_complete(self.asynchronous())\n self.loop.close()\n\n self.mysql_close(self.conn, self.cur)\n\n async def asynchronous(self):\n print('...running asynchronous')\n\n async with aiohttp.ClientSession(cookie_jar=aiohttp.DummyCookieJar()) as self.session:\n self.futures = [self.get_async(data) for data in self.futures]\n\n for future in asyncio.as_completed(self.futures):\n data, name, ticker, _from, _to = await future\n\n if data != None:\n self.processed_data += 1\n self._process_data(data, name, ticker, _from, _to)\n else:\n self.error_count += 1\n\n async def get_async(self, data):\n ticker = data[0]\n name = data[1]\n _from = data[2]\n _to = data[3]\n\n cookies = await self.get_cookies()\n\n if cookies != None:\n payload = self.get_payload(name, _from, _to)\n headers = {'Cookie': cookies}\n\n url = gen_url + 'explore'\n resp = await self.send_async_request(url, payload, headers)\n\n if resp != None:\n resp = re.findall(r'{.*}', resp)[0]\n resp = json.loads(resp)\n resp = resp['widgets'][0]\n token = resp['token']\n req_body = json.dumps(resp['request'])\n\n payload = {\n 'req': req_body,\n 'token': token,\n 'tz': self.tz\n }\n\n url = gen_url + 'widgetdata/multiline'\n data = await self.send_async_request(url, payload, headers)\n else:\n data = None\n else:\n data = None\n\n return data, name, ticker, _from, _to\n\n async def get_cookies(self):\n proxy = self.proxies[randint(0, len(self.proxies)-1)]\n\n try:\n async with self.session.request('GET', self.cookie_url, proxy=proxy) as resp:\n\n if resp.status == 200:\n return re.findall(r'Set-Cookie: (.*)', str(resp.cookies))[0]\n else:\n print('cookie status error: {}'.format(resp.status))\n return None\n except Exception as e:\n print('cookie error: {}'.format(e))\n return None\n\n async def send_async_request(self, url, payload, headers):\n proxy = self.proxies[randint(0, len(self.proxies)-1)]\n\n try:\n async with self.session.request('GET', url=url, params=payload, proxy=proxy, headers=headers) as resp: \n data, status = await resp.text(), resp.status\n\n if status == 200:\n return data\n else:\n print('{} {} error status: {}'.format(len(self.futures), self.error_count, status))\n\n# if self.error_count > 300:\n# os._exit(1)\n\n return None\n except Exception as e:\n print(e)\n\n def process_tickers(self):\n print('...processing tickers')\n\n query = \"SELECT ticker, company_name FROM stocks_industry WHERE is_active = 1 and status like 'dilutedeps: 0, debttoequity: 0, pricetoearningsgrowth: 0, cashpersharepercent: 0%'\"\n #query = \"SELECT ticker, company_name FROM stocks_industry WHERE is_active = 1\"\n\n self.cur.execute(query)\n data = self.cur.fetchall()\n self.total = len(data)\n print('...retrieved {} tickers'.format(self.total))\n\n\n for d in data[:]: #####################################\n self.process_ticker(d)\n\n def process_ticker(self, x):\n self.count += 1\n ticker = x[0]\n name = self.clean_words(x[1])\n\n for dr in self.get_missing_dates(ticker):\n self.get_dates(ticker, name, dr[0], dr[1])\n\n def _process_data(self, resp, key_word, ticker, _from, _to):\n _resp = re.findall(r'{.*}', resp)[0]\n data = json.loads(_resp)\n data = data['default']['timelineData']\n\n if len(data) == 0:\n missing_data = self.fillin_empty(_from, _to)\n \n for md in missing_data:\n self.ticker_sql(md, 0.0, ticker, key_word)\n print(len(self.futures), self.processed_data, key_word, ticker, md, 0)\n else:\n for line in data:\n time = datetime.fromtimestamp(int(line['time']))\n value = line['value'][0]\n self.ticker_sql(time, value, ticker, key_word)\n print(len(self.futures), self.processed_data, key_word, ticker, time.date(), value)\n\nif __name__ == \"__main__\":\n _from = sys.argv[1]\n _to = sys.argv[2]\n\n GoogleTrendsUpdate(_from, _to)\n\n","sub_path":"src/python/google_trends_update_async.py","file_name":"google_trends_update_async.py","file_ext":"py","file_size_in_byte":5728,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"276529265","text":"# ===============================================================================\n# Copyright 2012 Jake Ross\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ===============================================================================\n\n# ============= enthought library imports =======================\nfrom __future__ import absolute_import\n\nfrom apptools.preferences.preference_binding import bind_preference\nfrom traits.api import Float, Button, Bool, Any, Instance, Event, Int\nfrom traitsui.api import View, Item, HGroup, RangeEditor\nfrom math import ceil\nfrom pychron.image.standalone_image import FrameImage\nfrom pychron.mv.machine_vision_manager import MachineVisionManager, view_image\n\n\nclass AutoCenterManager(MachineVisionManager):\n canvas = Any\n\n # use_crop_size = Bool(False)\n # use_target_radius = Bool(False)\n\n # crop_size = Float(4)\n # target_radius = Float(1.0)\n\n configure_button = Button('configure')\n use_autocenter = Bool\n # use_hough_circle = Bool(False)\n\n use_adaptive_threshold = Bool(False)\n blur = Int\n stretch_intensity = Bool(False)\n search_step = Int\n search_n = Int\n search_width = Int\n blocksize = Int\n blocksize_step = Int\n\n display_image = Instance(FrameImage, ())\n\n def bind_preferences(self, pref_id):\n bind_preference(self, 'use_autocenter', '{}.use_autocenter'.format(pref_id))\n bind_preference(self, 'blur', '{}.autocenter_blur'.format(pref_id))\n bind_preference(self, 'stretch_intensity', '{}.autocenter_stretch_intensity'.format(pref_id))\n bind_preference(self, 'use_adaptive_threshold', '{}.autocenter_use_adaptive_threshold'.format(pref_id))\n bind_preference(self, 'search_step', '{}.autocenter_search_step'.format(pref_id))\n bind_preference(self, 'search_n', '{}.autocenter_search_n'.format(pref_id))\n bind_preference(self, 'search_width', '{}.autocenter_search_width'.format(pref_id))\n bind_preference(self, 'blocksize', '{}.autocenter_blocksize'.format(pref_id))\n bind_preference(self, 'blocksize_step', '{}.autocenter_blocksize_step'.format(pref_id))\n\n def calculate_new_center(self, cx, cy, offx, offy, dim=1.0, shape='circle'):\n frame = self.new_image_frame()\n loc = self._get_locator(shape=shape)\n\n cropdim = ceil(dim * 2.55)\n\n frame = loc.crop(frame, cropdim, cropdim, offx, offy)\n\n im = self.display_image\n im.source_frame = frame\n dim = self.pxpermm * dim\n\n preprop = {'stretch_intensity': self.stretch_intensity,\n 'blur': self.blur}\n search = dict(n=self.search_n,\n step=self.search_step,\n width=self.search_width,\n blocksize=self.blocksize,\n blocksize_step=self.blocksize_step,\n use_adaptive_threshold=self.use_adaptive_threshold)\n dx, dy = loc.find(im, frame, dim=dim, preprocess=preprop, search=search)\n\n if dx is None and dy is None:\n return\n else:\n # pdx, pdy = round(dx), round(dy)\n mdx = dx / self.pxpermm\n mdy = dy / self.pxpermm\n self.info('calculated deviation px={:n},{:n}, '\n 'mm={:0.3f},{:0.3f} ({})'.format(dx, dy, mdx, mdy, self.pxpermm))\n return cx + mdx, cy + mdy\n\n # private\n def _get_locator(self, *args, **kw):\n raise NotImplementedError\n\n # handlers\n def _configure_button_fired(self):\n w = h = self.crop_size * self.pxpermm\n canvas = self.canvas\n if canvas:\n cx, cy = canvas.get_center_rect_position(w, h)\n\n canvas.add_markup_rect(cx, cy, w, h, identifier='croprect')\n\n cx, cy = canvas.get_screen_center()\n r = self.target_radius * self.pxpermm\n canvas.add_markup_circle(cx, cy, r, identifier='target')\n\n self.edit_traits(view='configure_view', kind='livemodal')\n if canvas:\n canvas.remove_item('croprect')\n canvas.remove_item('target')\n\n def _crop_size_changed(self):\n canvas = self.canvas\n if canvas:\n canvas.remove_item('croprect')\n\n w = h = self.crop_size * self.pxpermm\n cx, cy = canvas.get_center_rect_position(w, h)\n\n canvas.add_markup_rect(cx, cy, w, h, identifier='croprect')\n\n def _target_radius_changed(self):\n canvas = self.canvas\n if canvas:\n canvas.remove_item('target')\n r = self.target_radius * self.pxpermm\n cx, cy = canvas.get_screen_center()\n canvas.add_markup_circle(cx, cy, r, identifier='target')\n\n # views\n # def configure_view(self):\n # v = View(Item('crop_size'),\n # Item('target_radius', editor=RangeEditor(low=0., high=5.)),\n # buttons=['OK', 'Cancel'])\n # return v\n #\n # def traits_view(self):\n # v = View(HGroup(Item('use_autocenter', label='Enabled'),\n # # Item('configure_button', show_label=False),\n # show_border=True,\n # label='Autocenter'))\n # return v\n\n\nclass CO2AutocenterManager(AutoCenterManager):\n # private\n def _get_locator(self, *args, **kw):\n from pychron.mv.co2_locator import CO2Locator\n return CO2Locator(pxpermm=self.pxpermm, pixel_depth=self.video.pixel_depth)\n\n\nclass DiodeAutocenterManager(AutoCenterManager):\n # private\n def _get_locator(self, *args, **kw):\n from pychron.mv.diode_locator import DiodeLocator\n return DiodeLocator(pxpermm=self.pxpermm, pixel_depth=self.video.pixel_depth)\n\n# ============= EOF =============================================\n","sub_path":"pychron/mv/autocenter_manager.py","file_name":"autocenter_manager.py","file_ext":"py","file_size_in_byte":6332,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"22315506","text":"from typing import Type, Optional, Dict\n\nfrom tatsu_parser.spec import Semantics\n\n\ndef parse(text: str, rule_key) -> Optional[Semantics]:\n from tatsu_parser.field_selector import FieldSelectorSemantics\n from tatsu_parser.logical_operator import LogicalOperatorSemantics\n\n semantics_map: Dict[str, Type[Semantics]] = {\n \"field_selector\": FieldSelectorSemantics,\n \"logical_operator\": LogicalOperatorSemantics,\n }\n\n semantics_cls = semantics_map.get(rule_key)\n if not semantics_cls:\n return None\n\n parser = semantics_cls.parser_cls()\n return parser.parse(text, rule_name=semantics_cls.rule_key, semantics=semantics_cls())\n","sub_path":"tatsu_parser/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":664,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"365370838","text":"\n# Machine Learning Imports\nimport pandas as pd\nimport sklearn as sk\nfrom sklearn import svm\n\n# Standard Imports\nfrom random import shuffle\n\ntestDataLen = 0 # Assigned a value in main() to specify how much data to learn from\n\n'''\n hill-valley.csv\n Instances: 1212\n Highest Community accuracy: ~77%\n Features: 101\n 100 floats of elevation-like values\n 1 value of 0 or 1 where 0=valley and 1=hill\n'''\n\ndef main():\n dataFrame = pd.read_csv('hill-valley.csv')\n data = dataFrame.values\n shuffle(data) # In case data is organized in some order, shuffle it, so unseen types of data occur less frequently\n global testDataLen # Allows assignment to global value\n testDataLen = int(len(data)*0.75) # Change size of how much data is tested here\n\n print('Amount of data to learn from is %d out of %d - (%d%s)' %(testDataLen, len(data), int(testDataLen/len(data) * 100), '%'))\n\n clf = svm.SVC(gamma=0.001, C=57)\n\n fitData = getLearnData(data)\n targetData = getTargetData(data)\n\n clf.fit(fitData, targetData)\n\n accuracy = testAcc(clf, data[testDataLen:])\n\n print(accuracy)\n\ndef getLearnData(data):\n fitData = []\n\n for r in data[:testDataLen]:\n row = []\n for i in r[:len(r)-1]:\n row.append(i)\n fitData.append(row)\n\n return fitData\n\ndef getTargetData(data):\n targetData = []\n\n for r in data[:testDataLen]:\n targetData.append(int(r[len(r)-1]))\n\n return targetData\n\ndef testAcc(clf, data):\n total = 0\n correct = 0\n for r in data:\n total += 1\n landLen = len(r)-1 # -1 to exclude target data pointvin index range below\n # predict() returns array so get first index\n if clf.predict([r[:landLen]])[0] == r[landLen]:\n correct += 1\n\n return correct / total\n\nif __name__ == '__main__':\n main()","sub_path":"learn_land.py","file_name":"learn_land.py","file_ext":"py","file_size_in_byte":1861,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"427549223","text":"import sys\nN = int(sys.stdin.readline())\nspace = []\nfor i in range(N):\n space.append(list(map(int,sys.stdin.readline().split())))\nanswer = 0\n\ndef dfs(y,x,shape):\n global answer\n if y == N-1 and x == N-1:\n answer += 1\n \n if shape == 1:\n ny2 = y\n nx2 = x + 1\n if 0 <= ny2 < N and 0 <= nx2 < N and space[ny2][nx2] == 0 :\n dfs(ny2,nx2,1)\n ny4 = y + 1\n nx4 = x + 1\n if 0 <= ny4 < N and 0 <= nx4 < N and space[ny4][nx4] == 0 and space[ny4][nx4-1] == 0 and space[ny4-1][nx4] == 0 :\n dfs(ny4,nx4,2)\n\n elif shape == 2:\n ny2 = y\n nx2 = x + 1\n if 0 <= ny2 < N and 0 <= nx2 < N and space[ny2][nx2] == 0 :\n dfs(ny2,nx2,1)\n ny4 = y + 1\n nx4 = x\n if 0 <= ny4 < N and 0 <= nx4 < N and space[ny4][nx4] == 0 :\n dfs(ny4,nx4,3)\n ny6 = y + 1\n nx6 = x + 1\n if 0 <= ny6 < N and 0 <= nx6 < N and space[ny6][nx6] == 0 and space[ny6][nx6-1] == 0 and space[ny6-1][nx6] == 0:\n dfs(ny6,nx6,2)\n\n elif shape == 3:\n ny2 = y + 1\n nx2 = x\n if 0 <= ny2 < N and 0 <= nx2 < N and space[ny2][nx2] == 0 :\n dfs(ny2,nx2,3)\n ny4 = y + 1\n nx4 = x + 1\n if 0 <= ny4 < N and 0 <= nx4 < N and space[ny4][nx4] == 0 and space[ny4][nx4-1] == 0 and space[ny4-1][nx4] == 0 :\n dfs(ny4,nx4,2)\n\nif space[-1][-1] == 1:\n print(0)\nelse:\n dfs(0,1,1)\n print(answer)","sub_path":"BoJ/BoJ.17070.py","file_name":"BoJ.17070.py","file_ext":"py","file_size_in_byte":1466,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"345717892","text":"#!/usr/bin/env python3\n\nimport os\nimport json\n\nlist = [\n # Default\n { 'n': 7, # Display days\n 'color_text': (0, 0, 0, 1), #RGBa # color text\n 'color_text_week': (0.5, 0, 0, 1), # color weekend\n 'color_shadow': (1, 1, 1, 0.7), # color shadow\n 'draw_shadow': True, # draw shadow\n 'show_block_wind_direct': True, # block wind direct\n 'block_wind_direct_left': -170, # position\n 'wind_direct_small': False, # small block wind direct\n 'show_block_add_info': True, # block with additional information\n 'block_add_info_left': 70, # position\n 'show_block_tomorrow': True, # block with the weather for tomorrow\n 'block_tomorrow_left': 180, # position\n 'show_block_today': True, # block with the weather for today\n 'block_today_left': -310, # position\n 'bg_custom': 'Light50', # this picture\n 'margin': 20, # inside padding\n 'block_now_left': 0,\n # customizable options\n 'preset_number':0,\n 'bg_left': 0,\n 'bg_top': 0,\n 'bg_width': -1,\n 'bg_height': -1,\n 'icon_now_top': 0,\n 'icon_now_left': 0,\n 'icon_now_size': 0,\n 'block_icons_left': 0,\n 'block_icons_top': 0,\n 'city_name_left': 0,\n 'city_name_top': 0,\n 'day_left': 0,\n 'day_top': 0,\n 't_now_left': 0,\n 't_now_top': 0,\n 't_now_size': 0,\n 't_now_alignment': 'right',\n 'text_now_left': 0,\n 'text_now_top': 0,\n 'height_fix': 0,\n 'splash_icon_top': 0,\n 'splash_version_top': 0,\n 'block_wind_direct_small_left': 0,\n 'block_today_top': 0,\n 'block_tomorrow_top': 0,\n 'block_wind_direct_small_top': 0,\n 'splash_block_top': 0\n },\n\n # Small\n { 'bg_left': 0,\n 'bg_top': 80,#38,\n 'bg_width': -1,\n 'bg_height': 185,\n 'block_now_left': 0,\n 'icon_now_top': -70,\n 'icon_now_left': 1120,\n 'icon_now_size': 80,\n 'block_icons_left': 199,\n 'block_icons_top': -1,\n 'city_name_left': 200,\n 'city_name_top': 27,\n 'day_left': 0,\n 'day_top': -75,\n 't_now_left': 1125,\n 't_now_top': 40,\n 't_now_size': 6,\n 't_now_alignment': 'left',\n 'text_now_left': 1161,\n 'text_now_top': 9,\n 'height_fix': -95,\n 'n': 3,\n 'show_block_wind_direct': False,\n 'show_block_add_info': False,\n 'show_block_tomorrow': False,\n 'show_block_today': False,\n 'splash_icon_top': 25,\n 'splash_version_top': 20,\n 'splash_block_top': 25,\n 'margin': 20\n },\n\n # Wood\n { 'bg_left': 0,\n 'bg_top': 0,\n 'bg_width': -1,\n 'bg_height': -1,\n 'icon_now_top': 120,\n 'icon_now_left': 0,\n 'block_icons_left': 0,\n 'block_icons_top': 0,\n 'city_name_left': 0,\n 'city_name_top':126,\n 'day_left': 0,\n 'day_top': 126,\n 'icon_now_size': 0,\n 't_now_left': 0,\n 't_now_top': 120,\n 't_now_size': 0,\n 't_now_alignment': 'right',\n 'text_now_left': 0,\n 'text_now_top': 120,\n 'height_fix': 120,\n 'n': 5,\n 'show_block_wind_direct': True,\n 'block_wind_direct_left': -170,\n 'wind_direct_small': True,\n 'show_block_add_info': False,\n 'block_add_info_left': 70,\n 'show_block_tomorrow': True,\n 'block_tomorrow_left': 90,\n 'show_block_today': True,\n 'block_today_left': -220,\n 'splash_icon_top': 0,\n 'splash_version_top': 0,\n 'bg_custom': 'Wood',\n 'margin': 15,\n 'block_wind_direct_small_left': 0,\n 'block_today_top': 120,\n 'block_tomorrow_top': 120,\n 'block_wind_direct_small_top': 120,\n 'splash_block_top': 70,\n 'color_text': (0.18, 0.18, 0.18, 1),\n 'draw_shadow': False,\n 'icons_name': 'Sketchy',\n 'show_bg_png': True\n },\n # NotePaper\n { 'bg_left': 0,\n 'bg_top': 0,\n 'bg_width': -1,\n 'bg_height': -1,\n 'block_now_left': 20,\n 'icon_now_top': 0,\n 'icon_now_left': 0,\n 'icon_now_size': 0,\n 'block_icons_left': 50,\n 'block_icons_top': 0,\n 'city_name_left': 20,\n 'city_name_top': 0,\n 'day_left': 20,\n 'day_top': 0,\n 't_now_left': 0,\n 't_now_top': 0,\n 't_now_size': 0,\n 't_now_alignment': 'right',\n 'text_now_left': 0,\n 'text_now_top': 0,\n 'height_fix': 0,\n 'n': 4,\n 'show_block_wind_direct': True,\n 'show_block_add_info': True,\n 'show_block_tomorrow': False,\n 'show_block_today': False,\n 'splash_block_top': 0,\n 'margin': 20,\n 'block_wind_direct_left': -150,\n 'block_add_info_left': 90,\n 'bg_custom': 'NotePaper',\n 'wind_direct_small': False,\n 'show_bg_png': True\n },\n # Default\n { 'n': 7, # Display days\n 'color_text': (0, 0, 0, 1), #RGBa # color text\n 'color_text_week': (0.5, 0, 0, 1), # color weekend\n 'color_shadow': (1, 1, 1, 0.7), # color shadow\n 'draw_shadow': True, # draw shadow\n 'show_block_wind_direct': True, # block wind direct\n 'block_wind_direct_left': -170, # position\n 'wind_direct_small': False, # small block wind direct\n 'show_block_add_info': True, # block with additional information\n 'block_add_info_left': 70, # position\n 'show_block_tomorrow': True, # block with the weather for tomorrow\n 'block_tomorrow_left': 180, # position\n 'show_block_today': True, # block with the weather for today\n 'block_today_left': -310, # position\n 'bg_custom': 'Winter', # this picture\n 'margin': 50, # inside padding\n 'block_now_left': 0,\n # customizable options\n 'preset_number':0,\n 'bg_left': 0,\n 'bg_top': 0,\n 'bg_width': -1,\n 'bg_height': -1,\n 'icon_now_top': 0,\n 'icon_now_left': 0,\n 'icon_now_size': 0,\n 'block_icons_left': 0,\n 'block_icons_top': 0,\n 'city_name_left': 0,\n 'city_name_top': 0,\n 'day_left': 0,\n 'day_top': 0,\n 't_now_left': 0,\n 't_now_top': 0,\n 't_now_size': 0,\n 't_now_alignment': 'right',\n 'text_now_left': 0,\n 'text_now_top': 0,\n 'height_fix': 0,\n 'splash_icon_top': 0,\n 'splash_version_top': 0,\n 'block_wind_direct_small_left': 0,\n 'block_today_top': 0,\n 'block_tomorrow_top': 0,\n 'block_wind_direct_small_top': 0,\n 'splash_block_top': 0\n }\n ]\n\nnames = {\n 0: 'Default',\n 1: 'Small',\n 2: 'Wood',\n 3: 'NotePaper',\n 4: 'Winter'\n}\n\ndef save_to_file(CONFIG_PATH):\n for i in range(len(list)):\n #if not os.path.exists(os.path.join(CONFIG_PATH, 'presets', 'preset_%s.json' %i)): FIXME after testing uncomment this\n json.dump(list[i], open(os.path.join(CONFIG_PATH, 'presets', 'preset_%s.json' %i), \"w\"), sort_keys=True, indent=4, separators=(', ', ': '))","sub_path":"utils/presets.py","file_name":"presets.py","file_ext":"py","file_size_in_byte":7447,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"437649633","text":"\"\"\"GridLAB-D Geodata Weather Package\n\nThe collects weather data from a region to allow object to refer to localized weather.\n\nINPUT:\n\n latitude the latitude of the location\n \n longitude the longitude of the location\n\nOUTPUT:\n\n name the geohash code name of the location\n \n filename the weather filename of the location\n\n\nOPTIONS:\n\n geohash_resolution the size of the geohash code name (default 6)\n \n key_index the output record name (default \"name\")\n \n starttime the default start time (Jan 1 of last year) \n \n stoptime the default stop time (Dec 31 of last year)\n\nCONFIGURATION:\n\n cachedir the path to the cache for data files (default \n \"$GLD_ETC/gridlabd/weather/nsrdb\")\n\nENVIRONMENT:\n\n GLD_ETC the path to the shared files (default \"/usr/local/opt/gridlabd//share/gridlabd\")\n\nCAVEATS:\n\n This package can require a lot of time when accessing several years over a wide area.\n\nSEE ALSO:\n\n * `gridlabd nsrbd_weather help` for details on NSRDB data source used by this package.\n\"\"\"\n\nversion = 1 # specify API version\n\nimport sys\nimport os\nimport json\nimport datetime\nimport math, numpy\nimport pandas\nimport haversine\n\nGLD_ETC = os.getenv(\"GLD_ETC\")\nif not GLD_ETC:\n GLD_ETC = \"/usr/local/share/gridlabd\"\nif GLD_ETC not in sys.path:\n sys.path.append(GLD_ETC)\nimport nsrdb_weather\n\n#\n# Defaults\n#\ndefault_options = dict(\n geohash_resolution = 6,\n key_index = \"name\",\n starttime = datetime.datetime(datetime.date.today().year-1,1,1,0,0,0).strftime(\"%Y\"),\n stoptime = datetime.datetime(datetime.date.today().year-1,12,31,23,0,0).strftime(\"%Y\"),\n )\n\ndefault_config = dict(\n cachedir = f\"{GLD_ETC}/weather/nsrdb\"\n )\n\n#\n# Implementation of weather package\n#\ndef apply(data, options=default_options, config=default_config, warning=print):\n \"\"\"Gather weather data for various locations\n\n ARGUMENTS:\n\n data (pandas.DataFrame)\n\n The data frame must contain `latitude` and `longitude` fields between which\n distances will be computed.\n\n options (dict)\n\n There are no options\n\n config (dict)\n\n There are no configuration options\n\n RETURNS:\n\n pandas.DataFrame\n\n The specified weather value for the geocodes provided.\n\n \"\"\"\n nsrdb_weather.geocode_precision = options[\"geohash_resolution\"]\n startyear = int(options[\"starttime\"])\n stopyear = int(options[\"stoptime\"])\n if startyear == stopyear:\n years = f\"{startyear}\"\n else:\n years = f\"{startyear}-{stopyear}\"\n location = list(map(lambda row:nsrdb_weather.geohash(float(row['latitude']),float(row['longitude']),nsrdb_weather.geocode_precision),data.to_dict('records')))\n data[options[\"key_index\"]] = location\n data[\"filename\"] = list(map(lambda code:f\"nsrdb_{code}_{years}.csv\",location))\n for code,file in zip(data[options[\"key_index\"]],data[\"filename\"]):\n if not os.path.exists(file):\n lat,lon = nsrdb_weather.geocode(code)\n years = list(range(startyear,stopyear+1))\n weather = nsrdb_weather.getyears(years,lat,lon)\n weather['DataFrame'].to_csv(file)\n return data\n\n#\n# Perform validation tests\n#\nif __name__ == '__main__':\n\n import unittest\n\n class TestWeather(unittest.TestCase):\n\n def test_weather(self):\n test = pandas.DataFrame({\n \"latitude\" : [37.4205,37.5205],\n \"longitude\" : [-122.2046,-122.3046],\n })\n starttime = \"2020\"\n stoptime = \"2020\"\n result = apply(test,options=dict(geohash_resolution=6,key_index=\"name\",starttime=starttime,stoptime=stoptime))\n pandas.set_option(\"display.max_rows\",None)\n pandas.set_option(\"display.max_columns\",None)\n pandas.set_option(\"display.max_colwidth\",None)\n print(result)\n # self.assertEqual(result[\"wind\"][1],12.0)\n\n if os.path.exists(f\"{os.getenv('HOME')}/.nsrdb/credentials.json\"):\n unittest.main()\n","sub_path":"geodata/geodata_weather.py","file_name":"geodata_weather.py","file_ext":"py","file_size_in_byte":4091,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"175626016","text":"import numpy as np\nimport os\nfrom PIL import Image\n\nfrom ..utils.misc_utils import index_last_non_zero\nfrom ..utils.slide_utils import get_level\n\ntry:\n import matlab\n from matlab import engine\nexcept ImportError:\n raise ImportError('No MATLAB engine found.')\n\n\n###\n\nclass OpenJP2(object):\n\n def __init__(self, wsi_file, engine):\n \"\"\"\n TODO: What is this?\n\n :param wsi_file: path to a WSI file.\n :param engine:\n \"\"\"\n self.wsi_file = wsi_file\n\n # Engine stuff\n self.engine = engine\n call_path = os.path.dirname(os.path.realpath(__file__))\n self.engine.addpath(r'{}'.format(call_path), nargout=0)\n\n # Just to flag as JP2\n self.jp2 = True\n\n ### Get slide info\n level_dim, level_downsamples, level_count = self.engine.get_jp2_info(self.wsi_file, nargout=3)\n # Make sure we have the right formats\n level_dim, level_downsamples, level_count = np.array(level_dim), np.array(level_downsamples), int(level_count)\n\n self.level_downsamples = [float(downsample[0]) for downsample in level_downsamples]\n self.level_dimensions = [(level_dim[level, 1], level_dim[level, 0]) for level in range(level_count)]\n\n def read_region(self, location, level, size):\n \"\"\"\n Read a region of the WSI using the MATLAB function `read_jp2_region`.\n\n :param location:\n :param level:\n :param size:\n :return:\n \"\"\"\n y1 = int(location[0] / pow(2, level)) + 1\n x1 = int(location[1] / pow(2, level)) + 1\n y2 = int(y1 + size[0] - 1)\n x2 = int(x1 + size[1] - 1)\n patch = self.engine.read_jp2_region(self.wsi_file, level, matlab.int32([x1, x2, y1, y2]))\n patch = np.array(patch._data).reshape(patch.size, order='F')\n return patch\n\n\n###\n\nclass JP2Plus(OpenJP2):\n\n def __init__(self, file, level0, engine):\n \"\"\"\n An extension to OpenJP2 object with a method to get a patch by maginifaction.\n\n :param file: Path to the matlab_files format WSI\n :param level0: The 'magnification' at level 0.\n :param engine: Matlab engine object.\n \"\"\"\n super(JP2Plus, self).__init__(file, engine)\n\n # ID (name) of the WSI\n self.ID = os.path.splitext(os.path.basename(file))[0]\n\n self.level0 = float(level0)\n\n # Compute level maginifications\n self.mags = [self.level0 / downsample for downsample in self.level_downsamples]\n\n def get_patch(self, w, h, mag, size):\n \"\"\"\n Get a patch.\n If required magnification is not available will use higher magnification and resize.\n\n :param w: Width coordinate in level 0 frame.\n :param h: Height coordinate in level 0 frame.\n :param mag: Desired magnification.\n :param size: Desired patch size (square patch).\n :return:\n \"\"\"\n assert self.level0 >= mag, 'Magnification not available.'\n\n higher_mags = [self.mags[i] >= mag for i in range(len(self.mags))]\n extraction_level = index_last_non_zero(higher_mags)\n extraction_mag = self.mags[extraction_level]\n extraction_size = int(size * extraction_mag / mag)\n\n patch = self.read_region((w, h), extraction_level, (extraction_size, extraction_size))\n patch = Image.fromarray(patch, 'RGB')\n if extraction_size != size:\n patch.thumbnail((size, size)) # Resize inplace.\n return patch\n\n def get_thumbnail(self, size):\n \"\"\"\n Generates a thumbnail image for visualisation\n :param size: a tuple of the target size\n :return: PIL Image\n \"\"\"\n level = get_level(mag=1.25, mags=self.mags, threshold=5.0)\n low_res = self.read_region(location=(0,0), level=level, size=self.level_dimensions[level])\n low_res = Image.fromarray(low_res)\n low_res.thumbnail(size)\n return low_res\n","sub_path":"wsisampler/slides/jp2plus.py","file_name":"jp2plus.py","file_ext":"py","file_size_in_byte":3916,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"413489157","text":"# -*- coding: utf-8 -*-\n\n\"\"\"\nThe Python and NumPy indexing operators \"[ ]\" and attribute operator \".\" provide quick \nand easy access to Pandas data structures across a wide range of use cases.\n.loc():Label based\n.iloc():Integer based\n.ix():Both Label and Integer based\n\"\"\"\nimport pandas as pd\nimport numpy as np\n#loc takes two single/list/range operator separated by ','. The first one indicates the row and the second one indicates columns.\ndf = pd.DataFrame(np.random.randn(8, 4),\nindex = ['a','b','c','d','e','f','g','h'], columns = ['A', 'B', 'C', 'D'])\nprint(df)\n\nprint(df.loc[:,'A'])\nprint(df.loc[:,['A','C']])\n\n\n# Select few rows for multiple columns, say list[]\nprint(df.loc[['a','b','f','h'],['A','C']])\n\n# Select range of all Columns\nprint(df.loc['a': 'h'])\n# getting Values with boolean array\nprint(df.loc['a']>0)\nprint(df.loc[:,'A']>0)\n#======================================iloc()================================================\n\"\"\"\nPandas provide various methods in order to get purely integer based indexing. Like python and numpy, these are 0-based indexing.\nThe various access methods are as follows −\nAn Integer\nA list of integers\nA range of values\n\"\"\"\ndata1 = pd.DataFrame(np.random.randn(8,4), columns = ['A','B','C','D'])\n# Select All row from Specific Comulns\ndata1.iloc[:,[0]]\n#data1.iloc[:4]\n\n# Inter Slicing\ndata1.iloc[:4]\ndata1.iloc[1:5,2:4]\n\n# Slicing through list of values\ndata1.iloc[[1,3,5],[2,3]]\ndata1.iloc[1:3,:]\ndata1.iloc[:,:]\ndata1.iloc[:,1:3]\n\"\"\"\n.ix()\nandas provides a hybrid method for selections and subsetting the object using the .ix() operator.\n\"\"\"\ndata1.ix[:,'A']\ndata1.ix[:,0]\n\n\n\n\n\n#Attribute Access\n#Columns can be selected using the attribute operator '.'.\ndata1.A\ndata1['A']\n#Note − We can pass a list of values to [ ] to select those columns.\ndata1[['A','B']]\n\n","sub_path":"python/pandas/indexingSelectingData.py","file_name":"indexingSelectingData.py","file_ext":"py","file_size_in_byte":1814,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"499118519","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sat Aug 25 16:13:23 2018\n\n@author: yamini\n\n\"\"\"\nclass Solution(object):\n def longestPalindrome(self, s):\n mydict = {}\n for each in s:\n mydict[each] = mydict.get(each,0)+1\n single = double = 0\n for val in mydict.values():\n if val % 2 == 0:\n double += val\n else:\n double += val -1\n single = 1\n return double + single\n\ns=Solution()\nprint(s.longestPalindrome('abcddddc'))\n \n","sub_path":"Longest_Palindrome.py","file_name":"Longest_Palindrome.py","file_ext":"py","file_size_in_byte":539,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"480015790","text":"\"\"\"\nUDP 套接字服务端\n\"\"\"\n\nfrom socket import *\n\nsockfd = socket(AF_INET, SOCK_DGRAM)\n\nsockfd.bind((\"172.40.74.177\", 22222))\n\nwhile True:\n print(\"please give me data and adress\")\n data, addr = sockfd.recvfrom(1024)\n print(addr)\n print(\"Message is \", data.decode())\n\n n = sockfd.sendto(b\"Receive\", addr)\n print(\"aleady sent %d bytes\" % n)\n\n if not data:\n break\n\nsockfd.close()\n","sub_path":"xiaojian/second_phase/day06/udp_server.py","file_name":"udp_server.py","file_ext":"py","file_size_in_byte":410,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"559505416","text":"cardList=[]\r\ndef menu():\r\n print(\"-----------------\")\r\n print(\"| 名片管理系统 |\")\r\n print(\"| 1.添加名片 |\")\r\n print(\"| 2.删除名片 |\")\r\n print(\"| 3.修改名片 |\")\r\n print(\"| 4.查询名片 |\")\r\n print(\"| 5.显示全部 |\")\r\n print(\"| 6.退出系统 |\")\r\n print(\"-----------------\")\r\n\r\ndef show():\r\n print(\"名片合集:\")\r\n for temp in cardList:\r\n print(\"姓名:%c\" % temp[\"name\"], \" \", end='')\r\n print(\"学号:%c\" % temp[\"number\"], \" \", end='')\r\n print(\"联系方式:%c\" % temp[\"tel\"])\r\n\r\ndef add():\r\n name = input(\"请输入姓名:\")\r\n number = input(\"请输入学号:\")\r\n tel = input(\"请输入联系方式:\")\r\n card={\"name\":name,\"number\":number,\"tel\":tel}\r\n cardList.append(card)\r\n\r\ndef delete():\r\n c = input(\"请输入要删除的名片的名字:\")\r\n for n in cardList:\r\n if c == n[\"name\"]:\r\n cardList.remove(n)\r\n\r\ndef change():\r\n c = input(\"请输入要修改的名片的名字:\")\r\n for n in cardList:\r\n if c == n[\"name\"]:\r\n new_name = input(\"请输入新姓名:\")\r\n new_number = input(\"请输入新学号:\")\r\n new_tel = input(\"请输入新联系方式:\")\r\n n[\"name\"] = new_name\r\n n[\"number\"] = new_number\r\n n[\"tel\"] = new_tel\r\n\r\ndef search():\r\n c = input(\"请输入要查询的名字:\")\r\n for n in cardList:\r\n if c == n[\"name\"]:\r\n print(\"查询结果如下:\")\r\n print(\"姓名:%c\" % n[\"name\"], \" \", end='')\r\n print(\"学号:%c\" % n[\"number\"], \" \", end='')\r\n print(\"联系方式:%c\" % n[\"tel\"])\r\n else:\r\n print(\"查无此人!\")\r\n\r\nif __name__ == '__main__':\r\n while True:\r\n menu()\r\n choice=input(\"请选择操作:\")\r\n a=int(choice)\r\n if a in [1,2,3,4,5,6]:\r\n if a==1:\r\n add()\r\n elif a == 2:\r\n delete()\r\n elif a == 3:\r\n change()\r\n elif a == 4:\r\n search()\r\n elif a==5:\r\n show()\r\n elif a==6:\r\n break\r\n else:\r\n print(\"操作无效!\")\r\n\r\n\r\n\r\n","sub_path":"大三下多媒体系统/multimedia/20200511/test/test6.py","file_name":"test6.py","file_ext":"py","file_size_in_byte":2294,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"333686554","text":"import numpy as np\r\nimport matplotlib.pyplot as plt\r\nimport seaborn as sns\r\n\r\nresult = []\r\ndef throw_coin (number_of_samples, sample_sizes):\r\n for i in range(number_of_samples):\r\n trial = np.random.choice(['H','T'], size = sample_sizes)\r\n result.append(np.mean(trial == 'H'))\r\n return result\r\n\r\nsample_sizes = np.arange(1,1001,1)\r\n\r\nprobabilities = throw_coin(20,10)\r\nprint(probabilities)\r\n \r\n# plt.plot(trials, probabilities, 'o-')\r\n# plt.xlabel(\"Number of trials\")\r\n# plt.ylabel(\"Probability\")\r\n# plt.title(\"Probability of Heads\")\r\n# plt.show()\r\n","sub_path":"probability_one.py","file_name":"probability_one.py","file_ext":"py","file_size_in_byte":557,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"23394020","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Apr 1 09:09:22 2020\n\n@author: idanovinda\n\"\"\"\n\n\nimport json\nimport pandas as pd\nimport re\n\n\nconll_input = \"../../data/Ted-Talk/conll2015/talk_1927_en/pdtb-parses.json\"\nwith open(conll_input) as f:\n f_input = json.load(f)\n \ndumps = json.dumps(f_input)\n \nclean_input = re.sub(\" +\", \" \", re.sub(r\"(? 0.9*time_limit:\n return([current_val,currentState,moves,1,0])\n else:\n States_moves = move(currentState)\n expanded = 1\n cutoff = 0\n N_STATES_EXPANDED += len(States_moves)\n #print('\\n1\\n')\n #print(States_moves)\n #print(len(States_moves))\n #time_cost = time.time()-time_start\n if maximizing:\n value = -1000\n count = 0\n for State_move in States_moves:\n count += 1\n #value = max(value, alpha_Beta(child, ply - 1, alpha, beta, False, useBasicStaticEval))\n #alpha = max(alpha, value)\n child = State_move[0]\n move_next = ((State_move[1][0] ,State_move[1][1]),(State_move[2][0] ,State_move[2][1]))\n output = alpha_Beta(child, ply - 1, alpha, beta, False, useBasicStaticEval)\n value_child = output[0]\n state_child = output[1]\n move_child = output[2]\n expanded = expanded + output[3]\n cutoff = cutoff + output[4]\n if (value < value_child)or((value == value_child)and(expanded % 2 == 0)):\n value = value_child\n state = child\n moves = move_next\n alpha = max(alpha, value)\n if alpha >= beta:\n cutoff = cutoff + len(States_moves) - count\n break\n return([value,state,moves,expanded,cutoff])\n else:\n value = 1000\n count = 0\n for State_move in States_moves:\n count += 1\n #value = min(value, alpha_Beta(child, ply - 1, alpha, beta, True, useBasicStaticEval))\n #beta = min(beta, value)\n child = State_move[0]\n move_next = ((State_move[1][0] ,State_move[1][1]),(State_move[2][0] ,State_move[2][1]))\n output = alpha_Beta(child, ply - 1, alpha, beta, True, useBasicStaticEval)\n value_child = output[0]\n state_child = output[1]\n move_child = output[2]\n expanded = expanded + output[3]\n cutoff = cutoff + output[4]\n if (value > value_child)or((value == value_child)and(expanded % 2 == 0)):\n value = value_child\n state = child\n moves = move_next\n beta = min(beta, value)\n if alpha >= beta:\n cutoff = cutoff + len(States_moves) - count\n break\n return([value,state,moves,expanded,cutoff])\n\ndef minmax(currentState, ply, maximizing = False, useBasicStaticEval=True):\n global time_cost, time_start, time_limit\n if (useBasicStaticEval == True):\n CURRENT_STATE_STATIC_VAL = basicStaticEval(currentState)\n else:\n CURRENT_STATE_STATIC_VAL = staticEval(currentState)\n state = currentState\n moves = ((0,0),(0,0))\n if (ply == 0)or(who_win(currentState) != \"No Win\"):\n return([CURRENT_STATE_STATIC_VAL,currentState,moves,1,0])\n time_cost = time.time()-time_start\n if time_cost > 0.9*time_limit:\n return([CURRENT_STATE_STATIC_VAL,currentState,moves,1,0])\n else:\n States_moves = move(currentState)\n expanded = 0\n if maximizing:\n value = -1000\n count = 0\n for State_move in States_moves:\n count += 1\n child = State_move[0]\n move_next = ((State_move[1][0] ,State_move[1][1]),(State_move[2][0] ,State_move[2][1]))\n output = minmax(child, ply - 1, False, useBasicStaticEval)\n value_child = output[0]\n state_child = output[1]\n move_child = output[2]\n expanded = expanded + output[3]\n if value < value_child:\n value = value_child\n state = child\n moves = move_next\n return([value,state,moves,expanded,0])\n else:\n value = 1000\n count = 0\n for State_move in States_moves:\n count += 1\n child = State_move[0]\n move_next = ((State_move[1][0] ,State_move[1][1]),(State_move[2][0] ,State_move[2][1]))\n output = minmax(child, ply - 1, True, useBasicStaticEval)\n value_child = output[0]\n state_child = output[1]\n move_child = output[2]\n expanded = expanded + output[3]\n if value > value_child:\n value = value_child\n state = child\n moves = move_next\n return([value,state,moves,expanded,0])\n\ndef makeMove(currentState, currentRemark, timelimit=10):\n global time_start, time_cost, time_limit\n # Compute the new state for a move.\n # You should implement an anytime algorithm based on IDDFS.\n\n # The following is a placeholder that just copies the current state.\n newState = BC.BC_state(currentState.board)\n\n # Fix up whose turn it will be.\n newState.whose_move = 1 - currentState.whose_move\n \n # Construct a representation of the move that goes from the\n # currentState to the newState.\n # Here is a placeholder in the right format but with made-up\n # numbers:\n time_start = time.time()\n time_cost = time.time()-time_start\n time_limit = timelimit\n alphabeta = True\n depth = 0\n basicStatic = False\n ZobristH = False\n output = parameterized_minimax(currentState,alphabeta,depth,basicStatic,ZobristH)\n depth = 1\n while time_cost < timelimit*0.9:\n output_last = output\n output = parameterized_minimax(currentState,alphabeta,depth,basicStatic,ZobristH)\n depth += 1\n #time_cost = time.time()-time_start\n print('Depth = '+str(depth))\n #value = output[0]\n state = output_last['NextState']\n moves = output_last['NextMove']\n #print(state)\n #print(moves)\n #print('CURRENT_STATE_STATIC_VAL = '+str(output_last['CURRENT_STATE_STATIC_VAL']))\n #print('N_STATES_EXPANDED = '+str(output_last['N_STATES_EXPANDED']))\n #print('N_STATIC_EVALS = '+str(output_last['N_STATIC_EVALS']))\n #print('N_CUTOFFS = '+str(output_last['N_CUTOFFS']))\n #newState = BC.BC_state(state.board)\n newState = state\n \n\n #move = ((5,1), (6,1))\n\n # Make up a new remark\n newRemark = \"I'll think harder in some future game. Here's my move\"\n\n return [[moves, newState], newRemark]\n\ndef nickname():\n return \"Stephen\"\n\ndef introduce():\n return \"I'm Stephen, a newbie Baroque Chess agent. I am created by Ye Jin. UW NETID yjin2. I am a character to play Baroque Chess\"\n\ndef prepare(player2Nickname):\n ''' Here the game master will give your agent the nickname of\n the opponent agent, in case your agent can use it in some of\n the dialog responses. Other than that, this function can be\n used for initializing data structures, if needed.'''\n return \"Hello %s. Let's begin.\" %player2Nickname\n\ndef basicStaticEval(state):\n '''Use the simple method for state evaluation described in the spec.\n This is typically used in parameterized_minimax calls to verify\n that minimax and alpha-beta pruning work correctly.'''\n sum_val = 0\n for i in (state.board):\n for j in i:\n sum_val = sum_val + Piece_VAL_Basic[j]\n return(sum_val)\n\ndef staticEval(state):\n '''Compute a more thorough static evaluation of the given state.\n This is intended for normal competitive play. How you design this\n function could have a significant impact on your player's ability\n to win games.'''\n sum_val = 0\n for i in (state.board):\n for j in i:\n sum_val = sum_val + Piece_VAL_Custom[j]\n return(sum_val)\n\ndef move(currentState):\n State = []\n for i in range(8):\n for j in range(8):\n if (currentState.board[i][j] % 2 == currentState.whose_move) and (currentState.board[i][j]!=0):\n if (currentState.board[i][j] == 2)or(currentState.board[i][j] == 3):\n State.extend(pawn_move(currentState,i,j))\n if (currentState.board[i][j] == 4)or(currentState.board[i][j] == 5):\n State.extend(coord_move(currentState,i,j))\n if (currentState.board[i][j] == 6)or(currentState.board[i][j] == 7):\n State.extend(leap_move(currentState,i,j))\n if (currentState.board[i][j] == 10)or(currentState.board[i][j] == 11):\n State.extend(withd_move(currentState,i,j))\n if (currentState.board[i][j] == 12)or(currentState.board[i][j] == 13):\n State.extend(king_move(currentState,i,j))\n if (currentState.board[i][j] == 14)or(currentState.board[i][j] == 15):\n State.extend(freez_move(currentState,i,j))\n if (currentState.board[i][j] == 8)or(currentState.board[i][j] == 9):\n State.extend(imit_move(currentState,i,j))\n #print(State)\n #print(len(State))\n return(State)\n\ndef pawn_move(currentState,posx,posy):\n State = []\n side = currentState.whose_move\n direction_x = [-1, 0, 1, 0]\n direction_y = [0, -1, 0, 1]\n if non_freezer(currentState,posx,posy):\n for i in range(4):\n for length in range(1,8):\n posx_new = posx + direction_x[i] * length\n posy_new = posy + direction_y[i] * length\n if outofrange(posx_new,posy_new)or(currentState.board[posx_new][posy_new] != 0):\n break\n else:\n newState = BC.BC_state(currentState.board)\n newState.whose_move = 1 - currentState.whose_move\n newState.board[posx_new][posy_new] = newState.board[posx][posy]\n newState.board[posx][posy] = 0\n for j in range(4):\n if not(outofrange(posx_new + 2*direction_x[j],posy_new + 2*direction_y[j])):\n if pawn_capture(newState,posx_new,posy_new, posx_new + direction_x[j],posy_new + direction_y[j]):\n newState.board[posx_new + direction_x[j]][posy_new + direction_y[j]] = 0\n State.append([newState, [posx, posy], [posx_new, posy_new]])\n return(State)\n\ndef coord_move(currentState,posx,posy):\n State = []\n side = currentState.whose_move\n direction_x = [-1, -1, 0, 1, 1, 1, 0, -1]\n direction_y = [0, 1, 1, 1, 0, -1, -1, -1]\n if non_freezer(currentState,posx,posy):\n for i in range(8):\n for length in range(1,8):\n posx_new = posx + direction_x[i] * length\n posy_new = posy + direction_y[i] * length\n if outofrange(posx_new,posy_new)or(currentState.board[posx_new][posy_new] != 0):\n break\n else:\n newState = BC.BC_state(currentState.board)\n newState.whose_move = 1 - currentState.whose_move\n newState.board[posx_new][posy_new] = newState.board[posx][posy]\n newState.board[posx][posy] = 0\n #Search king\n j = [j for j in newState.board if (12+side) in j][0]\n king_pos_x = newState.board.index(j)\n king_pos_y = j.index(12+side)\n if (newState.board[posx_new][king_pos_y]!=0)and(newState.board[posx_new][king_pos_y] % 2) != side:\n newState.board[posx_new][king_pos_y] = 0\n if (newState.board[posx_new][king_pos_y]!=0)and(newState.board[king_pos_x][posy_new] % 2) != side:\n newState.board[king_pos_x][posy_new] = 0\n State.append([newState, [posx, posy], [posx_new, posy_new]])\n return(State)\n\ndef leap_move(currentState,posx,posy):\n State = []\n side = currentState.whose_move\n direction_x = [-1, -1, 0, 1, 1, 1, 0, -1]\n direction_y = [0, 1, 1, 1, 0, -1, -1, -1]\n if non_freezer(currentState,posx,posy):\n for i in range(8):\n for length in range(1,8):\n posx_new = posx + direction_x[i] * length\n posy_new = posy + direction_y[i] * length\n if outofrange(posx_new,posy_new)or(sameside(currentState.board[posx_new][posy_new],currentState.board[posx][posy])):\n break\n else:\n if currentState.board[posx_new][posy_new] == 0:\n newState = BC.BC_state(currentState.board)\n newState.whose_move = 1 - currentState.whose_move\n newState.board[posx_new][posy_new] = newState.board[posx][posy]\n newState.board[posx][posy] = 0\n State.append([newState, [posx, posy], [posx_new, posy_new]])\n elif notsameside(currentState.board[posx_new][posy_new],currentState.board[posx][posy]):\n if (not(outofrange(posx_new+direction_x[i],posy_new+direction_y[i])))and(currentState.board[posx_new+direction_x[i]][posy_new+direction_y[i]]==0):\n newState = BC.BC_state(currentState.board)\n newState.whose_move = 1 - currentState.whose_move\n newState.board[posx_new+direction_x[i]][posy_new+direction_y[i]] = newState.board[posx][posy]\n newState.board[posx][posy] = 0\n newState.board[posx_new][posy_new] = 0\n posx_new = posx_new+direction_x[i]\n posy_new = posy_new+direction_y[i]\n State.append([newState, [posx, posy], [posx_new, posy_new]])\n break\n return(State)\n\ndef withd_move(currentState,posx,posy):\n State = []\n side = currentState.whose_move\n direction_x = [-1, -1, 0, 1, 1, 1, 0, -1]\n direction_y = [0, 1, 1, 1, 0, -1, -1, -1]\n if non_freezer(currentState,posx,posy):\n for i in range(8):\n for length in range(1,8):\n posx_new = posx + direction_x[i] * length\n posy_new = posy + direction_y[i] * length\n if outofrange(posx_new,posy_new)or(currentState.board[posx_new][posy_new] != 0):\n break\n else:\n newState = BC.BC_state(currentState.board)\n newState.whose_move = 1 - currentState.whose_move\n newState.board[posx_new][posy_new] = newState.board[posx][posy]\n newState.board[posx][posy] = 0\n if not(outofrange(posx+direction_x[(i+4)%8],posy+direction_y[(i+4)%8])):\n if notsameside(newState.board[posx+direction_x[(i+4)%8]][posy+direction_y[(i+4)%8]],currentState.board[posx][posy]):\n newState.board[posx+direction_x[(i+4)%8]][posy+direction_y[(i+4)%8]] = 0\n State.append([newState, [posx, posy], [posx_new, posy_new]])\n return(State)\n\ndef king_move(currentState,posx,posy):\n State = []\n side = currentState.whose_move\n direction_x = [-1, -1, 0, 1, 1, 1, 0, -1]\n direction_y = [0, 1, 1, 1, 0, -1, -1, -1]\n if non_freezer(currentState,posx,posy):\n for i in range(8):\n for length in range(1,2):\n posx_new = posx + direction_x[i] * length\n posy_new = posy + direction_y[i] * length\n if outofrange(posx_new,posy_new)or(sameside(currentState.board[posx_new][posy_new],currentState.board[posx][posy])):\n break\n else:\n newState = BC.BC_state(currentState.board)\n newState.whose_move = 1 - currentState.whose_move\n newState.board[posx_new][posy_new] = newState.board[posx][posy]\n newState.board[posx][posy] = 0\n State.append([newState, [posx, posy], [posx_new, posy_new]])\n return(State)\n\ndef freez_move(currentState,posx,posy):\n State = []\n side = currentState.whose_move\n direction_x = [-1, -1, 0, 1, 1, 1, 0, -1]\n direction_y = [0, 1, 1, 1, 0, -1, -1, -1]\n if (non_freezer(currentState,posx,posy))and(non_imitator(currentState,posx,posy)):\n for i in range(8):\n for length in range(1,8):\n posx_new = posx + direction_x[i] * length\n posy_new = posy + direction_y[i] * length\n if outofrange(posx_new,posy_new)or(currentState.board[posx_new][posy_new] != 0):\n break\n else:\n newState = BC.BC_state(currentState.board)\n newState.whose_move = 1 - currentState.whose_move\n newState.board[posx_new][posy_new] = newState.board[posx][posy]\n newState.board[posx][posy] = 0\n State.append([newState, [posx, posy], [posx_new, posy_new]])\n return(State)\n\ndef imit_move(currentState,posx,posy):\n State = []\n side = currentState.whose_move\n direction_x = [-1, -1, 0, 1, 1, 1, 0, -1]\n direction_y = [0, 1, 1, 1, 0, -1, -1, -1]\n if non_freezer(currentState,posx,posy):\n for i in range(8):\n for length in range(1,8):\n posx_new = posx + direction_x[i] * length\n posy_new = posy + direction_y[i] * length\n if (outofrange(posx_new,posy_new))or(sameside(currentState.board[posx_new][posy_new],currentState.board[posx][posy])):\n #print('\\n'+str(i)+'\\n')\n break\n else:\n if (currentState.board[posx_new][posy_new] == 0):\n eat = False\n if not(outofrange(posx+direction_x[(i+4)%8],posy+direction_y[(i+4)%8])):\n if (currentState.board[posx+direction_x[(i+4)%8]][posy+direction_y[(i+4)%8]] == BC.WHITE_WITHDRAWER - side):\n #eat the withdrawer\n newState = BC.BC_state(currentState.board)\n newState.whose_move = 1 - currentState.whose_move\n newState.board[posx_new][posy_new] = newState.board[posx][posy]\n newState.board[posx][posy] = 0\n newState.board[posx+direction_x[(i+4)%8]][posy+direction_y[(i+4)%8]] = 0\n State.append([newState, [posx, posy], [posx_new, posy_new]])\n eat = True\n if ((direction_x[i] == 0)or(direction_y[i] == 0)):\n eat_pincer = False\n for j in range(8):\n if ((direction_x[j] == 0)or(direction_y[j] == 0)):\n cap_x = posx_new + direction_x[j]\n cap_y = posy_new + direction_y[j]\n coop_x = posx_new + 2*direction_x[j]\n coop_y = posy_new + 2*direction_y[j]\n if (not(outofrange(coop_x,coop_y)))and(currentState.board[cap_x][cap_y] == BC.WHITE_PINCER - side)and(sameside(currentState.board[coop_x][coop_y],currentState.board[posx][posy])):\n #eat the pawn\n if eat_pincer == False:\n newState = BC.BC_state(currentState.board)\n newState.whose_move = 1 - currentState.whose_move\n newState.board[posx_new][posy_new] = newState.board[posx][posy]\n newState.board[posx][posy] = 0\n newState.board[cap_x][cap_y] = 0\n eat_pincer = True\n eat = True\n if eat_pincer == True:\n State.append([newState, [posx, posy], [posx_new, posy_new]])\n j = [j for j in currentState.board if (12+side) in j][0]\n king_pos_x = currentState.board.index(j)\n king_pos_y = j.index(12+side)\n if (currentState.board[posx_new][king_pos_y] == BC.WHITE_COORDINATOR - side)or(currentState.board[king_pos_x][posy_new] == BC.WHITE_COORDINATOR - side):\n #eat the coordinator\n newState = BC.BC_state(currentState.board)\n newState.whose_move = 1 - currentState.whose_move\n newState.board[posx_new][posy_new] = newState.board[posx][posy]\n newState.board[posx][posy] = 0\n if newState.board[posx_new][king_pos_y] == BC.WHITE_COORDINATOR - side:\n newState.board[posx_new][king_pos_y] = 0\n if newState.board[king_pos_x][posy_new] == BC.WHITE_COORDINATOR - side:\n newState.board[king_pos_x][posy_new] = 0\n eat = True\n State.append([newState, [posx, posy], [posx_new, posy_new]])\n if eat == False:\n newState = BC.BC_state(currentState.board)\n newState.whose_move = 1 - currentState.whose_move\n newState.board[posx_new][posy_new] = newState.board[posx][posy]\n newState.board[posx][posy] = 0\n State.append([newState, [posx, posy], [posx_new, posy_new]])\n elif (currentState.board[posx_new][posy_new] == BC.WHITE_KING - side)and(length == 1):\n #eat the king\n newState = BC.BC_state(currentState.board)\n newState.whose_move = 1 - currentState.whose_move\n newState.board[posx_new][posy_new] = newState.board[posx][posy]\n newState.board[posx][posy] = 0\n State.append([newState, [posx, posy], [posx_new, posy_new]])\n eat = True\n break\n elif (currentState.board[posx_new][posy_new] == BC.WHITE_LEAPER-side)and(not(outofrange(posx_new + direction_x[i],posy_new + direction_y[i]))):\n if currentState.board[posx_new + direction_x[i]][posy_new + direction_y[i]] == 0:\n #eat the leaper\n newState = BC.BC_state(currentState.board)\n newState.whose_move = 1 - currentState.whose_move\n newState.board[posx_new + direction_x[i]][posy_new + direction_y[i]] = newState.board[posx][posy]\n newState.board[posx][posy] = 0\n newState.board[posx_new][posy_new] = 0\n State.append([newState, [posx, posy], [posx_new + direction_x[i], posy_new + direction_y[i]]])\n else:\n break\n else:\n break\n #print(State)\n return(State) \n\ndef D2toD1(l):\n new_l = []\n for l1 in l:\n for l2 in l1:\n new_l.append(l2)\n return new_l\n\ndef non_freezer(currentState, posx, posy):\n direction_x = [-1, -1, -1, 0, 1, 1, 1, 0]\n direction_y = [-1, 0, 1, 1, 1, 0, -1, -1]\n side = currentState.whose_move\n for i in range(8):\n if not(outofrange(posx+direction_x[i], posy+direction_y[i])):\n if currentState.board[posx+direction_x[i]][posy+direction_y[i]] == (15 - side):\n return(False)\n return(True)\n\ndef non_imitator(currentState,posx,posy):\n direction_x = [-1, -1, -1, 0, 1, 1, 1, 0]\n direction_y = [-1, 0, 1, 1, 1, 0, -1, -1]\n side = currentState.whose_move\n for i in range(8):\n if not(outofrange(posx+direction_x[i], posy+direction_y[i])):\n if currentState.board[posx+direction_x[i]][posy+direction_y[i]] == (9 - side):\n return(False)\n return(True)\n\ndef nearby(currentState,posx,posy,piece):\n direction_x = [-1, -1, -1, 0, 1, 1, 1, 0]\n direction_y = [-1, 0, 1, 1, 1, 0, -1, -1]\n side = currentState.whose_move\n for i in range(8):\n if not(outofrange(posx+direction_x[i], posy+direction_y[i])):\n if currentState.board[posx+direction_x[i]][posy+direction_y[i]] == (piece - side):\n return(True)\n return(False)\n\ndef pawn_capture(currentState, posx, posy, pos_cap_x, pos_cap_y):\n side = 1 - currentState.whose_move\n cap = currentState.board[pos_cap_x][pos_cap_y]\n coop = currentState.board[pos_cap_x*2 - posx][pos_cap_y*2 - posy]\n if sameside(currentState.board[posx][posy], coop)and(notsameside(currentState.board[posx][posy], cap)):\n return(True)\n else:\n return(False)\n \ndef outofrange(posx,posy):\n if (posx > 7)or(posx < 0)or(posy > 7)or(posy < 0):\n return True\n else:\n return False\n\ndef sameside(a,b):\n if (a != 0)and(b != 0):\n if (a % 2) == (b % 2):\n return(True)\n else:\n return(False)\n else:\n return(False)\n\ndef notsameside(a,b):\n if (a != 0)and(b != 0):\n if (a % 2) != (b % 2):\n return(True)\n else:\n return(False)\n else:\n return(False)\n\ndef who_win(currentState):\n possibleWin = \"No Win\"\n black_king_detected = False\n white_king_detected = False\n for i in range(8):\n for j in range(8):\n if currentState.board[i][j] == BC.BLACK_KING: black_king_detected = True\n if currentState.board[i][j] == BC.WHITE_KING: white_king_detected = True\n if white_king_detected and not black_king_detected: possibleWin = \"Win for WHITE\"\n if black_king_detected and not white_king_detected: possibleWin = \"Win for BLACK\"\n return possibleWin","sub_path":"a5/PlayerSkeletonA.py","file_name":"PlayerSkeletonA.py","file_ext":"py","file_size_in_byte":25041,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"22422153","text":"# 1. The Whale Hotline API\r\nimport requests\r\nimport json\r\n\r\n# Creating a GET request\r\nurl = \"http://hotline.whalemuseum.org/api.json\"\r\nr = requests.get(url)\r\njson_obj = r.content.decode(\"utf-8\")\r\n# Store json data for future reference\r\nWhalesData = json.loads(json_obj)\r\n\r\n# 2. GBIF API\r\n# GBIF API refers to a data download from the website\r\n# it is now stored in gbif.csv file.\r\n\r\n\r\nfrom csv import reader, writer\r\nimport random\r\nimport csv\r\n\r\n\r\nchoice = [\"Male\", \"Male\", \"Female\"]\r\n# For Females:\r\nbirth_condition = [\"ready_for_fertilization\", \"recently_given_birth\", \"EXPECTANT\", \"INACTIVE\", \"INACTIVE\", \"INACTIVE\",\r\n \"INACTIVE\"]\r\n# Age list:\r\nage = []\r\nfor i in range(10):\r\n age.append(random.uniform(1.3, 9.8))\r\n age.append(random.uniform(0.1, 1))\r\nfor i in range(3):\r\n age.append(random.uniform(9.9, 16))\r\nsafety = []\r\nfor i in range(3):\r\n safety.append(\"DANGEROUS\")\r\nfor i in range(2):\r\n safety.append(\"RELATIVELY_DANGEROUS\")\r\nfor i in range(5):\r\n safety.append(\"SAFE\")\r\n\r\nspec_needs = []\r\n# Наразі залишимо цей список пустим.\r\n\r\nwith open('edited_gbif.csv', 'r') as read_obj:\r\n with open('edited_gbif.csv', 'w', newline='') as write_obj:\r\n csv_reader = reader(read_obj, delimiter=\"\\t\")\r\n\r\n csv_writer = writer(write_obj, delimiter=\"\\t\")\r\n # Read each row of the input csv file as list\r\n\r\n for row in csv_reader:\r\n # Append the parameter in the row / list\r\n row.append(random.choice(choice))\r\n if row[-1] == \"Female\":\r\n row.append(random.choice(birth_condition))\r\n else:\r\n row.append(\" --- \")\r\n\r\n row.append(round(random.choice(age), 1))\r\n\r\n if row[-1]<1:\r\n row.append(\"INFANT\")\r\n else:\r\n row.append(\" --- \")\r\n row.append(random.choice(safety))\r\n row.append(\"---\") # special needs\r\n\r\n # Add the updated row / list to the output file\r\n csv_writer.writerow(row)\r\n\r\n\r\n\r\n# with open(\"edited_gbif.csv\", \"r\") as csv_file:\r\n# csv_reader = csv.DictReader(csv_file, delimiter=\"\\t\")\r\n#\r\n# for line in csv_reader:\r\n# print(line)\r\n\r\n# print(WhalesData)\r\nwith open(\"whales.json\", \"w\") as file:\r\n json.dump(WhalesData, file)","sub_path":"HW2/project_api(ДЗ2).py","file_name":"project_api(ДЗ2).py","file_ext":"py","file_size_in_byte":2321,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"604341282","text":"\"\"\"\nDefinitions for the Dynamics. Dynamics derives from 2 other mixin\nclasses, which provide functionality for hierachical components and for local\ncomponents definitions of interface and dynamics\n\n:copyright: Copyright 2010-2013 by the Python lib9ML team, see AUTHORS.\n:license: BSD-3, see LICENSE for details.\n\"\"\"\nfrom nineml.exceptions import NineMLRuntimeError\nfrom nineml.utils import normalise_parameter_as_list, filter_discrete_types\nfrom itertools import chain\nfrom nineml.abstraction.componentclass import (\n ComponentClass, Parameter)\nfrom ..ports import (AnalogReceivePort, AnalogSendPort,\n AnalogReducePort, EventReceivePort,\n EventSendPort)\nfrom nineml.utils import (check_list_contain_same_items,\n assert_no_duplicates)\nfrom nineml.xmlns import NINEML\nfrom nineml.annotations import VALIDATE_DIMENSIONS\n\n\nclass Dynamics(ComponentClass):\n\n \"\"\"A Dynamics object represents a *component* in NineML.\n\n .. todo::\n\n For more information, see\n\n \"\"\"\n element_name = 'Dynamics'\n defining_attributes = (ComponentClass.defining_attributes +\n ('_analog_send_ports', '_analog_receive_ports',\n '_analog_reduce_ports', '_event_send_ports',\n '_event_receive_ports', '_regimes',\n '_state_variables'))\n class_to_member = dict(\n tuple(ComponentClass.class_to_member.iteritems()) +\n (('AnalogSendPort', 'analog_send_port'),\n ('AnalogReceivePort', 'analog_receive_port'),\n ('AnalogReducePort', 'analog_reduce_port'),\n ('EventSendPort', 'event_send_port'),\n ('EventReceivePort', 'event_receive_port'),\n ('Regime', 'regime'),\n ('StateVariable', 'state_variable')))\n\n send_port_dicts = ('_analog_send_ports', '_event_send_ports')\n receive_port_dicts = ('_analog_receive_ports', '_analog_reduce_ports',\n '_event_send_ports')\n\n def __init__(self, name, parameters=None, analog_ports=[],\n event_ports=[], regimes=None, aliases=None,\n state_variables=None, constants=None,\n validate_dimensions=True, url=None):\n \"\"\"Constructs a Dynamics\n\n :param name: The name of the component_class.\n :param parameters: A list containing either |Parameter| objects\n or strings representing the parameter names. If ``None``, then the\n parameters are automatically inferred from the |Dynamics| block.\n :param analog_ports: A list of |AnalogPorts|, which will be the\n local |AnalogPorts| for this object.\n :param event_ports: A list of |EventPorts| objects, which will be the\n local event-ports for this object. If this is ``None``, then they\n will be automatically inferred from the dynamics block.\n :param interface: A shorthand way of specifying the **interface** for\n this component_class; |Parameters|, |AnalogPorts| and |EventPorts|.\n ``interface`` takes a list of these objects, and automatically\n resolves them by type into the correct types.\n\n Examples:\n\n >>> a = Dynamics(name='MyComponent1')\n\n .. todo::\n\n Point this towards and example of constructing ComponentClasses.\n This can't be here, because we also need to know about dynamics.\n For examples\n\n \"\"\"\n ComponentClass.__init__(self, name=name, parameters=parameters,\n aliases=aliases, constants=constants,\n url=url)\n regimes = normalise_parameter_as_list(regimes)\n state_variables = normalise_parameter_as_list(state_variables)\n\n # Load the state variables as objects or strings:\n sv_types = (basestring, StateVariable)\n sv_td = filter_discrete_types(state_variables, sv_types)\n sv_from_strings = [StateVariable(o, dimension=None)\n for o in sv_td[basestring]]\n state_variables = sv_td[StateVariable] + sv_from_strings\n\n assert_no_duplicates(r.name for r in regimes)\n assert_no_duplicates(s.name for s in state_variables)\n\n self._regimes = dict((r.name, r) for r in regimes)\n self._state_variables = dict((s.name, s) for s in state_variables)\n\n # Ensure analog_ports is a list not an iterator\n analog_ports = list(analog_ports)\n event_ports = list(event_ports)\n\n # Check there aren't any duplicates in the port and parameter names\n assert_no_duplicates(p if isinstance(p, basestring) else p.name\n for p in chain(parameters if parameters else [],\n analog_ports, event_ports))\n\n self._analog_send_ports = dict((p.name, p) for p in analog_ports\n if isinstance(p, AnalogSendPort))\n self._analog_receive_ports = dict((p.name, p) for p in analog_ports\n if isinstance(p, AnalogReceivePort))\n self._analog_reduce_ports = dict((p.name, p) for p in analog_ports\n if isinstance(p, AnalogReducePort))\n\n # Create dummy event ports to keep the ActionVisitor base class of\n # the interface inferrer happy\n self._event_receive_ports = self._event_send_ports = self.subnodes = {}\n\n # EventPort, StateVariable and Parameter Inference:\n inferred_struct = DynamicsInterfaceInferer(self)\n\n # Check any supplied parameters match:\n if parameters is not None:\n inf_check(self._parameters.keys(), inferred_struct.parameter_names,\n 'Parameters')\n else:\n self._parameters = dict((n, Parameter(n))\n for n in inferred_struct.parameter_names)\n\n # Check any supplied state_variables match:\n if self.num_state_variables:\n state_var_names = [p.name for p in self.state_variables]\n inf_check(state_var_names, inferred_struct.state_variable_names,\n 'StateVariables')\n else:\n state_vars = dict((n, StateVariable(n)) for n in\n inferred_struct.state_variable_names)\n self._state_variables = state_vars\n\n # Set and check event receive ports match inferred\n self._event_receive_ports = dict(\n (p.name, p) for p in event_ports if isinstance(p,\n EventReceivePort))\n if len(self._event_receive_ports):\n # FIXME: not all OutputEvents are necessarily exposed as Ports,\n # so really we should just check that all declared output event\n # ports are in the list of inferred ports, not that the declared\n # list is identical to the inferred one.\n inf_check(self._event_receive_ports.keys(),\n inferred_struct.input_event_port_names,\n 'Event Ports In')\n else:\n # Event ports not supplied, so lets use the inferred ones.\n for pname in inferred_struct.input_event_port_names:\n self._event_receive_ports[pname] = EventReceivePort(name=pname)\n\n # Set and check event send ports match inferred\n self._event_send_ports = dict(\n (p.name, p) for p in event_ports if isinstance(p, EventSendPort))\n if len(self._event_send_ports):\n inf_check(self._event_send_ports.keys(),\n inferred_struct.event_out_port_names,\n 'Event Ports Out')\n else:\n # Event ports not supplied, so lets use the inferred ones.\n for pname in inferred_struct.event_out_port_names:\n self._event_send_ports[pname] = EventSendPort(name=pname)\n\n self.annotations[NINEML][VALIDATE_DIMENSIONS] = validate_dimensions\n for transition in self.all_transitions():\n transition.bind(self)\n # Is the finished component_class valid?:\n self.validate()\n\n # -------------------------- #\n\n def rename_symbol(self, old_symbol, new_symbol):\n DynamicsRenameSymbol(self, old_symbol, new_symbol)\n\n def assign_indices(self):\n DynamicsAssignIndices(self)\n\n def required_for(self, expressions):\n return DynamicsRequiredDefinitions(self, expressions)\n\n def dimension_of(self, element):\n try:\n resolver = self._dimension_resolver\n except AttributeError:\n resolver = DynamicsDimensionResolver(self)\n self._dimension_resolver = resolver\n return resolver.dimension_of(element)\n\n def overridden_in_regimes(self, alias):\n return (r for r in self.regimes if alias.name in r.alias_names)\n\n def _find_element(self, element):\n return DynamicsElementFinder(element).found_in(self)\n\n def __repr__(self):\n return \"\" % self.name\n\n def validate(self, validate_dimensions=None):\n if validate_dimensions is None:\n validate_dimensions = self.annotations[NINEML].get(\n VALIDATE_DIMENSIONS, True)\n self._resolve_transition_regimes()\n DynamicsValidator.validate_componentclass(self, validate_dimensions)\n\n def accept_visitor(self, visitor, **kwargs):\n \"\"\" |VISITATION| \"\"\"\n return visitor.visit_componentclass(self, **kwargs)\n\n @property\n def num_state_variables(self):\n return len(list(self._state_variables))\n\n @property\n def num_regimes(self):\n return len(list(self._regimes))\n\n @property\n def attributes_with_dimension(self):\n return chain(super(Dynamics, self).attributes_with_dimension,\n self.analog_ports, self.state_variables)\n\n @property\n def num_analog_send_ports(self):\n \"\"\"Returns an iterator over the local |AnalogSendPort| objects\"\"\"\n return len(self._analog_send_ports)\n\n @property\n def num_analog_receive_ports(self):\n \"\"\"Returns an iterator over the local |AnalogReceivePort| objects\"\"\"\n return len(self._analog_receive_ports)\n\n @property\n def num_analog_reduce_ports(self):\n \"\"\"Returns an iterator over the local |AnalogReducePort| objects\"\"\"\n return len(self._analog_reduce_ports)\n\n @property\n def num_event_send_ports(self):\n \"\"\"Returns an iterator over the local |EventSendPort| objects\"\"\"\n return len(self._event_send_ports)\n\n @property\n def num_event_receive_ports(self):\n \"\"\"Returns an iterator over the local |EventReceivePort| objects\"\"\"\n return len(self._event_receive_ports)\n\n @property\n def analog_send_ports(self):\n \"\"\"Returns an iterator over the local |AnalogSendPort| objects\"\"\"\n return self._analog_send_ports.itervalues()\n\n @property\n def analog_receive_ports(self):\n \"\"\"Returns an iterator over the local |AnalogReceivePort| objects\"\"\"\n return self._analog_receive_ports.itervalues()\n\n @property\n def analog_reduce_ports(self):\n \"\"\"Returns an iterator over the local |AnalogReducePort| objects\"\"\"\n return self._analog_reduce_ports.itervalues()\n\n @property\n def event_send_ports(self):\n \"\"\"Returns an iterator over the local |EventSendPort| objects\"\"\"\n return self._event_send_ports.itervalues()\n\n @property\n def event_receive_ports(self):\n \"\"\"Returns an iterator over the local |EventReceivePort| objects\"\"\"\n return self._event_receive_ports.itervalues()\n\n @property\n def ports(self):\n return chain(super(Dynamics, self).ports,\n self.analog_send_ports, self.analog_receive_ports,\n self.analog_reduce_ports, self.event_send_ports,\n self.event_receive_ports)\n\n def port(self, name):\n try:\n return self.send_port(name)\n except KeyError:\n return self.receive_port(name)\n\n def receive_port(self, name):\n try:\n return self.event_receive_port(name)\n except KeyError:\n try:\n return self.analog_receive_port(name)\n except KeyError:\n return self.analog_reduce_port(name)\n\n def send_port(self, name):\n try:\n return self.event_send_port(name)\n except KeyError:\n return self.analog_send_port(name)\n\n @property\n def send_ports(self):\n return chain(self.analog_send_ports, self.event_send_ports)\n\n @property\n def receive_ports(self):\n return chain(self.analog_receive_ports, self.analog_reduce_ports,\n self.event_receive_ports)\n\n @property\n def analog_ports(self):\n \"\"\"Returns an iterator over the local analog port objects\"\"\"\n return chain(self.analog_send_ports, self.analog_receive_ports,\n self.analog_reduce_ports)\n\n @property\n def event_ports(self):\n return chain(self.event_send_ports, self.event_receive_ports)\n\n def analog_port(self, name):\n try:\n return self.analog_send_port(name)\n except KeyError:\n try:\n return self.analog_receive_port(name)\n except KeyError:\n return self.analog_reduce_port(name)\n\n def event_port(self, name):\n try:\n return self.event_send_port(name)\n except KeyError:\n return self.event_receive_port(name)\n\n @property\n def regimes(self):\n \"\"\"Forwarding function to self._regimes\"\"\"\n return self._regimes.itervalues()\n\n @property\n def state_variables(self):\n \"\"\"Forwarding function to self._state_variables\"\"\"\n return self._state_variables.itervalues()\n\n def regime(self, name):\n return self._regimes[name]\n\n def state_variable(self, name):\n return self._state_variables[name]\n\n def analog_send_port(self, name):\n return self._analog_send_ports[name]\n\n def analog_receive_port(self, name):\n return self._analog_receive_ports[name]\n\n def analog_reduce_port(self, name):\n return self._analog_reduce_ports[name]\n\n def event_send_port(self, name):\n return self._event_send_ports[name]\n\n def event_receive_port(self, name):\n return self._event_receive_ports[name]\n\n @property\n def regime_names(self):\n return self._regimes.iterkeys()\n\n @property\n def state_variable_names(self):\n return self._state_variables.iterkeys()\n\n @property\n def port_names(self):\n return chain(self.analog_port_names, self.event_port_names)\n\n @property\n def analog_port_names(self):\n \"\"\"Returns an iterator over the local analog port objects\"\"\"\n return chain(self.analog_send_port_names,\n self.analog_receive_port_names,\n self.analog_reduce_port_names)\n\n @property\n def event_port_names(self):\n \"\"\"Returns an iterator over the local analog port objects\"\"\"\n return chain(self.event_send_port_names,\n self.event_receive_port_names)\n\n @property\n def analog_send_port_names(self):\n \"\"\"Returns an iterator over the local |AnalogSendPort| names\"\"\"\n return self._analog_send_ports.iterkeys()\n\n @property\n def analog_receive_port_names(self):\n \"\"\"Returns an iterator over the local |AnalogReceivePort| names\"\"\"\n return self._analog_receive_ports.iterkeys()\n\n @property\n def analog_reduce_port_names(self):\n \"\"\"Returns an iterator over the local |AnalogReducePort| names\"\"\"\n return self._analog_reduce_ports.iterkeys()\n\n @property\n def event_send_port_names(self):\n \"\"\"Returns an iterator over the local |EventSendPort| names\"\"\"\n return self._event_send_ports.iterkeys()\n\n @property\n def event_receive_port_names(self):\n \"\"\"Returns an iterator over the local |EventReceivePort| names\"\"\"\n return self._event_receive_ports.iterkeys()\n\n @property\n def all_components(self):\n \"\"\"\n Returns an iterator over this component_class and all sub_dynamics\n \"\"\"\n yield self\n for subcomponent in self.subnodes.values():\n for subcomp in subcomponent.all_components:\n yield subcomp\n\n @property\n def all_expressions(self):\n extractor = DynamicsExpressionExtractor()\n extractor.visit(self)\n return extractor.expressions\n\n @property\n def transitions(self):\n return self.all_transitions()\n\n def all_transitions(self):\n return chain(*(r.transitions for r in self.regimes))\n\n def all_on_conditions(self, trigger=None):\n return chain(*((oc for oc in r.on_conditions\n if trigger is None or oc.trigger == trigger)\n for r in self.regimes))\n\n def all_on_events(self, event_port=None):\n return chain(*((oe for oe in r.on_events\n if event_port is None or oe.port == event_port)\n for r in self.regimes))\n\n def all_time_derivatives(self, state_variable=None):\n return chain(*((td for td in r.time_derivatives\n if (state_variable is None or\n td.variable == state_variable.name))\n for r in self.regimes))\n\n def all_output_analogs(self):\n \"\"\"\n Returns an iterator over all aliases that are required for analog\n send ports\n \"\"\"\n return (a for a in self.aliases\n if a.name in self.analog_send_port_names)\n\n # -------------------------- #\n\n def backsub_all(self):\n \"\"\"Expand all alias definitions in local equations.\n\n This function finds |Aliases|, |TimeDerivatives|, *send* |AnalogPorts|,\n |StateAssignments| and |Conditions| which are defined in terms of other\n |Aliases|, and expands them, such that each only has |Parameters|,\n |StateVariables| and recv/reduce |AnalogPorts| on the RHS.\n\n \"\"\"\n\n for alias in self.aliases:\n alias_expander = DynamicsExpandAliasDefinition(\n originalname=alias.lhs, targetname=(\"(%s)\" % alias.rhs))\n alias_expander.visit(self)\n\n def _resolve_transition_regimes(self):\n # Check that the names of the regimes are unique:\n assert_no_duplicates([r.name for r in self.regimes])\n # We only worry about 'target' regimes, since source regimes are taken\n # care of for us by the Regime objects they are attached to.\n for regime in self.regimes:\n for trans in regime.transitions:\n trans.set_source_regime(regime)\n target = trans.target_regime_name\n if target is None:\n target = regime # to same regime\n else:\n try:\n target = self.regime(target) # Lookup by name\n except KeyError:\n self.regime(target)\n raise NineMLRuntimeError(\n \"Can't find regime '{}' referenced from '{}' \"\n \"transition\".format(trans.target_regime,\n trans._name))\n trans.set_target_regime(target)\n\n def to_xml(self, document, **kwargs): # @UnusedVariable\n self.standardize_unit_dimensions()\n self.validate()\n return DynamicsXMLWriter(document).visit(self)\n\n @classmethod\n def from_xml(cls, element, document, **kwargs):\n return DynamicsXMLLoader(document).load_dynamics(\n element, url=document.url, **kwargs)\n\n\ndef inf_check(l1, l2, desc):\n check_list_contain_same_items(l1, l2, desc1='Declared',\n desc2='Inferred', ignore=['t'], desc=desc)\n\n# Import visitor modules and those which import visitor modules\nfrom .regimes import StateVariable\nfrom .visitors.validators import DynamicsValidator\nfrom .visitors import DynamicsInterfaceInferer\nfrom .visitors.queriers import (DynamicsElementFinder,\n DynamicsRequiredDefinitions,\n DynamicsExpressionExtractor,\n DynamicsDimensionResolver)\nfrom .visitors.modifiers import (\n DynamicsRenameSymbol, DynamicsAssignIndices,\n DynamicsExpandAliasDefinition)\nfrom .visitors.xml import DynamicsXMLLoader, DynamicsXMLWriter\n","sub_path":"nineml/abstraction/dynamics/base.py","file_name":"base.py","file_ext":"py","file_size_in_byte":20581,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"338343333","text":"#coding:utf-8\nisTrain = True\ntrain_steps=5000 \ncheckpoint_steps = 200\nbatch_size=100\n\nimport tensorflow as tf\nfrom tensorflow.examples.tutorials.mnist import input_data\nmnist=input_data.read_data_sets('MNIST_data',one_hot=True)\n\nwith tf.variable_scope('Input'):\n xs=tf.placeholder(tf.float32,[None,784],name='x_input')/255\n ys=tf.placeholder(tf.float32,[None,10],name='y_input')\n\nwith tf.variable_scope('Net'):\n l1=tf.layers.dense(xs,500,tf.nn.relu,name='hid_layer')\n prediction=tf.layers.dense(l1,10,tf.nn.softmax,name='pre_layer')\n \ncross_entropy=tf.losses.softmax_cross_entropy(ys,prediction,scope='loss')\ntrain_step=tf.train.GradientDescentOptimizer(0.1).minimize(cross_entropy)\n\ncorrect_prediction=tf.equal(tf.argmax(prediction,1),tf.argmax(ys,1))\naccuracy=tf.reduce_mean(tf.cast(correct_prediction,tf.float32))\n\nsaver=tf.train.Saver(max_to_keep=1)\n\nwith tf.Session() as sess:\n sess.run(tf.global_variables_initializer())\n if isTrain:\n max_acc=0\n validate_feed={xs:mnist.validation.images,ys:mnist.validation.labels}\n test_feed={xs:mnist.test.images,ys:mnist.test.labels}\n for i in range(train_steps):\n batch_xs,batch_ys=mnist.train.next_batch(batch_size)\n sess.run(train_step,feed_dict={xs:batch_xs,ys:batch_ys})\n if i%checkpoint_steps==0:\n validate_acc=sess.run(accuracy,feed_dict=validate_feed)\n print(validate_acc)\n if validate_acc>max_acc:\n max_acc=validate_acc\n saver.save(sess,r'C:\\Users\\zylzlh\\Desktop\\my_model',global_step=i+1)\n else:\n # Restore model weights from previously saved model \n new_saver = tf.train.import_meta_graph(r'C:\\Users\\zylzlh\\Desktop\\my_model-501.meta')\n new_saver.restore(sess, tf.train.latest_checkpoint(r'C:\\Users\\zylzlh\\Desktop'))\n graph = tf.get_default_graph()\n print(sess.run('Weights:0'))\n print(sess.run('biases:0'))\n print(sess.run(prediction,feed_dict={xs:mnist.test.images}))\n validate_acc=sess.run(accuracy,feed_dict=test_feed)\n print(validate_acc)\n","sub_path":"mnistClassification.py","file_name":"mnistClassification.py","file_ext":"py","file_size_in_byte":2120,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"311973903","text":"from aws_cdk import core as cdk\n\nfrom aws_cdk import (\n core,\n aws_sqs as _sqs\n)\n\n\nclass AwsCdkSqsStackStack(cdk.Stack):\n\n def __init__(self, scope: cdk.Construct, construct_id: str, **kwargs) -> None:\n super().__init__(scope, construct_id, **kwargs)\n\n # The code that defines your stack goes here\n\n #Create SQS queue\n hui_queue = _sqs.Queue(\n self,\n \"huiqueue\",\n queue_name = \"hui_queue.fifo\",\n fifo = True,\n encryption = _sqs.QueueEncryption.KMS_MANAGED,\n retention_period = core.Duration.days(4),\n visibility_timeout = core.Duration.seconds(45)\n )\n","sub_path":"aws_cdk_sqs_stack/aws_cdk_sqs_stack/aws_cdk_sqs_stack_stack.py","file_name":"aws_cdk_sqs_stack_stack.py","file_ext":"py","file_size_in_byte":672,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"192112837","text":"import ctypes\nimport pycuda.autoinit\nimport pycuda.driver as cuda\nimport tensorrt as trt\n\n\nclass HostDeviceMem:\n def __init__(self, host_mem, device_mem):\n self.host = host_mem\n self.device = device_mem\n\n def __str__(self):\n return \"Host:\\n\" + str(self.host) + \"\\nDevice:\\n\" + str(self.device)\n\n def __repr__(self):\n return self.__str__()\n\n\nclass InferenceBackend:\n # initialize TensorRT\n TRT_LOGGER = trt.Logger(trt.Logger.ERROR)\n trt.init_libnvinfer_plugins(TRT_LOGGER, '')\n\n def __init__(self, model, batch_size):\n self.model = model\n self.batch_size = batch_size\n\n # load plugin if the model requires one\n if self.model.PLUGIN_PATH is not None:\n try:\n ctypes.cdll.LoadLibrary(self.model.PLUGIN_PATH)\n except OSError as err:\n raise RuntimeError('Plugin not found') from err\n\n # load trt engine or build one if not found\n if not self.model.ENGINE_PATH.exists():\n self.engine = self.model.build_engine(InferenceBackend.TRT_LOGGER, self.batch_size)\n else:\n runtime = trt.Runtime(InferenceBackend.TRT_LOGGER)\n with open(self.model.ENGINE_PATH, 'rb') as engine_file:\n buf = engine_file.read()\n self.engine = runtime.deserialize_cuda_engine(buf)\n if self.engine is None:\n raise RuntimeError('Unable to load the engine file')\n if self.engine.has_implicit_batch_dimension:\n assert self.batch_size <= self.engine.max_batch_size\n\n # allocate buffers\n self.bindings = []\n self.outputs = []\n for binding in self.engine:\n shape = self.engine.get_binding_shape(binding)\n size = trt.volume(shape)\n if self.engine.has_implicit_batch_dimension:\n size *= self.batch_size\n dtype = trt.nptype(self.engine.get_binding_dtype(binding))\n # allocate host and device buffers\n host_mem = cuda.pagelocked_empty(size, dtype)\n device_mem = cuda.mem_alloc(host_mem.nbytes)\n # append the device buffer to device bindings\n self.bindings.append(int(device_mem))\n if self.engine.binding_is_input(binding):\n if not self.engine.has_implicit_batch_dimension:\n assert self.batch_size == shape[0]\n self.input = HostDeviceMem(host_mem, device_mem)\n else:\n self.outputs.append(HostDeviceMem(host_mem, device_mem))\n self.context = self.engine.create_execution_context()\n self.stream = cuda.Stream()\n\n @property\n def input_handle(self):\n return self.input.host\n\n @input_handle.setter\n def input_handle(self, val):\n self.input.host[:] = val\n\n def infer(self):\n self.infer_async()\n return self.synchronize()\n\n def infer_async(self):\n cuda.memcpy_htod_async(self.input.device, self.input.host, self.stream)\n if self.engine.has_implicit_batch_dimension:\n self.context.execute_async(batch_size=self.batch_size, bindings=self.bindings,\n stream_handle=self.stream.handle)\n else:\n self.context.execute_async_v2(bindings=self.bindings, stream_handle=self.stream.handle)\n for out in self.outputs:\n cuda.memcpy_dtoh_async(out.host, out.device, self.stream)\n\n def synchronize(self):\n self.stream.synchronize()\n return [out.host for out in self.outputs]\n","sub_path":"fastmot/utils/inference.py","file_name":"inference.py","file_ext":"py","file_size_in_byte":3553,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"27"} +{"seq_id":"423918195","text":"# -*- coding: utf-8 -*-\n\n# Copyright (C) 2017 Luis López \n#\n# This program is free software; you can redistribute it and/or\n# modify it under the terms of the GNU General Public License\n# as published by the Free Software Foundation; either version 2\n# of the License, or (at your option) any later version.\n#\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program; if not, write to the Free Software\n# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301,\n# USA.\n\n\nimport fnmatch\nimport functools\n\n\nimport arroyo\nimport arroyo.extensions\n\n\nclass SourceFieldsFilter(arroyo.extensions.FilterExtension):\n __extension_name__ = 'sourcefields'\n\n HANDLES = (\n 'name',\n 'name_glob',\n 'language',\n 'type',\n 'provider',\n 'uri_glob')\n\n def _exact_match(self, key, value, item):\n try:\n val = getattr(item, key)\n return val == value\n\n except KeyError:\n return False\n\n def _glob_match(self, key, value, item):\n try:\n val = getattr(item, key)\n return fnmatch.fnmatch(val.lower(), value)\n\n except KeyError:\n return False\n\n def _type_match(self, key, value, item):\n _map = {\n 'source': lambda x: isinstance(x, arroyo.Source),\n 'episode': lambda x: x.entity and isinstance(x.entity, arroyo.Episode),\n 'movie': lambda x: x.entity and isinstance(x.entity, arroyo.Movie),\n }\n try:\n return _map[value](item)\n except KeyError:\n pass\n\n raise ValueError((key, value))\n\n def apply(self, key, value, it):\n if key in ('name', 'provider'):\n fn = functools.partial(self._exact_match, key, value)\n\n elif key in ('name_glob'):\n fn = functools.partial(self._glob_match, key[:-5], value.lower())\n\n elif key == 'type':\n fn = functools.partial(self._type_match, key, value.lower())\n\n else:\n raise ValueError(key)\n\n return filter(\n lambda x: fn(x),\n it)\n\n\n__arroyo_extensions__ = (SourceFieldsFilter,)\n","sub_path":"arroyo/plugins/filters/source.py","file_name":"source.py","file_ext":"py","file_size_in_byte":2439,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"23182975","text":"#!/usr/bin/env python\n#-*-coding:utf-8-*-\n \n# File Name: OCR_Digits.py\n# Author: Wang Junjie\n# Created Time: 2018-09-16\n\nimport numpy as np\nimport cv2\nimport matplotlib.pyplot as plt\n\nimg = cv2.imread('../images/digits.png')\ngray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)\n\ncells = [np.hsplit(i,100) for i in np.vsplit(gray,50)]\n\ndata = np.array(cells)\n\ntrain = data[:,:50].reshape(-1,400).astype(np.float32)\ntest = data[:,50:].reshape(-1,400).astype(np.float32)\n\nk = np.arange(10)\nresponses = np.repeat(k,250)[:,np.newaxis]\nlabel = np.copy(responses)\n\nknn = cv2.ml.KNearest_create()\nknn.train(train,cv2.ml.ROW_SAMPLE,responses)\n\nret,result,neigh,dst = knn.findNearest(test,5)\n\ncorrect = np.count_nonzero(result == label)\n\naccuracy = correct*100.0/result.size\nprint('The accuracy is:',accuracy)\n\n\nnp.savez('knn_data.npz',train = train,train_labels = label)\n\nwith np.load('knn_data.npz') as data:\n train = data['train']\n label = data['train_labels']\n\n\n\n","sub_path":"machine_learning/OCR_Digits.py","file_name":"OCR_Digits.py","file_ext":"py","file_size_in_byte":954,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"109283678","text":"\"\"\" \ntest SimpleBoost method\nnote: n=3 seems to do consistently better than other n's...\n\"\"\"\nimport jax.numpy as np\nimport tigerforecast\nfrom tigerforecast.utils.optimizers.ogd import OGD\nfrom tigerforecast.utils.optimizers.losses import mse\nimport matplotlib.pyplot as plt\nfrom tigerforecast.utils.random import set_key\nfrom tqdm import tqdm\n\ndef avg_regret(loss):\n avg_regret = []\n cur_avg = 0\n for i in range(len(loss)):\n cur_avg = (i / (i + 1)) * cur_avg + loss[i] / (i + 1)\n avg_regret.append(cur_avg)\n return avg_regret\n\ndef test_simple_boost(steps=5000, show=False):\n test_simple_boost_arma(steps=steps, show=show)\n #test_simple_boost_lstm(steps=steps, show=show)\n print(\"test_simple_boost passed\")\n\ndef avg_regret(loss):\n avg_regret = []\n cur_avg = 0\n for i in range(len(loss)):\n cur_avg = (i / (i + 1)) * cur_avg + loss[i] / (i + 1)\n avg_regret.append(cur_avg)\n return avg_regret\n\ndef test_simple_boost_lstm(steps=500, show=True):\n # method initialize\n T = steps\n method_id = \"LSTM\"\n ogd = OGD(learning_rate=0.01)\n method_params = {'n':1, 'm':1, 'l':5, 'h':10, 'optimizer':ogd}\n methods = []\n Ns = [1, 3, 6]\n for n in Ns: # number of weak learners\n method = tigerforecast.method(\"SimpleBoost\")\n method.initialize(method_id, method_params, n, reg=1.0) # regularization\n methods.append(method)\n\n # regular AutoRegressor for comparison\n autoreg = tigerforecast.method(\"AutoRegressor\")\n autoreg.initialize(p=4) # regularization\n\n # problem initialize\n p, q = 4, 0\n problem = tigerforecast.problem(\"ARMA-v0\")\n y_true = problem.initialize(p, q, noise_magnitude=0.1)\n \n # run all boosting method\n result_list = [[] for n in Ns]\n last_value = []\n autoreg_loss = []\n for i in range(T):\n y_next = problem.step()\n\n # predictions for every boosting method\n for result_i, method_i in zip(result_list, methods):\n y_pred = method_i.predict(y_true)\n result_i.append(mse(y_next, y_pred))\n method_i.update(y_next)\n\n # last value and autoregressor predictions\n last_value.append(mse(y_true, y_next))\n autoreg_loss.append(mse(autoreg.predict(y_true), y_next))\n autoreg.update(y_next)\n y_true = y_next\n \n # plot performance\n if show:\n start = 100\n x = np.arange(start, steps)\n plt.figure(figsize=(12,8))\n\n # plot every boosting method loss\n for n, results in zip(Ns, result_list):\n print(\"Mean loss for n={}: {}\".format(n, np.mean(np.array(results[start:]))))\n plt.plot(x, avg_regret(results[start:]), label=\"SimpleBoost, n={}\".format(n))\n\n # plot loss for last value and autoregressor methods\n print(\"Mean loss for LastValue: {}\".format(np.mean(np.array(last_value[start:]))))\n plt.plot(x, avg_regret(last_value[start:]), label=\"Last value method\")\n print(\"Mean loss for AutoRegressor: {}\".format(np.mean(np.array(autoreg_loss[start:]))))\n plt.plot(x, avg_regret(autoreg_loss[start:]), label=\"AutoRegressor method\")\n\n plt.title(\"SimpleBoost method on ARMA problem\")\n plt.legend()\n plt.show(block=False)\n plt.pause(10)\n plt.close()\n\n\ndef test_simple_boost_arma(steps=500, show=True):\n # method initialize\n T = steps\n method_id = \"AutoRegressor\"\n method_params = {'p':18, 'optimizer':OGD}\n Ns = [64]\n timelines = [6, 9, 12]\n\n # regular AutoRegressor for comparison\n autoreg = tigerforecast.method(\"AutoRegressor\")\n autoreg.initialize(p=18, optimizer = OGD) \n\n fig, ax = plt.subplots(nrows=1, ncols=3)\n cur = 0\n\n # run all boosting method\n for timeline in timelines:\n\n # problem initialize\n problem = tigerforecast.problem(\"ENSO-v0\")\n x, y_true = problem.initialize(input_signals = ['oni'], timeline = timeline)\n methods = []\n\n for n in Ns: # number of weak learners\n method = tigerforecast.method(\"SimpleBoost\")\n method.initialize(method_id, method_params, n, reg=0.0) # regularization\n methods.append(method)\n\n result_list = [[] for n in Ns]\n autoreg_loss = []\n\n for i in tqdm(range(T)):\n\n # predictions for every boosting method\n for result_i, method_i in zip(result_list, methods):\n y_pred = method_i.predict(x)\n result_i.append(mse(y_true, y_pred))\n method_i.update(y_true)\n\n # last value and autoregressor predictions\n autoreg_loss.append(mse(autoreg.predict(x), y_true))\n autoreg.update(y_true)\n x, y_true = problem.step()\n \n # plot performance\n if show:\n\n start = T//2\n\n # plot every boosting method loss\n for n, results in zip(Ns, result_list):\n print(\"Mean loss for n={}: {}\".format(n, np.mean(np.array(results))))\n ax[cur].plot(avg_regret(results[-start:]), label=\"SimpleBoost, n={}\".format(n))\n\n # plot loss for last value and autoregressor methods\n print(\"Mean loss for AutoRegressor: {}\".format(np.mean(np.array(autoreg_loss))))\n ax[cur].plot(avg_regret(autoreg_loss[-start:]), label=\"AutoRegressor method\")\n ax[cur].legend(loc=\"upper right\", fontsize=8)\n\n cur += 1\n\n fig.tight_layout()\n plt.show()\n\n\nif __name__ == \"__main__\":\n test_simple_boost(show=True)","sub_path":"tigerforecast/utils/boosting/tests/test_simple_boost.py","file_name":"test_simple_boost.py","file_ext":"py","file_size_in_byte":5543,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"519409807","text":"from bs4 import BeautifulSoup\r\nimport requests\r\nimport pandas as pd\r\n\r\n\r\n#url = 'https://www1.nseindia.com/products/dynaContent/equities/equities/htms/fiiEQ.htm'\r\nurl = 'https://www1.nseindia.com/products/dynaContent/equities/equities/htms/DiiEQ.htm'\r\nheaders = {'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.117 Safari/537.36'}\r\nresponse = requests.get(url, headers=headers).text\r\n\r\n\r\nsoup = BeautifulSoup(response, 'lxml')\r\ntables = soup.find_all('table', class_='holiday_list')\r\nfor table in tables:\r\n table_rows = table.find_all('tr')\r\n tablerows = []\r\n for table_row in table_rows:\r\n table_headers = table_row.find_all('th')\r\n tableheader = []\r\n for table_header in table_headers:\r\n tableheader.append(table_header.text)\r\n tablerows.append(tableheader)\r\n table_data = table_row.find_all('td')\r\n tabledata = []\r\n for table_data_row in table_data:\r\n tabledata.append(table_data_row.text)\r\n tablerows.append(tabledata)\r\n \r\n\r\ntablerows = [x for x in tablerows if x]\r\n#columns = tablerows[1]\r\n#df = pd.DataFrame(tablerows[1:])\r\n#df.reset_index(drop=True, inplace=True)\r\n#print(df)\r\ndata = {}\r\nfor col in range(len(tablerows[1])):\r\n data[tablerows[1][col]] = [tablerows[2][col]]\r\n\r\nprint(data)\r\ndf = pd.DataFrame(data)\r\nprint(df)\r\nprint(df.columns)","sub_path":"dii.py","file_name":"dii.py","file_ext":"py","file_size_in_byte":1412,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"138909521","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Sun Nov 15 14:25:35 2020\r\n\r\n@author: Manya\r\n\"\"\"\r\n\r\nimport csv\r\nimport math\r\nfrom numpy import matrix as np\r\nimport numpy as numpy\r\nimport scipy\r\nfrom scipy.cluster.hierarchy import dendrogram, linkage\r\nfrom matplotlib import pyplot as plt\r\nimport pandas as pd\r\nfrom copy import deepcopy\r\nfrom numpy.linalg import inv\r\n\r\ndef get_dataset(filepath):\r\n\r\n with open(filepath, newline='') as iris:\r\n # returning from 2nd row\r\n data = list(csv.reader(iris, delimiter=','))[1:]\r\n result = numpy.array(data).astype(\"float\")\r\n\r\n b = numpy.delete(result, 0, axis=1)\r\n\r\n return b\r\n\r\n\r\n# 1 = density etc.\r\ndef print_stats(dataset, col):\r\n\r\n i = 0\r\n tot = 0\r\n # for the std\r\n arr = numpy.zeros(shape=(252, 1))\r\n print(len(dataset))\r\n\r\n while i < len(dataset):\r\n tot += dataset[i][col]\r\n i += 1\r\n\r\n answer = tot/len(dataset)\r\n answer = str(round(answer, 2))\r\n print(answer)\r\n\r\n i = 0\r\n while i < len(dataset):\r\n arr[i] = float(dataset[i][col])\r\n i += 1\r\n\r\n arr1 = numpy.array(arr)\r\n\r\n std = numpy.std(arr1)\r\n answer1 = str(round(std, 2))\r\n print(answer1)\r\n\r\n\r\ndef regression(dataset, cols, betas):\r\n \r\n tot = 0\r\n\r\n for row in range(len(dataset)):\r\n s_e = betas[0]\r\n i = 1\r\n for col in cols:\r\n \r\n s_e += betas[i] * dataset[row][col]\r\n i += 1\r\n\r\n s_e = s_e - dataset[row][0]\r\n s_e = numpy.square(s_e)\r\n tot += s_e\r\n\r\n m_s_e = tot/(len(dataset))\r\n\r\n return m_s_e\r\n\r\n\r\ndef gradient_descent(dataset, cols, betas):\r\n\r\n num = len(dataset)\r\n tot = 0\r\n\r\n arr = []\r\n arr1 = []\r\n\r\n index = 0\r\n a = 0\r\n\r\n # go upto the beta which is at the last index of cols array\r\n while a <= cols[(len(cols)-1)]:\r\n tot = 0\r\n if (index == 0):\r\n\r\n for row in range(num):\r\n s_e = betas[0]\r\n i = 1\r\n for col in cols:\r\n s_e += betas[i] * dataset[row][col]\r\n i += 1\r\n\r\n s_e = s_e - dataset[row][0]\r\n tot += s_e\r\n\r\n g_d = (2*tot)/num\r\n arr1.append(g_d)\r\n\r\n # MULTIPLY Xij\r\n else:\r\n for row in range(num):\r\n s_e = betas[0]\r\n i = 1\r\n for col in cols:\r\n s_e += betas[i] * dataset[row][col]\r\n i += 1\r\n\r\n s_e = s_e - dataset[row][0]\r\n s_e = s_e * dataset[row][index]\r\n tot += s_e\r\n\r\n g_d = (2*tot)/num\r\n\r\n index += 1\r\n a += 1\r\n arr.append(g_d)\r\n\r\n # the betas that are needed are col indices\r\n b = 0\r\n while b < len(cols):\r\n\r\n arr1.append(arr[cols[b]])\r\n b += 1\r\n\r\n ret = numpy.array(arr1)\r\n\r\n return ret\r\n\r\n\r\ndef iterate_gradient(dataset, cols, betas, T, eta):\r\n\r\n size = int(T)\r\n ret = numpy.empty(shape=(size, 5))\r\n ret.fill(1)\r\n\r\n i = 0\r\n while i < T:\r\n # 0 is the indices upto T\r\n # f\"{num:.9f}\"\r\n index = i + 1\r\n ret[i][0] = index\r\n\r\n # 1 is current MSE\r\n grads = gradient_descent(dataset, cols, betas)\r\n a = 0\r\n while a < len(betas):\r\n betas[a] = betas[a] - (eta*grads[a])\r\n a += 1\r\n mse = float(regression(dataset, cols, betas))\r\n ret[i][1] = str(float(round(mse, 2)))\r\n ret[i][2] = float(betas[0])\r\n ret[i][3] = float(betas[1])\r\n ret[i][4] = float(betas[2])\r\n i += 1\r\n\r\n i = 0\r\n while i < T:\r\n print(str(int(ret[i][0])),\r\n \"{:.2f}\".format(ret[i][1]),\r\n \"{:.2f}\".format(ret[i][2]),\r\n \"{:.2f}\".format(ret[i][3]),\r\n \"{:.2f}\".format(ret[i][4]))\r\n\r\n i += 1\r\n\r\ndef compute_betas(dataset, cols) :\r\n\r\n data_copy = deepcopy(dataset)\r\n ones = numpy.ones( (len(dataset), 1)) \r\n \r\n extractedData = data_copy[:,[cols[0],cols[1]]]\r\n x = numpy.hstack( (ones, extractedData) ) \r\n\r\n x_copy = deepcopy(x)\r\n transpose = x.transpose()\r\n \r\n dot = np.dot(transpose, x)\r\n inverse = inv(dot)\r\n \r\n betas = np.dot(inverse, transpose)\r\n \r\n i = 0\r\n y = numpy.empty( (len(data_copy), 1) )\r\n \r\n # # bodyfat column\r\n while i < len(data_copy):\r\n y[i] = data_copy[i][0]\r\n i += 1\r\n \r\n betas = np.dot(transpose,y)\r\n ret_betas = np.dot(inverse, betas)\r\n \r\n in_betas = ret_betas.ravel()\r\n \r\n mse = regression(dataset, cols, in_betas)\r\n\r\n\r\n tup = (mse, in_betas[0], in_betas[cols[0]], in_betas[cols[1]])\r\n return tup\r\n \r\n \r\ndef predict(dataset, cols, features):\r\n \r\n betas = []*(len(cols)+1)\r\n \r\n tup = compute_betas(dataset, cols)\r\n \r\n i = 1\r\n while i < len(tup):\r\n betas.append(tup[i])\r\n i += 1\r\n\r\n pred = betas[0]\r\n i = 1\r\n while i < len(betas):\r\n pred += betas[i]*features[i-1]\r\n i +=1\r\n \r\n return pred\r\n \r\n \r\n\r\n\r\n\r\n\r\n\r\n","sub_path":"HW8/regression1.py","file_name":"regression1.py","file_ext":"py","file_size_in_byte":5061,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"175409922","text":"# Copyright 2015 The Swarming Authors. All rights reserved.\n# Use of this source code is governed by the Apache v2.0 license that can be\n# found in the LICENSE file.\n\n\"\"\"Google Compute Engine specific utility functions.\"\"\"\n\nimport json\nimport logging\nimport threading\nimport time\nimport urllib2\n\nfrom utils import tools\n\n\n### Private stuff.\n\n\n# Cache of GCE OAuth2 token.\n_CACHED_OAUTH2_TOKEN = {}\n_CACHED_OAUTH2_TOKEN_LOCK = threading.Lock()\n\n\n## Public API.\n\n\nclass SendMetricsFailure(Exception):\n \"\"\"Signals that metrics couldn't be sent successfully.\"\"\"\n\n\ndef is_gce():\n \"\"\"Returns True if running on Google Compute Engine.\"\"\"\n return bool(get_metadata())\n\n\n@tools.cached\ndef get_metadata():\n \"\"\"Returns the GCE metadata as a dict.\n\n Refs:\n https://cloud.google.com/compute/docs/metadata\n https://cloud.google.com/compute/docs/machine-types\n\n To get the at the command line from a GCE VM, use:\n curl --silent \\\n http://metadata.google.internal/computeMetadata/v1/?recursive=true \\\n -H \"Metadata-Flavor: Google\" | python -m json.tool | less\n \"\"\"\n url = 'http://metadata.google.internal/computeMetadata/v1/?recursive=true'\n headers = {'Metadata-Flavor': 'Google'}\n try:\n return json.load(\n urllib2.urlopen(urllib2.Request(url, headers=headers), timeout=5))\n except IOError as e:\n logging.info('GCE metadata not available: %s', e)\n return None\n\n\ndef oauth2_access_token(account='default'):\n \"\"\"Returns a value of oauth2 access token.\"\"\"\n # TODO(maruel): Move GCE VM authentication logic into client/utils/net.py.\n # As seen in google-api-python-client/oauth2client/gce.py\n with _CACHED_OAUTH2_TOKEN_LOCK:\n cached_tok = _CACHED_OAUTH2_TOKEN.get(account)\n # Cached and expires in more than 5 min from now.\n if cached_tok and cached_tok['expiresAt'] >= time.time() + 5*60:\n return cached_tok['accessToken']\n # Grab the token.\n url = (\n 'http://metadata.google.internal/computeMetadata/v1/instance'\n '/service-accounts/%s/token' % account)\n headers = {'Metadata-Flavor': 'Google'}\n try:\n resp = json.load(\n urllib2.urlopen(urllib2.Request(url, headers=headers), timeout=20))\n except IOError as e:\n logging.error('Failed to grab GCE access token: %s', e)\n raise\n tok = {\n 'accessToken': resp['access_token'],\n 'expiresAt': time.time() + resp['expires_in'],\n }\n _CACHED_OAUTH2_TOKEN[account] = tok\n return tok['accessToken']\n\n\ndef oauth2_available_scopes(account='default'):\n \"\"\"Returns a list of OAuth2 scopes granted to GCE service account.\"\"\"\n metadata = get_metadata()\n if not metadata:\n return []\n accounts = metadata['instance']['serviceAccounts']\n return accounts.get(account, {}).get('scopes') or []\n\n\n@tools.cached\ndef get_zone():\n \"\"\"Returns the zone containing the GCE VM.\"\"\"\n # Format is projects//zones/\n metadata = get_metadata()\n return unicode(metadata['instance']['zone'].rsplit('/', 1)[-1])\n\n\n@tools.cached\ndef get_machine_type():\n \"\"\"Returns the GCE machine type.\"\"\"\n # Format is projects//machineTypes/\n metadata = get_metadata()\n return unicode(metadata['instance']['machineType'].rsplit('/', 1)[-1])\n\n\n@tools.cached\ndef get_tags():\n \"\"\"Returns a list of instance tags or empty list if not GCE VM.\"\"\"\n return get_metadata()['instance']['tags']\n\n\ndef send_metric(name, value):\n \"\"\"Sets a lightweight custom metric.\n\n In particular, the metric has no description and it is double. To make this\n work, use \"--scopes https://www.googleapis.com/auth/monitoring\" when running\n \"gcloud compute instances create\". You can verify if the scope is enabled from\n within a GCE VM with:\n curl \"http://metadata.google.internal/computeMetadata/v1/instance/\\\nservice-accounts/default/scopes\" -H \"Metadata-Flavor: Google\"\n\n Ref: https://cloud.google.com/monitoring/custom-metrics/lightweight\n\n To create a metric, use:\n https://developers.google.com/apis-explorer/#p/cloudmonitoring/v2beta2/cloudmonitoring.metricDescriptors.create\n It is important to set the commonLabels.\n \"\"\"\n logging.info('send_metric(%s, %s)', name, value)\n assert isinstance(name, str), repr(name)\n assert isinstance(value, float), repr(value)\n\n metadata = get_metadata()\n project_id = metadata['project']['numericProjectId']\n\n url = (\n 'https://www.googleapis.com/cloudmonitoring/v2beta2/projects/%s/'\n 'timeseries:write') % project_id\n now = time.strftime('%Y-%m-%dT%H:%M:%SZ', time.gmtime())\n body = {\n 'commonLabels': {\n 'cloud.googleapis.com/service': 'compute.googleapis.com',\n 'cloud.googleapis.com/location': get_zone(),\n 'compute.googleapis.com/resource_type': 'instance',\n 'compute.googleapis.com/resource_id': metadata['instance']['id'],\n },\n 'timeseries': [\n {\n 'timeseriesDesc': {\n 'metric': 'custom.cloudmonitoring.googleapis.com/' + name,\n 'project': project_id,\n },\n 'point': {\n 'start': now,\n 'end': now,\n 'doubleValue': value,\n },\n },\n ],\n }\n try:\n token = oauth2_access_token()\n except (IOError, urllib2.HTTPError) as e:\n raise SendMetricsFailure(e)\n\n headers = {\n 'Authorization': 'Bearer ' + token,\n 'Content-Type': 'application/json',\n }\n logging.info('%s', json.dumps(body, indent=2, sort_keys=True))\n try:\n resp = urllib2.urlopen(urllib2.Request(url, json.dumps(body), headers))\n # Result must be valid JSON. A sample response:\n # {\"kind\": \"cloudmonitoring#writeTimeseriesResponse\"}\n logging.debug(json.load(resp))\n except (IOError, urllib2.HTTPError) as e:\n raise SendMetricsFailure(e)\n","sub_path":"appengine/swarming/swarming_bot/api/platforms/gce.py","file_name":"gce.py","file_ext":"py","file_size_in_byte":5646,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"345295425","text":"from flask import Flask, render_template, make_response, request\nfrom flask.json import jsonify\n\napp = Flask(__name__)\napp.__setattr__('function', '')\n\n@app.route('/')\ndef index():\n\treturn make_response(render_template('index.html'))\n\n\n@app.route('/eval', methods=['POST'])\ndef eval():\n\ttext = request.json['text']\n\tresult = app.function(text)\n\treturn jsonify({'personalities': result })\n\n\n","sub_path":"app/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":390,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"497063027","text":"import redis\nimport sys\n\nargs = sys.argv\n\nr = redis.Redis()\n\nfor who in args[1:]:\n tags = r.hgetall(who)\n print(who)\n for k,v in tags.items():\n print('\\tタグ:{}\\t被タグ数:{}'.format(k.decode('utf-8'), v.decode('utf-8')))\n # print('{}\\t{}'.format(who,tags))\n","sub_path":"take/chapter07/query_taginfo_for_knock63.py","file_name":"query_taginfo_for_knock63.py","file_ext":"py","file_size_in_byte":282,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"220824019","text":"import sys\nimport math\nimport random\n\nfrom twisted.internet.defer import inlineCallbacks\nfrom twisted.logger import Logger\n\nfrom autobahn.twisted.util import sleep\nfrom autobahn.twisted.wamp import ApplicationSession\nfrom autobahn.wamp.exception import ApplicationError\nfrom geoindex import GeoGridIndex, GeoPoint\n\n\nlatitude = 19.99\nlongitude = 73.78\n\n\ndef generate_random_data(lat, lon, num_rows):\n for _ in xrange(num_rows):\n dec_lat = random.random() / 100\n dec_lon = random.random() / 100\n return lon + dec_lon, lat + dec_lat\n\n\nclass AppSession(ApplicationSession):\n\n log = Logger()\n\n @inlineCallbacks\n def onJoin(self, details):\n\n while True:\n try:\n res = yield self.call('update_stuff', generate_random_data())\n self.log.info(\n \"update() called with result: {result}\", result=res\n )\n except ApplicationError as e:\n if e.error != 'wamp.error.no_such_procedure':\n raise e\n\n yield sleep(1)\n\nif __name__ == '__main__':\n print(generate_random_data(latitude, longitude, 1))\n","sub_path":"hello/hello.py","file_name":"hello.py","file_ext":"py","file_size_in_byte":1148,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"318421951","text":"# -*- coding: utf-8 -*-\nfrom django.core.paginator import Paginator, PageNotAnInteger, EmptyPage\nfrom django.db.models import F\nfrom django.http import HttpResponseRedirect, HttpResponse\nfrom django.shortcuts import render, redirect\n\nfrom link_cropper.forms import AddLinkForm\nfrom link_cropper.models import LinkItem\n\n\ndef index(request):\n form = AddLinkForm(request.POST or None)\n\n if form.is_valid():\n link_item = form.save(False)\n short_link = LinkItem.short_link_gen(link_item.link, link_item.link)\n\n try:\n link_item = LinkItem.objects.get(short_link=short_link)\n except LinkItem.DoesNotExist:\n link_item.short_link = short_link\n link_item.save()\n\n return render(request, 'link_info.html', {'link_item': link_item})\n\n links = LinkItem.objects.order_by('-views_count', '-created_date').all()[:20]\n\n return render(request, 'index.html', {'form': form, 'links': links})\n\n\ndef get_link(request):\n short_link = request.GET.get('l')\n\n try:\n link_item = LinkItem.objects.get(short_link=short_link)\n link_item.views_count = F('views_count') + 1\n link_item.save()\n return HttpResponseRedirect(link_item.link)\n except LinkItem.DoesNotExist:\n return HttpResponse(u'Указанной вами ссылки не существует')\n\n\ndef del_link(request):\n short_link = request.GET.get('l')\n\n try:\n link_item = LinkItem.objects.get(short_link=short_link)\n link_item.delete()\n return redirect('list_all')\n except LinkItem.DoesNotExist:\n return HttpResponse(u'Указанной вами ссылки не существует')\n\n\ndef list_all(request):\n links = LinkItem.objects.order_by('-views_count', '-created_date').all()\n paginator = Paginator(links, 25)\n page = request.GET.get('page')\n\n try:\n links = paginator.page(page)\n except PageNotAnInteger:\n links = paginator.page(1)\n except EmptyPage:\n links = paginator.page(paginator.num_pages)\n\n return render(request, 'list_all.html', {'links': links})\n","sub_path":"link_cropper/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2106,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"236797878","text":"import psycopg2\n\nclass DataSource:\n def __init__(self):\n self.connection = psycopg2.connect(database='hussaink', user='hussaink', password='orange434farm', host=\"localhost\")\n\n def getMajorList(self):\n '''\n Retrieves the names of all of the majors\n Returns:\n A list of major names\n '''\n major_list = []\n try:\n cursor = self.connection.cursor()\n query = \"SELECT major FROM table_2017 ORDER BY major ASC\"\n cursor.execute(query)\n for item in cursor.fetchall():\n str = ''.join(item)\n major_list.append(str)\n return major_list\n\n except Exception as e:\n print(\"Something went wrong when executing the query: \", e)\n return None\n\n def getMaxAndMinSalary(self):\n '''\n Retrieves the maximum salary and the minimun salary in the table\n Return:\n The maximum salary and the minimun salary\n '''\n try:\n cursor = self.connection.cursor()\n query = \"SELECT MAX(salary), MIN(salary) FROM table_2017\"\n cursor.execute(query)\n Salary = cursor.fetchall()\n return Salary\n\n except Exception as e:\n print(\"Something went wrong when executing the query: \", e)\n return None\n\n def getMaxAndMinPopularity(self):\n '''\n Retrieves the maximum popularity and the minimun popularity in the table\n Return:\n The maximum popularity and the minimun popularity\n '''\n try:\n cursor = self.connection.cursor()\n query = \"SELECT MAX(popularity), MIN(popularity) FROM table_2017\"\n cursor.execute(query)\n Popularity = cursor.fetchall()\n return Popularity\n\n except Exception as e:\n print(\"Something went wrong when executing the query: \", e)\n return None\n\n def getMajorsBySalary(self, minSalary, maxSalary):\n '''\n Retrieves the names of all of the majors that are in the salary scale\n Parameters:\n minSalary - the minimum of the desired salary\n maxSalary - the maximum of the desired salary\n Returs:\n A list of major that are within the salary range\n '''\n majorBySalary_list = []\n try:\n cursor = self.connection.cursor()\n query = \"SELECT major FROM table_2017 WHERE salary BETWEEN \" + minSalary + \" AND \" + maxSalary + \" ORDER BY salary ASC\"\n cursor.execute(query)\n for item in cursor.fetchall():\n str = ''.join(item)\n majorBySalary_list.append(str)\n return majorBySalary_list\n except Exception as e:\n print(\"Something went wrong when executing the query: \", e)\n return None\n\n def getSalary(self, major):\n '''\n Retrieves the salary of the specified major\n Parameters:\n major - retrieve the salary of the this major from the data\n Returns:\n The median annual salary of this major in dollar, or None if the query fails.\n '''\n try:\n cursor = self.connection.cursor()\n query = \"SELECT salary FROM table_2017 WHERE major LIKE '\" + major + \"'\"\n cursor.execute(query)\n salary = cursor.fetchone()\n return int(salary[0])\n\n except Exception as e:\n print (\"Something went wrong when executing the query: \", e)\n return None\n\n def getPopularity(self, major):\n pass\n '''\n Retrieves the popularity of the specified major\n Parameters:\n major - retrieve the popularity of the this major from the data\n Returns:\n the popularity of this major as an integer number in thousands, or None if the query fails.\n '''\n try:\n cursor = self.connection.cursor()\n query = \"SELECT popularity FROM table_2017 WHERE major LIKE '\" + major + \"'\"\n cursor.execute(query)\n popularity = cursor.fetchone()\n print(type(popularity[0]))\n pop = str(popularity[0])\n if len(str(popularity[0])) > 3:\n string = str(popularity[0])\n pop = string[0] + \",\" + string[1:]\n return pop\n\n except Exception as e:\n print (\"Something went wrong when executing the query: \", e)\n return None\n\n def getMajorsByPopularity(self, minPopularity, maxPopularity):\n '''\n Retrieves the names of all of the majors that are in the popularity scale\n Parameters:\n minPopularity - the minimum of the desired popularity\n maxPopularity - the maximum of the desired popularity\n Returs:\n A list of major that are within the popularity range\n '''\n majorByPopularity_list = []\n try:\n cursor = self.connection.cursor()\n query = \"SELECT major FROM table_2017 WHERE popularity BETWEEN \" + minPopularity + \" AND \" + maxPopularity + \" ORDER BY popularity ASC\"\n cursor.execute(query)\n for item in cursor.fetchall():\n str = ''.join(item)\n majorByPopularity_list.append(str)\n return majorByPopularity_list\n except Exception as e:\n print(\"Something went wrong when executing the query: \", e)\n return None\n\n def getMaleAndFemalePopularityPercentage(self, major):\n '''\n Retrieves the percentages of male and female with inputted degree from dataset.\n PARAMETERS:\n major - inputted degree needing to be obtained from database\n RETURN:\n Percentages of male and female holding this degree, or None if query cannot be found\n '''\n try:\n cursor = self.connection.cursor()\n query = \"SELECT male, female FROM percentages WHERE major LIKE '\" + major + \"'\"\n cursor.execute(query)\n percentages_list = []\n percentages = cursor.fetchall()\n percentages_list.append(percentages[0][0])\n percentages_list.append(percentages[0][1])\n return (percentages_list)\n\n except Exception as e:\n print(\"Something went wrong when executing the query: \", e)\n return None\n\n def getMaxInstitutionPopularity(self, major):\n '''\n Retrieves the kind of institution which has the highest popularity of the specified major\n PARAMETERS:\n major - retrieve the kind of institution which has the highest popularity of the this major from the data\n RETURNS:\n A text representing the kind of institution which has the highest popularity of this major, or None if the query fails.\n '''\n major_list = self.getMajorList()\n cursor = self.connection.cursor()\n if major in major_list:\n query = (\"SELECT 'Private, non-profit institution', popprivatenp FROM majors WHERE major =\\'\" + major + \"\\' AND popprivatenp = GREATEST(poppublic, popprivatenp, popprivatefp) \\n\"\n \"UNION SELECT 'Private, for-profit institution', popprivatefp FROM majors WHERE major =\\'\" + major + \"\\' AND popprivatefp = GREATEST(poppublic, popprivatenp, popprivatefp) \\n\"\n \"UNION SELECT 'Public institution', poppublic FROM majors WHERE major =\\'\" + major + \"\\' AND poppublic = GREATEST(poppublic, popprivatenp, popprivatefp)\")\n cursor.execute(query)\n institution = cursor.fetchall()\n return institution\n\ndef main():\n pass\nmain()\n","sub_path":"backend/datasource.py","file_name":"datasource.py","file_ext":"py","file_size_in_byte":7673,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"191912893","text":"#!/usr/bin/env python3.5\nimport operator\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport os\nimport sys\nimport urllib\nimport re\nimport math\n\n''' Utility '''\n\ndef check_tag_for_pipes(tag):\n if re.match(r\"(\\w+)\\|(\\w+)\", tag):\n tag = re.sub(r\"(\\w+)\\|(\\w+)\", r\"\\1\", tag)\n if re.match(r\"(\\w+)\\|(\\w+)\", tag):\n tag = re.sub(r\"(\\w+)\\|(\\w+)\", r\"\\1\", tag) \n return tag\n\ndef get_tag_array(tag_dict):\n tag_array = []\n for key, value in tag_dict.items():\n tag_array.append(key)\n return tag_array\n\n''' Load the data '''\n\n# Load just one file to see results\ndef load_one_testing_file(path):\n fo = open(path, \"r\")\n stat = os.stat(path)\n content = fo.read(stat.st_size)\n fo.close()\n return content\n\n# Load the data and split it into training and test data\ndef load_all_data(path, number_of_test):\n all_folders = [f for f in os.listdir(path)]\n length = len(all_folders)\n all_content = []\n\n for i in range(1, length):\n files = [f for f in os.listdir(path + '/' + all_folders[i])]\n for one_file in files:\n file_path = path + '/' + all_folders[i] + '/' + one_file\n all_content = np.concatenate((all_content, load_and_parse_one_file(file_path)), axis = 0)\n content_path = \"/Users/eldarbabayev/Desktop/computationaLinguistics/computationalling/data/all_content.POS\"\n fo = open(content_path, \"w\")\n stat = os.stat(content_path)\n for item in all_content:\n fo.write(\"%s\" % item)\n fo.close()\n length_of_content = len(all_content)\n training_data = []\n test_data = []\n\n range_test_data_start = int(round(length_of_content * number_of_test * 0.1))\n range_test_data_end = range_test_data_start + int(round(length_of_content * 0.1)) - 4\n ninety_percent_of_data = int(round(length_of_content * 0.9))\n\n # load the training data\n for i in range(0, range_test_data_start):\n training_data.append(all_content[i])\n for i in range(range_test_data_end + 1, length_of_content):\n training_data.append(all_content[i])\n # load the test data\n for i in range(range_test_data_start, range_test_data_end):\n test_data.append(all_content[i])\n return training_data, test_data\n\n \n''' Write to files '''\n\ndef write_to_testing_file(array):\n test_content_path = \"/Users/eldarbabayev/Desktop/computationaLinguistics/computationalling/data/test_content.POS\"\n fo = open(test_content_path, \"w\")\n stat = os.stat(test_content_path)\n for item in array:\n fo.write(\"%s\" % item)\n fo.close()\n\n''' Pre-processing of the data '''\n\n# Section is divided by ====..\ndef divide_by_sections(content):\n content = re.sub(r\"=+\", \"SECTION\", content)\n array_of_sections = content.split(\"SECTION\")\n return array_of_sections\n\ndef remove_unnecessary_new_lines(array_of_sections):\n for i in range(len(array_of_sections)-1,-1,-1):\n if re.match(r\"^[\\n]+$\", array_of_sections[i]):\n array_of_sections.pop(i)\n return array_of_sections\n\n# Divide the array by sentences\ndef divide_by_sentences(array):\n newarray = []\n for i in range(len(array)):\n if re.search(r\"\\./\\.\", array[i]) != None:\n elem = array[i]\n elem = elem.split(\"./.\")\n newarray = newarray + elem\n else:\n newarray.append(array[i])\n return newarray\n\n# Add START/STOP at beginning/end of sentences\ndef add_start_end(array):\n newarray = []\n for i in range(len(array)):\n elem = array[i]\n elem = \"\\n\" + \"START\" + elem + \"STOP\"\n newarray.append(elem)\n write_to_testing_file(newarray)\n return newarray\n \n# Remove quotes\ndef remove_quotes(array):\n newarray = []\n for i in range(len(array)):\n elem = array[i]\n elem = re.sub(r\"''/''\", r\"\", elem)\n elem = re.sub(r\"``/``\", r\"\", elem)\n elem = re.sub(r\"'/''\", r\"\", elem)\n elem = re.sub(r\"`/``\", r\"\", elem)\n newarray.append(elem)\n write_to_testing_file(newarray)\n return newarray\n\n# Remove commas\ndef remove_commas(array):\n newarray = []\n for i in range(len(array)):\n elem = array[i]\n elem = re.sub(r\",/,\", r\"\", elem)\n elem = re.sub(r\"2/,\", r\"\", elem)\n newarray.append(elem)\n write_to_testing_file(newarray)\n return newarray\n\n#remove colons and semicolons\ndef remove_colons_and_semicolons(array):\n newarray = []\n for i in range(len(array)):\n elem = array[i]\n elem = re.sub(r\":/:\", r\"\", elem)\n elem = re.sub(r\";/:\", r\"\", elem)\n newarray.append(elem)\n write_to_testing_file(newarray)\n return newarray\n\n#remove bang and question mark\ndef remove_bang_question_hash(array):\n newarray = []\n for i in range(len(array)):\n elem = array[i]\n elem = re.sub(r\"\\?/\\.\", r\"\", elem)\n elem = re.sub(r\"!/\\.\", r\"\", elem)\n elem = re.sub(r\"#/#\", r\"\", elem)\n newarray.append(elem)\n write_to_testing_file(newarray)\n return newarray\n\n#remove --/:\ndef remove_double_dash_one_dash_triple_dot(array):\n newarray = []\n for i in range(len(array)):\n elem = array[i]\n elem = re.sub(r\"--/:\", r\"\", elem)\n elem = re.sub(r\"\\.\\.\\./:\", r\"\", elem)\n elem = re.sub(r\"-/:\", r\"\", elem)\n newarray.append(elem)\n write_to_testing_file(newarray)\n return newarray\n\n# Remove square brackets\ndef remove_square_brackets(array):\n newarray = []\n for i in range(len(array)):\n elem = array[i]\n elem = re.sub(r\"\\[\", r\"\", elem)\n elem = re.sub(r\"\\]\", r\"\", elem)\n newarray.append(elem)\n write_to_testing_file(newarray)\n return newarray\n\n# Remove round brackets\ndef remove_round_brackets(array):\n newarray = []\n for i in range(len(array)):\n elem = array[i]\n elem = re.sub(r\"\\(/\\(\", r\"\", elem)\n elem = re.sub(r\"{/\\(\", r\"\", elem)\n elem = re.sub(r\"}/\\)\", r\"\", elem)\n elem = re.sub(r\"\\)/\\)\", r\"\", elem)\n newarray.append(elem)\n write_to_testing_file(newarray)\n return newarray \n\n# Remove new lines within sentences\ndef remove_new_lines_withing_sentences(array):\n newarray = []\n for i in range(len(array)):\n elem = array[i]\n elem = re.sub(r\"[\\n]+\", r\" \", elem)\n newarray.append(elem)\n write_to_testing_file(newarray)\n return newarray\n\n# Only keep one whitespace between word-tags\ndef remove_blank_spaces_but_one_between_wordtags(array):\n newarray = []\n for i in range(len(array)):\n elem = array[i]\n elem = re.sub(r\"[\\s]+\", r\"\\n\", elem)\n newarray.append(elem)\n write_to_testing_file(newarray)\n return newarray \n\n# Remove \\nSTART\\nSTOP element from array\ndef remove_empty_sentence_from_array(array):\n newarray = []\n for i in range(len(array)):\n if re.match(r\"\\nSTART\\nSTOP\", array[i]):\n # Do nothing\n newarray = newarray\n else:\n newarray.append(array[i])\n write_to_testing_file(newarray)\n return newarray\n\n# Remove newline on the first line of file\ndef remove_newline_from_beginning_of_each_sentence(array):\n newarray = []\n for i in range(len(array)):\n elem = array[i]\n elem = re.sub(\"^\\n\", \"\", elem)\n newarray.append(elem)\n return newarray\n\n# Create array of word/tag sequences\ndef merge_all_sentences_into_array(array):\n newarray = []\n for i in range(len(array)):\n if re.search(r\"\\n\", array[i]) != None:\n elem = array[i]\n elem = elem.split(\"\\n\")\n newarray = newarray + elem\n else:\n newarray = newarray + array[i]\n return newarray \n\n# convert 3\\/4/CD to 34/CD\ndef convert_ratio_to_number(array):\n newarray = []\n for i in range(len(array)):\n if re.search(r\"([0-9]+)\\\\/([0-9]+)(\\/CD)\", array[i]) != None:\n elem = array[i]\n elem = re.sub(r\"([0-9]+)\\\\/([0-9]+)(\\/CD)\", r\"\\1\\2\\3\", elem)\n newarray.append(elem)\n else:\n newarray.append(array[i])\n return newarray\n\n# convert word1\\/word2/tag to word1/tag\ndef convert_two_words_into_one(array):\n newarray = []\n for i in range(len(array)):\n if re.search(r\"([\\w-]+)\\\\/([\\w-]+)(\\/[A-Z$]+)\", array[i]) != None:\n elem = array[i]\n elem = re.sub(r\"([\\w-]+)\\\\/([\\w-]+)(\\/[A-Z$]+)\", r\"\\1\\3\", elem)\n newarray.append(elem)\n else:\n newarray.append(array[i])\n return newarray \n\n# convert S*/NNP&P/NN to S&P/NNP\ndef convert_word_and_word_into_one(array):\n newarray = []\n for i in range(len(array)):\n if re.search(r\"([\\w]+)\\*/([A-Z]+)&([\\w]+)/([A-Z]+)\", array[i]) != None:\n elem = array[i]\n elem = re.sub(r\"([\\w]+)\\*/([A-Z]+)&([\\w]+)/([A-Z]+)\", r\"\\1&\\3/\\2\", elem)\n newarray.append(elem)\n else:\n newarray.append(array[i])\n return newarray\n\n''' Load and parse one file '''\n\ndef load_and_parse_one_file(path):\n return convert_two_words_into_one(\n convert_word_and_word_into_one(\n convert_two_words_into_one(\n convert_ratio_to_number(\n merge_all_sentences_into_array(\n remove_newline_from_beginning_of_each_sentence(\n remove_empty_sentence_from_array(\n remove_blank_spaces_but_one_between_wordtags(\n remove_new_lines_withing_sentences(\n remove_double_dash_one_dash_triple_dot(\n remove_colons_and_semicolons(\n remove_bang_question_hash(\n remove_commas(\n remove_quotes(\n remove_round_brackets(\n remove_square_brackets(\n add_start_end(\n divide_by_sentences(\n remove_unnecessary_new_lines(\n divide_by_sections(\n load_one_testing_file(path)))))))))))))))))))))\n\n''' Create appropriate dictionaries '''\n\ndef create_dictionary_of_tags_and_word_and_tags(training_data):\n tag_dict = {}\n word_tag_dict = {}\n startkey = 'START'\n stopkey = 'STOP'\n count = 0\n for elem in training_data:\n count = count + 1\n if (elem == stopkey):\n number_of_stops = tag_dict.get(stopkey, 0)\n tag_dict[stopkey] = number_of_stops + 1\n elif (elem == startkey):\n number_of_starts = tag_dict.get(startkey, 0)\n tag_dict[startkey] = number_of_starts + 1\n else:\n [word, tag] = elem.split(\"/\")\n tag = check_tag_for_pipes(tag)\n key = word.lower() + \"/\" + tag\n tag_dict[tag] = tag_dict.get(tag, 0) + 1\n word_tag_dict[key] = word_tag_dict.get(key, 0) + 1\n return tag_dict, word_tag_dict\n\ndef create_consequent_tags_dictionary(training_data):\n startkey = 'START'\n stopkey = 'STOP'\n cons_tag_dict = {}\n for i in range(0, len(training_data) - 1):\n if (training_data[i] == startkey):\n [word, next_tag] = training_data[i+1].split(\"/\")\n next_tag = check_tag_for_pipes(next_tag)\n key = startkey + \"/\" + next_tag\n cons_tag_dict[key] = cons_tag_dict.get(key, 0) + 1\n elif (training_data[i] == stopkey):\n if (training_data[i+1] == startkey):\n key = stopkey + \"/\" + startkey\n cons_tag_dict[key] = cons_tag_dict.get(key, 0) + 1\n else:\n [word, next_tag] = training_data[i+1].split(\"/\")\n next_tag = check_tag_for_pipes(next_tag)\n key = stopkey + \"/\" + next_tag\n cons_tag_dict[key] = cons_tag_dict.get(key, 0) + 1\n else:\n if (training_data[i+1] == stopkey):\n [word, prev_tag] = training_data[i].split(\"/\")\n prev_tag = check_tag_for_pipes(prev_tag)\n key = prev_tag + \"/\" + stopkey\n cons_tag_dict[key] = cons_tag_dict.get(key, 0) + 1\n else:\n [word, prev_tag] = training_data[i].split(\"/\")\n [word, next_tag] = training_data[i+1].split(\"/\")\n prev_tag = check_tag_for_pipes(prev_tag)\n next_tag = check_tag_for_pipes(next_tag)\n key = prev_tag + \"/\" + next_tag\n cons_tag_dict[key] = cons_tag_dict.get(key, 0) + 1\n return cons_tag_dict\n\n''' Create log probabilities dictionary '''\n\ndef compute_probabilities(word_tag_dict, just_tag_dict, consequent_tags_dict):\n word_tag_prob = {}\n word_tag_prob_log = {}\n consequent_tags_prob = {}\n consequent_tags_prob_log = {}\n \n for key, value in word_tag_dict.items():\n [word, tag] = key.split(\"/\")\n count_of_tag = just_tag_dict[tag]\n prob = value / count_of_tag\n word_tag_prob[key] = prob\n word_tag_prob_log[key] = math.log(prob)\n \n for key, value in consequent_tags_dict.items():\n [prev_tag, next_tag] = key.split(\"/\")\n count_of_tag = just_tag_dict[prev_tag]\n prob = value / count_of_tag\n consequent_tags_prob[key] = prob\n consequent_tags_prob_log[key] = math.log(prob)\n\n return word_tag_prob_log, consequent_tags_prob_log\n\n''' Viterbi Algorithm '''\n\ndef viterbi(test_data, cons_tags_prob_log, word_tag_prob_log, tag_dict):\n tag_array = get_tag_array(tag_dict)\n number_of_tags = len(tag_dict)\n\n test_data_size = len(test_data)\n\n # Initialise score and backpointer arrays\n score = [[0 for x in range(test_data_size)] for x in range(number_of_tags)]\n backpointer = [[0 for x in range(test_data_size)] for x in range(number_of_tags)]\n\n # Initialise the array of predictions\n best_tagging = [0 for x in range(test_data_size)]\n\n # Initialise\n for i in range(0, number_of_tags):\n tag = tag_array[i]\n word_and_tag = test_data[0] + \"/\" + tag\n start_and_tag = \"START\" + \"/\" + tag\n if word_and_tag in word_tag_prob_log:\n if start_and_tag in cons_tags_prob_log:\n score[i][0] = word_tag_prob_log[word_and_tag] + cons_tags_prob_log[start_and_tag]\n else:\n cons_tags_prob_log[start_and_tag] = math.log(1/(len(cons_tags_prob_log)))\n score[i][0] = word_tag_prob_log[word_and_tag] + cons_tags_prob_log[start_and_tag]\n else:\n if start_and_tag in cons_tags_prob_log:\n # Do laplacian smoothing, add word_and_tag to dict and compute probs\n word_tag_prob_log[word_and_tag] = math.log(1/(len(word_tag_prob_log)))\n score[i][0] = word_tag_prob_log[word_and_tag] + cons_tags_prob_log[start_and_tag]\n else:\n cons_tags_prob_log[start_and_tag] = math.log(1/(len(cons_tags_prob_log)))\n word_tag_prob_log[word_and_tag] = math.log(1/(len(word_tag_prob_log)))\n score[i][0] = word_tag_prob_log[word_and_tag] + cons_tags_prob_log[start_and_tag]\n \n # Induction\n for j in range(1, test_data_size):\n for i in range(0, number_of_tags):\n # find max prev score\n max_val = float(\"-inf\")\n max_k = 0\n for k in range(0, number_of_tags):\n tag = tag_array[k] + \"/\" + tag_array[i]\n word_and_tag = test_data[j] + \"/\" + tag_array[i]\n if tag in cons_tags_prob_log:\n if word_and_tag in word_tag_prob_log:\n current = score[k][j-1] + cons_tags_prob_log[tag] + word_tag_prob_log[word_and_tag]\n else:\n # Do laplacian smoothing, add word_and_tag to dict and compute probs\n word_tag_prob_log[word_and_tag] = math.log(1/(len(word_tag_prob_log)))\n current = score[k][j-1] + word_tag_prob_log[word_and_tag] + cons_tags_prob_log[tag]\n\n else:\n if word_and_tag in word_tag_prob_log:\n # Do laplacian smoothing, add tag to dict and compute probs\n cons_tags_prob_log[tag] = math.log(1/(len(cons_tags_prob_log)))\n current = score[k][j-1] + word_tag_prob_log[word_and_tag] + cons_tags_prob_log[tag]\n else:\n cons_tags_prob_log[tag] = math.log(1/(len(cons_tags_prob_log)))\n word_tag_prob_log[word_and_tag] = math.log(1/(len(word_tag_prob_log)))\n current = score[k][j-1] + word_tag_prob_log[word_and_tag] + cons_tags_prob_log[tag]\n\n if (current > max_val):\n # update max value and index\n max_val = current\n max_k = k\n # update score and backpointer arrays\n score[i][j] = max_val\n backpointer[i][j] = max_k\n\n # Back tracing the best tagging\n max_tn = float(\"-inf\")\n max_i = 0\n for i in range(0, number_of_tags):\n if (max_tn < score[i][test_data_size-1]):\n max_tn = score[i][test_data_size-1]\n max_i = i\n \n best_tagging[test_data_size-1] = max_i\n \n for j in range(test_data_size-2,0, -1):\n best_tagging[j] = backpointer[best_tagging[j+1]][j+1]\n\n prediction = []\n for i in range(len(best_tagging)):\n prediction.append(tag_array[best_tagging[i]])\n\n return prediction\n \n# convert word/tag to just word\ndef get_test_data_and_tags_from_ground_truth(ground_truth):\n test_data = []\n tags = []\n for elem in ground_truth:\n if elem == 'STOP':\n #do nothing..\n test_data = test_data\n elif elem == 'START':\n #do nothing..\n test_data = test_data\n else:\n [word, tag] = elem.split(\"/\")\n test_data.append(word)\n tags.append(tag)\n return test_data, tags\n\n# compute classification accuracy\ndef compute_classification_accuracy(ground_truth, prediction):\n accuracy = 0\n print(prediction)\n print(ground_truth)\n ground_truth = [x for x in ground_truth if x != 'STOP']\n ground_truth = [x for x in ground_truth if x != 'START']\n for i in range(len(ground_truth)):\n if (ground_truth[i] == prediction[i]):\n accuracy = accuracy + 1\n average = (accuracy/len(ground_truth))*100\n return average\n\ndef do_cross_validation(path):\n accuracy_list = []\n # for i in range(0, 10):\n for i in range(0, 10):\n print(i)\n training_data, ground_truth = load_all_data(path, i)\n test_data, tags = get_test_data_and_tags_from_ground_truth(ground_truth)\n tag_dict, word_tag_dict = create_dictionary_of_tags_and_word_and_tags(training_data)\n cons_tag_dict = create_consequent_tags_dictionary(training_data)\n word_tag_prob_log, cons_tag_prob_log = compute_probabilities(word_tag_dict, tag_dict, cons_tag_dict)\n prediction = viterbi(test_data, cons_tag_prob_log, word_tag_prob_log, tag_dict)\n accuracy_list.append(compute_classification_accuracy(tags, prediction))\n \n final_accuracy = sum(accuracy_list) / len(accuracy_list)\n return final_accuracy\n\n''' Running the program '''\n\n# Main function, start of program\nif __name__ == \"__main__\":\n # Testing on one sentence\n path = \"/Users/eldarbabayev/Desktop/computationaLinguistics/computationalling/WSJ-2-12/05/WSJ_0515.POS\"\n load_and_parse_one_file(path)\n\n # Testing on 90 percent of data\n path = \"/Users/eldarbabayev/Desktop/computationaLinguistics/computationalling\\\n/WSJ-2-12new\"\n print(do_cross_validation(path))\n\n\n\n\n \n","sub_path":"POStagger.py","file_name":"POStagger.py","file_ext":"py","file_size_in_byte":19341,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"300444368","text":"import theano\nimport theano.tensor as T\nimport numpy as np\n\n\nclass Network:\n\n def __init__(self, layers):\n self.layers = layers\n\n\nclass FullConnectedLayer:\n\n def __int__(self, n_in, n_out, W, b, activation=T.nnet.sigmoid, dropout_frac=0.0):\n self.n_in = n_in\n self.n_out = n_out\n\n self.activation_fn = activation\n self.dropout_frac = dropout_frac\n\n self.W = theano.shared(\n value=np.asarray(W),\n dtype=theano.config.floatX\n )\n\n self.b = theano.shared(\n value=np.asarray(b),\n dtype=theano.config.floatX\n )\n\n self.params = [self.W, self.b]\n\n","sub_path":"src/network-theano.py","file_name":"network-theano.py","file_ext":"py","file_size_in_byte":659,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"448624910","text":"# -*- coding: utf-8 -*-\n#\n# Copyright 2017 Xilosopher\n#\n# Author: Moro JoJo\n\n\nfrom webserver.app import create_app\n\n\ndef start_server(host='localhost', port=36728):\n app = create_app('development')\n app.run(host=host, port=port, use_reloader=False, debug=True)\n\n\nif __name__ == '__main__':\n start_server()\n","sub_path":"webserver/manager.py","file_name":"manager.py","file_ext":"py","file_size_in_byte":315,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"457433893","text":"import os, sys, threading, time\nfrom http.server import HTTPServer, CGIHTTPRequestHandler\n\nport = 80\nwebdir = '.'\nif len(sys.argv) > 1:\n\twebdir = sys.argv[1]\nif len(sys.argv) > 2:\n\tport = int(sys.argv[2])\n\ndef launcher():\n\ttime.sleep(3)\n\tos.system(\"start http://localhost:{0}/cgi-bin/lab2.py\".format(port))\n\ndef main():\n\tprint('webdir \"%s\", port %s' % (webdir, port))\n\tos.chdir(webdir)\n\n\tthreading.Thread(target=launcher).start()\n\tHTTPServer(('', port), CGIHTTPRequestHandler).serve_forever()\n\ntry:\n\tmain()\nexcept:\n\tprint(\"bye\")\n\n","sub_path":"lab2.py","file_name":"lab2.py","file_ext":"py","file_size_in_byte":530,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"} +{"seq_id":"629079982","text":"#!/usr/bin/env python\n\nfrom distutils.core import setup\nimport os.path\n\ndescription = file(os.path.join(os.path.dirname(__file__), 'README'), 'rb').read()\n\nsetup(name=\"anonymiseip\",\n version=\"0.0.1\",\n description=\"Web service for IP anonymisation.\",\n long_description=description,\n maintainer=\"Robert Collins\",\n maintainer_email=\"robert.collins@canonical.com\",\n url=\"https://launchpad.net/anonymiseip\",\n packages=['anonymiseip'],\n package_dir = {'':'.'},\n classifiers = [\n 'Development Status :: 2 - Pre-Alpha',\n 'Intended Audience :: Developers',\n 'License :: OSI Approved :: GNU Affero General Public License v3',\n 'Operating System :: OS Independent',\n 'Programming Language :: Python',\n ],\n install_requires = [\n ],\n )\n","sub_path":"pypi_install_script/anonymiseip-0.0.1.tar/setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":837,"program_lang":"python","lang":"en","doc_type":"code","dataset":"code-starcoder2","pt":"28"}